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.

coding_direct_with_intercept.py 3.2 kB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. """
  2. This example show case how to intercept the tool execution using
  3. intervention hanlder.
  4. The intervention handler is used to intercept the FunctionCall message
  5. before it is sent out, and prompt the user for permission to execute the tool.
  6. """
  7. import asyncio
  8. import os
  9. import sys
  10. from typing import Any, List
  11. from agnext.application import SingleThreadedAgentRuntime
  12. from agnext.components import FunctionCall
  13. from agnext.components.code_executor import LocalCommandLineCodeExecutor
  14. from agnext.components.models import SystemMessage
  15. from agnext.components.tool_agent import ToolAgent, ToolException
  16. from agnext.components.tools import PythonCodeExecutionTool, Tool
  17. from agnext.core import AgentId, AgentInstantiationContext
  18. from agnext.core.intervention import DefaultInterventionHandler, DropMessage
  19. sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
  20. from coding_direct import Message, ToolUseAgent
  21. from common.utils import get_chat_completion_client_from_envs
  22. class ToolInterventionHandler(DefaultInterventionHandler):
  23. async def on_send(self, message: Any, *, sender: AgentId | None, recipient: AgentId) -> Any | type[DropMessage]:
  24. if isinstance(message, FunctionCall):
  25. # Request user prompt for tool execution.
  26. user_input = input(
  27. f"Function call: {message.name}\nArguments: {message.arguments}\nDo you want to execute the tool? (y/n): "
  28. )
  29. if user_input.strip().lower() != "y":
  30. raise ToolException(content="User denied tool execution.", call_id=message.id)
  31. return message
  32. async def main() -> None:
  33. # Create the runtime with the intervention handler.
  34. runtime = SingleThreadedAgentRuntime(intervention_handler=ToolInterventionHandler())
  35. # Define the tools.
  36. tools: List[Tool] = [
  37. # A tool that executes Python code.
  38. PythonCodeExecutionTool(
  39. LocalCommandLineCodeExecutor(),
  40. )
  41. ]
  42. # Register agents.
  43. await runtime.register(
  44. "tool_executor_agent",
  45. lambda: ToolAgent(
  46. description="Tool Executor Agent",
  47. tools=tools,
  48. ),
  49. )
  50. await runtime.register(
  51. "tool_enabled_agent",
  52. lambda: ToolUseAgent(
  53. description="Tool Use Agent",
  54. system_messages=[SystemMessage("You are a helpful AI Assistant. Use your tools to solve problems.")],
  55. model_client=get_chat_completion_client_from_envs(model="gpt-4o-mini"),
  56. tool_schema=[tool.schema for tool in tools],
  57. tool_agent=AgentId("tool_executor_agent", AgentInstantiationContext.current_agent_id().key),
  58. ),
  59. )
  60. runtime.start()
  61. # Send a task to the tool user.
  62. response = await runtime.send_message(
  63. Message("Run the following Python code: print('Hello, World!')"), AgentId("tool_enabled_agent", "default")
  64. )
  65. print(response.content)
  66. # Run the runtime until the task is completed.
  67. await runtime.stop()
  68. if __name__ == "__main__":
  69. import logging
  70. logging.basicConfig(level=logging.WARNING)
  71. logging.getLogger("agnext").setLevel(logging.DEBUG)
  72. asyncio.run(main())