OpenAIのAPIにリクエストを送る方法を調べた

はじめに

最近OpenAIが話題に上がることが多いですね。今回の記事ではOpenAIのAPIにリクエストを送る方法を調べたので、具体例を交えて共有したいと思います。

前提

  • OpenAIにサインアップしていること
  • APIキーを取得済みであること

また、SDK(Python、Node)を利用する方法については本記事では扱いません。

HTTPリクエストの送り方を学ぶ

以下のページに様々な例があります。

https://platform.openai.com/examples

その中でも今回は「Q&A」を使って説明したいと思います。

https://platform.openai.com/examples/default-qa

画面下部のAPI requestのところでcurlを選ぶと以下のように表示されます。

curl https://api.openai.com/v1/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -d '{
  "model": "text-davinci-003",
  "prompt": "I am a highly intelligent question answering bot. If you ask me a question that is rooted in truth, I will give you the answer. If you ask me a question that is nonsense, trickery, or has no clear answer, I will respond with \"Unknown\".\n\nQ: What is human life expectancy in the United States?\nA: Human life expectancy in the United States is 78 years.\n\nQ: Who was president of the United States in 1955?\nA: Dwight D. Eisenhower was president of the United States in 1955.\n\nQ: Which party did he belong to?\nA: He belonged to the Republican Party.\n\nQ: What is the square root of banana?\nA: Unknown\n\nQ: How does a telescope work?\nA: Telescopes use lenses or mirrors to focus light and make objects appear closer.\n\nQ: Where were the 1992 Olympics held?\nA: The 1992 Olympics were held in Barcelona, Spain.\n\nQ: How many squigs are in a bonk?\nA: Unknown\n\nQ: Where is the Valley of Kings?\nA:",
  "temperature": 0,
  "max_tokens": 100,
  "top_p": 1,
  "frequency_penalty": 0.0,
  "presence_penalty": 0.0,
  "stop": ["\n"]
}'

curlの次にあるのがURL、 -Hの部分がヘッダー、-dの部分がリクエストの本文となります。なお、リクエストメソッドはPOSTになります。

本文のpromptの部分ですが、ここは少し加工します。Q: Who was president of the United States in 1955?以降、たくさんの質問と回答例が書かれていますが、おそらくここは不要なのでは?と予想し、今回の記事では以下のようにします。

I am a highly intelligent question answering bot. If you ask me a question that is rooted in truth, I will give you the answer. If you ask me a question that is nonsense, trickery, or has no clear answer, I will respond with \"Unknown\".\n\nQ: [ここに質問を書く]\nA

具体例

上記を具体的に実装した例を見てみましょう。

プログラムを書く場合(C#)

私が普段よく使っているC#での実装例です。.NET 6のコンソールアプリを使います。
コードは以下のようになります。

using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;

string apiKey = "[OpenAIのAPIキー]";
string uri = "https://api.openai.com/v1/completions";
var question = "[質問したいこと]";

//本文に使うJSONの作成
JsonBody json = new JsonBody
{
    model = "text-davinci-003",
    prompt= $"I am a highly intelligent question answering bot. If you ask me a question that is rooted in truth, I will give you the answer. If you ask me a question that is nonsense, trickery, or has no clear answer, I will respond with \"Unknown\". Q:{question} A:",
    temperature = 0,
    max_tokens = 100,
    top_p = 1,
    frequency_penalty = 0.0f,
    presence_penalty = 0.0f,
    stop = new string[1] { "\\n" }
};

HttpClient _httpClient = new();
var request = new HttpRequestMessage
{
    Method = HttpMethod.Post,  //リクエストの種類を指定
    RequestUri = new Uri(uri)  //URLを指定
};

//ヘッダーの指定
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);

//本文の作成
var content = JsonSerializer.Serialize(json);
request.Content = new StringContent(content, Encoding.UTF8, "application/json");

//リクエストを送信
var response = await _httpClient.SendAsync(request);
if (response.IsSuccessStatusCode)
{
    //結果を文字列として取得
    var resultContent = await response.Content.ReadAsStringAsync();

    //結果の表示
    Console.WriteLine("回答:" + JsonNode.Parse(resultContent)!["choices"]![0]!["text"]);
}


//JSON作成用のクラス
class JsonBody
{
    public string model { get; set; } = "";
    public string prompt { get; set; } = "";
    public int temperature { get; set; }
    public int max_tokens { get; set; }
    public int top_p { get; set; }
    public float frequency_penalty { get; set; }
    public float presence_penalty { get; set; }
    public string[]? stop { get; set; }
}

例えばquestion日本の人口はどのくらい?と入力すると以下の結果が得られます。

回答:日本の人口は約1億2,800万人です。

ここではコンソールアプリにしましたが、上記を応用してデスクトップアプリやWEBアプリに実装するといいと思います。

ローコードの場合(Power Automate)

Power AutomateでもOpenAIを使ってみましょう。HTTPコネクタを使うと以下のようになります。

上記画像の2か所([OpenAIのAPIキー]、[ここに質問を書く])を書き換えて使います。
[ここに質問を書く]は直接書くよりも変数を挿入した方が使いやすいと思います。(例えば、Power Appsから受け取った文字列など)
受け取った結果はJSONの解析を利用すると扱いやすくなります。今回の場合は以下のようなスキーマにしました。

{
    "type": "object",
    "properties": {
        "id": {
            "type": "string"
        },
        "object": {
            "type": "string"
        },
        "created": {
            "type": "integer"
        },
        "model": {
            "type": "string"
        },
        "choices": {
            "type": "array",
            "items": {
                "type": "object",
                "properties": {
                    "text": {
                        "type": "string"
                    },
                    "index": {
                        "type": "integer"
                    },
                    "logprobs": {},
                    "finish_reason": {
                        "type": "string"
                    }
                },
                "required": [
                    "text",
                    "index",
                    "logprobs",
                    "finish_reason"
                ]
            }
        },
        "usage": {
            "type": "object",
            "properties": {
                "prompt_tokens": {
                    "type": "integer"
                },
                "completion_tokens": {
                    "type": "integer"
                },
                "total_tokens": {
                    "type": "integer"
                }
            }
        }
    }
}

これとPower Appsを組み合わせると、以下のようなアプリを作ることができます。

終わりに

今回はQ&Aを例として使い方や実装方法などを紹介しました。他にも色々な使い方ができると思うのでぜひ試してみて下さい。

執筆担当者プロフィール
古川 貴浩

古川 貴浩(日本ビジネスシステムズ株式会社)

HoloLens 2アプリケーションの開発をしています。

担当記事一覧