From 70834cd741331683a63a6b7932b00ed49ac87191 Mon Sep 17 00:00:00 2001 From: mackong Date: Fri, 28 Jun 2024 03:49:26 +0800 Subject: [PATCH] community[patch]: support convert FunctionMessage for Tongyi (#23569) **Description:** For function call agent with Tongyi, cause the AgentAction will be converted to FunctionMessage by https://github.com/langchain-ai/langchain/blob/47f69fe0d85056a378d7de7e7210247f5b9a8704/libs/core/langchain_core/agents.py#L188 But now Tongyi's *convert_message_to_dict* doesn't support FunctionMessage https://github.com/langchain-ai/langchain/blob/47f69fe0d85056a378d7de7e7210247f5b9a8704/libs/community/langchain_community/chat_models/tongyi.py#L184-L207 Then next round conversation will be failed by the *TypeError* exception. This patch adds the support to convert FunctionMessage for Tongyi. **Issue:** N/A **Dependencies:** N/A --- .../langchain_community/chat_models/tongyi.py | 8 ++++++++ .../tests/unit_tests/chat_models/test_tongyi.py | 13 +++++++++++++ 2 files changed, 21 insertions(+) diff --git a/libs/community/langchain_community/chat_models/tongyi.py b/libs/community/langchain_community/chat_models/tongyi.py index 91541e37781..90dc84c239f 100644 --- a/libs/community/langchain_community/chat_models/tongyi.py +++ b/libs/community/langchain_community/chat_models/tongyi.py @@ -32,6 +32,7 @@ from langchain_core.messages import ( BaseMessageChunk, ChatMessage, ChatMessageChunk, + FunctionMessage, HumanMessage, HumanMessageChunk, SystemMessage, @@ -202,6 +203,13 @@ def convert_message_to_dict(message: BaseMessage) -> dict: "content": message.content, "name": message.name, } + elif isinstance(message, FunctionMessage): + message_dict = { + "role": "tool", + "tool_call_id": "", + "content": message.content, + "name": message.name, + } else: raise TypeError(f"Got unknown type {message}") return message_dict diff --git a/libs/community/tests/unit_tests/chat_models/test_tongyi.py b/libs/community/tests/unit_tests/chat_models/test_tongyi.py index 8bb20abc6bf..452870f7aa4 100644 --- a/libs/community/tests/unit_tests/chat_models/test_tongyi.py +++ b/libs/community/tests/unit_tests/chat_models/test_tongyi.py @@ -1,5 +1,6 @@ from langchain_core.messages import ( AIMessage, + FunctionMessage, HumanMessage, SystemMessage, ) @@ -83,3 +84,15 @@ def test__convert_message_to_dict_system() -> None: result = convert_message_to_dict(message) expected_output = {"role": "system", "content": "foo"} assert result == expected_output + + +def test__convert_message_to_dict_tool() -> None: + message = FunctionMessage(name="foo", content="bar") + result = convert_message_to_dict(message) + expected_output = { + "role": "tool", + "tool_call_id": "", + "content": "bar", + "name": "foo", + } + assert result == expected_output