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.

app_agent.py 2.4 kB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. from typing import List, cast
  2. import chainlit as cl
  3. import yaml
  4. from autogen_agentchat.agents import AssistantAgent
  5. from autogen_agentchat.base import Response
  6. from autogen_agentchat.messages import ModelClientStreamingChunkEvent, TextMessage
  7. from autogen_core import CancellationToken
  8. from autogen_core.models import ChatCompletionClient
  9. @cl.set_starters # type: ignore
  10. async def set_starts() -> List[cl.Starter]:
  11. return [
  12. cl.Starter(
  13. label="Greetings",
  14. message="Hello! What can you help me with today?",
  15. ),
  16. cl.Starter(
  17. label="Weather",
  18. message="Find the weather in New York City.",
  19. ),
  20. ]
  21. @cl.step(type="tool") # type: ignore
  22. async def get_weather(city: str) -> str:
  23. return f"The weather in {city} is 73 degrees and Sunny."
  24. @cl.on_chat_start # type: ignore
  25. async def start_chat() -> None:
  26. # Load model configuration and create the model client.
  27. with open("model_config.yaml", "r") as f:
  28. model_config = yaml.safe_load(f)
  29. model_client = ChatCompletionClient.load_component(model_config)
  30. # Create the assistant agent with the get_weather tool.
  31. assistant = AssistantAgent(
  32. name="assistant",
  33. tools=[get_weather],
  34. model_client=model_client,
  35. system_message="You are a helpful assistant",
  36. model_client_stream=True, # Enable model client streaming.
  37. reflect_on_tool_use=True, # Reflect on tool use.
  38. )
  39. # Set the assistant agent in the user session.
  40. cl.user_session.set("prompt_history", "") # type: ignore
  41. cl.user_session.set("agent", assistant) # type: ignore
  42. @cl.on_message # type: ignore
  43. async def chat(message: cl.Message) -> None:
  44. # Get the assistant agent from the user session.
  45. agent = cast(AssistantAgent, cl.user_session.get("agent")) # type: ignore
  46. # Construct the response message.
  47. response = cl.Message(content="")
  48. async for msg in agent.on_messages_stream(
  49. messages=[TextMessage(content=message.content, source="user")],
  50. cancellation_token=CancellationToken(),
  51. ):
  52. if isinstance(msg, ModelClientStreamingChunkEvent):
  53. # Stream the model client response to the user.
  54. await response.stream_token(msg.content)
  55. elif isinstance(msg, Response):
  56. # Done streaming the model client response. Send the message.
  57. await response.send()