|
| 1 | +// <complete_code> |
| 2 | +// Demonstrates the OpenAI Responses API against the Foundry Local OpenAI-compatible web service. |
| 3 | +// |
| 4 | +// SDK responsibilities (Foundry Local): |
| 5 | +// - SDK initialization |
| 6 | +// - EP download/registration |
| 7 | +// - model lookup, download, load |
| 8 | +// - starting/stopping the local web service |
| 9 | +// |
| 10 | +// Responses API calls go through the official OpenAI .NET package's `ResponsesClient` |
| 11 | +// pointed at the local web service, mirroring how `foundry-local-web-server` uses |
| 12 | +// `OpenAIClient.GetChatClient(...)`. |
| 13 | + |
| 14 | +using System.ClientModel; |
| 15 | +using System.Text; |
| 16 | +using System.Text.Json; |
| 17 | + |
| 18 | +using Microsoft.AI.Foundry.Local; |
| 19 | + |
| 20 | +using OpenAI; |
| 21 | +using OpenAI.Responses; |
| 22 | + |
| 23 | +var config = new Configuration |
| 24 | +{ |
| 25 | + AppName = "foundry_local_samples", |
| 26 | + LogLevel = Microsoft.AI.Foundry.Local.LogLevel.Information, |
| 27 | + Web = new Configuration.WebService |
| 28 | + { |
| 29 | + Urls = "http://127.0.0.1:52495" |
| 30 | + } |
| 31 | +}; |
| 32 | + |
| 33 | +// Initialize the singleton instance. |
| 34 | +await FoundryLocalManager.CreateAsync(config, Utils.GetAppLogger()); |
| 35 | +var mgr = FoundryLocalManager.Instance; |
| 36 | + |
| 37 | +// Download and register all execution providers. |
| 38 | +var currentEp = ""; |
| 39 | +await mgr.DownloadAndRegisterEpsAsync((epName, percent) => |
| 40 | +{ |
| 41 | + if (epName != currentEp) |
| 42 | + { |
| 43 | + if (currentEp != "") Console.WriteLine(); |
| 44 | + currentEp = epName; |
| 45 | + } |
| 46 | + Console.Write($"\r {epName.PadRight(30)} {percent,6:F1}%"); |
| 47 | +}); |
| 48 | +if (currentEp != "") Console.WriteLine(); |
| 49 | + |
| 50 | +// Get the model catalog |
| 51 | +var catalog = await mgr.GetCatalogAsync(); |
| 52 | + |
| 53 | +// Get a model using an alias |
| 54 | +var model = await catalog.GetModelAsync("qwen2.5-0.5b") ?? throw new Exception("Model not found"); |
| 55 | + |
| 56 | +// Download the model (the method skips download if already cached) |
| 57 | +await model.DownloadAsync(progress => |
| 58 | +{ |
| 59 | + Console.Write($"\rDownloading model: {progress:F2}%"); |
| 60 | + if (progress >= 100f) |
| 61 | + { |
| 62 | + Console.WriteLine(); |
| 63 | + } |
| 64 | +}); |
| 65 | + |
| 66 | +// Load the model |
| 67 | +Console.Write($"Loading model {model.Id}..."); |
| 68 | +await model.LoadAsync(); |
| 69 | +Console.WriteLine("done."); |
| 70 | + |
| 71 | +// Start the web service |
| 72 | +Console.Write($"Starting web service on {config.Web.Urls}..."); |
| 73 | +await mgr.StartWebServiceAsync(); |
| 74 | +Console.WriteLine("done."); |
| 75 | + |
| 76 | +// <<<<<< OPEN AI RESPONSES SDK USAGE >>>>>> |
| 77 | +// Use the OpenAI Responses client to call the local Foundry web service. |
| 78 | +ApiKeyCredential key = new ApiKeyCredential("notneeded"); |
| 79 | +OpenAIClient openai = new OpenAIClient(key, new OpenAIClientOptions |
| 80 | +{ |
| 81 | + Endpoint = new Uri(config.Web.Urls + "/v1"), |
| 82 | +}); |
| 83 | +ResponsesClient responses = openai.GetResponsesClient(); |
| 84 | + |
| 85 | +// 1) Non-streaming |
| 86 | +Console.WriteLine("\n=== Non-streaming ==="); |
| 87 | +ResponseResult simple = await responses.CreateResponseAsync(model.Id, "What is 2 + 2? Respond with just the number."); |
| 88 | +Console.WriteLine($"[ASSISTANT]: {simple.GetOutputText()}"); |
| 89 | + |
| 90 | +// 2) Streaming |
| 91 | +Console.WriteLine("\n=== Streaming ==="); |
| 92 | +Console.Write("[ASSISTANT]: "); |
| 93 | +await foreach (StreamingResponseUpdate update in responses.CreateResponseStreamingAsync(model.Id, "Count from 1 to 3.")) |
| 94 | +{ |
| 95 | + if (update is StreamingResponseOutputTextDeltaUpdate delta && !string.IsNullOrEmpty(delta.Delta)) |
| 96 | + { |
| 97 | + Console.Write(delta.Delta); |
| 98 | + } |
| 99 | +} |
| 100 | +Console.WriteLine(); |
| 101 | + |
| 102 | +// 3) Function/tool calling — full round-trip using previous_response_id. |
| 103 | +Console.WriteLine("\n=== Function calling ==="); |
| 104 | +var weatherSchema = BinaryData.FromString(""" |
| 105 | + { |
| 106 | + "type": "object", |
| 107 | + "properties": { |
| 108 | + "city": { "type": "string", "description": "The city to look up" } |
| 109 | + }, |
| 110 | + "required": ["city"] |
| 111 | + } |
| 112 | + """); |
| 113 | + |
| 114 | +var toolOptions = new CreateResponseOptions( |
| 115 | + model.Id, |
| 116 | + new[] { ResponseItem.CreateUserMessageItem("Use get_weather to look up the weather in Seattle, then summarize it.") }) |
| 117 | +{ |
| 118 | + StoredOutputEnabled = true, |
| 119 | + ToolChoice = ResponseToolChoice.CreateRequiredChoice(), |
| 120 | +}; |
| 121 | +toolOptions.Tools.Add(ResponseTool.CreateFunctionTool( |
| 122 | + functionName: "get_weather", |
| 123 | + functionParameters: weatherSchema, |
| 124 | + strictModeEnabled: true, |
| 125 | + functionDescription: "Get the current weather for a given city.")); |
| 126 | + |
| 127 | +ResponseResult toolCallResponse = await responses.CreateResponseAsync(toolOptions); |
| 128 | + |
| 129 | +// Find the function-call output item the model produced. |
| 130 | +FunctionCallResponseItem? functionCall = null; |
| 131 | +foreach (var item in toolCallResponse.OutputItems) |
| 132 | +{ |
| 133 | + if (item is FunctionCallResponseItem fc && fc.FunctionName == "get_weather") |
| 134 | + { |
| 135 | + functionCall = fc; |
| 136 | + break; |
| 137 | + } |
| 138 | +} |
| 139 | + |
| 140 | +if (functionCall is null) |
| 141 | +{ |
| 142 | + Console.WriteLine("Model did not produce a function call; skipping tool round-trip."); |
| 143 | +} |
| 144 | +else |
| 145 | +{ |
| 146 | + var argsJson = functionCall.FunctionArguments?.ToString() ?? "{}"; |
| 147 | + var city = "unknown"; |
| 148 | + try |
| 149 | + { |
| 150 | + city = JsonDocument.Parse(argsJson).RootElement.GetProperty("city").GetString() ?? "unknown"; |
| 151 | + } |
| 152 | + catch (KeyNotFoundException) { /* model gave us no city */ } |
| 153 | + |
| 154 | + Console.WriteLine($"Tool call: get_weather(city=\"{city}\")"); |
| 155 | + var toolOutput = $$$"""{"city": "{{{city}}}", "temperatureF": 68, "summary": "partly cloudy"}"""; |
| 156 | + Console.WriteLine($"Tool output: {toolOutput}"); |
| 157 | + |
| 158 | + // Submit the tool's output and ask the model to continue using `previous_response_id`. |
| 159 | + var followUpOptions = new CreateResponseOptions( |
| 160 | + model.Id, |
| 161 | + new[] { ResponseItem.CreateFunctionCallOutputItem(functionCall.CallId, toolOutput) }) |
| 162 | + { |
| 163 | + PreviousResponseId = toolCallResponse.Id, |
| 164 | + StoredOutputEnabled = true, |
| 165 | + }; |
| 166 | + followUpOptions.Tools.Add(ResponseTool.CreateFunctionTool( |
| 167 | + functionName: "get_weather", |
| 168 | + functionParameters: weatherSchema, |
| 169 | + strictModeEnabled: true, |
| 170 | + functionDescription: "Get the current weather for a given city.")); |
| 171 | + |
| 172 | + ResponseResult finalResponse = await responses.CreateResponseAsync(followUpOptions); |
| 173 | + Console.WriteLine($"[ASSISTANT]: {finalResponse.GetOutputText()}"); |
| 174 | +} |
| 175 | +// <<<<<< END OPEN AI RESPONSES SDK USAGE >>>>>> |
| 176 | + |
| 177 | +// Tidy up |
| 178 | +await mgr.StopWebServiceAsync(); |
| 179 | +await model.UnloadAsync(); |
| 180 | +// </complete_code> |
0 commit comments