A programming framework for agentic AI
Add thinking mode support for anthropic client (#7002)
SrikarMannepalli5216bf373726
diff --git a/python/packages/autogen-ext/src/autogen_ext/models/anthropic/_anthropic_client.py b/python/packages/autogen-ext/src/autogen_ext/models/anthropic/_anthropic_client.pyindex 3bc989878..6f68cf7b8 100644--- a/python/packages/autogen-ext/src/autogen_ext/models/anthropic/_anthropic_client.py+++ b/python/packages/autogen-ext/src/autogen_ext/models/anthropic/_anthropic_client.py@@ -90,6 +90,7 @@ anthropic_message_params = {"tool_choice","stream","metadata",+ "thinking",}disallowed_create_args = {"stream", "messages"}required_create_args: Set[str] = {"model"}@@ -465,6 +466,9 @@ class BaseAnthropicChatCompletionClient(ChatCompletionClient):self._total_usage = RequestUsage(prompt_tokens=0, completion_tokens=0)self._actual_usage = RequestUsage(prompt_tokens=0, completion_tokens=0)+ # Store last used tools for anthropic API requirement+ self._last_used_tools: List[ToolParam] = []+def _serialize_message(self, message: MessageParam) -> Dict[str, Any]:"""Convert an Anthropic MessageParam to a JSON-serializable format."""if isinstance(message, dict):@@ -513,6 +517,27 @@ class BaseAnthropicChatCompletionClient(ChatCompletionClient):return messages+ def _get_thinking_config(self, extra_create_args: Mapping[str, Any]) -> Dict[str, Any]:+ """+ Get the thinking configuration for API calls++ Args:+ extra_create_args: Extra arguments that may contain thinking config++ Returns:+ dict: Thinking configuration or empty dict if not provided+ """+ # Check if thinking is specified in extra_create_args (priority)+ thinking_config = extra_create_args.get("thinking")+ if thinking_config is None:+ # Check if thinking is specified in base create_args+ thinking_config = self._create_args.get("thinking")++ if thinking_config is None:+ return {}++ return {"thinking": thinking_config}+def _rstrip_last_assistant_message(self, messages: Sequence[LLMMessage]) -> Sequence[LLMMessage]:"""Remove the last assistant message if it is empty.@@ -643,6 +668,11 @@ class BaseAnthropicChatCompletionClient(ChatCompletionClient):if param in create_args:request_args[param] = create_args[param]+ # Add thinking configuration if available+ thinking_config = self._get_thinking_config(extra_create_args)+ if thinking_config:+ request_args.update(thinking_config)+# Execute the requestfuture: asyncio.Task[Message] = asyncio.ensure_future(self._client.messages.create(**request_args)) # type: ignore@@ -674,14 +704,21 @@ class BaseAnthropicChatCompletionClient(ChatCompletionClient):# Check if the response includes tool usestool_uses = [block for block in result.content if getattr(block, "type", None) == "tool_use"]+ # Check for thinking blocks+ thinking_blocks = [block for block in result.content if getattr(block, "type", None) == "thinking"]+if tool_uses:# Handle tool use responsecontent = []- # Check for text content that should be treated as thought- text_blocks: List[TextBlock] = [block for block in result.content if isinstance(block, TextBlock)]- if text_blocks:- thought = "".join([block.text for block in text_blocks])+ # Extract thinking content+ if thinking_blocks:+ thought = "".join([getattr(block, "thinking", "") for block in thinking_blocks])+ else:+ # Fallback: text content before tool calls is treated as thought+ text_blocks: List[TextBlock] = [block for block in result.content if isinstance(block, TextBlock)]+ if text_blocks:+ thought = "".join([block.text for block in text_blocks])# Process tool use blocksfor tool_use in tool_uses:@@ -701,7 +738,14 @@ class BaseAnthropicChatCompletionClient(ChatCompletionClient):)else:# Handle text response- content = "".join([block.text if isinstance(block, TextBlock) else "" for block in result.content])+ if thinking_blocks:+ # Extract thinking content+ thought = "".join([getattr(block, "thinking", "") for block in thinking_blocks])+ # Get only text content for the main content field+ content = "".join([block.text if isinstance(block, TextBlock) else "" for block in result.content])+ else:+ # No thinking blocks, just get text content+ content = "".join([block.text if isinstance(block, TextBlock) else "" for block in result.content])# Create the final resultresponse = CreateResult(@@ -843,6 +887,11 @@ class BaseAnthropicChatCompletionClient(ChatCompletionClient):if param in create_args:request_args[param] = create_args[param]+ # Add thinking configuration if available+ thinking_config = self._get_thinking_config(extra_create_args)+ if thinking_config:+ request_args.update(thinking_config)+# Stream the responsestream_future: asyncio.Task[AsyncStream[RawMessageStreamEvent]] = asyncio.ensure_future(cast(Coroutine[Any, Any, AsyncStream[RawMessageStreamEvent]], self._client.messages.create(**request_args))@@ -854,6 +903,7 @@ class BaseAnthropicChatCompletionClient(ChatCompletionClient):stream: AsyncStream[RawMessageStreamEvent] = cast(AsyncStream[RawMessageStreamEvent], await stream_future) # type: ignoretext_content: List[str] = []+ thinking_content: List[str] = []tool_calls: Dict[str, Dict[str, Any]] = {} # Track tool calls by IDcurrent_tool_id: Optional[str] = Noneinput_tokens: int = 0@@ -884,6 +934,9 @@ class BaseAnthropicChatCompletionClient(ChatCompletionClient):"input": json.dumps(chunk.content_block.input),"partial_json": "", # May be populated from deltas}+ elif chunk.content_block.type == "thinking":+ # Start of a thinking block - no special handling needed for start+ passelif chunk.type == "content_block_delta":if hasattr(chunk.delta, "type") and chunk.delta.type == "text_delta":@@ -892,7 +945,14 @@ class BaseAnthropicChatCompletionClient(ChatCompletionClient):text_content.append(delta_text)if delta_text:yield delta_text-+ elif hasattr(chunk.delta, "type") and chunk.delta.type == "thinking_delta":+ # Handle thinking content+ if hasattr(chunk.delta, "thinking"):+ delta_thinking = chunk.delta.thinking+ thinking_content.append(delta_thinking)+ # Optionally yield thinking content as it streams+ if delta_thinking:+ yield delta_thinking# Handle tool input deltas - they come as InputJSONDeltaelif hasattr(chunk.delta, "type") and chunk.delta.type == "input_json_delta":if current_tool_id is not None and hasattr(chunk.delta, "partial_json"):@@ -935,8 +995,11 @@ class BaseAnthropicChatCompletionClient(ChatCompletionClient):if tool_calls:# We received tool calls- if text_content:- # Text before tool calls is treated as thought+ # Extract thinking content+ if thinking_content:+ thought = "".join(thinking_content)+ elif text_content:+ # Fallback: text before tool calls is treated as thoughtthought = "".join(text_content)# Convert tool calls to FunctionCall objects@@ -961,8 +1024,14 @@ class BaseAnthropicChatCompletionClient(ChatCompletionClient):))else:- # Just text content- content = "".join(text_content)+ # Just text content - no tool calls+ if thinking_content:+ # Extract thinking content+ thought = "".join(thinking_content)+ content = "".join(text_content)+ else:+ # No thinking content, just regular text+ content = "".join(text_content)# Create the final resultresult = CreateResult(diff --git a/python/packages/autogen-ext/src/autogen_ext/models/anthropic/config/__init__.py b/python/packages/autogen-ext/src/autogen_ext/models/anthropic/config/__init__.pyindex 22dfc067f..10b46b6a6 100644--- a/python/packages/autogen-ext/src/autogen_ext/models/anthropic/config/__init__.py+++ b/python/packages/autogen-ext/src/autogen_ext/models/anthropic/config/__init__.py@@ -9,6 +9,13 @@ class ResponseFormat(TypedDict):type: Literal["text", "json_object"]+class ThinkingConfig(TypedDict, total=False):+ """Configuration for thinking mode."""++ type: Required[Literal["enabled", "disabled"]]+ budget_tokens: Optional[int] # Required if type is "enabled"++class CreateArguments(TypedDict, total=False):model: strmax_tokens: Optional[int]@@ -18,6 +25,7 @@ class CreateArguments(TypedDict, total=False):stop_sequences: Optional[List[str]]response_format: Optional[ResponseFormat]metadata: Optional[Dict[str, str]]+ thinking: Optional[ThinkingConfig]class BedrockInfo(TypedDict):@@ -57,6 +65,13 @@ class AnthropicBedrockClientConfiguration(AnthropicClientConfiguration, total=Fa# Pydantic equivalents of the above TypedDicts+class ThinkingConfigModel(BaseModel):+ """Configuration for thinking mode."""++ type: Literal["enabled", "disabled"]+ budget_tokens: int | None = None # Required if type is "enabled"++class CreateArgumentsConfigModel(BaseModel):model: strmax_tokens: int | None = 4096@@ -66,6 +81,7 @@ class CreateArgumentsConfigModel(BaseModel):stop_sequences: List[str] | None = Noneresponse_format: ResponseFormat | None = Nonemetadata: Dict[str, str] | None = None+ thinking: ThinkingConfigModel | None = Noneclass BaseAnthropicClientConfigurationConfigModel(CreateArgumentsConfigModel):diff --git a/python/packages/autogen-ext/tests/models/test_anthropic_model_client.py b/python/packages/autogen-ext/tests/models/test_anthropic_model_client.pyindex 13bff87ca..6238eee3b 100644--- a/python/packages/autogen-ext/tests/models/test_anthropic_model_client.py+++ b/python/packages/autogen-ext/tests/models/test_anthropic_model_client.py@@ -1107,3 +1107,150 @@ async def test_streaming_tool_usage_with_arguments(provider: str) -> None:assert isinstance(content, FunctionCall)assert content.name == "add_numbers"assert json.loads(content.arguments) is not None+++def test_mock_thinking_config_validation() -> None:+ """Test thinking configuration handling logic."""+ client = AnthropicChatCompletionClient(+ model="claude-3-haiku-20240307", # Known model for basic validation+ api_key="fake-key",+ )++ # Test valid enabled thinking config+ valid_config = {"thinking": {"type": "enabled", "budget_tokens": 2000}}+ result = client._get_thinking_config(valid_config) # pyright: ignore[reportPrivateUsage]+ assert result == valid_config++ # Test thinking config with any budget_tokens (API will validate)+ any_budget_config = {"thinking": {"type": "enabled", "budget_tokens": 500}}+ result = client._get_thinking_config(any_budget_config) # pyright: ignore[reportPrivateUsage]+ assert result == any_budget_config++ # Test valid disabled thinking config+ disabled_config = {"thinking": {"type": "disabled"}}+ result = client._get_thinking_config(disabled_config) # pyright: ignore[reportPrivateUsage]+ assert result == disabled_config++ # Test no thinking config+ result = client._get_thinking_config({}) # pyright: ignore[reportPrivateUsage]+ assert result == {}++ # Test thinking config from base create_args+ client_with_thinking = AnthropicChatCompletionClient(+ model="claude-sonnet-4-20250514",+ api_key="fake-key",+ model_info={+ "vision": True,+ "function_calling": True,+ "json_output": True,+ "family": "anthropic",+ "structured_output": True,+ },+ thinking={"type": "enabled", "budget_tokens": 3000},+ )+ result = client_with_thinking._get_thinking_config({}) # pyright: ignore[reportPrivateUsage]+ assert result == {"thinking": {"type": "enabled", "budget_tokens": 3000}}++ # Test extra_create_args takes priority over base create_args+ override_config = {"thinking": {"type": "enabled", "budget_tokens": 4000}}+ result = client_with_thinking._get_thinking_config(override_config) # pyright: ignore[reportPrivateUsage]+ assert result == override_config+++async def test_anthropic_thinking_mode_basic() -> None:+ """Test basic thinking mode functionality."""+ api_key = os.getenv("ANTHROPIC_API_KEY")+ if not api_key:+ pytest.skip("ANTHROPIC_API_KEY not found in environment variables")++ client = AnthropicChatCompletionClient(+ model="claude-sonnet-4-20250514", # Use a model that supports thinking+ api_key=api_key,+ temperature=0.7, # Should be overridden to 1.0+ )++ messages = [UserMessage(content="Calculate 17 * 23 step by step.", source="test")]++ # Test WITHOUT thinking mode+ result_no_thinking = await client.create(messages)+ assert isinstance(result_no_thinking.content, str)+ assert result_no_thinking.thought is None++ # Test WITH thinking mode+ thinking_config = {"thinking": {"type": "enabled", "budget_tokens": 2000}}++ result_with_thinking = await client.create(messages, extra_create_args=thinking_config)+ assert isinstance(result_with_thinking.content, str)+ # Should have thinking content+ assert result_with_thinking.thought is not None+ assert len(result_with_thinking.thought) > 10+ # Main content should contain the final answer+ assert "391" in result_with_thinking.content or "17" in result_with_thinking.content+++async def test_anthropic_thinking_mode_streaming() -> None:+ """Test thinking mode with streaming."""+ api_key = os.getenv("ANTHROPIC_API_KEY")+ if not api_key:+ pytest.skip("ANTHROPIC_API_KEY not found in environment variables")++ client = AnthropicChatCompletionClient(+ model="claude-sonnet-4-20250514", # Use a model that supports thinking+ api_key=api_key,+ )++ messages = [UserMessage(content="What is 15 + 27? Think through it step by step.", source="test")]++ thinking_config = {"thinking": {"type": "enabled", "budget_tokens": 1500}}++ chunks: List[str | CreateResult] = []+ async for chunk in client.create_stream(messages, extra_create_args=thinking_config):+ chunks.append(chunk)++ # Should have received chunks+ assert len(chunks) > 1++ # Final result should have thinking content+ final_result = chunks[-1]+ assert isinstance(final_result, CreateResult)+ assert isinstance(final_result.content, str)+ assert final_result.thought is not None+ assert len(final_result.thought) > 10+ # Should contain the answer+ assert "42" in final_result.content+++async def test_anthropic_thinking_mode_with_tools() -> None:+ """Test thinking mode combined with tool calling."""+ api_key = os.getenv("ANTHROPIC_API_KEY")+ if not api_key:+ pytest.skip("ANTHROPIC_API_KEY not found in environment variables")++ client = AnthropicChatCompletionClient(+ model="claude-sonnet-4-20250514", # Use a model that supports thinking+ api_key=api_key,+ )++ # Define tool+ add_tool = FunctionTool(_add_numbers, description="Add two numbers together", name="add_numbers")++ messages = [+ UserMessage(content="I need to add 25 and 17. Use the add tool after thinking about it.", source="test")+ ]++ thinking_config = {"thinking": {"type": "enabled", "budget_tokens": 2000}}++ result = await client.create(messages, tools=[add_tool], extra_create_args=thinking_config)++ # Should get tool calls+ assert isinstance(result.content, list)+ assert len(result.content) >= 1+ assert isinstance(result.content[0], FunctionCall)+ assert result.content[0].name == "add_numbers"++ # Should have thinking content even with tool calls+ assert result.thought is not None+ assert len(result.thought) > 10