Skip to content

Commit

Permalink
clean up tool agent registration
Browse files Browse the repository at this point in the history
  • Loading branch information
lordlinus committed Nov 3, 2024
1 parent 4522c8c commit 199e51f
Show file tree
Hide file tree
Showing 4 changed files with 64 additions and 36 deletions.
25 changes: 17 additions & 8 deletions backend/agents/travel_activities.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,13 @@

import aiohttp
from autogen_core.base import AgentId, MessageContext
from autogen_core.components import (DefaultTopicId, RoutedAgent,
message_handler, type_subscription)
from autogen_core.components.models import (LLMMessage, SystemMessage,
UserMessage)
from autogen_core.components import (
DefaultTopicId,
RoutedAgent,
message_handler,
type_subscription,
)
from autogen_core.components.models import LLMMessage, SystemMessage, UserMessage
from autogen_core.components.tool_agent import tool_agent_caller_loop
from autogen_core.components.tools import FunctionTool, Tool
from autogen_ext.models import AzureOpenAIChatCompletionClient
Expand All @@ -16,8 +19,14 @@
from typing_extensions import Annotated

from ..config import Config
from ..data_types import (Activities, AgentResponse, EndUserMessage,
GroupChatMessage, HandoffMessage, TravelRequest)
from ..data_types import (
Activities,
AgentResponse,
EndUserMessage,
GroupChatMessage,
HandoffMessage,
TravelRequest,
)
from ..otlp_tracing import logger


Expand Down Expand Up @@ -98,7 +107,7 @@ def __init__(
self,
model_client: AzureOpenAIChatCompletionClient,
tools: List[Tool],
tool_agent_id: AgentId,
tool_agent_type: str,
) -> None:
super().__init__("ActivitiesAgent")
self._system_messages: List[LLMMessage] = [
Expand All @@ -108,7 +117,7 @@ def __init__(
]
self._model_client = model_client
self._tools = tools
self._tool_agent_id = tool_agent_id
self._tool_agent_id = AgentId(tool_agent_type, self.id.key)

async def _process_request(
self, message_content: str, ctx: MessageContext
Expand Down
33 changes: 22 additions & 11 deletions backend/agents/travel_hotel.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,25 @@
from typing import Dict, List

from autogen_core.base import AgentId, MessageContext
from autogen_core.components import (DefaultTopicId, RoutedAgent,
message_handler, type_subscription)
from autogen_core.components.models import (LLMMessage, SystemMessage,
UserMessage)
from autogen_core.components import (
DefaultTopicId,
RoutedAgent,
message_handler,
type_subscription,
)
from autogen_core.components.models import LLMMessage, SystemMessage, UserMessage
from autogen_core.components.tool_agent import tool_agent_caller_loop
from autogen_core.components.tools import FunctionTool, Tool
from autogen_ext.models import AzureOpenAIChatCompletionClient
from typing_extensions import Annotated

from ..data_types import (AgentResponse, EndUserMessage, GroupChatMessage,
HandoffMessage, TravelRequest)
from ..data_types import (
AgentResponse,
EndUserMessage,
GroupChatMessage,
HandoffMessage,
TravelRequest,
)
from ..otlp_tracing import logger


Expand All @@ -27,6 +35,9 @@ async def create_hotel_booking(
],
) -> Dict[str, str | int]:
# Simulate available hotel options
logger.info(
f"Function call: Creating hotel booking for {city} from {check_in_date} to {check_out_date}"
)
hotel_options = [
{"hotel_name": "Hilton", "room_type": "Deluxe", "price_per_night": 200},
{"hotel_name": "Marriott", "room_type": "Standard", "price_per_night": 150},
Expand Down Expand Up @@ -72,6 +83,7 @@ async def create_hotel_booking(
"total_price": total_price,
"booking_reference": booking_reference,
}
logger.info(f"Hotel booking details: {hotel_booking_details}")

return hotel_booking_details

Expand All @@ -92,17 +104,15 @@ def __init__(
self,
model_client: AzureOpenAIChatCompletionClient,
tools: List[Tool],
tool_agent_id: AgentId,
tool_agent_type: str,
) -> None:
super().__init__("HotelAgent")
self._system_messages: List[LLMMessage] = [
SystemMessage(
"You are a helpful AI assistant that can advise on hotel bookings based on user preferences."
)
SystemMessage("You are a helpful AI assistant that can make hotel booking.")
]
self._model_client = model_client
self._tools = tools
self._tool_agent_id = tool_agent_id
self._tool_agent_id = AgentId(tool_agent_type, self.id.key)

async def _process_request(self, message_content: str, ctx: MessageContext) -> str:
# Create a session for the activities agent
Expand All @@ -119,6 +129,7 @@ async def _process_request(self, message_content: str, ctx: MessageContext) -> s
tool_schema=self._tools,
cancellation_token=ctx.cancellation_token,
)
logger.info(f"Tool agent caller loop completed: {messages}")
except Exception as e:
logger.error(f"Tool agent caller loop failed: {str(e)}")
return "Failed to book hotel. Please try again."
Expand Down
20 changes: 15 additions & 5 deletions backend/app.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,28 @@
import sys
import os

# Add the root directory of the project to the Python path
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

import asyncio
import uuid
from contextlib import asynccontextmanager
from typing import Dict

from autogen_core.base import MessageContext
from autogen_core.components import (DefaultTopicId, RoutedAgent,
default_subscription, message_handler)
from autogen_core.components import (
DefaultTopicId,
RoutedAgent,
default_subscription,
message_handler,
)
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor
from starlette.websockets import WebSocketState

from .data_types import AgentResponse, EndUserMessage
from .otlp_tracing import logger
from .utils import initialize_agent_runtime
from backend.data_types import AgentResponse, EndUserMessage
from backend.otlp_tracing import logger
from backend.utils import initialize_agent_runtime


@asynccontextmanager
Expand Down
22 changes: 10 additions & 12 deletions backend/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,7 @@
from llama_index.tools.wikipedia import WikipediaToolSpec

from .agents.ext_agents import LlamaIndexAgent
from .agents.travel_activities import (ActivitiesAgent,
get_travel_activity_tools)
from .agents.travel_activities import ActivitiesAgent, get_travel_activity_tools
from .agents.travel_car import CarRentalAgent
from .agents.travel_destination import DestinationAgent
from .agents.travel_flight import FlightAgent
Expand All @@ -32,8 +31,8 @@
# Create AzureOpenAI model instance
llm = AzureOpenAI(
deployment_name=Config.AZURE_OPENAI_DEPLOYMENT_NAME,
temperature=0.0,
max_tokens=1000,
temperature=0.01,
max_tokens=2000,
api_key=Config.AZURE_OPENAI_API_KEY,
azure_endpoint=Config.AZURE_OPENAI_ENDPOINT,
api_version=Config.AZURE_OPENAI_API_VERSION,
Expand Down Expand Up @@ -63,28 +62,26 @@ async def initialize_agent_runtime() -> SingleThreadedAgentRuntime:
intent_classifier = IntentClassifier()
agent_registry = AgentRegistry()
travel_activity_tools = get_travel_activity_tools()
travel_activity_tool_agent_id = AgentId("activity_tool_executor_agent", "default")
hotel_booking_tool = get_hotel_booking_tool()
hotel_booking_tool_agent_id = AgentId(
"hotel_booking_tool_executor_agent", "default"
)

# Register Tool Agents
await ToolAgent.register(
agent_runtime,
"activity_tool_executor_agent",
lambda: ToolAgent("Travel tool executor agent", travel_activity_tools),
)
await ToolAgent.register(
agent_runtime,
"hotel_tool_executor_agent",
"hotel_booking_tool_exec_agent",
lambda: ToolAgent("Hotel tool executor agent", hotel_booking_tool),
)

# Add subscriptions
await agent_runtime.add_subscription(
DefaultSubscription(topic_type="user_proxy", agent_type="user_proxy")
)

# Register agents with the runtime
# Register Semantic Router Agent
await SemanticRouterAgent.register(
agent_runtime,
"router",
Expand All @@ -97,20 +94,21 @@ async def initialize_agent_runtime() -> SingleThreadedAgentRuntime:
),
)

# Register other agents
await FlightAgent.register(agent_runtime, "flight_booking", lambda: FlightAgent())
await HotelAgent.register(
agent_runtime,
"hotel_booking",
lambda: HotelAgent(
aoai_model_client, hotel_booking_tool, hotel_booking_tool_agent_id
aoai_model_client, hotel_booking_tool, "hotel_booking_tool_exec_agent"
),
)
await CarRentalAgent.register(agent_runtime, "car_rental", lambda: CarRentalAgent())
await ActivitiesAgent.register(
agent_runtime,
"activities_booking",
lambda: ActivitiesAgent(
aoai_model_client, travel_activity_tools, travel_activity_tool_agent_id
aoai_model_client, travel_activity_tools, "activity_tool_executor_agent"
),
)
await DestinationAgent.register(
Expand Down

0 comments on commit 199e51f

Please sign in to comment.