From a9246333fd4bb8f2cef5e4dbea3fcaf31a306e61 Mon Sep 17 00:00:00 2001 From: Ankush Gola <9536492+agola11@users.noreply.github.com> Date: Mon, 19 Jun 2023 21:30:52 -0700 Subject: [PATCH] fix anthropic chat model mutating input list (#6457) Fixes: ChatAnthropic was mutating the input message list during formatting which isn't ideal bc you could be changing the behavior for other chat models when using the same input #### Before submitting #### Who can review? Tag maintainers/contributors who might be interested: --- langchain/chat_models/anthropic.py | 2 ++ .../chat_models/test_anthropic.py | 16 ++++++++++++++++ 2 files changed, 18 insertions(+) diff --git a/langchain/chat_models/anthropic.py b/langchain/chat_models/anthropic.py index 023c9e4150..edb036526b 100644 --- a/langchain/chat_models/anthropic.py +++ b/langchain/chat_models/anthropic.py @@ -76,6 +76,8 @@ class ChatAnthropic(BaseChatModel, _AnthropicCommon): Returns: str: Combined string with necessary HUMAN_PROMPT and AI_PROMPT tags. """ + messages = messages.copy() # don't mutate the original list + if not self.AI_PROMPT: raise NameError("Please ensure the anthropic package is loaded") diff --git a/tests/integration_tests/chat_models/test_anthropic.py b/tests/integration_tests/chat_models/test_anthropic.py index a7186c8be6..f0c2de7980 100644 --- a/tests/integration_tests/chat_models/test_anthropic.py +++ b/tests/integration_tests/chat_models/test_anthropic.py @@ -24,6 +24,22 @@ def test_anthropic_call() -> None: assert isinstance(response.content, str) +def test_anthropic_generate() -> None: + """Test generate method of anthropic.""" + chat = ChatAnthropic(model="test") + chat_messages: List[List[BaseMessage]] = [ + [HumanMessage(content="How many toes do dogs have?")] + ] + messages_copy = [messages.copy() for messages in chat_messages] + result: LLMResult = chat.generate(chat_messages) + assert isinstance(result, LLMResult) + for response in result.generations[0]: + assert isinstance(response, ChatGeneration) + assert isinstance(response.text, str) + assert response.text == response.message.content + assert chat_messages == messages_copy + + def test_anthropic_streaming() -> None: """Test streaming tokens from anthropic.""" chat = ChatAnthropic(model="test", streaming=True)