| Microsoft AutoGen is an open-source framework developed by Microsoft that simplifies the orchestration, optimization, and automation of complex large language model workflows by enabling multiple cooperative agents to converse with one another to solve tasks. Its most beneficial features include a highly customizable and conversable agent architecture, support for diverse conversation patterns ranging from simple bilateral chats to complex group dynamics, seamless integration of human-in-the-loop feedback, and native capabilities for automatic code execution and validation, which together significantly reduce the development overhead required to build robust, multi-agent artificial intelligence applications. 
To build a conversational chatbot that can write and execute code on the fly in C#, we can utilize AutoGen for .NET combined with AutoGen.DotnetInteractive. This provides an architecture where one agent acts as the developer generating the code, and a middleware or secondary runner compiles and executes it locally using the .NET Interactive Kernel. PrerequisitesInstall the required AutoGen packages via the .NET CLI: dotnet add package Microsoft.SemanticKernel
dotnet add package AutoGen
dotnet add package AutoGen.SourceGenerator
dotnet add package AutoGen.DotnetInteractive
AutoGen C# ImplementationHere is a fully functional implementation of a multi-turn chat setup where the agent produces C# snippets in response to your prompts, and the code is immediately run inside an in-process interactive kernel. using AutoGen;
using AutoGen.Core;
using AutoGen.OpenAI;
using AutoGen.DotnetInteractive;
using FluentAssertions;
namespace AutoGenChatbot;
public class CodeExecutionChatbot
{
public static async Task RunAsync()
{
// 1. Configure the OpenAI (or Azure OpenAI) backend
var apiKey = Environment.GetEnvironmentVariable("OPENAI_API_KEY")
?? throw new Exception("Please set OPENAI_API_KEY");
var gptConfig = new OpenAIConfig(apiKey, "gpt-4");
// 2. Set up a .NET Interactive kernel for executing generated code
var workDir = Path.Combine(Path.GetTempPath(), "autogen_work");
Directory.CreateDirectory(workDir);
using var kernel = DotnetInteractiveKernelBuilder
.CreateDefaultInProcessKernelBuilder()
.Build();
// 3. The "coder" agent — writes C# code from natural-language prompts
var coder = new AssistantAgent(
name: "coder",
systemMessage: """
You are a C# programmer. When asked to solve a task, write
the C# code to accomplish it inside a ```csharp code block.
Only write ONE code block per reply. After the code runs,
inspect the result. Reply "TERMINATE" when the task is done.
""",
llmConfig: new ConversableAgentConfig
{
Temperature = 0,
ConfigList = new[] { gptConfig },
})
.RegisterPrintMessage();
// 4. The "runner" agent — extracts code blocks and executes them
var runner = new UserProxyAgent(
name: "runner",
humanInputMode: HumanInputMode.NEVER)
.RegisterDotnetCodeBlockExecutionHook(kernel)
.RegisterPrintMessage();
// 5. Wire them into a conversation. The runner drives the coder,
// executes returned code, and feeds results back until TERMINATE.
var chatHistory = await runner.InitiateChatAsync(
receiver: coder,
message: "Compute the first 15 Fibonacci numbers and print them.",
maxRound: 10);
// 6. Optional: assert the conversation reached a terminal state
chatHistory.Any(m => m.GetContent()?.Contains("TERMINATE") is true)
.Should().BeTrue();
}
}
public static class Program
{
public static async Task Main(string[] args)
{
await CodeExecutionChatbot.RunAsync();
}
}
Interactive Chat Loop VariantTo take prompts from the user in a loop rather than a fixed message: public static async Task RunInteractiveAsync()
{
var apiKey = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;
var gptConfig = new OpenAIConfig(apiKey, "gpt-4");
using var kernel = DotnetInteractiveKernelBuilder
.CreateDefaultInProcessKernelBuilder()
.Build();
var coder = new AssistantAgent(
name: "coder",
systemMessage: "You are a C# coding assistant. Return runnable " +
"C# in ```csharp blocks. Say TERMINATE when done.",
llmConfig: new ConversableAgentConfig
{
Temperature = 0,
ConfigList = new[] { gptConfig },
});
var runner = new UserProxyAgent("runner", HumanInputMode.NEVER)
.RegisterDotnetCodeBlockExecutionHook(kernel);
Console.WriteLine("Chatbot ready. Type a prompt (or 'exit'):");
string? input;
while ((input = Console.ReadLine()) is not null && input != "exit")
{
await runner.InitiateChatAsync(coder, input, maxRound: 8);
Console.WriteLine("\n--- Ready for next prompt ---");
}
}
How It WorksThe coder agent receives the natural-language prompt and returns C# code inside a fenced code block. The runner (a UserProxyAgent) uses RegisterDotnetCodeBlockExecutionHook to extract that code, execute it against the in-process .NET Interactive kernel, and send the execution output back to the coder. This loop repeats until the coder emits TERMINATE or maxRound is reached. A few practical notes: the AutoGen library for .NET has evolved — some builds expose the newer Microsoft.AutoGen namespaces while the example above uses the widely-published AutoGen / AutoGen.DotnetInteractive packages, so check the exact method names against the version you install. You'll also need the .NET Interactive tooling available (dotnet tool install -g Microsoft.dotnet-interactive) for the code-execution kernel to initialize. For production use, run the execution kernel in a sandboxed container rather than in-process, since it runs arbitrary generated code. Because API surfaces here shift between releases, it's worth confirming the current package names and signatures — I can look those up if you tell me which AutoGen version you're targeting. |