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

基于模型的类型安全

AI SDK 提供了针对 modelOptions特定模型类型安全。每个模型的能力决定了允许哪些模型选项,TypeScript 会在编译时强制执行此操作。

工作原理

用法示例

✅ 正确用法

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

// ✅ gpt-5 supports structured outputs - `text` is allowed
const validCall = chat({
  adapter: openaiText("gpt-5"),
  messages: [],
  modelOptions: {
    // OK - text is included for gpt-5
    text: {
      type: "json_schema",
      json_schema: {
        /* ... */
      },
    },
  },
});

❌ 错误用法

typescript
// ❌ gpt-4-turbo does NOT support structured outputs - `text` is rejected
const invalidCall = chat({
  adapter: openaiText("gpt-4-turbo"),
  messages: [],
  modelOptions: {
    text: {}, // ❌ TypeScript error: 'text' does not exist in type
  },
});

TypeScript 将会产生

error TS2353: Object literal may only specify known properties, and 'text' does not exist in type ...'.

优势

  • 编译时安全:在部署前捕获不正确的模型选项
  • 更好的 IDE 体验:自动补全仅显示每个模型的有效选项
  • 自文档化:模型能力在类型系统中显式
  • 零运行时开销:所有类型检查都在编译时发生