237 lines
8.4 KiB
Plaintext
237 lines
8.4 KiB
Plaintext
{
|
|
"cells": [
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "1ad612e0",
|
|
"metadata": {},
|
|
"source": [
|
|
"AG2 Async Agent Chat with Automated Responses\n",
|
|
"\n",
|
|
"This notebook demonstrates how to leverage asynchronous programming with AG2 agents \n",
|
|
"to create automated conversations between AI agents, eliminating the need for human \n",
|
|
"input while maintaining full traceability.\n",
|
|
"\n",
|
|
"Overview\n",
|
|
"This notebook demonstrates a practical example of automated AI-to-AI communication where we:\n",
|
|
"\n",
|
|
"1. Initialize AG2 agents with OpenAI's GPT-4o-mini model\n",
|
|
"2. Create custom async agents that simulate human-like responses and processing delays\n",
|
|
"3. Automate the entire conversation flow without requiring manual intervention\n",
|
|
"4. Track all interactions using AgentOps for monitoring and analysis\n",
|
|
"\n",
|
|
"By using async operations and automated responses, you can create fully autonomous \n",
|
|
"agent conversations that simulate real-world scenarios. This is particularly useful \n",
|
|
"for testing, prototyping, and creating demos where you want to showcase agent \n",
|
|
"capabilities without manual input."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"id": "361b3cf5",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"%pip install agentops\n",
|
|
"%pip install ag2\n",
|
|
"%pip install nest-asyncio"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"id": "9962270b",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"import asyncio\n",
|
|
"from typing import Dict, Optional, Union\n",
|
|
"import os\n",
|
|
"from dotenv import load_dotenv\n",
|
|
"import nest_asyncio\n",
|
|
"import agentops\n",
|
|
"from autogen import AssistantAgent\n",
|
|
"from autogen.agentchat.user_proxy_agent import UserProxyAgent"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"id": "60e84ffb",
|
|
"metadata": {
|
|
"lines_to_next_cell": 1
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"# Load environment variables for API keys\n",
|
|
"load_dotenv()\n",
|
|
"os.environ[\"AGENTOPS_API_KEY\"] = os.getenv(\"AGENTOPS_API_KEY\", \"your_api_key_here\")\n",
|
|
"os.environ[\"OPENAI_API_KEY\"] = os.getenv(\"OPENAI_API_KEY\", \"your_openai_api_key_here\")\n",
|
|
"# Initialize AgentOps for tracking and monitoring\n",
|
|
"agentops.init(auto_start_session=False, trace_name=\"AG2 Async Demo\")\n",
|
|
"tracer = agentops.start_trace(trace_name=\"AG2 Async Agent Demo\", tags=[\"ag2-async-demo\", \"agentops-example\"])"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"id": "8c1dc105",
|
|
"metadata": {
|
|
"lines_to_next_cell": 1
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"# Define an asynchronous function that simulates async processing\n",
|
|
"async def simulate_async_processing(task_name: str, delay: float = 1.0) -> str:\n",
|
|
" \"\"\"\n",
|
|
" Simulate some asynchronous processing (e.g., API calls, file operations, etc.)\n",
|
|
" \"\"\"\n",
|
|
" print(f\"🔄 Starting async task: {task_name}\")\n",
|
|
" await asyncio.sleep(delay) # Simulate async work\n",
|
|
" print(f\"✅ Completed async task: {task_name}\")\n",
|
|
" return f\"Processed: {task_name}\""
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"id": "0d683b3d",
|
|
"metadata": {
|
|
"lines_to_next_cell": 1
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"# Define a custom UserProxyAgent that simulates automated user responses\n",
|
|
"class AutomatedUserProxyAgent(UserProxyAgent):\n",
|
|
" def __init__(self, name: str, **kwargs):\n",
|
|
" super().__init__(name, **kwargs)\n",
|
|
" self.response_count = 0\n",
|
|
" self.predefined_responses = [\n",
|
|
" \"Yes, please generate interview questions for these topics.\",\n",
|
|
" \"The questions look good. Can you make them more specific to senior-level positions?\",\n",
|
|
" \"Perfect! These questions are exactly what we need. Thank you!\",\n",
|
|
" ]\n",
|
|
"\n",
|
|
" async def a_get_human_input(self, prompt: str) -> str:\n",
|
|
" # Simulate async processing before responding\n",
|
|
" await simulate_async_processing(f\"Processing user input #{self.response_count + 1}\")\n",
|
|
"\n",
|
|
" if self.response_count < len(self.predefined_responses):\n",
|
|
" response = self.predefined_responses[self.response_count]\n",
|
|
" self.response_count += 1\n",
|
|
" print(f\"👤 User: {response}\")\n",
|
|
" return response\n",
|
|
" else:\n",
|
|
" print(\"👤 User: TERMINATE\")\n",
|
|
" return \"TERMINATE\"\n",
|
|
"\n",
|
|
" async def a_receive(\n",
|
|
" self,\n",
|
|
" message: Union[Dict, str],\n",
|
|
" sender,\n",
|
|
" request_reply: Optional[bool] = None,\n",
|
|
" silent: Optional[bool] = False,\n",
|
|
" ):\n",
|
|
" await super().a_receive(message, sender, request_reply, silent)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"id": "b792d207",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"# Define an AssistantAgent that simulates async processing before responding\n",
|
|
"class AsyncAssistantAgent(AssistantAgent):\n",
|
|
" async def a_receive(\n",
|
|
" self,\n",
|
|
" message: Union[Dict, str],\n",
|
|
" sender,\n",
|
|
" request_reply: Optional[bool] = None,\n",
|
|
" silent: Optional[bool] = False,\n",
|
|
" ):\n",
|
|
" # Simulate async processing before responding\n",
|
|
" await simulate_async_processing(\"Analyzing request and preparing response\", 0.5)\n",
|
|
" await super().a_receive(message, sender, request_reply, silent)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"id": "7f8c6c50",
|
|
"metadata": {
|
|
"lines_to_next_cell": 1
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"async def main():\n",
|
|
" print(\"🚀 Starting AG2 Async Demo\")\n",
|
|
"\n",
|
|
" # Create agents with automated behavior\n",
|
|
" user_proxy = AutomatedUserProxyAgent(\n",
|
|
" name=\"hiring_manager\",\n",
|
|
" human_input_mode=\"NEVER\", # No human input required\n",
|
|
" max_consecutive_auto_reply=3,\n",
|
|
" code_execution_config=False,\n",
|
|
" is_termination_msg=lambda msg: \"TERMINATE\" in str(msg.get(\"content\", \"\")),\n",
|
|
" )\n",
|
|
"\n",
|
|
" assistant = AsyncAssistantAgent(\n",
|
|
" name=\"interview_consultant\",\n",
|
|
" system_message=\"\"\"You are an expert interview consultant. When given interview topics, \n",
|
|
" you create thoughtful, relevant questions. You ask for feedback and incorporate it.\n",
|
|
" When the user is satisfied with the questions, end with 'TERMINATE'.\"\"\",\n",
|
|
" llm_config={\"config_list\": [{\"model\": \"gpt-4o-mini\", \"api_key\": os.environ.get(\"OPENAI_API_KEY\")}]},\n",
|
|
" is_termination_msg=lambda msg: \"TERMINATE\" in str(msg.get(\"content\", \"\")),\n",
|
|
" )\n",
|
|
"\n",
|
|
" try:\n",
|
|
" print(\"🤖 Initiating automated conversation...\")\n",
|
|
" # Start the automated chat between the user and assistant\n",
|
|
" await user_proxy.a_initiate_chat(\n",
|
|
" assistant,\n",
|
|
" message=\"\"\"I need help creating interview questions for these topics:\n",
|
|
" - Resume Review\n",
|
|
" - Technical Skills Assessment \n",
|
|
" - Project Discussion\n",
|
|
" - Job Role Expectations\n",
|
|
" - Closing Remarks\n",
|
|
" \n",
|
|
" Please create 2-3 questions for each topic.\"\"\",\n",
|
|
" max_turns=6,\n",
|
|
" )\n",
|
|
" except Exception as e:\n",
|
|
" print(f\"\\n❌ Error occurred: {e}\")\n",
|
|
" finally:\n",
|
|
" agentops.end_trace(tracer, end_state=\"Success\")\n",
|
|
"\n",
|
|
" print(\"\\n🎉 Demo completed successfully!\")"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"id": "e4520d6f",
|
|
"metadata": {
|
|
"lines_to_next_cell": 2
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"# Run the main async demo\n",
|
|
"nest_asyncio.apply()\n",
|
|
"asyncio.run(main())"
|
|
]
|
|
}
|
|
],
|
|
"metadata": {
|
|
"jupytext": {
|
|
"cell_metadata_filter": "-all",
|
|
"main_language": "python",
|
|
"notebook_metadata_filter": "-all"
|
|
}
|
|
},
|
|
"nbformat": 4,
|
|
"nbformat_minor": 5
|
|
}
|