文档
CodeRabbit
Cloudflare
AG Grid
Netlify
Neon
WorkOS
Clerk
Convex
Electric
PowerSync
Sentry
Railway
Prisma
Strapi
Unkey
CodeRabbit
Cloudflare
AG Grid
Netlify
Neon
WorkOS
Clerk
Convex
Electric
PowerSync
Sentry
Railway
Prisma
Strapi
Unkey
类引用
函数引用
接口引用
类型别名引用
变量引用
适配器

Grok (xAI)

Grok 适配器提供对 xAI 的 Grok 模型访问权限,包括 Grok 4.1、Grok 4、Grok 3,以及使用 Grok 2 Image 进行图像生成。

安装

sh
npm install @tanstack/ai-grok

基本用法

typescript
import { chat } from "@tanstack/ai";
import { grokText } from "@tanstack/ai-grok";

const stream = chat({
  adapter: grokText("grok-4"),
  messages: [{ role: "user", content: "Hello!" }],
});

基本用法 - 自定义 API 密钥

typescript
import { chat } from "@tanstack/ai";
import { createGrokText } from "@tanstack/ai-grok";

const adapter = createGrokText("grok-4", process.env.XAI_API_KEY!);

const stream = chat({
  adapter,
  messages: [{ role: "user", content: "Hello!" }],
});

配置

typescript
import { createGrokText, type GrokTextConfig } from "@tanstack/ai-grok";

const config: Omit<GrokTextConfig, "apiKey"> = {
  baseURL: "https://api.x.ai/v1", // Optional, this is the default
};

const adapter = createGrokText("grok-4", process.env.XAI_API_KEY!, config);

示例:聊天完成

typescript
import { chat, toStreamResponse } from "@tanstack/ai";
import { grokText } from "@tanstack/ai-grok";

export async function POST(request: Request) {
  const { messages } = await request.json();

  const stream = chat({
    adapter: grokText("grok-4"),
    messages,
  });

  return toStreamResponse(stream);
}

示例:使用工具

typescript
import { chat, toolDefinition } from "@tanstack/ai";
import { grokText } from "@tanstack/ai-grok";
import { z } from "zod";

const getWeatherDef = toolDefinition({
  name: "get_weather",
  description: "Get the current weather",
  inputSchema: z.object({
    location: z.string(),
  }),
});

const getWeather = getWeatherDef.server(async ({ location }) => {
  // Fetch weather data
  return { temperature: 72, conditions: "sunny" };
});

const stream = chat({
  adapter: grokText("grok-4-1-fast-reasoning"),
  messages,
  tools: [getWeather],
});

模型选项

Grok 支持各种特定于提供商的选项

typescript
const stream = chat({
  adapter: grokText("grok-4"),
  messages,
  modelOptions: {
    frequency_penalty: 0.5,
    presence_penalty: 0.5,
    stop: ["END"],
  },
});

摘要

总结长文本内容

typescript
import { summarize } from "@tanstack/ai";
import { grokSummarize } from "@tanstack/ai-grok";

const result = await summarize({
  adapter: grokSummarize("grok-4"),
  text: "Your long text to summarize...",
  maxLength: 100,
  style: "concise", // "concise" | "bullet-points" | "paragraph"
});

console.log(result.summary);

图像生成

使用 Grok 2 Image 生成图像

typescript
import { generateImage } from "@tanstack/ai";
import { grokImage } from "@tanstack/ai-grok";

const result = await generateImage({
  adapter: grokImage("grok-2-image-1212"),
  prompt: "A futuristic cityscape at sunset",
  numberOfImages: 1,
});

console.log(result.images);

环境变量

将您的 API 密钥设置为环境变量

sh
XAI_API_KEY=xai-...

实现说明

为什么使用聊天完成 API(而非响应 API)

Grok 适配器使用 xAI 的 聊天完成 API (/v1/chat/completions),而不是响应 API (/v1/responses)。这是一个有意的架构决策

  1. 用户自定义工具:聊天完成 API 支持用户定义的函数工具,这对于 TanStack AI 的工具调用功能至关重要。响应 API 仅支持 xAI 的服务器端工具(网络搜索、X 搜索、代码执行)。

  2. 完全的工具调用支持:使用聊天完成,您可以定义使用 Zod 模式在您的应用程序中运行的自定义工具。响应 API 将您限制为仅使用 xAI 的内置工具。

  3. 流式传输兼容性:两种 API 之间的流式传输事件格式差异很大。聊天完成使用 delta.tool_calls 进行参数累积,而响应 API 使用 response.output_item.addedresponse.function_call_arguments.done

  4. OpenAI SDK 兼容性:xAI 的聊天完成 API 与 OpenAI SDK 完全兼容,从而简化了集成,同时保持了工具调用的所有功能。

如果您需要 xAI 的服务器端工具(网络搜索、X/Twitter 搜索、代码执行),则需要直接使用响应 API。但是,对于大多数需要自定义工具定义的使用案例,聊天完成 API 是正确的选择。

API 参考

grokText(model, config?)

使用环境变量创建一个 Grok 文本适配器。

参数

  • model - 模型名称(例如 'grok-4', 'grok-4-1-fast-reasoning'
  • config.baseURL? - 自定义基础 URL (可选)

返回值: 一个 Grok 文本适配器实例。

createGrokText(model, apiKey, config?)

使用显式 API 密钥创建一个 Grok 文本适配器。

参数

  • model - 模型名称
  • apiKey - 您的 xAI API 密钥
  • config.baseURL? - 自定义基础 URL (可选)

返回值: 一个 Grok 文本适配器实例。

grokSummarize(model, config?)

使用环境变量创建一个 Grok 摘要适配器。

返回值: 一个 Grok 摘要适配器实例。

createGrokSummarize(model, apiKey, config?)

使用显式 API 密钥创建一个 Grok 摘要适配器。

返回值: 一个 Grok 摘要适配器实例。

grokImage(model, config?)

使用环境变量创建一个 Grok 图像生成适配器。

返回值: 一个 Grok 图像适配器实例。

createGrokImage(model, apiKey, config?)

使用显式 API 密钥创建一个 Grok 图像生成适配器。

返回值: 一个 Grok 图像适配器实例。

限制

  • 文本转语音:Grok 不支持文本转语音。请使用 OpenAI 进行 TTS。
  • 转录:Grok 不支持音频转录。请使用 OpenAI 的 Whisper。
  • 响应 API 工具:服务器端工具(网络搜索、X 搜索、代码执行)不支持通过此适配器。请改用带有自定义工具的聊天完成 API。

下一步