Sub topic 2
What you can build: a map of application types
This chapter gives you a map of the main LLM application patterns. Later chapters cover each pattern in detail. Here you learn to look at a product idea and name the pattern it needs.
Prerequisites: basic Python, familiarity with JSON and HTTP APIs, and the idea from the previous chapter that a model predicts text one token at a time from the prompt you give it.
Why a map helps
Most LLM products are built from a small set of patterns, often combined. If you can name the pattern, you can predict the building blocks, the cost, and the failure modes before you write code. A common error is to treat "add AI" as one task. A ticket router, a document Q&A bot, and a booking assistant need different parts and fail in different ways.
Each pattern below answers three questions: what goes in, what comes out, and what your code has to provide around the model.
The main patterns
Text transformation
Input is text you already have. Output is new text derived from it: a summary, a rewrite in another tone, a translation, a first draft. The model needs no outside knowledge, because everything it needs is in the prompt.
This is the simplest pattern. Its main risk is that the output drifts from the source: dropped details, added claims, or a changed meaning.
Classification and extraction
Input is text. Output is a label from a fixed list, or a set of fields pulled from the text, such as the vendor and total on an invoice. Your code consumes the result, so the output must be predictable.
The key building block is a constrained prompt plus a check in code. This example asks for one label and falls back to a safe default when the reply is not allowed.
LABELS = ["billing", "bug", "feature_request", "other"]
def classify(ticket: str, complete) -> str:
prompt = (
"Classify the support ticket into exactly one label from: "
+ ", ".join(LABELS)
+ ".\nReply with the label only.\n\nTicket: " + ticket
)
answer = complete(prompt).strip().lower()
return answer if answer in LABELS else "other"Here complete is any function that takes a prompt string and returns the model's reply. Passing it in keeps the logic independent of a particular vendor and easy to test with a fake.
Structured output
This is a refinement of extraction. The model returns JSON that downstream code parses. The model can produce malformed or incomplete JSON, so you validate before use.
import json
def parse_invoice(raw: str) -> dict:
data = json.loads(raw)
if not isinstance(data.get("vendor"), str):
raise ValueError("vendor must be a string")
if not isinstance(data.get("total"), (int, float)):
raise ValueError("total must be a number")
return data
print(parse_invoice('{"vendor": "Acme", "total": 129.5}'))A failure here raises an error instead of passing bad data along. That is the goal: fail loudly at the boundary.
Conversational assistants
Input is a running dialogue. Output is the next reply. The model itself keeps no memory between calls, so your application resends the relevant history each time and decides what to keep when the history grows too long.
Retrieval-augmented generation (RAG)
Input is a question. Your system first searches your own documents, then places the best passages in the prompt, then the model answers from them. This lets a model answer about content it was never trained on, such as your internal policies. It depends on embeddings, which are lists of numbers that represent meaning, and on a similarity search.
This example shows retrieval in miniature. It ranks documents by cosine similarity between vectors.
import math
def cosine(a, b):
dot = sum(x * y for x, y in zip(a, b))
norm_a = math.sqrt(sum(x * x for x in a))
norm_b = math.sqrt(sum(y * y for y in b))
return dot / (norm_a * norm_b)
def top_k(query_vec, docs, k=2):
# docs is a list of (text, vector) pairs
ranked = sorted(docs, key=lambda d: cosine(query_vec, d[1]), reverse=True)
return [text for text, _ in ranked[:k]]
docs = [("refund policy", [1.0, 0.0]), ("shipping times", [0.0, 1.0]), ("refund steps", [0.9, 0.1])]
print(top_k([1.0, 0.0], docs))The output is ['refund policy', 'refund steps']. In a real system the vectors come from an embedding model and have hundreds or thousands of dimensions, but the ranking idea is the same.
Tool use
Input is a request the model cannot satisfy from text alone, such as "What is the weather in Oslo?" The model proposes a call to a function as structured data. Your code runs the function and returns the result as text. The model never executes anything itself.
import json
def get_weather(city):
return {"city": city, "temp_c": 18}
TOOLS = {"get_weather": get_weather}
def run_tool_call(call):
fn = TOOLS[call["name"]]
return json.dumps(fn(**call["arguments"]))
print(run_tool_call({"name": "get_weather", "arguments": {"city": "Oslo"}}))The TOOLS dictionary is an allow-list. Only functions you list can be called, which limits what a mistaken or manipulated model can do.
Agents
An agent is a loop. The model chooses an action, your code runs it, the result goes back into the prompt, and the model chooses again until it decides the task is done or a limit is reached. Agents handle multi-step tasks, but each step adds cost, delay, and a chance of error.
Code assistance
Input is code and an instruction. Output is code, an explanation, or a review. It combines text transformation with tool use, since good helpers can run tests and read files.
Multimodal features
Input or output includes images, audio, or documents with layout, such as a scanned receipt. These patterns often reduce to extraction or Q&A once the non-text content is read.
How the patterns relate
The patterns build on each other. Structured output is what makes tool use possible, since a tool call is structured data. Tool use is what makes agents possible. Retrieval can be seen as a tool the system calls on every question.
Matching an idea to a pattern
Use these questions in order.
- Does the answer depend only on text the user provides? Use text transformation, classification, or extraction.
- Does it depend on your private or changing documents? Use RAG.
- Does it need live data or must it change something in the world? Use tool use.
- Does it need an unknown number of steps? Consider an agent, but first check whether a fixed sequence of calls would do.
- Does the user need back-and-forth? Add a conversational layer on top of the pattern you chose.
| Product idea | Pattern | Main extra part |
|---|---|---|
| Route support tickets | Classification | Label list and fallback |
| Read invoices into a database | Extraction with structured output | Schema validation |
| Answer questions about the HR handbook | RAG | Embeddings and a document index |
| Book a meeting from a chat message | Tool use in a conversation | Calendar function and allow-list |
| Investigate a failing build | Agent | Step limit and logging |
Common errors when choosing
- Starting with an agent when a fixed two-step pipeline would be cheaper, faster, and easier to test.
- Using RAG when the documents are small enough to fit directly in the prompt.
- Skipping validation because the model "usually" returns the right format. Usually is not always.
- Letting the model's text drive actions without an allow-list.
Exercise
A company wants a tool that reads incoming emails, decides whether each is a complaint, a sales lead, or spam, and then files it in the right folder using their email system's API. Which patterns does it need, and which parts must your own code provide?
Show answer
It needs classification (three labels) and tool use (the folder action). Your code provides the label list with a fallback for unexpected replies, the function that calls the email API, an allow-list of callable functions, and the step that executes the call and returns results. No agent is needed because the steps are fixed.
Exercise
You run top_k([0.0, 1.0], docs) using the docs list from the retrieval example. What does it return, and why?
Show answer
It returns ['shipping times', 'refund steps']. The query vector points along the second axis, so "shipping times" has cosine similarity 1.0. "refund steps" scores about 0.11 and "refund policy" scores 0.0, so "refund steps" takes the second place.