Lesson 9.6core4 h

Generation side: context assembly, citations, structured outputs and tool calling

Turning retrieved chunks into answers people can trust

Retrieval delivers evidence; generation decides whether the user gets a grounded, cited, well-formed answer or a confident fabrication. This lesson covers the prompt that makes a model answer from sources, the token budget and ordering effects that silently break it, citations and the abstain path, structured outputs that downstream code can consume, and tool calling — the mechanism that turns retrieval into something the model invokes on demand and the core mechanic of agents (10.2 Tool use and function calling). It ends with a complete minimal RAG system in forty lines of plain Python.

You'll be able to

  • Write a grounding prompt with numbered sources, citation rules and an explicit refusal path
  • Budget and order context tokens, and explain the lost-in-the-middle effect
  • Produce and validate structured outputs with a JSON schema or Pydantic model
  • Expose retrieval as a tool and run the tool-call loop
  • Implement a complete minimal RAG pipeline in plain Python and know which line each later upgrade replaces

Key ideas

  1. A grounding prompt sets role and rules, lists numbered sources with metadata, asks the question and fixes the output format — stable parts first, question last.
  2. Budget context by tokens: window minus system, question and reserved output; models read the beginning and end of long contexts better than the middle (lost in the middle).
  3. Numbered sources make citations cheap; verify claims against cited chunks post hoc and design an explicit, helpful refusal path.
Show 4 more key ideas
  1. Structured outputs (JSON schema / Pydantic) with constrained decoding let code consume answers reliably; validate citations as part of the schema.
  2. Exposing retrieval as a tool lets the model decide when and what to search — agentic RAG in miniature, at the cost of extra round-trips.
  3. A complete RAG system is about forty lines: embed chunks, cosine top-k, grounded prompt, LLM call; every later technique replaces one of those lines.
  4. Stream tokens, show sources early and collect one-click feedback — UX decisions double as evaluation data.

Suggested path through this lesson