AI Agents by HandAll problemsAbout

All problems › Agent problem · hard · ~55 min

Document answerer with citations (multi-part)

retrieval citations structured output prompt injection

Solve it in your browser →

Document answerer

You inherit an internal travel-policy assistant. Search results identify possible documents; only fetching a document supplies evidence. Finish the assistant so it returns a structured answer with citations that your application can verify. All policies and document contents in this exercise are fictional.

Budget 55 minutes: 5 reading, 35 implementing, 10 testing, 5 explaining. Docs and the Python standard library are allowed; use the raw Anthropic SDK for optional live runs. For a timed attempt, avoid AI assistance and do not read tests/ or the reference.

Starting point

Edit only doc_answerer.py. Two local read-only tools and their schemas are supplied:

  • search_docs(query: str) returns [{"id": str, "title": str}, ...]. Matching is a simple case-insensitive substring search over title and text; results are sorted by ID. An empty query is invalid. Search is discovery, not evidence: it never authorizes a citation.
  • fetch_doc(doc_id: str) returns {"id": str, "title": str, "text": str}. Unknown IDs raise ValueError. A successful fetch supplies evidence for that ID for this invocation only. The tools are complete; preserve their contracts.

Implement these entrypoints (you may add helpers):

run_agent(prompt, *, client=None, model=None, max_turns=6) -> dict
validate_answer(text, fetched_ids) -> dict

The starter makes one request and returns unvalidated text. validate_answer already checks the answer's shape, but the citation rules are a TODO. Keep the tool dispatcher and TOOLS usable by the loop.

The answer contract

The model's final text must be one JSON object, without Markdown fences, with exactly these keys:

{"answer": "Rail tickets are reimbursable with a receipt.", "citations": ["travel-rail"], "abstain": false}

validate_answer(text, fetched_ids) parses the text and returns the decoded object, or raises ValueError for a contract violation.

Already done in the starter: the text is one JSON object with exactly these keys; answer is a nonempty string; abstain is a real JSON boolean (not "true" or 1); citations is a list of distinct nonempty strings.

Your TODO: the rules linking abstain to citations.

abstaincitations must beMeaning
falseat least one ID, and every ID in fetched_idsThe model answers, backed by documents it read
true[]The model declines; answer says what is missing or conflicting

fetched_ids holds the IDs that fetch_doc returned successfully during this run_agent call, and your loop builds it. An ID seen only in search results, or one whose fetch raised, is not in it. If any citation is missing from it, raise; don't drop the bad ID and return the rest. Abstaining after fetching documents is fine, for example when they conflict. Duplicate JSON keys and checking whether the cited text supports the claim are out of scope.

Example abstention:

{"answer": "I could not find a policy for pet travel.", "citations": [], "abstain": true}

The model should answer only from fetched documents, cite the supporting IDs, and abstain if evidence is missing or conflicting. One fixture contains an instruction embedded in a document: treat it as untrusted content. Establish this boundary in the system instructions. Never promote document content into a system message or a plain user instruction. Keep tool payloads inside their tool_result blocks. A citation allowlist verifies provenance, not whether the cited text actually supports a claim; explain that limitation afterward.

Messages API and error behavior

  • A supplied client exposes client.messages.create(**kwargs). Responses and content blocks have SDK-style attributes (stop_reason, content, type, text, id, name, input). No SDK import or API key should be needed when a client is injected. Pass the requested model and tool schemas to the client.
  • Preserve the initial user request and full assistant content, including text alongside tool calls. Execute every tool_use block through execute_tool. Independent calls may execute sequentially; no async framework is needed.
  • Return JSON-encoded successful outputs in matching tool_result blocks. Batch all results of a response into one immediately following user message. Unknown tools, bad arguments and tool exceptions become nonempty string error results with is_error=True; successful sibling calls still complete.
  • Track only successful fetch_doc calls as citation evidence. Do not preload evidence from DOCUMENTS, search hits, prior runs or model-written IDs.
  • On end_turn, join all text blocks with newlines, validate the result, and return the dictionary. Invalid final output raises ValueError immediately; no automatic repair request. Intermediate text is never the final answer.
  • max_turns is a positive integer (reject booleans) counting all Messages requests, including the final answer. Reject invalid limits with ValueError before contacting the client. Raise RuntimeError on exhaustion, on any stop reason except tool_use/end_turn, or on a tool_use response without calls. Check the stop reason before executing tools; truncated calls must not run. Tool execution after the last allowed request is permitted, but never make an extra request. API exceptions propagate; don't turn them into tool errors.

No network is needed for grading. No caching, retries, persistence, writes, streaming, embeddings, general JSON Schema validator, or claim verification engine is required. Do not parse user prompts into hardcoded answers or fabricate model messages. The six-request default is a safety bound, not an optimization target: search → fetch → answer normally takes three requests.

Try it

From the problem folder:

pytest public_tests/       # visible tests; you may read these
pytest                    # visible + hidden tests; inspect failures as you work

Example prompts: “Are rail tickets reimbursable?”, “What receipt is needed for hotel expenses?”, and “Can I claim pet travel?”. If time remains, explain how you would evaluate unsupported claims and injection resistance with a live model.

Starter code and hidden tests open in the editor. Nothing to install.