tanstack-ai
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseTanStack AI (Provider-Agnostic LLM SDK)
TanStack AI(与供应商无关的LLM开发工具包)
Status: Production Ready ✅
Last Updated: 2025-12-09
Dependencies: Node.js 18+, TypeScript 5+; React 18+ for; Solid 1.8+ for
Latest Versions: @tanstack/ai@latest (alpha), @tanstack/ai-react@latest, @tanstack/ai-client@latest, adapters: @tanstack/ai-openai@latest @tanstack/ai-anthropic@latest @tanstack/ai-gemini@latest @tanstack/ai-ollama@latest
Last Updated: 2025-12-09
Dependencies: Node.js 18+, TypeScript 5+; React 18+ for
@tanstack/ai-react@tanstack/ai-solidLatest Versions: @tanstack/ai@latest (alpha), @tanstack/ai-react@latest, @tanstack/ai-client@latest, adapters: @tanstack/ai-openai@latest @tanstack/ai-anthropic@latest @tanstack/ai-gemini@latest @tanstack/ai-ollama@latest
状态:可投入生产使用 ✅
最后更新:2025-12-09
依赖项:Node.js 18+、TypeScript 5+;使用需React 18+;使用需Solid 1.8+
最新版本:@tanstack/ai@latest(测试版)、@tanstack/ai-react@latest、@tanstack/ai-client@latest,适配器:@tanstack/ai-openai@latest @tanstack/ai-anthropic@latest @tanstack/ai-gemini@latest @tanstack/ai-ollama@latest
最后更新:2025-12-09
依赖项:Node.js 18+、TypeScript 5+;使用
@tanstack/ai-react@tanstack/ai-solid最新版本:@tanstack/ai@latest(测试版)、@tanstack/ai-react@latest、@tanstack/ai-client@latest,适配器:@tanstack/ai-openai@latest @tanstack/ai-anthropic@latest @tanstack/ai-gemini@latest @tanstack/ai-ollama@latest
Quick Start (7 Minutes)
快速入门(7分钟)
1) Install core + adapter
1) 安装核心包 + 适配器
bash
pnpm add @tanstack/ai @tanstack/ai-react @tanstack/ai-openaibash
pnpm add @tanstack/ai @tanstack/ai-react @tanstack/ai-openaiswap adapters as needed: @tanstack/ai-anthropic @tanstack/ai-gemini @tanstack/ai-ollama
根据需要替换适配器:@tanstack/ai-anthropic @tanstack/ai-gemini @tanstack/ai-ollama
pnpm add zod # recommended for tool schemas
**Why this matters:**
- Core is framework-agnostic; React binding just wraps the headless client. citeturn1search3
- Adapters abstract provider quirks so you can change models without rewriting code. citeturn1search3pnpm add zod # 推荐用于工具 schema
**关键意义**:
- 核心包与框架无关;React绑定仅对无头客户端进行封装。 citeturn1search3
- 适配器封装了供应商的特性差异,让你无需重写代码即可切换模型。 citeturn1search32) Ship a streaming chat endpoint (Next.js or TanStack Start)
2) 部署流式聊天接口(Next.js 或 TanStack Start)
ts
// app/api/chat/route.ts (Next.js) or src/routes/api/chat.ts (TanStack Start)
import { chat, toStreamResponse } from '@tanstack/ai'
import { openai } from '@tanstack/ai-openai'
import { tools } from '@/tools/definitions' // definitions only
export async function POST(request: Request) {
const { messages, conversationId } = await request.json()
const stream = chat({
adapter: openai(),
messages,
model: 'gpt-4o',
tools,
})
return toStreamResponse(stream)
}CRITICAL:
- Pass tool definitions to the server so the LLM can request them; implementations live in their runtimes. citeturn0search7
- Always stream; chunked responses keep UIs responsive and reduce token waste. citeturn0search1
ts
// app/api/chat/route.ts(Next.js)或 src/routes/api/chat.ts(TanStack Start)
import { chat, toStreamResponse } from '@tanstack/ai'
import { openai } from '@tanstack/ai-openai'
import { tools } from '@/tools/definitions' // 仅导入定义
export async function POST(request: Request) {
const { messages, conversationId } = await request.json()
const stream = chat({
adapter: openai(),
messages,
model: 'gpt-4o',
tools,
})
return toStreamResponse(stream)
}重要提示:
- 将工具定义传递给服务器,以便LLM可以请求调用;工具实现需放在对应的运行环境中。 citeturn0search7
- 始终使用流式传输;分块响应能保持UI的响应性,减少令牌浪费。 citeturn0search1
3) Wire the client with useChat
+ SSE
useChat3) 通过useChat
+ SSE连接客户端
useChattsx
// components/Chat.tsx
import { useChat, fetchServerSentEvents } from '@tanstack/ai-react'
import { clientTools } from '@tanstack/ai-client'
import { updateUIDef } from '@/tools/definitions'
const updateUI = updateUIDef.client(({ message }) => {
alert(message)
return { success: true }
})
export function Chat() {
const tools = clientTools(updateUI)
const { messages, sendMessage, isLoading, approval } = useChat({
connection: fetchServerSentEvents('/api/chat'),
tools,
})
return (
<form onSubmit={e => { e.preventDefault(); sendMessage(e.currentTarget.prompt.value) }}>
<textarea name="prompt" disabled={isLoading} />
{approval?.pending && (
<button type="button" onClick={() => approval.approve()}>
Approve tool
</button>
)}
</form>
)
}CRITICAL:
- Use (or matching adapter) to mirror the streaming response. citeturn0search0
fetchServerSentEvents - Keep client tool names identical to definitions to avoid “tool not found” errors. citeturn0search7
tsx
// components/Chat.tsx
import { useChat, fetchServerSentEvents } from '@tanstack/ai-react'
import { clientTools } from '@tanstack/ai-client'
import { updateUIDef } from '@/tools/definitions'
const updateUI = updateUIDef.client(({ message }) => {
alert(message)
return { success: true }
})
export function Chat() {
const tools = clientTools(updateUI)
const { messages, sendMessage, isLoading, approval } = useChat({
connection: fetchServerSentEvents('/api/chat'),
tools,
})
return (
<form onSubmit={e => { e.preventDefault(); sendMessage(e.currentTarget.prompt.value) }}>
<textarea name="prompt" disabled={isLoading} />
{approval?.pending && (
<button type="button" onClick={() => approval.approve()}>
批准工具调用
</button>
)}
</form>
)
}重要提示:
- 使用(或匹配的适配器)来对接流式响应。 citeturn0search0
fetchServerSentEvents - 保持客户端工具名称与定义完全一致,避免出现“工具未找到”错误。 citeturn0search7
The 4-Step Setup Process
四步设置流程
Step 1: Choose provider + model safely
步骤1:安全选择供应商 + 模型
- Add the correct adapter and set the matching API key (,
OPENAI_API_KEY,ANTHROPIC_API_KEY, or Ollama host).GEMINI_API_KEY - Prefer per-model option typing from adapters to avoid invalid options (e.g., vision-only fields). citeturn1search3
- 添加正确的适配器并设置匹配的API密钥(、
OPENAI_API_KEY、ANTHROPIC_API_KEY或Ollama主机地址)。GEMINI_API_KEY - 优先使用适配器提供的各模型专属选项类型,避免无效选项(例如仅视觉相关字段)。 citeturn1search3
Step 2: Define tools once, implement per runtime
步骤2:一次定义工具,按运行环境分别实现
ts
// tools/definitions.ts
import { z, toolDefinition } from '@tanstack/ai'
export const getWeatherDef = toolDefinition({
name: 'getWeather',
description: 'Get current weather for a city',
inputSchema: z.object({ city: z.string() }),
needsApproval: true,
})
export const getWeather = getWeatherDef.server(async ({ city }) => {
const data = await fetch(`https://api.weather.gov/points?q=${city}`).then(r => r.json())
return { summary: data.properties?.relativeLocation?.properties?.city ?? city }
})
export const showToast = getWeatherDef.client(({ city }) => {
console.log(`Showing toast for ${city}`)
return { acknowledged: true }
})Key Points:
- forces explicit user approval for sensitive actions. citeturn0search1
needsApproval: true - Keep tools single-purpose and idempotent; return structured objects instead of throwing errors. citeturn0search1
ts
// tools/definitions.ts
import { z, toolDefinition } from '@tanstack/ai'
export const getWeatherDef = toolDefinition({
name: 'getWeather',
description: '获取城市当前天气',
inputSchema: z.object({ city: z.string() }),
needsApproval: true,
})
export const getWeather = getWeatherDef.server(async ({ city }) => {
const data = await fetch(`https://api.weather.gov/points?q=${city}`).then(r => r.json())
return { summary: data.properties?.relativeLocation?.properties?.city ?? city }
})
export const showToast = getWeatherDef.client(({ city }) => {
console.log(`Showing toast for ${city}`)
return { acknowledged: true }
})核心要点:
- 会强制要求用户对敏感操作进行明确批准。 citeturn0search1
needsApproval: true - 保持工具单一职责且幂等;返回结构化对象而非抛出错误。 citeturn0search1
Step 3: Create connection adapter + chat options
步骤3:创建连接适配器 + 聊天选项
- Server: for HTTP streaming;
toStreamResponse(stream)helper for Server-Sent Events. citeturn0search3turn0search4toServerSentEventsStream - Client: or a custom adapter for websockets if needed. citeturn0search0
fetchServerSentEvents('/api/chat') - Configure (e.g.,
agentLoopStrategy) to cap tool recursion. citeturn1search4maxIterations(8)
- 服务器端:使用实现HTTP流式传输;使用
toStreamResponse(stream)工具类实现Server-Sent Events。 citeturn0search3turn0search4toServerSentEventsStream - 客户端:使用,若有需要可自定义适配器用于websocket连接。 citeturn0search0
fetchServerSentEvents('/api/chat') - 配置(例如
agentLoopStrategy)以限制工具递归次数。 citeturn1search4maxIterations(8)
Step 4: Add observability + guardrails
步骤4:添加可观测性 + 防护机制
- Log tool executions and stream chunks for debugging; alpha exposes hooks while devtools are in progress. citeturn0search1
- Validate inputs with Zod; fail fast and return typed error objects.
- Enforce timeouts on external API calls inside tools to prevent stuck agent loops.
- 记录工具执行情况和流分块信息用于调试;测试版已暴露相关钩子,调试工具仍在开发中。 citeturn0search1
- 使用Zod验证输入;快速失败并返回类型化错误对象。
- 对工具内部的外部API调用设置超时时间,防止Agent循环陷入停滞。
Critical Rules
关键规则
Always Do
必须遵守
✅ Stream responses; avoid waiting for full completions. citeturn0search1
✅ Pass definitions to the server and implementations to the correct runtime. citeturn0search7
✅ Use Zod schemas for tool inputs/outputs to keep type safety across providers. citeturn0search1
✅ Cap agent loops with to prevent runaway tool calls. citeturn1search4
✅ Require for destructive or billing-sensitive tools. citeturn0search1
✅ Pass definitions to the server and implementations to the correct runtime. citeturn0search7
✅ Use Zod schemas for tool inputs/outputs to keep type safety across providers. citeturn0search1
✅ Cap agent loops with
maxIterations✅ Require
needsApproval✅ 使用流式响应;避免等待完整结果返回。 citeturn0search1
✅ 将定义传递给服务器,将实现部署到对应运行环境。 citeturn0search7
✅ 使用Zod schema定义工具输入/输出,保持跨供应商的类型安全。 citeturn0search1
✅ 通过限制Agent循环次数,防止工具调用失控。 citeturn1search4
✅ 对破坏性或涉及计费的工具要求。 citeturn0search1
✅ 将定义传递给服务器,将实现部署到对应运行环境。 citeturn0search7
✅ 使用Zod schema定义工具输入/输出,保持跨供应商的类型安全。 citeturn0search1
✅ 通过
maxIterations✅ 对破坏性或涉及计费的工具要求
needsApprovalNever Do
禁止操作
❌ Mix provider adapters in a single request—instantiate one adapter per call.
❌ Throw raw errors from tools; return structured error payloads.
❌ Send client tool implementations to the server (definitions only).
❌ Hardcode model capabilities; rely on adapter typings for per-model options. citeturn0search1
❌ Skip API key checks; fail fast with helpful messages on the server. citeturn0search1
❌ Throw raw errors from tools; return structured error payloads.
❌ Send client tool implementations to the server (definitions only).
❌ Hardcode model capabilities; rely on adapter typings for per-model options. citeturn0search1
❌ Skip API key checks; fail fast with helpful messages on the server. citeturn0search1
❌ 在单个请求中混合使用多个供应商适配器——每次调用仅实例化一个适配器。
❌ 从工具中抛出原始错误;返回结构化错误负载。
❌ 将客户端工具实现发送到服务器(仅传递定义)。
❌ 硬编码模型能力;依赖适配器类型获取各模型专属选项。 citeturn0search1
❌ 跳过API密钥检查;在服务器端快速失败并返回友好提示信息。 citeturn0search1
❌ 从工具中抛出原始错误;返回结构化错误负载。
❌ 将客户端工具实现发送到服务器(仅传递定义)。
❌ 硬编码模型能力;依赖适配器类型获取各模型专属选项。 citeturn0search1
❌ 跳过API密钥检查;在服务器端快速失败并返回友好提示信息。 citeturn0search1
Known Issues Prevention
已知问题预防
This skill prevents 3 documented issues:
本工具可预防3个已记录的问题:
Issue #1: “tool not found” / silent tool failures
问题1:“工具未找到” / 工具静默失败
Why it happens: Definitions aren’t passed to ; only implementations exist locally.
Prevention: Export definitions separately and include them in the server array; keep names stable. citeturn0search7
chat()Prevention: Export definitions separately and include them in the server
tools原因:未将定义传递给;仅本地存在工具实现。
预防方案:单独导出定义并将其包含在服务器的数组中;保持工具名称稳定。 citeturn0search7
chat()预防方案:单独导出定义并将其包含在服务器的
toolsIssue #2: Streaming stalls in the UI
问题2:UI中流式传输停滞
Why it happens: Mismatch between server response type and client adapter (HTTP chunked vs SSE).
Prevention: Use on the server + (or matching adapter) on the client. citeturn0search1turn0search0
Prevention: Use
toStreamResponsefetchServerSentEvents原因:服务器响应类型与客户端适配器不匹配(HTTP分块 vs SSE)。
预防方案:服务器端使用,客户端使用(或匹配的适配器)。 citeturn0search1turn0search0
预防方案:服务器端使用
toStreamResponsefetchServerSentEventsIssue #3: Model option validation errors
问题3:模型选项验证错误
Why it happens: Provider-specific options (e.g., vision params) sent to unsupported models.
Prevention: Use adapter-provided types; rely on per-model option typing to surface invalid fields at compile time. citeturn1search3
Prevention: Use adapter-provided types; rely on per-model option typing to surface invalid fields at compile time. citeturn1search3
原因:向不支持的模型发送供应商专属选项(例如视觉参数)。
预防方案:使用适配器提供的类型;依赖各模型专属选项类型在编译阶段发现无效字段。 citeturn1search3
预防方案:使用适配器提供的类型;依赖各模型专属选项类型在编译阶段发现无效字段。 citeturn1search3
Configuration Files Reference
配置文件参考
.env.local (Full Example)
.env.local(完整示例)
env
OPENAI_API_KEY=sk-...
ANTHROPIC_API_KEY=
GEMINI_API_KEY=
OLLAMA_HOST=http://localhost:11434
AI_STREAM_STRATEGY=immediateWhy these settings:
- Keep non-active providers empty to avoid accidental multi-provider calls.
- is read by the sample client to pick chunk strategies (immediate vs buffered).
AI_STREAM_STRATEGY
env
OPENAI_API_KEY=sk-...
ANTHROPIC_API_KEY=
GEMINI_API_KEY=
OLLAMA_HOST=http://localhost:11434
AI_STREAM_STRATEGY=immediate设置意义:
- 未使用的供应商留空,避免意外触发多供应商调用。
- 供示例客户端读取,用于选择分块策略(即时 vs 缓冲)。
AI_STREAM_STRATEGY
Common Patterns
常见模式
Pattern 1: Agentic cycle with bounded tools
模式1:带工具限制的Agent循环
ts
import { chat, maxIterations } from '@tanstack/ai'
import { openai } from '@tanstack/ai-openai'
const stream = chat({
adapter: openai(),
messages,
tools,
agentLoopStrategy: maxIterations(8), // hard cap
})When to use: Any flow where the LLM could recurse across tools (search → summarize → fetch detail). citeturn1search4
ts
import { chat, maxIterations } from '@tanstack/ai'
import { openai } from '@tanstack/ai-openai'
const stream = chat({
adapter: openai(),
messages,
tools,
agentLoopStrategy: maxIterations(8), // 硬限制
})适用场景:LLM可能在工具间递归调用的任何流程(搜索 → 总结 → 获取详情)。 citeturn1search4
Pattern 2: Hybrid server + client tools
模式2:混合服务器 + 客户端工具
ts
// server: data fetch
const fetchUser = fetchUserDef.server(async ({ id }) => db.user.find(id))
// client: UI update
const highlightUser = highlightUserDef.client(({ id }) => {
document.querySelector(`#user-${id}`)?.classList.add('ring')
return { highlighted: true }
})
chat({ tools: [fetchUser, highlightUser] })When to use: When the model must both fetch data and mutate UI state in one loop. citeturn0search1
ts
// 服务器端:数据获取
const fetchUser = fetchUserDef.server(async ({ id }) => db.user.find(id))
// 客户端:UI更新
const highlightUser = highlightUserDef.client(({ id }) => {
document.querySelector(`#user-${id}`)?.classList.add('ring')
return { highlighted: true }
})
chat({ tools: [fetchUser, highlightUser] })适用场景:模型需要在一次循环中同时获取数据并修改UI状态时。 citeturn0search1
Using Bundled Resources
使用捆绑资源
Scripts (scripts/)
脚本(scripts/)
- — verifies required provider keys are present before running dev servers.
scripts/check-ai-env.sh
Example Usage:
bash
./scripts/check-ai-env.sh- —— 启动开发服务器前验证所需供应商密钥是否存在。
scripts/check-ai-env.sh
示例用法:
bash
./scripts/check-ai-env.shReferences (references/)
参考文档(references/)
- — condensed server/client/tool patterns plus troubleshooting cues.
references/tanstack-ai-cheatsheet.md
When Claude should load these: When debugging tool routing, streaming issues, or recalling exact API calls.
- —— 浓缩的服务器/客户端/工具模式及故障排查提示。
references/tanstack-ai-cheatsheet.md
Claude应何时加载: 调试工具路由、流式传输问题或回忆具体API调用时。
Assets (assets/)
资源文件(assets/)
- — copy/paste API route template with streaming + tools.
assets/api-chat-route.ts - — ready-to-use toolDefinition examples with approval + zod schemas.
assets/tool-definitions.ts
- —— 可直接复制粘贴的API路由模板,包含流式传输 + 工具配置。
assets/api-chat-route.ts - —— 现成的toolDefinition示例,包含审批机制 + zod schema。
assets/tool-definitions.ts
When to Load References
何时加载参考文档
Load reference files for specific implementation scenarios:
-
Adapter Comparison: Loadwhen choosing between OpenAI, Anthropic, Gemini, or Ollama adapters, or when debugging provider-specific quirks.
references/adapter-matrix.md -
React Integration Details: Loadwhen implementing useChat hooks, handling SSE streams in React components, or managing client-side tool state.
references/react-integration.md -
Routing Setup: Loadwhen setting up API routes in Next.js vs TanStack Start, or troubleshooting streaming response setup.
references/start-vs-next-routing.md -
Streaming Issues: Loadwhen debugging SSE connection problems, chunk delivery issues, or HTTP streaming configuration.
references/streaming-troubleshooting.md -
Quick Reference: Loadfor condensed API patterns, tool definition syntax, or rapid troubleshooting cues.
references/tanstack-ai-cheatsheet.md -
Tool Architecture: Loadwhen implementing complex client/server tool workflows, approval flows, or hybrid tool patterns.
references/tool-patterns.md -
Type Safety Details: Loadwhen working with per-model option typing, multimodal inputs, or debugging type errors across adapters.
references/type-safety.md
针对特定实现场景加载参考文件:
-
适配器对比:选择OpenAI、Anthropic、Gemini或Ollama适配器,或调试供应商专属问题时,加载。
references/adapter-matrix.md -
React集成细节:实现useChat钩子、在React组件中处理SSE流或管理客户端工具状态时,加载。
references/react-integration.md -
路由设置:在Next.js或TanStack Start中设置API路由,或排查流式响应设置问题时,加载。
references/start-vs-next-routing.md -
流式传输问题:调试SSE连接问题、分块交付问题或HTTP流式传输配置时,加载。
references/streaming-troubleshooting.md -
快速参考:需要浓缩的API模式、工具定义语法或快速故障排查提示时,加载。
references/tanstack-ai-cheatsheet.md -
工具架构:实现复杂的客户端/服务器工具工作流、审批流程或混合工具模式时,加载。
references/tool-patterns.md -
类型安全细节:处理各模型专属选项类型、多模态输入或调试跨适配器类型错误时,加载。
references/type-safety.md
Advanced Topics
进阶主题
Per-model type safety
各模型类型安全
- Use adapter typings to pick valid options per model; avoid generic options on
any. citeturn1search3chat() - For multimodal models, send with correct MIME types; unsupported modalities are caught at compile time. citeturn1search3
parts
- 使用适配器类型选择各模型的有效选项;避免在中使用通用
chat()类型选项。 citeturn1search3any - 对于多模态模型,发送带有正确MIME类型的;不支持的模态会在编译阶段被捕获。 citeturn1search3
parts
Tool approval UX
工具审批用户体验
- Surfaced via object in
approval; render approve/reject UI and persist decision per tool call. citeturn0search1useChat - For auditable actions, log approval decisions alongside tool inputs.
- 通过中的
useChat对象暴露;渲染批准/拒绝UI并针对每个工具调用保存决策。 citeturn0search1approval - 对于可审计操作,将审批决策与工具输入一起记录。
Connection adapters
连接适配器
- Default to (SSE) for minimal setup; switch to custom adapters for websockets or HTTP chunking. citeturn0search0
fetchServerSentEvents - Use in the client to emit every chunk for typing indicator UIs. citeturn0search0
ImmediateStrategy
- 默认使用(SSE)实现最小化配置;若需websocket或HTTP分块传输可切换为自定义适配器。 citeturn0search0
fetchServerSentEvents - 在客户端使用以输出每个分块,用于实现输入指示器UI。 citeturn0search0
ImmediateStrategy
Dependencies
依赖项
Required:
- @tanstack/ai@latest — core chat + tool engine
- @tanstack/ai-react@latest — React bindings (skip for headless usage)
- @tanstack/ai-client@latest — headless chat client + adapters
- Adapter: one of @tanstack/ai-openai@latest | @tanstack/ai-anthropic@latest | @tanstack/ai-gemini@latest | @tanstack/ai-ollama@latest
- zod@latest — schema validation for tools
Optional:
- @tanstack/ai-solid@latest — Solid bindings
- @tanstack/react-query@latest — cache data fetched inside tools
- @tanstack/start@latest — co-locate AI tools with server functions
必填:
- @tanstack/ai@latest —— 核心聊天 + 工具引擎
- @tanstack/ai-react@latest —— React绑定(无头使用可跳过)
- @tanstack/ai-client@latest —— 无头聊天客户端 + 适配器
- 适配器:以下之一 @tanstack/ai-openai@latest | @tanstack/ai-anthropic@latest | @tanstack/ai-gemini@latest | @tanstack/ai-ollama@latest
- zod@latest —— 工具schema验证
可选:
- @tanstack/ai-solid@latest —— Solid绑定
- @tanstack/react-query@latest —— 缓存工具内部获取的数据
- @tanstack/start@latest —— 将AI工具与服务器函数共存
Official Documentation
官方文档
- TanStack AI Overview: https://tanstack.com/ai/latest/docs/getting-started/overview
- Quick Start: https://tanstack.com/ai/latest/docs/getting-started/quick-start
- Tool Architecture & Approval: https://tanstack.com/ai/latest/docs/guides/tool-architecture
- Client Tools: https://tanstack.com/ai/latest/docs/guides/client-tools
- API Reference: https://tanstack.com/ai/latest/docs/api/ai
- TanStack AI 概览:https://tanstack.com/ai/latest/docs/getting-started/overview
- 快速入门:https://tanstack.com/ai/latest/docs/getting-started/quick-start
- 工具架构与审批:https://tanstack.com/ai/latest/docs/guides/tool-architecture
- 客户端工具:https://tanstack.com/ai/latest/docs/guides/client-tools
- API参考:https://tanstack.com/ai/latest/docs/api/ai
Package Versions (Verified 2025-12-09)
包版本(2025-12-09 验证)
json
{
"dependencies": {
"@tanstack/ai": "latest",
"@tanstack/ai-react": "latest",
"@tanstack/ai-client": "latest",
"@tanstack/ai-openai": "latest"
},
"devDependencies": {
"zod": "latest"
}
}json
{
"dependencies": {
"@tanstack/ai": "latest",
"@tanstack/ai-react": "latest",
"@tanstack/ai-client": "latest",
"@tanstack/ai-openai": "latest"
},
"devDependencies": {
"zod": "latest"
}
}Troubleshooting
故障排查
Problem: UI never receives tool output
问题:UI从未收到工具输出
Solution: Ensure tool implementations return serializable objects; avoid returning undefined. Register client implementations via .
clientTools(...)解决方案:确保工具实现返回可序列化对象;避免返回undefined。通过注册客户端实现。
clientTools(...)Problem: “Missing API key” responses
问题:“缺少API密钥”响应
Solution: Run and set the relevant provider key in . Fail fast in the route before invoking . citeturn0search1
./scripts/check-ai-env.sh.env.localchat()解决方案:运行并在中设置对应供应商的密钥。在调用前在路由中快速失败。 citeturn0search1
./scripts/check-ai-env.sh.env.localchat()Problem: Streaming stops after first chunk
问题:流式传输在第一个分块后停止
Solution: Confirm the server returns (or SSE helper) and that any reverse proxy allows chunked transfer.
toStreamResponse(stream)解决方案:确认服务器返回(或SSE工具类),且任何反向代理允许分块传输。
toStreamResponse(stream)Complete Setup Checklist
完整设置检查清单
Use this checklist to verify your setup:
- Installed core + one adapter and zod
- API route returns with tool definitions included
toStreamResponse(stream) - Client uses (or matching adapter) and registers client tool implementations
fetchServerSentEvents - paths render approve/reject UI
needsApproval - Agent loop capped (e.g., )
maxIterations - Environment keys validated with
check-ai-env.sh - Multimodal inputs tested if targeting vision/audio models
Questions? Issues?
- Load for deeper examples
references/tanstack-ai-cheatsheet.md - Re-run quick start steps with a single provider adapter
- Review official docs above for API surface updates
使用此清单验证你的设置:
- 已安装核心包 + 一个适配器及zod
- API路由返回,且包含工具定义
toStreamResponse(stream) - 客户端使用(或匹配的适配器)并注册客户端工具实现
fetchServerSentEvents - 路径已渲染批准/拒绝UI
needsApproval - Agent循环已设置限制(例如)
maxIterations - 已通过验证环境密钥
check-ai-env.sh - 若针对视觉/音频模型,已测试多模态输入
有疑问?遇到问题?
- 加载查看更多示例
references/tanstack-ai-cheatsheet.md - 使用单个供应商适配器重新运行快速入门步骤
- 查看上述官方文档了解API更新