LangChain Reference home pageLangChain ReferenceLangChain Reference
  • GitHub
  • Main Docs
Deep Agents
LangChain
LangGraph
Integrations
LangSmith
  • Overview
    • Overview
    • Caches
    • Callbacks
    • Documents
    • Document loaders
    • Embeddings
    • Exceptions
    • Language models
    • Serialization
    • Output parsers
    • Prompts
    • Rate limiters
    • Retrievers
    • Runnables
    • Utilities
    • Vector stores
    MCP Adapters
    Standard Tests
    Text Splitters
    ⌘I

    LangChain Assistant

    Ask a question to get started

    Enter to send•Shift+Enter new line

    Menu

    OverviewCachesCallbacksDocumentsDocument loadersEmbeddingsExceptionsLanguage modelsSerializationOutput parsersPromptsRate limitersRetrieversRunnablesUtilitiesVector stores
    MCP Adapters
    Standard Tests
    Text Splitters
    Language
    Theme
    Pythonlangchain-coremessagesutilsconvert_to_openai_messages
    Function●Since v0.3

    convert_to_openai_messages

    Copy
    convert_to_openai_messages(
      messages: MessageLikeRepresentation | Sequence[MessageLikeRepresentation],
      *,
      text_format: Literal

    Used in Docs

    • Run backtests on a new version of an agent
    View source on GitHub
    [
    'string'
    ,
    'block'
    ]
    =
    'string'
    ,
    include_id
    :
    bool
    =
    False
    ,
    pass_through_unknown_blocks
    :
    bool
    =
    True
    )
    ->
    dict
    |
    list
    [
    dict
    ]

    Parameters

    NameTypeDescription
    messages*MessageLikeRepresentation | Sequence[MessageLikeRepresentation]

    Message-like object or iterable of objects whose contents are in OpenAI, Anthropic, Bedrock Converse, or VertexAI formats.

    text_formatLiteral['string', 'block']
    Default:'string'

    How to format string or text block contents:

    • 'string': If a message has a string content, this is left as a string. If a message has content blocks that are all of type 'text', these are joined with a newline to make a single string. If a message has content blocks and at least one isn't of type 'text', then all blocks are left as dicts.
    • 'block': If a message has a string content, this is turned into a list with a single content block of type 'text'. If a message has content blocks these are left as is.
    include_idbool
    Default:False
    pass_through_unknown_blocksbool
    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.