<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Sheik Nomaan, Ph.D. on Medium]]></title>
        <description><![CDATA[Stories by Sheik Nomaan, Ph.D. on Medium]]></description>
        <link>https://medium.com/@sumon0604030?source=rss-84c9ed3eae75------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*xzg4P-1k9y1-d904cwZjgg.jpeg</url>
            <title>Stories by Sheik Nomaan, Ph.D. on Medium</title>
            <link>https://medium.com/@sumon0604030?source=rss-84c9ed3eae75------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 17:41:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sumon0604030/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[AI Agent Evaluation: A Practical Guide with a Working Application]]></title>
            <link>https://pub.towardsai.net/ai-agent-evaluation-a-practical-guide-with-a-working-application-093e00a22ec2?source=rss-84c9ed3eae75------2</link>
            <guid isPermaLink="false">https://medium.com/p/093e00a22ec2</guid>
            <category><![CDATA[ai-evaluation]]></category>
            <dc:creator><![CDATA[Sheik Nomaan, Ph.D.]]></dc:creator>
            <pubDate>Sat, 03 Oct 2026 22:01:01 GMT</pubDate>
            <atom:updated>2026-10-03T23:06:10.562Z</atom:updated>
            <content:encoded><![CDATA[<h4>An end-to-end guide to deterministic checks, retrieval metrics, human review, LLM judges, and regression testing, with practical examples from a local multi-agent RAG application.</h4><p>The reliability of an AI agent depends on several connected processes, including the selection of tools, retrieval of relevant information, interpretation of evidence, and preparation of the final response. A change intended to improve one process may also affect the others. For a research assistant, requiring a source and page number may increase the frequency of citations without improving the support for the answer. The agent may cite a real passage that does not support its claim, omit a required verification step, or decline a question that the available evidence could answer. Evaluation therefore needs to establish both whether the intended behavior improved and whether the change introduced failures elsewhere in the application.</p><p>To examine these issues, a local research assistant was used to evaluate how changes to citation handling affected the application’s overall behavior. The assistant answers questions about research papers by retrieving relevant passages, checking claims, and preparing a response supported by references. The evaluation considered whether the assistant found the required evidence, followed the intended workflow, and produced answers that the evidence supported. Code-based checks, human review, and an LLM acting as an evaluator were used to assess different aspects of performance. Through this working example, the article explains how these methods can be combined to identify improvements, detect unintended failures, and support decisions about whether a change is ready for use.</p><h3>The research assistant and evaluation setting</h3><p>The application answers questions about three papers: <a href="https://arxiv.org/abs/1706.03762"><em>Attention Is All You Need</em></a>, <a href="https://arxiv.org/abs/1810.04805">BERT</a>, and <a href="https://arxiv.org/abs/2407.21783">the Llama 3 report</a>. Requests range from a simple fact, such as the number of attention heads in the Transformer base model, to comparisons across papers. The Coordinator receives the question, delegates work to specialists, and prepares the final answer. The Retriever searches ChromaDB directly, without making an LLM call. The Fact Checker receives a proposed claim, retrieves evidence separately, and calls the model to assess that claim.</p><figure><img alt="Application workflow and offline evaluation" src="https://cdn-images-1.medium.com/proxy/1*5-ULibqDguQXJTvuWW8VNw.png" /><figcaption>The research assistant and its offline evaluation. Both specialists return their results to the Coordinator. The Coordinator, Fact Checker, and offline judge use the same NIM-served model. Diagram by the author.</figcaption></figure><p>The papers are split within each PDF page using recursive character splitting, with a target size of 1,000 characters and 200 characters of overlap. The splitter tries to respect natural text boundaries, and each passage retains its source and PDF page number in ChromaDB. Llama 3.1 8B Instruct handles model calls through a local NVIDIA NIM container on an RTX 3090. DeepAgents and LangGraph organize the workflow, while Streamlit provides the interface.</p><p>For a supported technical question, the intended sequence is retrieval, claim checking, and answer preparation. A greeting should bypass the specialists, while an unsupported request should receive an explanation of the collection’s limits. These different paths provide observable requirements against which the application can be evaluated. Although the sequence is specific to the research assistant, the evaluation approach can be applied to other agent frameworks by examining the actions taken, the evidence available at each step, and the response delivered to the user.</p><p>The citation experiment compared three versions of the same assistant. In <strong>A</strong>, the original version used as the baseline, the model writes citations within its answer. In <strong>B</strong>, the model links claims to passage identifiers, which are stable labels for retrieved excerpts; code then converts those labels into source and page references. <strong>C</strong> adds a check of the references and allows one attempt to repair an invalid response before withholding the answer. These changes provide a concrete evaluation question: does greater control over citations improve the response while preserving retrieval, verification, and the ability to answer supported questions? The methods below examine those requirements before the three versions are compared.</p><h3>Defining expected behavior and test cases</h3><p>Agent evaluation begins with a description of the expected behavior under a defined set of conditions. For the question “How many attention heads does the Transformer base model use?”, the expected fact is eight. The research assistant is also required to retrieve supporting evidence, check a proposed claim, and cite the source. Together, these requirements form a <strong>behavior contract</strong>, which specifies what the application must do, what it may do, and what it should avoid. The contract extends beyond factual questions. A greeting requires a direct reply, a question about an unsupported paper requires an explanation of scope, and a follow-up may require information from an earlier turn. A request for BERT’s exact training electricity bill should receive an appropriate refusal because the presence of hardware information does not establish that cost.</p><p>These expectations are recorded with the input and starting conditions so that a failure can be interpreted against the intended task. For the attention-head question, a compact test case might contain the following fields:</p><ul><li><strong>Question:</strong> How many attention heads does the Transformer base model use?</li><li><strong>Starting state:</strong> A new conversation with no previous messages</li><li><strong>Required fact:</strong> Eight attention heads</li><li><strong>Reference evidence:</strong> The supporting passage on PDF page 5 of the Transformer paper</li><li><strong>Workflow:</strong> Retrieve first, call the Fact Checker once, then answer</li><li><strong>Citation:</strong> A reference that supports the eight-head claim</li></ul><p>Recording the evidence, workflow, and starting state makes it possible to distinguish failures that would be obscured by a question-and-answer pair alone. An answer could state eight but cite BERT, identify the correct paper but omit verification, or succeed because evidence remained from an earlier conversation. Reference labels also require a review status, since expectations drafted with AI assistance remain provisional until the intended human review has occurred. The same requirements apply when the proposed change concerns only citations or wording; the scope of the change does not remove the need to evaluate other required behaviors.</p><p>The application test set contains 60 cases covering single-paper questions, comparisons, unavailable information, casual messages, follow-ups, and claim verification. Fifty-two cases exercise the full agent, while eight test the Fact Checker separately. Coverage comes from the behaviors represented, rather than the count alone. Repeating many easy factual questions would provide little evidence about refusal behavior, cross-paper comparisons, or conversation context.</p><p>The study also uses a separate collection of deliberately constructed answers to evaluate the LLM judge. Those examples include known errors so that the judge’s ability to recognize a defect can be checked against human ratings. The application test set therefore evaluates the assistant, while the constructed examples evaluate the evaluator. Answers saved from running the assistant form a third kind of record: they are observed outputs of the experiments, rather than additional test questions.</p><h3>Development and holdout sets</h3><p>A prompt revised repeatedly against the attention-head question may eventually produce the expected answer. That result demonstrates improvement on a known case, but provides limited evidence about performance on other questions. Separating development from evaluation helps address this limitation. A <strong>development set</strong> contains the cases used during inspection and revision, while a <strong>holdout set</strong> reserves other cases for assessing the chosen design after the prompts and grading rules have been fixed. The distinction is relevant to prompt changes as well as code changes because both can become tailored to the examples used during development.</p><p>The 60 application cases were divided into 40 development cases and 20 holdout cases. Related paraphrases and conversation turns remained in the same set to reduce overlap between the conditions used for revision and those used for evaluation. Once a holdout failure informs a further revision, the affected example becomes part of development, and a later independent assessment requires fresh held-out cases. Maintaining that separation is necessary when interpreting whether an observed improvement extends beyond the questions used to produce it.</p><p>The final study was not an entirely untouched holdout evaluation because some holdout cases had already run during an earlier diagnostic experiment. A bug identified through a development case was corrected, and the final experiment restarted with fresh conversations, excluding the earlier results. That restart removed previous conversation state, but could not undo the earlier exposure of the cases. The study record preserves the full sequence so that the limitation remains visible when interpreting the results.</p><h3>Deterministic checks and semantic evaluation</h3><p>Several requirements can be assessed directly from the execution record. Code can determine whether retrieval occurred, whether the Fact Checker followed retrieval, and whether a cited passage appeared in the evidence supplied to the agent. These are <strong>deterministic checks</strong>, meaning that a fixed rule applied to the same saved input produces the same result. The evaluation harness, which runs the cases and saves their outputs, applies these checks to recorded tool calls and evidence. The execution record is necessary because a statement in the final answer that a fact was verified does not establish that verification occurred.</p><p>The limitation of a structural check becomes apparent when an answer states “64 attention heads” while citing the correct page. The passage and page exist, and the required tools may have run, although the paper specifies eight heads. <strong>Semantic evaluation</strong> examines the meaning of the answer in relation to the evidence. A simple numerical requirement may still be checked by extracting and comparing the value, whereas a broader response may paraphrase several passages or omit a qualification that changes the conclusion. Such cases require interpretation by a human reviewer or a calibrated LLM evaluator. Structural and semantic results therefore need to remain distinguishable: reference presence establishes that a reference was supplied, while answer quality depends on whether the referenced evidence supports the claim.</p><h3>Evaluation of retrieval performance</h3><p>Retrieval evaluation examines whether the information supplied to the agent is sufficient for the requested answer. A comparison of positional encoding in the original Transformer and Llama 3 papers, for example, requires evidence from both sources. If a search returns only the Transformer paper, <strong>source recall</strong> is one of two expected sources, or 50%. Returning five passages from that paper does not improve source recall because the second source remains absent. Finding both papers raises the score to 100%, although the retrieved passages may still omit the sections needed for the comparison.</p><p>More detailed checks are therefore needed to interpret evidence coverage. <strong>Reference-page recall</strong> measures whether known supporting pages were retrieved, with the qualification that useful evidence may also appear on pages outside the reference list. <strong>Passage relevance</strong> examines whether each returned excerpt contributes to answering the question. For example, a passage about attention may be topically related but provide no evidence about the number of attention heads. The distinction between source coverage and passage relevance is necessary when selecting metrics, since a retrieval method can perform well on the former while supplying insufficient evidence for the answer.</p><p>Relevance judgments support several metrics. <strong>Precision</strong> measures the useful share of returned passages: in an illustrative set of five results with two relevant passages, precision is 2/5, or 40%. <strong>Reciprocal rank</strong> measures where the first useful passage appears; a relevant result in second place receives 1/2. Averaging that score across questions gives mean reciprocal rank, or MRR. These calculations require appropriate relevance labels. Unreviewed passages should remain unjudged, and a report should define whether its cutoff counts results from one search or merged results from several searches.</p><p>The retrieval experiment compared a single vector search, which returns passages similar to the question, with the application’s targeted search procedure. For a question naming multiple papers, the targeted procedure creates a query for each named paper, combines the results, and removes duplicate passages. Each query can return five passages, so the combined result may contain more than five. The paper names guide the query wording rather than restricting the search to a particular document.</p><p>Across 12 cross-paper cases, the single search achieved 62.5% mean expected-source recall, while targeted searches reached 95.8%. The targeted method also returned an average of 9.4 passages instead of five. The higher recall may therefore reflect both the different queries and the larger number of returned passages. Comparing the methods while allowing each to return the same number of passages would help distinguish those effects. Passage relevance has not been reviewed across the full collection, so the precision calculation above illustrates the metric rather than reporting measured project-wide performance.</p><h3>Evaluation of tool use and conversation context</h3><p>Workflow evaluation uses the tool trace, the saved record of tool calls, to examine call order, arguments, results, and errors. In the research assistant, a supported technical request requires retrieval before the Fact Checker. The checker must receive a statement to assess, such as “The Transformer base model uses eight attention heads,” rather than a general request to find information. A greeting should bypass both specialists. These requirements describe the intended behavior of the application rather than a universal sequence for agents. A coding agent, for example, may allow several valid investigation paths while requiring tests before completion. Evaluation rules consequently need to reflect the application’s contract without rejecting alternative paths that satisfy the same requirements.</p><p>Conversation cases extend the evaluation to behavior that depends on previous turns. After “How many parameters does BERT Base have?”, the follow-up “And the larger version?” refers to BERT Large. Evaluating the follow-up in isolation changes the task and removes the context needed to interpret the request. The application’s scope guard checks the latest message for paper-related terms, allowing a follow-up to lose specialist access even when the earlier message has been stored correctly. The failure arises from the use of context during routing. Each conversation case therefore preserves its session across turns, while separate cases begin with empty memory. Examining these traces can reveal whether a citation-focused change also affects follow-ups, verification, or repeated tool use.</p><h3>Human evaluation and the answer-quality rubric</h3><p>Human evaluation examines several dimensions of answer quality that may not agree for the same response. An answer stating “BERT Base has 110 million parameters” is factually correct; however, the answer is not supported by the available evidence if the agent received only a passage about masking policy. <strong>Correctness</strong> and <strong>grounding</strong> therefore require separate judgments. <strong>Completeness</strong> concerns coverage of the request, <strong>citation support</strong> concerns the references attached to claims, and <strong>appropriate abstention</strong> concerns the decision to answer or decline. A refusal may be justified when the collection lacks the requested fact but unjustified when the necessary evidence is available. Separating these dimensions makes the reason for a low score more informative than a single overall judgment.</p><p>Reviewers need both <strong>reference evidence</strong>, which establishes what a good answer should contain, and <strong>available evidence</strong>, which records what the agent actually received. In the citation experiments, available evidence means passages returned to the Coordinator by the Retriever, including retained passages from earlier turns. The Fact Checker’s private retrieval is recorded separately. Its generated verdict is not treated as an independent source document.</p><p>The rubric uses 2 for a pass, 1 for partial credit, and 0 for failure, with definitions specific to each dimension. For completeness, the scores correspond to covering all required facts, some, or none of the required answer. A central false claim fails correctness regardless of the fluency of the surrounding explanation. Citation support receives full credit when references support the substantive claims, partial credit for mixed support, and failure when references are absent or unrelated. An honest refusal without factual claims or misleading references can receive a not-applicable citation score. These definitions provide a common basis for assessment while preserving differences among factual errors, missing information, and unsupported claims.</p><p>The reviewer reads the question, unchanged answer, and evidence together, then records a reason for the judgment. One reviewed answer claimed that BERT uses only token embeddings. Completeness received partial credit for naming one component, while correctness failed because “only” excluded segment and position embeddings. Another answer used an unrelated passage ID alongside a supporting page number. The partial citation score becomes understandable only when the explanation records that conflict.</p><p>The separate collection used to evaluate the judge contains 30 constructed answers for individual scoring and nine answer pairs for preference comparisons. The individual answers include correct responses and known defects, such as false facts, missing citations, and unrelated references. Human ratings establish the expected assessment of those examples before the judge’s results are interpreted. For the pairs, the reviewer identifies which answer is better, or whether the answers are equivalent under the stated criteria.</p><p>When several reviewers are available, independent judgments on a shared sample can reveal unclear instructions before disagreements are discussed. The completed review in this study involved one human confirming visible AI-assisted draft scores, preferences, and reasons. The review therefore represents human assessment with disclosed assistance; it does not provide blinded independent labels or a measure of agreement among human reviewers. Human review of the separate collection of 423 saved answers from the agent experiments remains pending. Reviewing the constructed examples helps assess the judge, but does not establish the overall quality of the assistant’s actual responses.</p><h3>LLM judging and calibration against human ratings</h3><p>An <strong>LLM judge</strong> applies a rubric to a saved answer. The grading input contains the question, candidate response, required facts, reference evidence, and evidence available to the agent. The prompt defines the scores and asks for reasons, while structured JSON allows code to reject missing fields, invalid score types, and unknown evidence IDs. Answers and source passages are treated as data, so instructions embedded inside them should not override the grading rules.</p><p>The offline judge has a different role from the application’s Fact Checker. The checker contributes to producing an answer; the judge grades the saved response afterward. Both used the same local Llama 3.1 8B model as the Coordinator, making the experiment feasible on one workstation while allowing shared misunderstandings. The 30 constructed answers provide a way to examine whether the judge recognizes known errors. Comparing its scores with the human ratings is <strong>calibration</strong>: establishing where the automated assessment agrees with the reviewed standard and where it does not.</p><p>The judge-calibration collection has its own development and holdout split, separate from the 60 application cases. Each constructed answer was graded three times. Twelve answers belonged to the calibration holdout set, producing 36 ratings per dimension. Six citation ratings were not applicable, leaving 30 for that comparison. Agreement with the completed human review was:</p><ul><li><strong>Correctness:</strong> 33 / 36 (91.7%)</li><li><strong>Grounding:</strong> 33 / 36 (91.7%)</li><li><strong>Completeness:</strong> 33 / 36 (91.7%)</li><li><strong>Citation support:</strong> 12 / 30 (40.0%)</li></ul><p>The scores summarize repeated judgments of 12 examples, not 36 independent examples. Agreement was much lower for citation support than for the other reported dimensions. One held-out answer illustrates the reason: the answer correctly described the Transformer’s sine and cosine encodings but supplied no citation. The judge granted full citation credit in all three trials because it could see supporting evidence in its own grading input. It treated that evidence as though the candidate answer had cited it.</p><p>Across 21 holdout ratings expected to fail citation support, the judge awarded a full pass to 15. Such errors are <strong>false acceptances</strong>, meaning that an unacceptable result receives approval. <strong>False rejection</strong> occurs when an acceptable result is rejected. The direction of disagreement matters because a judge that repeatedly approves unsupported citations could allow the very failures the evaluation is intended to detect. An overall agreement rate alone does not show that risk.</p><p>Human review also clarified how to assess a refusal carrying an unrelated citation. Declining the request was appropriate, but attaching a misleading reference still required a citation judgment; that example is included in the 30 applicable citation ratings. The completed human ratings were saved separately from the earlier provisional labels so that the change in interpretation remains traceable. Calibration provided limited evidence about borderline answers because the reviewed collection contained only two partial-credit judgments.</p><p>A separate disagreement concerned the definition of abstention. The human rubric evaluates whether the agent should answer or decline, while assessing factual errors under correctness. The tested judge prompt also penalizes invented facts under abstention. An incorrect answer to an answerable question can consequently receive different abstention scores even when both evaluators recognize the factual error. Abstention agreement is excluded from the reported comparison until the definitions are aligned in a new rubric version. The example shows why calibration must examine the grading instructions as well as the judge’s scores.</p><h3>Pairwise evaluation, bias, and repeated grading</h3><p>Calibration asks whether the judge applies the intended standard. Additional tests examine whether its decision changes for reasons unrelated to answer quality, such as display order or unnecessary length, and whether repeated grading produces consistent results. <strong>Pairwise evaluation</strong> provides one way to investigate these questions: the judge compares two answers under a stated preference rule and selects either answer or a tie. Presenting the same pair in both orders helps reveal whether the judge favors whichever answer appears first or second.</p><p>The judge evaluated the nine human-reviewed pairs three times in each display order, producing 54 calls. A response was usable only if it passed the required output checks, including the expected fields and allowed values. Of the 54 outputs, 31 passed and all agreed with the human preference; 23 were invalid and could not be used as preference judgments. For 13 repeated comparisons, usable outputs were available in both orders, and none reversed preference. Those results describe agreement within the valid subset, while the high number of unusable outputs limits confidence in the judge’s practical reliability.</p><p>Other tests examine whether the judge rewards unnecessary length or follows grading instructions embedded inside a candidate answer. Research on <a href="https://arxiv.org/abs/2306.05685">LLM-as-judge evaluation</a> discusses position, verbosity, and self-enhancement biases. The study’s verbosity and instruction-injection tests each produced six invalid outputs. The responses therefore demonstrate an output-reliability problem, but do not establish whether the judge resisted either influence. A test that produces no usable judgment leaves the intended behavior unresolved.</p><p>Repeated grading examines consistency independently of agreement with human ratings. All 30 constructed answers received the same set of dimension scores across three trials, including answers the judge scored incorrectly. Consistency therefore did not establish accuracy. The generation setting of temperature zero reduces sampling variation, but should not be treated as a guarantee of identical future judgments. Taken together, the calibration and reliability tests support using the judge to assist inspection, while its citation scores remain unsuitable for automatically approving a change to the agent.</p><h3>Paired experiments and agent regression testing</h3><p>A <strong>regression</strong> occurs when a change damages behavior that previously met the application’s requirements. The citation experiment combines the preceding checks to compare A, with model-written citations; B, with references rendered from passage identifiers; and C, with added validation and one repair attempt. Here, a <strong>paired experiment</strong> means evaluating each version on the same test cases and comparing the outcomes case by case. This differs from pairwise judging, which asks an evaluator to choose between two answers. The paired experiment includes tool behavior, answer properties, errors, and cost, rather than relying on a preference judgment alone.</p><p>Each version used the same retrieval settings, scope rules, model, and generation settings. Cases ran three times per version, and repeated trials from the same case remained grouped when estimating uncertainty. Of the 20 application holdout cases, 17 test the full agent and three test the Fact Checker separately. The 17 agent cases include one two-turn conversation, giving 18 turns per run and 54 technical turns across the three repetitions. Of those, 39 concern questions the collection can answer. Citation presence was assessed on those 39 turns so that appropriate refusals to unavailable requests were not penalized for lacking references.</p><figure><img alt="Citation presence, routing, latency, and resource use across the three agent versions" src="https://cdn-images-1.medium.com/proxy/1*ZkJRHfJNImxqYYVpZ1ITuQ.png" /><figcaption>Holdout results for the three agent versions. Citation presence uses 39 answerable turns; other technical measurements use 54 turns. Figure by the author.</figcaption></figure><p>Recognized citations appeared in 12 of 39 answerable turns for A, 32 for B, and 38 for C. Mean response time across all 54 technical turns increased from 6.36 seconds to 7.21 and 7.29 seconds, respectively. The results demonstrate that stronger control over references increased citation presence at an additional time cost. However, the citation count alone cannot establish whether the evidence supported the answer. Examination of the saved responses was therefore necessary to determine whether the structural improvement corresponded to a semantic improvement.</p><p>In the first trial comparing positional encoding, A and B both expanded RoPE incorrectly as “Reformer-style Positional Embeddings.” RoPE means Rotary Position Embedding, as defined in the <a href="https://arxiv.org/abs/2104.09864">RoFormer paper</a>. B attached a valid passage ID from PDF page 7 of the Llama 3 report. The cited row identifies “RoPE (θ = 500,000),” supporting the use of RoPE and the parameter value but supplying no expansion of the acronym. The reference check passed because the identifier belonged to the available evidence set. Membership alone could not establish the meaning of the claim.</p><p>Version C withheld its answer after a repair attempt failed structural validation. The block establishes failure to satisfy the reference rules, but does not demonstrate that the validator identified the incorrect expansion. The offline judge nevertheless granted full credit on every dimension to all three responses, including C’s message, “Unable to produce an answer with valid evidence references.” The grading explanation credited facts from the reference material as though they appeared in the candidate answer. Comparison of the response, cited passage, and grading reason thus identified separate failures in the agent and the evaluator, neither of which was apparent from the citation-presence score.</p><figure><img alt="Saved answers, structural checks, and judge ratings for the position-encoding question" src="https://cdn-images-1.medium.com/proxy/1*qaieraSqHc-Rg6qUAC-MJQ.png" /><figcaption>One saved comparison connects the answer, available references, workflow checks, and judge output. The displayed judge scores are observed errors, not endorsed grades. Figure by the author.</figcaption></figure><p>Across development and holdout, C attempted 25 repairs and withheld 12 answers. Some affected cases already had poor baseline answers, so withholding all 12 cannot be classified as new losses in answer quality. Identifying a regression requires comparison with the corresponding baseline result: whether the changed version damaged behavior that previously worked. The release decision must then consider those case-level failures alongside citation presence, response time, and the remaining uncertainty about semantic quality.</p><h3>Latency, resource use, and release criteria</h3><p>An improvement in answer quality may justify additional response time or resource use, depending on the requirements of the application. Assessing that tradeoff requires measurements of all serving calls, including the Fact Checker’s internal call and any repair attempts, together with input and output tokens, elapsed time, and errors. Missing usage data must remain unknown rather than being recorded as zero. Greetings also need to be separated from complete research workflows, since combining fast direct replies with technical tasks can understate the time required for a full retrieval-and-checking sequence.</p><p>Offline evaluation has a separate cost. Calibration used 144 model calls, while grading 423 saved agent answers required another 423 calls, more than a million input tokens, and 31.76 minutes of cumulative model-call time. Forty-six grading responses failed validation. Those calls did not contribute to the user’s wait for an answer, but they affect the practicality of repeating the evaluation. On a local workstation, token counts describe workload; a monetary estimate also needs assumptions or measurements for hardware, electricity, and utilization.</p><p>Release criteria provide a basis for interpreting the tradeoff and should be defined before the final comparison is inspected. The project rules block new critical failures such as invented references, broken routing, tool loops, or execution errors, while latency increases above 20% and token increases above 25% trigger review. These thresholds reflect choices for the research assistant rather than general standards for agent deployment. Code checks contribute evidence to the release decision, but semantic review remains necessary. In particular, the completed human calibration review establishes judgments for the constructed examples and does not substitute for reviewing the separate collection of agent answers.</p><p>Under the project rules, neither modified version was selected to replace the baseline. B introduced a development routing failure and referenced passages outside the Coordinator’s supplied evidence in two other trials. C also introduced a routing failure and withheld answers in cases that triggered the release-blocking rule. Although B had no new failures under the holdout code checks, the known development failures still prevented its acceptance. Retaining A as the comparison baseline did not establish that A was reliable; the decision indicated that the proposed changes had not yet met the requirements for replacement.</p><h3>Evaluation after release</h3><p>All measured results in this study concern <strong>offline evaluation</strong>, where saved or controlled test cases are assessed before a release decision. After deployment, <strong>online monitoring</strong> would examine real requests through representative execution records, errors, latency, unexpected refusals, and human feedback. Investigated failures can become development cases and later regression tests. The connection between monitoring and testing allows the evaluation set to reflect conditions that were not represented in the original experiments.</p><p>Product outcomes such as acceptance, completion, abandonment, adoption, and time saved provide further evidence about practical value, but each requires a clear definition. A user leaving the chat, for example, can indicate either that the task is complete or that the answer was unhelpful. These outcomes were not measured in the local study and should not be inferred from its offline scores. <a href="https://www.anthropic.com/engineering/demystifying-evals-for-ai-agents">Anthropic’s agent-evaluation guide</a> discusses the relationship between controlled evaluation and evidence from real operating conditions.</p><h3>Reproducibility and implications for application evaluation</h3><p>Interpretation of an evaluation result depends on the ability to inspect the observations underlying the reported score. The study preserves exact answers, retrieved passages, tool calls, grades, and reasons alongside configuration snapshots. Each result can therefore be traced to its case, repeated trial, agent version, and evaluation record. Later human judgments remain separate from the original labels so that changes in interpretation can be distinguished from changes in agent behavior. Preserving those records also allows an evaluator failure to be investigated without repeating the original agent run.</p><p>The <a href="https://github.com/smnomaan/nvidia_nim/tree/feat/agent-evaluation/examples/agent-evaluation">companion materials on GitHub</a> provide three sample cases, the human-review rubric, the tested judge prompt, and the saved A/B/C responses for the position-encoding example. From the repository root, run node examples/agent-evaluation/check-example.cjs. The example checks tool order and citation identifiers using Node.js, without a GPU, model server, or API key. Its README explains why a structural pass does not establish semantic support. The package demonstrates saved-output evaluation rather than reproducing the complete study, and its frozen rubric and prompt retain the limitations discussed above.</p><p>The results of this study demonstrate that improvements in a limited measure of agent behavior can coexist with failures elsewhere in the application. Reference validation increased citation presence, but the saved responses showed that valid identifiers could accompany unsupported claims and that an LLM judge could repeat the same error. Deterministic checks, retrieval metrics, human assessment, and judge calibration supplied different parts of the evidence needed to interpret those outcomes. Repeated paired experiments then connected the observed improvements and regressions to the proposed changes and their resource requirements. For practical agent development, the implication is that an improvement should be assessed against the combined behavior contract of the application, with the underlying responses and traces available for review before a release decision is made.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=093e00a22ec2" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/ai-agent-evaluation-a-practical-guide-with-a-working-application-093e00a22ec2">AI Agent Evaluation: A Practical Guide with a Working Application</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Can NVIDIA NIM Power a Local Agentic Application?]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://pub.towardsai.net/can-nvidia-nim-power-a-local-agentic-application-23920a83f421?source=rss-84c9ed3eae75------2"><img src="https://cdn-images-1.medium.com/max/1672/1*VpJaONuTcGh9UAd-cj7YxQ.png" width="1672"></a></p><p class="medium-feed-snippet">Testing NVIDIA NIM for agentic AI with a Dockerized multi-agent RAG system on an RTX 3090</p><p class="medium-feed-link"><a href="https://pub.towardsai.net/can-nvidia-nim-power-a-local-agentic-application-23920a83f421?source=rss-84c9ed3eae75------2">Continue reading on Towards AI »</a></p></div>]]></description>
            <link>https://pub.towardsai.net/can-nvidia-nim-power-a-local-agentic-application-23920a83f421?source=rss-84c9ed3eae75------2</link>
            <guid isPermaLink="false">https://medium.com/p/23920a83f421</guid>
            <dc:creator><![CDATA[Sheik Nomaan, Ph.D.]]></dc:creator>
            <pubDate>Mon, 14 Sep 2026 15:31:01 GMT</pubDate>
            <atom:updated>2026-09-14T15:31:01.374Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[The RAG Triad Explained: Modern RAG Evaluation That Actually Works]]></title>
            <link>https://ai.plainenglish.io/the-rag-triad-explained-modern-rag-evaluation-that-actually-works-7cddf442d36d?source=rss-84c9ed3eae75------2</link>
            <guid isPermaLink="false">https://medium.com/p/7cddf442d36d</guid>
            <category><![CDATA[rag-evaluation]]></category>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[generative-ai]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Sheik Nomaan, Ph.D.]]></dc:creator>
            <pubDate>Sun, 26 Apr 2026 12:28:32 GMT</pubDate>
            <atom:updated>2026-04-26T12:36:13.267Z</atom:updated>
            <content:encoded><![CDATA[<p>You deploy a new RAG system. The answers <em>sound</em> right. Users are happy. Everything feels good.</p><p>Then one day, a seemingly simple but important question comes in:</p><p><strong>Question:</strong> “How do I reset a user’s password in the system?”</p><p><strong>Human reference answer:</strong> “To reset a password, users should navigate to the login page, click ‘Forgot Password’, enter their registered email address, and follow the verification link sent to their inbox.”</p><p><strong>AI-generated response:</strong> “You can reset your password by requesting a link through your email from the sign-in screen.”</p><p>On the surface it looks fine. But something is off. The response is shorter, misses key steps, and feels incomplete — even though it’s not outright wrong.</p><p>That moment made us realize we had no reliable, objective way to measure “good enough.”</p><p>We needed a better system — one that could tell us <em>why</em> the answer failed and exactly where to fix it in the pipeline.</p><p>So we adopted the <strong>RAG Triad</strong>: the modern, battle-tested framework for evaluating Retrieval-Augmented Generation systems. It evaluates three critical dimensions of every response:</p><ul><li><strong>Context Relevance</strong> — Did we retrieve the right information in the first place?</li><li><strong>Faithfulness</strong> — Is the answer fully grounded in the retrieved context (no hallucinations)?</li><li><strong>Answer Relevance</strong> — Does the final response actually address the user’s question?</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bTyof3hH5Z2oP3oPqzPV1A.png" /><figcaption>The RAG Triad — Context Relevance, Faithfulness, and Answer Relevance</figcaption></figure><p>Combined with <strong>LLM-as-a-Judge</strong> techniques, this triad turns subjective feelings into actionable, reproducible scores.</p><p>Here’s exactly how the RAG Triad works in practice.</p><h3>Context Relevance: Did We Retrieve the Right Stuff?</h3><p>This metric checks whether the documents pulled from the knowledge base actually contain information useful for answering the query.</p><p><strong>How it works (LLM-as-a-Judge):</strong> The judge model looks at the query plus each retrieved chunk and scores how relevant that chunk is. Low scores mean the retriever is pulling noise instead of signal.</p><p><strong>Typical scoring (0–1 scale):</strong></p><ul><li>0.9–1.0 → Excellent retrieval</li><li>0.7–0.9 → Good (most production systems aim here)</li><li>Below 0.7 → Retrieval is the bottleneck</li></ul><p>Real example from the password reset case: The AI response missed steps because the retriever only pulled a high-level “account settings” page instead of the exact “password reset flow” documentation. Context Relevance score: 0.45. Once chunking and metadata filtering were improved, it jumped to 0.92.</p><h3>Faithfulness (Groundedness): Is the Answer Actually True to the Context?</h3><p>This is the anti-hallucination metric. It verifies that every factual claim in the generated answer is directly supported by the retrieved context.</p><p><strong>How it works:</strong> The judge extracts atomic claims from the answer, then checks each one against the retrieved documents. Any unsupported claim tanks the score.</p><p><strong>Score interpretation:</strong></p><ul><li>0.95+ → Rock-solid (almost no hallucinations)</li><li>0.8–0.95 → Acceptable for most use cases</li><li>Below 0.8 → High risk of hallucinations — fix the prompt or retrieval immediately</li></ul><p>In the password reset case, the response was mostly faithful, but it invented a shortcut that wasn’t in any document. Faithfulness caught it instantly.</p><h3>Answer Relevance: Does It Actually Answer the Question?</h3><p>Even if the retrieval was good and the answer is faithful, it still has to be <em>on-topic</em>.</p><p><strong>How it works:</strong> Under the hood, this is semantic similarity in action — just used in a more clever way than older reference-based approaches.</p><p>The judge model first generates several synthetic questions that the AI’s answer appears to be answering. It then uses embeddings and cosine similarity to measure how closely those synthetic questions match the original user question. The final score is the average of those similarities.</p><p>In other words: if the answer “sounds like” it’s responding to the same intent as the user’s query, the score is high. This is the spiritual successor to the Semantic Similarity metric used before — except now it doesn’t require a human reference answer at all.</p><p><strong>Score range (0–1):</strong></p><ul><li>0.9+ → Perfectly on-point</li><li>0.7–0.9 → Mostly relevant (minor drift)</li><li>Below 0.7 → The model wandered off-topic or addressed a different intent</li></ul><p>In the password-reset example, the AI gave correct information about requesting a link — but it ignored the full user flow the question implied. Answer Relevance flagged it clearly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QgOh1E5OXG37XLsG_an2Jg.png" /><figcaption>Real impact of the RAG Triad: Context Relevance, Faithfulness, and Answer Relevance improved in one fix</figcaption></figure><h3>When to Prioritize Which Metric</h3><p>Not every RAG system needs to optimize the triad in the same way. The right priority depends on the risk profile of your use case.</p><p><strong>Customer Support</strong><br>Prioritize <strong>Answer Relevance</strong>.<br>Users usually care most about getting a clear, direct, and helpful response. A technically correct answer still fails if it does not address the user’s actual question.</p><p><strong>Technical Documentation</strong><br>Prioritize <strong>Faithfulness</strong>.<br>Accuracy matters more than style. The answer should stay tightly grounded in the documentation, especially when it includes setup steps, commands, API behavior, or troubleshooting instructions.</p><p><strong>Legal and Compliance</strong><br>Prioritize <strong>Faithfulness + Context Relevance</strong>.<br>These systems have very little tolerance for hallucinations or unsupported claims. You need the right source material first, and the final answer must stay grounded in that material.</p><p><strong>Educational Content</strong><br>Prioritize <strong>all three metrics</strong>.<br>A good educational answer needs to retrieve the right context, explain it accurately, and respond to the learner’s actual intent.</p><p><strong>Internal Knowledge Base and Search</strong><br>Prioritize <strong>Context Relevance</strong>.<br>If retrieval is weak, everything downstream suffers. Even a well-written answer can become useless if it starts from the wrong documents.</p><h3>Real Scenarios Where the Triad Saved Us</h3><p>The real power of the RAG Triad becomes clear when it is used to guide decisions. Here are three examples from our own experience:</p><p><strong>Scenario 1: Chunking Strategy Comparison</strong></p><p>Three different chunking approaches were tested: fixed-size, semantic, and agent-based. The triad quickly revealed that semantic chunking dramatically improved Context Relevance (from around 0.6 to over 0.9) while keeping Faithfulness high. Fixed-size chunking — which had been used for months — was quietly limiting retrieval quality. Switching to semantic chunking delivered one of the largest single improvements.</p><p><strong>Scenario 2: Retrieval Method Optimization</strong></p><p>Vector-only search produced strong Context Relevance but sometimes lower Faithfulness. After testing hybrid search (vector + keyword), the triad scores became much more balanced across all three metrics. This hybrid approach is now the default in production.</p><p><strong>Scenario 3: Prompt Engineering</strong></p><p>A single, well-targeted prompt tweak — adding explicit instructions to stay strictly within the retrieved context — raised Faithfulness from 0.68 to 0.94 across 200 test questions. The change was fast, inexpensive, and immediately visible in the metrics.</p><p>These experiments showed that the triad does more than just score answers — it points directly to the most effective fix in the pipeline.</p><h3>Common Questions We Get</h3><p><strong>Are human reference answers still required?</strong><br> Not always. One of the advantages of the RAG Triad is that it can be mostly reference-free. Instead of comparing every answer against a manually written gold answer, you can evaluate whether the retrieved context is relevant, whether the response is grounded in that context, and whether the final answer addresses the original question. This makes the triad especially useful for dynamic knowledge bases that change frequently.</p><p><strong>How reliable is LLM-as-a-Judge?</strong><br> It depends on the rubric, the judge model, and the risk level of the application. For many production workflows, LLM-as-a-Judge works well when the evaluation criteria are specific and the judge is given clear scoring instructions. For higher-risk systems, I would not rely on a single judge score. Run multiple evaluations, sample failures manually, and compare judge decisions against human review on a regular basis.</p><p><strong>What counts as a “good enough” score?</strong><br> There is no universal threshold. A score of 0.85+ across the triad is a reasonable starting point for many production systems, but the right threshold depends on the use case. A customer support bot, an internal search assistant, and a legal compliance system should not all use the same bar. Start with a baseline, inspect real failures, and adjust the threshold based on the risk of being wrong.</p><h3>Quick Start Tips for Production</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8yfENncSr83tu4Z5zYoV9Q.png" /><figcaption>RAG Triad Production Loop: Turning production questions into triad scores, alerts, and targeted fixes across the RAG pipeline.</figcaption></figure><ul><li>Start with 50–100 real questions from your own domain. Include easy cases, edge cases, and questions where your current RAG system already struggles.</li><li>Evaluate each response across the full triad: Context Relevance, Faithfulness, and Answer Relevance. Avoid relying on a single composite score too early, because each metric points to a different failure mode.</li><li>Use frameworks like RAGAS or DeepEval to automate the first version of this evaluation loop. They can help you move from manual review to repeatable scoring without building everything from scratch.</li><li>Track the scores over time with tools like LangSmith, Phoenix, or Helicone. The goal is not just to score test runs, but to catch production drift when retrieval quality, grounding, or answer relevance starts dropping.</li><li>Set alerts when any triad score falls below your threshold. A drop in Context Relevance usually points to retrieval or chunking. A drop in Faithfulness points to grounding or prompt issues. A drop in Answer Relevance points to response quality or intent mismatch.</li></ul><h3>Conclusion</h3><p>We used to evaluate RAG responses mostly by gut feel. If an answer sounded good enough, we often moved on. That approach worked for simple demos, but it did not hold up in production. Too many subtle failures slipped through — responses that looked reasonable on the surface but missed key steps, relied on weak context, or quietly drifted away from the user’s actual intent.</p><p>The RAG Triad gave us a much better way to reason about quality. Instead of debating whether a response “felt right,” we could now ask three clear, concrete questions: Did we retrieve the right context? Is the answer fully grounded in that context? And most importantly — does the response actually address what the user asked?</p><p>That shift made the evaluation process far more actionable. A low Context Relevance score points toward retrieval, chunking, or metadata filtering. A low Faithfulness score points toward grounding or prompt issues. A low Answer Relevance score reveals a mismatch with the user’s intent.</p><p>The best part is that getting started requires very little. Even 40 or 50 real questions from the actual domain are usually enough to uncover the biggest blind spots and provide a clear path for meaningful improvements.</p><h3>A message from our Founder</h3><p>Hey, <a href="https://linkedin.com/in/sunilsandhu">Sunil</a> here. I wanted to take a moment to thank you for reading until the end and for being a part of this community. Did you know that our team run these publications as a volunteer effort to over 3.5m monthly readers? We don’t receive any funding, we do this to support the community.</p><p>If you want to show some love, please take a moment to follow me on <a href="https://linkedin.com/in/sunilsandhu">LinkedIn</a>, <a href="https://tiktok.com/@messyfounder">TikTok</a>, <a href="https://instagram.com/sunilsandhu">Instagram</a>. You can also subscribe to our <a href="https://newsletter.plainenglish.io/">weekly newsletter</a>. And before you go, don’t forget to clap and follow the writer️!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7cddf442d36d" width="1" height="1" alt=""><hr><p><a href="https://ai.plainenglish.io/the-rag-triad-explained-modern-rag-evaluation-that-actually-works-7cddf442d36d">The RAG Triad Explained: Modern RAG Evaluation That Actually Works</a> was originally published in <a href="https://ai.plainenglish.io/">Artificial Intelligence in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deepagents on LangGraph: Debugging Long-Running AI Agents with Time-Travel]]></title>
            <link>https://pub.towardsai.net/deepagents-on-langgraph-debugging-long-running-ai-agents-with-time-travel-ff897ef50b73?source=rss-84c9ed3eae75------2</link>
            <guid isPermaLink="false">https://medium.com/p/ff897ef50b73</guid>
            <category><![CDATA[langgraph]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[deep-agent]]></category>
            <category><![CDATA[time-travel]]></category>
            <dc:creator><![CDATA[Sheik Nomaan, Ph.D.]]></dc:creator>
            <pubDate>Fri, 24 Apr 2026 20:01:02 GMT</pubDate>
            <atom:updated>2026-04-24T20:01:02.354Z</atom:updated>
            <content:encoded><![CDATA[<p>Imagine we’re building a research agent that analyzes the latest developments in generative AI and delivers a weekly summary report. After running for several minutes and consuming thousands of tokens across multiple sources, it produces a confident output.</p><p>While reviewing the report, stakeholders identified a major flaw: several key claims in the report are based on outdated 2024 benchmarks, presented as current 2026 insights. The agent didn’t just make a retrieval error — it allowed bad data to propagate through its reasoning chain because it had no mechanism to isolate context or recover from an early mistake.</p><p>In traditional agent workflows, this kind of error is costly. Typical options to address the issue includes —</p><ul><li>restart the entire run and waste all prior computation,</li><li>manually patch the output and risk introducing new inconsistencies, or</li><li>ship the flawed result and hope the issue doesn’t surface again.</li></ul><p>What if we could do something fundamentally better —</p><blockquote>pause the workflow at the point of failure, go back to an earlier state in the execution graph, inject a precise correction (“ignore all sources before 2025”), and let the agent continue from that exact checkpoint instead of starting over?</blockquote><p>That capability is exactly what we explored by building a research coordinator agent using <strong>Deepagents</strong> on top of <strong>LangGraph</strong>. By combining structured subagent delegation for clean context isolation with LangGraph’s checkpointing and time-travel capabilities, the system transforms a full restart into targeted, <strong>stateful recovery</strong>.</p><p>In this article, I’ll break down the architecture, show how an intentional mix of outdated and current sources creates realistic failure modes, and demonstrate how checkpoint forking fundamentally changes the way we debug and recover from agent errors.</p><h3>Why Most Agents Fail in Real Workflows</h3><p>Traditional agents operate on a “straight-line” logic. While this works for basic tool-calling, multi-step research exposes four critical breaking points:</p><ul><li><strong>Context pollution</strong>: The agent’s memory gets bloated with irrelevant details from previous steps.</li><li><strong>The Domino Effect:</strong> A single bad retrieval or hallucination early in the process poisons everything that follows.</li><li><strong>The “All-or-Nothing” Trap:</strong> When something goes wrong at Step 4 of a 10-step workflow, the only practical option is to throw everything away and start over.</li><li><strong>Debugging difficulty</strong>: Understanding exactly where and why the agent went wrong is often opaque.</li></ul><p>We need something fundamentally better — an architecture that could plan effectively, delegate intelligently, maintain clean context, and recover gracefully when things inevitably go wrong.</p><h3>The Solution: Persistence and Forking</h3><p>Instead of treating agent execution as a one-way linear chain, we need to treat it as a <strong>versioned, stateful history</strong>.</p><p>By moving away from linear chains toward a stateful graph, we gain three pillars of reliability that traditional “stateless” agents simply don’t have:</p><ul><li>Persistence: Every action — every variable, memory, and scheduled next step — is automatically saved as an immutable checkpoint.</li><li>Threads: Each execution session lives under a unique thread_id that maintains a complete, versioned history of all checkpoints for that run.</li><li>Checkpoint Forking: The ability to “time travel” to any past state, inject a surgical correction, and branch the execution forward without losing prior work.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6b4H7RuSjviemcL7WTNGJA.png" /><figcaption>As the diagram above illustrates, this changes everything. When you discover an error at Step 4, you no longer have to restart from scratch. You simply navigate back to the relevant checkpoint (e.g., Checkpoint 2), apply a targeted update, and fork a new path forward. The original history remains intact while the corrected branch becomes the active, current workflow.</figcaption></figure><h3>Discovering Deepagents + LangGraph</h3><p>This is exactly where the combination of <strong>Deepagents + LangGraph</strong> shines. While LangGraph provides the low-level primitives — persistence, threads, and checkpoint forking — turning those into a production-grade system usually requires heavy boilerplate.</p><p><strong>Deepagents </strong>acts as a lightweight, opinionated harness — <strong>essentially a pre-configured toolkit</strong> — built directly on top of LangGraph. It provides the high-level abstractions that make these advanced features practical to use:</p><ul><li><strong>Built-in Planning:</strong> Tools like write_todos to keep the coordinator agent focused.</li><li><strong>Virtual Filesystem:</strong> A dedicated space for managing intermediate notes and research outputs.</li><li><strong>Subagent Isolation:</strong> Native support for specialized subagents that prevent context from leaking.</li><li><strong>Seamless Integration:</strong> Full access to LangGraph’s time-travel capabilities without the manual setup.</li></ul><p>Together, these tools allowed us to implement a clean Coordinator Pattern. The main agent focuses purely on orchestrating and delegating, while the underlying system handles the heavy lifting of state recovery.</p><h3>Project Overview: The Research Coordinator Agent</h3><p>Instead of building yet another monolithic agent overloaded with tools, we chose a strict Coordinator Pattern.</p><p>In this design, the main agent has <strong>zero custom tools</strong>. Its only responsibilities are high-level orchestration:</p><ul><li>Planning: Creating a structured roadmap using write_todos.</li><li>Delegation: Routing subtasks to specialized subagents using the built-in task() tool.</li></ul><p>This separation of concerns ensures the coordinator never suffers from context bloat. It stays focused on the big picture while specialized agents handle the detailed work.</p><h3>Architecture: Coordinator + Specialized Subagents</h3><p><strong>We</strong> implemented two focused subagents:</p><ul><li><strong>research-specialist</strong>: Responsible for searching the knowledge base and returning structured findings.</li><li><strong>fact-checker</strong>: Responsible for validating claims and explicitly flagging outdated or inconsistent information.</li></ul><p><strong>We</strong> deliberately seeded the knowledge base with a realistic mix of correct 2025–2026 documents and some outdated 2024 ones. This created intentional failure scenarios where the agent could make mistakes — and then correct them through time-travel.</p><p>The coordinator breaks down the user query into todos and delegates each task to the most appropriate subagent. Thanks to strong context isolation, each subagent only sees the information relevant to its role.</p><h3>How Subagent Delegation Works</h3><p>Here’s the core code for defining the subagents and creating the coordinator agent:</p><pre>from deepagents import create_deep_agent<br>from langgraph.checkpoint.memory import MemorySaver<br>from langchain_openai import ChatOpenAI<br><br># Define specialized subagents<br>research_subagent = {<br>    &quot;name&quot;: &quot;research-specialist&quot;,<br>    &quot;description&quot;: &quot;Focused agent for retrieving and structuring information from the knowledge base.&quot;,<br>    &quot;prompt&quot;: (<br>        &quot;You are a precise research specialist. Gather accurate, structured findings &quot;<br>        &quot;from the knowledge base. Return only relevant information.&quot;<br>    ),<br>    &quot;tools&quot;: [&quot;search_knowledge_base&quot;]<br>}<br><br>fact_checker_subagent = {<br>    &quot;name&quot;: &quot;fact-checker&quot;,<br>    &quot;description&quot;: &quot;Specialized agent for validating claims and detecting outdated content.&quot;,<br>    &quot;prompt&quot;: (<br>        &quot;You are a rigorous fact-checker. Always verify dates and flag any information &quot;<br>        &quot;from 2024 or earlier as outdated.&quot;<br>    ),<br>    &quot;tools&quot;: [&quot;search_knowledge_base&quot;]<br>}<br><br># Create the deep agent (coordinator)<br>agent = create_deep_agent(<br>    model=ChatOpenAI(model=&quot;gpt-4o&quot;, temperature=0),<br>    tools=[],                                      # Coordinator has no direct tools<br>    system_prompt=(<br>        &quot;You are a Research Coordinator. Plan every task using todos and delegate &quot;<br>        &quot;all research and fact-checking exclusively to your subagents.&quot;<br>    ),<br>    subagents=[research_subagent, fact_checker_subagent],<br>    interrupt_on={&quot;write_file&quot;: True},<br>    checkpointer=MemorySaver(),<br>)</pre><p><em>(Simplified for clarity. The full, production-ready version with detailed prompts and modular structure is in src/agents/coordinator.py and src/agents/subagents.py in the repository.)</em></p><p>By giving the coordinator no direct tools, we forced it to act purely as an orchestrator. This pattern significantly improves maintainability and makes debugging much clearer.</p><h3>The Real Magic: Time-Travel Debugging &amp; Checkpoint Forking</h3><p>This is where the theory of stateful graphs becomes a tangible superpower. Because LangGraph snapshots every state, we don’t have to watch helplessly as a run fails. If the agent produces a report based on 2024 data, we can “rewind the tape.”</p><p>First, we inspect the thread’s history to find the exact moment the 2024 data was introduced:</p><pre>states = list(agent.get_state_history(config))<br><br>for i, snapshot in enumerate(states):<br>    print(f&quot;Step {i}: {snapshot.metadata.get(&#39;step&#39;)} | Next: {snapshot.next}&quot;)</pre><p>Once we identify the “point of infection,” we perform a Checkpoint Fork. We don’t just retry the prompt; we jump back to that specific moment in time and inject a surgical correction.</p><pre>fork_config = {<br>    &quot;configurable&quot;: {<br>        &quot;thread_id&quot;: thread_id,<br>        &quot;checkpoint_id&quot;: chosen_checkpoint_id<br>    }<br>}<br><br>correction = &quot;IMPORTANT: Only use sources from 2025 or later. Ignore any 2024 documents.&quot;<br><br>forked_result = agent.invoke(<br>    {&quot;messages&quot;: [HumanMessage(content=correction)]},<br>    config=fork_config<br>)</pre><p><em>(Simplified for clarity. The full time-travel logic is in demos/time_travel.py.)</em></p><p>The agent resumes exactly from the chosen checkpoint, incorporates the new instruction, re-delegates if necessary, and produces a corrected final report. This “time-travel” capability turns debugging from a frustrating process into a controlled and repeatable one.</p><h3>Visualizing the Recovery: The Streamlit Demo</h3><p>To make these concepts truly interactive, <strong>we</strong> built a Streamlit dashboard that brings the “undo” button to life. It hides the complexity of checkpoint IDs and thread history behind a clean, intuitive interface where you can:</p><ul><li><strong>Observe in Real Time</strong>: Watch the coordinator break down a query into todos and delegate tasks to the research-specialist and fact-checker subagents.</li><li><strong>Time Travel</strong>: Browse the full state history, select any past checkpoint, apply a targeted correction, and instantly see the agent fork a new, successful execution path.</li></ul><p>This demo makes the power of checkpoint forking feel tangible — you can intentionally trigger a failure and recover from it in seconds.</p><h3>Key Lessons &amp; Production Tips</h3><ul><li>Restricting the coordinator to planning and delegation (zero custom tools) is highly effective at preventing context bloat.</li><li>Subagent isolation is one of the best defenses against polluted context and cascading errors.</li><li>Time-travel debugging changes how we think about agent reliability — it gives us a true “undo” button. In production, we rarely scan checkpoints manually. Instead, we combine <strong>strategic interrupts</strong> (e.g. after the fact-checker), <strong>automated flagging</strong> by subagents, and simple review UIs so humans (or a supervisor agent) can quickly approve, edit, or fork from the right checkpoint.</li><li>Start with MemorySaver during development. For production, switch to PostgresSaver (or any persistent checkpointer) and implement regular checkpoint pruning to keep storage under control.</li><li>Beyond debugging, persistence and checkpoint forking unlock powerful patterns: safely resuming long-running agents after interruptions, running parallel experiment branches (A/B testing corrections), and implementing safe rollback mechanisms in production workflows.</li></ul><h3>Conclusion</h3><p>Deepagents on top of LangGraph offers a practical way to build long-running agents that are not only capable, but also recoverable. By combining coordinator-based delegation with persistent execution state and checkpoint forking, the system moves away from fragile straight-line workflows and toward something much closer to a production-ready operating model.</p><p>The most important takeaway is that long-running agent reliability is not just a prompting problem. It is an execution problem. Once an agent runs across multiple stages, tools, and intermediate artifacts, we need state, isolation, and recovery mechanisms to keep the system trustworthy. That is what makes this pattern valuable.</p><p>If you are building research agents, complex RAG systems, or any workflow where failures can emerge late and reruns are costly, this approach is worth exploring. It does not eliminate the need for better retrieval or validation, but it gives us something many agent systems still lack: a disciplined way to recover from mistakes without discarding everything that came before them.</p><p>The complete code and interactive Streamlit demo are available in the repository: → <a href="https://github.com/smnomaan/deepagents-research-coordinator"><strong>smnomaan/deepagents-research-coordinator</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ff897ef50b73" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/deepagents-on-langgraph-debugging-long-running-ai-agents-with-time-travel-ff897ef50b73">Deepagents on LangGraph: Debugging Long-Running AI Agents with Time-Travel</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Structured Output for LLMs in Production:
From json.loads() to Validated Objects]]></title>
            <link>https://pub.towardsai.net/structured-output-for-llms-in-production-from-json-loads-to-validated-objects-84e14a2504d0?source=rss-84c9ed3eae75------2</link>
            <guid isPermaLink="false">https://medium.com/p/84e14a2504d0</guid>
            <dc:creator><![CDATA[Sheik Nomaan, Ph.D.]]></dc:creator>
            <pubDate>Wed, 15 Apr 2026 15:01:01 GMT</pubDate>
            <atom:updated>2026-04-15T15:01:01.874Z</atom:updated>
            <content:encoded><![CDATA[<h3>Structured Output for LLMs in Production: From json.loads() to Validated Objects</h3><p>In the era of GenAI hype, every team has ideas — and every idea needs a proof of concept (PoC) by Friday.</p><p>During the PoC phase, nobody questions the LLM response. As long as json.loads(response.content) works and the output looks right, we move fast. We’re vibe coding, building fast, demo on Thursday, and the LLM is returning clean JSON on every test call. Ship it.</p><p>Then we move toward production.</p><p>Suddenly, the LLM starts returning markdown fences around the JSON, so we strip them. On the next call, the keys are slightly different, so we normalize them. Then a number comes back as a string, so we cast it. Before we realize it, we are 30 lines deep into a hand-rolled parser, and every new edge case adds another if statement.</p><p>Here’s the part that really bites: the database does not care that this system started as a 5-day PoC. Tables have schemas. Columns have types. The INSERT statement expects title VARCHAR, year INTEGER, and category VARCHAR — not whatever shape the LLM felt like returning today. That is exactly where probabilistic model output collides with deterministic application boundaries.</p><p>The gap between <em>“the LLM gave me a JSON string”</em> and <em>“this data is ready for my schema”</em> is where production bugs hide — the kind that happily pass every test we wrote during the PoC.</p><p>In this guide, I’ll walk through what structured output is, why it matters, and how to implement it properly with <strong>Pydantic and LangChain</strong>, using concrete code examples that show exactly what goes wrong at each stage when we don’t.</p><h3>The Problem: LLMs Return Strings, Applications Need Structured Data</h3><p>Let’s say we’re building a feature that recommends movies and stores them in a database.</p><p>At the prototype stage, the LLM call looks deceptively simple:</p><pre>from openai import OpenAI<br><br>client = OpenAI()<br><br>response = client.chat.completions.create(<br>    model=&quot;gpt-4o&quot;,<br>    messages=[<br>        {<br>            &quot;role&quot;: &quot;user&quot;,<br>            &quot;content&quot;: &quot;Recommend a sci-fi movie. Return JSON with: title, year, genre&quot;<br>        }<br>    ],<br>)<br><br>text = response.choices[0].message.content<br>print(text)</pre><p>We run this five times. Here’s what we get:</p><pre># Run 1 — perfect<br>&#39;{&quot;title&quot;: &quot;Inception&quot;, &quot;year&quot;: 2010, &quot;genre&quot;: &quot;sci-fi&quot;}&#39;<br><br># Run 2 — wrapped in markdown fences<br>&#39;```json\n{&quot;title&quot;: &quot;Arrival&quot;, &quot;year&quot;: 2016, &quot;genre&quot;: &quot;sci-fi&quot;}\n```&#39;<br><br># Run 3 — year is a string<br>&#39;{&quot;title&quot;: &quot;Interstellar&quot;, &quot;year&quot;: &quot;2014&quot;, &quot;genre&quot;: &quot;Sci-Fi&quot;}&#39;<br><br># Run 4 — different key names<br>&#39;{&quot;movie_title&quot;: &quot;The Matrix&quot;, &quot;release_year&quot;: 1999, &quot;category&quot;: &quot;Science Fiction&quot;}&#39;<br><br># Run 5 — helpful prose before the JSON<br>&#39;Here is my recommendation:\n{&quot;title&quot;: &quot;Blade Runner 2049&quot;, &quot;year&quot;: 2017, &quot;genre&quot;: &quot;sci-fi&quot;}&#39;</pre><p>Five calls, five different formats. Naturally, the first instinct is to do the obvious thing:</p><pre>import json<br><br>def parse_movie(llm_text: str) -&gt; dict:<br>    return json.loads(llm_text)</pre><p>It works for Run 1, but crashes on Run 2 and Run 5 with <em>json.JSONDecodeError</em>.</p><p>So we patch the parser to strip markdown and extract the JSON block. Now the syntax problem is solved.</p><p>But the real production problems are only beginning.</p><p>Run 3 gives us a string instead of an integer:</p><pre>{&quot;year&quot;: &quot;2014&quot;}</pre><p>At first glance, downstream code still looks fine:</p><pre>movie = parse_movie(llm_text)<br><br>db.execute(<br>    &quot;INSERT INTO movies (title, year, genre) VALUES (%s, %s, %s)&quot;,<br>    (movie[&quot;title&quot;], movie[&quot;year&quot;], movie[&quot;genre&quot;])<br>)</pre><p>And that is exactly what makes this class of bug dangerous. Depending on the database, driver, or downstream system, the value may be coerced, rejected, or silently preserved as the wrong type. Even if the insert succeeds, we have already lost schema guarantees in application code.</p><p>Run 4 introduces a different failure mode.</p><pre>{<br>    &quot;movie_title&quot;: &quot;The Matrix&quot;,<br>    &quot;release_year&quot;: 1999,<br>    &quot;category&quot;: &quot;Science Fiction&quot;<br>}</pre><p>It parses successfully, but now the application code breaks:</p><pre>title = movie[&quot;title&quot;]   # KeyError: &#39;title&#39;</pre><p>The natural response is to add more defensive logic: key normalization, type casting, and casing fixes. Before long, we are 30 lines deep into brittle parsing code for just three fields — and it is still fragile.</p><p>The next model version might return a different key, wrap the payload in XML-style tags, or prepend reasoning text above the JSON.</p><p>The challenge is no longer parsing syntax; it is enforcing a reliable contract between probabilistic model output and deterministic application systems.</p><blockquote>Structured output is how we restore that contract.</blockquote><h3>The 4 Levels of Structured Output</h3><p>After seeing how quickly parser debt accumulates, the next question becomes: how much control can we actually exert over LLM output?</p><p>In practice there is a clear spectrum — from “please try to follow this format” all the way to “the model literally cannot produce invalid output.” Most production systems evolve through these four levels.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rAblWNRvKn4hiI-WzjUe4g.png" /><figcaption>Figure 1. The guarantee spectrum: from best-effort prompting to schema-enforced output.</figcaption></figure><h3><strong>Level 1: Prompt-Based (Hope)</strong></h3><p>At the first level, we rely entirely on prompt instructions.</p><pre>response = client.chat.completions.create(<br>    model=&quot;gpt-4o&quot;,<br>    messages=[{<br>        &quot;role&quot;: &quot;user&quot;,<br>        &quot;content&quot;: &quot;Recommend a movie. Return JSON with keys: title, year, genre&quot;<br>    }]<br>)</pre><p>The model tries its best, but everything we saw earlier can still happen: markdown fences, prose, wrong keys, or wrong types.</p><p><strong>Guarantee: none.</strong></p><h3><strong>Level 2: JSON Mode (Valid JSON, Wrong Shape)</strong></h3><p>We force valid JSON.</p><pre>response = client.chat.completions.create(<br>    model=&quot;gpt-4o&quot;,<br>    messages=[{<br>        &quot;role&quot;: &quot;user&quot;,<br>        &quot;content&quot;: &quot;Recommend a movie. Return JSON with keys: title, year, genre&quot;<br>    }],<br>    response_format={&quot;type&quot;: &quot;json_object&quot;}<br>)</pre><p>json.loads() now works reliably. The parsing problem is solved. But the schema problem remains — the model can still return wrong keys or wrong types.</p><h3><strong>Level 3: JSON Schema Mode (Right Shape)</strong></h3><p>We define the exact structure we want and no longer asking for it.</p><pre>response = client.chat.completions.create(<br>    model=&quot;gpt-4o&quot;,<br>    messages=[{<br>        &quot;role&quot;: &quot;user&quot;,<br>        &quot;content&quot;: &quot;Recommend a sci-fi movie from the 2000s&quot;<br>    }],<br>    response_format={<br>        &quot;type&quot;: &quot;json_schema&quot;,<br>        &quot;json_schema&quot;: {<br>            &quot;name&quot;: &quot;movie_recommendation&quot;,<br>            &quot;schema&quot;: {<br>                &quot;type&quot;: &quot;object&quot;,<br>                &quot;properties&quot;: {<br>                    &quot;title&quot;: {&quot;type&quot;: &quot;string&quot;},<br>                    &quot;year&quot;: {&quot;type&quot;: &quot;integer&quot;},<br>                    &quot;genre&quot;: {&quot;type&quot;: &quot;string&quot;, &quot;enum&quot;: [&quot;action&quot;, &quot;comedy&quot;, &quot;sci-fi&quot;, &quot;drama&quot;]}<br>                },<br>                &quot;required&quot;: [&quot;title&quot;, &quot;year&quot;, &quot;genre&quot;],<br>                &quot;additionalProperties&quot;: False<br>            }<br>        }<br>    }<br>)</pre><p>The model must return the correct keys, correct types, and valid enum values.</p><h3>Level 4: Constrained Decoding (Schema-Enforced Output)</h3><p>We don’t just validate after generation — we constrain generation itself.</p><pre>response_format = {<br>    &quot;type&quot;: &quot;json_schema&quot;,<br>    &quot;json_schema&quot;: {<br>        &quot;name&quot;: &quot;movie_recommendation&quot;,<br>        &quot;strict&quot;: True,<br>        &quot;schema&quot;: { ... }   # same schema as above<br>    }<br>}</pre><p>With<em> strict=True</em>, the model literally cannot generate invalid output (for example, it cannot return a string for a field defined as integer). This is currently the strongest guarantee available.</p><p>Structure is now enforced during decoding itself and this naturally raises the next question: How do we get all these guarantees without manually writing raw JSON Schema by hand?</p><p>For three fields this is manageable. For 15 fields, nested objects, enums, and validation constraints, it quickly becomes tedious and error-prone.</p><p>This is exactly where Python developers want something more ergonomic.</p><h3><strong>Enter Pydantic: Schemas in Python</strong></h3><p>By this point we have seen how quickly raw strings and hand-rolled parsers become brittle. Once the response structure grows beyond a few flat fields, maintaining clean output handling turns into a maintenance nightmare.</p><p>Instead of writing raw JSON Schema by hand, we define the structure directly as a Python class:</p><pre>from pydantic import BaseModel, Field<br>from enum import Enum<br><br>class Genre(str, Enum):<br>    ACTION = &quot;action&quot;<br>    COMEDY = &quot;comedy&quot;<br>    SCI_FI = &quot;sci-fi&quot;<br>    DRAMA = &quot;drama&quot;<br><br>class MovieRecommendation(BaseModel):<br>    title: str = Field(description=&quot;Full movie title, without year or parentheses&quot;)<br>    year: int = Field(ge=1888, le=2030, description=&quot;Release year as a 4-digit number&quot;)<br>    genre: Genre = Field(description=&quot;Primary genre - pick exactly one&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7Q5AuZKkgx0E5_oAZJLrPw.png" /><figcaption>Figure 2. A single Pydantic model automatically generates schema and validates runtime data at the application boundary.</figcaption></figure><p>With a single Python class, we get three major benefits at once: automatic JSON Schema generation, built-in validation, and field-level guidance for the LLM.</p><h3>Automatic JSON Schema Generation</h3><p>The first benefit is that Pydantic automatically generates JSON Schema for us.</p><pre>import json<br><br>print(json.dumps(MovieRecommendation.model_json_schema(), indent=2))</pre><pre>{<br>  &quot;$defs&quot;: {<br>    &quot;Genre&quot;: {<br>      &quot;enum&quot;: [&quot;action&quot;, &quot;comedy&quot;, &quot;sci-fi&quot;, &quot;drama&quot;],<br>      &quot;title&quot;: &quot;Genre&quot;,<br>      &quot;type&quot;: &quot;string&quot;<br>    }<br>  },<br>  &quot;properties&quot;: {<br>    &quot;title&quot;: {<br>      &quot;description&quot;: &quot;Full movie title, without year or parentheses&quot;,<br>      &quot;title&quot;: &quot;Title&quot;,<br>      &quot;type&quot;: &quot;string&quot;<br>    },<br>    &quot;year&quot;: {<br>      &quot;description&quot;: &quot;Release year as a 4-digit number&quot;,<br>      &quot;minimum&quot;: 1888,<br>      &quot;maximum&quot;: 2030,<br>      &quot;title&quot;: &quot;Year&quot;,<br>      &quot;type&quot;: &quot;integer&quot;<br>    },<br>    &quot;genre&quot;: {<br>      &quot;$ref&quot;: &quot;#/$defs/Genre&quot;,<br>      &quot;description&quot;: &quot;Primary genre - pick exactly one&quot;<br>    }<br>  },<br>  &quot;required&quot;: [&quot;title&quot;, &quot;year&quot;, &quot;genre&quot;],<br>  &quot;title&quot;: &quot;MovieRecommendation&quot;,<br>  &quot;type&quot;: &quot;object&quot;<br>}</pre><p>There is no hand-written JSON Schema to maintain. We update the Python class, and the schema updates automatically. That is one of the biggest “aha” moments in structured output pipelines:</p><blockquote>define the structure once in Python, and the schema can then be reused downstream.</blockquote><h3>Built-in Validation</h3><p>The second advantage is validation. Pydantic validates and, when appropriate, coerces data as it enters the object.</p><pre>movie = MovieRecommendation(<br>    title=&quot;Inception&quot;,<br>    year=&quot;2010&quot;,<br>    genre=&quot;sci-fi&quot;<br>)<br><br>print(movie.year)        # 2010<br>print(type(movie.year))  # &lt;class &#39;int&#39;&gt;</pre><p>Here, &quot;2010&quot; came in as a string, but Pydantic converted it into an integer.</p><p>Now compare that with invalid values:</p><pre>MovieRecommendation(<br>    title=&quot;Inception&quot;,<br>    year=2010,<br>    genre=&quot;banana&quot;<br>)<br><br># ValidationError:<br># Input should be &#39;action&#39;, &#39;comedy&#39;, &#39;sci-fi&#39; or &#39;drama&#39;<br><br>MovieRecommendation(<br>    title=&quot;Inception&quot;,<br>    year=99999,<br>    genre=&quot;sci-fi&quot;<br>)<br><br># ValidationError:<br># Input should be less than or equal to 2030</pre><p>The failure now happens exactly where it should: at the application boundary, before invalid data can leak into downstream logic. That is precisely where schema violations should fail in a production system.</p><h3>Schema as Model Guidance</h3><p>The third benefit is often overlooked: the description= text is not just documentation for humans. It becomes part of the generated schema, which in turn helps guide structured generation.</p><p>For example:</p><pre>year: int = Field(<br>    ge=1888,<br>    le=2030,<br>    description=&quot;Release year as a 4-digit number&quot;<br>)</pre><p>This acts as a field-level instruction. It is significantly more precise than simply naming the field year and hoping the model interprets it correctly. In practice, this is where schema design starts improving output quality, not just output validation.</p><p>So far, we’ve focused on structure and validation at the schema level and this is only half of the story. In production systems, structure alone is not enough; we also need a reliable way to move validated data between the LLM and the application boundary. That brings us to serialization</p><h3>Serialization: The Bridge Between the LLM and the Application</h3><p>There’s one concept that ties everything together: serialization.</p><p>An LLM returns JSON text. Our application needs a validated Python object. Serialization (and its reverse, deserialization) is the process that moves data across that boundary.</p><p>Without structure, this step becomes the fragile hand-rolled parser we saw earlier. With Pydantic, it becomes a single method call.</p><pre>llm_response = &#39;{&quot;title&quot;: &quot;Inception&quot;, &quot;year&quot;: 2010, &quot;genre&quot;: &quot;sci-fi&quot;}&#39;<br><br>movie = MovieRecommendation.model_validate_json(llm_response)<br><br>print(movie.title)   # &quot;Inception&quot;<br>print(movie.year)    # 2010<br>print(movie.genre)   # Genre.SCI_FI</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1qM2MQxoSvNVKsVBHMi7Ag.png" /><figcaption>Figure 3. Pydantic replaces fragile parsing with a validated boundary between raw LLM JSON and application-safe objects.</figcaption></figure><p>We are no longer converting text into a loose dictionary. We are converting it directly into a validated domain object — typed, coerced, and application-safe.</p><p>When we need to send data back out, Pydantic gives us clean round-trip methods:</p><pre>movie.model_dump()<br># {&#39;title&#39;: &#39;Inception&#39;, &#39;year&#39;: 2010, &#39;genre&#39;: &#39;sci-fi&#39;}<br><br>movie.model_dump_json()<br># &#39;{&quot;title&quot;:&quot;Inception&quot;,&quot;year&quot;:2010,&quot;genre&quot;:&quot;sci-fi&quot;}&#39;</pre><p>The fragile parser we started with has now been replaced by a clean, typed serialization boundary. That is one of the most important architectural shifts in production LLM systems.</p><h3>Wiring It Together: Two Approaches</h3><p>At the schema layer, we have everything we need. Our Pydantic model now gives us automatic JSON Schema generation, validation during deserialization, and a clean serialization boundary between the LLM and the application. The remaining question is straightforward: <strong>how do we connect this schema to the actual model call?</strong></p><p>Today, there are two clean ways to do that. Both completely eliminate the hand-rolled parser from the beginning of this article. The right choice depends mostly on your stack and how much orchestration you need.</p><h3>Option A: Native SDK (Recommended for single-provider stacks)</h3><p>For teams using only OpenAI or Azure OpenAI, the native SDK is often the simplest and cleanest approach. Recent SDK versions allow a Pydantic model to be passed directly as the response format, which means schema conversion, validation, and deserialization are handled internally.</p><pre>from openai import OpenAI<br>from pydantic import BaseModel, Field<br>from enum import Enum<br><br>class Genre(str, Enum):<br>    ACTION = &quot;action&quot;<br>    COMEDY = &quot;comedy&quot;<br>    SCI_FI = &quot;sci-fi&quot;<br>    DRAMA = &quot;drama&quot;<br><br>class MovieRecommendation(BaseModel):<br>    title: str = Field(description=&quot;Full movie title&quot;)<br>    year: int = Field(ge=1888, le=2030, description=&quot;Release year&quot;)<br>    genre: Genre = Field(description=&quot;Primary genre&quot;)<br><br>client = OpenAI()<br><br>response = client.beta.chat.completions.parse(<br>    model=&quot;gpt-4o&quot;,<br>    messages=[{<br>        &quot;role&quot;: &quot;user&quot;,<br>        &quot;content&quot;: &quot;Recommend a sci-fi movie from the 2000s&quot;<br>    }],<br>    response_format=MovieRecommendation,<br>)<br><br>movie = response.choices[0].message.parsed<br>print(movie)</pre><p>The important point here is that .parsed is already a fully validated Pydantic object. There is no json.loads(), no fence stripping, and no manual key normalization.</p><p>This pattern is no longer limited to OpenAI. Claude, Gemini, and Grok now all provide native structured output capabilities in their respective SDKs, including schema-based validation and typed responses.</p><p>If your system is built around a single provider, the native SDK is usually the most ergonomic option. However, if you expect provider switching, multi-step chains, retrieval pipelines, or agent workflows, LangChain’s .with_structured_output() becomes the stronger abstraction because it normalizes provider-specific differences behind a single interface.</p><h3>Option B: LangChain .with_structured_output()</h3><p>If your stack already uses LangChain — or you anticipate multi-step workflows, retrieval pipelines, or multi-provider support — LangChain provides a clean abstraction on top of the same Pydantic foundation.</p><pre>from langchain_openai import ChatOpenAI<br><br>llm = ChatOpenAI(<br>    model=&quot;gpt-4o&quot;,<br>    temperature=0<br>)<br><br>structured_llm = llm.with_structured_output(MovieRecommendation)<br><br>movie = structured_llm.invoke(<br>    &quot;Recommend a sci-fi movie from the 2000s&quot;<br>)<br><br>print(movie)</pre><p>The output is still the same validated domain object. The difference is architectural: LangChain makes it easier to compose structured output into larger systems such as retrieval pipelines, agents, or multi-step reasoning workflows.</p><p>The key shift remains the same. We are no longer receiving text and attempting to reverse-engineer structure after the fact. Instead, the model output enters the application as a typed object that already satisfies the schema contract.</p><h3>A More Realistic Example: Support Ticket Extraction</h3><p>Movie recommendations are useful for illustrating the mechanics, but production systems rarely stop at toy examples. The real value of structured output becomes much clearer in extraction workflows such as support email processing.</p><p>Consider a support email pipeline:</p><pre>class Priority(str, Enum):<br>    LOW = &quot;low&quot;<br>    MEDIUM = &quot;medium&quot;<br>    HIGH = &quot;high&quot;<br>    URGENT = &quot;urgent&quot;<br><br>class SupportTicket(BaseModel):<br>    subject: str<br>    priority: Priority<br>    product: str<br>    is_billing_issue: bool<br>    customer_sentiment: float = Field(ge=-1.0, le=1.0)<br>    action_items: list[str]</pre><p>The extraction step is now reduced to a schema-bound model call:</p><pre>ticket_llm = llm.with_structured_output(SupportTicket)<br><br>ticket = ticket_llm.invoke(<br>    f&quot;Extract structured data from this support email:\n{email}&quot;<br>)</pre><p>The returned object can flow directly into downstream systems such as ticketing workflows, API responses, analytics pipelines, or database inserts. Instead of parsing a paragraph to infer urgency, billing status, sentiment, and next steps, the application receives a validated object with correct types and constraints already enforced. Structured output is no longer just a developer convenience; in production workflows, it becomes an operational requirement.</p><h3>Production Hardening</h3><p>Once structured output is part of a production system, observability becomes just as important as validation. One of the most useful patterns here is returning the raw response alongside the parsed object:</p><pre>structured_llm = llm.with_structured_output(<br>    SupportTicket,<br>    include_raw=True<br>)</pre><p>Validation failures should be treated as observable signals rather than opaque exceptions. When the same field fails repeatedly, it usually points to one of three issues: an unclear field description, overly strict constraints, or a schema shape that needs refinement.</p><p>For workflows that directly feed downstream systems, strict mode should generally be the default:</p><pre>structured_llm = llm.with_structured_output(<br>    SupportTicket,<br>    method=&quot;json_schema&quot;,<br>    strict=True<br>)</pre><p>With <em>strict=True</em>, schema enforcement moves into the generation process itself instead of relying only on post-generation validation. It adds roughly 5–15% latency but virtually eliminates downstream errors — a trade-off that is almost always worth it for production data.</p><p>For ultra-critical workflows, wrap the call in a simple retry that falls back to plain json_object mode after two failures. This gives you the best of both worlds: maximum reliability with a safety net.</p><h3>Design Principles That Actually Matter</h3><p>After working through the full lifecycle, a few practical rules consistently matter in production:</p><ul><li>every field should have a clear description</li><li>use enums whenever values are constrained</li><li>add numeric bounds wherever possible</li><li>keep schemas flat unless nesting is necessary</li><li>log every validation failure</li></ul><p>These are not implementation details. They directly improve reliability and make downstream systems safer.</p><h3>Closing Thoughts: From Text to Application Boundaries</h3><p>The real challenge in production LLM systems is not generating text — it is turning probabilistic model output into reliable application data.</p><p>We started with json.loads(), a few assumptions, and fast-moving demo code. That approach works for a quick prototype, but it breaks the moment output feeds downstream systems.</p><p>Structured output changes that model entirely.</p><p>Once we define schemas first and validate at the boundary, model output stops behaving like unstructured text and starts behaving like a real interface contract.</p><p>That shift, from best-effort parsing to schema-first engineering, is what turns an LLM workflow into an production-grade system.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=84e14a2504d0" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/structured-output-for-llms-in-production-from-json-loads-to-validated-objects-84e14a2504d0">Structured Output for LLMs in Production:
From json.loads() to Validated Objects</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SKILL.md: Treating Prompts as First-Class Artifacts in Production LLM Systems]]></title>
            <link>https://pub.towardsai.net/skill-md-treating-prompts-as-first-class-artifacts-in-production-llm-systems-b566efbea613?source=rss-84c9ed3eae75------2</link>
            <guid isPermaLink="false">https://medium.com/p/b566efbea613</guid>
            <category><![CDATA[llm-applications]]></category>
            <category><![CDATA[generative-ai]]></category>
            <category><![CDATA[prompt-engineering]]></category>
            <category><![CDATA[context-engineering]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <dc:creator><![CDATA[Sheik Nomaan, Ph.D.]]></dc:creator>
            <pubDate>Thu, 02 Apr 2026 17:56:23 GMT</pubDate>
            <atom:updated>2026-04-04T09:51:22.756Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>From a Simple Prompt to a Real Invoice Extraction Pipeline:</strong></h3><p>We first introduced <strong>SKILL.md</strong> while building a document extraction pipeline to process invoices and return structured JSON for downstream systems. The initial implementation was deliberately simple: extract raw text from uploaded PDFs and pass it to an LLM with a short system prompt that asked for a fixed schema.</p><p>What became clear early on was that the prompt was not just an inline instruction. As it evolved, it began accumulating business rules, output constraints, and validation behavior. At that point, we were no longer treating it as a string embedded in Python code — we were depending on it as a versioned system component. That shift is what we mean by treating prompts as first-class artifacts: assets with clear ownership, reviewability, and an independent lifecycle.</p><p>For example, the first version looked something like this:</p><pre>SYSTEM_PROMPT = &quot;&quot;&quot;<br>You are an assistant that extracts structured data from invoices.<br><br>Return valid JSON with the following fields:<br>- invoice_number<br>- vendor_name<br>- invoice_date<br>- due_date<br>- subtotal<br>- tax_amount<br>- total_amount<br><br>Do not add extra fields.<br>If a field is missing, return null.<br>&quot;&quot;&quot;</pre><p>The prompt was then used directly in the LLM call:</p><pre>response = await client.chat.completions.create(<br>    messages=[<br>        {&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: SYSTEM_PROMPT},<br>        {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: invoice_text}<br>    ]<br>)</pre><p>For early experimentation, this approach worked surprisingly well. A simple inline prompt inside Python was enough to validate the workflow and prove that the model could reliably extract structured fields from semi-structured documents.</p><p>That simplicity did not last for long. As new invoice templates were introduced, the prompt quickly started absorbing business logic. We needed it to handle missing fields, normalize dates into ISO format, preserve currency units, extract line items from tables, distinguish header metadata from footer notes, and explicitly avoid inferring values that were not present in the source document.</p><p>The turning point came when extraction rules started living inside the prompt alongside API calls, retry handlers, and JSON parsing logic in the same Python file. At that stage, the problem was no longer prompt quality, but software boundaries. Once we reached that point, the next step was no longer prompt tuning. It was separating prompt behavior from orchestration code, which is what led us to adopt <strong>SKILL.md</strong>.</p><h3>How We Introduced SKILL.md into the Pipeline</h3><p>As the prompt began taking on more extraction logic, it became clear that it no longer belonged inside orchestration code. Instead of keeping that logic inside a Python string literal, we moved it into a standalone <strong>SKILL.md</strong> file within the extraction module.</p><p>The pipeline structure evolved into something like this:</p><pre>invoice_pipeline/<br>├── extract.py<br>├── parser.py<br>├── validators.py<br>└── skills/<br>    └── invoice_extraction/<br>        └── SKILL.md</pre><p>The <strong>SKILL.md</strong> file contained both metadata and the prompt body. For example:</p><pre>---<br>name: invoice_extraction<br>description: Extract structured fields from invoice PDFs<br>version: 1.0.0<br>output_format: json<br>owner: document-intelligence-team<br>---<br><br>You are an assistant that extracts structured data from invoice documents.<br><br>Return valid JSON with the following fields:<br>- invoice_number<br>- vendor_name<br>- invoice_date<br>- due_date<br>- subtotal<br>- tax_amount<br>- total_amount<br>- currency<br>- line_items<br><br>Rules:<br>1. Return null for missing fields<br>2. Normalize dates to YYYY-MM-DD<br>3. Preserve currency symbols exactly as written<br>4. Extract line_items only from table sections<br>5. Do not infer values that do not explicitly appear in the document</pre><p>Separating metadata from the instruction body gave us a much cleaner unit for versioning and review. Prompt-only updates no longer required changes to extract.py, and extraction rules such as date normalization or missing-field handling could now be reviewed directly inside <strong>SKILL.md</strong>.</p><h3>Loading and Using SKILL.md at Runtime</h3><p>Externalizing the prompt into <strong>SKILL.md</strong> only solves part of the problem. The real value comes from how easily it fits into the runtime path.</p><p>Our goal was to keep the integration as simple as the original inline implementation while separating prompt logic from orchestration code. To do that, we introduced a small loader that reads the <strong>SKILL.md</strong> file, parses the frontmatter, and returns the prompt body.</p><p>A simplified version looked like this:</p><pre>from pathlib import Path<br>import yaml<br><br>def load_skill(name: str) -&gt; dict:<br>    raw = Path(f&quot;skills/{name}/SKILL.md&quot;).read_text()<br><br>    parts = raw.split(&quot;---&quot;, 2)<br>    frontmatter = parts[1]<br>    body = parts[2]<br><br>    metadata = yaml.safe_load(frontmatter)<br><br>    return {<br>        &quot;metadata&quot;: metadata,<br>        &quot;prompt&quot;: body.strip()<br>    }</pre><p>The YAML frontmatter carries metadata such as version, ownership, and output format, while the markdown body becomes the system prompt passed to the model at runtime.</p><p>At runtime, the integration stayed almost identical to the original inline approach:</p><pre><br>skill = load_skill(&quot;invoice_extraction&quot;)<br><br>response = await client.chat.completions.create(<br>    messages=[<br>        {&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: skill[&quot;prompt&quot;]},<br>        {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: invoice_text},</pre><p>That simplicity was important. The orchestration code remained responsible for document ingestion, retries, and response parsing, while <strong>SKILL.md</strong> owned extraction behavior. The biggest change was not the amount of code, but the boundary itself. Prompt-only updates no longer required editing Python files, and orchestration changes no longer had to be mixed with prompt edits in the same diff. As a result, reviews, version tracking, and prompt iteration all became much cleaner.</p><h3>What Changed After We Adopted SKILL.md</h3><p>The biggest improvement showed up in code review. Before adopting SKILL.md, even a small prompt update, such as changing how missing invoice totals were handled or adding support for a new date format, required touching Python files. These diffs often mixed prompt changes with retry logic, validation updates, or response parsing, which made reviews slower and harder to reason about.</p><p>A typical review diff started to look much cleaner:</p><pre>Before<br>extract.py                    +42 -28<br>(prompt changes + orchestration logic)<br><br>After<br>skills/invoice_extraction/SKILL.md   +35 -12<br>(just the prompt)<br><br>extract.py                    +12 -3<br>(just the orchestration logic)</pre><p>With the prompt moved into <strong>SKILL.md</strong>, prompt-only updates became isolated and easy to review. A reviewer could immediately tell whether a pull request changed extraction behavior or application logic.</p><p>Versioning became much simpler as well. Because the prompt carried explicit metadata, it was much easier to compare behavior across versions. Instead of digging through commits to figure out which prompt was deployed, we could directly compare outputs from one skill version to another.</p><p>The same separation improved ownership. Changes to extraction rules no longer required editing orchestration code, which made it easier for analysts or domain experts to contribute directly to prompt updates.</p><p>What stood out most, though, was the speed of prompt iteration. Once updates became easier to review and safer to ship, we started improving them more often. Changes that previously felt risky, like tightening missing-field rules or supporting a new invoice template, became normal parts of the workflow.</p><h3>Testing and Versioned Evaluation</h3><p>The first time we needed to compare extraction quality across two prompt revisions, the benefit of <strong>SKILL.md</strong> became immediately clear.</p><p>Before externalizing prompts, even answering a simple question like <em>“did date extraction improve?”</em> often meant tracing back through application commits and trying to separate prompt edits from Python changes.</p><p>With <strong>SKILL.md</strong>, that comparison became straightforward. Because each prompt carried explicit version metadata, we could run the same validation dataset against two skill versions and compare outputs side by side.</p><p>For example, a prompt revision could move from one explicit skill version to the next:</p><pre><br># v1.0.0<br>---<br>name: invoice_extraction<br>version: 1.0.0<br>---<br><br># v1.1.0<br>---<br>name: invoice_extraction<br>version: 1.1.0<br>---</pre><p>A simple evaluation flow looked like this:</p><pre>test_invoices = load_test_dataset()<br><br>for invoice in test_invoices:<br>    result_v1 = run_skill(<br>        &quot;invoice_extraction&quot;,<br>        version=&quot;1.0.0&quot;,<br>        invoice=invoice<br>    )<br><br>    result_v2 = run_skill(<br>        &quot;invoice_extraction&quot;,<br>        version=&quot;1.1.0&quot;,<br>        invoice=invoice<br>    )<br><br>    compare_outputs(result_v1, result_v2)</pre><p>This made it much easier to answer practical questions such as:</p><ul><li>Did date extraction improve?</li><li>Did missing-field handling regress?</li><li>Did line-item extraction become more reliable?</li></ul><p>Running the same invoice dataset against both versions made these differences much easier to inspect. Instead of relying on intuition or checking a few sample outputs manually, prompt revisions could be validated against a consistent benchmark set before release. That gave us much stronger confidence during iteration and reduced the risk of introducing silent regressions.</p><h3>Where SKILL.md Fits Best</h3><p>This pattern is not necessary for every LLM application.</p><p>For early prototypes, notebooks, or one-off experiments, keeping the prompt inline is often the right choice. At that stage, speed matters more than architecture.</p><p>SKILL.md becomes valuable when prompts stop behaving like simple inline instructions and begin shaping system behavior. In our case, that happened as extraction rules started evolving across multiple invoice templates, edge cases, and validation constraints.</p><p>It tends to fit best in systems where prompts change frequently, multiple prompt-driven stages exist, or different people own prompt logic and orchestration code.</p><p>Common examples include:</p><ul><li>document extraction pipelines</li><li>multi-step classification workflows</li><li>validation and post-processing stages</li><li>retrieval and summarization chains</li><li>production systems with frequent prompt iteration</li></ul><p>It is especially useful when prompt authors and application engineers are not always the same people. In those cases, treating prompts as first-class artifacts makes ownership, versioning, and review workflows significantly cleaner.</p><p>More than the file format itself, the real value of SKILL.md lies in the engineering boundary it creates for prompt-driven systems.</p><h3>Conclusion</h3><p>The biggest lesson from this implementation was that prompts in production systems need the same engineering discipline as code.</p><p>As prompt logic began driving extraction rules, validation behavior, and output structure, keeping it as an inline string no longer scaled. Moving it into <strong>SKILL.md</strong> gave it clear ownership, versioning, and a clean boundary from orchestration code.</p><p>That boundary made reviews easier, evaluations repeatable, and prompt iteration significantly safer.</p><p>More than the file format itself, the real value of SKILL.md lies in the software boundary it creates.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b566efbea613" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/skill-md-treating-prompts-as-first-class-artifacts-in-production-llm-systems-b566efbea613">SKILL.md: Treating Prompts as First-Class Artifacts in Production LLM Systems</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>