expose function for converting messages to messages (#8426)

This commit is contained in:
Harrison Chase 2023-07-28 13:00:54 -07:00 committed by GitHub
parent 06bdbe06fe
commit af7e70d4af
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 39 additions and 1 deletions

View File

@ -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}

View File

@ -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 {