In AutoGen, you can start a conversation between two agents using InitiateChatAsync or one of SendAsync APIs. When conversation starts, the sender agent will firstly send a message to receiver agent, then receiver agent will generate a reply and send it back to sender agent. This process will repeat until either one of the agent sends a termination message or the maximum number of turns is reached.
Note
A termination message is an IMessage which content contains the keyword: TERMINATE. To determine if a message is a terminate message, you can use IsGroupChatTerminateMessage.
A basic example
The following example shows how to start a conversation between the teacher agent and student agent, where the student agent starts the conversation by asking teacher to create math questions.
Tip
You can use RegisterPrintMessage to pretty print the message replied by the agent.
Note
The conversation is terminated when teacher agent sends a message containing the keyword: TERMINATE.
Note
The teacher agent uses RegisterPostProcess to register a post process function which returns a hard-coded termination message when a certain condition is met. Comparing with putting the TERMINATE keyword in the prompt, this approach is more robust especially when a weaker LLM model is used.
var gpt4oMini = LLMConfiguration.GetOpenAIGPT4o_mini();
// create teacher agent
// teacher agent will create math questions
var teacher = new OpenAIChatAgent(
chatClient: gpt4oMini,
name: "teacher",
systemMessage: @"You are a teacher that create pre-school math question for student and check answer.
If the answer is correct, you stop the conversation by saying [COMPLETE].
If the answer is wrong, you ask student to fix it.")
.RegisterMessageConnector()
.RegisterMiddleware(async (msgs, option, agent, _) =>
{
var reply = await agent.GenerateReplyAsync(msgs, option);
if (reply.GetContent()?.ToLower().Contains("complete") is true)
{
return new TextMessage(Role.Assistant, GroupChatExtension.TERMINATE, from: reply.From);
}
return reply;
})
.RegisterPrintMessage();
// create student agent
// student agent will answer the math questions
var student = new OpenAIChatAgent(
chatClient: gpt4oMini,
name: "student",
systemMessage: "You are a student that answer question from teacher")
.RegisterMessageConnector()
.RegisterPrintMessage();
// start the conversation
var conversation = await student.InitiateChatAsync(
receiver: teacher,
message: "Hey teacher, please create math question for me.",
maxRound: 10);
// output
// Message from teacher
// --------------------
// content: Of course!Here's a math question for you:
//
// What is 2 + 3 ?
// --------------------
//
// Message from student
// --------------------
// content: The sum of 2 and 3 is 5.
// --------------------
//
// Message from teacher
// --------------------
// content: [GROUPCHAT_TERMINATE]
// --------------------