非リアルタイム WebSockets API では、毎回のハンドシェイクなしで、AI リクエスト向けの持続的な接続を確立できます。リアルタイムのやり取りは不要でも、レイテンシの削減と継続的な通信の恩恵を受けたいアプリケーションに適しています。
- 適切な AI Gateway Run 権限付きの AI Gateway トークンを生成し、認証済みゲートウェイの利用にオプトインします。
wss://プロトコルで WebSocket 接続を開始します。wss://gateway.ai.cloudflare.com/v1/{account_id}/{gateway_id}- AI Gateway Run 権限付きの Cloudflare トークンで認証し、WebSocket 接続を開きます。
import WebSocket from "ws";
const ws = new WebSocket(
"wss://gateway.ai.cloudflare.com/v1/my-account-id/my-gateway/",
{
headers: {
"cf-aig-authorization": "Bearer AI_GATEWAY_TOKEN",
},
},
);
ws.on("open", () => {
ws.send(
JSON.stringify({
type: "universal.create",
request: {
eventId: "my-request",
provider: "workers-ai",
endpoint: "@cf/meta/llama-3.1-8b-instruct",
headers: {
Authorization: "Bearer WORKERS_AI_TOKEN",
"Content-Type": "application/json",
},
query: {
prompt: "tell me a joke",
},
},
}),
);
})
ws.on("message", (message) => {
console.log(message.toString());
});{
"type": "universal.created",
"metadata": {
"cacheStatus": "MISS",
"eventId": "my-request",
"logId": "01JC3R94FRD97JBCBX3S0ZAXKW",
"step": "0",
"contentType": "application/json"
},
"response": {
"result": {
"response": "Why was the math book sad? Because it had too many problems. Would you like to hear another one?"
},
"success": true,
"errors": [],
"messages": []
}
}ストリーミングリクエストでは、AI Gateway はまず、ストリーム開始を示すリクエストメタデータ付きの初期メッセージを送ります。
{
"type": "universal.created",
"metadata": {
"cacheStatus": "MISS",
"eventId": "my-request",
"logId": "01JC40RB3NGBE5XFRZGBN07572",
"step": "0",
"contentType": "text/event-stream"
}
}この初期メッセージのあと、推論プロバイダーから届いたストリーミングチャンクは、到着と同時に WebSocket 接続へリアルタイムで中継されます。これらのストリーミングチャンクのメタデータに含まれるのは eventId フィールドだけです。eventId により、ストリーミング WebSocket 環境でも、各メッセージにクライアント定義の ID を含められます。
{
"type": "universal.stream",
"metadata": {
"eventId": "my-request"
},
"response": {
"response": "would"
}
}リクエストのチャンクをすべてストリーミングし終えると、AI Gateway はリクエスト完了を知らせる最終メッセージを送ります。柔軟性のため、このメッセージには、ストリーミング開始時にすでに送ったメタデータが再びすべて含まれます。
{
"type": "universal.done",
"metadata": {
"cacheStatus": "MISS",
"eventId": "my-request",
"logId": "01JC40RB3NGBE5XFRZGBN07572",
"step": "0",
"contentType": "text/event-stream"
}
}