convert_to_openai_messages(
messages: MessageLikeRepresentation | Sequence[MessageLikeRepresentation],
*,
text_format: Literal| 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: False |
pass_through_unknown_blocks | bool | Default: True |
Convert LangChain messages into OpenAI message dicts.
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": "what's 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": "that's nice"},
]
oai_messages = convert_to_openai_messages(messages)
# -> [
# {'role': 'system', 'content': 'foo'},
# {'role': 'user', 'content': [{'type': 'text', 'text': 'what's 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': 'that's nice'}
# ]Whether to include message IDs in the openai messages, if they are present in the source messages.
Whether to include content blocks with unknown
formats in the output. If False, an error is raised if an unknown
content block is encountered.