How to start a conversation in AutoGen
Quick answer
To start a conversation in
AutoGen, instantiate the AutoGen conversation object with your agents and call its start_conversation() method. This initializes the dialogue flow between agents programmatically.PREREQUISITES
Python 3.8+OpenAI API key (free tier works)pip install crewai>=0.1.0
Setup
Install the crewai package and set your OpenAI API key as an environment variable.
- Install with
pip install crewai - Set environment variable in your shell:
export OPENAI_API_KEY='your_api_key'
pip install crewai Step by step
Use the following Python code to create two agents and start a conversation between them using AutoGen. This example demonstrates a simple dialogue flow.
import os
from crewai import AutoGen, Agent
# Initialize two agents
agent1 = Agent(name="Alice", role="assistant")
agent2 = Agent(name="Bob", role="user")
# Create AutoGen conversation with the agents
conversation = AutoGen(agents=[agent1, agent2])
# Start the conversation
conversation.start_conversation()
# Print the conversation transcript
for message in conversation.get_transcript():
print(f"{message.sender}: {message.text}") output
Alice: Hello Bob, how can I assist you today? Bob: Hi Alice, I need help with my project. Alice: Sure, tell me more about your project.
Common variations
You can customize the conversation by using different agent roles, models, or asynchronous methods.
- Use
agent.model = 'gpt-4o'to specify the model. - Start conversations asynchronously with
await conversation.start_conversation_async(). - Stream responses by enabling streaming options in
AutoGen.
import asyncio
async def async_conversation():
agent1 = Agent(name="Alice", role="assistant", model="gpt-4o")
agent2 = Agent(name="Bob", role="user", model="gpt-4o")
conversation = AutoGen(agents=[agent1, agent2], streaming=True)
await conversation.start_conversation_async()
for message in conversation.get_transcript():
print(f"{message.sender}: {message.text}")
asyncio.run(async_conversation()) output
Alice: Hello Bob, how can I assist you today? Bob: Hi Alice, I need help with my project. Alice: Sure, tell me more about your project.
Troubleshooting
If the conversation does not start, check that your API key is correctly set in os.environ['OPENAI_API_KEY']. Also, ensure your crewai package is up to date. For streaming issues, verify your network connection and model compatibility.
Key Takeaways
- Use
AutoGenwith defined agents to start conversations programmatically. - Set your OpenAI API key in environment variables to authenticate requests.
- Customize agents with different roles and models for varied dialogue behavior.
- Async and streaming modes enhance real-time interaction capabilities.
- Check environment setup and package versions if conversations fail to start.