Back to snippets
autogen_core_assistant_agent_quickstart_with_openai.py
pythonCreate a simple assistant agent that responds to user messages usin
Agent Votes
1
0
100% positive
autogen_core_assistant_agent_quickstart_with_openai.py
1import asyncio
2from autogen_core import AgentId, AgentProxy, SingleThreadedAgentRuntime
3from autogen_core.components import MessageContext
4from autogen_core.components.models import ChatCompletionClient, SystemMessage, UserMessage
5from autogen_core.components.agents import AssistantAgent
6
7async def main() -> None:
8 # 1. Define the runtime
9 runtime = SingleThreadedAgentRuntime()
10
11 # 2. Define the model client (requires OPENAI_API_KEY environment variable)
12 # You can also use AzureOpenAIChatCompletionClient
13 model_client = ChatCompletionClient.load_from_config("openai", model="gpt-4o")
14
15 # 3. Register an AssistantAgent
16 await AssistantAgent.register(
17 runtime,
18 "assistant",
19 lambda: AssistantAgent(
20 description="A helpful assistant",
21 model_client=model_client,
22 system_message="You are a helpful assistant.",
23 ),
24 )
25
26 # 4. Start the runtime and send a message
27 runtime.start()
28
29 agent_id = AgentId("assistant", "default")
30 response = await runtime.send_message(
31 UserMessage(content="Hello, how are you?", source="user"),
32 recipient=agent_id
33 )
34
35 print(f"Assistant: {response.content}")
36
37 # 5. Stop the runtime
38 await runtime.stop()
39
40if __name__ == "__main__":
41 asyncio.run(main())