### Install and Start Vanilla Chat Source: https://github.com/tanstack/ai/blob/main/examples/README.md Steps to get the Vanilla Chat example running, including dependency installation and starting the development server. ```bash cd examples/vanilla-chat pnpm install pnpm start ``` -------------------------------- ### Install and Start Group Chat Source: https://github.com/tanstack/ai/blob/main/examples/README.md Instructions for setting up the Group Chat example, including dependency installation and API key configuration. ```bash cd examples/ts-group-chat pnpm install cp .env.example .env # Edit .env and add your ANTHROPIC_API_KEY pnpm dev ``` -------------------------------- ### Install and Start TanStack Chat Source: https://github.com/tanstack/ai/blob/main/examples/README.md Steps to install dependencies, set up environment variables, and start the TanStack Chat example. ```bash cd examples/ts-react-chat pnpm install cp env.example .env # Edit .env and add your OPENAI_API_KEY pnpm start ``` -------------------------------- ### Install and Run Project Source: https://github.com/tanstack/ai/blob/main/examples/ts-react-chat/README.md Use these commands to install project dependencies and start the development server. ```bash pnpm install pnpm dev ``` -------------------------------- ### Copy Environment File Source: https://github.com/tanstack/ai/blob/main/examples/ts-vue-chat/README.md Copies the example environment file to `.env` for local configuration. This is a crucial setup step before installing dependencies or running the application. ```bash cp env.example .env ``` -------------------------------- ### Run Example Application Source: https://github.com/tanstack/ai/blob/main/CLAUDE.md Navigate to the example directory and start the development server for the TypeScript React Chat example. This allows for local testing and development of the example application. ```bash cd examples/ts-react-chat pnpm install # if needed pnpm dev # start dev server ``` -------------------------------- ### Install and Start TanStack App Source: https://github.com/tanstack/ai/blob/main/examples/ts-react-search/README.md Use these commands to install project dependencies and start the development server. ```bash pnpm install pnpm start ``` -------------------------------- ### Install Dependencies Source: https://github.com/tanstack/ai/blob/main/examples/vanilla-chat/README.md Install the necessary dependencies for the vanilla chat example by navigating to the directory and running npm or pnpm install. ```bash cd examples/vanilla-chat npm install # or pnpm install ``` -------------------------------- ### Setup Live Test Environment (Bash) Source: https://github.com/tanstack/ai/blob/main/packages/ai-code-mode-skills/README.md Prepare the environment for live testing by copying the example .env file and adding your API key. ```bash cp test-cli/env.example test-cli/.env.local ``` ```bash OPENAI_API_KEY=sk-... # or ANTHROPIC_API_KEY=sk-ant-... ``` -------------------------------- ### Install and Start TanStack App Source: https://github.com/tanstack/ai/blob/main/examples/ts-solid-chat/README.md Commands to install dependencies and start the TanStack application. ```bash pnpm install pnpm start ``` -------------------------------- ### Initial Project Setup Source: https://github.com/tanstack/ai/blob/main/CONTRIBUTING.md Clone the repository, install dependencies, and build all packages to resolve workspace dependencies. Use `PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1` to skip browser download if E2E tests are not needed. ```bash git clone https://github.com/TanStack/ai.git cd ai pnpm install pnpm run build:all # build all public packages once so workspace deps resolve ``` -------------------------------- ### Install Dependencies Source: https://github.com/tanstack/ai/blob/main/AGENTS.md Run this command to install all project dependencies. It should be run before starting any task and after every merge with the main branch. ```bash pnpm install ``` -------------------------------- ### Clone Repository and Install Dependencies Source: https://github.com/tanstack/ai/blob/main/examples/ts-group-chat/README.md Clones the project repository and installs its dependencies using pnpm. This is the initial setup step for the project. ```bash # Clone the repository git clone cd capnweb-chat-demo # Install dependencies pnpm install ``` -------------------------------- ### Run the Expo React Native Chat Example Source: https://github.com/tanstack/ai/blob/main/docs/getting-started/quick-start-react-native.md Execute this command to start the Hono server and the Expo/Metro bundler for the React Native chat example. ```bash pnpm --filter ts-react-native-chat dev ``` -------------------------------- ### Install Dependencies and Start Development Server Source: https://github.com/tanstack/ai/blob/main/examples/ts-react-native-chat/README.md Installs project dependencies and starts the Hono server and Expo/Metro dev server for the React Native app. This script automatically configures the backend URL for physical devices. ```bash pnpm install --no-frozen-lockfile pnpm --filter ts-react-native-chat dev ``` -------------------------------- ### Log Request Start with onStart Source: https://github.com/tanstack/ai/blob/main/docs/advanced/middleware.md Utilize the `onStart` hook to perform setup tasks at the beginning of a request, such as logging the request ID and iteration number. This hook is called after the initial `onConfig` completes. ```typescript import { type ChatMiddleware } from "@tanstack/ai"; const timer: ChatMiddleware = { name: "timer", onStart: (ctx) => { console.log(`Request ${ctx.requestId} started at iteration ${ctx.iteration}`); }, }; ``` -------------------------------- ### Install Groq Adapter Source: https://github.com/tanstack/ai/blob/main/docs/adapters/groq.md Install the Groq adapter package using npm. ```bash npm install @tanstack/ai-groq ``` -------------------------------- ### Install @tanstack/ai-isolate-quickjs Source: https://github.com/tanstack/ai/blob/main/packages/ai-isolate-quickjs/README.md Install the package using pnpm. ```bash pnpm add @tanstack/ai-isolate-quickjs ``` -------------------------------- ### Install OpenAI-Compatible Adapter Source: https://github.com/tanstack/ai/blob/main/docs/adapters/openai-compatible.md Install the adapter from the `@tanstack/ai-openai` package. No additional installation is required as it ships within this package. ```bash npm install @tanstack/ai-openai ``` -------------------------------- ### Install QuickJS Driver Source: https://github.com/tanstack/ai/blob/main/docs/code-mode/code-mode-isolates.md Install the QuickJS driver using pnpm. ```bash pnpm add @tanstack/ai-isolate-quickjs ``` -------------------------------- ### Start Production Server Source: https://github.com/tanstack/ai/blob/main/examples/ts-group-chat/README.md Starts the production server after the application has been built. ```bash pnpm start ``` -------------------------------- ### Install @tanstack/ai-mcp and @modelcontextprotocol/sdk Source: https://github.com/tanstack/ai/blob/main/packages/ai-mcp/README.md Install the necessary packages for using the MCP client. ```bash pnpm add @tanstack/ai-mcp @modelcontextprotocol/sdk ``` -------------------------------- ### Install Ollama on Linux Source: https://github.com/tanstack/ai/blob/main/docs/adapters/ollama.md Install Ollama on Linux by downloading and executing the official installation script. ```bash # Linux curl -fsSL https://ollama.com/install.sh | sh ``` -------------------------------- ### Install @tanstack/ai-svelte Source: https://github.com/tanstack/ai/blob/main/packages/ai-svelte/README.md Install the library using npm, pnpm, or yarn. ```bash npm install @tanstack/ai-svelte # or pnpm add @tanstack/ai-svelte # or yarn add @tanstack/ai-svelte ``` -------------------------------- ### Generate Video with fal.ai Adapter Source: https://github.com/tanstack/ai/blob/main/docs/media/video-generation.md This example demonstrates generating video using the fal.ai adapter, specifying a model and providing a prompt that includes image URLs for the start and end frames, along with text. The 'end_frame' role hint is used for the last image. ```typescript import { generateVideo } from '@tanstack/ai' import { falVideo } from '@tanstack/ai-fal' import { firstFrameUrl, lastFrameUrl } from './assets' await generateVideo({ adapter: falVideo('fal-ai/kling-video/v3/pro/image-to-video'), prompt: [ { type: 'image', source: { type: 'url', value: firstFrameUrl } }, { type: 'text', content: 'Slow cinematic push-in then a hard cut' }, { type: 'image', source: { type: 'url', value: lastFrameUrl }, metadata: { role: 'end_frame' }, }, ], }) ``` -------------------------------- ### Install @tanstack/ai-groq Source: https://github.com/tanstack/ai/blob/main/packages/ai-groq/README.md Install the package using npm, pnpm, or yarn. ```bash npm install @tanstack/ai-groq # or pnpm add @tanstack/ai-groq # or yarn add @tanstack/ai-groq ``` -------------------------------- ### Install fal.ai Adapter Source: https://github.com/tanstack/ai/blob/main/docs/adapters/fal.md Install the @tanstack/ai-fal package using npm. ```bash npm install @tanstack/ai-fal ``` -------------------------------- ### Install @tanstack/ai-client Source: https://github.com/tanstack/ai/blob/main/docs/api/ai-client.md Install the @tanstack/ai-client package using npm. ```bash npm install @tanstack/ai-client ``` -------------------------------- ### Install Solid-Query dependencies Source: https://github.com/tanstack/ai/blob/main/examples/ts-solid-chat/README.md Install the required packages for Solid-Query and its devtools. ```bash pnpm add @tanstack/solid-query @tanstack/solid-query-devtools ``` -------------------------------- ### Install Soniox Adapter Source: https://github.com/tanstack/ai/blob/main/docs/community-adapters/soniox.md Install the Soniox adapter package using npm. ```bash npm install @soniox/tanstack-ai-adapter ``` -------------------------------- ### Basic Usage Example Source: https://github.com/tanstack/ai/blob/main/docs/reference/functions/generateTranscription.md Example of how to use generateTranscription with a specific adapter and audio input. ```APIDOC ## Example: Basic Usage ```ts import { generateTranscription } from '@tanstack/ai' import { openaiTranscription } from '@tanstack/ai-openai' const result = await generateTranscription({ adapter: openaiTranscription('whisper-1'), audio: audioFile, // File, Blob, or base64 string language: 'en' }) console.log(result.text) ``` ``` -------------------------------- ### Install ElevenLabs Adapter Source: https://github.com/tanstack/ai/blob/main/docs/adapters/elevenlabs.md Install the ElevenLabs adapter and its peer dependencies for TanStack AI. ```bash npm install @tanstack/ai-elevenlabs npm install @tanstack/ai @tanstack/ai-client ``` -------------------------------- ### Install Ollama Adapter Source: https://github.com/tanstack/ai/blob/main/docs/adapters/ollama.md Install the @tanstack/ai-ollama package using npm. ```bash npm install @tanstack/ai-ollama ``` -------------------------------- ### Start Ollama Server Source: https://github.com/tanstack/ai/blob/main/docs/adapters/ollama.md Start the Ollama server. It will run on `http://localhost:11434` by default. ```bash ollama serve ``` -------------------------------- ### Setup Analytics Tracking Middleware Source: https://github.com/tanstack/ai/blob/main/packages/ai/skills/ai-core/middleware/SKILL.md Example of setting up middleware for analytics tracking. It logs chat start, tracks analytics on finish, and reports errors. ```typescript import { chat, toServerSentEventsResponse } from '@tanstack/ai' import { openaiText } from '@tanstack/ai-openai' const stream = chat({ adapter: openaiText('gpt-5.2'), messages, middleware: [ { onStart: (ctx) => { console.log('Chat started:', ctx.model) }, onFinish: (ctx, info) => { trackAnalytics({ model: ctx.model, tokens: info.usage?.totalTokens }) }, onError: (ctx, info) => { reportError(info.error) }, }, ], }) return toServerSentEventsResponse(stream) ``` -------------------------------- ### Environment Variables Setup Source: https://github.com/tanstack/ai/blob/main/examples/README.md Copy the env.example file to .env and add your API keys for services like OpenAI and Anthropic. ```bash OPENAI_API_KEY=sk-... ANTHROPIC_API_KEY=sk-ant-... ``` -------------------------------- ### Transcription with Verbose JSON Response Source: https://github.com/tanstack/ai/blob/main/docs/reference/functions/generateTranscription.md This example demonstrates how to get a more detailed transcription response, including segments with start and end times, by setting the `responseFormat` to 'verbose_json'. ```typescript const result = await generateTranscription({ adapter: openaiTranscription('whisper-1'), audio: audioFile, responseFormat: 'verbose_json' }) result.segments?.forEach(segment => { console.log(`[${segment.start}s - ${segment.end}s]: ${segment.text}`) }) ``` -------------------------------- ### setup Source: https://github.com/tanstack/ai/blob/main/docs/reference/interfaces/ChatMiddleware.md Provisioning hook that runs first across all middleware in array order. Use it to call `provide` accessors so later middleware can consume capabilities. ```APIDOC ## setup() ### Description Provisioning hook. Runs FIRST — before `onConfig` (init) — across all middleware in array order. Use it to call `provide` accessors so later middleware (`onConfig` onward) can consume the capabilities. Receives the stable context; does NOT receive the mutable config. ### Parameters #### ctx [`ChatMiddlewareContext`](ChatMiddlewareContext.md) ### Returns `void` | `Promise` ``` -------------------------------- ### setup() Method Source: https://github.com/tanstack/ai/blob/main/docs/reference/interfaces/ChatMiddleware.md The provisioning hook that runs first, before `onConfig`. Use this to call `provide` accessors for capabilities that later middleware can consume. It receives the stable context and not the mutable config. ```typescript optional setup: (ctx) => void | Promise; ``` -------------------------------- ### Complete Example with Polling Loop Source: https://github.com/tanstack/ai/blob/main/docs/media/video-generation.md A comprehensive example demonstrating how to create a video job, poll for its completion, and retrieve the video URL. ```APIDOC ## Complete Example with Polling Loop ### Description This example shows the complete workflow: creating a video job, implementing a polling loop to check its status, and finally retrieving the video URL upon successful completion. ### Method Signature `createAndAwaitVideo(prompt: string, options?: { size?: string, duration?: number }): Promise ` ### Parameters - **prompt** (string) - Required - The text prompt describing the desired video. - **size** (string) - Optional - The desired video resolution (e.g., '1280x720'). - **duration** (number) - Optional - The desired video duration in seconds (4, 8, or 12). ### Request Example ```typescript import { generateVideo, getVideoJobStatus } from '@tanstack/ai' import { openaiVideo } from '@tanstack/ai-openai' async function createAndAwaitVideo(prompt: string, options?: { size?: string, duration?: number }): Promise { // 1. Create the job const { jobId } = await generateVideo({ adapter: openaiVideo('sora-2'), prompt, size: options?.size || '1280x720', duration: options?.duration || 8, }) console.log('Job created:', jobId) // 2. Poll for completion let status = 'pending'; while (status !== 'completed' && status !== 'failed') { // Wait 5 seconds between polls await new Promise((resolve) => setTimeout(resolve, 5000)); const result = await getVideoJobStatus({ adapter: openaiVideo('sora-2'), jobId, }); status = result.status; console.log(`Status: ${status}${result.progress ? ` (${result.progress}%)` : ''}`); if (result.status === 'failed') { throw new Error(result.error || 'Video generation failed'); } } // 3. Get the video URL const result = await getVideoJobStatus({ adapter: openaiVideo('sora-2'), jobId, }); if (result.status === 'completed' && result.url) { return result.url; } throw new Error('Video generation failed or URL not available'); } // Usage const videoUrl = await createAndAwaitVideo('A cat playing piano in a jazz bar', { duration: 4 }); console.log('Video ready:', videoUrl); ``` ``` -------------------------------- ### Install Core and OpenAI Packages Source: https://github.com/tanstack/ai/blob/main/README.md Install the core TanStack AI package along with the OpenAI provider. This is a common starting point for integrating OpenAI capabilities. ```bash pnpm add @tanstack/ai @tanstack/ai-openai ``` -------------------------------- ### Setup React Query Client and Provider Source: https://github.com/tanstack/ai/blob/main/examples/ts-react-search/README.md Initialize a QueryClient and wrap your application with QueryClientProvider in main.tsx. ```tsx import { QueryClient, QueryClientProvider } from '@tanstack/react-query' // ... const queryClient = new QueryClient() // ... if (!rootElement.innerHTML) { const root = ReactDOM.createRoot(rootElement) root.render( , ) } ``` -------------------------------- ### Install TSX and Add Server Dev Script Source: https://github.com/tanstack/ai/blob/main/docs/getting-started/quick-start-react-native.md Install the TSX package for running TypeScript files directly and add a script to your package.json to easily start the Hono server. ```bash pnpm add -D tsx pnpm pkg set scripts.dev:server="tsx server.ts" pnpm dev:server ``` -------------------------------- ### Backend Example: TanStack Start Chat API with Tools Source: https://github.com/tanstack/ai/blob/main/packages/ai-solid/README.md Implement a streaming chat API endpoint in TanStack Start that supports automatic tool execution using `@tanstack/ai` and `@tanstack/ai-anthropic`. ```typescript import { createFileRoute } from '@tanstack/react-router' import { chat, toServerSentEventsResponse } from '@tanstack/ai' import { anthropicText } from '@tanstack/ai-anthropic' export const Route = createFileRoute('/api/chat')({ server: { handlers: { POST: async ({ request }) => { const { messages } = await request.json() // One line with automatic tool execution! return toServerSentEventsResponse( chat({ adapter: anthropicText(), model: 'claude-sonnet-4-20250514', messages, tools, // Tools with execute functions }), ) }, }, }, }) ``` -------------------------------- ### Initialize QueryClient and Provider Source: https://github.com/tanstack/ai/blob/main/examples/ts-solid-chat/README.md Set up the QueryClient instance in your main entry file. ```tsx import { QueryClient, QueryClientProvider } from '@tanstack/solid-query' // ... const queryClient = new QueryClient() // ... ``` -------------------------------- ### Set Up Server Token Endpoint with TanStack Start Source: https://github.com/tanstack/ai/blob/main/docs/media/realtime-chat.md Generates short-lived tokens on the server to avoid exposing API keys to the client. Works with any server framework, example uses TanStack Start. ```typescript import { realtimeToken } from '@tanstack/ai' import { openaiRealtimeToken } from '@tanstack/ai-openai' import { createServerFn } from '@tanstack/react-start' const getRealtimeToken = createServerFn({ method: 'POST' }) .handler(async () => { return realtimeToken({ adapter: openaiRealtimeToken({ model: 'gpt-realtime', }), }) }) ``` -------------------------------- ### Start development server Source: https://github.com/tanstack/ai/blob/main/examples/ts-code-mode-web/README.md Launch the Vite development server on port 3001. ```bash pnpm dev # starts the Vite dev server on port 3001 ``` -------------------------------- ### Convert ArkType Schema to JSON Schema Source: https://github.com/tanstack/ai/blob/main/docs/reference/functions/convertSchemaToJsonSchema.md This example demonstrates converting an ArkType schema to a JSON Schema format usable by LLM providers. Ensure ArkType is installed. ```typescript import { type } from 'arktype'; const arkSchema = type({ location: 'string', unit: "'celsius' | 'fahrenheit'" }); const jsonSchema = convertSchemaToJsonSchema(arkSchema); ``` -------------------------------- ### Quick Start with Cloudflare Isolate Driver Source: https://github.com/tanstack/ai/blob/main/packages/ai-isolate-cloudflare/README.md Integrate the Cloudflare isolate driver into your TanStack AI setup. Ensure your `yourTextAdapter` is defined and replace `'http://localhost:8787'` with your actual worker URL. ```typescript import { chat, toolDefinition } from '@tanstack/ai' import { createCodeMode } from '@tanstack/ai-code-mode' import { createCloudflareIsolateDriver } from '@tanstack/ai-isolate-cloudflare' import { z } from 'zod' const fetchWeather = toolDefinition({ name: 'fetchWeather', description: 'Get weather for a city', inputSchema: z.object({ location: z.string() }), outputSchema: z.object({ temperature: z.number(), condition: z.string(), }), }).server(async ({ location }) => { return { temperature: 72, condition: `sunny in ${location}` } }) const driver = createCloudflareIsolateDriver({ workerUrl: 'http://localhost:8787', // local dev server URL authorization: 'Bearer your-secret-token', // optional }) const { tool, systemPrompt } = createCodeMode({ driver, tools: [fetchWeather], timeout: 30_000, }) const result = await chat({ adapter: yourTextAdapter, model: 'gpt-4o-mini', systemPrompts: ['You are a helpful assistant.', systemPrompt], tools: [tool], messages: [{ role: 'user', content: 'Compare weather in Tokyo and Paris' }], }) ``` -------------------------------- ### Install and Run Stream Processor Test Panel Source: https://github.com/tanstack/ai/blob/main/testing/panel/README.md Instructions for installing dependencies and running the test panel locally. Ensure you are in the workspace root before running. ```bash pnpm install cd testing/panel pnpm dev ``` -------------------------------- ### Set Up AI Provider API Keys Source: https://github.com/tanstack/ai/blob/main/docs/getting-started/quick-start.md Configure your API keys in a `.env.local` file to connect to various AI providers like OpenRouter, OpenAI, Anthropic, and Google Gemini. ```bash # OpenRouter (recommended — access 300+ models with one key) OPENROUTER_API_KEY=sk-or-... # OpenAI OPENAI_API_KEY=your-openai-api-key # Anthropic ANTHROPIC_API_KEY=your-anthropic-api-key # Google Gemini GEMINI_API_KEY=your-gemini-api-key ``` -------------------------------- ### Full Server + Client Example for MCP Integration Source: https://github.com/tanstack/ai/blob/main/docs/tools/mcp-manual.md A complete TanStack Start API route that connects to two MCP servers and streams the response to the browser, along with a client component to interact with the API. ```typescript import { createFileRoute } from '@tanstack/react-router' import { chat, toServerSentEventsResponse } from '@tanstack/ai' import { openaiText } from '@tanstack/ai-openai' import { createMCPClients } from '@tanstack/ai-mcp' export const Route = createFileRoute('/api/chat')({ server: { handlers: { POST: async ({ request }) => { const body = await request.json() if (typeof body !== 'object' || body === null || !Array.isArray(body.messages)) { return new Response('Bad request', { status: 400 }) } const pool = await createMCPClients({ github: { transport: { type: 'http', url: process.env.GITHUB_MCP_URL!, headers: { Authorization: `Bearer ${process.env.GITHUB_MCP_TOKEN}` }, }, }, linear: { transport: { type: 'http', url: process.env.LINEAR_MCP_URL!, headers: { Authorization: `Bearer ${process.env.LINEAR_MCP_TOKEN}` }, }, }, }) const stream = chat({ adapter: openaiText('gpt-5.5'), messages: body.messages, tools: await pool.tools(), // Close after the run ends — tools execute while the response streams. middleware: [ { name: 'mcp-close', onFinish: () => pool.close(), onAbort: () => pool.close(), onError: () => pool.close(), }, ], }) return toServerSentEventsResponse(stream) }, }, }, }) ``` ```tsx import { useChat } from '@tanstack/ai-react' import { fetchServerSentEvents } from '@tanstack/ai-client' const chatOptions = { connection: fetchServerSentEvents('/api/chat'), } export function Chat() { const { messages, sendMessage, status } = useChat(chatOptions) return (
    {messages.map((m) => (
  • {m.role}:{' '} {m.parts.find((p) => p.type === 'text')?.content}
  • ))}
) } ``` -------------------------------- ### Define Server Tool: Get User Data Source: https://github.com/tanstack/ai/blob/main/docs/tools/server-tools.md Defines a server tool to retrieve user information from a database. This example shows the basic structure for defining a tool's schema and its server-side implementation. ```typescript import { toolDefinition } from "@tanstack/ai"; import { z } from "zod"; import { db } from "./db"; const getUserDataDef = toolDefinition({ name: "get_user_data", description: "Get user information from the database", inputSchema: z.object({ userId: z.string().meta({ description: "The user ID to look up" }), }), outputSchema: z.object({ name: z.string(), email: z.string().email(), createdAt: z.string(), }), }); const getUserData = getUserDataDef.server(async ({ userId }) => { // This runs on the server - secure access to database const user = await db.users.findUnique({ where: { id: userId } }); return { name: user.name, email: user.email, createdAt: user.createdAt.toISOString(), }; }); ``` -------------------------------- ### Example with Tools Source: https://github.com/tanstack/ai/blob/main/docs/adapters/openai.md Demonstrates integrating tools with the OpenAI adapter for advanced chat functionalities. Requires zod for schema definition and server-side tool implementation. ```typescript import { chat, toServerSentEventsResponse, 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" }; }); export async function POST(request: Request) { const { messages } = await request.json(); const stream = chat({ adapter: openaiText("gpt-5.2"), messages, tools: [getWeather], }); return toServerSentEventsResponse(stream); } ``` -------------------------------- ### Client Hook for Direct Transcription Fetcher Source: https://github.com/tanstack/ai/blob/main/docs/media/transcription.md Utilizes the `useTranscription` hook with a custom fetcher function that calls a TanStack Start server function for direct, non-streaming transcription. The UI component remains the same as the streaming example. ```tsx import { useTranscription } from '@tanstack/ai-react' import { transcribeFn } from '../lib/server-functions' function AudioTranscriber() { const { generate, result, isLoading } = useTranscription({ fetcher: (input) => transcribeFn({ data: input }), }) // ... same UI as above } ``` -------------------------------- ### Chat Completion with Tools using OpenRouter Source: https://github.com/tanstack/ai/blob/main/docs/adapters/openrouter.md This example demonstrates how to enable tool usage for chat completions with OpenRouter. Define your tools using `toolDefinition` and pass them to the `chat` function. Ensure zod is installed for schema validation. ```typescript import { chat, toServerSentEventsResponse, toolDefinition } from "@tanstack/ai"; import { openRouterText } from "@tanstack/ai-openrouter"; 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 }) => { return { temperature: 72, conditions: "sunny" }; }); export async function POST(request: Request) { const { messages } = await request.json(); const stream = chat({ adapter: openRouterText("openai/gpt-5"), messages, tools: [getWeather], }); return toServerSentEventsResponse(stream); } ``` -------------------------------- ### Complete Example with Polling Source: https://github.com/tanstack/ai/blob/main/docs/community-adapters/decart.md A comprehensive example demonstrating the creation of a video generation job and subsequent polling for its completion status, including error handling for failed jobs. ```APIDOC ## Complete Example with Polling A comprehensive example demonstrating the creation of a video generation job and subsequent polling for its completion status, including error handling for failed jobs. ```typescript import { generateVideo, getVideoJobStatus } from "@tanstack/ai"; import { decartVideo } from "@decartai/tanstack-ai-adapter"; async function createVideo(prompt: string) { const adapter = decartVideo("lucy-pro-t2v"); // Create the job const { jobId } = await generateVideo({ adapter, prompt }); console.log("Job created:", jobId); // Poll for completion let status = "pending"; while (status !== "completed" && status !== "failed") { await new Promise((resolve) => setTimeout(resolve, 5000)); const result = await getVideoJobStatus({ adapter, jobId }); status = result.status; console.log(`Status: ${status}`); if (result.status === "failed") { throw new Error("Video generation failed"); } if (result.status === "completed" && result.url) { return result.url; } } } const videoUrl = await createVideo("A drone shot over a tropical beach"); ``` ``` -------------------------------- ### Get Video Job Status Example Source: https://github.com/tanstack/ai/blob/main/docs/reference/functions/getVideoJobStatus.md Demonstrates how to use the getVideoJobStatus function to check the status of a video generation job. It logs the status, progress, and video URL if available. Ensure you have the necessary adapter and job ID. ```typescript import { getVideoJobStatus } from '@tanstack/ai' import { openaiVideo } from '@tanstack/ai-openai' const result = await getVideoJobStatus({ adapter: openaiVideo('sora-2'), jobId: 'job-123' }) console.log('Status:', result.status) console.log('Progress:', result.progress) if (result.url) { console.log('Video URL:', result.url) } ``` -------------------------------- ### Stream Chat and Convert to Text Source: https://github.com/tanstack/ai/blob/main/docs/reference/functions/streamToText.md This example demonstrates how to use the chat function to get a stream of responses and then use streamToText to convert the entire stream into a single string. Ensure you have the necessary adapters like openaiText() configured. ```typescript const stream = chat({ adapter: openaiText(), model: 'gpt-4o', messages: [{ role: 'user', content: 'Hello!' }] }); const text = await streamToText(stream); console.log(text); // "Hello! How can I help you today?" ``` -------------------------------- ### Using chatParamsFromRequest in a POST Handler (Frameworks with Auto-Response Handling) Source: https://github.com/tanstack/ai/blob/main/docs/reference/functions/chatParamsFromRequest.md Example of how to use chatParamsFromRequest within a POST request handler in frameworks that automatically handle thrown Response objects, such as TanStack Start, SolidStart, Remix, or React Router 7. ```typescript export async function POST(req: Request) { const params = await chatParamsFromRequest(req) // ...use params } ``` -------------------------------- ### Base Generation Composable Setup Source: https://github.com/tanstack/ai/blob/main/docs/api/ai-vue.md Demonstrates the setup for the base `useGeneration` composable, which is the foundation for all specialized generation composables. It shows how to import the composable and initialize it with a connection. ```typescript import { useGeneration } from "@tanstack/ai-vue"; import { fetchServerSentEvents } from "@tanstack/ai-client"; const { generate, result, isLoading, error, status, stop, reset } = useGeneration({ connection: fetchServerSentEvents("/api/generate/custom"), }); ``` -------------------------------- ### Complete Example with Eager and Lazy Tools Source: https://github.com/tanstack/ai/blob/main/docs/tools/lazy-tool-discovery.md This snippet demonstrates how to define and use both eager (always available) and lazy (discovered on demand) tools within a TanStack AI chat application. It includes tool definitions, server-side implementations, and the chat setup for handling user messages. ```typescript import { toolDefinition, chat, toServerSentEventsResponse, maxIterations } from "@tanstack/ai"; import { openaiText } from "@tanstack/ai-openai"; import { z } from "zod"; import { db } from "./db"; // Eager tool — always available const getProductsDef = toolDefinition({ name: "getProducts", description: "Get all products from the catalog", inputSchema: z.object({}), outputSchema: z.array( z.object({ id: z.number(), name: z.string(), price: z.number(), }) ), }); const getProducts = getProductsDef.server(async () => { return await db.products.findMany(); }); // Lazy tool — discovered on demand const compareProductsDef = toolDefinition({ name: "compareProducts", description: "Compare two or more products side by side", inputSchema: z.object({ productIds: z.array(z.number()).min(2), }), lazy: true, }); const compareProducts = compareProductsDef.server(async ({ productIds }) => { const products = await db.products.findMany({ where: { id: { in: productIds } }, }); return { products }; }); // Lazy tool — discovered on demand const calculateFinancingDef = toolDefinition({ name: "calculateFinancing", description: "Calculate monthly payment plans for a product", inputSchema: z.object({ productId: z.number(), months: z.number(), }), lazy: true, }); const calculateFinancing = calculateFinancingDef.server(async ({ productId, months }) => { const product = await db.products.findUnique({ where: { id: productId } }); const monthlyPayment = product.price / months; return { monthlyPayment, totalPrice: product.price, months }; }); // Use in chat export async function POST(request: Request) { const { messages } = await request.json(); const stream = chat({ adapter: openaiText("gpt-5.5"), messages, tools: [getProducts, compareProducts, calculateFinancing], agentLoopStrategy: maxIterations(20), }); return toServerSentEventsResponse(stream); } ``` -------------------------------- ### Initialize Fal.ai Video Adapter Source: https://github.com/tanstack/ai/blob/main/docs/adapters/fal.md Creates a Fal.ai video adapter instance. Use the FAL_KEY environment variable or provide an explicit apiKey in the config. The proxyUrl is optional and useful for client-side usage. ```javascript import { falVideo } from "@fal-ai/serverless-ai-adapter"; const videoAdapter = falVideo("fal-ai/kling-video/v2.6/pro/text-to-video", { apiKey: "your-fal-api-key", proxyUrl: "http://localhost:3000/api" }); ``` -------------------------------- ### TanStack AI: Mid-loop Model Switching Example Source: https://github.com/tanstack/ai/blob/main/docs/migration/migration-from-vercel-ai.md Demonstrates mid-loop model switching in TanStack AI by ending one chat run and starting a new one with a different adapter. This is the TanStack AI equivalent of Vercel AI SDK v6's `prepareStep` returning a different model. ```typescript import { chat, maxIterations } from '@tanstack/ai' import { openaiText } from '@tanstack/ai-openai' import { getWeather } from './tools' const messages = [{ role: 'user' as const, content: 'Hello' }] // Stage 1: heavy model for the opening turn const firstPass = await chat({ adapter: openaiText('gpt-4o'), messages, agentLoopStrategy: maxIterations(1), stream: false, }) // Stage 2: cheaper model for the rest const followUp = chat({ adapter: openaiText('gpt-4o-mini'), messages: [...messages, { role: 'assistant' as const, content: firstPass }], tools: [getWeather], }) ``` -------------------------------- ### startRecording() Source: https://github.com/tanstack/ai/blob/main/docs/reference/classes/StreamProcessor.md Initiates the recording of chunks. ```APIDOC ## startRecording() ### Description Start recording chunks ### Returns `void` ``` -------------------------------- ### Install TanStack AI packages Source: https://github.com/tanstack/ai/blob/main/docs/getting-started/agent-skills.md Install the core TanStack AI library and necessary adapter packages. ```bash pnpm add @tanstack/ai @tanstack/ai-openai ``` -------------------------------- ### Install Dependencies with pnpm Source: https://github.com/tanstack/ai/blob/main/examples/ts-vue-chat/README.md Installs project dependencies using pnpm. Ensure pnpm is installed and the project's package.json is set up correctly. ```bash pnpm install ``` -------------------------------- ### Compare Guitars Prompt Source: https://github.com/tanstack/ai/blob/main/examples/ts-react-chat/README.md Example prompt to trigger the 'compareGuitars' lazy tool discovery. ```text Can you compare the Motherboard Guitar and the Racing Guitar for me? ``` -------------------------------- ### Configure AI Client with ImmediateStrategy Source: https://github.com/tanstack/ai/blob/main/docs/api/ai-client.md This snippet shows how to initialize the ChatClient with a connection and configure it to use the ImmediateStrategy, which emits every chunk as it arrives. ```typescript import { ChatClient, ImmediateStrategy, fetchServerSentEvents, } from "@tanstack/ai-client"; const client = new ChatClient({ connection: fetchServerSentEvents("/api/chat"), streamProcessor: { chunkStrategy: new ImmediateStrategy(), // Emit every chunk }, }); ```