The following example shows how to create a GetWeatherAsync function and pass it to OpenAIChatAgent.
Firstly, you need to install the following packages:
<ItemGroup>
<PackageReference Include="AutoGen.OpenAI" Version="AUTOGEN_VERSION" />
<PackageReference Include="AutoGen.SourceGenerator" Version="AUTOGEN_VERSION" />
</ItemGroup>
Note
The AutoGen.SourceGenerator package carries a source generator that adds support for type-safe function definition generation. For more information, please check out Create type-safe function.
Note
If you are using VSCode as your editor, you may need to restart the editor to see the generated code.
Firstly, import the required namespaces:
using AutoGen.Core;
using AutoGen.OpenAI;
using AutoGen.OpenAI.Extension;
Then, define a public partial class: Function with GetWeather method
public partial class Functions
{
[Function]
public async Task<string> GetWeather(string location)
{
return "The weather in " + location + " is sunny.";
}
}
Then, create an OpenAIChatAgent and register it with OpenAIChatRequestMessageConnector so it can support ToolCallMessage and ToolCallResultMessage. These message types are necessary to use FunctionCallMiddleware, which provides support for processing and invoking function calls.
var openAIKey = Environment.GetEnvironmentVariable("OPENAI_API_KEY") ?? throw new Exception("Please set OPENAI_API_KEY environment variable.");
var modelId = "gpt-3.5-turbo";
var openAIClient = new OpenAIClient(openAIKey);
// create an open ai chat agent
var openAIChatAgent = new OpenAIChatAgent(
chatClient: openAIClient.GetChatClient(modelId),
name: "assistant",
systemMessage: "You are an assistant that help user to do some tasks.")
.RegisterMessageConnector();
Then, create an FunctionCallMiddleware with GetWeather function and register it with the agent above. When creating the middleware, we also pass a functionMap to FunctionCallMiddleware, which means the function will be automatically invoked when the agent replies a GetWeather function call.
var functions = new Functions();
var functionCallMiddleware = new FunctionCallMiddleware(
functions: [functions.GetWeatherFunctionContract], // GetWeatherFunctionContract is auto-generated from the GetWeather function
functionMap: new Dictionary<string, Func<string, Task<string>>>
{
{ functions.GetWeatherFunctionContract.Name, functions.GetWeatherWrapper } // GetWeatherWrapper is a wrapper function for GetWeather, which is also auto-generated
});
openAIChatAgent = openAIChatAgent.RegisterStreamingMiddleware(functionCallMiddleware);
Finally, you can chat with the OpenAIChatAgent and invoke the GetWeather function.
var reply = await openAIChatAgent.SendAsync("what is the weather in Seattle?");
reply.GetContent().Should().Be("The weather in Seattle is sunny.");
reply.GetToolCalls().Count.Should().Be(1);
reply.GetToolCalls().First().Should().Be(this.GetWeatherFunctionContract.Name);