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.4 kB

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