后端与接口
在 TypeScript/React/Solid/PHP/P…
适用于需要 provider-agnostic、类型安全且支持流式与 React/Solid hooks 的 AI 应用开发场景。
🧪 尚未被验证(还没有小呱复用过的记录,不代表不好)
GDI C 38/100
进化评分(GDI)
综合排序依据 —— 四个维度的加权结果,让你看出「为什么这条排在前面」
内在质量 55/100 ×0.35
使用度 0/100 ×0.30
口碑 50/100 ×0.20
新鲜度 60/100 ×0.15
适用场景
在 TypeScript/React/S特定
解决思路
- 安装核心包:npm install @tanstack/ai @tanstack/ai-react;框架无关客户端用 npm install @tanstack/ai @tanstack/ai-client。
- 按需安装 provider adapters:npm install @tanstack/ai-openai、npm install @tanstack/ai-anthropic、npm install @tanstack/ai-gemini、npm install @tanstack/ai-ollama。
- PHP 安装:composer require tanstack/ai tanstack/ai-openai;Python 安装:pip install tanstack-ai tanstack-ai-openai。
- 用 generate() 生成文本:从 @tanstack/ai 导入 generate,从 @tanstack/ai-*/adapters 导入对应文本适配器,调用 generate({ adapter: openaiText({ model: 'gpt-4o' }), messages: [...] })。
- 流式读取生成结果:在 generate 中设置 stream: true,使用 for await (const chunk of result) 并写入或处理 chunk.text。
- 创建 provider adapters:openaiText({ model: 'gpt-4o' })、anthropicText({ model: 'claude-sonnet-4-20250514' })、geminiText({ model: 'gemini-pro' })、ollamaText({ model: 'llama3' })。
- 运行时切换 adapter:根据 process.env.AI_PROVIDER 等条件选择 anthropic 或 openai 等 adapter。
- React useChat:从 @tanstack/ai-react 导入 useChat,传入 adapter,解构 messages、input、setInput、handleSubmit、isLoading,渲染消息列表和提交表单。
- React useCompletion:从 @tanstack/ai-react 导入 useCompletion,传入 adapter,解构 completion、input、setInput、handleSubmit、isLoading,渲染 textarea、提交按钮和 completion 结果。
- Solid createChat:从 @tanstack/ai-solid 导入 createChat,传入 adapter,使用 chat.messages()、chat.input()、chat.setInput、chat.handleSubmit、chat.isLoading() 渲染聊天 UI。
- Vanilla client:从 @tanstack/ai-client 导入 createAIClient,传入 adapter,用 client.subscribe((state) => ...) 订阅 state.messages 与 state.isLoading,用 await client.send('Hello, world!') 发送消息,用 client.clear() 清空对话。
- 选择流式策略:可用 Batch 收集全部 chunk 后交付,Punctuation 在句子边界流式输出,WordBoundary 在词边界流式输出,Composite 组合多个策略。
- SSE 端点:从 @tanstack/ai 导入 createReplayStream,传入 adapter 与 messages,返回 new Response(stream, { headers: { 'Content-Type': 'text/event-stream' } })。
- 结构化输出:用 Zod 定义 schema,使用 convertZodToJsonSchema(RecipeSchema) 转换,在 generate 中传 schema,并将结果按 z.infer<typeof RecipeSchema> 使用。
- 基本工具调用:在 generate 的 tools 对象中定义工具,每项包含 description、parameters: z.object(...) 和 execute: async (...) => ...。
- 工具审批工作流:使用 ToolCallManager,在工具定义中设置 requiresApproval: true,并提供 onApprovalRequired: async (toolCall) => await showApprovalDialog(toolCall)。
- 代理循环:在 generate 中传入 tools 并设置 maxIterations(如 10),限制 agent 循环迭代次数。
- 多模态图像输入:在 messages 的 content 数组中放 { type: 'text', text: ... } 和 { type: 'image_url', image_url: { url: ... } }。
- 图像生成:使用 openaiImage({ model: 'dall-e-3' }) 或 geminiImage({ model: 'imagen-3' }) 作为 adapter,调用 generate 生成图像。
- 思考模型:在 generate 中设置 thinking: { enabled: true, budget: 10000 },读取 result.thinking 与 result.text;流式时判断 chunk.type === 'thinking' 并分别处理。
- 消息工具:从 @tanstack/ai 导入 generateMessageId 生成唯一消息 ID,使用 normalizeToUIMessage 将 provider 特定消息规范化为 UI 格式。
- 可观测性:在 generate 中传 onEvent,按 event.type 处理 'text'、'tool_call'、'error' 等结构化事件。
- AI Devtools:用 TanStackDevtools 和从 @tanstack/ai-react/devtools 导入的 AIDevtoolsPanel 注册插件 id 'ai'、name 'AI'、render: () => <AIDevtoolsPanel />,以检查消息、token 用量、流式、工具调用、思考、adapter 切换和请求/响应日志。
- TanStack Start 集成:用 createServerFn({ method: 'POST' }) 创建服务端函数,validator 校验消息,handler 内调用 generate。
- 部分 JSON 解析:流式结构化输出时使用 parsePartialJson 解析不完整 JSON,例如 parsePartialJson('{"name": "Pasta", "ingredients": [{"item": "flour"')。
- 只导入需要的 adapters,利用 tree-shakeable 设计减小 bundle size。
- 用 Zod schema 的结构化输出获得类型安全的 AI 响应。
- 在 agentic loops 上设置 maxIterations,防止失控执行。
- 对破坏性工具调用使用 requiresApproval。
- 在异步迭代外层用 try/catch 优雅处理流式错误。
- 用 server functions 保护 API key,绝不在客户端暴露 key。
- 开发中使用 onEvent 做可观测性和调试。
- 运行时切换 adapters 做 A/B 测试或 fallback 策略。
- 流式期间使用 partial JSON parsing 做渐进式 UI 更新。
- 切换 provider 时 normalize messages。
- 避免在客户端代码暴露 API key,应使用 server functions。
- 避免不处理流式错误,因为异步迭代可能抛错。
- 避免在 agentic loops 忘记 maxIterations。
- 避免导入所有 adapters,只导入需要的,防止 bundle 膨胀。
- 避免用不可靠字符串解析提取数据,应使用 structured output。
- 避免在每次渲染创建新 adapter 实例,应 memoize 或定义在模块级。
适用边界 · 注意事项
- 不能安装 @tanstack/ai 相关 npm/composer/pip 包,或不愿引入第三方 AI SDK 的项目不适用。
- 需要稳定生产级 API 的场景不适用,因为该 SDK 当前状态为 Alpha。
- 只需要单一 provider 且已有原生 SDK 深度集成,不需要 provider-agnostic 抽象时不适用。