autogen/dotnet/website/articles/Run-dotnet-code.md
Griffin Bassman 850377c74a
fix: Various fixes and cleanups to dotnet autogen core (#5242)
Co-authored-by: Jack Gerrits <jack@jackgerrits.com>
Co-authored-by: Ryan Sweet <rysweet@microsoft.com>
2025-01-28 17:13:36 -05:00

3.4 KiB

AutoGen provides a built-in feature to run code snippet from agent response. Currently the following languages are supported:

  • dotnet

More languages will be supported in the future.

What is a code snippet?

A code snippet in agent response is a code block with a language identifier. For example:

[!code-csharp]

Why running code snippet is useful?

The ability of running code snippet can greatly extend the ability of an agent. Because it enables agent to resolve tasks by writing code and run it, which is much more powerful than just returning a text response.

For example, in data analysis scenario, agent can resolve tasks like "What is the average of the sales amount of the last 7 days?" by firstly write a code snippet to query the sales amount of the last 7 days, then calculate the average and then run the code snippet to get the result.

Warning

Running arbitrary code snippet from agent response could bring risks to your system. Using this feature with caution.

Use dotnet interactive kernel to execute code snippet?

The built-in feature of running dotnet code snippet is provided by dotnet-interactive. To run dotnet code snippet, you need to install the following package to your project, which provides the intergraion with dotnet-interactive:

<PackageReference Include="AutoGen.DotnetInteractive" />

Then you can use @AutoGen.DotnetInteractive.DotnetInteractiveKernelBuilder* to create a in-process dotnet-interactive composite kernel with C# and F# kernels. [!code-csharp]

After that, use @AutoGen.DotnetInteractive.Extension.RunSubmitCodeCommandAsync* method to run code snippet. The method will return the result of the code snippet. [!code-csharp]

Run python code snippet

To run python code, firstly you need to have python installed on your machine, then you need to set up ipykernel and jupyter in your environment.

pip install ipykernel
pip install jupyter

After ipykernel and jupyter are installed, you can confirm the ipykernel is installed correctly by running the following command:

jupyter kernelspec list

The output should contain all available kernels, including python3.

Available kernels:
    python3    /usr/local/share/jupyter/kernels/python3
    ...

Then you can add the python kernel to the dotnet-interactive composite kernel by calling AddPythonKernel method.

[!code-csharp]

Further reading

You can refer to the following examples for running code snippet in agentic workflow:

  • Dynamic_GroupChat_Coding_Task:
  • Dynamic_GroupChat_Calculate_Fibonacci: