Conversation Multi-Agent Chatbot with On-the-Fly Code Execition via Microsoft AutoGen

CK CK 3788 
Created at
Updated at  
306 0 0

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.

Conversation Multi-Agent Chatbot with On-the-Fly Code Execition via Microsoft AutoGen

 

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.

 

Prerequisites

Install 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# Implementation

Here 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 Variant

To 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 Works

The 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.

Tags AI Agent Framework AI Agents AI Orchestration Agentic AI AutoGen AutoGen Features AutoGen.DotnetInteractive Autonomous AI Agents GenAI LLM Development Microsoft AI Microsoft AutoGen Multi Agent Systems Facebook X
Comments 0
Similar posts
  1. How to Build a Python Chatbot That Writes and Runs Code Using Microsoft AutoGen (With Sample Code)
    244
  2. AWS Multi-Agent Collaboration Approach: Fully Managed vs. Code-based Implementation
    292
  3. Vector Database Integration on Fully Managed Multi-Agent Environment
    319
  4. Semantic Kernel: Microsoft's GenAI Orchestration SDK
    416
  5. LLM Application Development with LangGraph: Features and Architectures for Stateful Multi-Actor LLM Applications
    364
  6. Microsoft AutoGen: Next-Generation Multi-Agent Framework
    318
  7. Architecting an LLM-Powered Multi-Agent Orchestration System: Design and Requirements
    260
  8. When Do You Need Real-Time Model Registry Versioning Powered by Autonomous Agents?
    242
  9. Beyond Static Pipelines: Architecting LLM Multi-Agent Systems for Autonomous Workflow Orchestration
    598
  10. The Concept of Scaffolding in AI Agents
    245
  11. Why Reranking is Crucial for RAG and Agentic AI Systems?
    276
  12. Technical Hierarchy of AI Agents
    826
  1. Getting Started with FAISS: A CentOS 7 Installation Guide
    288
  2. CMake - a cross-platform build system generator that creates Makefiles used in C++ projects
    299
  3. How To Check If Your Printer Is Connected Using C#
    1,027
  4. KMP String Matching Algorithm
    676
  5. How to get process id in C# like windows task manager ?
    871
  6. How to implement switch statement in C# ?
    992
  7. How to implement while loop in C# ?
    1,351
  8. How to delete file ?
    1,200
  9. How to convert integer to text string ?
    701
  10. How to convert text string to integer ?
    616
  11. How to set an certain color as transparent color on bitmap
    526
  12. How to resize and save PNG or Jpeg Image file ?
    638
  13. How to display message box in C#
    1,129
  14. How to convert bitmap image to jpeg image ?
    362
  15. To load image from file
    457
Recently updated
  1. Google OAuth Token Expiration: Causes and Solutions
    31
  2. Why 100% SEO Guarantees Better User Engagement and How to Achieve It in Your Service
    57
  3. Why SPF and DKIM Are Essential for Linux Email Servers?
    51
  4. How do I create animated background for Google Meet?
    23,206
  5. MaxMind GeoLite2 vs. DB-IP Lite vs. ip-api.com: Choosing the Right Free IP Geolocation Solution
    273
  6. Meet Valkey: Why Redis Changed Its License, Why Valkey is Better, and How to Use It as a Drop-in Replacement
    104
  7. How Rogue Web Scrapers Are Stealing My Content and Destroying My Server
    170
  8. Array of arguments passed to script in PHP
    99
  9. Invalid Auction Storms in Ad Tech
    107
  10. Building MRC-Compliant Instrumentation in Ad Tech: Implementation Steps and Key Challenges
    208
  11. The Two Clocks of Ad Server Architecture
    78
  12. Frequency Cap Architecture Overview
    527
  13. Collecting Proof-of-Play from 100,000 Screens
    153
  14. Vector Search in Relational Databases (RDBs): Trends & Usage Environments
    303
  15. What is RedisVL?
    116
  16. Designing a Skill Registry Architecture: Minimize Token Usage and Maximize AI Performance
    247
  17. TPU & GPU Cluster Management Tools
    258
  18. AI-DLC vs. AI-SDLC: Model-Centric vs. System-Centric AI Development
    268
  19. Fine-Tuning Open-Weight LLMs: Training, Licensing, and Deploying Custom Models with Ollama
    354
  20. Inside the Next-Generation Streaming Architecture: Ultra-Low Latency, SGAI, and AI Codecs
    207
  21. Machine Learning: Training vs. Ranking
    229
  22. The Continuous Learning Machine: Designing a Loop That Actually Turns
    228
  23. The Next-Gen Low-Latency Standards: LL-HLS & MoQ
    203
  24. Designing a Data Curation System Around a Vector Database
    230
  25. Extracting Context from Live Video: The Architecture Got Simpler When We Stopped Building Features
    263
  26. The New Ad Stack Behind Live Sports Streaming: Inside SGAI, EABN, and the Standards Race to Fix Live Monetization
    674
  27. Designing MLOps Architectures to Handle Seasonal Data Drift in EV Fleet Models
    201
  28. From 15 to 40+ FPS: Accelerating PyTorch Object Detection on Automotive ECUs
    233
  29. Understanding Data Lineage
    272
  30. System Requirements and Architecture: Intelligent Priority-Based Scheduler
    176