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 4.3 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. from typing import List, cast
  2. import chainlit as cl
  3. import yaml
  4. import asyncio
  5. #from dataclasses import dataclass
  6. from autogen_core import (
  7. AgentId,
  8. MessageContext,
  9. SingleThreadedAgentRuntime,
  10. ClosureAgent,
  11. ClosureContext,
  12. TopicId,
  13. TypeSubscription
  14. )
  15. from autogen_core.models import (
  16. ChatCompletionClient,
  17. CreateResult,
  18. UserMessage,
  19. )
  20. from autogen_core.tools import FunctionTool, Tool
  21. #from autogen_ext.models.openai import OpenAIChatCompletionClient
  22. #from autogen_core.model_context import BufferedChatCompletionContext
  23. from SimpleAssistantAgent import SimpleAssistantAgent, StreamResult
  24. TASK_RESULTS_TOPIC_TYPE = "task-results"
  25. task_results_topic_id = TopicId(type=TASK_RESULTS_TOPIC_TYPE, source="default")
  26. CLOSURE_AGENT_TYPE = "collect_result_agent"
  27. @cl.set_starters # type: ignore
  28. async def set_starts() -> List[cl.Starter]:
  29. return [
  30. cl.Starter(
  31. label="Greetings",
  32. message="Hello! What can you help me with today?",
  33. ),
  34. cl.Starter(
  35. label="Weather",
  36. message="Find the weather in New York City.",
  37. ),
  38. ]
  39. # Function called when closure agent receives message. It put the messages to the output queue
  40. async def output_result(_agent: ClosureContext, message: StreamResult, ctx: MessageContext) -> None:
  41. queue = cast(asyncio.Queue[StreamResult], cl.user_session.get("queue_stream")) # type: ignore
  42. await queue.put(message)
  43. @cl.step(type="tool") # type: ignore
  44. async def get_weather(city: str) -> str:
  45. return f"The weather in {city} is 73 degrees and Sunny."
  46. @cl.on_chat_start # type: ignore
  47. async def start_chat() -> None:
  48. # Load model configuration and create the model client.
  49. with open("model_config.yaml", "r") as f:
  50. model_config = yaml.safe_load(f)
  51. model_client = ChatCompletionClient.load_component(model_config)
  52. #context = BufferedChatCompletionContext(buffer_size=10)
  53. # Create a runtime and save to chainlit session
  54. runtime = SingleThreadedAgentRuntime()
  55. cl.user_session.set("run_time", runtime) # type: ignore
  56. # Create tools
  57. tools: List[Tool] = [FunctionTool(get_weather, description="Get weather tool.")]
  58. # Create a queue for output stream data and save to chainlit session
  59. queue_stream = asyncio.Queue[StreamResult]()
  60. cl.user_session.set("queue_stream", queue_stream) # type: ignore
  61. # Create the assistant agent with the get_weather tool.
  62. await SimpleAssistantAgent.register(runtime, "weather_agent", lambda: SimpleAssistantAgent(
  63. name="weather_agent",
  64. tool_schema=tools,
  65. model_client=model_client,
  66. system_message="You are a helpful assistant",
  67. #context=context,
  68. model_client_stream=True, # Enable model client streaming.
  69. reflect_on_tool_use=True, # Reflect on tool use.
  70. ))
  71. # Register the Closure Agent to process streaming chunks from agents by exeucting the output_result
  72. # function, whihc sends the stream response to the output queue
  73. await ClosureAgent.register_closure(
  74. runtime, CLOSURE_AGENT_TYPE, output_result, subscriptions=lambda:[TypeSubscription(topic_type=TASK_RESULTS_TOPIC_TYPE, agent_type=CLOSURE_AGENT_TYPE)]
  75. )
  76. runtime.start() # Start processing messages in the background.
  77. @cl.on_message # type: ignore
  78. async def chat(message: cl.Message) -> None:
  79. # Construct the response message for the user message received.
  80. ui_resp = cl.Message("")
  81. # Get the runtime and queue from the session
  82. runtime = cast(SingleThreadedAgentRuntime, cl.user_session.get("run_time")) # type: ignore
  83. queue = cast(asyncio.Queue[StreamResult], cl.user_session.get("queue_stream")) # type: ignore
  84. task1 = asyncio.create_task( runtime.send_message(UserMessage(content=message.content, source="User"), AgentId("weather_agent", "default")))
  85. # Consume items from the response queue until the stream ends or an error occurs
  86. while True:
  87. stream_msg = await queue.get()
  88. if (isinstance(stream_msg.content, str)):
  89. await ui_resp.stream_token(stream_msg.content)
  90. elif (isinstance(stream_msg.content, CreateResult)):
  91. await ui_resp.send()
  92. break
  93. await task1