Skip to content

Commit d1d9dc2

Browse files
committed
fix: round-trip thinking blocks in the Claude model
Claude.anthropicContentBlockToPart converted only text and tool_use blocks and threw UnsupportedOperationException("Not supported yet.") for any other block. The Claude 5 models use adaptive thinking when the request has no thinking field, which ADK Java never sets, so their responses can contain thinking blocks without being asked, and each such response ended the agent run. Convert the blocks the same way as ADK Python: - thinking -> Part(text, thought=true, thoughtSignature=signature) - redacted_thinking -> Part(thought=true, thoughtSignature=data) partToAnthropicMessageBlock sends them back unchanged, which Anthropic requires within a tool-use turn: a thought with a signature becomes a thinking block when it has text and a redacted_thinking block when it has none. Only signatures stored this way, as UTF-8 text, are sent back. A binary signature that another model such as Gemini left on a thought is not Claude's, and Anthropic rejects signatures it cannot decode. It also ports google/adk-python@a5d6238cb. A non-thought part that carries only a thought signature, which Gemini leaves in the history, is dropped with a warning instead of throwing or going out as an empty text block, and a message whose parts were all dropped is left out, since Anthropic rejects empty messages. The part stays in the session, so without this every later turn failed the same way. Three deliberate differences from ADK Python: - A thought with empty text (display "omitted", the Claude 5 default) goes back as the thinking block it came from. ADK Python treats the empty text as absent and sends a redacted_thinking block whose data is the signature. - Any other thought is never sent as a thinking block. It is still sent as text, as before, or dropped if it has no text, since there is nothing to send back and Anthropic rejects empty text blocks. ADK Python sends an unsigned thought with text as a thinking block with an empty signature. - A part with a function call or response is always sent as tool_use or tool_result, even if it is a thought or also has text, so that the call and its tool_result stay paired. ADK Python checks non-empty text and a thought's signature before the call, so the call is lost in those cases.
1 parent c239870 commit d1d9dc2

2 files changed

Lines changed: 492 additions & 4 deletions

File tree

‎core/src/main/java/com/google/adk/models/Claude.java‎

Lines changed: 69 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,14 +16,18 @@
1616

1717
package com.google.adk.models;
1818

19+
import static java.nio.charset.StandardCharsets.UTF_8;
20+
1921
import com.anthropic.client.AnthropicClient;
2022
import com.anthropic.models.messages.ContentBlock;
2123
import com.anthropic.models.messages.ContentBlockParam;
2224
import com.anthropic.models.messages.Message;
2325
import com.anthropic.models.messages.MessageCreateParams;
2426
import com.anthropic.models.messages.MessageParam;
2527
import com.anthropic.models.messages.MessageParam.Role;
28+
import com.anthropic.models.messages.RedactedThinkingBlockParam;
2629
import com.anthropic.models.messages.TextBlockParam;
30+
import com.anthropic.models.messages.ThinkingBlockParam;
2731
import com.anthropic.models.messages.Tool;
2832
import com.anthropic.models.messages.ToolChoice;
2933
import com.anthropic.models.messages.ToolChoiceAuto;
@@ -32,6 +36,7 @@
3236
import com.anthropic.models.messages.ToolUseBlockParam;
3337
import com.fasterxml.jackson.core.type.TypeReference;
3438
import com.google.adk.JsonBaseModel;
39+
import com.google.common.base.Utf8;
3540
import com.google.common.collect.ImmutableList;
3641
import com.google.common.collect.ImmutableMap;
3742
import com.google.genai.types.*;
@@ -44,6 +49,7 @@
4449
import java.util.Objects;
4550
import java.util.Optional;
4651
import java.util.stream.Collectors;
52+
import org.jspecify.annotations.Nullable;
4753
import org.slf4j.Logger;
4854
import org.slf4j.LoggerFactory;
4955

@@ -104,6 +110,8 @@ public Flowable<LlmResponse> generateContent(LlmRequest llmRequest, boolean stre
104110
List<MessageParam> messages =
105111
llmRequest.contents().stream()
106112
.map(this::contentToAnthropicMessageParam)
113+
// Anthropic rejects empty messages, e.g. a turn whose parts were all dropped.
114+
.filter(message -> !message.content().asBlockParams().isEmpty())
107115
.collect(Collectors.toList());
108116

109117
List<ToolUnion> tools = ImmutableList.of();
@@ -173,10 +181,53 @@ private MessageParam contentToAnthropicMessageParam(Content content) {
173181
.build();
174182
}
175183

176-
private ContentBlockParam partToAnthropicMessageBlock(Part part) {
177-
if (part.text().isPresent()) {
178-
return ContentBlockParam.ofText(TextBlockParam.builder().text(part.text().get()).build());
179-
} else if (part.functionCall().isPresent()) {
184+
/** Whether a non-thought part carries a signature and nothing to send, as in ADK Python. */
185+
private static boolean isContentFreeSignature(Part part) {
186+
return part.thoughtSignature().map(signature -> signature.length > 0).orElse(false)
187+
&& !part.thought().orElse(false)
188+
&& part.text().map(String::isEmpty).orElse(true)
189+
&& part.functionCall().isEmpty()
190+
&& part.functionResponse().isEmpty()
191+
&& part.inlineData().isEmpty()
192+
&& part.fileData().isEmpty()
193+
&& part.executableCode().isEmpty()
194+
&& part.codeExecutionResult().isEmpty()
195+
&& part.toolCall().isEmpty()
196+
&& part.toolResponse().isEmpty()
197+
&& part.audioTranscription().isEmpty();
198+
}
199+
200+
private @Nullable ContentBlockParam partToAnthropicMessageBlock(Part part) {
201+
if (isContentFreeSignature(part)) {
202+
logger.warn("Dropping a thought signature from another model.");
203+
return null;
204+
}
205+
if (part.thought().orElse(false)
206+
&& part.functionCall().isEmpty()
207+
&& part.functionResponse().isEmpty()) {
208+
// Signatures this class stores are UTF-8; a binary one (e.g. Gemini's) is not Claude's.
209+
Optional<String> signature =
210+
part.thoughtSignature()
211+
.filter(bytes -> bytes.length > 0 && Utf8.isWellFormed(bytes))
212+
.map(bytes -> new String(bytes, UTF_8));
213+
if (signature.isPresent()) {
214+
// Unlike ADK Python, empty text (display "omitted") stays thinking, not redacted_thinking.
215+
return part.text().isPresent()
216+
? ContentBlockParam.ofThinking(
217+
ThinkingBlockParam.builder()
218+
.thinking(part.text().get())
219+
.signature(signature.get())
220+
.build())
221+
: ContentBlockParam.ofRedactedThinking(
222+
RedactedThinkingBlockParam.builder().data(signature.get()).build());
223+
}
224+
// Other thoughts go out as text (ADK Python sends thinking), or are dropped without text.
225+
if (part.text().map(String::isEmpty).orElse(true)) {
226+
return null;
227+
}
228+
}
229+
// Unlike ADK Python, a call or response is always sent, even on a thought or beside text.
230+
if (part.functionCall().isPresent()) {
180231
return ContentBlockParam.ofToolUse(
181232
ToolUseBlockParam.builder()
182233
.id(part.functionCall().get().id().orElse(""))
@@ -205,6 +256,8 @@ private ContentBlockParam partToAnthropicMessageBlock(Part part) {
205256
.content(content)
206257
.isError(false)
207258
.build());
259+
} else if (part.text().isPresent()) {
260+
return ContentBlockParam.ofText(TextBlockParam.builder().text(part.text().get()).build());
208261
}
209262
throw new UnsupportedOperationException("Not supported yet.");
210263
}
@@ -387,6 +440,18 @@ private Part anthropicContentBlockToPart(ContentBlock block) {
387440
.convert(new TypeReference<Map<String, Object>>() {}))
388441
.build())
389442
.build();
443+
} else if (block.isThinking()) {
444+
return Part.builder()
445+
.text(block.asThinking().thinking())
446+
.thought(true)
447+
.thoughtSignature(block.asThinking().signature().getBytes(UTF_8))
448+
.build();
449+
} else if (block.isRedactedThinking()) {
450+
// Keep the encrypted data in thoughtSignature so the block can be sent back unchanged.
451+
return Part.builder()
452+
.thought(true)
453+
.thoughtSignature(block.asRedactedThinking().data().getBytes(UTF_8))
454+
.build();
390455
}
391456
throw new UnsupportedOperationException("Not supported yet.");
392457
}

0 commit comments

Comments
 (0)