Building an AI System Is More Than Calling an LLM
Calling an LLM is easy. Building a reliable AI system is not. Using a contract analysis assistant as a practical example, this article explores the layers behind real-world AI applications, why simple implementations break down, and when techniques such as RAG and AI agents become necessary.
Table of Contents
- Introduction
- 1. Start With a Real Problem
- 2. What Happens When You Call an LLM?
- 3. From an LLM Call to an AI Application
- 4. The First Version: A Simple Contract Analyzer
- 5. Where the Simple Approach Breaks
- 6. The Layers of a Production AI System
- 7. Why We Should Not Start With RAG or Agents
- 8. How Do We Know the System Actually Works?
- 9. The Architecture We Will Build Toward
- Summary
Introduction
Building an AI application has never been easier.
You can call an API, provide a prompt, receive a response, and have a working prototype in minutes. With modern AI coding tools, you can even generate a user interface, connect a database, and deploy the entire application in a single afternoon.
But there is a fundamental difference between an application that can call an LLM and a system that reliably solves a real problem.
Consider a simple request:
Analyze this contract and identify the clauses that could expose my company to financial or legal risk.
A modern language model can produce a convincing answer. It may identify unusual payment terms, explain termination conditions, and summarize liability clauses.
The answer might even be correct.
But what happens when the contract is 150 pages long? What if the relevant clause appears in an appendix? What if two sections contradict each other? What if the model invents a clause that does not exist? What if the user asks for evidence supporting a recommendation?
A successful demo does not answer these questions.
And that is where AI engineering begins.
In this series, we will build an AI-powered contract analysis system from the ground up. We will start with the simplest possible implementation, identify its limitations, and introduce more sophisticated techniques only when the problem requires them.
Along the way, we will explore LLM applications, Retrieval-Augmented Generation (RAG), AI agents, evaluation, and production architecture.
The goal is not to collect AI terminology.
It is to understand which problems each technique solves, why it works, and when it is worth the additional complexity.
1. Start With a Real Problem
Before choosing a model, framework, or architecture, we need to define what the system is supposed to accomplish.
Our initial use case is contract analysis.
A user uploads a contract and asks questions such as:
- What are the payment terms?
- Can either party terminate the agreement early?
- What penalties apply if we deliver late?
- Which clauses create unusual financial exposure?
- What evidence supports each finding?
At first glance, these all look like text-generation tasks.
However, they have different requirements.
| Requirement | What the system needs |
|---|---|
| Understand the question | Interpret the user's intent and scope |
| Access the contract | Read and process the actual document |
| Find relevant evidence | Locate the clauses that answer the question |
| Produce an answer | Explain the findings clearly |
| Support its conclusions | Reference the correct sections and passages |
| Handle uncertainty | Admit when the document does not provide enough evidence |
| Protect sensitive data | Enforce access control and data-handling policies |
| Demonstrate reliability | Pass repeatable tests on representative contracts |
Notice that only one of these requirements is directly about generating text.
The others concern information access, correctness, security, and system behavior.
This distinction matters because the model is only one component of the solution.
If the system cannot find the correct clause, a more eloquent model will not necessarily fix the problem. If the application gives the model incomplete information, the answer may still sound confident. If the application exposes a contract to the wrong user, answer quality becomes irrelevant.
We should therefore define success before selecting the architecture.
For our first version, the goal is:
Given a supported contract and a question, return an accurate answer grounded in the contract, with traceable evidence and an explicit indication when sufficient evidence cannot be found.
This becomes the foundation for every technical decision that follows.
2. What Happens When You Call an LLM?
Let's begin with the smallest possible AI interaction.
Conceptually, an application sends a prompt to a language model and receives generated text.
flowchart TD
A[Application] -->|Prompt| B[Language Model]
B -->|Generated Response| C[Application]In code, the interaction might look like this:
interface LLM {
generate(input: {
system: string;
user: string;
}): Promise<string>;
}
async function answerQuestion(
llm: LLM,
question: string,
): Promise<string> {
return llm.generate({
system: "You are a helpful contract analysis assistant.",
user: question,
});
}The LLM interface is deliberately provider-independent. A concrete implementation would connect to a model API or a locally hosted model.
This code is enough to demonstrate the basic interaction. It is not enough to implement contract analysis.
Why?
Because the application has not provided the contract.
The model has received a question about information it may not possess. It can explain general contract concepts, but it cannot reliably determine what a specific agreement says without access to that agreement.
We could include the entire contract in the prompt. For a short document, that may be perfectly reasonable.
async function analyzeContract(
llm: LLM,
contractText: string,
question: string,
): Promise<string> {
return llm.generate({
system: [
"You analyze contracts.",
"Use only the supplied contract as evidence.",
"If the evidence is insufficient, say so.",
].join("\n"),
user: [
"Contract:",
contractText,
"",
"Question:",
question,
].join("\n"),
});
}This is already a more useful application.
The model now has access to the source material and explicit instructions about how to answer.
For a short contract and a narrow set of questions, this approach may be sufficient.
But it introduces our first architectural constraint: the application must fit the relevant information into the model's usable context while preserving the evidence needed to answer correctly.
A model's context window is not the same thing as an unlimited, reliable document database. Even when a document fits, the model may overlook relevant passages, misinterpret relationships between sections, or produce unsupported conclusions.
We have now encountered our first important engineering decision:
Should we give the model the entire document, or should the application retrieve only the relevant information?
We should not answer that question with a technology preference. We should answer it based on the document size, retrieval requirements, accuracy expectations, latency, and cost.
3. From an LLM Call to an AI Application
A real AI application introduces additional components around the model.
For our contract analyzer, the basic architecture becomes:
flowchart TD
U[User] --> API[Application API]
API --> VAL_IN[Input Validation]
VAL_IN --> CTX[Prepare Contract and Question]
CTX --> PROMPT[Prompt Construction]
PROMPT --> LLM[LLM Provider]
LLM --> VAL_OUT[Output Validation]
VAL_OUT --> RES[Response to User]Each component has a different responsibility.
Input validation ensures that the request contains a valid question and a supported document.
Prompt construction organizes the task instructions, source material, and user question.
The model integration handles communication with the selected provider, including timeouts and provider errors.
Output validation checks whether the returned result conforms to the application's expected format.
These components are not necessarily separate services. At the beginning, they may simply be functions in one application.
That distinction is important.
Architecture is about separating responsibilities where separation improves understanding, correctness, or changeability. It is not about creating the maximum possible number of classes, packages, or microservices.
For example, suppose we want our contract analyzer to return structured findings rather than an unrestricted paragraph.
We could define a domain model:
interface ContractFinding {
title: string;
explanation: string;
severity: "low" | "medium" | "high";
evidence: string[];
}The model can be instructed to return this structure, ideally using the provider's structured-output or schema-constrained generation capabilities where available.
However, a TypeScript interface alone does not validate runtime data. We still need to validate the actual response before trusting it.
More importantly, a structurally valid answer is not necessarily a factually correct one.
This response may satisfy our interface:
{
"title": "Unlimited liability",
"explanation": "The supplier accepts unlimited liability.",
"severity": "high",
"evidence": [
"The supplier accepts unlimited liability for all claims."
]
}But what if the quoted sentence does not exist in the contract?
The response is syntactically valid and semantically plausible. It is still wrong.
This reveals an important distinction:
- Structural validation asks whether the output has the expected shape.
- Semantic evaluation asks whether the answer is correct and supported by evidence.
We need both.
4. The First Version: A Simple Contract Analyzer
Let's establish a baseline before introducing advanced retrieval or agent frameworks.
Assume that our application can extract readable text from a supported document format. We will use an LLM to analyze the supplied text and return a structured result.
For this initial implementation, we will deliberately keep the scope small:
- One contract at a time.
- One user question at a time.
- No external tools.
- No autonomous planning.
- No vector database.
- No agent loop.
Here is a simplified implementation:
interface ContractFinding {
title: string;
explanation: string;
severity: "low" | "medium" | "high";
evidence: string[];
}
interface ContractAnalysis {
summary: string;
findings: ContractFinding[];
limitations: string[];
}
interface StructuredLLM {
generateObject<T>(input: {
system: string;
user: string;
schema: unknown;
}): Promise<T>;
}
async function analyzeContract(
llm: StructuredLLM,
contractText: string,
question: string,
): Promise<ContractAnalysis> {
const result = await llm.generateObject<ContractAnalysis>({
system: [
"You are a contract analysis assistant.",
"Analyze only the supplied contract text.",
"Do not invent clauses or quotations.",
"Support findings with evidence from the source.",
"If evidence is insufficient, state the limitation.",
"Do not present your output as definitive legal advice.",
].join("\n"),
user: [
"Analyze the following contract.",
"",
"CONTRACT TEXT:",
contractText,
"",
"USER QUESTION:",
question,
].join("\n"),
schema: contractAnalysisSchema,
});
return validateContractAnalysis(result);
}The generateObject method and contractAnalysisSchema represent provider-specific structured generation and runtime validation interfaces that we would implement or connect to in a real application. They are intentionally abstracted here.
Even this simplified design needs a few safeguards before production use.
First, validateContractAnalysis must perform real runtime validation. It cannot simply return the object because the TypeScript generic claims that the result has the right type.
Second, the application should verify evidence against the source text or its extracted representation. Exact quotation checks can catch some fabricated evidence, although they cannot prove that an interpretation is correct.
Third, we need document size limits, request timeouts, error handling, and authorization checks around the application.
Finally, the system should preserve enough source information to let users inspect the clauses behind important findings.
We now have a useful starting point. It is easy to understand, relatively inexpensive to build, and simple to test.
But we have not yet solved the more difficult cases.
5. Where the Simple Approach Breaks
Imagine that our contract analyzer has been tested on ten short agreements. The results look good, so we begin accepting larger documents.
Then we encounter several problems.
5.1 The document does not fit comfortably into the request
A long contract may exceed the model's usable context budget once we account for instructions, the user's question, previous messages, and the expected response.
We could split the contract into chunks and analyze each chunk separately. That might work for some tasks, but it introduces new questions:
- How should we split the document?
- How do we preserve section headings and clause relationships?
- How do we determine which chunks are relevant to a question?
- What happens when an answer depends on two distant sections?
- How do we combine the results without losing important evidence?
Splitting text is easy.
Preserving the information needed to answer a question is much harder.
5.2 The relevant clause is difficult to find
Suppose the user asks:
Can the customer terminate the agreement without cause?
The answer might depend on a termination clause, an amendment, and a special provision in an appendix.
A basic implementation that supplies only the first few pages will miss important evidence.
Supplying the entire contract may work for some models and documents, but it can become expensive or unreliable as the workload grows.
The application needs a strategy for locating relevant information.
This is where retrieval becomes important.
5.3 The answer requires evidence from multiple sections
Consider a contract with these provisions:
- Section 4 defines the delivery deadline.
- Section 8 describes late-delivery penalties.
- Section 12 establishes exceptions to those penalties.
A question about the financial consequences of late delivery may require all three sections.
Finding one relevant paragraph is not necessarily enough. The system must retrieve sufficient evidence, preserve the relationships between clauses, and reason about their combined meaning.
5.4 The model produces a convincing but unsupported answer
Even when the correct text is available, a model can misread it or generate a claim that goes beyond the evidence.
For example, a contract may allow termination only after a material breach and a specified cure period.
The model might summarize this as an unrestricted termination right, omitting the conditions that matter most.
Adding more instructions may improve behavior, but prompts alone do not guarantee correctness.
We need ways to constrain the available evidence, verify outputs, and measure how often the system fails.
5.5 The application must work beyond the happy path
A real system must also handle:
- Scanned documents that require OCR.
- Tables, footnotes, and appendices.
- Malformed or password-protected files.
- Provider rate limits and outages.
- Duplicate requests and expensive retries.
- Unauthorized document access.
- Sensitive information in logs and traces.
These are not all problems that an LLM can solve by generating a better response.
They require application architecture, document-processing logic, operational controls, and testing.
The key lesson is not that our initial implementation was a mistake.
It was the right starting point because it exposed the limitations we actually need to solve.
6. The Layers of a Production AI System
We can now describe a more complete architecture without committing to a particular framework.
flowchart TD
USER[User Interface] --> API[Application API]
API --> AUTH[Authentication and Access Control]
AUTH --> ORCH[Task Orchestration]
ORCH --> DOC[Document Access]
ORCH --> MODEL[Model Integration]
DOC --> STORE[Document Store]
DOC -. Relevant evidence .-> MODEL
MODEL --> LLM[LLM Provider]
LLM --> VALIDATE[Output Validation]
VALIDATE --> RESPONSE[Evidence and Response]
RESPONSE --> USER
EVAL[Evaluation] -. Measures quality .-> ORCH
OBS[Observability] -. Records execution .-> ORCH
SEC[Security Controls] -. Enforces policies .-> API
COST[Cost and Latency Monitoring] -. Tracks usage .-> MODELThis diagram represents logical responsibilities, not a requirement to deploy each component as an independent service.
Let's examine the most important layers.
6.1 Document processing and storage
The application must turn uploaded files into information that can be searched and referenced.
Depending on the documents, this may involve:
- Extracting text from PDFs and Word documents.
- Applying OCR to scanned pages.
- Preserving section headings and page references.
- Handling tables and structured content.
- Storing the original file and extracted representation.
- Tracking document versions and processing status.
Document processing is often underestimated. If text extraction loses table relationships or omits footnotes, downstream retrieval and generation can fail even when the model itself is capable.
6.2 Retrieval
Retrieval identifies the portions of a document that are likely to contain the evidence needed for a question.
Possible techniques include keyword search, full-text search, vector search, hybrid retrieval, and reranking.
We do not need all of them immediately.
For a small, structured collection of short contracts, a conventional database query or full-text search may be sufficient. Vector search becomes useful when semantic similarity helps find relevant passages despite differences in wording.
The appropriate choice depends on the data and the questions we need to answer.
6.3 Model integration
The model integration layer manages communication with an LLM provider.
Its responsibilities may include:
- Selecting the model for a task.
- Constructing requests.
- Enforcing timeouts.
- Handling rate limits and provider errors.
- Validating structured outputs.
- Recording token usage and cost.
- Applying retry policies where safe.
It is also useful to separate application-level behavior from provider-specific APIs so that model changes do not force a complete rewrite of the business logic.
That does not mean every application needs a sophisticated multi-provider abstraction from day one. The abstraction should be proportionate to the likelihood and cost of changing providers.
6.4 Orchestration
Orchestration controls the sequence of operations needed to complete a task.
Our initial analyzer has a simple, predictable sequence:
- Validate the request.
- Load the authorized document.
- Prepare the relevant text.
- Call the model.
- Validate the response.
- Return the result.
A more advanced system may need conditional steps, repeated retrieval, tool calls, or human approval.
The important question is whether the execution path is fixed or requires the model to make decisions dynamically.
That distinction will become central when we discuss workflows and AI agents.
6.5 Evaluation and observability
Evaluation tells us whether the system produces acceptable results.
Observability helps us understand what happened when it does not.
For example, when the analyzer misses a termination clause, we need to investigate:
- Was the clause extracted correctly?
- Did retrieval find it?
- Did the prompt include it?
- Did the model interpret it correctly?
- Did output validation catch any issues?
- Did the final response preserve the relevant conditions?
Without visibility into these stages, debugging becomes guesswork.
A single end-to-end accuracy score cannot explain every failure. We need to inspect the individual components as well as the final outcome.
7. Why We Should Not Start With RAG or Agents
At this point, it is tempting to jump directly into a RAG framework or build an autonomous agent.
But advanced architecture is not automatically better architecture.
Let's compare several approaches for our contract analyzer.
| Approach | Best fit | Main limitation |
|---|---|---|
| Direct LLM call | General explanations and simple transformations | No inherent access to private source documents |
| Full-document prompting | Short documents that fit comfortably in context | Context limits, cost, and potentially missed evidence |
| RAG | Large or numerous documents requiring targeted retrieval | Retrieval can miss or misrank relevant evidence |
| Deterministic workflow | Tasks with known, repeatable steps | Less flexible when execution paths vary |
| AI agent | Tasks requiring dynamic tool selection and iterative decisions | Less predictable execution, added latency, cost, and risk |
These approaches are not mutually exclusive.
A RAG application still calls an LLM. An agent can use RAG as one of its tools. A deterministic workflow can contain model calls, and a production system may combine all three.
The important distinction is the problem each component solves.
RAG addresses information access. It helps provide relevant external information to a model at answer time.
An agent addresses dynamic execution. It allows a model-driven control loop to select tools or actions based on intermediate results.
Neither technique automatically guarantees correctness, security, or good evaluation results.
For example, our first version probably does not need an agent. An agent would add complexity if every request simply follows the same sequence of steps.
Likewise, a short contract may not need a vector database if its complete text can be processed reliably and economically.
We should introduce complexity when the simpler approach demonstrably fails to meet a requirement.
This gives us a practical rule:
Start with the simplest architecture that satisfies the requirements. Measure its limitations, then introduce the smallest change that addresses the actual failure.
8. How Do We Know the System Actually Works?
Before improving the architecture, we need a way to measure its behavior.
Otherwise, we risk building a more sophisticated system that only appears better in a few hand-picked examples.
For our contract analyzer, we can start with a small golden dataset: a collection of representative contracts, questions, expected evidence, and evaluation criteria.
An individual test case might look like this:
interface ContractTestCase {
id: string;
contractId: string;
question: string;
expectedEvidence: string[];
expectedOutcome:
| "answerable"
| "insufficient_evidence";
}A test case could ask whether a customer can terminate a contract without cause. Its expected evidence would identify the relevant clause or clauses, while its expected outcome would indicate whether the supplied document contains enough information to answer.
We should evaluate several dimensions independently.
| Dimension | Example evaluation question |
|---|---|
| Evidence retrieval | Did the system find the relevant clauses? |
| Answer correctness | Does the response accurately interpret the contract? |
| Groundedness | Are the claims supported by the supplied evidence? |
| Citation correctness | Do the citations point to the passages they claim to support? |
| Abstention | Does the system acknowledge insufficient evidence? |
| Operational behavior | Does it handle failures, timeouts, and malformed files appropriately? |
These dimensions help us identify the actual source of a failure.
For instance, if the expected clause never reaches the model, changing the generation prompt may not solve the underlying problem.
If the correct clause is present but the answer misinterprets it, we may need to improve the prompt, change the model, restructure the context, or apply domain-specific validation.
If the answer is correct but its citation points to the wrong page, we need to fix evidence tracking rather than celebrate the answer's apparent quality.
We should also evaluate operational concerns such as latency, cost, and failure rates separately from answer quality.
There is no single metric that captures the overall quality of a production AI system.
Finally, legal or contractual risk assessment needs appropriate human review. An automated evaluation suite can measure consistency against defined criteria, but it cannot by itself establish that the system is legally correct for every jurisdiction and situation.
Evaluation is not a final testing phase that we add after development.
It is part of the architecture from the beginning.
9. The Architecture We Will Build Toward
We now have a clear direction for the rest of this series.
Rather than introducing every technique at once, we will evolve the contract analyzer in stages.
flowchart TD
V1["Stage 1: Direct LLM Call"] --> V2["Stage 2: Document Processing"]
V2 --> V3["Stage 3: Retrieval and RAG"]
V3 --> V4["Stage 4: Evidence and Answer Evaluation"]
V4 --> V5["Stage 5: Workflows and Agents"]
V5 --> V6["Stage 6: Production Monitoring"]
V1 -. Establish baseline .-> EVAL["Shared Golden Dataset"]
V2 -. Test extraction quality .-> EVAL
V3 -. Measure retrieval quality .-> EVAL
V4 -. Measure answer quality .-> EVAL
V5 -. Measure task completion .-> EVAL
V6 -. Track production behavior .-> EVALThe stages are an investigative roadmap, not a mandatory sequence for every AI application. We will introduce each capability when the requirements justify it.
Stage 1: Establish the baseline
Build a simple application that accepts a contract and a question, calls an LLM, validates the response, and returns evidence-backed findings.
The objective is to understand the basic application flow and establish initial evaluation cases.
Stage 2: Introduce document processing
Improve text extraction, preserve section structure, handle document metadata, and establish reliable source references.
The goal is to make sure the information entering the AI pipeline is usable and traceable.
Stage 3: Introduce retrieval
As document size and collection size grow, investigate how to find relevant clauses efficiently.
We will examine document ingestion, chunking, embeddings, keyword search, vector search, hybrid retrieval, and reranking.
We will also investigate how retrieval failures affect final answers.
Stage 4: Improve evidence and answer quality
We will focus on citations, context construction, handling conflicting clauses, and recognizing insufficient evidence.
The objective is not merely to generate more convincing answers, but to make the relationship between source material and conclusions easier to inspect.
Stage 5: Introduce workflows and agents where justified
Some contract analysis tasks may require multiple dependent steps: locating provisions, comparing clauses, checking amendments, and generating a structured report.
We will determine which steps should remain deterministic and which decisions, if any, benefit from agent-driven execution.
We will also examine tool permissions, execution limits, retries, and failure recovery.
Stage 6: Build an evaluation and production strategy
Finally, we will create a repeatable evaluation pipeline and examine how to monitor quality, latency, cost, and reliability.
We will use the same underlying problem and test cases to compare successive implementations.
That last point matters. If we change the architecture, the dataset, the prompts, and the evaluation criteria simultaneously, it becomes difficult to tell which change actually improved the system.
Our objective is to make each architectural decision explainable and measurable.
Summary
An AI system is more than an LLM API call.
The model generates responses, but the application determines what information it receives, which operations it can perform, how its output is validated, and what happens when something fails.
Through our contract analysis example, we have identified several distinct engineering problems:
- Providing the model with the right information.
- Retrieving evidence from large documents.
- Producing answers that remain grounded in their sources.
- Validating outputs beyond their structure.
- Controlling execution, cost, and access.
- Measuring quality through repeatable evaluation.
These problems do not all require advanced AI techniques. Some can be solved with conventional application engineering, and others may benefit from RAG, workflows, or agents.
The challenge is knowing which is which.
That is the perspective we will use throughout this series: understand the problem first, choose the architecture second, and evaluate whether the solution actually works.
In the next article, we will examine a fundamental limitation that motivates many knowledge-based AI applications:
Why an LLM Cannot Reliably Answer Questions About Your Documents.
We will look at what a model knows, what it can access, why those are different things, and why simply writing a better prompt is not always enough.
- LLM applications
- AI system architecture
- RAG
- AI agents
- LLM evaluation
- Production AI systems
- contract analysis AI