From af7e70d4af5f52b460a9f0cd8900695a93f7f47a Mon Sep 17 00:00:00 2001 From: Harrison Chase Date: Fri, 28 Jul 2023 13:00:54 -0700 Subject: [PATCH] expose function for converting messages to messages (#8426) --- .../langchain/langchain/chat_models/openai.py | 12 ++++++++ .../unit_tests/chat_models/test_openai.py | 28 ++++++++++++++++++- 2 files changed, 39 insertions(+), 1 deletion(-) diff --git a/libs/langchain/langchain/chat_models/openai.py b/libs/langchain/langchain/chat_models/openai.py index 2da3a14d0d..520c205c08 100644 --- a/libs/langchain/langchain/chat_models/openai.py +++ b/libs/langchain/langchain/chat_models/openai.py @@ -142,6 +142,18 @@ def _convert_dict_to_message(_dict: Mapping[str, Any]) -> BaseMessage: return ChatMessage(content=_dict["content"], role=role) +def convert_openai_messages(messages: List[dict]) -> List[BaseMessage]: + """Convert dictionaries representing OpenAI messages to LangChain format. + + Args: + messages: List of dictionaries representing OpenAI messages + + Returns: + List of LangChain BaseMessage objects. + """ + return [_convert_dict_to_message(m) for m in messages] + + def _convert_message_to_dict(message: BaseMessage) -> dict: if isinstance(message, ChatMessage): message_dict = {"role": message.role, "content": message.content} diff --git a/libs/langchain/tests/unit_tests/chat_models/test_openai.py b/libs/langchain/tests/unit_tests/chat_models/test_openai.py index 7719358d72..95ecbe9e5b 100644 --- a/libs/langchain/tests/unit_tests/chat_models/test_openai.py +++ b/libs/langchain/tests/unit_tests/chat_models/test_openai.py @@ -9,7 +9,12 @@ from langchain.chat_models.openai import ( ChatOpenAI, _convert_dict_to_message, ) -from langchain.schema.messages import FunctionMessage +from langchain.schema.messages import ( + AIMessage, + FunctionMessage, + HumanMessage, + SystemMessage, +) def test_function_message_dict_to_function_message() -> None: @@ -27,6 +32,27 @@ def test_function_message_dict_to_function_message() -> None: assert result.content == content +def test__convert_dict_to_message_human() -> None: + message = {"role": "user", "content": "foo"} + result = _convert_dict_to_message(message) + expected_output = HumanMessage(content="foo") + assert result == expected_output + + +def test__convert_dict_to_message_ai() -> None: + message = {"role": "assistant", "content": "foo"} + result = _convert_dict_to_message(message) + expected_output = AIMessage(content="foo") + assert result == expected_output + + +def test__convert_dict_to_message_system() -> None: + message = {"role": "system", "content": "foo"} + result = _convert_dict_to_message(message) + expected_output = SystemMessage(content="foo") + assert result == expected_output + + @pytest.fixture def mock_completion() -> dict: return {