Implementation:Langchain ai Langchain AIMessageChunk Accumulation
Appearance
| Knowledge Sources | |
|---|---|
| Domains | Streaming, Data_Aggregation |
| Last Updated | 2026-02-11 00:00 GMT |
Overview
Concrete tool for accumulating streaming chunks into a complete response using the AIMessageChunk addition operator provided by langchain-core.
Description
The AIMessageChunk.__add__() method merges two chunks by concatenating content strings, merging tool_call_chunks by index, combining usage_metadata, and merging response_metadata. This enables reconstructing the full response from a stream.
Usage
Use the + operator on AIMessageChunk objects to accumulate a full response from streaming output.
Code Reference
Source Location
- Repository: langchain
- File: libs/core/langchain_core/messages/ai.py
- Lines: L413-500+
Signature
class AIMessageChunk(AIMessage, BaseMessageChunk):
type: Literal["AIMessageChunk"] = "AIMessageChunk"
tool_call_chunks: list[ToolCallChunk] = Field(default_factory=list)
def __add__(self, other: AIMessageChunk) -> AIMessageChunk:
# Merges content, tool_call_chunks, usage_metadata, response_metadata
...
Import
from langchain_core.messages import AIMessageChunk
I/O Contract
Inputs
| Name | Type | Required | Description |
|---|---|---|---|
| self | AIMessageChunk | Yes | Accumulated chunk so far |
| other | AIMessageChunk | Yes | New chunk to merge |
Outputs
| Name | Type | Description |
|---|---|---|
| return | AIMessageChunk | Merged chunk with combined content, tool calls, and metadata |
Usage Examples
Accumulating a Full Response
from langchain_openai import ChatOpenAI
llm = ChatOpenAI(model="gpt-4o-mini")
full = None
for chunk in llm.stream("Explain Python in 3 sentences"):
print(chunk.content, end="", flush=True)
full = chunk if full is None else full + chunk
print(f"\n\nFull content: {full.content}")
print(f"Usage: {full.usage_metadata}")
Related Pages
Implements Principle
Page Connections
Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment