You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

test_tool_agent.py 2.5 kB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import asyncio
  2. import json
  3. import pytest
  4. from agnext.application import SingleThreadedAgentRuntime
  5. from agnext.components import FunctionCall
  6. from agnext.components.models import FunctionExecutionResult
  7. from agnext.components.tool_agent import (
  8. InvalidToolArgumentsException,
  9. ToolAgent,
  10. ToolExecutionException,
  11. ToolNotFoundException,
  12. )
  13. from agnext.components.tools import FunctionTool
  14. from agnext.core import CancellationToken
  15. from agnext.core import AgentId
  16. def _pass_function(input: str) -> str:
  17. return "pass"
  18. def _raise_function(input: str) -> str:
  19. raise Exception("raise")
  20. async def _async_sleep_function(input: str) -> str:
  21. await asyncio.sleep(10)
  22. return "pass"
  23. @pytest.mark.asyncio
  24. async def test_tool_agent() -> None:
  25. runtime = SingleThreadedAgentRuntime()
  26. await runtime.register(
  27. "tool_agent",
  28. lambda: ToolAgent(
  29. description="Tool agent",
  30. tools=[
  31. FunctionTool(_pass_function, name="pass", description="Pass function"),
  32. FunctionTool(_raise_function, name="raise", description="Raise function"),
  33. FunctionTool(_async_sleep_function, name="sleep", description="Sleep function"),
  34. ],
  35. ),
  36. )
  37. agent = AgentId("tool_agent", "default")
  38. runtime.start()
  39. # Test pass function
  40. result = await runtime.send_message(
  41. FunctionCall(id="1", arguments=json.dumps({"input": "pass"}), name="pass"), agent
  42. )
  43. assert result == FunctionExecutionResult(call_id="1", content="pass")
  44. # Test raise function
  45. with pytest.raises(ToolExecutionException):
  46. await runtime.send_message(FunctionCall(id="2", arguments=json.dumps({"input": "raise"}), name="raise"), agent)
  47. # Test invalid tool name
  48. with pytest.raises(ToolNotFoundException):
  49. await runtime.send_message(FunctionCall(id="3", arguments=json.dumps({"input": "pass"}), name="invalid"), agent)
  50. # Test invalid arguments
  51. with pytest.raises(InvalidToolArgumentsException):
  52. await runtime.send_message(FunctionCall(id="3", arguments="invalid json /xd", name="pass"), agent)
  53. # Test sleep and cancel.
  54. token = CancellationToken()
  55. result_future = runtime.send_message(
  56. FunctionCall(id="3", arguments=json.dumps({"input": "sleep"}), name="sleep"), agent, cancellation_token=token
  57. )
  58. token.cancel()
  59. with pytest.raises(asyncio.CancelledError):
  60. await result_future
  61. await runtime.stop()