From 41e232b31f96dee414db65d0b6b0819faca83955 Mon Sep 17 00:00:00 2001 From: Andrei Bondarev Date: Mon, 16 Dec 2024 18:09:06 -0500 Subject: [PATCH] Empty text content should not be set when content is nil when using AnthropicMessage (#900) * Empty text content should not be set when content is nil when using AnthropicMessage * CHANGELOG entry --- CHANGELOG.md | 1 + .../assistant/messages/anthropic_message.rb | 12 +++---- .../messages/anthropic_message_spec.rb | 34 +++++++++++++++++++ 3 files changed, 41 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c7e903069..a7baec7b7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ - [SECURITY]: A change which fixes a security vulnerability. ## [Unreleased] +- [BUGFIX] [https://github.com/patterns-ai-core/langchainrb/pull/900] Empty text content should not be set when content is nil when using AnthropicMessage ## [0.19.2] - 2024-11-26 - [FEATURE] [https://github.com/patterns-ai-core/langchainrb/pull/884] Add `tool_execution_callback` to `Langchain::Assistant`, a callback function (proc, lambda) that is called right before a tool is executed diff --git a/lib/langchain/assistant/messages/anthropic_message.rb b/lib/langchain/assistant/messages/anthropic_message.rb index dcdd17011..70f38209e 100644 --- a/lib/langchain/assistant/messages/anthropic_message.rb +++ b/lib/langchain/assistant/messages/anthropic_message.rb @@ -53,14 +53,14 @@ def to_hash # # @return [Hash] The message as an Anthropic API-compatible hash, with the role as "assistant" def assistant_hash + content_array = [] + if content && !content.empty? + content_array << {type: "text", text: content} + end + { role: "assistant", - content: [ - { - type: "text", - text: content - } - ].concat(tool_calls) + content: content_array.concat(tool_calls) } end diff --git a/spec/langchain/assistant/messages/anthropic_message_spec.rb b/spec/langchain/assistant/messages/anthropic_message_spec.rb index 7f8300090..a1f04924e 100644 --- a/spec/langchain/assistant/messages/anthropic_message_spec.rb +++ b/spec/langchain/assistant/messages/anthropic_message_spec.rb @@ -60,6 +60,40 @@ ] ) end + + it "returns assistant_hash with tool_calls without content" do + message = described_class.new( + role: role, + content: nil, + tool_calls: [ + { + "type" => "tool_use", + "id" => "toolu_01UEciZACvRZ6S4rqAwD1syH", + "name" => "news_retriever__get_everything", + "input" => { + "q" => "Google I/O 2024", + "sort_by" => "publishedAt", + "language" => "en" + } + } + ] + ) + expect(message.to_hash).to eq( + role: role, + content: [ + { + "type" => "tool_use", + "id" => "toolu_01UEciZACvRZ6S4rqAwD1syH", + "name" => "news_retriever__get_everything", + "input" => { + "q" => "Google I/O 2024", + "sort_by" => "publishedAt", + "language" => "en" + } + } + ] + ) + end end context "when role is tool_result" do