openai / openai-dotnet

The official .NET library for the OpenAI API
https://www.nuget.org/packages/OpenAI/AbsoluteLatest
MIT License
722 stars 62 forks source link

Added helper APIs for chat function/tool calls #42

Open KrzysztofCwalina opened 3 weeks ago

KrzysztofCwalina commented 3 weeks ago
  1. Added ChatTool[] ChatTool.CreateFunctionTools(Type functionHolder) method. The method reflects on the functionHolder and builds an array of ChatTool instances corresponding to the reflected on methods.
  2. Added ChatToolCall.GetFunctionArgument, which helps with parsing function call arguments.

Users can now do:

ChatCompletionOptions options = new() {
    Tools = ChatTool.CreateFunctionTools(typeof(MyFunctions))
};

internal static class MyFunctions {
    [Description("Get the user's current location")]
    public static string GetCurrentLocation() => "San Francisco";

    [Description("Get the current weather in a given location")]
    public static string GetCurrentWeather([Description("The city and state, e.g. Boston, MA")] string location, TemperatureUnit unit) => "31 {unit}";
}

...
case nameof(MyFunctions.GetCurrentWeather): 
        var location = toolCall.GetFunctionArgument<string>("location");
        var unit = toolCall.GetFunctionArgument("unit", defaultValue: MyFunctions.TemperatureUnit.Celsius);
        string toolResult = MyFunctions.GetCurrentWeather(location, unit);
        messages.Add(new ToolChatMessage(toolCall.Id, toolResult));
        break;