What separates a language model demo that wows a room from a system that quietly runs thousands of real requests a day? Almost always, it is the integration pattern, not the model. The same foundation model can feel brilliant in a chat window and useless inside a product if the plumbing around it is wrong. Picking the right pattern early saves months of rework later.
This article walks through the main patterns teams use to connect large language models to real systems, what each one is good at, where it breaks, and the practical mistakes that show up again and again.
Why the Integration Pattern Matters More Than the Model
A model on its own only takes text in and gives text out. Everything useful happens at the edges: where it reads your data, calls your tools, and returns something your application can trust. That edge layer is the integration pattern.
The pattern decides three things at once: how accurate the output is, how much it costs per request, and how badly it fails when something goes wrong. A retrieval pattern with clean data beats a bigger model with no context almost every time. A tool-calling pattern with tight schemas beats a clever prompt that asks the model to “please format the answer as JSON.”
There is also a maintenance angle. Patterns that follow published standards survive model swaps. Patterns built on one vendor’s quirks tend to die with the next API change. That is why teams now treat integration design as architecture, not glue code.
Pattern 1: Plain Prompting With Structured Output

The simplest integration is still the most common. The application sends a prompt, the model returns text, and the code parses it. The upgrade that makes this production-ready is structured output: forcing the model to return valid JSON that matches a schema.
Structured output turns a fuzzy text generator into a component with a contract. Instead of hoping the model writes a clean address, you define fields for street, city, and postal code, and the parser either accepts the object or rejects it. OpenAI’s documentation on structured outputs explains how schema adherence works in practice, and it is worth reading before designing your own validation layer. (OpenAI function calling documentation)
Practical tips that actually work:
- Keep schemas small. Models handle five fields far more reliably than fifty.
- Make every field required or explicitly nullable. Optional fields invite silent omissions.
- Validate on your side anyway. Never trust a schema-enforced response without a parser check.
- Version your schemas the way you version APIs.
The common mistake here is treating JSON mode as a guarantee of correctness. It guarantees shape, not truth. A perfectly formed object can still contain the wrong answer.
Pattern 2: Tool and Function Calling
Function calling lets the model ask your application to run a function. The model returns a structured request naming the function and its arguments, your code executes it, and the result goes back to the model. This pattern is how assistants check inventory, book meetings, or query a database.
The idea spread fast after it appeared in mid-2023, and nearly every major provider now offers some version of it. The catch is portability. Schema constraints differ subtly between providers, especially around strict modes and nested objects, so a tool definition written for one API may need rewriting for another. Treat tool schemas as provider-specific artifacts.
What works in practice:
- Write tool descriptions for a smart new colleague, not for a compiler. Say when to use the tool and when not to.
- Return errors as data the model can read, not as stack traces.
- Cap the number of tool calls per turn so a confused model cannot loop forever.
- Log every call and its arguments. Debugging agents without call logs is guesswork.
The classic failure is a tool that returns too much. A database query that dumps 400 rows into the context window burns tokens and buries the answer. Return the three fields the model needs.
Pattern 3: Retrieval-Augmented Generation
Retrieval-augmented generation, or RAG, fixes the model’s biggest weakness: it does not know your private or recent information. Instead of retraining, you fetch relevant documents at request time and paste them into the prompt.
The pattern was formalized in the 2020 paper introducing retrieval-augmented generation, which combined a generative model with a searchable index of documents. The architecture has barely changed since: embed the query, find similar chunks, feed them in, generate.
Under the hood, most RAG systems rely on vector search using approximate nearest-neighbour indexes. The HNSW algorithm, described in the original HNSW paper on hierarchical navigable small world graphs, is the workhorse behind many of these indexes because it stays fast as collections grow.
Where teams go wrong with RAG:
| Mistake | What happens | Fix |
|---|---|---|
| Chunking by fixed character count | Sentences split mid-thought, answers get garbled | Chunk by headings and paragraphs |
| No reranking step | Top results are loosely related | Add a reranker before generation |
| Ignoring metadata filters | Users see documents they lack permission to read | Filter by tenant and role at query time |
| No evaluation set | Nobody notices quality drops | Build 50 gold questions with known answers |
The permission point deserves emphasis. If retrieval pulls from a shared index without access checks, the model will happily summarize a document the user should never see. Filter first, retrieve second.
Pattern 4: The Agent Loop
An agent is a model running in a loop: think, act, observe, repeat. The most influential formalization is the ReAct pattern, which interleaves reasoning traces with tool actions so the model can plan and adjust. The ReAct paper on reasoning and acting in language models is the clearest explanation of why this loop works.
Agents shine on multi-step tasks: research, triage, data cleanup. They also fail in spectacular ways. A loop with no stopping condition can run for minutes and spend real money. A loop with vague tools can thrash between options without progress.
What actually works in production:
- Set a hard step limit, usually five to ten, and return partial results when it is hit.
- Give the agent a scratchpad so it does not re-derive the same facts each turn.
- Require a final structured answer, not free text, so downstream code can use it.
- Log the full trace. When an agent misbehaves, the trace is the only evidence you have.
Be skeptical of the word “agent” itself. Vendors use it inconsistently, and there is no single agreed definition. Ask what the loop actually does before comparing products. (News)
Pattern 5: Standardized Tool Protocols
Every team that builds tool calling eventually writes the same adapter code. The Model Context Protocol, announced in late 2024 as an open standard, tries to end that duplication. It defines a client-server architecture where an LLM application connects to external tools and data sources through a common interface, with messages exchanged in JSON-RPC.
The appeal is obvious: write a server once, connect it to any compatible client. The Model Context Protocol specification site documents the message format, transport options, and server capabilities in detail.
A word of caution. Adoption moved quickly after launch, and support around MCP is still settling. Before you base architecture on MCP, check which clients your team uses support it today and how mature their implementations are. A standard is only as strong as its weakest implementation.
Pattern 6: Streaming Responses
Users judge latency by the first word they see, not the last. Streaming sends tokens as they are generated, which makes a ten-second response feel instant. Most LLM APIs stream using server-sent events, a long-lived HTTP connection that pushes text chunks to the browser. The WHATWG specification for server-sent events explains the mechanics if you need to build the client side yourself.
Streaming adds complexity that surprises people. Errors arrive after content has already rendered. Token counts are only final at the end. Retries mid-stream mean duplicate text unless you handle it. Plan for a “stream failed, show retry” state from day one.
Pattern 7: Guardrails and Evaluation
Every pattern above can be attacked or can quietly degrade. Prompt injection, where untrusted text in a document or web page hijacks the model’s instructions, is the signature risk of integrating LLMs with outside data. The OWASP Top 10 for LLM Applications catalogs prompt injection and related risks, and it is the standard checklist most security teams start from.
Guardrails belong at three points:
- Input: strip or flag instructions hidden in retrieved content.
- Tool use: require human approval for destructive actions like refunds or deletions.
- Output: validate structure, scan for leaked secrets, and log everything.
Evaluation is the other half. A regression suite of real questions with known answers catches silent quality drops when you change a prompt, a model, or a retrieval index. Teams that skip this step discover breakage from angry users instead. (Blog)
How the Patterns Fit Together
Most production systems combine several patterns rather than picking one.
| System type | Typical stack |
|---|---|
| Support chatbot | RAG plus structured output plus streaming |
| Internal research assistant | Agent loop plus tool calling plus RAG |
| Data extraction pipeline | Structured output plus guardrails plus evaluation |
| Developer tooling | MCP servers plus tool calling |
The practical advice is to start with the simplest pattern that solves the problem. Plain prompting with structured output covers more ground than people expect. Add retrieval when the model lacks knowledge. Add tools when it needs to act. Add an agent loop only when the task genuinely requires multiple dependent steps.
One more habit pays off: watch how vendors announce changes. A new integration feature often sounds bigger than it is. A short guide on how to read a vendor integration announcement helps separate real capability from marketing; read it before you rewrite your stack. Watching the news feed at 9481.org is a low-effort way to catch shifts in the surrounding tooling, and the blog at 9481.org covers hands-on patterns as they mature.
Conclusion
LLM integration patterns are not glamorous, but they are where reliability lives. Structured output gives you a contract. Tool calling gives you reach. Retrieval gives you knowledge. Agent loops give you autonomy, at a price. Protocols like MCP promise portability, and streaming makes it all feel fast. Guardrails and evaluation keep it honest.
Start simple, measure everything, and add complexity only when a real user problem demands it. The teams that ship dependable AI products are rarely the ones with the fanciest pattern. They are the ones who chose the right pattern for the job and tested it relentlessly.
What is the difference between RAG and fine-tuning?
RAG fetches relevant documents at request time and puts them in the prompt, so the model can answer from fresh or private data without retraining. Fine-tuning changes the model’s weights to teach style or format. RAG is usually better for facts that change; fine-tuning is better for behavior that stays the same.
Do I need an agent for my LLM integration?
Usually not. Most tasks need one model call with good context and a clear output format. Agents add cost, latency, and failure modes because the model decides its own steps. Reach for an agent loop only when the task genuinely requires multiple dependent actions that cannot be planned in advance.
How do I stop the model from returning broken JSON?
Use structured output or JSON mode from your provider, define a strict schema with required fields, and validate every response on your side before using it. Keep schemas small and avoid optional fields. Even with schema enforcement, always keep a parser check and a fallback path.
What is prompt injection and why does it matter for integrations?
Prompt injection is when untrusted text, such as a retrieved document or web page, contains instructions that hijack the model. It matters most in integrations because that is where outside content enters the prompt. Defenses include treating retrieved text as data, limiting tool permissions, and requiring approval for sensitive actions.
How many tool calls should an agent be allowed per turn?
Most production teams cap it between five and ten. The cap prevents runaway loops that burn tokens and time. When the limit is hit, return the partial result with a clear status so the user or the calling code knows the task was not finished.
How do I test an LLM integration before launch?
Build a small evaluation set of real questions with known correct answers, then run it after every change to prompts, models, or retrieval. Add adversarial cases for injection and edge cases for empty results. Track pass rates over time so silent quality drops show up before users notice.







