AI AgentsLangChain

How do you return structured content from a tool?

Question 296 of 324 · Updated

On this page

Direct answer#

In LangChain, a tool can return a serializable structured value, such as a dictionary built from a validated Pydantic result model. When the application needs richer data than the model should receive, configure the tool with response_format="content_and_artifact" and return a two-element tuple of model-facing content and an application artifact. In a compatible tool-call execution path, LangChain can construct a ToolMessage carrying the content, artifact and tool-call correlation ID.

The tool's input schema validates the request. Its result schema validates the observation. Neither guarantees that the result is factually correct, authorized or current. Validate those domain properties before presenting evidence to the model or application.

The earlier tool decorator lesson (#291) covers basic return values, #293 covers input validation, #295 covers persistent state, and the general tool-output validation lesson (#102) covers output trust. This lesson focuses on the concrete LangChain tool-result representation, message correlation and separation of model content from application artifacts. Agent-level final structured responses are covered in later lessons.

1. Distinguish the three output contracts#

A tool that estimates fictional delivery costs might return a quote total, an itemized breakdown and provenance metadata. Different consumers need different representations.

LayerConsumerExample
Domain resultTrusted serviceVerified total, currency and pricing-catalog version
Tool observationModelConcise JSON or text describing the verified quote
Application artifactAuthorized host/UITyped breakdown, document reference or evidence metadata
Final agent responseUser or downstream applicationExplanation or separately validated response object

A common mistake is returning a complete service response directly to the model. That response may contain internal identifiers, private account fields, headers, large arrays or credentials that are irrelevant to the task.

Instead, validate the domain result, project an explicit allowlist of model-visible fields, and separately construct the artifact that the authorized application actually needs. An artifact is not a place to hide arbitrary sensitive data: it may be retained in execution state, traced, serialized or exposed by an application. Apply a suitable access and retention policy to both channels.

Loading diagram…

The diagram represents the intended information flow. The exact transport and persistence behavior depend on the installed LangChain runtime and provider adapter.

2. Return a dictionary for simple structured observations#

A small serializable dictionary is useful when all its fields are appropriate for model consumption.

PYTHON
from langchain.tools import tool @tool def delivery_quote(parcels: int) -> dict: """Return a fictional delivery estimate without creating a shipment.""" if type(parcels) is not int or not 1 <= parcels <= 10: raise ValueError("parcel count out of range") return { "status": "estimate_only", "currency": "USD", "cost_cents": 400 + 150 * parcels, } # Direct invocation in a compatible environment: result = delivery_quote.invoke({"parcels": 3}) print(result)

The intended logical result is an estimate of 850 cents (USD 8.50), not a completed purchase or shipment. The pricing is fictional.

The default tool response format commonly treats the function return value as content. Direct invocation with an argument dictionary may return the logical Python value. During a model-generated tool call, the runtime may wrap or serialize that value into a ToolMessage. Do not assume every provider receives a Python dictionary as a native structured object: it may receive serialized text or supported content blocks.

Verification note: LangChain, langchain_core and langgraph were not installed locally. All SDK examples are illustrative and unexecuted. The actual Pydantic implementation in section 6 was executed using Python 3.13.5 and Pydantic 2.13.5. Check the installed API and provider integration before running the SDK snippets.

A function's return annotation documents the intended type but does not automatically guarantee that the decorator validates all outputs. For example, a function annotated as returning a dictionary can still return an invalid string in ordinary Python. Use explicit output validation at the service or tool boundary.

3. Use a Pydantic response model for the tool's own result#

Pydantic is useful for defining the tool's result contract independently of its input schema. Consider a fictional quotation with a stable reference, integer monetary amount and source identifier.

PYTHON
from typing import Literal from pydantic import BaseModel, ConfigDict, Field class QuoteResult(BaseModel): model_config = ConfigDict(strict=True, extra="forbid") quote_id: str = Field(pattern=r"^Q-[0-9]+$") currency: Literal["USD"] cost_cents: int = Field(ge=0, le=100000) source_ref: str = Field(pattern=r"^catalog:[0-9]+$")

This example expresses the result shape. Use model_validate on the proposed result, then choose an appropriate serialization method:

  • model_dump() returns a Python representation that may still contain non-JSON-native values.
  • model_dump(mode="json") produces a JSON-compatible representation for supported field types.
  • model_dump_json() produces a JSON string.

The standalone test in section 6 uses the same result constraints. The schema does not independently establish that the quote belongs to the caller or that the source reference points to an approved, current catalog. The application must verify those facts against trusted evidence.

For currency, prefer integer minor units or an appropriately validated decimal representation. Avoid converting exact monetary values into floating-point numbers without considering rounding and units. If serializing Decimal, dates, UUIDs or other special values, document the intended wire representation and test round-trip behavior.

Do not confuse a tool response model with create_agent(response_format=SomeSchema). The latter configures an agent-level structured response strategy in compatible releases. It does not automatically validate every tool's return value. A tool's response_format option and an agent's response_format option serve different purposes.

4. ToolMessage and response_format="content_and_artifact"#

When the host needs more data than the model, a supported LangChain tool can return content and artifact separately.

PYTHON
from langchain.tools import tool @tool(response_format="content_and_artifact") def quote_with_breakdown(quote_id: str) -> tuple[str, dict]: """Read a fictional quote and return its total with an itemized artifact.""" if quote_id != "Q-17": return ( '{"status":"unavailable"}', {"schema_version": 1, "status": "unavailable"}, ) return ( '{"quote_id":"Q-17","currency":"USD",' '"cost_cents":850,"source_ref":"catalog:3"}', {"schema_version": 1, "quote_id": "Q-17", "source_ref": "catalog:3", "breakdown_cents": [400, 450]}, )

The tool returns exactly two values: the content intended for the model and the application artifact. The application can use the itemized amounts for a quote-detail UI without asking the model to reproduce them. The example uses fixed synthetic data, not a real authorization system.

To inspect the artifact through a compatible tool invocation path, supply a structured tool-call envelope rather than only a plain argument dictionary:

PYTHON
from langchain_core.messages import ToolMessage message = quote_with_breakdown.invoke({ "type": "tool_call", "id": "call-demo-1", "name": "quote_with_breakdown", "args": {"quote_id": "Q-17"}, }) assert isinstance(message, ToolMessage) assert message.tool_call_id == "call-demo-1" print(message.content) print(message.artifact)

This is an illustrative SDK test to run after installing a compatible version. It was not executed locally. Verify the accepted tool-call envelope and return type in the installed release. In modern supported tool implementations, the tool-call ID permits construction of the correlated ToolMessage. A bare invocation such as invoke({"quote_id":"Q-17"}) may return only the content instead of the full message and artifact.

A ToolMessage can also be constructed explicitly in a custom orchestration implementation, provided the host preserves the required message sequence and correlation:

PYTHON
from langchain_core.messages import ToolMessage observation = ToolMessage( content='{"quote_id":"Q-17","cost_cents":850,"currency":"USD"}', artifact={"schema_version": 1, "breakdown_cents": [400, 450]}, tool_call_id="call-demo-1", )

Use the actual tool-call ID from the model response in real code. Do not fabricate a correlation ID or replace it with the invoice ID, quote ID or request ID. In a normal create_agent tool-node path the runtime commonly constructs and correlates the message for you; avoid wrapping an already correlated result twice.

Loading diagram…

The artifact is intended for application use rather than inclusion in the model's tool-response content. Verify the actual provider conversion and tracing behavior. Custom middleware, serializers or message transformations could deliberately or accidentally expose artifact values. The artifact field is not an encrypted vault or independent authorization barrier.

5. Choose a return format deliberately#

Return patternBest forWhat to verify
Short stringSimple textual observationEvidence, length and clear success/failure semantics
Dictionary or JSON stringSmall typed recordsSerialization, required fields, units and provider representation
Validated Pydantic projectionBusiness result with a stable schemaExplicit output validation and serialization
Content and artifact tupleCompact observation plus richer application dataActual ToolMessage behavior, correlation and artifact access
Supported content blocksMultimodal or provider-specific observationsContent types, size and adapter compatibility
Command state updateExplicit graph-state transitionState schema, reducers and required tool observation

Use ordinary content when the model needs all the returned fields. Use content and artifact when an authorized non-model consumer needs separate information. Use Command when the intended operation is to update graph state, as discussed in #295. The artifact itself does not automatically update state or persist a record across threads.

Avoid returning raw file bytes or very large tables merely because the artifact field supports a Python object in a particular runtime. Prefer a small validated descriptor containing a durable authorized reference, content type, size, checksum and version when the application has an appropriate artifact service. Reauthorize retrieval at access time. An unguessable reference is not a substitute for access control.

A checksum can detect accidental changes to a known byte sequence; it does not authenticate the source by itself. Use trusted source identity, verified transport and signed or otherwise approved provenance when the risk warrants them.

6. Tested Python implementation: validate, project and separate output channels#

The following executable example uses actual Pydantic v2. It deliberately returns a JSON string and a JSON-compatible dictionary, matching the intended shape of a content-and-artifact tool function without pretending to implement LangChain's runtime. All records are synthetic.

PYTHON
import json from typing import Literal from pydantic import BaseModel, ConfigDict, Field, ValidationError class Observation(BaseModel): model_config = ConfigDict(strict=True, extra='forbid') quote_id: str = Field(pattern=r'^Q-[0-9]+$') currency: Literal['USD'] cost_cents: int = Field(ge=0, le=100000) source_ref: str = Field(pattern=r'^catalog:[0-9]+$') class Artifact(BaseModel): model_config = ConfigDict(strict=True, extra='forbid') schema_version: Literal[1] = 1 quote_id: str source_ref: str breakdown_cents: list[int] def package(raw, expected_id, allowed_sources): public = Observation.model_validate({k: raw[k] for k in Observation.model_fields if k in raw}) artifact = Artifact(quote_id=public.quote_id, source_ref=public.source_ref, breakdown_cents=raw['breakdown_cents']) if public.quote_id != expected_id or public.source_ref not in allowed_sources: raise ValueError('evidence mismatch') if any(x < 0 for x in artifact.breakdown_cents) or sum(artifact.breakdown_cents) != public.cost_cents: raise ValueError('invalid breakdown') return public.model_dump_json(), artifact.model_dump(mode='json') raw = {'quote_id':'Q-17', 'currency':'USD', 'cost_cents':850, 'source_ref':'catalog:3', 'breakdown_cents':[400,450], 'internal_token':'SYNTHETIC-SECRET'} content, artifact = package(raw, 'Q-17', {'catalog:3'}) assert json.loads(content)['cost_cents'] == 850 assert artifact['breakdown_cents'] == [400,450] assert artifact['schema_version'] == 1 assert 'breakdown_cents' not in json.loads(content) assert 'SYNTHETIC-SECRET' not in content and 'SYNTHETIC-SECRET' not in json.dumps(artifact) assert Observation.model_validate_json(content).quote_id == artifact['quote_id'] for changed, expected, sources, error in [ ({'cost_cents':'850'}, 'Q-17', {'catalog:3'}, ValidationError), ({'cost_cents':-1}, 'Q-17', {'catalog:3'}, ValidationError), ({'currency':'EUR'}, 'Q-17', {'catalog:3'}, ValidationError), ({}, 'Q-18', {'catalog:3'}, ValueError), ({}, 'Q-17', {'catalog:4'}, ValueError), ({'breakdown_cents':[400,449]}, 'Q-17', {'catalog:3'}, ValueError), ({'breakdown_cents':[-1,851]}, 'Q-17', {'catalog:3'}, ValueError), ({'breakdown_cents':[400,'450']}, 'Q-17', {'catalog:3'}, ValidationError), ]: try: package({**raw, **changed}, expected, sources) except error: pass else: raise AssertionError('invalid result accepted') print('14 checks passed') print(content, artifact)

Actual local execution on Python 3.13.5 and Pydantic 2.13.5 printed:

14 checks passed
{"quote_id":"Q-17","currency":"USD","cost_cents":850,"source_ref":"catalog:3"} {'schema_version': 1, 'quote_id': 'Q-17', 'source_ref': 'catalog:3', 'breakdown_cents': [400, 450]}

The six successful checks verify exact cost, artifact breakdown, schema revision, separation of the breakdown from public content, absence of the synthetic sensitive field from both outputs, and consistency of quote IDs after a round trip through JSON. Eight negative cases verify rejection of coercible strings, negative totals, wrong currency, mismatched requested quote, unapproved source, inconsistent breakdown, negative components and improperly typed breakdown entries.

The source allowlist and expected quote identifier must be supplied by trusted application code after authorization. Matching an allowlisted string does not prove that a malicious upstream service actually used that catalog. In production, verify authoritative source records and freshness. The example does not authenticate a caller, enforce complete privacy policies, bound the size of arbitrary raw input or validate the actual LangChain message transport. Missing breakdown_cents raises KeyError; normalize such malformed upstream failures at the service boundary before returning a sanitized observation. An empty breakdown with zero cost is permitted by this example; constrain list length and nonemptiness if the real contract requires it.

Explicit projection is safer than serializing raw and attempting to remove a handful of known secret keys. A new field added upstream is not automatically exposed. Nevertheless, allowlisted string values can themselves contain sensitive information or malicious instructions. Validate their semantics, formats and authorization rather than relying only on the field name.

7. Preserve provenance and evidence#

Tool results often serve as evidence for subsequent reasoning. A useful observation identifies the exact operation and source without exposing internal credentials or unrelated records.

Provenance fieldPurpose
Stable result referenceIdentifies the record or calculation
Source reference and revisionIdentifies approved data used to generate the result
Observed timestamp or validity intervalHelps evaluate freshness
Schema revisionLets the host validate the representation
Correlation IDAssociates a ToolMessage with a particular model tool call
Domain operation IDTracks a durable external operation when applicable

Do not treat these identifiers as interchangeable. A correlation ID links messages in the model conversation; a business operation ID can identify a durable transaction; a source reference identifies evidence. A generated source identifier alone does not verify the underlying source.

For search or retrieval tools, return bounded excerpts with stable source references. Keep the full authorized document in an artifact service if the application needs it. A model should not cite a document that the tool did not actually retrieve or claim a source supports a statement simply because a string looks like a citation.

For write-capable tools, distinguish requested, accepted, committed, verified and uncertain outcomes. A structured result saying success=true is only useful when it reflects the authoritative service's actual outcome. Never convert a timeout into success or retry an uncertain write without reconciliation.

8. Validate output before it reaches either consumer#

Loading diagram…

Validate and enforce authorization before exposing the result. Bound the number of records, content length and artifact size. If a service returns partial results, make that status explicit and do not silently imply completeness. Check the requested identifier, expected tenant and relevant business invariants. For example, the total of line items must equal the quoted price when that is the defined calculation.

Treat retrieved text, HTML, OCR, documents and tool observations as untrusted data. An external result that says "ignore the system instructions" does not gain instruction authority. Separating content and artifact reduces unnecessary exposure but does not neutralize indirect prompt injection. Use independent tool authorization and review any component that promotes stored text into instructions.

If a tool cannot produce a valid result, return a bounded error observation or propagate a controlled error using the installed runtime's supported mechanism. Avoid raw exception text that may include secret input values, connection details or private records. Detailed exception routing and recovery are covered in the next lesson.

9. Numerical example: avoid sending unnecessary artifact data#

Suppose a retrieval tool returns a 3,000-token document and the model needs only a 300-token approved excerpt. The application can retain a secure document reference and send only the excerpt and source metadata. If the difference of 2,700 logical tokens is included in four model invocations, the hypothetical reduction is 10,800 input tokens per run. At an illustrative uncached rate of USD 2 per million input tokens, that represents USD 0.0216 in gross input cost per run.

These figures are hypothetical, not current provider pricing or a measured LangChain benchmark. Actual tokenization, repeated context transmission, prompt caching and billing depend on the provider and runtime. An artifact can still have storage, processing and access-control costs. Never remove evidence essential to correct reasoning merely to reduce token usage.

10. Production integration tests#

A local Pydantic test establishes the application's result contract. An actual LangChain integration test must establish the separate message and provider contracts.

TestAcceptance criterion
Direct invocationReturns expected logical content for valid synthetic arguments
Tool-call envelope invocationProduces the expected ToolMessage and actual correlation ID
Content and artifact tupleBoth fields appear in the supported application representation
Provider conversionOnly approved model-facing fields enter the request
Sensitive sentinelNever appears in model content, unauthorized artifacts or exported traces
Invalid upstream responseNo successful or misleading observation is returned
Unauthorized artifact accessDenied even with a valid artifact reference
Serialization and resumeSupported fields survive intended persistence round trips
Oversized or partial resultControlled truncation, pagination or explicit incomplete outcome
Provenance mismatchRejected before claiming a grounded result
Multiple tool callsEach result is associated with the correct request

Use a deterministic scripted model or mock transport to inspect the actual provider-bound payload where supported. Test malformed content blocks and invalid tuple shapes as well as successful output. With approved live integration tests, use synthetic records and a bounded budget.

Track response-schema revision, tool implementation revision, provider integration version and fixture dataset. Monitor validation failures, result sizes, artifact retrieval denials, serialization errors, mismatched evidence and unsupported final claims. Log safe correlation metadata, not entire raw responses by default.

Interview-ready answer#

I return a small serializable dictionary or explicitly validated Pydantic result from a LangChain tool. When the application needs richer data than the model, I configure the tool with response_format="content_and_artifact" and return a content/artifact pair. In a supported tool-call execution path, the runtime creates a ToolMessage correlated with the actual call ID. I validate the result and its source, project approved fields, enforce authorization on both channels, and test serialization and provider conversion. I never assume that a return annotation validates outputs, that artifacts are secret by default, or that tool output configuration is the same as agent-level structured response configuration.

Official documentation research leads and verification status#

Authorized offline research exception applied. These official URLs are documentation research leads, not live-accessed citations. The standalone result-packaging code was executed on Python 3.13.5 and Pydantic 2.13.5; all 14 checks passed. LangChain, langchain_core and langgraph were absent. The SDK examples, actual ToolMessage/artifact transport, provider conversion, live documentation and public site rendering remain unverified. Mermaid blocks use triple-backtick fences; rendering was not tested. No real customer records or provider calls were used.

References

  1. 1.
    LangChain toolsdocs.langchain.com
  2. 2.
    LangChain messagesdocs.langchain.com
  3. 3.
    LangChain agentsdocs.langchain.com
  4. 4.
    LangChain structured outputdocs.langchain.com
  5. 5.
    LangChain API referencereference.langchain.com
  6. 6.
    Pydantic serializationdocs.pydantic.dev
  7. 7.
    Pydantic modelsdocs.pydantic.dev
  8. 8.

Related questions

Explore other topics:Forward Deployed EngineeringLarge Language ModelsRetrieval-Augmented GenerationMLOps

Machinoai Logo
Machinoai

Your edge in the AI era. Deep dives into machine learning concepts, paper explainers, verified industry jobs, and developer tools.

© 2026 Machinoai. All rights reserved.