|
| 1 | +# MEAI Tool Calling |
| 2 | + |
| 3 | +Use function/tool calling via the Microsoft.Extensions.AI IChatClient interface. |
| 4 | + |
| 5 | +This example assumes `using tryAGI.OpenAI;` is in scope and `apiKey` contains your tryAGI.OpenAI API key. |
| 6 | + |
| 7 | +```csharp |
| 8 | +using var client = new OpenAiClient(apiKey); |
| 9 | + |
| 10 | +// using Meai = Microsoft.Extensions.AI; |
| 11 | +Meai.IChatClient chatClient = client; |
| 12 | + |
| 13 | +var tool = Meai.AIFunctionFactory.Create( |
| 14 | + (string city) => city switch |
| 15 | + { |
| 16 | + "Paris" => "22C, sunny", |
| 17 | + "London" => "15C, cloudy", |
| 18 | + _ => "Unknown", |
| 19 | + }, |
| 20 | + name: "GetWeather", |
| 21 | + description: "Gets the current weather for a city"); |
| 22 | + |
| 23 | +var chatOptions = new Meai.ChatOptions |
| 24 | +{ |
| 25 | + ModelId = "gpt-4o-mini", |
| 26 | + Tools = [tool], |
| 27 | +}; |
| 28 | + |
| 29 | +var messages = new List<Meai.ChatMessage> |
| 30 | +{ |
| 31 | + new(Meai.ChatRole.User, "What's the weather in Paris? Respond with the temperature only."), |
| 32 | +}; |
| 33 | + |
| 34 | +// First turn: get tool call |
| 35 | +var response = await chatClient.GetResponseAsync( |
| 36 | + (IEnumerable<Meai.ChatMessage>)messages, chatOptions); |
| 37 | + |
| 38 | +var functionCall = response.Messages |
| 39 | + .SelectMany(m => m.Contents) |
| 40 | + .OfType<Meai.FunctionCallContent>() |
| 41 | + .First(); |
| 42 | + |
| 43 | +// Execute tool and add result |
| 44 | +var toolResult = await tool.InvokeAsync( |
| 45 | + functionCall.Arguments is { } args |
| 46 | + ? new Meai.AIFunctionArguments(args) |
| 47 | + : null); |
| 48 | +messages.AddRange(response.Messages); |
| 49 | +messages.Add(new Meai.ChatMessage(Meai.ChatRole.Tool, |
| 50 | + new Meai.AIContent[] |
| 51 | + { |
| 52 | + new Meai.FunctionResultContent(functionCall.CallId, toolResult), |
| 53 | + })); |
| 54 | + |
| 55 | +// Second turn: get final response |
| 56 | +var finalResponse = await chatClient.GetResponseAsync( |
| 57 | + (IEnumerable<Meai.ChatMessage>)messages, chatOptions); |
| 58 | + |
| 59 | +Console.WriteLine(finalResponse.Messages[0].Text); |
| 60 | +``` |
0 commit comments