@cloudflare/ai-gateway

中文文档
0.0.6发布于 2025/12/10TypeScriptESM + CJS近 30 天下载 3704

SDK for Cloudflare AI Gateway

原始使用文档
文档目录15 节
  1. Table of Contents
  2. Features
  3. Installation
  4. Getting Started
  5. Basic Usage
  6. Streaming Responses
  7. Structured Output (Zod)
  8. Streaming Structured Output
  9. Custom Tools
  10. Limitations
  11. Streaming
  12. API Reference
  13. new AIGateway(config: GatewayConfig)
  14. gateway.generateText(options: GenerateTextOptions)
  15. createTool(config: ToolConfig)

AI Gateway SDK

A lightweight TypeScript SDK to Cloudflare's AI Gateway for unified access to multiple AI providers (OpenAI, Google AI Studio, and more).
Supports text generation (with optional streaming), structured output via Zod, and custom tool integration.


Table of Contents


Features

  • Multi‐provider support: OpenAI, Google AI Studio, etc.
  • Streaming responses for low‐latency consumption.
  • Structured outputs using Zod.
  • Custom tool integration (function calling) for external data/actions.

Installation

npm install @cloudflare/ai-gateway
# or
yarn add @cloudflare/ai-gateway

Getting Started

Instantiate the AIGateway with your account details and API keys:

import { AIGateway } from "@cloudflare/ai-gateway";

const gateway = new AIGateway({
  gatewayName: "<YOUR_GATEWAY_NAME>",
  accountId: "<YOUR_ACCOUNT_ID>",
  apiKey: "<YOUR_AIG_CF_TOKEN>"
});

Basic Usage

Generate a one‐off text completion:

const { output } = await gateway.generateText({
  modelName: "openai/gpt-4.1",
  userPrompt: "Hello, how are you?",
  metadata: {
    eu: true,
  },
});
console.log("Output:", output);

Streaming Responses

Receive partial results as they arrive:

const { output } = await gateway.generateText({
  modelName: "google-ai-studio/gemini-2.5-flash-preview-04-17",
  userPrompt:
    "Write a 500 word essay on the importance of AI in modern society.",
  stream: true,
});

for await (const chunk of output) {
  console.log("Chunk:", chunk);
}

Structured Output (Zod)

Enforce a JSON schema on the model’s response:

import z from "zod";

const { output } = await gateway.generateText({
  modelName: "openai/gpt-4.1",
  schema: z.object({
    answer: z.string(),
  }),
  userPrompt: "Hello, how are you?",
});

// `output.answer` is guaranteed to be a string by Zod
console.log("Answer:", output.answer);

Streaming Structured Output

Combine streaming with schema validation:

const { output } = await gateway.generateText({
  modelName: "openai/gpt-4.1",
  schema: z.object({
    answer: z.string(),
    details: z.object({
      length: z.number(),
      language: z.string(),
    }),
  }),
  stream: true,
  userPrompt:
    "Hello, how are you? What is the length of your response and what language is it in?",
});

output.details.length.then((length) => {
  console.log("Length:", length);
});
output.details.language.then((language) => {
  console.log("Language:", language);
});
output.answer.then((answer) => {
  console.log("Answer:", answer);
});

Custom Tools

Define and register external “tools” (functions) that the model can call:

import { createTool } from "@cloudflare/ai-gateway";
import z from "zod"; //v3

const weatherTool = createTool({
  name: "getWeather",
  description: "Get the current weather for a given city",
  parameters: z.object({
    city: z.string().describe("The city to fetch weather for"),
  }),
  function: async ({ city }) => {
    // Your implementation here (API call, database lookup, etc.)
    return { city, temperature: 22, condition: "Sunny" };
  },
});

const { output } = await gateway.generateText({
  modelName: "google-ai-studio/gemini-2.5-flash-preview-04-17",
  tools: [weatherTool],
  userPrompt: "Hello, what is the weather in Bangalore?",
});

console.log("Weather:", output);

Limitations

Streaming

  • The SDK runs on the assumption that content chunks always stream in before tool chunks or tool_chunks before content, if either of the chunks come in intertwined then the previous stream chunk is dropped

API Reference

new AIGateway(config: GatewayConfig)

Creates a new AI gateway client.

new AIGateway({
  gatewayName: string,
  accountId: string,
  apiKey: string,
});
PropertyTypeDescription
gatewayNamestringYour unique gateway identifier.
accountIdstringYour account ID.
apiKeystringA CF token with AI Gateway run scope.

gateway.generateText(options: GenerateTextOptions)

Generate text (optionally streaming or schema-validated).

gateway.generateText({
  modelName: string,
  userPrompt: string,
  schema?: ZodSchema<T>,
  stream?: boolean,
  tools?: ReturnType<typeof createTool>[],
  metadata?: Record<string, any>,
}): Promise<GenerateTextResult<T>>
OptionTypeDescription
modelNamestringIdentifier of the provider/model (e.g. "openai/gpt-4.1", "google-ai-studio/gemini-…")
userPromptstringThe text prompt or user query.
schema?ZodSchema<T>Optional Zod schema to validate and type the JSON response.
stream?booleanIf true, returns an async iterable of text chunks or field Promises.
tools?ReturnType<typeof createTool>[]Array of function-calling tools for the model to invoke.
metadata?Record<string, any>Provider-specific metadata (e.g. region flags).

Returns:

  • Text:

    { output: string | AsyncIterable<string> }
    
  • Structured Output:

    { output: T | { [K in keyof T]: Promise<T[K]> } }
    

createTool(config: ToolConfig)

Define a custom function-calling tool.

createTool({
  name: string,
  description: string,
  parameters: ZodSchema<object>,
  function: (args: any) => Promise<any>,
});
PropertyTypeDescription
namestringUnique tool identifier.
descriptionstringHuman-readable description for the model.
parametersZodSchema<object>Zod schema defining the tool’s input parameters.
function(args) => Promise<any>Implementation that receives validated inputs and returns a result.

版本与发布记录

@cloudflare/ai-gateway 共发布 10 个版本,首次发布于 2025/07/04;过去 12 个月发布了 8 个版本。

版本发布日期距今
0.0.6latest2025/12/1010 个月前
0.0.52025/12/0311 个月前
0.0.42025/12/0311 个月前
0.0.32025/11/2411 个月前
0.0.3-binbin2025/11/2411 个月前
0.0.2-bin2025/11/2411 个月前

其他发布通道:beta → 0.0.1,bin → 0.0.3-bin。

关于 @cloudflare/ai-gateway 的常见问题

@cloudflare/ai-gateway 是什么?

SDK for Cloudflare AI Gateway

如何安装 @cloudflare/ai-gateway?

在项目目录运行 npm install @cloudflare/ai-gateway,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:@cloudflare/workers-types(*)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@cloudflare/ai-gateway 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@cloudflare/ai-gateway 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@cloudflare/ai-gateway 可以商用吗?

@cloudflare/ai-gateway 使用 未声明 许可。package.json 没有声明许可证。没有许可证的代码默认保留全部权利,商用前请联系作者或查看仓库中的 LICENSE 文件。以上为概括,不构成法律意见,请以许可原文为准。

@cloudflare/ai-gateway 的下载量有多少?

根据 npm 官方下载统计,@cloudflare/ai-gateway 在 2026/10/10 – 2026/11/08 这 30 天内被下载 3,704 次,日均约 123 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@cloudflare/ai-gateway 还在维护吗?

最新版本 0.0.6 发布于 2025/12/10(10 个月前);至今共发布 10 个版本,其中过去 12 个月发布了 8 个;首次发布于 2025/07/04。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。