AI & Data3 January 20277 min read

Build Lab: From Chain to Governed Agent — Part 1 of 8

From model call to structured output

A model call returns text. A service needs fields it can check, route and record. Part 1 of Build Lab: From Chain to Governed Agent shows the ways LangChain asks a model for structured output, what the schema cannot guarantee, and the output contract card a team should complete before any downstream code trusts a field.

#AI Engineering#Structured Output#LangChain#AI Agents#Production AI

A person at an illustrative public service counter types: "I lost my document and my appointment is on Friday. What do I bring?" A single model call returns three polite paragraphs. They mention a replacement process, suggest arriving early and close with a friendly wish. A person reading the reply might find it helpful. The software around the model cannot use it. It cannot tell which intent the model recognised, which language it answered in, which approved source it relied on, or whether it thinks a person should take over.

That gap is where most AI builds start, and where many stall. The first working demonstration is a model call. The first production component is a contract.

A model call returns text, but a service needs fields it can check, route and record: structured output is where the build starts, and a schema is a promise that only your own validation can keep.

This is Part 1 of Build Lab: From Chain to Governed Agent. The companion article, The framework is not the product, explains why the series treats the framework as one layer among several.

A model call is not an interface

Text is a good output for a person and a poor one for a program. Downstream code needs to know, without guessing, which branch to take. If it has to search prose for a phrase such as "you may need to speak to an official", the routing logic now depends on the model's wording, and the wording changes whenever the model, the prompt or the temperature does.

Structured output moves that decision into named, typed fields. The model still interprets the request. The output now has a shape that code can test: an intent from a closed list, a language code, an answer, the identifiers of the sources used and a flag that says whether a person is needed.

The earlier article From prompt to structured contract sets out the four layers between a model's answer and an action: the prompt asks, the schema shapes, code validates and business rules decide. This part does not repeat that. It shows how the framework layer implements the shape, and where it stops.

Three ways to ask for structure

LangChain's documentation, opened on 25 November 2026, describes three routes.

Bind a schema to the model. The models page describes with_structured_output, which accepts a Pydantic model, a TypedDict or a JSON Schema. Its method parameter selects json_schema (the provider's dedicated structured output feature), function_calling (a forced tool call that follows the schema) or json_mode (valid JSON, with the schema described in the prompt). The page notes that support varies by provider.

Ask an agent for a response format. The structured output page describes the response_format argument of create_agent. A ProviderStrategy relies on the provider's native structured output; a ToolStrategy works with any model that supports tool calling. If a schema type is passed directly, LangChain chooses between them from the model's profile. The result appears under the structured_response key of the agent's final state.

Parse after the fact. For chains built with the pipe operator, the same page says there is no built-in retry for parsing failures, and points to binding the schema instead, or to a repairing parser in the langchain-classic package.

The first route is the right start for a single interpretation step. The second belongs to an agent that also calls tools. The third is a fallback, not a design.

Illustrative; check against the current documentation.

from typing import Literal
from pydantic import BaseModel
from langchain.chat_models import init_chat_model

class CounterAnswer(BaseModel):
    schema_version: Literal["1.0"]
    intent: Literal["status_check", "requirements", "booking", "other"]
    language: str
    answer: str
    source_ids: list[str]
    needs_person: bool

model = init_chat_model("provider:model-name", temperature=0, max_retries=2)
structured = model.with_structured_output(CounterAnswer, include_raw=True)
result = structured.invoke("Synthetic request: what do I bring to replace a lost document?")

The model name is a placeholder and the request is synthetic. With include_raw=True, the documentation says the result is a dictionary with raw, parsed and parsing_error keys, so the raw message and its token counts are kept alongside the parsed object.

From a model call to a validated output contract. A request passes through a versioned prompt template to the model call. The model is asked for output bound to a schema. Validation in code then checks the result. If the output is valid, business rules decide the next step: answer with sources, confirm with the person, or escalate. If it is invalid, refused or truncated, the system makes one bounded retry, and after that hands the case to a person. Every attempt records the raw response, the parsed result, the schema version, the prompt version and the model identifier in the trace.INTERPRETATIONINPUTRequestVERSIONEDPrompt templateCOMPONENTModel callSCHEMA-BOUNDStructured outputCONTROLYOUR CODEValidate: types, ranges, sourcesBUSINESS RULESAnswer, confirm or escalatevalidINVALID, REFUSED OR TRUNCATEDOne bounded retry, then a personinvalidretry onceESCALATIONHuman review with the raw outputstill invalidTrace every attempt: raw response, parsed result, schema version,prompt version, model identifier, retries and outcome.Illustrative. Reproducible means the same structure, validated and recorded; it does not mean the same wording every time.
The schema shapes the output. Your own code decides whether it can be used, and only business rules act on it. CloudNala analysis; illustrative, not a description of any live service.

What the schema cannot guarantee

A schema constrains shape. It does not make the content true, and the documentation is candid about the edges.

Validation depends on the schema type. Pydantic models validate automatically. The models page says TypedDict and JSON Schema outputs need manual validation. A team that switches schema types to save a dependency may lose its first line of checking without noticing.

Refusals are a separate outcome. According to the models page, a refusal from with_structured_output raises a ModelRefusalError rather than a parsing error, or is returned in parsing_error when include_raw=True. Under an agent, the structured output page says a ProviderStrategy refusal raises a validation error, while a ToolStrategy agent ends without a structured_response. Each of these needs an explicit branch in your code, because "no answer" must route somewhere.

Retries are automatic unless you bound them. A ToolStrategy returns validation errors to the model and asks it to correct its output. Its handle_errors setting defaults to retrying on all errors. Separately, the models page lists max_retries on init_chat_model with a default of 6, for failed calls. Each retry costs time and tokens, and an unbounded correction loop is how a small validation failure becomes a slow, expensive request. Set the limits on purpose and log every attempt.

Providers differ, and tools change behaviour. The LangChain 101 manual at aiengineeringfromscratch.com, a third-party source opened on 25 November 2026, reports that structured output from its agent loop held on one hosted provider but failed on a small local model when tools were bound. Its advice is to test structured output on your own provider with tools bound. That is the manual's own observation; treat it as a reason to test, not as a general result.

Valid is not correct. A perfectly shaped answer can still cite the wrong source, pick a plausible but wrong intent or state a requirement that does not exist. Your own code checks what the schema cannot: does each source identifier exist in the approved set, is the intent consistent with the request type, is the language one the route supports? Business rules then decide. Part 3 covers the source boundary.

The output contract card

The decision tool for this part is a contract card. Complete one row per field before any downstream code is allowed to act on it.

FieldType and allowed valuesWho consumes itChecked byIf missing or invalid
schema_versionFixed stringEvery consumerConsumer rejects unknown versionsReject and log
intentClosed list of four codesRouterSchema, then a consistency ruleTreat as other and offer a person
languageSupported language codeResponse renderer, interpreter queueCode: in the supported listEscalate to an interpreter
answerText, length limitThe person, after renderingCode: length, protected termsDo not show; escalate
source_idsList of approved identifiersEvidence log, the personCode: every identifier exists and is currentDo not show the answer
needs_personBooleanRouterSchema; a rule may also force it trueRoute to a person

Three habits make the card work. Every field that code acts on is a closed list or a checked value, not free text. The payload carries its own version, so consumers can reject what they do not understand. And the free-text fields are for people to read, never for code to branch on.

Reproducible means recorded

A common acceptance test for an AI workflow is "a reproducible structured output". That cannot mean the same words every time. Even at a low temperature, model output can vary, and providers update models. A reproducible output is one where the same input produces the same structure, passes the same validation and leaves a record that lets someone explain the result later.

For each call, record:

  • the raw response and the parsed result;
  • the schema version and the prompt version;
  • the model identifier and the parameters used;
  • the number of retries and any refusal or parsing error;
  • the latency and token counts; and
  • a correlation identifier that links the call to the request.

That record is the start of the trace that Part 7 uses to reconstruct failures, and Observability for AI sets out the wider event.

Where this sits in the NalaTolika pattern

NalaTolika is a CloudNala concept and reference architecture for governed language interpretation. It has no customers, deployments, pilots, data or results. Its routine path is the chain this part builds: receive a request, detect the language and intent, translate or normalise it, retrieve approved service information, and produce a structured answer with source references. The structured output is what lets the next two steps work: asking the person to confirm, and escalating when confidence, identity or policy thresholds are not met. Without named fields, neither step has anything reliable to test.

The first section of the Chain-to-Governed-Agent Readiness Checklist turns this part into checks a team can sign off.

Next in the series: Prompt templates are versioned components. All parts are on the series page.

Sources and limits: this article is CloudNala analysis. LangChain behaviour is taken from docs.langchain.com (models and structured output pages), opened on 25 November 2026; APIs and defaults change, so check the current documentation before relying on them. The code is illustrative, uses a placeholder model name and synthetic text, and has not been run against a live provider by CloudNala. The provider observation comes from a third-party manual and is its own result. The counter example is illustrative and names no department. NalaTolika is a concept with no deployments. LangChain is named as a dated example, not a recommendation.

How CloudNala can help

CloudNala reviews the output contracts in an AI workflow before downstream systems depend on them. We list every field your code acts on, check how each is constrained and validated, test refusal, truncation and retry paths, and give your team a contract card and a short set of recorded test cases that run on every change.


Work with CloudNala

CloudNala helps organisations move from technology ambition to practical execution across cloud, AI, data, platform engineering and digital services.

Whether you are exploring AI, modernising your cloud environment, building a public-sector digital service, or turning an idea into a working MVP, we can help you shape the roadmap and deliver the next step.

Book an AI Production Readiness Review or write to us at consult@cloudnala.co.za

Found this useful?

Share