chat-gpt’s diary

ChatGPTでAIと会話した結果を残してます。

下記curlの実行をc#に置き換えてください。

下記curlの実行をc#に置き換えてください。

curl https://api.openai.com/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -d '{
    "model": "gpt-3.5-turbo",
    "messages": [{"role": "user", "content": "Hello!"}]
  }'

以下は、C#で実行するためのコード例です。

using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        var openaiApiKey = "your-openai-api-key";

        var httpClient = new HttpClient();
        httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", openaiApiKey);

        var requestUrl = "https://api.openai.com/v1/chat/completions";
        var requestBody = new
        {
            model = "gpt-3.5-turbo",
            messages = new[]
            {
                new { role = "user", content = "Hello!" }
            }
        };
        var jsonRequestBody = JsonConvert.SerializeObject(requestBody);

        var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, requestUrl);
        httpRequestMessage.Content = new StringContent(jsonRequestBody, Encoding.UTF8, "application/json");

        var response = await httpClient.SendAsync(httpRequestMessage);

        var responseContent = await response.Content.ReadAsStringAsync();
        Console.WriteLine(responseContent);
    }
}

上記の例では、HttpClientを使用して、HTTP POSTリクエストを送信します。リクエスト本文には、匿名型を使用してJSON形式のデータを構築し、StringContentを使用してHTTPリクエストボディに変換します。Httpリクエストに必要な認証情報をAuthorizationヘッダに追加しています。最後に、HTTPリクエストを送信して、HTTP応答を取得しています。

一部修正して実行