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
Original file line number Diff line number Diff line change
Expand Up @@ -696,11 +696,26 @@ def _prepare_messages_for_anthropic(self, messages: Sequence[Message]) -> list[d

This skips the first message if it is a system message,
as Anthropic expects system instructions as a separate parameter.

Anthropic's API requires that the conversation ends with a user message.
If the last message is from the assistant, its role is changed to user
to satisfy this constraint.
"""
# first system message is passed as instructions
if messages and isinstance(messages[0], Message) and messages[0].role == "system":
return [self._prepare_message_for_anthropic(msg) for msg in messages[1:]]
return [self._prepare_message_for_anthropic(msg) for msg in messages]
msgs = list(messages[1:])
else:
msgs = list(messages)

result = [self._prepare_message_for_anthropic(msg) for msg in msgs]

# Anthropic requires the conversation to end with a user message.
# Re-role a trailing assistant message as user so chained agent
# outputs work as valid context for the next agent.
if result and result[-1].get("role") == "assistant":
result[-1] = {**result[-1], "role": "user"}
Comment on lines +712 to +716

return result

def _prepare_message_for_anthropic(self, message: Message) -> dict[str, Any]:
"""Prepare a Message for the Anthropic client.
Expand Down
6 changes: 3 additions & 3 deletions python/packages/core/agent_framework/_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -636,7 +636,7 @@ async def invoke(
parsed_arguments = dict(arguments)
if self.input_model is not None and not self._schema_supplied:
parsed_arguments = self.input_model.model_validate(parsed_arguments).model_dump(
exclude_none=True
exclude_none=False
)
Comment on lines 636 to 640
elif isinstance(arguments, BaseModel):
if (
Expand All @@ -645,7 +645,7 @@ async def invoke(
and not isinstance(arguments, self.input_model)
):
raise TypeError(f"Expected {self.input_model.__name__}, got {type(arguments).__name__}")
parsed_arguments = arguments.model_dump(exclude_none=True)
parsed_arguments = arguments.model_dump(exclude_none=False)
Comment on lines 645 to +648
else:
raise TypeError(
f"Expected mapping-like arguments for tool '{self.name}', got {type(arguments).__name__}"
Expand Down Expand Up @@ -1492,7 +1492,7 @@ async def _auto_invoke_function(
runtime_kwargs["session"] = invocation_session
try:
if not cast(bool, getattr(tool, "_schema_supplied", False)) and tool.input_model is not None:
args = tool.input_model.model_validate(parsed_args).model_dump(exclude_none=True)
args = tool.input_model.model_validate(parsed_args).model_dump(exclude_none=False)
else:
args = dict(parsed_args)
args = _validate_arguments_against_schema(
Expand Down
17 changes: 17 additions & 0 deletions python/packages/core/tests/core/test_tools.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
# Copyright (c) Microsoft. All rights reserved.
import asyncio
from typing import Annotated, Any, Literal, get_args, get_origin
from unittest.mock import Mock

Expand Down Expand Up @@ -1462,4 +1463,20 @@ def test_skip_parsing_is_singleton() -> None:
assert repr(SKIP_PARSING) == "SKIP_PARSING"


def test_invoke_preserves_explicit_none_arguments() -> None:
"""Optional parameters explicitly set to None must not be stripped before invocation."""

@tool
def greet(name: str, greeting: str | None = None) -> str:
return f"{greeting or 'Hello'}, {name}!"

result = asyncio.run(greet.invoke(arguments={"name": "World", "greeting": None}))
assert isinstance(result, list)
assert result[0].text == "Hello, World!"

result = asyncio.run(greet.invoke(arguments={"name": "World"}))
assert isinstance(result, list)
assert result[0].text == "Hello, World!"
Comment on lines +1466 to +1479


# endregion