AI Chat API 串接說明

我們知道,市面上一些問答 API 的串接還是相對沒那麼容易的,比如說 OpenAI 的 Chat Completions API,它有一個 messages 欄位,如果要完成連續對話,需要我們把所有的上下文歷史全部傳遞,同時還需要處理 Token 超出限制的問題。

零壹AI 提供的 AI 問答 API 針對上述情況進行了最佳化,在保證問答效果不變的情況下,對連續對話的實作進行了封裝,串接時無須再關心 messages 的傳遞,也無須關心 Token 超出限制的問題(API 內部自動進行了處理),同時也提供了對話查詢、修改等功能,使得整體的串接大大簡化。

本文文件會介紹 AI 問答 API 的串接說明。

申請流程

要使用 AI 問答 API,首先到 零壹AI 控制台 取得您的 API Token,留作備用。

如果你尚未登入或註冊,會自動跳轉到登入頁面邀請你註冊和登入,完成後會自動返回目前頁面。

通用應用程式的 API Key 可用於帳號已開放的服務;專用應用程式的 Key 按該應用程式的服務範圍使用。請檢查 Key 的權限、有效期和限額,並確認應用程式餘額足以支付本次請求。可用試用額度以帳號顯示為準,餘額不足時點擊「充值」按鈕即可。

📘 完整文件:AI 問答 API →

基本使用

首先先了解一下基本的使用方式,就是輸入問題,獲得回答,只需要簡單地傳遞一個 question 欄位,並指定相應模型即可。

比如說詢問:「你叫什麼名字?」,我們接下來就可以在介面上填寫對應的內容,如圖所示:

可以看到這裡我們設定了請求標頭,包括:

  • accept:想要接收什麼格式的回應結果,這裡填寫為 application/json,即 JSON 格式。
  • authorization:呼叫 API 的金鑰,申請之後可以直接下拉選擇。

另外設定了請求本文,包括:

  • 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.01ai.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.01ai.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.01ai.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"
}

第二次請求,將第一次請求返回的 id 欄位作為參數傳遞,同時 stateful 參數依然設定為 true,詢問「我剛才問了你什麼?」,如圖所示:

對應程式碼如下:

curl -X POST 'https://api.01ai.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"
}

可以看到,就可以根據上下文回答對應的問題了。

對話管理與計費

POST /aichat/conversations 省略 action 或傳入 "action": "chat" 時,需提供 question 和 model,按所選模型計費。以下四種對話管理操作每次均為 0 Credits,無須提供 question 或 model。

沿用上文的請求位址和授權標頭,將範例中的 <id> 替換為自己的多輪對話返回的 id。

操作 JSON 請求本文範例 結果
查詢對話 {"action":"retrieve","id":"<id>"} 返回儲存的對話,包括訊息歷史。
批次查詢 {"action":"retrieve_batch","ids":["<id>"]} items 包含查詢到的對話,count 為結果數。
更新對話 {"action":"update","id":"<id>","title":"項目討論"} 設定標題。傳入 messages 陣列可替換整段訊息歷史,也可同時更新兩者。
刪除對話 {"action":"delete","id":"<id>"} 返回 id 和 deleted: true。

串流回應

該介面也支援串流回應,這對網頁串接十分有用,可以讓網頁實現逐字顯示效果。

如果想串流返回回應,可以更改請求標頭裡面的 accept 參數,修改為 application/x-ndjson。

修改如圖所示,不過呼叫程式碼需要有對應的更改才能支援串流回應。

將 accept 修改為 application/x-ndjson 之後,API 將逐行返回對應的 JSON 資料,在程式碼層面我們需要做相應的修改來取得逐行的結果。

Python 範例呼叫程式碼:

import requests

url = "https://api.01ai.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.01ai.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.01ai.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.01ai.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.01ai.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.01ai.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,回答效果會更好。