Convert LangChain messages into OpenAI message dicts.
convert_to_openai_messages(
messages: MessageLikeRepresentation | Sequence[MessageLikeRepresentation],
*,
text_format: Literal['string', 'block'] = 'string',
include_id: bool = False,
pass_through_unknown_blocks: bool = True
) -> dict | list[dict]Example:
from langchain_core.messages import (
convert_to_openai_messages,
AIMessage,
SystemMessage,
ToolMessage,
)
messages = [
SystemMessage([{"type": "text", "text": "foo"}]),
{
"role": "user",
"content": [
{"type": "text", "text": "whats in this"},
{
"type": "image_url",
"image_url": {"url": "data:image/png;base64,'/9j/4AAQSk'"},
},
],
},
AIMessage(
"",
tool_calls=[
{
"name": "analyze",
"args": {"baz": "buz"},
"id": "1",
"type": "tool_call",
}
],
),
ToolMessage("foobar", tool_call_id="1", name="bar"),
{"role": "assistant", "content": "thats nice"},
]
oai_messages = convert_to_openai_messages(messages)
# -> [
# {'role': 'system', 'content': 'foo'},
# {'role': 'user', 'content': [{'type': 'text', 'text': 'whats in this'}, {'type': 'image_url', 'image_url': {'url': "data:image/png;base64,'/9j/4AAQSk'"}}]},
# {'role': 'assistant', 'tool_calls': [{'type': 'function', 'id': '1','function': {'name': 'analyze', 'arguments': '{"baz": "buz"}'}}], 'content': ''},
# {'role': 'tool', 'name': 'bar', 'content': 'foobar'},
# {'role': 'assistant', 'content': 'thats nice'}
# ]| Name | Type | Description |
|---|---|---|
messages* | MessageLikeRepresentation | Sequence[MessageLikeRepresentation] | Message-like object or iterable of objects whose contents are in OpenAI, Anthropic, Bedrock Converse, or VertexAI formats. |
text_format | Literal['string', 'block'] | Default: 'string'How to format string or text block contents:
|
include_id | bool | Default: FalseWhether to include message IDs in the openai messages, if they are present in the source messages. |
pass_through_unknown_blocks | bool | Default: TrueWhether to include content blocks with unknown
formats in the output. If |