A programming framework for agentic AI
Add tool agent class for convience of creating AI agents (#271)
Eric Zhu84d4e277763f
diff --git a/python/src/agnext/components/tool_agent/__init__.py b/python/src/agnext/components/tool_agent/__init__.pynew file mode 100644index 000000000..5c3b4026b--- /dev/null+++ b/python/src/agnext/components/tool_agent/__init__.py@@ -0,0 +1,15 @@+from ._tool_agent import (+ InvalidToolArgumentsException,+ ToolAgent,+ ToolException,+ ToolExecutionException,+ ToolNotFoundException,+)++__all__ = [+ "ToolAgent",+ "ToolException",+ "ToolNotFoundException",+ "InvalidToolArgumentsException",+ "ToolExecutionException",+]diff --git a/python/src/agnext/components/tool_agent/_tool_agent.py b/python/src/agnext/components/tool_agent/_tool_agent.pynew file mode 100644index 000000000..6d70e7931--- /dev/null+++ b/python/src/agnext/components/tool_agent/_tool_agent.py@@ -0,0 +1,90 @@+import json+from dataclasses import dataclass+from typing import List++from ...core import CancellationToken+from .. import FunctionCall, TypeRoutedAgent, message_handler+from ..models import FunctionExecutionResult+from ..tools import Tool++__all__ = [+ "ToolAgent",+ "ToolException",+ "ToolNotFoundException",+ "InvalidToolArgumentsException",+ "ToolExecutionException",+]+++@dataclass+class ToolException(BaseException):+ call_id: str+ content: str+++@dataclass+class ToolNotFoundException(ToolException):+ pass+++@dataclass+class InvalidToolArgumentsException(ToolException):+ pass+++@dataclass+class ToolExecutionException(ToolException):+ pass+++class ToolAgent(TypeRoutedAgent):+ """A tool agent accepts direct messages of the type `FunctionCall`,+ executes the requested tool with the provided arguments, and returns the+ result as `FunctionExecutionResult` messages.++ Args:+ description (str): The description of the agent.+ tools (List[Tool]): The list of tools that the agent can execute.+ """++ def __init__(+ self,+ description: str,+ tools: List[Tool],+ ) -> None:+ super().__init__(description)+ self._tools = tools++ @message_handler+ async def handle_function_call(+ self, message: FunctionCall, cancellation_token: CancellationToken+ ) -> FunctionExecutionResult:+ """Handles a `FunctionCall` message by executing the requested tool with the provided arguments.++ Args:+ message (FunctionCall): The function call message.+ cancellation_token (CancellationToken): The cancellation token.++ Returns:+ FunctionExecutionResult: The result of the function execution.++ Raises:+ ToolNotFoundException: If the tool is not found.+ InvalidToolArgumentsException: If the tool arguments are invalid.+ ToolExecutionException: If the tool execution fails.+ """+ tool = next((tool for tool in self._tools if tool.name == message.name), None)+ if tool is None:+ raise ToolNotFoundException(call_id=message.id, content=f"Error: Tool not found: {message.name}")+ else:+ try:+ arguments = json.loads(message.arguments)+ result = await tool.run_json(args=arguments, cancellation_token=cancellation_token)+ result_as_str = tool.return_value_as_string(result)+ except json.JSONDecodeError as e:+ raise InvalidToolArgumentsException(+ call_id=message.id, content=f"Error: Invalid arguments: {message.arguments}"+ ) from e+ except Exception as e:+ raise ToolExecutionException(call_id=message.id, content=f"Error: {e}") from e+ return FunctionExecutionResult(content=result_as_str, call_id=message.id)diff --git a/python/tests/test_tool_agent.py b/python/tests/test_tool_agent.pynew file mode 100644index 000000000..f2dd5423f--- /dev/null+++ b/python/tests/test_tool_agent.py@@ -0,0 +1,74 @@+import asyncio+import json++import pytest+from agnext.application import SingleThreadedAgentRuntime+from agnext.components import FunctionCall+from agnext.components.models import FunctionExecutionResult+from agnext.components.tool_agent import (+ InvalidToolArgumentsException,+ ToolAgent,+ ToolExecutionException,+ ToolNotFoundException,+)+from agnext.components.tools import FunctionTool+from agnext.core import CancellationToken+++def _pass_function(input: str) -> str:+ return "pass"+++def _raise_function(input: str) -> str:+ raise Exception("raise")+++async def _async_sleep_function(input: str) -> str:+ await asyncio.sleep(10)+ return "pass"+++async def test_tool_agent() -> None:+ runtime = SingleThreadedAgentRuntime()+ agent = await runtime.register_and_get(+ "tool_agent",+ lambda: ToolAgent(+ description="Tool agent",+ tools=[+ FunctionTool(_pass_function, name="pass", description="Pass function"),+ FunctionTool(_raise_function, name="raise", description="Raise function"),+ FunctionTool(_async_sleep_function, name="sleep", description="Sleep function"),+ ],+ ),+ )+ run = runtime.start()++ # Test pass function+ result = await runtime.send_message(+ FunctionCall(id="1", arguments=json.dumps({"input": "pass"}), name="pass"), agent+ )+ assert result == FunctionExecutionResult(call_id="1", content="pass")++ # Test raise function+ with pytest.raises(ToolExecutionException):+ await runtime.send_message(FunctionCall(id="2", arguments=json.dumps({"input": "raise"}), name="raise"), agent)++ # Test invalid tool name+ with pytest.raises(ToolNotFoundException):+ await runtime.send_message(FunctionCall(id="3", arguments=json.dumps({"input": "pass"}), name="invalid"), agent)++ # Test invalid arguments+ with pytest.raises(InvalidToolArgumentsException):+ await runtime.send_message(FunctionCall(id="3", arguments="invalid json /xd", name="pass"), agent)++ # Test sleep and cancel.+ token = CancellationToken()+ result_future = runtime.send_message(+ FunctionCall(id="3", arguments=json.dumps({"input": "sleep"}), name="sleep"), agent, cancellation_token=token+ )+ token.cancel()+ with pytest.raises(asyncio.CancelledError):+ await result_future++ await run.stop()