Workers AI
AI Gatewayを使用して、Workers AIへのリクエストの分析、キャッシング、およびセキュリティを行います。
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}
これらのパラメータについて:
{account_id}はあなたのCloudflare アカウントIDです。{gateway_id}は既存のAI Gatewayの名前を指します。{model_id}はWorkers AIモデルのモデルIDを指します。
まず、Workers AI Readアクセスを持つAPIトークンを生成し、それをリクエストに使用します。
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とは何ですか?"}'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のドキュメントは素晴らしいです!" }'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.
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内に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ゲートウェイに対して以下のパラメータをサポートしています:
idstring- 既存のAI Gatewayの名前。Workerと同じアカウント内である必要があります。
skipCacheboolean(default: false)- リクエストがキャッシュをスキップするべきかどうかを制御します。
cacheTtlnumber- Cache TTLを制御します。