文档
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
类引用
函数引用
接口引用
类型别名引用
变量引用
适配器

OpenAI

OpenAI 适配器提供对 OpenAI 模型的访问,包括 GPT-4o、GPT-5、图像生成(DALL-E)、文本转语音(TTS)和音频转录(Whisper)。

安装

sh
npm install @tanstack/ai-openai

基本用法

typescript
import { chat } from "@tanstack/ai";
import { openaiText } from "@tanstack/ai-openai";

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

基本用法 - 自定义 API 密钥

typescript
import { chat } from "@tanstack/ai";
import { createOpenaiChat } from "@tanstack/ai-openai";

const adapter = createOpenaiChat(process.env.OPENAI_API_KEY!, {
  // ... your config options
});

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

配置

typescript
import { createOpenaiChat, type OpenAIChatConfig } from "@tanstack/ai-openai";

const config: Omit<OpenAIChatConfig, 'apiKey'> = {
  organization: "org-...", // Optional
  baseURL: "https://api.openai.com/v1", // Optional, for custom endpoints
};

const adapter = createOpenaiChat(process.env.OPENAI_API_KEY!, config);

示例:聊天完成

typescript
import { chat, toServerSentEventsResponse } from "@tanstack/ai";
import { openaiText } from "@tanstack/ai-openai";

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

  const stream = chat({
    adapter: openaiText("gpt-5.2"),
    messages,
  });

  return toServerSentEventsResponse(stream);
}

示例:使用工具

typescript
import { chat, toolDefinition } from "@tanstack/ai";
import { openaiText } from "@tanstack/ai-openai";
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: openaiText("gpt-5.2"),
  messages,
  tools: [getWeather],
});

模型选项

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

typescript
const stream = chat({
  adapter: openaiText("gpt-5.2"),
  messages,
  modelOptions: {
    temperature: 0.7,
    max_tokens: 1000,
    top_p: 0.9,
    frequency_penalty: 0.5,
    presence_penalty: 0.5,
    stop: ["END"],
  },
});

推理

为支持推理的模型启用推理(例如,GPT-5、O3)。这允许模型展示其推理过程,该过程以 思考中 块流式传输

typescript
modelOptions: {
  reasoning: {
    effort: "medium", // "none" | "minimal" | "low" | "medium" | "high"
    summary: "detailed", // "auto" | "detailed" (optional)
  },
}

当启用推理时,模型的推理过程会与响应文本分开流式传输,并显示为 UI 中的可折叠思考部分。

摘要

总结长文本内容

typescript
import { summarize } from "@tanstack/ai";
import { openaiSummarize } from "@tanstack/ai-openai";

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

console.log(result.summary);

图像生成

使用 DALL-E 生成图像

typescript
import { generateImage } from "@tanstack/ai";
import { openaiImage } from "@tanstack/ai-openai";

const result = await generateImage({
  adapter: openaiImage("gpt-image-1"),
  prompt: "A futuristic cityscape at sunset",
  numberOfImages: 1,
  size: "1024x1024",
});

console.log(result.images);

图像模型选项

typescript
const result = await generateImage({
  adapter: openaiImage("gpt-image-1"),
  prompt: "...",
  modelOptions: {
    quality: "hd", // "standard" | "hd"
    style: "natural", // "natural" | "vivid"
  },
});

文本转语音

从文本生成语音

typescript
import { generateSpeech } from "@tanstack/ai";
import { openaiTTS } from "@tanstack/ai-openai";

const result = await generateSpeech({
  adapter: openaiTTS("tts-1"),
  text: "Hello, welcome to TanStack AI!",
  voice: "alloy",
  format: "mp3",
});

// result.audio contains base64-encoded audio
console.log(result.format); // "mp3"

TTS 声音

可用声音:alloyechofableonyxnovashimmerashballadcoralsageverse

TTS 模型选项

typescript
const result = await generateSpeech({
  adapter: openaiTTS("tts-1-hd"),
  text: "High quality speech",
  modelOptions: {
    speed: 1.0, // 0.25 to 4.0
  },
});

语音转文本

将音频转录为文本

typescript
import { generateTranscription } from "@tanstack/ai";
import { openaiTranscription } from "@tanstack/ai-openai";

const result = await generateTranscription({
  adapter: openaiTranscription("whisper-1"),
  audio: audioFile, // File object or base64 string
  language: "en",
});

console.log(result.text); // Transcribed text

转录模型选项

typescript
const result = await generateTranscription({
  adapter: openaiTranscription("whisper-1"),
  audio: audioFile,
  modelOptions: {
    response_format: "verbose_json", // Get timestamps
    temperature: 0,
    prompt: "Technical terms: API, SDK",
  },
});

// Access segments with timestamps
console.log(result.segments);

环境变量

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

sh
OPENAI_API_KEY=sk-...

API 参考

openaiText(config?)

使用环境变量创建一个 OpenAI 聊天适配器。

返回值:一个 OpenAI 聊天适配器实例。

createOpenaiChat(apiKey, config?)

使用显式 API 密钥创建一个 OpenAI 聊天适配器。

参数

  • apiKey - 您的 OpenAI API 密钥
  • config.organization? - 组织 ID(可选)
  • config.baseURL? - 自定义基础 URL (可选)

返回值:一个 OpenAI 聊天适配器实例。

openaiSummarize(config?)

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

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

createOpenaiSummarize(apiKey, config?)

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

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

openaiImage(config?)

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

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

createOpenaiImage(apiKey, config?)

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

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

openaiTTS(config?)

使用环境变量创建一个 OpenAI TTS 适配器。

返回值:一个 OpenAI TTS 适配器实例。

createOpenaiTTS(apiKey, config?)

使用显式 API 密钥创建一个 OpenAI TTS 适配器。

返回值:一个 OpenAI TTS 适配器实例。

openaiTranscription(config?)

使用环境变量创建一个 OpenAI 转录适配器。

返回值:一个 OpenAI 转录适配器实例。

createOpenaiTranscription(apiKey, config?)

使用显式 API 密钥创建一个 OpenAI 转录适配器。

返回值:一个 OpenAI 转录适配器实例。

下一步