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

    Convert LangChain messages into OpenAI message dicts.

    Copy
    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'}
    # ]

    Used in Docs

    • Run backtests on a new version of an agent

    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

    Whether to include message IDs in the openai messages, if they are present in the source messages.

    pass_through_unknown_blocksbool
    Default:True

    Whether to include content blocks with unknown formats in the output. If False, an error is raised if an unknown content block is encountered.

    View source on GitHub