Skip to content

Commit 41e232b

Browse files
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
1 parent 9bbd609 commit 41e232b

File tree

3 files changed

+41
-6
lines changed

3 files changed

+41
-6
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
- [SECURITY]: A change which fixes a security vulnerability.
1111

1212
## [Unreleased]
13+
- [BUGFIX] [https://github.com/patterns-ai-core/langchainrb/pull/900] Empty text content should not be set when content is nil when using AnthropicMessage
1314

1415
## [0.19.2] - 2024-11-26
1516
- [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

lib/langchain/assistant/messages/anthropic_message.rb

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -53,14 +53,14 @@ def to_hash
5353
#
5454
# @return [Hash] The message as an Anthropic API-compatible hash, with the role as "assistant"
5555
def assistant_hash
56+
content_array = []
57+
if content && !content.empty?
58+
content_array << {type: "text", text: content}
59+
end
60+
5661
{
5762
role: "assistant",
58-
content: [
59-
{
60-
type: "text",
61-
text: content
62-
}
63-
].concat(tool_calls)
63+
content: content_array.concat(tool_calls)
6464
}
6565
end
6666

spec/langchain/assistant/messages/anthropic_message_spec.rb

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,40 @@
6060
]
6161
)
6262
end
63+
64+
it "returns assistant_hash with tool_calls without content" do
65+
message = described_class.new(
66+
role: role,
67+
content: nil,
68+
tool_calls: [
69+
{
70+
"type" => "tool_use",
71+
"id" => "toolu_01UEciZACvRZ6S4rqAwD1syH",
72+
"name" => "news_retriever__get_everything",
73+
"input" => {
74+
"q" => "Google I/O 2024",
75+
"sort_by" => "publishedAt",
76+
"language" => "en"
77+
}
78+
}
79+
]
80+
)
81+
expect(message.to_hash).to eq(
82+
role: role,
83+
content: [
84+
{
85+
"type" => "tool_use",
86+
"id" => "toolu_01UEciZACvRZ6S4rqAwD1syH",
87+
"name" => "news_retriever__get_everything",
88+
"input" => {
89+
"q" => "Google I/O 2024",
90+
"sort_by" => "publishedAt",
91+
"language" => "en"
92+
}
93+
}
94+
]
95+
)
96+
end
6397
end
6498

6599
context "when role is tool_result" do

0 commit comments

Comments
 (0)