Table of Contents

Create type-safe function call using AutoGen.SourceGenerator

AutoGen provides a source generator to easness the trouble of manually craft function definition and function call wrapper from a function. To use this feature, simply add the AutoGen.SourceGenerator package to your project and decorate your function with FunctionAttribute.

dotnet add package AutoGen.SourceGenerator
Note

It's recommended to enable structural xml document support by setting GenerateDocumentationFile property to true in your project file. This allows source generator to leverage the documentation of the function when generating the function definition.

<PropertyGroup>
    <!-- This enables structural xml document support -->
    <GenerateDocumentationFile>true</GenerateDocumentationFile>
</PropertyGroup>

Then, create a public partial class to host the methods you want to use in AutoGen agents. The method has to be a public instance method and its return type must be Task<string>. After the methods is defined, mark them with @AutoGen.FunctionAttribute attribute:

Note

A public partial class is required for the source generator to generate code. The method has to be a public instance method and its return type must be Task<string>. Mark the method with FunctionAttribute attribute.

Firstly, import the required namespaces:

using AutoGen.Core;

Then, create a WeatherReport function and mark it with FunctionAttribute:

public partial class TypeSafeFunctionCall
{
    /// <summary>
    /// Get weather report
    /// </summary>
    /// <param name="city">city</param>
    /// <param name="date">date</param>
    [Function]
    public async Task<string> WeatherReport(string city, string date)
    {
        return $"Weather report for {city} on {date} is sunny";
    }
}

The source generator will generate the FunctionContract and function call wrapper for WeatherReport in another partial class based on its signature and structural comments. The FunctionContract is introduced by #1736 and contains all the necessary metadata such as function name, parameters, and return type. It is LLM independent and can be used to generate openai function definition or semantic kernel function. The function call wrapper is a helper class that provides a type-safe way to call the function.

Note

If you are using VSCode as your editor, you may need to restart the editor to see the generated code.

The following code shows how to generate openai function definition from the FunctionContract and call the function using the function call wrapper.

var functionInstance = new TypeSafeFunctionCall();

// Get the generated function definition
var functionDefiniton = functionInstance.WeatherReportFunctionContract.ToChatTool();

// Get the generated function wrapper
Func<string, Task<string>> functionWrapper = functionInstance.WeatherReportWrapper;

// ...