Skip to content

The agent engineering platform.

feat(core): add optional include_id param to convert_to_openai_messages function (#33242)

SN99361e623a37
diff --git a/libs/core/langchain_core/messages/utils.py b/libs/core/langchain_core/messages/utils.py
index 48d57617e2..7e2bd238c1 100644
--- a/libs/core/langchain_core/messages/utils.py
+++ b/libs/core/langchain_core/messages/utils.py
@@ -1045,6 +1045,7 @@ def convert_to_openai_messages(
messages: Union[MessageLikeRepresentation, Sequence[MessageLikeRepresentation]],
*,
text_format: Literal["string", "block"] = "string",
+ include_id: bool = False,
) -> Union[dict, list[dict]]:
"""Convert LangChain messages into OpenAI message dicts.
@@ -1062,6 +1063,8 @@ def convert_to_openai_messages(
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_id: Whether to include message ids in the openai messages, if they
+ are present in the source messages.
Raises:
ValueError: if an unrecognized ``text_format`` is specified, or if a message
@@ -1150,6 +1153,8 @@ def convert_to_openai_messages(
oai_msg["refusal"] = message.additional_kwargs["refusal"]
if isinstance(message, ToolMessage):
oai_msg["tool_call_id"] = message.tool_call_id
+ if include_id and message.id:
+ oai_msg["id"] = message.id
if not message.content:
content = "" if text_format == "string" else []
diff --git a/libs/core/tests/unit_tests/messages/test_utils.py b/libs/core/tests/unit_tests/messages/test_utils.py
index 5b67f1076a..32151132b3 100644
--- a/libs/core/tests/unit_tests/messages/test_utils.py
+++ b/libs/core/tests/unit_tests/messages/test_utils.py
@@ -882,10 +882,21 @@ def test_convert_to_openai_messages_string() -> None:
def test_convert_to_openai_messages_single_message() -> None:
- message = HumanMessage(content="Hello")
+ message: BaseMessage = HumanMessage(content="Hello")
result = convert_to_openai_messages(message)
assert result == {"role": "user", "content": "Hello"}
+ # Test IDs
+ result = convert_to_openai_messages(message, include_id=True)
+ assert result == {"role": "user", "content": "Hello"} # no ID
+
+ message = AIMessage(content="Hello", id="resp_123")
+ result = convert_to_openai_messages(message)
+ assert result == {"role": "assistant", "content": "Hello"}
+
+ result = convert_to_openai_messages(message, include_id=True)
+ assert result == {"role": "assistant", "content": "Hello", "id": "resp_123"}
+
def test_convert_to_openai_messages_multiple_messages() -> None:
messages = [