AI AgentsLangChain
How do you use message objects and content blocks?
Question 306 of 324 · Updated
On this page
- Direct answer
- 1. Think in envelopes, blocks and application data
- 2. Use BaseMessage and concrete message objects
- 3. Understand content versus content_blocks
- 4. Inspect message metadata without confusing it with content
- 5. Handle tool proposals and results as typed objects
- 6. Serialize messages for the right purpose
- 7. Tested Python implementation: text-block normalization, versioned projection and correlation
- 8. Design a safe provider interoperability boundary
- 9. Validate content and build separate consumer projections
- Practical example: projecting rather than flattening
- 10. Production verification and observability
- Common mistakes
- Interview-ready answer
- Official documentation research leads and verification status
Direct answer#
Use LangChain's typed message objects to represent the conversation, and use content blocks to represent the individual pieces of a message's payload. BaseMessage supplies the common message envelope; concrete classes such as HumanMessage, AIMessage and ToolMessage add role-specific semantics. The content field can hold text or a list of supported content representations. In modern releases, content_blocks provides a standardized view of supported content, helping application code work across provider-specific formats.
Do not reduce every message to its text. Tool proposals, tool results, message identity, usage metadata, provider extensions and application artifacts may carry important information outside a plain text field. Preserve the full supported execution representation for runtime use, while creating a separate, validated, permission-aware projection for display and downstream consumers.
This lesson builds on LangChain #25 (AI Agents #305), which explains conversation history and message accumulation, and #16 (#296), which separates tool content from artifacts. It focuses on message representation, normalization, serialization and interoperability. The next two lessons examine message roles and multimodal input in detail; this lesson introduces those topics only where needed to explain the object structure.
1. Think in envelopes, blocks and application data#
A conversation is not merely a list of strings. A model response can include a short text statement, a structured tool proposal and information about the provider request. A tool response can contain evidence for that proposal, a correlation identifier and an application artifact.
A fictional order-support assistant might say "I will check the order" while requesting a read-only lookup of O-1. The UI may display that text, but the executor must inspect the tool proposal rather than treating the sentence as proof that a lookup has already occurred.
| Layer | Examples | Responsibility |
|---|---|---|
| Message envelope | Message class, message ID, name | Identify the message and its role |
| Content | String or list of blocks | Represent the message payload |
| Standardized blocks | Text, supported media or reasoning representations | Offer a common content view |
| Tool-call structure | Tool name, arguments, call ID | Express a proposed operation |
| Tool response | Content and tool_call_id | Associate an observation with a proposal |
| Metadata | Response metadata, token usage, provider extensions | Record execution information where available |
| Application projection | Validated status, display text, evidence references | Serve a specific authorized consumer |
The exact boundaries are representation-dependent. A provider may encode a tool request within its content blocks, while the adapter also exposes normalized tool_calls on AIMessage. Do not execute both representations of the same proposal.
The diagram shows conceptual views, not an exact memory layout. A standardized view may be computed from the original content. Converting a provider representation to a common format is not necessarily lossless.
2. Use BaseMessage and concrete message objects#
In modern LangChain Python, the message API is commonly available through langchain.messages or langchain_core.messages. The following examples use langchain_core.messages. BaseMessage is the shared base representation, while the appropriate concrete class conveys the message's meaning.
PYTHONfrom langchain_core.messages import BaseMessage, HumanMessage, AIMessage user = HumanMessage( content="Check fictional order O-1.", id="message-user-1", ) assistant = AIMessage( content="I can check that order.", id="message-ai-1", ) def describe(message: BaseMessage) -> dict: return { "id": message.id, "type": message.type, "content": message.content, } print(describe(user)) print(describe(assistant))
These are illustrative SDK examples. The local environment has Python 3.13.5 but does not contain langchain, langchain_core or langgraph. The SDK snippets in this article were not executed or checked against an installed version. The independent standard-library implementation in section 7 was executed successfully. Confirm the installed package imports, object fields, block types and adapter behavior before integrating them.
For a normal chat model call, a compatible model can accept a list of message objects rather than a concatenated prompt string. Modern agent input also commonly accepts supported message shorthand, such as dictionaries with role and content. The framework may convert shorthand into message objects internally. For example:
PYTHONfrom langchain_core.messages import HumanMessage # Illustrative: agent is a previously configured create_agent instance. state = agent.invoke({ "messages": [HumanMessage(content="Check fictional order O-1.")] }) messages = state["messages"]
Do not send arbitrary message objects from a browser as authoritative runtime state. Trusted application code constructs the appropriate user-message envelope and restores authorized execution history. The next lesson explains role distinctions and instruction authority in detail.
3. Understand content versus content_blocks#
The content field can be a string or a list of supported block representations, depending on the message type, framework release and provider. A list allows a message to contain several ordered pieces rather than one flattened text value.
Consider a text-only example with two separate parts. Although both are textual, keeping them separate can preserve boundaries relevant to rendering or processing.
PYTHONfrom langchain_core.messages import HumanMessage plain = HumanMessage(content="Read the fictional order status.") parts = HumanMessage(content=[ {"type": "text", "text": "Order: O-1"}, {"type": "text", "text": "Question: current status"}, ]) # Modern message API: inspect the standardized block view. for block in parts.content_blocks: if block.get("type") == "text": print(block["text"])
In a compatible modern release, the content_blocks property exposes a standardized view of supported content. A plain string can be represented as a text block. Provider-native content may be normalized to supported standard block types; unsupported or nonstandard material may remain represented through extension or nonstandard forms. Check the actual message and adapter contract.
Do not assume that content_blocks is always a complete substitute for content, additional_kwargs or role-specific fields. Certain providers encode information in forms that cannot be faithfully mapped into a universal representation. Some integrations may retain original provider data alongside normalized fields. The supported conversion path, block keys and extension handling can change across releases.
Some modern integrations support an output_version option such as content_blocks-related versioned output, including configurations commonly described as v1. That controls representation where supported; it is not required merely to inspect content_blocks. Verify the exact installed API and configuration rather than blindly copying the option. Existing applications may expect provider-native content and require a migration before changing serialized representation.
| Representation | Use it for | Avoid assuming |
|---|---|---|
| content | Original supported message payload | Always a string |
| content_blocks | Standardized inspection and processing | Every provider extension is losslessly normalized |
| Text-only projection | Chat UI or downstream text consumer | Contains all execution evidence |
| Provider-specific representation | Adapter-level operations requiring exact features | Portable across unrelated providers |
The next multimodal lesson covers image, audio, file and media constraints. Here the central principle is that content can be heterogeneous and must be interpreted according to its block type. An application that only supports text should explicitly reject or handle other block types, not convert arbitrary dictionaries into visible text.
4. Inspect message metadata without confusing it with content#
The common message envelope and concrete message classes can expose metadata fields. Typical modern message interfaces include:
| Field | Purpose |
|---|---|
| id | Optional message identity |
| name | Optional message name or source label |
| response_metadata | Provider response details, such as model or completion information where supplied |
| additional_kwargs | Extra or provider-specific information |
| usage_metadata on AIMessage | Normalized usage information where supplied |
| tool_calls on AIMessage | Normalized model-proposed tool calls |
| invalid_tool_calls on AIMessage | Tool-call parsing failures where available |
| tool_call_id on ToolMessage | Correlates a result with a proposal |
| artifact on ToolMessage | Separate application-facing data where supported |
These fields are version- and class-dependent. Token usage may be absent, partial, or have provider-specific accounting semantics. Do not infer billing solely from an optional metadata field. Completion metadata can also vary: an explicit refusal, truncation or unfinished response must be interpreted under the selected provider contract.
Metadata is not automatically trustworthy authority. A model-generated identifier, tool argument or claim does not become authenticated simply because it occupies a structured field. Separate application-owned identity and authorization from provider-supplied data.
Likewise, do not publish raw additional_kwargs or response_metadata by default. They can contain provider details or sensitive content. Only include fields that the consumer needs and is allowed to access. Reasoning or internal content blocks should not automatically be shown to users; use an approved display policy and supported user-facing content.
5. Handle tool proposals and results as typed objects#
A modern AIMessage may expose tool_calls separately from content. Each normalized tool call generally includes a name, arguments and an identifier. This structure describes a proposal, not an executed action.
PYTHONfrom langchain_core.messages import AIMessage, ToolMessage proposal = AIMessage( content="", tool_calls=[ {"name": "read_order", "args": {"order_id": "O-1"}, "id": "call-1", "type": "tool_call"}, ], ) # Fictional verified result; production dispatch must independently # validate the actual proposal, authorization and domain result. observation = ToolMessage( content='{"order_id":"O-1","status":"shipped"}', tool_call_id="call-1", ) assert observation.tool_call_id == proposal.tool_calls[0]["id"]
The assertion is illustrative and was not run against LangChain locally. In real execution, use the actual model-provided call ID, not a guessed ID or the message ID. The business operation may also have its own durable logical operation identity; a tool-call ID is not automatically an idempotency key.
An assistant message can have empty textual content while containing a valid tool proposal. A text-only filter that drops all empty-content messages can destroy the execution sequence. Conversely, an assistant message can contain both text and tool calls, depending on the provider. Neither text nor metadata alone determines whether the turn has completed.
Check invalid_tool_calls where the selected integration exposes it. Malformed tool arguments must not be executed by guessing their intended values. Reject, request a bounded correction or propagate the appropriate controlled failure according to the runtime policy. Validate the actual tool name, argument schema, current resource authorization and operation safety before dispatch.
This is an illustrative flow, not a promise of exact internal graph execution. In a normal create_agent path, the runtime commonly handles message construction and correlation. Do not dispatch the same proposal independently a second time.
6. Serialize messages for the right purpose#
Modern LangChain provides message serialization helpers commonly exposed as messages_to_dict and messages_from_dict. They convert supported message objects to and from a framework representation. They are distinct from provider request serialization and are not a universal, permanently stable wire format.
PYTHONimport json from langchain_core.messages import ( HumanMessage, AIMessage, messages_to_dict, messages_from_dict, ) original = [ HumanMessage(content="Fictional order O-1", id="m1"), AIMessage(content="I can inspect that reference.", id="m2"), ] encoded = json.dumps(messages_to_dict(original)) restored = messages_from_dict(json.loads(encoded)) assert restored[0].id == "m1" assert restored[1].content == original[1].content
This SDK round-trip is illustrative and unexecuted. Real messages can contain provider objects, artifacts or extension fields that are not directly JSON-serializable. A simple json.dumps on every possible message is not a guaranteed persistence strategy. Check supported framework serializers, versions, allowed types and retention policies. Avoid unsafe arbitrary-object deserialization of untrusted data.
Choose the representation based on the consumer:
- Runtime persistence requires the supported execution representation, including relevant message identity and correlation.
- A display API needs a small authorized projection of user-facing content.
- A provider adapter needs the correct supported request format, not merely a stored framework dictionary.
- An audit or evidence system may require independent operation identities, trusted timestamps and immutable domain records.
The prior history lesson explains how checkpointing retains messages across turns. This lesson does not propose replacing a graph checkpointer with a JSON file. The tested application format below is intentionally narrower than the framework's execution representation.
7. Tested Python implementation: text-block normalization, versioned projection and correlation#
This standalone program defines a limited text-only application contract. It accepts plain text or explicitly supported text blocks, preserves their order, rejects unsupported shapes, and serializes a versioned display projection. It separately verifies the correspondence between proposed call IDs and returned text observations.
The code is not a LangChain implementation or a generic provider adapter. Its restrictive block schema is a deliberate application choice. A real application may support additional fields or block types only after reviewing their meaning and handling requirements.
PYTHONimport json, sys, importlib.util from dataclasses import dataclass @dataclass(frozen=True) class Text: text: str def normalize(content): if isinstance(content, str): content = [{'type': 'text', 'text': content}] if not isinstance(content, list) or len(content) > 16: raise ValueError('invalid content') result = [] for block in content: if not isinstance(block, dict) or set(block) != {'type', 'text'} or block['type'] != 'text': raise ValueError('unsupported block') value = block['text'] if not isinstance(value, str) or len(value) > 2000: raise ValueError('invalid text') result.append(Text(value)) return tuple(result) def encode(message_id, content): if not isinstance(message_id, str) or not message_id: raise ValueError('invalid ID') return json.dumps({'version': 1, 'id': message_id, 'blocks': [{'type': 'text', 'text': b.text} for b in normalize(content)]}, ensure_ascii=True, allow_nan=False) def decode(raw): item = json.loads(raw) if not isinstance(item, dict) or set(item) != {'version','id','blocks'} or type(item['version']) is not int or item['version'] != 1: raise ValueError('unsupported envelope') if not isinstance(item['id'], str) or not item['id']: raise ValueError('invalid ID') if not isinstance(item['blocks'], list): raise ValueError('invalid blocks') return item['id'], normalize(item['blocks']) def correlate(calls, results): if not all(isinstance(x, str) and x for x in calls) or len(set(calls)) != len(calls): raise ValueError('invalid calls') by_id = {} for call_id, content in results: if call_id not in calls or call_id in by_id: raise ValueError('unexpected result') by_id[call_id] = normalize(content) if set(by_id) != set(calls): raise ValueError('missing result') return tuple((c, by_id[c]) for c in calls) def reject(fn): try: fn() except ValueError: return raise AssertionError('expected rejection') assert normalize('hello') == (Text('hello'),) assert normalize([{'type':'text','text':'A'}, {'type':'text','text':'B'}]) == (Text('A'),Text('B')) assert normalize([]) == () assert decode(encode('m1','नमस्ते')) == ('m1',(Text('नमस्ते'),)) assert correlate(['c1','c2'], [('c2','B'),('c1','A')]) == (('c1',(Text('A'),)),('c2',(Text('B'),))) for bad in [42, [{'type':'reasoning','text':'private'}], [{'type':'text','text':3}], [{'type':'text','text':'x','extra':1}], [{'type':'text','text':'x'*2001}], [{'type':'text','text':'x'}]*17]: reject(lambda: normalize(bad)) reject(lambda: decode('{"version":2,"id":"m1","blocks":[]}')) reject(lambda: correlate(['c1','c1'], [('c1','A')])) reject(lambda: correlate(['c1'], [('c2','B')])) reject(lambda: correlate(['c1'], [('c1','A'),('c1','B')])) reject(lambda: correlate(['c1','c2'], [('c1','A')])) print('16 checks passed') print(sys.version.split()[0]); print({p: importlib.util.find_spec(p) is not None for p in ['langchain','langchain_core','langgraph']})
Actual local execution:
16 checks passed
3.13.5
{'langchain': False, 'langchain_core': False, 'langgraph': False}| Test | Verified behavior |
|---|---|
| Plain text | Normalized into one text block |
| Multiple blocks | Preserves block order |
| Empty block list | Returns an empty projection |
| Unicode round-trip | Preserves original text and message identifier |
| Out-of-order tool results | Associates results by call ID and returns proposal order |
| Non-string/non-list payload | Rejected |
| Reasoning block | Rejected by this text-only contract |
| Non-string text | Rejected |
| Unexpected block fields | Rejected |
| Oversized block | Rejected |
| Excessive block count | Rejected |
| Unknown envelope version | Rejected |
| Duplicate proposal ID | Rejected |
| Unknown result ID | Rejected |
| Duplicate result ID | Rejected |
| Missing result | Rejected |
The test verifies the exact application format, not LangChain's BaseMessage, content_blocks conversion, provider tool-call parsing or SDK serialization. It uses no provider calls. It demonstrates a narrow projection and not a complete model-facing history: roles, metadata, non-text blocks and artifacts are deliberately omitted. The resulting display record must never be used as a replacement for an execution checkpoint.
The correlation function assumes finite sequences of well-shaped result pairs and string proposal IDs. It checks a completed batch, not streaming fragments or incomplete batches. The returned proposal order is an application convention, not a guarantee that every provider requires or accepts that ordering.
The parser uses Python's ordinary JSON decoder; it does not reject duplicate JSON object keys, bound raw input bytes or implement a full hostile-input depth quota. For a public ingress, enforce byte and nesting limits, validate the decoded structure, and apply an appropriate duplicate-key policy before using the payload. The text limit is in Python characters, not provider tokens or UTF-8 bytes. The example does not authenticate message IDs, verify actual content truth, detect sensitive text, authorize tools or render HTML. Those are separate application requirements.
8. Design a safe provider interoperability boundary#
A provider-neutral application model is valuable only if it accurately represents the features the application uses. The adapter must map native fields into standard semantics and preserve or explicitly reject unsupported behavior. For example, if provider A represents a tool call inside a native content block and provider B represents it in a separate field, the application should consume one normalized proposal rather than duplicate execution.
A common block format does not eliminate provider differences. Some providers require special request ordering, specific tool-call grouping, particular metadata continuity or supported block types. Some message fields may be meaningful only for the originating provider. When migrating between providers, verify both the incoming conversion and outbound conversion rather than assuming saved native messages can be sent unchanged.
Keep a compatibility matrix for the exact model profile and integration revision. Record supported text and block shapes, normalized tool fields, finish metadata, usage accounting and serialization behavior. Test representative examples where the same logical message has different native encodings. If a required representation cannot be translated safely, stop or choose a reviewed compatible path.
If the application needs to migrate in-progress agent executions, preserve execution identities and determine whether the alternate adapter can replay the supported history. Prefer applying model/provider changes to new invocations when there is no tested migration for active tool-call sequences.
9. Validate content and build separate consumer projections#
Treat message data from users, models, retrieval services and external providers as untrusted at the appropriate boundary. The fact that data is contained in a valid typed message does not prove that its contents are safe, authorized or accurate.
| Boundary | Validation |
|---|---|
| Ingress | Authorized sender and role, accepted message shape, size limits |
| Block normalization | Recognized types, required fields, bounded sizes and supported extensions |
| Tool proposal | Exact capability, valid arguments, current authorization, operation policy |
| Tool observation | Correlation, verified domain result, allowed disclosure |
| Display projection | Approved user-visible content, output encoding and privacy policy |
| Serialization | Supported version and types, secure storage and validated restoration |
For a text-only consumer, use explicit type dispatch rather than concatenating arbitrary dictionaries. Unknown blocks should have a documented handling decision: reject, omit from a limited display projection with an explicit unavailable state, or retain securely for a supported consumer. Do not silently drop content required for the task and report a successful complete result.
When rendering model text in a web application, use appropriate escaping and sanitization for the rendering mode. Never execute code or arbitrary HTML embedded in a message simply because the provider labeled it text. A text block containing instructions from an external source remains untrusted data; it does not acquire system authority.
Practical example: projecting rather than flattening#
Consider an AIMessage with text "Checking O-1" and a tool call whose normalized arguments specify O-1. An authorized chat UI may render the text and a separate progress indicator. The dispatcher uses the actual tool call, validates its arguments, executes only an approved read, and preserves the resulting ToolMessage. A transcript export might omit internal metadata. These consumers operate on different projections of the same conversation event, not interchangeable copies of a string.
10. Production verification and observability#
Test the actual installed message and provider interfaces separately from application-owned content transformations. A useful test suite includes captured synthetic fixtures for every supported representation and negative fixtures for unsupported or malformed data.
| Test area | Required acceptance condition |
|---|---|
| Plain string and text blocks | Standardized view represents intended text |
| Provider-native blocks | Supported fields map to intended standardized semantics |
| Nonstandard extensions | Documented behavior; no unsafe display or silent execution |
| Empty AI text with tool calls | Valid proposal retained |
| Invalid tool arguments | No unauthorized execution |
| Duplicate representations | One logical proposal dispatched once |
| Parallel call results | Correct ID correlation regardless of completion order |
| SDK serialization round-trip | Required message fields survive supported restoration |
| Provider conversion | Actual outbound request preserves required semantics |
| Usage and finish metadata | Missing or provider-specific fields handled explicitly |
| Content validation | Oversized, malformed and unsupported payloads handled safely |
| Display privacy | Internal fields and unauthorized artifacts excluded |
| Version upgrade | Representative stored messages and native conversions reverified |
Use deterministic mock responses for protocol and content fixtures, then separately approved live-provider tests to establish compatibility. Measure normalization failures, unsupported block types, missing metadata, invalid tool proposals, correlation failures, serialization errors and duplicate dispatch attempts. Do not log entire message contents or raw provider extensions by default. Use safe identifiers, normalized categories, block counts and schema versions.
For streaming interfaces, distinguish a message chunk from a complete message. A chunk may contain partial text or incomplete tool arguments. Aggregate only through supported mechanisms and validate the completed proposal before execution. Detailed streaming and multimodal handling are separate lessons.
Common mistakes#
- Reading message.content as if it were always a string.
- Treating a standardized block view as universally lossless.
- Dropping assistant messages whose text is empty but whose tool_calls are populated.
- Executing both provider-native and normalized representations of the same call.
- Associating tool observations by list position instead of their call IDs.
- Serializing a whole message object and assuming every field is JSON-compatible.
- Sending internal metadata, reasoning blocks or artifacts directly to a user-facing UI.
- Reconstructing an execution history from a text-only projection.
- Confusing typed content with verified evidence or authenticated authority.
Interview-ready answer#
I use LangChain BaseMessage-derived objects to preserve message identity, typed content and role-specific execution fields. I inspect content directly when the original supported payload matters and use content_blocks for a standardized view of recognized representations. I handle tool_calls and ToolMessage.tool_call_id explicitly, avoid duplicate dispatch, and keep provider metadata separate from approved user-facing content. I use supported serializers for runtime representations and a versioned validated projection for application consumers. I verify actual adapter compatibility, block normalization, correlation, serialization and content-policy behavior in integration tests rather than assume standardization removes provider differences.
Official documentation research leads and verification status#
- LangChain messages
- LangChain models
- LangChain agents
- LangChain tools
- LangChain API reference
- LangGraph persistence
- Python JSON documentation
- Python dataclasses documentation
Authorized offline research exception applied. These URLs are official documentation research leads, not live-accessed citations. The standalone text projection and correlation program was executed locally on Python 3.13.5 and passed all 16 checks. Local inspection confirmed that langchain, langchain_core and langgraph were absent. SDK snippets, actual standardized block conversion, provider interoperability, message serialization helpers, current signatures, live documentation and public rendering were not executed or verified. All examples use synthetic data. Mermaid diagrams use standard triple-backtick fences; rendering was not tested.
References
- 1.LangChain messagesdocs.langchain.com
- 2.LangChain modelsdocs.langchain.com
- 3.LangChain agentsdocs.langchain.com
- 4.LangChain toolsdocs.langchain.com
- 5.LangChain API referencereference.langchain.com
- 6.LangGraph persistencedocs.langchain.com
- 7.Python JSON documentationdocs.python.org
- 8.Python dataclasses documentationdocs.python.org
Related questions
Explore other topics:Forward Deployed EngineeringLarge Language ModelsRetrieval-Augmented GenerationMLOps