From 9e92aef933c72dc41009346a923fc66188fb2c3a Mon Sep 17 00:00:00 2001 From: Mason Daugherty Date: Wed, 6 Aug 2025 11:10:58 -0400 Subject: [PATCH] feat: update message ID logic --- libs/core/langchain_core/messages/ai.py | 7 +++---- libs/core/langchain_core/v1/chat_models.py | 15 +++++++++++++++ 2 files changed, 18 insertions(+), 4 deletions(-) diff --git a/libs/core/langchain_core/messages/ai.py b/libs/core/langchain_core/messages/ai.py index b980761a121..2c1307dbd28 100644 --- a/libs/core/langchain_core/messages/ai.py +++ b/libs/core/langchain_core/messages/ai.py @@ -25,8 +25,10 @@ from langchain_core.utils.usage import _dict_int_op logger = logging.getLogger(__name__) +_LC_AUTO_PREFIX = "lc_" +"""LangChain auto-generated ID prefix for messages and content blocks.""" -_LC_ID_PREFIX = "run-" +_LC_ID_PREFIX = f"{_LC_AUTO_PREFIX}run-" """Internal tracing/callback system identifier. Used for: @@ -35,9 +37,6 @@ Used for: - Enables tracking parent-child relationships between operations """ -_LC_AUTO_PREFIX = "lc_" -"""LangChain auto-generated ID prefix for messages and content blocks.""" - class InputTokenDetails(TypedDict, total=False): """Breakdown of input token counts. diff --git a/libs/core/langchain_core/v1/chat_models.py b/libs/core/langchain_core/v1/chat_models.py index 5270ef787e8..55ef5b74d37 100644 --- a/libs/core/langchain_core/v1/chat_models.py +++ b/libs/core/langchain_core/v1/chat_models.py @@ -48,6 +48,7 @@ from langchain_core.messages import ( get_buffer_string, is_data_content_block, ) +from langchain_core.messages.ai import _LC_ID_PREFIX from langchain_core.messages.utils import ( convert_from_v1_message, convert_to_messages_v1, @@ -471,6 +472,9 @@ class BaseChatModel(RunnableSerializable[LanguageModelInput, AIMessageV1], ABC): run_manager.on_llm_error(e) raise + if run_manager and full_message.id and full_message.id.startswith("lc_"): + full_message.id = f"{_LC_ID_PREFIX}-{run_manager.run_id}-0" + run_manager.on_llm_end(full_message) return full_message @@ -542,6 +546,9 @@ class BaseChatModel(RunnableSerializable[LanguageModelInput, AIMessageV1], ABC): ) raise + if run_manager and full_message.id and full_message.id.startswith("lc_"): + full_message.id = f"{_LC_ID_PREFIX}-{run_manager.run_id}-0" + await run_manager.on_llm_end(full_message) return full_message @@ -613,6 +620,10 @@ class BaseChatModel(RunnableSerializable[LanguageModelInput, AIMessageV1], ABC): raise msg = add_ai_message_chunks(chunks[0], *chunks[1:]) + + if run_manager and msg.id and msg.id.startswith("lc_"): + msg.id = f"{_LC_ID_PREFIX}-{run_manager.run_id}-0" + run_manager.on_llm_end(msg) @override @@ -686,6 +697,10 @@ class BaseChatModel(RunnableSerializable[LanguageModelInput, AIMessageV1], ABC): raise msg = add_ai_message_chunks(chunks[0], *chunks[1:]) + + if run_manager and msg.id and msg.id.startswith("lc_"): + msg.id = f"{_LC_ID_PREFIX}-{run_manager.run_id}-0" + await run_manager.on_llm_end(msg) # --- Custom methods ---