- Capstones
- Capstone 1
Structured research assistant
The finished assistant reads an article, streams its progress as server-sent events and returns key findings, named entities and a confidence score as JSON that always passes a strict schema, repairing broken replies up to twice before failing clearly. You build it from the outside in: the prompt and schema, a provider switch with a fake model, streaming, the repair loop, a 20-article test set, and finally tests that measure each acceptance target.
A command-line or web assistant that reads an article, streams its progress, and returns findings as validated JSON: key findings, named entities and a confidence score. It works with a hosted API or a local open-weights model behind the same interface.
Try each milestone yourself first. Hints and the solution for each step are folded away until you open them. Everything runs offline with a built-in fake model, so you need no API key and spend no credits.
Architecture
Structured research assistant
Swipe to change step
Step 1 of 8. The article fills a prompt template with named variables: the text, the output rules and the JSON Schema the reply must match. Article (text to read). Prompt template (article, rules, schema). arrow from Article to Prompt template. a article moving along e1.
Set up
Clone the capstones repository to run the reference solution, or start an empty folder with the same layout to build it yourself. You need Python 3.11 or later and uv.
git clone https://github.com/gauthamboppana/agentic-ai-wiki-capstones.git
cd agentic-ai-wiki-capstones/research-assistantuv sync
uv run pytest -q
uv run python -m research_assistant.cli demoLessons to finish first (9)
- 1.2 Pydantic models and runtime validation
- 1.6 Streaming with server-sent events
- 1.7 Retries with exponential backoff and jitter
- 6.4 Picking settings for extraction vs creative work
- 11.5 Message roles: system, developer and user
- 14.2 Constrained decoding and strict schema modes
- 14.8 Refusals, truncation and validation retries
- 15.5 Prompt templates with variables
- 30.7 Desktop runners: Ollama, LM Studio and llama.cpp
Milestone 1 of 6
Write the prompt template and the strict schema
A filled prompt carries the article, the output rules and a strict JSON Schema generated from typed models.
Steps
- Create Pydantic models Entity and Findings with extra fields forbidden: article_id, key_findings (1 to 5), entities with a fixed set of types, and confidence from 0 to 1.
- Write strict_json_schema(): start from model_json_schema(), then on every object list all properties as required, set additionalProperties to false and drop title and default.
- Write the prompt as a string.Template with named variables for the article id, title, text, rules and schema.
- Keep the output rules as a list so you can change them without touching the template.
- Add a short repair template that names the problem and asks for only the corrected JSON.
Hint 1
Strict structured output on most hosts wants every property required and no extra keys, including inside $defs.
Hint 2
Template.substitute raises KeyError on a missing variable, which is exactly what you want: a silent blank is worse.
Hint 3 (strongest)
Walk the schema recursively: dicts and lists both, so the Entity definition is tightened too.
Checkpoint
uv run pytest -q tests/test_prompt_schema.py4 tests pass: the prompt holds every variable, a missing one raises, the schema is strict and bad values are rejected.
Show solution src/research_assistant/schema.py
class Findings(BaseModel):
"""What the assistant must return for every article."""
model_config = ConfigDict(extra="forbid")
article_id: str = Field(min_length=1)
key_findings: list[str] = Field(min_length=1, max_length=5)
entities: list[Entity] = Field(max_length=20)
confidence: float = Field(ge=0.0, le=1.0)
def strict_json_schema(model: type[BaseModel] = Findings) -> dict:
"""Pydantic's schema, tightened for strict structured output.
Strict mode on most hosts wants every property listed in `required`,
`additionalProperties: false` on every object, and no `default` or `title`
noise. We walk the whole tree, including `$defs`, and fix each object.
"""
schema = copy.deepcopy(model.model_json_schema())
def tighten(node: object) -> None:
if isinstance(node, dict):
node.pop("title", None)
node.pop("default", None)
if node.get("type") == "object" and "properties" in node:
node["required"] = list(node["properties"].keys())
node["additionalProperties"] = False
for value in node.values():
tighten(value)
elif isinstance(node, list):
for item in node:
tighten(item)
tighten(schema)
return {"name": "findings", "strict": True, "schema": schema}
The Pydantic model is the single source of truth: the same class validates replies and generates the schema sent to the model, so the two cannot drift apart.
Milestone 2 of 6
Add the provider switch and a fake model
One stream(messages) interface serves a deterministic fake, a hosted API and a local runner, chosen by environment variables.
Steps
- Define a Provider protocol: a name and stream(messages) that yields text chunks.
- Write FakeModel: read the article out of the prompt, build honest findings with simple rules, and stream the JSON in small chunks after a short delay.
- Give the fake a fault plan per article (truncate, prose, bad confidence, missing field) so some first replies are broken.
- Write OpenAICompatible: POST to /chat/completions with stream true, parse the data: lines and yield each delta.
- Write get_provider() that reads RA_PROVIDER, RA_BASE_URL, RA_MODEL and RA_API_KEY, with the fake as the default.
- Make the HTTP transport injectable so tests feed recorded event lines and never touch the network.
Hint 1
If the fake keeps a counter, repeated runs disagree. Work out the attempt number from the conversation instead.
Hint 2
A local runner such as Ollama serves the same format at http://localhost:11434/v1, so one adapter covers hosted and local.
Hint 3
Read the key only from the environment and keep it out of repr() and logs.
Hint 4 (strongest)
Count earlier assistant turns in the messages list: zero means first try, one means first repair.
Checkpoint
uv run pytest -q tests/test_providers.py5 tests pass: the default is the fake, the environment switches to the adapter, the key never shows, and recorded stream lines go through the same pipeline.
Show solution src/research_assistant/providers.py
class FakeModel:
"""Deterministic and offline. Reads the article out of the prompt, streams JSON in small chunks.
`faults` maps article id to a list of fault names, one per attempt, so the repair path runs.
The attempt number is worked out from the conversation (one assistant turn per earlier try),
so the fake keeps no hidden state and every run is repeatable.
"""
name = "fake"
def __init__(self, faults: dict[str, list[str]] | None = None, first_token_delay: float = 0.02,
chunk_size: int = 24, chunk_delay: float = 0.0):
self.faults = DEFAULT_FAULTS if faults is None else faults
self.first_token_delay = first_token_delay
self.chunk_size = chunk_size
self.chunk_delay = chunk_delay
def reply(self, messages: list[Message]) -> str:
m = ARTICLE_RE.search(next(x["content"] for x in messages if x["role"] == "user"))
if not m:
return apply_fault("refuse", {})
good = extract(m["id"], m["text"])
attempt = sum(1 for x in messages if x["role"] == "assistant")
plan = self.faults.get(m["id"], [])
return apply_fault(plan[attempt], good) if attempt < len(plan) else json.dumps(good)
def stream(self, messages: list[Message]) -> Iterator[str]:
text = self.reply(messages)
time.sleep(self.first_token_delay)
for i in range(0, len(text), self.chunk_size):
if i and self.chunk_delay:
time.sleep(self.chunk_delay)
yield text[i : i + self.chunk_size]
Faults are data, not randomness, so every test run exercises the same repairs. The adapter speaks one widely copied wire format, which is what lets hosted and local models share a code path.
Milestone 3 of 6
Stream progress as server-sent events
Tokens and a progress count arrive as SSE frames while the model writes, ending in a result or an error frame.
Steps
- Make the core a generator that yields JSON-safe events: start, token, progress, invalid, result and error.
- Stamp the time when the request goes out and again at the first non-empty chunk: that gap is the time to first token.
- Write format_sse(): an event line, a data line of JSON and a blank line.
- Serve GET /analyse?id= with the standard library HTTP server and Content-Type text/event-stream, flushing after each frame.
- Add a ProgressLine for the terminal that rewrites one line with a carriage return.
Hint 1
If the terminal, the server and the tests each run their own loop, they will drift. Let them all consume the same events.
Hint 2
A stream that raises halfway leaves the browser hanging. Return the error as a final frame instead.
Hint 3 (strongest)
FastAPI is optional here: StreamingResponse over the same generator gives the same frames.
Checkpoint
uv run pytest -q tests/test_streaming.py3 tests pass: frames round-trip, the progress count only grows and matches the tokens, and the progress line ends with done.
Show solution src/research_assistant/sse.py
def format_sse(event: dict) -> str:
"""One SSE frame: an `event:` line, a `data:` line of JSON, and a blank line to end it."""
return f"event: {event['event']}\ndata: {json.dumps(event['data'], ensure_ascii=False)}\n\n"
def sse_stream(article: dict, provider: Provider, **kwargs) -> Iterator[str]:
"""Every pipeline event as an SSE frame. Ends with a `result` or an `error` frame, never an exception."""
for event in run(article, provider, **kwargs):
yield format_sse(event)
def parse_sse(text: str) -> list[tuple[str, dict]]:
"""The client side, for tests and scripts: split a stream back into (event, data) pairs."""
out = []
for frame in text.strip().split("\n\n"):
fields = dict(line.split(": ", 1) for line in frame.splitlines() if ": " in line)
out.append((fields.get("event", "message"), json.loads(fields.get("data", "null"))))
return out
parse_sse is the client side, so tests can check a real stream end to end without opening a socket.
Milestone 4 of 6
Validate strictly and repair up to twice
Every reply is checked against the schema; broken ones go back to the model with the exact problem, at most twice, then fail with a clear error.
Steps
- Write check(): empty, refused, truncated, not JSON or schema error, each with a short message. Do no silent fixes.
- On failure, append the broken reply as an assistant turn and a repair prompt naming the problem as a user turn.
- Loop for one try plus MAX_REPAIRS = 2 repairs, and record every attempt with its TTFT, length and error kind.
- When the attempts run out, build a ResearchError that names the article, the attempt count and the last problem.
- Treat provider exceptions such as timeouts as a failed attempt rather than a crash.
Hint 1
Stripping code fences looks helpful, but it hides a model problem. Send it back as a repair so it counts.
Hint 2
Truncated JSON usually fails with an Unterminated string error or more opening braces than closing ones.
Hint 3 (strongest)
Also check that article_id matches the article you sent: a valid object about the wrong article is still wrong.
Checkpoint
uv run pytest -q tests/test_repair.py11 tests pass: problems are classified, nothing is silently fixed, the repair prompt carries the error and two repairs is the limit.
Show solution src/research_assistant/pipeline.py
def run(article: dict, provider: Provider, max_repairs: int = MAX_REPAIRS, unsure_below: float | None = None,
clock: Callable[[], float] = time.perf_counter) -> Generator[Event, None, ResearchResult | ResearchError]:
"""Yields progress events; returns the result, or a ResearchError (it does not raise, so streams can close cleanly)."""
aid = article["id"]
messages: list[Message] = [
{"role": "system", "content": SYSTEM},
{"role": "user", "content": build_prompt(aid, article.get("title", ""), article["text"])},
]
attempts: list[Attempt] = []
for n in range(1, max_repairs + 2):
yield {"event": "start", "data": {"article_id": aid, "attempt": n, "provider": provider.name}}
start, ttft, parts = clock(), None, []
try:
for chunk in provider.stream(messages):
if not chunk:
continue
if ttft is None:
ttft = clock() - start
parts.append(chunk)
yield {"event": "token", "data": {"attempt": n, "text": chunk}}
yield {"event": "progress", "data": {"attempt": n, "chars": sum(map(len, parts))}}
text = "".join(parts)
findings, kind, error = check(text, aid)
except Exception as e: # network errors and timeouts count as a failed attempt, not a crash
text, findings, kind, error = "".join(parts), None, "provider_error", f"{type(e).__name__}: {e}"
attempts.append(Attempt(n, ttft, clock() - start, len(text), findings is not None, kind, error))
if findings is not None:
status = "unsure" if unsure_below is not None and findings.confidence < unsure_below else "ok"
result = ResearchResult(findings, attempts, status)
yield {"event": "result", "data": {"status": status, "retries": result.retries,
"ttft_ms": _ms(result.ttft_s), "findings": findings.model_dump()}}
return result
yield {"event": "invalid", "data": {"attempt": n, "kind": kind, "error": error,
"will_retry": n <= max_repairs}}
messages = messages + [
{"role": "assistant", "content": text or "(empty reply)"},
{"role": "user", "content": build_repair_prompt(aid, f"{kind}: {error}")},
]
err = ResearchError(aid, attempts)
yield {"event": "error", "data": {"article_id": aid, "message": str(err)}}
return err
run() returns the ResearchError instead of raising it, so a stream can always close with an error frame. analyse() is the thin wrapper that raises for ordinary callers.
Milestone 5 of 6
Bundle the test set and the scoring script
Twenty short original articles run through the pipeline and produce one report of validity, retries, TTFT and entity recall.
Steps
- Write 20 short articles, each naming a few people, organisations and places, and list the expected entities with each one.
- Load them with importlib.resources so the data ships inside the package.
- Write a nearest-rank percentile function and use it for p50 and p90 TTFT.
- Score every article, keep results and failures apart, and compute entity recall against the expected names.
- Render a short report with PASS or FAIL against the TTFT target.
Hint 1
Original data keeps the set free to share and means the model cannot have memorised it.
Hint 2
Count TTFT on the first attempt of each request: that is the wait the user feels.
Hint 3 (strongest)
Nearest rank on 20 values: the 90th percentile is the 18th smallest.
Checkpoint
uv run pytest -q tests/test_scoring.py3 tests pass: 20 unique articles with expected entities, the percentile is right and the report shows every target.
Show solution src/research_assistant/score.py
def entity_recall(result: ResearchResult, expected: Iterable[str]) -> float:
expected = [e.lower() for e in expected]
found = {e.name.lower() for e in result.findings.entities}
return sum(1 for e in expected if e in found) / max(1, len(expected))
def score(provider: Provider, articles: Iterable[dict] | None = None,
on_event: Callable[[str, Event], None] | None = None) -> Report:
report = Report()
for article in load_articles() if articles is None else articles:
hook = (lambda ev, a=article["id"]: on_event(a, ev)) if on_event else None
try:
result = analyse(article, provider, on_event=hook)
except ResearchError as err:
report.failures[article["id"]] = err
continue
report.results[article["id"]] = result
report.recall[article["id"]] = entity_recall(result, article.get("expected_entities", []))
return report
Failures are caught per article, so one bad article never stops the scoring run and still shows up in the report.
Milestone 6 of 6
Measure the acceptance targets
Tests and a demo command show 20 of 20 schema-valid outputs, a TTFT p90 under 1.5 s and no crash on three broken cases.
Steps
- Score all 20 articles with the fake and assert 20 valid, re-validating each result and checking the four repaired ids.
- Run once with max_repairs=0 to prove the faulty articles really fail without the repair loop.
- Assert the TTFT p90 is under 1.5 s on the fake path, and that a slow fake fails the same check.
- Feed three broken cases: truncated then good, refused then good, and broken every time, which must raise a clear error.
- Wire it into cli demo so one command prints the acceptance report.
Hint 1
A control run without repairs turns 20 of 20 from a claim into evidence.
Hint 2
Check the error message itself: the article id, the attempt count and the last problem should all be there.
Hint 3 (strongest)
For the hosted path, point RA_PROVIDER at your host and run cli score to get a real p90.
Checkpoint
uv run pytest -q tests/test_accept_schema_valid.py tests/test_accept_ttft.py tests/test_accept_failures.py11 tests pass, and uv run python -m research_assistant.cli demo prints 20/20 valid, p90 PASS and the three broken cases.
Show solution tests/test_accept_failures.py
TRUNCATED = '{"article_id": "a01", "key_findings": ["The coastal town of Pen'
REFUSED = "I'm sorry, but I can't help with that request."
def test_case_1_truncated_then_recovers(article, good_reply):
result = analyse(article, ScriptedModel([TRUNCATED, good_reply]))
assert result.retries == 1
assert result.attempts[0].error_kind == "truncated"
def test_case_2_refused_then_recovers(article, good_reply):
result = analyse(article, ScriptedModel([REFUSED, REFUSED, good_reply]))
assert result.retries == 2
assert [a.error_kind for a in result.attempts] == ["refused", "refused", None]
def test_case_3_exhausted_retries_raise_a_clear_error(article):
with pytest.raises(ResearchError) as info:
analyse(article, ScriptedModel([TRUNCATED, REFUSED, TRUNCATED]))
message = str(info.value)
assert "'a01'" in message and "3 attempts" in message and "2 repairs" in message
assert "truncated" in message
assert [a.error_kind for a in info.value.attempts] == ["truncated", "refused", "truncated"]
Each case asserts the error kinds attempt by attempt, so the test proves the repair loop saw the problem rather than just reaching a happy ending.
Acceptance targets
- Schema-valid outputs
- 20 of 20 articlesValidate every output against the schema; retries count, silent fixes don't.
- Time to first token
- under 1.5 s on the hosted pathLog TTFT per request and report the 90th percentile.
- Failure handling
- no crash on truncated or refused outputFeed three broken cases and show the retry or the clear error.
Stretch: Add a confidence threshold below which the assistant says it is unsure instead of answering.