Programming[edit]
Project の作成[edit]
dotnet new console -o Net8 -f net8.0
cd Net8
dotnet add package OpenAI
vi Program.cs
dotnet run
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}");
非同期によるチャット補完[edit]
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);
}
}
構造化された出力によるチャット補完[edit]
dotnet add package System.Text.Json
dotnet list package
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")}");
}