AI Chat API 連携ガイド

ご存じのとおり、市場にある一部の質問応答 API との連携は、依然として比較的容易ではありません。例えば、OpenAI の Chat Completions API には messages フィールドがあり、継続的な対話を行うには、すべてのコンテキスト履歴を渡す必要があると同時に、トークンが制限を超える問題にも対処する必要があります。

AceDataCloud が提供する AI 質問応答 API は、上記の状況に対応するために最適化されており、質問応答の品質を維持したまま、継続的な対話の実装をカプセル化しています。連携時に messages の受け渡しを気にする必要がなく、トークンが制限を超える問題も気にする必要がありません(API 内部で自動的に処理されます)。また、対話の照会や変更などの機能も提供されているため、連携全体が大幅に簡素化されます。

このドキュメントでは、AI 質問応答 API との連携方法を紹介します。

申請手順

AI 質問応答 API を使用するには、まず Ace Data Cloud コンソールにアクセスし、API トークンを取得して控えておきます。

まだログインまたは登録していない場合は、登録とログインを促すログインページに自動的に移動し、完了後に現在のページへ自動的に戻ります。

汎用アプリケーションの API Key は、アカウントで利用可能になっているサービスに使用できます。専用アプリケーションの Key は、そのアプリケーションのサービス範囲に応じて使用します。Key の権限、有効期限、上限を確認し、アプリケーションの残高が今回のリクエストの支払いに十分であることを確認してください。利用可能なトライアル枠はアカウントに表示されている内容をご確認ください。残高が不足している場合は、「チャージ」ボタンをクリックしてください。

📘 完全なドキュメント:AI 質問応答 API →

基本的な使い方

まず、基本的な使い方を確認しましょう。質問を入力して回答を得るには、question フィールドを渡し、対応するモデルを指定するだけです。

例えば、「お名前は何ですか?」と質問する場合、以下の図のように、画面に対応する内容を入力できます。

ここでは、以下を含む Request Headers を設定しています。

  • accept:受け取りたいレスポンス結果の形式。ここでは JSON 形式である application/json を入力します。
  • authorization:API を呼び出すためのキー。申請後、ドロップダウンから直接選択できます。

また、以下を含む Request Body も設定しています。

  • model:モデルの選択。例えば、主流の GPT 3.5、GPT 4 などです。
  • question:質問する内容。任意のプレーンテキストを指定できます。

選択すると、以下の図のように、右側に対応するコードも生成されます。

「Try」ボタンをクリックするとテストできます。上の図のように、ここでは以下の結果が得られました。

{
  "answer": "I am an AI language model developed by OpenAI and I don't have a personal name. However, you can call me GPT or simply Chatbot. How can I assist you today?"
}

返された結果には answer フィールドがあり、これが質問への回答です。任意の質問を入力すれば、それに対する回答を得ることができます。

複数ターンの対話をサポートする必要がない場合、この API によって連携が大幅に容易になります。

また、対応する連携コードを生成したい場合は、生成されたコードを直接コピーできます。例えば、CURL のコードは次のとおりです。

curl -X POST 'https://api.acedata.cloud/aichat/conversations' \
-H 'accept: application/json' \
-H 'authorization: Bearer {token}' \
-H 'content-type: application/json' \
-d '{
  "model": "gpt-3.5",
  "question": "What's your name?"
}'

Python の連携コードは次のとおりです。

import requests

url = "https://api.acedata.cloud/aichat/conversations"

headers = {
    "accept": "application/json",
    "authorization": "Bearer {token}",
    "content-type": "application/json"
}

payload = {
    "model": "gpt-3.5",
    "question": "What's your name?"
}

response = requests.post(url, json=payload, headers=headers)
print(response.text)

複数ターンの対話

複数ターンの対話機能を連携したい場合は、追加パラメーター stateful を渡し、その値を true にする必要があります。以降の各リクエストにもこのパラメーターを含める必要があります。stateful パラメーターを渡すと、API は現在の対話の ID を表す id パラメーターを追加で返します。以降はこの ID をパラメーターとして渡すだけで、複数ターンの対話を簡単に実現できます。

以下で具体的な操作を説明します。

最初のリクエストでは、stateful パラメーターを true に設定し、model と question パラメーターを通常どおり渡します。以下の図をご覧ください。

対応するコードは次のとおりです。

curl -X POST 'https://api.acedata.cloud/aichat/conversations' \
-H 'accept: application/json' \
-H 'authorization: Bearer {token}' \
-H 'content-type: application/json' \
-d '{
  "model": "gpt-3.5",
  "question": "What's your name?",
  "stateful": true
}'

以下の回答が得られます。

{
  "answer": "I am an AI language model created by OpenAI and I don't have a personal name. You can simply call me OpenAI or ChatGPT. How can I assist you today?",
  "id": "7cdb293b-2267-4979-a1ec-48d9ad149916"
}

2 回目のリクエストでは、最初のリクエストで返された id フィールドをパラメーターとして渡し、stateful パラメーターは引き続き true に設定して、「さっき私は何を質問しましたか?」と尋ねます。以下の図をご覧ください。

対応するコードは次のとおりです。

curl -X POST 'https://api.acedata.cloud/aichat/conversations' \
-H 'accept: application/json' \
-H 'authorization: Bearer {token}' \
-H 'content-type: application/json' \
-d '{
  "model": "gpt-3.5",
  "stateful": true,
  "id": "7cdb293b-2267-4979-a1ec-48d9ad149916",
  "question": "What I asked you just now?"
}'

結果は次のとおりです。

{
  "answer": "You asked me what my name is. As an AI language model, I do not possess a personal identity, so I don't have a specific name. However, you can refer to me as OpenAI or ChatGPT, the names used for this AI model. Is there anything else I can help you with?",
  "id": "7cdb293b-2267-4979-a1ec-48d9ad149916"
}

このように、コンテキストに基づいて質問に回答できることがわかります。

ストリーミングレスポンス

このインターフェースはストリーミングレスポンスにも対応しています。これは Web ページとの連携に非常に便利で、文字を逐次表示する効果を実現できます。

レスポンスをストリーミングで返したい場合は、リクエストヘッダー内の accept パラメーターを application/x-ndjson に変更できます。

変更は以下の図のとおりですが、ストリーミングレスポンスに対応するには、呼び出しコードも変更する必要があります。

accept を application/x-ndjson に変更すると、API は対応する JSON データを 1 行ずつ返します。行ごとの結果を取得するには、コード側で適切な変更を行う必要があります。

Python のサンプル呼び出しコード:

import requests

url = "https://api.acedata.cloud/aichat/conversations"

headers = {
    "accept": "application/x-ndjson",
    "authorization": "Bearer {token}",
    "content-type": "application/json"
}

payload = {
    "model": "gpt-3.5",
    "stateful": True,
    "id": "7cdb293b-2267-4979-a1ec-48d9ad149916",
    "question": "Hello"
}

response = requests.post(url, json=payload, headers=headers, stream=True)
for line in response.iter_lines():
    print(line.decode())

出力結果は以下のとおりです:

{"answer": "Hello", "delta_answer": "Hello", "id": "7cdb293b-2267-4979-a1ec-48d9ad149916"}
{"answer": "Hello!", "delta_answer": "!", "id": "7cdb293b-2267-4979-a1ec-48d9ad149916"}
{"answer": "Hello! How", "delta_answer": " How", "id": "7cdb293b-2267-4979-a1ec-48d9ad149916"}
{"answer": "Hello! How can", "delta_answer": " can", "id": "7cdb293b-2267-4979-a1ec-48d9ad149916"}
{"answer": "Hello! How can I", "delta_answer": " I", "id": "7cdb293b-2267-4979-a1ec-48d9ad149916"}
{"answer": "Hello! How can I assist", "delta_answer": " assist", "id": "7cdb293b-2267-4979-a1ec-48d9ad149916"}
{"answer": "Hello! How can I assist you", "delta_answer": " you", "id": "7cdb293b-2267-4979-a1ec-48d9ad149916"}
{"answer": "Hello! How can I assist you today", "delta_answer": " today", "id": "7cdb293b-2267-4979-a1ec-48d9ad149916"}
{"answer": "Hello! How can I assist you today?", "delta_answer": "?", "id": "7cdb293b-2267-4979-a1ec-48d9ad149916"}

ご覧のとおり、レスポンス内の answer は最新の回答内容であり、delta_answer は新たに追加された回答内容です。結果に基づいて、お使いのシステムに連携できます。

JavaScript もサポートされています。例えば、Node.js のストリーミング呼び出しコードは以下のとおりです:

const axios = require("axios");

const url = "https://api.acedata.cloud/aichat/conversations";
const headers = {
  "Content-Type": "application/json",
  Accept: "application/x-ndjson",
  Authorization: "Bearer {token}",
};
const body = {
  question: "Hello",
  model: "gpt-3.5",
  stateful: true,
};

axios
  .post(url, body, { headers: headers, responseType: "stream" })
  .then((response) => {
    console.log(response.status);
    response.data.on("data", (chunk) => {
      console.log(chunk.toString());
    });
  })
  .catch((error) => {
    console.error(error);
  });

Java のサンプルコード:

String url = "https://api.acedata.cloud/aichat/conversations";
OkHttpClient client = new OkHttpClient();
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, "{\"question\": \"Hello\", \"stateful\": true, \"model\": \"gpt-3.5\"}");
Request request = new Request.Builder()
        .url(url)
        .post(body)
        .addHeader("Content-Type", "application/json")
        .addHeader("Accept", "application/x-ndjson")
        .addHeader("Authorization", "Bearer {token}")
        .build();

client.newCall(request).enqueue(new Callback() {
    @Override
    public void onFailure(Call call, IOException e) {
        e.printStackTrace();
    }

    @Override
    public void onResponse(Call call, Response response) throws IOException {
        if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
        try (BufferedReader br = new BufferedReader(
                new InputStreamReader(response.body().byteStream(), "UTF-8"))) {
            String responseLine;
            while ((responseLine = br.readLine()) != null) {
                System.out.println(responseLine);
            }
        }
    }
});

その他の言語については、ご自身で書き換えることができます。仕組みはすべて同じです。

モデルのプリセット

ご存じのとおり、OpenAI 関連の API には system_prompt という概念があり、モデル全体に名前などのプリセットを設定できます。この AI 質問応答 API でも、このパラメータが preset という名前で公開されており、これを利用してモデルにプリセットを追加できます。例を使って試してみましょう:

ここでは preset フィールドを追加し、内容を You are a professional artist とします。図のとおりです:

対応するコードは以下のとおりです:

curl -X POST 'https://api.acedata.cloud/aichat/conversations' \
-H 'accept: application/json' \
-H 'authorization: Bearer {token}' \
-H 'content-type: application/json' \
-d '{
  "model": "gpt-3.5",
  "stateful": true,
  "question": "What can you help me?",
  "preset": "You are a professional artist"
}'

実行結果は以下のとおりです:

{
    "answer": "As a professional artist, I can offer a range of services and assistance depending on your specific needs. Here are a few ways I can help you:\n\n1. Custom Artwork: If you have a specific vision or idea, I can create custom artwork for you. This can include paintings, drawings, digital art, or any other medium you prefer.\n\n2. Commissioned Pieces: If you have a specific subject or concept in mind, I can create commissioned art pieces tailored to your preferences. This could be for personal enjoyment or as a unique gift for someone special.\n\n3. Art Consultation: If you need guidance on art selection, interior design, or how to showcase and display art in your space, I can provide professional advice to help enhance your aesthetic sense and create a cohesive look."
}

ご覧のとおり、ここでは GPT に自分がロボットであると伝え、私たちのために何ができるかを尋ねると、ロボットの役割を演じて質問に答えることができます。

画像認識

この AI は、添付ファイルを追加して画像認識を行うこともサポートしています。references を通じて対応する画像のリンクを渡すだけです。例えば、ここにリンゴの画像があります。図のとおりです:

この画像のリンクは https://cdn.acedata.cloud/ht05g0.png です。これをそのまま references パラメータとして渡します。また、モデルは視覚認識をサポートするものを選択する必要があることに注意してください。現在サポートされているのは gpt-4-vision なので、以下のように入力します:

対応するコードは以下のとおりです:

curl -X POST 'https://api.acedata.cloud/aichat/conversations' \
-H 'accept: application/json' \
-H 'authorization: Bearer {token}' \
-H 'content-type: application/json' \
-d '{
  "model": "gpt-4-vision",
  "question": "How many apples in the picture?",
  "references": ["https://cdn.acedata.cloud/ht05g0.png"]
}'

実行結果は以下のとおりです:

{
  "answer": "There are 5 apples in the picture."
}

ご覧のとおり、対応する画像についての回答結果を無事に取得できました。

インターネットに接続した質問応答

この API はインターネットに接続するモデルもサポートしており、GPT-3.5 と GPT-4 のどちらにも対応しています。API の背後では、インターネットを自動的に検索して要約する処理が行われます。モデルに gpt-3.5-browsing を選択して試すことができます。図のとおりです:

コードは以下のとおりです:

curl -X POST 'https://api.acedata.cloud/aichat/conversations' \
-H 'accept: application/json' \
-H 'authorization: Bearer {token}' \
-H 'content-type: application/json' \
-d '{
  "model": "gpt-3.5-browsing",
  "question": "What's the weather of New York today?"
}'

実行結果は次のとおりです。

{
  "answer": "The weather in New York today is as follows:\n- Current Temperature: 16°C (60°F)\n- High: 16°C (60°F)\n- Low: 10°C (50°F)\n- Humidity: 47%\n- UV Index: 6 of 11\n- Sunrise: 5:42 am\n- Sunset: 8:02 pm\n\nIt's overcast with a chance of occasional showers overnight, and the chance of rain is 50%.\nFor more details, you can visit [The Weather Channel](https://weather.com/weather/tenday/l/96f2f84af9a5f5d452eb0574d4e4d8a840c71b05e22264ebdc0056433a642c84).\n\nIs there anything else you'd like to know?"
}

ここでは、The Weather Channel のウェブサイトを自動的にオンライン検索して、その中の情報を取得し、さらにリアルタイムの結果を返したことがわかります。

モデルの回答品質により高い要件がある場合は、モデルを gpt-4-browsing に変更すると、回答の質が向上します。