Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 9 additions & 2 deletions autogen/oai/anthropic.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@
with optional_import_block():
from anthropic import Anthropic, AnthropicBedrock, AnthropicVertex
from anthropic import __version__ as anthropic_version
from anthropic.types import Message, TextBlock, ToolUseBlock
from anthropic.types import Message, TextBlock, ThinkingBlock, ToolUseBlock

TOOL_ENABLED = anthropic_version >= "0.23.1"
if TOOL_ENABLED:
Expand Down Expand Up @@ -488,7 +488,14 @@ def _extract_json_response(self, response: Message) -> Any:
return response

# Extract content from response
content = response.content[0].text if response.content else ""
if response.content:
if type(response.content[0]) == TextBlock:
content = response.content[0].text

elif type(response.content[0]) == ThinkingBlock:
content = response.content[0].thinking
else:
content = ""

# Try to extract JSON from tags first
json_match = re.search(r"<json_response>(.*?)</json_response>", content, re.DOTALL)
Expand Down
31 changes: 30 additions & 1 deletion test/oai/test_anthropic.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
from autogen.oai.anthropic import AnthropicClient, AnthropicLLMConfigEntry, _calculate_cost

with optional_import_block() as result:
from anthropic.types import Message, TextBlock
from anthropic.types import Message, TextBlock, ThinkingBlock


from typing import Literal
Expand Down Expand Up @@ -291,6 +291,35 @@ class MathReasoning(BaseModel):

with pytest.raises(ValueError, match="No valid JSON found in response for Structured Output."):
anthropic_client._extract_json_response(no_json_response)

# Test case 5: Plain JSON without tags, using ThinkingBlock - SHOULD STILL PASS
plain_response = Message(
id="msg_123",
content=[
ThinkingBlock(
signature="json_response",
thinking="""Here's the solution:
{
"steps": [
{"explanation": "Step 1", "output": "8x = -30"},
{"explanation": "Step 2", "output": "x = -3.75"}
],
"final_answer": "x = -3.75"
}""",
type="thinking",
)
],
model="claude-3-5-sonnet-latest",
role="assistant",
stop_reason="end_turn",
type="message",
usage={"input_tokens": 10, "output_tokens": 25},
)

result = anthropic_client._extract_json_response(plain_response)
assert isinstance(result, MathReasoning)
assert len(result.steps) == 2
assert result.final_answer == "x = -3.75"


@run_for_optional_imports(["anthropic"], "anthropic")
Expand Down
Loading