Skip to content

Commit

Permalink
Merge pull request #15 from lordlinus/cleanup
Browse files Browse the repository at this point in the history
re-organise and remove debug logging
  • Loading branch information
lordlinus authored Nov 10, 2024
2 parents 7511fd4 + dbf2f2d commit 1bc8ac3
Show file tree
Hide file tree
Showing 13 changed files with 101 additions and 453 deletions.
13 changes: 0 additions & 13 deletions backend/agents/ext_agents.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,19 +17,6 @@
from ..otlp_tracing import logger


# class Message(BaseModel):
# """
# Represents a message exchanged during the chat.

# Attributes:
# content (str): The textual content of the message.
# sources (Optional[List[Resource]]): List of resources associated with the message.
# """

# content: str
# sources: Optional[List[Resource]] = None


@default_subscription
@type_subscription("default_agent")
class LlamaIndexAgent(RoutedAgent):
Expand Down
3 changes: 1 addition & 2 deletions backend/agents/travel_activities.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,11 @@
from ..config import Config
from ..data_types import (
Activities,
AgentResponse,
AgentStructuredResponse,
EndUserMessage,
GroupChatMessage,
HandoffMessage,
TravelRequest,
AgentStructuredResponse,
)
from ..otlp_tracing import logger

Expand Down
8 changes: 2 additions & 6 deletions backend/agents/travel_car.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,11 +43,6 @@ async def simulate_car_rental_booking(
{"car_type": "Electric", "company": "Tesla Rentals", "price_per_day": 120},
{"car_type": "Hybrid", "company": "Green Wheels", "price_per_day": 60},
{"car_type": "Sports Car", "company": "Exotic Rentals", "price_per_day": 200},
{"car_type": "Station Wagon", "company": "Family Rentals", "price_per_day": 75},
{"car_type": "Van", "company": "Van Rentals Inc.", "price_per_day": 85},
{"car_type": "Crossover", "company": "Cross Rentals", "price_per_day": 65},
{"car_type": "Coupe", "company": "Luxury Line", "price_per_day": 110},
{"car_type": "Hatchback", "company": "City Rentals", "price_per_day": 45},
]

selected_car = random.choice(car_options)
Expand Down Expand Up @@ -121,7 +116,7 @@ async def handle_message(
AgentStructuredResponse(
agent_type=self.id.type,
data=response,
content=f"Car rented: {response}",
message=f"Car rented: {response}",
),
DefaultTopicId(type="user_proxy", source=ctx.topic_id.source),
)
Expand All @@ -148,4 +143,5 @@ async def handle_travel_request(
return GroupChatMessage(
source=self.id.type,
content=f"Car rented: {response}",

)
10 changes: 5 additions & 5 deletions backend/agents/travel_destination.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,9 +58,8 @@ async def handle_message(
json.loads(response_content.content)
)
except Exception as e:
logger.error(f"Failed to parse activities response: {str(e)}")
logger.error(f"Failed to parse destination response: {str(e)}")
destination_info_structured = DestinationInfo()
pass

await self.publish_message(
AgentStructuredResponse(
Expand Down Expand Up @@ -93,9 +92,10 @@ async def handle_travel_request(
json.loads(response_content.content)
)
except Exception as e:
logger.error(f"Failed to parse activities response: {str(e)}")
logger.error(f"Failed to parse destination response: {str(e)}")
destination_info_structured = DestinationInfo()
pass

return GroupChatMessage(
source=self.id.type, content=destination_info_structured.model_dump_json()
source=self.id.type,
content=destination_info_structured.model_dump_json(),
)
6 changes: 4 additions & 2 deletions backend/agents/travel_flight.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ async def simulate_flight_booking(
destination_city: str = "Paris",
departure_date: str = "2023-12-20",
return_date: str = "2023-12-30",
number_of_passengers: int = 2,
) -> FlightBooking:
flight_options = [
{"airline": "Air France", "flight_number": "AF123", "price_per_ticket": 200},
Expand Down Expand Up @@ -56,7 +57,7 @@ async def simulate_flight_booking(
flight_number=selected_flight["flight_number"],
total_price=total_price,
booking_reference=booking_reference,
number_of_passengers=2,
number_of_passengers=number_of_passengers,
)


Expand Down Expand Up @@ -106,7 +107,8 @@ async def handle_travel_request(
) -> GroupChatMessage:
logger.info(f"FlightAgent received travel request sub-task: {message.content}")

response = await simulate_flight_booking()
return GroupChatMessage(
source=self.id.type,
content="Flight booking processed as requested and confirmation will be sent by email",
content=f"Flight booking processed: {response}",
)
38 changes: 34 additions & 4 deletions backend/agents/travel_group_chat.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,16 @@ async def handle_complex_travel_request(
)
for task in message.subtasks
]
group_results: List[GroupChatMessage] = await asyncio.gather(*tasks)
try:
group_results: List[GroupChatMessage] = await asyncio.gather(*tasks)
logger.info("-" * 50)
logger.info(
f"GroupChatManager received responses from agents: {group_results}"
)
logger.info("-" * 50)
except Exception as e:
logger.error(f"Error sending messages to agents: {e}")
return

logger.info(f"GroupChatManager received responses from agents: {group_results}")
# Compile the final travel plan based on agent responses
Expand All @@ -90,7 +99,7 @@ async def handle_complex_travel_request(
await self.publish_message(
AgentStructuredResponse(
agent_type=self.id.type,
data=GroupChatResponse(
data=GroupChatMessage(
source=self.id.type,
content=final_plan,
),
Expand All @@ -116,7 +125,7 @@ async def request_relevant_agents(self, relevant_agents: List[str]) -> None:
TravelRequest(
source="GroupChatManager",
content="Provide details for the travel plan",
requirements={"destination_city": "Paris"},
original_task="General travel plan",
),
DefaultTopicId(type=agent_type, source=self._session_id),
)
Expand All @@ -133,9 +142,30 @@ async def handle_handoff(self, message: TravelRequest, ctx: MessageContext) -> N
session_id = ctx.topic_id.source
logger.info(f"Received handoff message from {message.source}")

if message.complete:
if message.original_task and "complete" in message.content.lower():
self._conversation_complete = True
logger.info("Conversation completed. Clearing session.")
# Add cleanup or finalization logic here if needed.
else:
await self.compile_final_plan()

async def compile_final_plan(self) -> None:
"""
Compiles the final travel plan based on collected responses from agents.
"""
logger.info("Compiling final travel plan from collected responses.")
final_plan = "\n".join(
response.content for response in self._responses[self._session_id]
)
logger.info(f"Compiled Final Travel Plan: {final_plan}")
await self.publish_message(
AgentStructuredResponse(
agent_type=self.id.type,
data=GroupChatResponse(
source=self.id.type,
content=final_plan,
),
message=f"Here is your comprehensive travel plan:\n{final_plan}",
),
DefaultTopicId(type="user_proxy", source=self._session_id),
)
21 changes: 8 additions & 13 deletions backend/agents/travel_hotel.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,19 +45,6 @@ async def create_hotel_booking(
{"hotel_name": "Hyatt", "room_type": "Suite", "price_per_night": 300},
{"hotel_name": "Sheraton", "room_type": "Executive", "price_per_night": 250},
{"hotel_name": "Holiday Inn", "room_type": "Standard", "price_per_night": 100},
{"hotel_name": "Ritz-Carlton", "room_type": "Luxury", "price_per_night": 400},
{
"hotel_name": "Four Seasons",
"room_type": "Presidential Suite",
"price_per_night": 500,
},
{
"hotel_name": "InterContinental",
"room_type": "Club Room",
"price_per_night": 350,
},
{"hotel_name": "Westin", "room_type": "Deluxe", "price_per_night": 220},
{"hotel_name": "Radisson", "room_type": "Standard", "price_per_night": 180},
]

# Randomly select a hotel option
Expand Down Expand Up @@ -180,6 +167,14 @@ async def handle_travel_request(
response_content = await self._process_request(message.content, ctx)
logger.info(f"HotelAgent response: {response_content}")

simulated_func_call = await create_hotel_booking(
city="Singapore",
check_in_date=datetime.datetime.now().strftime("%Y-%m-%d"),
check_out_date=(
datetime.datetime.now() + datetime.timedelta(days=5)
).strftime("%Y-%m-%d"),
)

return GroupChatMessage(
source=self.id.type,
content=f"{response_content}",
Expand Down
31 changes: 3 additions & 28 deletions backend/agents/travel_router.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,9 @@
AgentStructuredResponse,
Greeter,
)
from ..intent import IntentClassifier
from ..otlp_tracing import logger
from ..registry import AgentRegistry
from ..session_state import SessionStateManager
from ..registry import AgentRegistry

agent_registry = AgentRegistry()

Expand All @@ -45,14 +43,12 @@ def __init__(
name: str,
model_client: AzureOpenAIChatCompletionClient,
agent_registry: AgentRegistry,
intent_classifier: IntentClassifier,
session_manager: SessionStateManager,
) -> None:
super().__init__("SemanticRouterAgent")
self._name = name
self._model_client = model_client
self._registry = agent_registry
self._classifier = intent_classifier
self._session_manager = session_manager

@message_handler
Expand Down Expand Up @@ -127,7 +123,7 @@ async def handle_handoff(
logger.info(f"Received handoff message from {message.source}")

# Clear session if conversation is complete, otherwise continue routing
if message.complete:
if message.original_task and "complete" in message.content.lower():
self._session_manager.clear_session(session_id)
else:
await self.route_message(
Expand Down Expand Up @@ -156,31 +152,10 @@ async def _get_agents_to_route(
system_message = agent_registry.get_planner_prompt(
message=message, history=history
)
logger.info(f"System message: {system_message}")
# logger.info(f"System message: {system_message}")
except Exception as e:
logger.error(e)
# system_message = f"""
# You are an orchestration agent.
# Your job is to decide which agents to run based on the user's request and the conversation history.
# Below are the available agents:

# * hotel_booking - Helps in booking hotels. Available functions
# * activities_booking - Helps in providing activities information.
# * flight_booking - Helps in providing flight information.
# * car_rental - Helps in booking car rentals.
# * group_chat_manager - Coordinates messages between agents to create a travel plan.
# * destination_info - Provides information about a destination city.
# * default_agent - Handles any other requests that do not match the above agents, including greetings and general queries.

# The current user message: {message.content}
# Conversation history so far: {[msg.content for msg in history]}

# Note:
# - If the user's message is a greeting or a general query, assign it to `default_agent`.
# - For other requests, analyze and break down the user's message into appropriate subtasks.
# - Assign each subtask to the relevant agent by setting `assigned_agent`.
# - Ensure that `assigned_agent` is not blank.
# """

try:
response = await self._model_client.create(
[SystemMessage(system_message)],
Expand Down
39 changes: 1 addition & 38 deletions backend/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,6 @@
from backend.otlp_tracing import logger
from backend.utils import initialize_agent_runtime, get_web_pub_client

from azure.messaging.webpubsubservice import WebPubSubServiceClient


@asynccontextmanager
async def lifespan(app: FastAPI):
"""
Expand Down Expand Up @@ -115,11 +112,6 @@ async def handle_websocket(self, websocket: WebSocket, session_id: str):
user_message,
DefaultTopicId(type="user_proxy", source=session_id),
)
# Send message to WebPubSub
web_pubsub_client.send_to_all(
content_type="application/json",
message={"from": session_id, "message": user_message_text},
)
await asyncio.sleep(0.1)
except WebSocketDisconnect:
logger.info(f"WebSocket connection closed: {session_id}")
Expand All @@ -134,35 +126,6 @@ async def handle_websocket(self, websocket: WebSocket, session_id: str):
logger.info(f"WebSocket already closed: {session_id}")


# Default Agent
# @default_subscription
# class DefaultAgent(RoutedAgent):
# """
# Handles messages that do not match any specific intent.
# """

# def __init__(self) -> None:
# super().__init__("DefaultAgent")

# @message_handler
# async def handle_unknown_intent(
# self, message: EndUserMessage, ctx: MessageContext
# ) -> None:
# """
# Handles messages with unknown intent by providing a default response.

# Args:
# message (EndUserMessage): The user's message.
# ctx (MessageContext): The message context.
# """
# logger.info(f"DefaultAgent received message: {message.content}")
# content = "I'm sorry, I couldn't understand your request. Could you please provide more details?"
# await self.publish_message(
# AgentResponse(source="DefaultAgent", content=content),
# DefaultTopicId(type="user_proxy", source=ctx.topic_id.source),
# )


# User Proxy Agent
@default_subscription
class UserProxyAgent(RoutedAgent):
Expand All @@ -183,7 +146,7 @@ async def handle_agent_response(
Sends the agent's response back to the user via WebSocket.
Args:
message (AgentResponse): The agent's response message.
message (AgentStructuredResponse): The agent's response message.
ctx (MessageContext): The message context.
"""
logger.info(f"UserProxyAgent received agent response: {message}")
Expand Down
Loading

0 comments on commit 1bc8ac3

Please sign in to comment.