Inferensys

Prompt

Source Attribution for Agent-Generated Answers Prompt

A practical prompt playbook for using Source Attribution for Agent-Generated Answers Prompt in production AI workflows.
Developer designing multi-agent workflow on laptop, architecture diagram on screen, casual home office setup with afternoon light.
PROMPT PLAYBOOK

When to Use This Prompt

Define the job, reader, and constraints for source attribution in multi-step agent trajectories.

This prompt is designed for agent systems that synthesize final answers from multiple tool calls and retrieval steps. Its primary job is to produce per-statement source attribution, tracking exactly which tool, document, or API response each factual claim derives from. The ideal user is an AI engineer or product developer building a compound agent where a single answer may be assembled from a web search, a database lookup, and a document retrieval call. Without this prompt, the provenance of each claim is lost in the agent's internal reasoning, making it impossible to verify outputs or debug hallucinations after the fact.

Use this prompt when your agent trajectory spans three or more distinct tool calls and the final answer combines evidence from multiple origins. It is essential when downstream users need to click a citation and see the exact source, or when an audit trail must prove that a claim came from a specific retrieval step and not from the model's parametric knowledge. The prompt requires the full agent trajectory as input, including tool names, query parameters, and raw responses. Do not use this prompt for single-step RAG where a standard inline citation prompt suffices, or for conversational agents that do not perform tool-use. It is also inappropriate when latency constraints prevent passing the full trajectory context, as attribution accuracy degrades without complete tool-call history.

Before implementing this prompt, ensure your agent harness captures and passes the complete [AGENT_TRAJECTORY] including tool names, input arguments, output payloads, and call order. The prompt works best with structured output schemas that enforce a claim-to-source mapping per statement. Plan for validation: every claim in the output must reference at least one source present in the trajectory, and every cited source must actually contain the claimed information. For high-stakes domains like healthcare, legal, or finance, route outputs with missing or low-confidence attributions to human review. Start by running this prompt against a golden dataset of known agent trajectories where you can verify that attributions are neither hallucinated nor omitted.

PRACTICAL GUARDRAILS

Use Case Fit

Source attribution for agent-generated answers works best in multi-step, multi-tool environments where provenance is non-negotiable. It fails when the agent trajectory is too long to track or when the underlying tools don't return source identifiers.

01

Good Fit: Multi-Tool Agent Pipelines

Use when: An agent calls a search API, a database, and a calculator before synthesizing a final answer. Guardrail: Each tool response must include a stable source identifier that the attribution prompt can reference. Without tool-level source IDs, attribution degrades to guesswork.

02

Bad Fit: Single-Step RAG Without Tool Logs

Avoid when: The system retrieves context and generates an answer in one call without preserving chunk IDs or document metadata. Guardrail: Use a simpler inline citation prompt instead. Source attribution for agents requires a trajectory log; if you don't have one, you're asking the model to invent provenance.

03

Required Inputs

Must have: The full agent trajectory log including each tool call, its parameters, its raw response, and any source identifiers returned. Guardrail: Validate that the trajectory log is complete before calling the attribution prompt. Missing steps create attribution gaps that the model will silently fill with plausible but incorrect sources.

04

Operational Risk: Long Trajectory Drift

What to watch: As agent steps increase beyond 5-7 tool calls, attribution accuracy degrades. The model loses track of which claim came from which intermediate step. Guardrail: Chunk the trajectory into segments and attribute per segment, then merge. Set a maximum trajectory length and escalate to human review when exceeded.

05

Operational Risk: Tool Responses Without Source IDs

What to watch: Some tools return synthesized answers without citing their own sources. The attribution prompt cannot trace claims through opaque tool responses. Guardrail: Wrap tools that lack source IDs in a thin harness that captures the query and response with a generated identifier. Flag claims derived from opaque tools as 'tool-synthesized, source untraceable' rather than fabricating a citation.

06

Operational Risk: Cross-Tool Claim Merging

What to watch: The agent combines information from two tools into one claim. The attribution prompt may assign the merged claim to only one source. Guardrail: Instruct the prompt to flag merged claims and list all contributing sources. Add an eval check that detects single-source attribution for claims that required multiple tool calls.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt template for generating per-statement source attribution in multi-step agent answers, ready to copy and adapt.

This prompt template is designed for agent systems that synthesize final answers from multiple tool calls and retrieval steps. Its core job is to produce an answer where every factual statement is explicitly linked to its origin—a specific tool output, document chunk, or API response—preserving the attribution chain across the agent's entire trajectory. Use this when you need audit-ready traceability, not just a plausible-sounding answer. Do not use this for simple single-hop RAG where a basic inline citation prompt would suffice; this template adds overhead for multi-step provenance tracking that simpler workflows don't need.

text
You are an attribution specialist for an AI agent. Your task is to generate a final answer based on the provided agent trajectory, which includes a sequence of tool calls and their outputs. You must produce an answer where every factual claim is explicitly linked to its source.

## AGENT TRAJECTORY
[AGENT_TRAJECTORY]

## USER QUERY
[USER_QUERY]

## OUTPUT SCHEMA
Produce a JSON object with the following structure:
{
  "answer": "A synthesized, coherent answer to the user query.",
  "statements": [
    {
      "statement_id": "s1",
      "text": "A single, atomic factual claim from the answer.",
      "source_tool": "The name of the tool call that produced the evidence (e.g., 'web_search', 'document_retrieval', 'calculator').",
      "source_reference": "A precise identifier for the evidence within the tool output (e.g., a URL, document ID, chunk index, or line number).",
      "source_excerpt": "The exact text from the tool output that supports this claim.",
      "confidence": "high | medium | low",
      "attribution_gap": "If confidence is not 'high', explain what is missing or uncertain."
    }
  ],
  "unattributed_claims": [
    {
      "text": "A claim in the answer that could not be traced to any tool output.",
      "reason": "Why no source was found (e.g., 'inferred from multiple sources', 'common knowledge', 'no supporting evidence in trajectory')."
    }
  ]
}

## CONSTRAINTS
[CONSTRAINTS]

## EXAMPLES
[EXAMPLES]

To adapt this template, replace the square-bracket placeholders with your specific context. [AGENT_TRAJECTORY] should be a structured log of every tool call and its raw output, preserving the order of execution. [CONSTRAINTS] is where you enforce domain-specific rules, such as 'Never attribute a claim to a source that only partially supports it' or 'Flag any claim derived from a source older than [DATE] as low confidence.' [EXAMPLES] should include at least one multi-step trajectory example showing how a claim that depends on two tool outputs (e.g., a search result and a calculator confirmation) is attributed to both. After copying this template, immediately test it with a trajectory where a tool call fails or returns empty results to ensure the unattributed_claims array is populated correctly rather than silently omitted.

IMPLEMENTATION TABLE

Prompt Variables

Required inputs for the Source Attribution for Agent-Generated Answers Prompt. Each placeholder must be populated before the prompt is assembled and sent to the model. Validation notes describe how to programmatically verify that each input is well-formed before execution.

PlaceholderPurposeExampleValidation Notes

[AGENT_TRAJECTORY]

Complete multi-step agent execution log including all tool calls, retrieved documents, intermediate reasoning, and final synthesized answer

{"steps": [{"tool": "search_kb", "query": "Q4 revenue 2024", "result": {"doc_id": "fin-042", "text": "Revenue was $12.3B"}}], "final_answer": "Revenue reached $12.3 billion in Q4 2024."}

Must be valid JSON with steps array. Each step requires tool name, input, and output fields. Reject if trajectory is empty or missing final_answer field.

[TOOL_REGISTRY]

Schema definitions for all tools available to the agent, including tool names, descriptions, parameter signatures, and return types

{"tools": [{"name": "search_kb", "description": "Search internal knowledge base", "parameters": {"query": "string"}, "returns": {"doc_id": "string", "text": "string"}}]}

Must be valid JSON with tools array. Each tool requires name, description, and returns schema. Reject if tool names in trajectory are not present in registry.

[SOURCE_METADATA_SCHEMA]

Required metadata fields for each attributed source, such as document title, publication date, author, version, and retrieval timestamp

{"required_fields": ["source_id", "title", "publication_date", "retrieval_timestamp", "authority_level"]}

Must be valid JSON with required_fields array. Each field name must be a non-empty string. Reject if source_id is not in required_fields list.

[ATTRIBUTION_GRANULARITY]

Specifies the level of attribution detail required: statement-level, paragraph-level, sentence-level, or claim-level

"statement-level"

Must be one of: statement-level, paragraph-level, sentence-level, claim-level. Reject on unknown values. Controls how finely the output splits attributed units.

[CONFIDENCE_THRESHOLD]

Minimum confidence score for including a source attribution in output; attributions below this threshold are flagged as uncertain

0.7

Must be a float between 0.0 and 1.0. Reject if non-numeric or out of range. Used to filter weak attributions before output generation.

[MAX_SOURCES_PER_STATEMENT]

Upper limit on how many distinct sources can be cited for a single statement to prevent citation clutter

3

Must be a positive integer. Reject if zero or negative. Prevents attribution overload when many sources support the same claim.

[UNATTRIBUTABLE_POLICY]

Instruction for handling statements that cannot be traced to any tool output or retrieved source

"flag_with_null_source_and_confidence_zero"

Must be one of: flag_with_null_source_and_confidence_zero, omit_from_output, mark_as_agent_generated, escalate_for_human_review. Reject on unknown values. Defines behavior for untraceable claims.

[OUTPUT_FORMAT]

Desired output structure specification, such as inline annotations, side-by-side mapping, or structured JSON with statement-to-source arrays

{"type": "json_array", "schema": {"statement": "string", "sources": [{"source_id": "string", "tool": "string", "confidence": "float", "evidence_span": "string"}]}}

Must be valid JSON with type field and schema definition. Reject if schema is missing required fields for attribution tracking. Schema must include source_id and confidence fields at minimum.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the Source Attribution prompt into a multi-step agent application with validation, retries, and audit logging.

The Source Attribution for Agent-Generated Answers prompt is designed to operate as a post-hoc verification step within an agent loop, not as a standalone generator. After the agent synthesizes a final answer from multiple tool calls and retrievals, this prompt processes the combined trajectory—including the final answer text, the ordered list of tool calls, and the raw content returned by each tool—to produce a statement-level attribution map. The implementation harness must therefore capture the agent's execution trace before invoking this prompt. Store each tool call as a record with a unique tool_call_id, the tool name, input parameters, and the full response payload. The agent's final answer should be captured as a separate string. These two artifacts become the primary inputs to the attribution prompt.

Wire the prompt into the agent's post-generation pipeline. After the agent produces a final answer, immediately invoke the attribution prompt with the answer text and the serialized tool-call trace. The prompt returns a structured JSON array where each object maps a claim from the answer to one or more source tool calls. Implement a validation layer that checks every returned claim against the original answer text to ensure no hallucinated claims were introduced by the attribution step itself. For each attribution, verify that the referenced tool_call_id exists in the captured trace and that the cited evidence substring appears in the corresponding tool response. If validation fails, retry the attribution prompt once with the validation errors included as feedback. If the retry also fails, flag the answer for human review and log the failure for prompt debugging.

Model choice matters for this workflow. Use a model with strong instruction-following and structured output capabilities, such as GPT-4o or Claude 3.5 Sonnet, because the prompt requires precise JSON output and faithful extraction of claims from the source text. Avoid smaller or older models that may introduce attribution errors or fail to maintain the required output schema. Set the temperature to 0 or a very low value (0.1) to maximize deterministic behavior. Enable structured output mode if the model API supports it, providing the expected JSON schema directly. For high-throughput production systems, consider batching multiple agent answers into a single attribution call if the context window permits, but ensure each batch item is independently traceable to its source trace. Log every attribution call with the input trace, raw output, validation results, and any retry attempts. This audit trail is essential for debugging attribution failures and for demonstrating provenance to downstream consumers or compliance reviewers.

IMPLEMENTATION TABLE

Expected Output Contract

Define the exact shape of the structured output for the Source Attribution prompt. This contract is used to validate the agent's final response, ensuring every claim is linked to a specific tool call or document source.

Field or ElementType or FormatRequiredValidation Rule

attributed_answer

string (markdown)

Must contain at least one inline citation token matching the pattern [SOURCE_ID].

sources

array of objects

Array length must be >= 1. Each object must pass the source object validation rules below.

sources[].source_id

string

Must match a SOURCE_ID used in the attributed_answer field. Must be unique within the sources array.

sources[].tool_name

string

Must be a non-empty string matching one of the tool names provided in the agent's [TOOL_REGISTRY] context.

sources[].document_title

string or null

Must be a non-empty string if the source is a retrieved document; otherwise null.

sources[].retrieved_snippet

string

Must be a direct, verbatim quote from the tool output. Length must be > 0.

sources[].claim_summary

string

A concise summary of the specific claim this source supports. Must be a non-empty string.

unsupported_statements

array of strings

If present, each string must be a factual statement from the answer that could not be attributed to any source. If empty or absent, it implies full attribution.

PRACTICAL GUARDRAILS

Common Failure Modes

Source attribution in multi-step agent systems breaks in predictable ways. Here are the most common failure modes and how to guard against them before they reach production.

01

Attribution Drift Across Tool Calls

What to watch: The agent retrieves a fact in step 2, summarizes it in step 4, and by step 6 the source pointer is lost or points to the wrong tool output. Multi-step trajectories create attribution gaps where claims float free of their evidence chain. Guardrail: Require the agent to carry a structured attribution_map object across turns, updating it with every synthesis step. Validate that every claim in the final output has a non-null source pointer before returning.

02

Silent Evidence Fabrication

What to watch: The model generates a plausible-sounding claim and attributes it to a real tool or document that never actually contained that information. This is especially dangerous when the cited source exists but the claim doesn't appear in it. Guardrail: Implement a post-hoc evidence verification step that re-queries the cited source and checks for claim presence. Flag any attribution where the quoted or paraphrased content cannot be located in the referenced tool output.

03

Cross-Contamination Between Sources

What to watch: The agent retrieves from Tool A and Tool B, then synthesizes a claim that blends information from both but attributes it only to Tool A. The attribution is partially correct but misleading because it implies a single source supports the full claim. Guardrail: Require granular, per-statement attribution rather than paragraph-level citation. When a claim synthesizes multiple sources, the attribution must list all contributing sources with a note on which part each source supports.

04

Tool Output Truncation Masking Gaps

What to watch: A tool returns truncated results due to token limits, and the agent treats the partial output as complete evidence. Claims attributed to that tool may be unsupported because the relevant passage was cut off. Guardrail: Include a truncation_flag in every tool response schema. Instruct the agent to check this flag before citing the tool and to mark any claim derived from truncated output with a partial_evidence warning.

05

Attribution to Agent Reasoning Instead of Evidence

What to watch: The agent performs internal reasoning, inference, or calculation and presents the result as a fact with a source citation. The cited source may contain raw data but not the derived conclusion, creating a false impression of evidentiary support. Guardrail: Distinguish between evidence_derived and agent_inferred claim types in the output schema. Require the agent to label any claim that involves extrapolation, calculation, or synthesis beyond what the source explicitly states.

06

Stale Attribution from Earlier Turns

What to watch: The agent cites a source from turn 3 in turn 7, but the information was superseded or contradicted by a later retrieval. The attribution is technically correct but temporally misleading. Guardrail: Timestamp every tool retrieval and include a retrieved_at field in the attribution map. Instruct the agent to prefer the most recent retrieval when sources conflict and to flag any claim backed only by older evidence when newer evidence exists.

IMPLEMENTATION TABLE

Evaluation Rubric

Use this rubric to test the quality of source attribution outputs before shipping. Each criterion targets a specific failure mode common in multi-step agent attribution. Run these checks on a golden set of agent trajectories with known ground-truth sources.

CriterionPass StandardFailure SignalTest Method

Statement Coverage

Every factual statement in the final answer has at least one source citation

Uncited factual assertion present in output

Parse output into individual claims; verify each claim has a non-null [SOURCE_ID] or [TOOL_CALL_ID] reference

Source Traceability

Each citation resolves to a specific tool call, document chunk, or retrieval step in the agent trajectory

Citation references a source not present in the trajectory log or uses a fabricated identifier

Cross-reference all [SOURCE_ID] values against the agent's tool call history and retrieval metadata

Attribution Granularity

Citations are attached at the statement level, not paragraph level

Entire paragraph cited to a single source when it contains claims from multiple retrieval steps

Split output by sentence boundary; check that each sentence with a distinct claim carries its own citation anchor

Tool Provenance Accuracy

Each claim is attributed to the correct tool or retrieval that actually produced the evidence

Claim attributed to tool A when evidence originated from tool B in the trajectory

Compare attribution labels against ground-truth tool-to-claim mapping from annotated trajectories

Null Evidence Handling

Statements without supporting evidence are explicitly marked as unverified rather than silently uncited

Unsupported claim appears without [UNVERIFIED] flag or fabricated citation is generated

Inject trajectories with known evidence gaps; confirm output contains explicit unsupported-statement markers

Cross-Step Attribution Integrity

Claims synthesized across multiple agent steps preserve attribution to each contributing step

Multi-step synthesis collapses all attribution to the final retrieval step only

Test with trajectories requiring evidence combination from 3+ tool calls; verify each contributing step appears in citation map

Citation Format Compliance

All citations match the specified [CITATION_FORMAT] schema exactly

Malformed citation string, missing required fields, or wrong format type

Validate output citations against [CITATION_FORMAT] JSON Schema; reject on parse errors or missing required fields

No Hallucinated Evidence

Cited source content actually exists in the referenced tool output or document

Citation quotes text not present in the referenced source or summarizes content the source does not contain

Extract quoted spans from citations; perform exact substring match against referenced source content from trajectory logs

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Use the base prompt with a single agent trajectory and one round of tool calls. Focus on getting the attribution format right before adding complexity. Replace the full trajectory placeholder with a simplified trace containing only the final answer and the tool outputs it references. Use a lightweight JSON schema for the output but skip strict validation in the harness.

Prompt snippet

code
You are an attribution tracer. Given the agent's final answer and the tool outputs it used, map each factual statement to its source.

Agent answer: [ANSWER]
Tool outputs: [TOOL_OUTPUTS]

Output a JSON array where each object has:
- "statement": the factual claim
- "source": the tool name or document ID
- "confidence": "direct" | "inferred" | "uncertain"

Watch for

  • Statements attributed to the wrong tool call when multiple retrievals return similar content
  • Inferred attributions that should be marked uncertain
  • Missing attribution for claims synthesized across multiple sources
Prasad Kumkar

About the author

Prasad Kumkar

CEO & MD, Inference Systems

Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.

His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.