コンテンツにスキップ

Workers AI

AI Gatewayを使用して、Workers AIへのリクエストの分析、キャッシング、およびセキュリティを行います。

REST API

REST APIと対話するには、リクエストに使用するURLを更新します。

  • 以前: https://api.cloudflare.com/client/v4/accounts/{account_id}/ai/run/{model_id}
  • 新しい: https://gateway.ai.cloudflare.com/v1/{account_id}/{gateway_id}/workers-ai/{model_id}

これらのパラメータについて:

まず、Workers AI Readアクセスを持つAPIトークンを生成し、それをリクエストに使用します。

Workers AI llamaモデルへのリクエスト
curl https://gateway.ai.cloudflare.com/v1/{account_id}/{gateway_id}/workers-ai/@cf/meta/llama-3.1-8b-instruct \
--header 'Authorization: Bearer {cf_api_token}' \
--header 'Content-Type: application/json' \
--data '{"prompt": "Cloudflareとは何ですか?"}'
Workers AIテキスト分類モデルへのリクエスト
curl https://gateway.ai.cloudflare.com/v1/{account_id}/{gateway_id}/workers-ai/@cf/huggingface/distilbert-sst-2-int8 \
--header 'Authorization: Bearer {cf_api_token}' \
--header 'Content-Type: application/json' \
--data '{ "text": "Cloudflareのドキュメントは素晴らしいです!" }'

OpenAI互換エンドポイント

Workers AI supports OpenAI compatible endpoints for text generation (/v1/chat/completions) and text embedding models (/v1/embeddings). This allows you to use the same code as you would for your OpenAI commands, but swap in Workers AI easily.


OpenAI互換エンドポイントへのリクエスト
curl https://gateway.ai.cloudflare.com/v1/{account_id}/{gateway_id}/workers-ai/v1/chat/completions \
--header 'Authorization: Bearer {cf_api_token}' \
--header 'Content-Type: application/json' \
--data '{
"model": "@cf/meta/llama-3.1-8b-instruct",
"messages": [
{
"role": "user",
"content": "Cloudflareとは何ですか?"
}
]
}
'

Worker

Worker内にAI Gatewayを含めるには、リクエスト内にゲートウェイをオブジェクトとして追加します。

export interface Env {
AI: Ai;
}
export default {
async fetch(request: Request, env: Env): Promise<Response> {
const response = await env.AI.run(
"@cf/meta/llama-3.1-8b-instruct",
{
prompt: "なぜAI推論にCloudflareを使用すべきですか?",
},
{
gateway: {
id: "{gateway_id}",
skipCache: false,
cacheTtl: 3360,
},
},
);
return new Response(JSON.stringify(response));
},
} satisfies ExportedHandler<Env>;

Workers AIはAIゲートウェイに対して以下のパラメータをサポートしています:

  • id string
    • 既存のAI Gatewayの名前。Workerと同じアカウント内である必要があります。
  • skipCache boolean(default: false)
  • cacheTtl number