_format_messages() — langchain Function Reference
Architecture documentation for the _format_messages() function in chat_models.py from the langchain codebase.
Entity Profile
Dependency Diagram
graph TD a1122c23_c68d_f096_a90e_42f0e4d39d61["_format_messages()"] a85819c7_917d_4c71_2864_a19e68947340["chat_models.py"] a1122c23_c68d_f096_a90e_42f0e4d39d61 -->|defined in| a85819c7_917d_4c71_2864_a19e68947340 954f0cfe_731b_ac1b_0145_b5a3d210030b["_get_request_payload()"] 954f0cfe_731b_ac1b_0145_b5a3d210030b -->|calls| a1122c23_c68d_f096_a90e_42f0e4d39d61 69a9ca1f_89ff_e8cc_0a13_8af61d334b1d["get_num_tokens_from_messages()"] 69a9ca1f_89ff_e8cc_0a13_8af61d334b1d -->|calls| a1122c23_c68d_f096_a90e_42f0e4d39d61 005a5002_49e5_d89d_8695_51674ab4fc58["_merge_messages()"] a1122c23_c68d_f096_a90e_42f0e4d39d61 -->|calls| 005a5002_49e5_d89d_8695_51674ab4fc58 4db283f3_f14d_8856_90b5_c06620f07118["_format_image()"] a1122c23_c68d_f096_a90e_42f0e4d39d61 -->|calls| 4db283f3_f14d_8856_90b5_c06620f07118 7042d659_4e83_4ce8_9e4c_bfd32dddc9aa["_format_data_content_block()"] a1122c23_c68d_f096_a90e_42f0e4d39d61 -->|calls| 7042d659_4e83_4ce8_9e4c_bfd32dddc9aa 544f8a91_bddd_d6fd_dea8_33f43056d1a2["_lc_tool_calls_to_anthropic_tool_use_blocks()"] a1122c23_c68d_f096_a90e_42f0e4d39d61 -->|calls| 544f8a91_bddd_d6fd_dea8_33f43056d1a2 style a1122c23_c68d_f096_a90e_42f0e4d39d61 fill:#6366f1,stroke:#818cf8,color:#fff
Relationship Graph
Source Code
libs/partners/anthropic/langchain_anthropic/chat_models.py lines 410–662
def _format_messages(
messages: Sequence[BaseMessage],
) -> tuple[str | list[dict] | None, list[dict]]:
"""Format messages for Anthropic's API."""
system: str | list[dict] | None = None
formatted_messages: list[dict] = []
merged_messages = _merge_messages(messages)
for _i, message in enumerate(merged_messages):
if message.type == "system":
if system is not None:
msg = "Received multiple non-consecutive system messages."
raise ValueError(msg)
if isinstance(message.content, list):
system = [
(
block
if isinstance(block, dict)
else {"type": "text", "text": block}
)
for block in message.content
]
else:
system = message.content
continue
role = _message_type_lookups[message.type]
content: str | list
if not isinstance(message.content, str):
# parse as dict
if not isinstance(message.content, list):
msg = "Anthropic message content must be str or list of dicts"
raise ValueError(
msg,
)
# populate content
content = []
for block in message.content:
if isinstance(block, str):
content.append({"type": "text", "text": block})
elif isinstance(block, dict):
if "type" not in block:
msg = "Dict content block must have a type key"
raise ValueError(msg)
if block["type"] == "image_url":
# convert format
source = _format_image(block["image_url"]["url"])
content.append({"type": "image", "source": source})
elif is_data_content_block(block):
content.append(_format_data_content_block(block))
elif block["type"] == "tool_use":
# If a tool_call with the same id as a tool_use content block
# exists, the tool_call is preferred.
if (
isinstance(message, AIMessage)
and (block["id"] in [tc["id"] for tc in message.tool_calls])
and not block.get("caller")
):
overlapping = [
tc
for tc in message.tool_calls
if tc["id"] == block["id"]
]
content.extend(
_lc_tool_calls_to_anthropic_tool_use_blocks(
overlapping,
),
)
else:
if tool_input := block.get("input"):
args = tool_input
elif "partial_json" in block:
try:
args = json.loads(block["partial_json"] or "{}")
except json.JSONDecodeError:
args = {}
else:
args = {}
tool_use_block = _AnthropicToolUse(
type="tool_use",
Domain
Subdomains
Calls
Source
Frequently Asked Questions
What does _format_messages() do?
_format_messages() is a function in the langchain codebase, defined in libs/partners/anthropic/langchain_anthropic/chat_models.py.
Where is _format_messages() defined?
_format_messages() is defined in libs/partners/anthropic/langchain_anthropic/chat_models.py at line 410.
What does _format_messages() call?
_format_messages() calls 4 function(s): _format_data_content_block, _format_image, _lc_tool_calls_to_anthropic_tool_use_blocks, _merge_messages.
What calls _format_messages()?
_format_messages() is called by 2 function(s): _get_request_payload, get_num_tokens_from_messages.
Analyze Your Own Codebase
Get architecture documentation, dependency graphs, and domain analysis for your codebase in minutes.
Try Supermodel Free