Add an LLM to a Real App — Building with LLMs, Part 2
Updated: Nov 23
Building with LLMs · Part 2
The ticket summaries had been live for a month when the support lead noticed refund requests being answered with the wrong template. A prompt change the week before had made the summaries shorter, and the shorter ones often dropped what the customer was actually asking for. Agents read the summary, picked a reply template, and sent it. The obvious fix was to roll back the prompt and regenerate the bad summaries. Nobody could find them: the summaries were stored without any record of which prompt or model had written them.
None of this was a model problem. The call worked, the text read well, and the error handling caught every API failure. What the integration hadn't handled was that the model's output became data in the app, and people made decisions from it.
This part wires an LLM into an existing service with that in mind. The example is ticket summarisation, but the same steps apply to classification, extraction or drafting.
What you'll build
a written definition of who reads the output, what they decide with it, and what a wrong answer costs
a service layer that returns the output together with the model, prompt version, latency and tokens that produced it
validation that treats model output as untrusted input
a background job that can't run the same work twice
storage and UI that show the output is AI-generated and keep the original one click away
a rollout behind a flag, with checks before every prompt or model change
Prerequisites: a first API call (Part 1), an app with a background job queue, Python 3.10+, the anthropic package.
Why a working API call isn't a working integration
The output becomes data. Once a summary is stored on the ticket, it's read in place of the ticket. A wrong summary doesn't throw an error; it changes what an agent does. The OWASP Top 10 for LLM Applications names this risk improper output handling: insufficient validation and handling of model outputs before other components consume them. Its mitigation is to treat the model like any other user and validate its responses before they reach the rest of the system.
Without provenance, you can't fix what you change. Prompts and models change: you tune the prompt, and providers retire models on a published schedule. Anthropic, for example, gives at least 60 days' notice and lists retirement dates on its deprecations page; Claude Sonnet 4.5 retires from the Claude API on 30 November 2026. If each stored output doesn't record the prompt version and model that produced it, a bad change can't be traced or reversed selectively.
Retries happen at several layers. The Anthropic Python SDK retries connection errors, rate limits and server errors twice by default. Background job systems retry failed jobs too. Add a retry in your own code and one failing call can become many, each billed, and each possibly writing its own result. Handle Agent Failures covers the same mechanism in agents.
The test: pick any AI-generated value stored in your app today. Can you say which prompt version and model produced it, and when? If not, you can't find the outputs affected by your next change.
A worked example: the summaries nobody could find
This is a composite drawn from common patterns, not one company. The figures are illustrative.
Context. A software company summarised every incoming support ticket in a background job. About 2,500 tickets a day. The summary appeared above the ticket in the agent's view, and agents had started choosing a reply template from it.
The fork. When the wrong-template complaints arrived, the engineering lead's plan was to roll back the prompt and regenerate the last week of summaries, around 17,500 calls. The support lead asked a question first: "Who reads this summary, what do they decide from it, and what happens when it's wrong?" The answer reframed the job. Agents used the summary to choose a reply template, so the one thing it had to get right was the customer's request. A wrong summary cost a wrong reply and a repeat contact.
The redesign.
The prompt now asked for structured output with a required request field: what the customer wants, in their own words where possible.
Every summary was stored with its prompt version, model ID and creation time.
A validator rejected any summary without a request, or longer than the ticket itself.
The agent view labelled the block "AI summary" and showed the first lines of the original message beneath it.
Before any prompt or model change, the team ran the new version on 40 real tickets with the expected request written down, and compared.
Regenerating only the summaries from the bad prompt version became a one-line query.
The discovery move. "Who reads it, what do they decide, and what does wrong cost?" sets the quality bar for any LLM output in an app. It tells you which field must be right, where a person should check, and what to measure.
The test: for one LLM feature in your app, write down the reader, the decision and the cost of a wrong output in one sentence each. If you can't, the feature has no definition of correct yet.
Step 1: Write down the job and collect real examples (20 min)
Feature: ticket summary
Reader: support agent, before replying
Decision: which reply template to use, and whether to escalate
Must be right: the customer's request; the product; whether money is involved
Cost of a wrong output: wrong reply, repeat contact, possible wrong refund
Then collect 20 to 40 real inputs, including hard ones, and write down the expected value for each field that must be right. That's your first evaluation set; Build Your First Eval Set covers it in depth.
Step 2: Build a service layer that returns provenance (20 min)
# services/llm_service.py
import json, os, time
from dataclasses import dataclass
import anthropic
PROMPT_VERSION = "ticket-summary-v4"
SUMMARY_PROMPT = """Summarise the support ticket as JSON with keys:
"request" (what the customer wants, using their words where possible),
"product", "involves_money" (true/false), "summary" (two sentences at most).
Return only the JSON."""
@dataclass
class LLMResult:
output: dict
model: str
prompt_version: str
input_tokens: int
output_tokens: int
latency_ms: int
class LLMService:
def __init__(self):
# The SDK retries connection errors, 429 and 5xx twice by default; don't add another loop.
self.client = anthropic.Anthropic(timeout=30.0, max_retries=2)
self.model = os.environ.get("SUMMARY_MODEL", "claude-sonnet-5-5")
def summarize_ticket(self, ticket_text: str) -> LLMResult:
start = time.monotonic()
response = self.client.messages.create(
model=self.model,
max_tokens=400,
system=SUMMARY_PROMPT,
messages=[{"role": "user", "content": ticket_text}],
)
text = "".join(b.text for b in response.content if b.type == "text")
return LLMResult(
output=json.loads(text), # a parse error is handled by the caller
model=response.model,
prompt_version=PROMPT_VERSION,
input_tokens=response.usage.input_tokens,
output_tokens=response.usage.output_tokens,
latency_ms=int((time.monotonic() - start) * 1000),
)
Version the prompt in code beside the service, and change PROMPT_VERSION whenever the prompt text changes. Record response.model, the model that actually answered, not just the one you asked for.
Step 3: Validate the output before you store it (15 min)
REQUIRED = ("request", "product", "involves_money", "summary")
def validate_summary(out: dict, ticket_text: str) -> list[str]:
problems = [f"missing {k}" for k in REQUIRED if k not in out]
if not str(out.get("request", "")).strip():
problems.append("empty request")
if len(str(out.get("summary", ""))) > len(ticket_text):
problems.append("summary longer than the ticket")
if not isinstance(out.get("involves_money"), bool):
problems.append("involves_money not a boolean")
return problems
An output that fails validation isn't stored as a summary. The ticket shows its original text instead, and the failure is counted. Never render model output as HTML or pass it into a query or command without the same escaping you'd apply to user input.
Step 4: Make the background job safe to run twice (15 min)
def generate_summary(ticket_id: int):
ticket = Ticket.find(ticket_id)
if ticket.summary_prompt_version == PROMPT_VERSION:
return # already done for this prompt version
try:
result = llm_service.summarize_ticket(ticket.full_text)
except (anthropic.APIError, json.JSONDecodeError) as e:
metrics.increment("summary_failed", tags={"reason": type(e).__name__})
return # let the UI fall back; don't re-queue forever
if problems := validate_summary(result.output, ticket.full_text):
metrics.increment("summary_invalid", tags={"reason": problems[0]})
return
ticket.update(
summary=result.output,
summary_model=result.model,
summary_prompt_version=result.prompt_version,
summary_created_at=now(),
)
log_llm_call("summarize_ticket", result) # tokens, latency, model, prompt version
# When a ticket is created
def create_ticket(data):
ticket = Ticket.create(data)
jobs.enqueue(generate_summary, ticket.id, max_attempts=2) # the user never waits for the model
return ticket
The check at the top makes the job idempotent: a retry, or a duplicate enqueue, does nothing once a summary exists for the current prompt version. The job doesn't retry on its own; the SDK has already retried what's worth retrying.
Step 5: Show it as AI output, with the original beside it (10 min)
{ticket.summary ? (
<section aria-label="AI summary">
<p className="label">AI summary · {ticket.summaryPromptVersion}</p>
<p><strong>Request:</strong> {ticket.summary.request}</p>
<p>{ticket.summary.summary}</p>
</section>
) : null}
<details open={!ticket.summary}>
<summary>Original message</summary>
<p>{ticket.firstLines}</p>
</details>
If there's no valid summary, the reader sees the original, not a placeholder that might never fill. Don't disguise a fallback as a summary: a truncated original labelled as such is honest; an extractive "summary" presented the same way as the model's isn't.
Step 6: Roll out behind a flag (10 min)
Put the feature behind a flag and enable it for a small share of tickets or one team first. Compare the outcome you care about, such as repeat contacts or reply-template changes after first reply, against tickets without summaries. A/B Test Prompts in Production covers how to read that comparison without fooling yourself.
Step 7: Check every prompt and model change before it ships (15 min)
def evaluate(service: LLMService, cases: list[dict]) -> dict:
hits = 0
for case in cases:
out = service.summarize_ticket(case["text"]).output
hits += case["expected_request_keyword"].lower() in out.get("request", "").lower()
return {"cases": len(cases), "request_correct": hits / len(cases)}
Run it on the current and the proposed prompt or model, and ship only if the field that must be right doesn't get worse. For model retirements, put the date in your calendar from the provider's deprecations page and run this check on the replacement before the date, not after.
Step 8: Watch it in production (10 min)
Log tokens, latency, model and prompt version for every call, and track:
failure and invalid rates by reason, from Step 4
cost per ticket, from token counts
a weekly review of a fixed number of summaries (say 30), read against their tickets by someone who knows the domain
the outcome from Step 6, so you'd notice the wrong-template problem in days, not weeks
Production Observability for Agents covers tracing and outcome metrics in more depth.
Completion check: the reader, decision and cost are written down; every stored output has a model and prompt version; outputs are validated before storage; the job is idempotent; the UI labels AI output and shows the original; a change can't ship without the evaluation run.
Choosing where the LLM call runs
Option | Gains | Costs | Best suited for | Warning signs |
Synchronous, in the request | Simple; result available immediately | User waits for the model; failures hit the request | Short, interactive tasks the user asked for | Timeouts on the user's request path |
Background job | User never waits; easy to retry safely | Result arrives later; needs a placeholder | Enrichment such as summaries and tags | Jobs re-queued endlessly; duplicate writes |
Batch, scheduled | Cheapest at volume; easy to re-run | Results hours old | Backfills, nightly reports | Used for data people need now |
Human-reviewed draft | A person checks before it's used | Reviewer time | Outputs sent to customers or affecting money | Approval rate near 100% in seconds |
When you need less of this
An internal tool where the person who triggered the call reads the output immediately needs little of the storage and provenance work: the reader is the check. The steps matter once output is stored, shown to someone else, or used to make a decision later.
Common failure modes
Output stored without provenance. You can't find what a bad change affected.
Output trusted like your own data. Rendered, queried or acted on without validation.
Retry on retry. Your loop around the SDK's loop inside the job queue's loop.
Non-idempotent jobs. A duplicate enqueue writes a second, different summary.
A fallback that looks like the real thing. The reader can't tell they're not seeing a model summary.
A model retirement found out on the day. Check the provider's deprecations page and test the replacement first.
Final takeaway
An LLM in a real app produces data that people act on, so treat it that way. Write down who reads the output, what they decide and what a wrong answer costs. Validate outputs like untrusted input, store the prompt version and model with every one, make the jobs that create them safe to run twice, and show readers what's AI-generated with the original beside it. Then let no prompt or model change ship without running it on your real examples first.

Sources
OWASP Gen AI Security Project, "LLM05:2025 Improper Output Handling", OWASP Top 10 for LLM Applications 2025: insufficient validation, sanitization and handling of model outputs before other components consume them; treat the model as any other user and validate its responses. https://genai.owasp.org/llmrisk/llm052025-improper-output-handling/
Anthropic, Python SDK documentation, "Retries" and "Timeouts": connection errors, 408, 409, 429 and 5xx errors are retried twice by default; max_retries and timeout configure this. https://platform.claude.com/docs/en/cli-sdks-libraries/sdks/python
Anthropic, "Model deprecations", Claude documentation, accessed 19 November 2026: at least 60 days' notice before retiring publicly released models; Claude Sonnet 4.5 retires on the Claude API on 30 November 2026. https://platform.claude.com/docs/en/about-claude/model-deprecations
Continue the Building with LLMs path
Previous — Part 1: Call Your First LLM API
Part of the Building with LLMs learning path.


