openai/openai-dotnet
Publicmirrored from https://github.com/openai/openai-dotnetAvailable
docs/guides/tools/responses/function_calling.cs
48lines · modecode
| 1 | // SAMPLE: Generate response from function calling through Responses API |
| 2 | // PAGE: https://platform.openai.com/docs/guides/tools?tool-type=function-calling |
| 3 | // GUIDANCE: Instructions to run this code: https://aka.ms/oai/net/start |
| 4 | #pragma warning disable OPENAI001 |
| 5 | |
| 6 | #:package OpenAI@2.* |
| 7 | #:property PublishAot=false |
| 8 | |
| 9 | using System.Text.Json; |
| 10 | using System.Text.Json.Serialization.Metadata; |
| 11 | using OpenAI.Responses; |
| 12 | |
| 13 | string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!; |
| 14 | ResponsesClient client = new(key); |
| 15 | |
| 16 | CreateResponseOptions options = new() { Model = "gpt-5.2" }; |
| 17 | options.Tools.Add( |
| 18 | ResponseTool.CreateFunctionTool( |
| 19 | functionName: "get_weather", |
| 20 | functionDescription: "Get current temperature for a given location.", |
| 21 | functionParameters: BinaryData.FromObjectAsJson(new |
| 22 | { |
| 23 | type = "object", |
| 24 | properties = new |
| 25 | { |
| 26 | location = new |
| 27 | { |
| 28 | type = "string", |
| 29 | description = "City and country e.g. Bogotá, Colombia", |
| 30 | } |
| 31 | }, |
| 32 | required = new[] { "location" }, |
| 33 | additionalProperties = false |
| 34 | }), |
| 35 | strictModeEnabled: true |
| 36 | ) |
| 37 | ); |
| 38 | options.InputItems.Add( |
| 39 | ResponseItem.CreateUserMessageItem("What is the weather like in Paris today?") |
| 40 | ); |
| 41 | |
| 42 | ResponseResult response = client.CreateResponse(options); |
| 43 | JsonSerializerOptions serializerOptions = new() |
| 44 | { |
| 45 | TypeInfoResolver = new DefaultJsonTypeInfoResolver() |
| 46 | }; |
| 47 | |
| 48 | Console.WriteLine(JsonSerializer.Serialize(response.OutputItems[0], serializerOptions)); |