Building Production-Ready RAG & AI Agent Systems with TypeScript, LangChain and LangGraph
What changes when a RAG or AI-agent prototype has to survive real users: retrieval quality, permissions, workflow state, evaluation, failure handling, latency, and cost.
On this page
Most RAG demos look convincing on a small set of clean documents. The interesting problems start later.
A user asks something vague. The useful answer is split across three documents. One of those documents is outdated. A tool call times out. The model returns valid-looking JSON with the wrong value. Then another user asks the same question in a completely different way and retrieval misses the section that mattered.
That is the point where an AI feature stops being mostly a prompting exercise and starts looking like the rest of software engineering.
Over time, I have found it more useful to think about RAG and agents as ordinary application systems with one unusual component: some decisions are probabilistic. Everything around that component still needs the same things I would expect from a normal production service — clear boundaries, permissions, validation, observability, tests, and sensible failure modes.
This is the approach I use when I think about building these systems with TypeScript, LangChain, LangGraph, and the rest of a typical web stack.
The LLM should not become the application
One mistake I try to avoid is pushing too much responsibility into the model.
Authentication should not live in a prompt. Authorization should not depend on whether the model believes somebody is an admin. Billing rules, ownership checks, database constraints, and destructive operations should remain normal application logic.
I usually treat the LLM as a component that can help with interpretation, generation, routing, or deciding which tool may be useful. The application still decides whether that tool is allowed to run.
For example, an agent may conclude that deleting a project is the correct next action. That does not mean the action should execute immediately.
async function deleteProjectTool(input: { actorId: string; projectId: string;}) { const membership = await membershipRepo.find( input.actorId, input.projectId, ); if (!membership || membership.role !== 'owner') { throw new Error('Forbidden'); } return projectRepo.delete(input.projectId);}The model can choose the tool. The server still enforces the permission boundary.
That separation sounds obvious, but it becomes easy to blur once an agent can call five or ten different tools and the orchestration layer starts growing.
The part that usually breaks first is retrieval
When a RAG answer is poor, the instinct is often to change the prompt or try a larger model. Sometimes that helps. Quite often the model never received the right evidence in the first place.
I debug these systems by separating retrieval from generation.
The first question is simple: did we retrieve the information required to answer the question?
If the answer is no, prompt changes are mostly a distraction. I look at document parsing, chunk boundaries, metadata, filters, the search query, the embedding model, and ranking.
Chunking in particular gets underestimated. Splitting every document into fixed blocks of a few hundred tokens is a reasonable baseline, but it can create strange fragments. A heading can end up in one chunk and its explanation in another. Tables get cut in half. A policy clause loses the exception written immediately below it.
For structured documents, I prefer chunks that follow the information itself: a heading with its section, an FAQ question with its answer, an API endpoint with its description, or a policy clause with the relevant exception.
I also keep useful metadata with the chunk instead of treating the vector store as a pile of anonymous text.
type DocumentChunk = { id: string; documentId: string; tenantId: string; source: string; title?: string; section?: string; content: string; updatedAt: string; permissions?: string[];};That metadata becomes important very quickly. It gives you source links, freshness checks, tenant isolation, access control, product filters, and a way to understand where an answer actually came from.
I rarely rely on vector search alone
Vector search is useful because users do not ask questions with the same words used in the documentation. It is much less impressive when the query contains an exact invoice number, an error code, a product identifier, or a person’s name.
For that reason, I generally prefer hybrid retrieval for larger knowledge bases: semantic search for meaning, keyword or full-text search for exact terms, then a ranking step over the combined candidates.
A simplified version can be as small as this:
const [semantic, keyword] = await Promise.all([ vectorSearch(query, { limit: 20 }), fullTextSearch(query, { limit: 20 }),]);const candidates = mergeAndDeduplicate(semantic, keyword);const ranked = await rerank(query, candidates);return ranked.slice(0, 8);The numbers are not important. I would tune those against real queries instead of copying a topK value from an example project.
Reranking is useful for the same reason. Retrieval can be generous; the final context should not be. Feeding twenty vaguely related passages into the model often makes the answer worse while also increasing latency and token cost.
The goal is to put the strongest evidence in front of the model, not the largest amount of evidence.
Query rewriting is helpful, but I keep it boring
Real users do not write search-engine queries. They write things like:
Why can’t this customer use the feature anymore?
That single sentence may depend on account state, subscription rules, the feature name, plan limits, and a recently changed policy.
A small query-rewrite or decomposition step can help turn that into better retrieval queries. I do not want that step to become an elaborate autonomous research agent unless the problem genuinely needs one. Most of the time a focused rewrite, a few targeted searches, and a good reranker are easier to operate.
This is a pattern I come back to a lot with AI systems: use the model where it improves the product, but do not create extra intelligence just because the framework makes it easy.
Agents are easier to reason about when the state is explicit
The word “agent” is used for a lot of different designs. For production work, I care less about whether something is technically an agent and more about whether I can explain what happens next when a step fails.
That is one reason I like graph-style orchestration with LangGraph.
Instead of one long loop that keeps asking the model what to do next, the workflow can expose its state directly:
type AgentState = { userId: string; tenantId: string; request: string; retrievedContext: string[]; selectedTool?: string; toolResult?: unknown; attempts: number; requiresApproval: boolean; completed: boolean;};A node can retrieve knowledge. Another can choose a tool. Another can validate a result or request human approval. The transitions are visible, which makes it much easier to test and debug.
I also put hard limits around loops. If an agent can keep planning forever, eventually one request will do exactly that.
const MAX_AGENT_STEPS = 6;if (state.attempts >= MAX_AGENT_STEPS) { return { ...state, completed: true, requiresApproval: true, };}Six is just an example. The important part is that there is a limit and a defined fallback.
For higher-risk actions I prefer an approval boundary as well. Preparing an email, refund, deployment, permission change, or content publication can be automated. Actually committing the action may still require a person to approve it.
That does not make an agent less useful. In many business workflows it makes the agent usable at all.
Structured output helps, but validation still belongs to the application
I use structured model output whenever downstream code needs to make a decision.
import { z } from 'zod';const AnswerSchema = z.object({ answer: z.string(), confidence: z.enum(['high', 'medium', 'low']), sources: z.array(z.string()), requiresHumanReview: z.boolean(),});The important part is what happens next:
const parsed = AnswerSchema.safeParse(modelOutput);if (!parsed.success) { throw new Error('Invalid AI response schema');}Structured output is not the same thing as correct output. A model can return perfectly valid JSON that contains a bad decision. The schema protects the shape; application rules and evaluation have to protect the behavior.
I find this distinction especially important around tool calls. Parsing free-form prose to decide whether money should move, data should be deleted, or a customer should be granted access is unnecessary risk.
Evaluation has to be split into smaller questions
“Did the AI give a good answer?” is too broad to be useful when something breaks.
For a RAG system, I want to know at least two things separately:
Did retrieval find the evidence? If not, I look at chunking, filters, search, query rewriting, and ranking.
Did the model use the evidence correctly? If retrieval was good but the answer was still wrong, then prompt instructions, context formatting, model behavior, or output validation are more likely to be the problem.
That separation saves a lot of random tuning.
I also prefer evaluation cases taken from real application behavior rather than synthetic questions that happen to match the documentation perfectly.
type EvaluationCase = { question: string; expectedFacts: string[]; expectedSources?: string[]; forbiddenClaims?: string[];};A small, representative dataset is already useful. It gives you something to run after changing a prompt, switching an embedding model, adjusting chunk sizes, adding a reranker, or moving to another model provider.
Without that baseline, it is easy to improve five examples manually while quietly making another part of the system worse.
Observability matters more once one request becomes many requests
A normal API call might hit a database and another service. An agent request can do much more: classify intent, rewrite a query, run multiple searches, rerank results, call an LLM, execute a tool, then call the LLM again.
If I can only see the final response, debugging that request is painful.
For each run, I want enough information to reconstruct what happened: the model and prompt version, retrieval query, documents returned, ranking scores, tool calls, latency, token usage, validation errors, retries, and the final result.
This is where tooling such as LangSmith is useful, although the same idea works with custom tracing and OpenTelemetry-style instrumentation.
The specific product is less important than having a trace that lets me answer: where did this request go wrong?
Latency and cost are architectural concerns
It is easy to build an AI endpoint that works well and quietly takes eight seconds because one user request triggers four model calls, two searches, a reranker, and an external API.
I try to set a rough latency budget early and decide which parts actually require a strong model.
Classification and simple routing can often use a smaller model. Independent retrieval calls can run concurrently. Stable embeddings can be cached. Long conversation history can be summarized. Some branches of the workflow can be deterministic and skip the LLM completely.
That last point is worth emphasizing. Not every step becomes better when a model is involved.
If a rule can be expressed reliably in TypeScript, I usually prefer the TypeScript.
Multi-tenant RAG needs permission checks before the prompt is built
For SaaS applications, access control has to happen during retrieval. Filtering after generation is too late because the private content has already reached the model context.
A retrieval call should be scoped to the user and tenant just like a database query would be.
const results = await vectorStore.search({ queryEmbedding, filter: { tenantId: currentUser.tenantId, visibility: ['public', currentUser.role], }, limit: 20,});I apply the same rule to retrieved documents that I apply to tool inputs: treat them as untrusted data.
A document can contain a prompt injection just as easily as a user message can. Text that says “ignore your previous instructions” must not be able to bypass permissions or cause a privileged tool to run.
The real security boundary is the application, not the prompt.
What I want to know before I ship
By the time a RAG or agent feature is ready for production, I am less interested in whether the demo looks impressive and more interested in a few practical questions.
Can I explain why a particular source was retrieved? Can the system say that it does not have enough evidence? Are tool permissions enforced outside the model? Is there a hard stop for loops? Can I inspect a failed run? Do we have a few evaluation cases that would catch a regression? What happens if the model provider or external API is slow? What is the most expensive path through the workflow?
If those answers are clear, the system is usually in a much healthier place.
RAG and agents are useful because they let applications work with messy language, changing knowledge, and tasks that are difficult to express as fixed rules. But the surrounding system should still be boring in the best possible way: understandable, observable, permission-aware, and predictable when something goes wrong.
That is the part of AI engineering I find most important — not making the model look more intelligent, but making the whole product dependable.
KEEP READING
Related engineering notes
A Failover Route Is Not a Recovery Path: Proving Independence in AI Infrastructure
Two LLM providers can share the same failure domain. Build an evidence-backed recovery graph that checks cloud, networking, identity, control-plane and capacity dependencies before admitting fallback routes, then test correlated outages without weakening safety.
Read articleAn Eval Platform Sunset Can Erase Your Release Evidence: Build an Evidence-Escrow Migration Gate
When a hosted LLM evaluation platform retires, switching runners is not enough. Preserve the historical evidence, reconstruct grader semantics, validate scoring parity, and enforce a fail-closed release gate that survives the service shutdown.
Read articleWhen the Package Runs Before Your App: Quarantining AI Framework Releases
The 2026 agent-framework PyPI compromise exposed a blind spot in AI build pipelines: Python startup hooks execute before application imports. Design an artifact-quarantine gate, inspect wheels without installing them, separate credentials, and recover from suspected exposure.
Read article