#author("2024-11-20T13:18:04+00:00","default:iseki","iseki") ** [[dotnet>.NET]] - for OpenAI v2.x - https://github.com/openai/openai-dotnet *** Programming **** Project の作成 <pre> dotnet new console -o Net8 -f net8.0 cd Net8 dotnet add package OpenAI vi Program.cs dotnet run </pre> ** Sample - https://github.com/openai/openai-dotnet *** 基本 <pre> using OpenAI.Chat; ChatClient client = new(model: "gpt-4o-mini", apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY")); //ChatClient client = new(model: "gpt-4o-mini", apiKey: "sk-........"); ChatCompletion completion = client.CompleteChat("こんにちは"); Console.WriteLine($"[ASSISTANT]: {completion.Content[0].Text}"); </pre> *** 非同期によるチャット補完 <pre> using static System.Console; using System.ClientModel; // for CollectionResult using OpenAI; using OpenAI.Chat; ChatClient client = new(model: "gpt-4o-mini", apiKey: "sk-....."); CollectionResult<StreamingChatCompletionUpdate> completionUpdates = client.CompleteChatStreaming("Hello World"); foreach (StreamingChatCompletionUpdate completionUpdate in completionUpdates) { if (completionUpdate.ContentUpdate.Count > 0) { Console.Write(completionUpdate.ContentUpdate[0].Text); } } </pre> *** 構造化された出力によるチャット補完 dotnet add package System.Text.Json dotnet list package <pre> using static System.Console; using System.ClientModel; // for CollectionResult using OpenAI; using OpenAI.Chat; using System.Text.Json; ChatClient client = new(model: "gpt-4o-mini", apiKey: "sk-...."); List<ChatMessage> messages = [ new UserChatMessage("How can I solve 8x + 7 = -23?"), ]; ChatCompletionOptions options = new() { ResponseFormat = ChatResponseFormat.CreateJsonSchemaFormat( jsonSchemaFormatName: "math_reasoning", jsonSchema: BinaryData.FromBytes(""" { "type": "object", "properties": { "steps": { "type": "array", "items": { "type": "object", "properties": { "explanation": { "type": "string" }, "output": { "type": "string" } }, "required": ["explanation", "output"], "additionalProperties": false } }, "final_answer": { "type": "string" } }, "required": ["steps", "final_answer"], "additionalProperties": false } """u8.ToArray()), jsonSchemaIsStrict: true) }; ChatCompletion completion = client.CompleteChat(messages, options); using JsonDocument structuredJson = JsonDocument.Parse(completion.Content[0].Text); Console.WriteLine($"Final answer: {structuredJson.RootElement.GetProperty("final_answer")}"); Console.WriteLine("Reasoning steps:"); foreach (JsonElement stepElement in structuredJson.RootElement.GetProperty("steps").EnumerateArray()) { Console.WriteLine($" - Explanation: {stepElement.GetProperty("explanation")}"); Console.WriteLine($" Output: {stepElement.GetProperty("output")}"); } </pre>