AI AgentsLangChain
How do you handle invalid structured output safely?
Question 304 of 324 · Updated
On this page
- Direct answer
- 1. Identify the failed boundary
- 2. Understand LangChain structured-output exceptions
- Distinguish multiple responses from multiple business tools
- 3. Configure ToolStrategy handle_errors deliberately
- Host-managed recovery alternative
- 4. Return sanitized and actionable correction feedback
- 5. Enforce a bounded correction loop
- 6. Handle malformed JSON, refusals and truncation as different outcomes
- 7. Tested Python: bounded, sanitized response-only recovery
- 8. Preserve idempotency and authoritative outcomes
- 9. Fallback and human escalation
- 10. Observability and production failure testing
- Interview-ready answer
- Official documentation research leads and verification status
Direct answer#
Treat invalid structured output as an unaccepted candidate, classify the failure, and allow only a bounded, explicitly authorized correction path. In modern LangChain, ToolStrategy can handle certain structured-response errors through handle_errors. StructuredOutputValidationError and MultipleStructuredOutputsError distinguish an invalid structured-response payload from multiple final-response calls when the configured contract expects one. Use reviewed correction messages, enforce an independent total-run budget, and verify the actual behavior in the installed framework.
A schema-valid result may still contain an unsupported claim. Keep semantic acceptance separate from framework parsing. A provider refusal, incomplete generation, revoked permission or uncertain external mutation must not be turned into success through JSON repair or an unconditional retry. If correction cannot safely produce an accepted result, return a controlled incomplete outcome, reconcile the authoritative operation, or escalate to an authorized human reviewer.
Source questions #21–23 (AI Agents #301–303) cover the final response interface, strategy choice and response-schema design. Source question #17 (#297) covers ordinary tool exceptions. This lesson concentrates on failure detection and recovery at the final structured-response boundary, including LangChain's structured-output error classes, safe feedback, limited regeneration and business-side-effect protection.
1. Identify the failed boundary#
A final agent result passes through several layers. An error at one layer should not be disguised as a failure at another.
Consider a fictional order-support agent that reads an authorized order. The verified observation establishes that O-1 shipped, with evidence identifier E-1. The downstream consumer requires an order ID, status and evidence reference. If the model returns a syntactically valid report claiming that O-1 is pending, a JSON parser and enum validator may accept its shape, but the application must reject the unsupported claim.
| Failure class | Example | Appropriate boundary |
|---|---|---|
| Transport or provider failure | Request fails before a response is obtained | Approved infrastructure recovery |
| Provider refusal | Provider explicitly declines the generation | Preserve refusal and stop the prohibited path |
| Truncation or incomplete generation | Generation stops before the final object is complete | Completion-status handling |
| Malformed representation | Invalid JSON, duplicate keys, invalid encoding | Bounded parser or provider adapter |
| Structured-response cardinality | Model proposes multiple final-response calls | Framework strategy or runtime policy |
| Schema violation | Missing required field, invalid type or enum | Framework and local schema validation |
| Semantic failure | Valid status conflicts with verified evidence | Independent application acceptance |
| Authorization failure | Evidence is outside the caller's scope | Trusted service or policy enforcement |
| Uncertain external commitment | Action may have completed despite a missing acknowledgement | Authoritative reconciliation |
The correct response is not always another model call. A deterministic application may already have enough verified data to construct a result itself. If no trustworthy evidence exists, a correction prompt cannot create it.
This is a host-level design, not an exact representation of the framework's internal graph. The chosen strategy determines which errors become model-visible correction messages, which propagate as exceptions, and which appear as provider-specific outcomes.
2. Understand LangChain structured-output exceptions#
In modern LangChain's agent structured-output implementation, StructuredOutputValidationError and MultipleStructuredOutputsError are useful error classifications associated with the final-response contract. They should not be confused with an ordinary business ToolException or a transport timeout.
StructuredOutputValidationError indicates that a proposed structured response failed parsing or validation under the relevant framework contract. Depending on the implementation and schema type, the underlying cause can include Pydantic validation failures or another schema parsing error. Inspect the pinned release to determine the exact circumstances in which this exception is raised.
MultipleStructuredOutputsError represents a model proposing multiple structured-response tool calls when one final structured response is expected. For example, the model may produce two final-answer calls with conflicting statuses. Silently choosing the first or last can make an unsupported result appear authoritative. Correct the response cardinality or return an incomplete outcome.
These error classes do not necessarily cover every failure from every provider strategy. Native provider schema rejection, refusal, transport failure or truncation may surface through different adapter-specific exceptions or metadata. Do not write a single exception handler and assume it covers all final-response failures.
Distinguish multiple responses from multiple business tools#
A model can legitimately propose several independent business reads in one turn. The issue is not the total number of tool calls; it is the number of final structured-response proposals relative to the declared contract. A response schema may itself contain a list of several findings. One valid response object containing multiple findings is not the same as several competing final-response tool calls.
3. Configure ToolStrategy handle_errors deliberately#
In supported modern LangChain releases, ToolStrategy accepts a handle_errors configuration. It controls how selected structured-output errors are handled within the agent's response-tool loop.
| Common configuration | Intended behavior |
|---|---|
| True | Handle supported structured-output errors using framework-provided feedback |
| False | Do not use ToolStrategy's built-in correction handling for these errors |
| String | Use a reviewed fixed feedback message for handled errors |
| Exception type or tuple of types | Restrict handling to specified error classes |
| Callable | Generate feedback from the error under the application's policy |
The exact supported signature, default behavior, exception matching and generated messages depend on the installed version. True must not be interpreted as "retry every possible provider failure indefinitely." False must not be interpreted as "all errors propagate unchanged through every surrounding middleware." The actual agent execution stack needs integration tests.
The following illustrative configuration uses a fixed-response schema and exception-specific feedback. The model identifier and synthetic task are examples. There are no live external operations.
PYTHONfrom typing import Literal from pydantic import BaseModel, ConfigDict from langchain.agents import create_agent from langchain.agents.structured_output import ( ToolStrategy, StructuredOutputValidationError, MultipleStructuredOutputsError, ) class StatusAnswer(BaseModel): model_config = ConfigDict(strict=True, extra="forbid") order_id: str status: Literal["shipped", "pending"] evidence_id: str def safe_feedback(error: Exception) -> str: if isinstance(error, MultipleStructuredOutputsError): return "Return exactly one final structured response." if isinstance(error, StructuredOutputValidationError): return "Match the declared response fields and types." # Do not silently convert unknown failures into a retry. raise error agent = create_agent( model="openai:gpt-4o-mini", tools=[], response_format=ToolStrategy( StatusAnswer, handle_errors=safe_feedback, ), system_prompt=( "Return only the fictional verified status provided by the host. " "Do not invent evidence." ), )
SDK verification limitation: LangChain, langchain_core and langgraph were absent from the local environment. This integration and all other SDK snippets are illustrative and unexecuted. Confirm the exact imports, callable semantics and error propagation behavior in the pinned framework release. No claim is made that the illustrative model currently supports a particular response strategy. The independent Python recovery implementation in section 7 was actually executed on Python 3.13.5 with Pydantic 2.13.5.
This example has no business tools because the intended workload is finalization from evidence already obtained by the trusted host. A production finalization prompt must receive the appropriate authorized evidence, and the host must independently verify the output against that evidence. Merely instructing the model to use evidence is not a validation guarantee.
A callback returning a string does not itself impose a correction-attempt limit. The runtime can make additional model calls after receiving feedback. Apply a separate verified total-run, model-call, time and cost budget. Where a supported framework limit exists, test that the structured-response correction path is included in the limit. Do not assume a graph recursion limit is an exact count of model correction attempts.
Host-managed recovery alternative#
For a finalization step that requires a stricter application-owned decision boundary, a compatible configuration may disable ToolStrategy's built-in error handling:
PYTHONstrict_finalizer = create_agent( model="openai:gpt-4o-mini", tools=[], response_format=ToolStrategy( StatusAnswer, handle_errors=False, ), )
This is an alternative to the preceding configuration, not another stage to run automatically. In a compatible environment, catch and classify only documented errors at the host boundary, inspect incomplete outcomes, and apply a limited response-only correction policy. Verify actual exceptions and surrounding middleware behavior. Do not catch every Exception or retry the entire action-capable agent indiscriminately.
4. Return sanitized and actionable correction feedback#
A correction message should tell the model what is wrong with its proposed output without exposing private input, hidden instructions, internal implementation details or unnecessary evidence.
Raw validation exceptions can include the original input value, unexpected keys, field values and custom error context. A message generated from str(error) may disclose sensitive data or repeat untrusted text back into the conversation. Avoid indiscriminate exception forwarding.
| Classification | Reviewed model-facing correction |
|---|---|
| Malformed JSON | Return one complete JSON object. |
| Schema mismatch | Match the declared response fields and types. |
| Multiple final responses | Return exactly one final response. |
| Unsupported claim with available trusted evidence | Use only verified evidence for the requested order. |
| Missing required evidence | Do not invent a value; use an approved unavailable or review outcome. |
| Permission denial or provider refusal | Do not attempt an alternate identity or bypass. Stop under policy. |
A useful correction can identify an approved field name or a stable validation category when doing so helps the model. Extract only allowlisted locations and normalized error codes from validation diagnostics. Do not include arbitrary unknown property names or error inputs. Sensitive application telemetry may require further redaction and access restrictions.
Correction feedback should remain distinct from authoritative evidence. An error message saying the status was unsupported does not prove which alternative status is correct. Supply the actual authorized observation through the intended evidence channel. If conflicting observations cannot be reconciled, escalate rather than prompt the model until it picks one.
5. Enforce a bounded correction loop#
An application can allow a small number of final-response attempts. Define the difference between total attempts and retries: an initial attempt plus one correction is two total generation attempts. Count all layers, including internal framework corrections, host regeneration and transport retry behavior, under an overall workload budget.
For example, a host that performs three attempts, each of which can internally perform four model calls, may generate up to twelve model calls before counting business-tool iterations or transport retries. If an additional transport layer retries each request, actual service attempts can be higher. These figures are illustrative, not measured LangChain behavior.
Prefer a single owner for correction policy where feasible. If using framework-managed feedback, enforce and measure a run-level budget that covers the resulting extra turns. If using host-managed correction, configure the framework appropriately so nested correction loops do not defeat the cap.
A finalization-only correction is usually easier to reason about than restarting an entire tool-enabled agent. The host retains verified evidence and permits the model to produce another representation of that evidence without executing business tools again.
Use a deadline and an output-token budget in production in addition to an attempt counter. Each correction consumes resources, and an invalid response can be large. Stop when remaining time is insufficient. Preserve cancellation and unexpected programming faults rather than disguising them as recoverable model output errors.
Repeatedly receiving the same error can indicate a schema incompatibility, an unclear task, an unsupported provider feature or a defective adapter. More attempts are not necessarily the solution. Stop, report the classified issue and investigate.
6. Handle malformed JSON, refusals and truncation as different outcomes#
A malformed complete candidate may be eligible for correction. If the application receives raw JSON, apply a size limit, parse with the appropriate strictness, reject ambiguous duplicate keys and nonstandard numeric constants where required, and then validate the resulting object. Do not use eval or execute generated code to repair a JSON response.
Do not repair arbitrary fragments by appending closing braces, guessing missing fields or choosing a duplicated field value. Those operations can transform ambiguous model text into a superficially valid but unsupported business result. An explicitly documented deterministic normalization may be acceptable if it preserves meaning and is independently tested, but it must not silently change the contract.
In a normal LangChain structured-response path, the provider adapter or framework may already have decoded JSON before the application sees a Python object. Duplicate-key detection cannot recover a duplicate after a permissive parser has discarded one occurrence. If raw-representation integrity matters, enforce it at the earliest boundary where the original bytes or text are accessible, and verify the adapter's behavior.
A provider refusal is different from malformed syntax. Preserve the actual refusal or policy outcome. Do not treat it as an instruction to try another model until one produces the prohibited result. Likewise, if generation is truncated, use the provider's documented completion metadata rather than infer completion from a string ending in a brace. A compatible application may approve a new response-only attempt with an appropriate output budget, but it must not accept a partial candidate as the final result.
The local example below chooses a conservative policy: refused and truncated candidates terminate the current finalization attempt sequence. This is an application decision, not a universal LangChain default.
7. Tested Python: bounded, sanitized response-only recovery#
The following executable example uses the actual Pydantic v2 library and Python's JSON parser. It implements a host-level finalization policy independent of LangChain. A scripted generator supplies normalized synthetic provider outcomes, so the tests do not depend on a provider or external credentials.
The generator is assumed to be response-only: it has no business tools, and the application has already established authorized evidence. A prior uncertain mutation blocks finalization and requires reconciliation.
PYTHONimport json from dataclasses import dataclass from typing import Literal from pydantic import BaseModel, ConfigDict, ValidationError class Answer(BaseModel): model_config = ConfigDict(strict=True, extra='forbid', frozen=True) order_id: str status: Literal['shipped', 'pending'] evidence_id: str class InvalidJSON(Exception): pass class EvidenceMismatch(Exception): pass def unique_pairs(pairs): result = {} for key, value in pairs: if key in result: raise InvalidJSON('duplicate key') result[key] = value return result def reject_constant(value): raise InvalidJSON('nonstandard number') def parse(raw): if not isinstance(raw, str) or len(raw.encode('utf-8')) > 4096: raise InvalidJSON('invalid payload size or type') try: return json.loads(raw, object_pairs_hook=unique_pairs, parse_constant=reject_constant) except (json.JSONDecodeError, RecursionError) as exc: raise InvalidJSON('invalid JSON') from exc def accept(raw, order_id, evidence): answer = Answer.model_validate(parse(raw)) if answer.order_id != order_id or evidence.get(answer.evidence_id) != (order_id, answer.status): raise EvidenceMismatch('unsupported claim') return answer @dataclass(frozen=True) class Candidate: kind: Literal['complete','multiple','refused','truncated','uncertain'] raw: str = '' @dataclass(frozen=True) class Outcome: code: str attempts: int answer: Answer | None = None FEEDBACK = {'malformed': 'Return one complete JSON object.', 'schema': 'Match the declared response fields and types.', 'multiple': 'Return exactly one final response.', 'evidence': 'Use only verified evidence for the requested order.'} def finalize(generate, order_id, evidence, *, max_attempts=2, effects_uncertain=False): if type(max_attempts) is not int or not 1 <= max_attempts <= 3: raise ValueError('invalid attempt budget') if effects_uncertain: return Outcome('reconcile', 0) feedback = None for attempt in range(1, max_attempts+1): item = generate(feedback) # response-only generation; no business tools if item.kind == 'refused': return Outcome('refused', attempt) if item.kind == 'truncated': return Outcome('truncated', attempt) if item.kind == 'uncertain': return Outcome('reconcile', attempt) if item.kind == 'multiple': code = 'multiple' elif item.kind == 'complete': try: answer = accept(item.raw, order_id, evidence) except InvalidJSON: code = 'malformed' except ValidationError: code = 'schema' except EvidenceMismatch: code = 'evidence' else: return Outcome('accepted', attempt, answer) else: raise RuntimeError('unrecognized provider outcome') feedback = FEEDBACK[code] return Outcome('review:' + code, max_attempts) class Script: def __init__(self, *items): self.items = iter(items) self.feedback = [] def __call__(self, feedback): self.feedback.append(feedback) return next(self.items) if __name__ == '__main__': evidence = {'E-1': ('O-1','shipped')} good = Candidate('complete','{"order_id":"O-1","status":"shipped","evidence_id":"E-1"}') malformed = Candidate('complete','{"order_id":') duplicate = Candidate('complete','{"order_id":"O-1","order_id":"O-2"}') wrong = Candidate('complete','{"order_id":"O-1","status":"pending","evidence_id":"E-1"}') schema = Candidate('complete','{"order_id":123,"secret":"SYNTHETIC-SECRET"}') def run(s, **kw): return finalize(s,'O-1',evidence,**kw) assert run(Script(good)).code == 'accepted' for candidate, code in [(malformed,'malformed'),(duplicate,'malformed'),(schema,'schema'),(wrong,'evidence'),(Candidate('multiple'),'multiple')]: s = Script(candidate,good) assert run(s).code == 'accepted' and s.feedback == [None, FEEDBACK[code]] s = Script(schema,schema) assert run(s) == Outcome('review:schema',2) assert 'SYNTHETIC-SECRET' not in str(s.feedback) for kind, code in [('refused','refused'),('truncated','truncated'),('uncertain','reconcile')]: s = Script(Candidate(kind),good) assert run(s) == Outcome(code,1) and len(s.feedback)==1 s = Script(good) assert run(s,effects_uncertain=True)==Outcome('reconcile',0) and not s.feedback assert run(Script(Candidate('complete',' '*4097)),max_attempts=1)==Outcome('review:malformed',1) assert run(Script(Candidate('complete','{"value":NaN}')),max_attempts=1)==Outcome('review:malformed',1) try: run(Script(good),max_attempts=0) except ValueError: pass else: raise AssertionError('invalid budget accepted') try: run(Script(Candidate('unknown'))) except RuntimeError: pass else: raise AssertionError('unknown outcome swallowed') assert Answer.model_validate(json.loads(wrong.raw)).status == 'pending' try: accept(wrong.raw,'O-1',evidence) except EvidenceMismatch: pass else: raise AssertionError('semantic mismatch accepted') print('17 checks passed')
Actual local execution:
17 checks passedThe script ran with Python 3.13.5 and Pydantic 2.13.5. The numbered message counts the primary assertions and exception checks across the fixtures; the final two checks separately establish that the incorrect status passes schema validation and fails the dedicated semantic acceptance boundary.
| Test group | Observed behavior |
|---|---|
| Valid first candidate | Accepted without correction |
| Malformed JSON | Approved correction message followed by accepted result |
| Duplicate JSON keys | Rejected as ambiguous representation |
| Schema mismatch | Reviewed schema feedback, then acceptance |
| Structurally valid incorrect claim | Dedicated evidence feedback, then acceptance |
| Multiple final candidates | Cardinality feedback, then acceptance |
| Repeated schema failure | Review after two total attempts |
| Sensitive fixture text | Not present in correction feedback |
| Provider refusal | Stops after one candidate |
| Truncation | Stops after one candidate |
| Uncertain outcome during finalization | Reconcile after one candidate |
| Uncertain external effect before finalization | No generation attempt |
| Oversized representation | Rejected |
| NaN constant | Rejected |
| Invalid attempt budget | Raises ValueError |
| Unknown normalized outcome | Raises RuntimeError |
| Independent semantic boundary | Valid enum value rejected by EvidenceMismatch |
The test deliberately distinguishes EvidenceMismatch from Pydantic ValidationError, so the semantic rejection is not accidentally satisfied by catching a superclass shared with schema validation. The wrong-status fixture is first shown to pass the Pydantic model and then independently rejected by the evidence check.
The example is intentionally limited. Candidate.kind values are synthetic normalized metadata; Python Literal does not validate a dataclass field at construction, and the policy rejects unrecognized values explicitly. A production adapter must obtain the true completion, refusal and cardinality information from a trusted provider/framework boundary. The test does not establish actual LangChain exception dispatch, real provider refusals, cancellation, timeouts, durable idempotency or reconciliation.
The raw input is limited to 4,096 UTF-8 bytes after encoding. A production boundary should enforce incoming byte limits before decoding and handle invalid Unicode, encoding failures and other supported parser exceptions. Very large integer literals and other parser-specific limits may raise errors beyond the explicitly handled classes; normalize those at a reviewed parser boundary. The example does not implement a general hardened parser or depth quota. The scripted generator can raise unexpected exceptions, which propagate. No network calls or external actions occurred.
The trusted evidence map is a synthetic fixture; it does not authenticate a caller or verify freshness. The correction policy assumes sufficient authorized evidence is available and that regeneration is truly response-only. A production host must enforce those prerequisites, stop when evidence is missing, and never let a model determine whether side effects are uncertain.
8. Preserve idempotency and authoritative outcomes#
Invalid final output can occur after a business action successfully commits. For example, an authorized support workflow might submit a request and receive a durable operation reference, then fail to generate its final structured report. Restarting the entire workflow could submit the request again.
The final response and the external operation have separate lifecycles.
This diagram assumes the service outcome is known. If an acknowledgement is lost, the host must query or reconcile the authoritative operation before reporting success or replaying a mutation. A final response error does not roll back an external transaction.
Use a stable idempotency identity bound to the authenticated principal, approved operation and canonical payload. The service should enforce uniqueness and payload consistency atomically. A generated tool-call ID may help trace an invocation but is not automatically a durable operation identity. Repeated finalization should not perform the external action again.
For a workflow where the outcome is already recorded, a deterministic host can often construct the final response without another model call. If the result requires natural-language synthesis or judgment, permit a restricted response-only model step and keep the accepted evidence immutable or appropriately revalidated.
For a failed or uncertain action, distinguish known rejection, known success, partial completion and unresolved outcome. Do not produce an arbitrary success status because a schema requires one. Use an approved incomplete envelope or review path when a successful response cannot be substantiated.
The Python example tests a non-replay policy decision by blocking its generator when effects are uncertain. It does not test a real idempotency store, transaction or external service.
9. Fallback and human escalation#
Fallback is useful only when it preserves the same acceptance and security requirements. If the provider rejects a schema before any business operation starts, an approved compatible strategy or provider may be eligible. If a final response is merely malformed, a reviewed bounded correction may be cheaper and simpler than switching models.
Do not allow a fallback to:
- Remove mandatory fields, weaken strictness or discard evidence requirements.
- Send sensitive data to a provider that has not been approved for the workload.
- Circumvent a provider refusal or application permission denial.
- Restart an action-capable agent after an ambiguous external outcome.
- Add a second unbounded correction loop.
The previous strategy-selection lesson (#302) defines the capability and performance decision framework. This lesson uses that same eligibility policy rather than designing an unrelated fallback strategy.
Human escalation is appropriate when required evidence is missing or conflicting, an external outcome remains unresolved, a meaningful approval is needed, or the correction budget has been exhausted. Preserve a concise, authorized review record: the task reference, failure category, approved evidence references, known operation outcome and requested reviewer decision. Do not expose raw private model input by default.
A reviewer must still have authority to perform any subsequent action. Escalation does not grant privileges or convert an invalid candidate into accepted data. If a reviewer resolves the task, validate the resulting consumer response under the same business contract.
10. Observability and production failure testing#
Collect distinct metrics for model output shape, correction behavior and real task success. For example, a system may have a high eventual schema-valid rate but a low evidence-supported acceptance rate. If metrics report only JSON parsing success, the semantic failures are hidden.
| Metric | What it reveals |
|---|---|
| First-pass schema-valid rate | Initial generation compatibility |
| Final accepted-result rate | Completed outputs satisfying the application contract |
| Correction attempts per task | Cost and error-loop amplification |
| Error category distribution | Parsing, schema, cardinality, evidence and provider issues |
| Refusal and truncation rates | Provider outcome characteristics |
| Budget exhaustion rate | Repeated failures or unsuitable configuration |
| Review and reconciliation rate | Unresolved business outcomes |
| Unauthorized or duplicated executions | Critical safety failures, not merely model errors |
| Latency and cost per accepted result | End-to-end operational efficiency |
Use explicit denominators. If 100 tasks initiate finalization, 90 produce valid schema objects on the first attempt and 95 ultimately produce accepted results, the initial schema-valid rate is 90% and the eventual accepted-result rate is 95%. The second number includes the consequences of all correction attempts; it is not an estimate of factual accuracy for all provider outputs. These numbers are hypothetical.
Record schema revision, effective strategy, framework and adapter version, safe correlation identifiers, normalized error category, attempt number, completion status and acceptance verdict. Use reviewed redaction for diagnostics. A log entry containing the raw ValidationError, model output or request state may disclose the very values withheld from correction feedback.
Test the actual integration after the deterministic policy passes:
| Failure fixture | Required acceptance condition |
|---|---|
| Invalid response-tool arguments | Observed structured validation error and bounded approved feedback |
| Multiple final-response tool calls | No arbitrary winner selected |
| Multiple legitimate business reads | Not misclassified as multiple final responses |
| Framework handle_errors disabled | Actual exception/outcome behavior observed at host boundary |
| Framework handle_errors enabled | Correction messages and total generation budget verified |
| Raw duplicate keys where raw JSON accessible | Ambiguous representation rejected |
| Unknown normalized provider outcome | Controlled operational fault, not fabricated success |
| Schema-valid unsupported status | Independent semantic rejection |
| Provider refusal | No bypass or unsupported fallback |
| Truncated candidate | No accepted partial result |
| Sensitive validation inputs | No raw-value disclosure through feedback, logs or traces |
| Exhausted time or attempt budget | Controlled review or incomplete outcome |
| Prior verified external commit | Finalization can be retried without duplicating action |
| Uncertain external commit | Reconciliation required before replay or success claim |
| Consumer serialization | Accepted result only; incomplete outcome handled explicitly |
Use a deterministic model substitute or scripted adapter where the installed framework supports it. Inspect real exception types, correlated error observations, state transitions and completion semantics. Then conduct separately approved synthetic provider integration tests. Do not infer live framework behavior from the standalone Python policy.
Interview-ready answer#
I treat invalid structured output as an unaccepted candidate and classify malformed representations, schema validation errors, multiple final responses, unsupported claims, refusals and incomplete generation separately. In compatible LangChain releases I can configure ToolStrategy.handle_errors and use StructuredOutputValidationError and MultipleStructuredOutputsError to provide reviewed correction feedback. I enforce a total attempt, time and cost budget independently of the framework's internal loop. I verify claims against trusted evidence and regenerate only the final response when safe, rather than replaying a business action. If the provider refuses, authorization fails, effects are uncertain or correction is exhausted, I stop, reconcile or escalate. I test both the deterministic recovery policy and the actual framework/provider integration before release.
Official documentation research leads and verification status#
- LangChain structured output
- LangChain agents
- LangChain middleware overview
- LangChain API reference
- Pydantic validation errors
- Pydantic models
- Pydantic strict mode
- Python JSON documentation
Authorized offline research exception applied. The official URLs are documentation research leads rather than live-accessed citations. The standalone Python recovery program was executed on Python 3.13.5 with Pydantic 2.13.5 and passed all 17 labeled test groups; the source includes additional supporting assertions. Local inspection confirmed langchain, langchain_core and langgraph were absent. The SDK integrations, actual structured-output exception behavior, provider refusal and truncation metadata, real business idempotency and current documentation were not verified. All fixtures are synthetic. Mermaid diagrams use triple-backtick fences; actual rendering and public website display were not verified.
References
- 1.LangChain structured outputdocs.langchain.com
- 2.LangChain agentsdocs.langchain.com
- 3.LangChain middleware overviewdocs.langchain.com
- 4.LangChain API referencereference.langchain.com
- 5.Pydantic validation errorsdocs.pydantic.dev
- 6.Pydantic modelsdocs.pydantic.dev
- 7.Pydantic strict modedocs.pydantic.dev
- 8.Python JSON documentationdocs.python.org
Related questions
Explore other topics:Forward Deployed EngineeringLarge Language ModelsRetrieval-Augmented GenerationMLOps