Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

README.md

504 lines12.5 KB

1# TanStack AI Examples
2​
3This directory contains comprehensive examples demonstrating TanStack AI across multiple TypeScript frameworks.
4​
5## Quick Start
6​
7Choose an example based on your use case:
8​
9- **Want the smallest React + Start chat?** → [Basic Chat](#basic-chat)
10- **Want an image from a prompt?** → [Generate Image](#generate-image)
11- **Want a table that fills as JSON streams?** → [Streaming Structured Table](#streaming-structured-table)
12- **Want typed ticket routing?** → [Evaluate](#evaluate)
13- **Want a blog desk with three agents?** → [Subagents](#subagents)
14- **Want your own MCP server?** → [MCP server](#mcp-server)
15- **Want the model to use a web page?** → [Computer Use](#computer-use)
16- **Want a full-stack TypeScript app?** → [TanStack Chat (ts-react-chat)](#tanstack-chat-ts-react-chat)
17- **Need a live world stream?** → [World generation (ts-react-media)](#world-generation-ts-react-media)
18- **Need a vanilla JS frontend?** → [Vanilla Chat](#vanilla-chat)
19- **Multi-User TypeScript chat app?** → [Group Chat (ts-group-chat)](#group-chat-ts-group-chat)
20- **Polyglot AG-UI backends (Go/Rust/PHP/Zig/Bash/Python)?** → [AG-UI Polyglot Echo (ag-ui)](#ag-ui-polyglot-echo-ag-ui)
21​
22## TypeScript Examples
23​
24### Basic Chat
25​
26A slim TanStack Start chat. One provider (OpenRouter). You paste your own key.
27​
28**Path:** `examples/react/basic-chat`
29​
30**Getting Started:**
31​
32```bash
33pnpm --filter basic-chat dev
34```
35​
36Open http://localhost:3100. Paste an OpenRouter key. Send a message.
37​
38📖 [Full Documentation](react/basic-chat/README.md)
39​
40---
41​
42### Generate Image
43​
44A slim TanStack Start image app. One provider (OpenRouter). You paste your own key.
45​
46**Path:** `examples/react/generate-image`
47​
48**Getting Started:**
49​
50```bash
51pnpm --filter generate-image dev
52```
53​
54Open http://localhost:3100. Paste an OpenRouter key. Type a prompt. Click Generate.
55​
56📖 [Full Documentation](react/generate-image/README.md)
57​
58---
59​
60### Streaming Structured Table
61​
62A slim TanStack Start app. One schema. `chat({ outputSchema, stream: true })` fills a table as JSON streams in.
63​
64**Path:** `examples/react/streaming-structured-table`
65​
66**Getting Started:**
67​
68```bash
69pnpm --filter streaming-structured-table dev
70```
71​
72Open http://localhost:3100. Paste an OpenRouter key. Send `Compare 6 JavaScript frameworks`.
73​
74📖 [Full Documentation](react/streaming-structured-table/README.md)
75​
76---
77​
78### Subagents
79​
80A slim TanStack Start chat. Three named agents: researcher, SEO, and writer. Jev picks the agents for each turn. Research and SEO run together, and the writer runs after them. The UI shows a nested card for each.
81​
82**Path:** `examples/react/subagents`
83​
84**Getting Started:**
85​
86```bash
87pnpm --filter subagents dev
88```
89​
90Open http://localhost:3100. Paste an OpenRouter key. Ask for research, SEO titles, or a draft.
91​
92📖 [Full Documentation](react/subagents/README.md)
93​
94---
95​
96### Persisted subagents
97​
98The blog desk from the subagents example, with a saved chat. A refresh keeps the messages and the cards. A refresh during a run continues that run.
99​
100**Path:** `examples/react/subagents-persisted`
101​
102**Getting Started:**
103​
104```bash
105pnpm --filter subagents-persisted dev
106```
107​
108Open http://localhost:3105. Paste an OpenRouter key. Send a prompt. Then refresh the page.
109​
110📖 [Full Documentation](react/subagents-persisted/README.md)
111​
112---
113​
114### Evaluate
115​
116A slim TanStack Start app. Paste a support ticket. The app shows queue, urgency, and refund.
117​
118**Path:** `examples/react/evaluate`
119​
120**Getting Started:**
121​
122```bash
123pnpm --filter evaluate dev
124```
125​
126Open http://localhost:3100. For a hosted provider, add its key in `.env`. For Ollaya, run `ollaya serve` and `ollaya pull laya:latest`. Pick a provider. Click Submit.
127​
128📖 [Full Documentation](react/evaluate/README.md)
129​
130---
131​
132### MCP server
133​
134A slim TanStack Start app. One tool, one resource, and one prompt. The page calls that server.
135​
136**Path:** `examples/react/mcp-server`
137​
138**Getting Started:**
139​
140```bash
141pnpm --filter mcp-server dev
142```
143​
144Open http://localhost:3100. Click Call the server.
145​
146📖 [Full Documentation](react/mcp-server/README.md)
147​
148---
149​
150### Computer Use
151​
152A slim TanStack Start app. The model opens tanstack.com in Chromium and finds the computer use docs. One provider (OpenAI). Each screenshot shows in the chat.
153​
154**Path:** `examples/react/computer-use`
155​
156**Getting Started:**
157​
158```bash
159pnpm --filter computer-use exec playwright-core install chromium
160pnpm --filter computer-use dev
161```
162​
163Set `OPENAI_API_KEY` in `.env.local`. Open http://localhost:3100. Click Send.
164​
165📖 [Full Documentation](react/computer-use/README.md)
166​
167---
168​
169### TanStack Chat (ts-react-chat)
170​
171A full-featured chat application built with the TanStack ecosystem.
172​
173**Tech Stack:**
174​
175- TanStack Start (full-stack React framework)
176- TanStack Router (type-safe routing)
177- TanStack Store (state management)
178- `@tanstack/ai` (AI backend)
179- `@tanstack/ai-react` (React hooks)
180- `@tanstack/ai-client` (headless client)
181​
182**Features:**
183​
184- ✅ Real-time streaming with OpenAI GPT-4o
185- ✅ Automatic tool execution loop
186- ✅ Rich markdown rendering
187- ✅ Conversation management
188- ✅ Modern UI with Tailwind CSS
189​
190**Getting Started:**
191​
192```bash
193cd examples/ts-react-chat
194pnpm install
195cp env.example .env
196# Edit .env and add your OPENAI_API_KEY
197pnpm start
198```
199​
200📖 [Full Documentation](ts-react-chat/README.md)
201​
202---
203​
204### Group Chat (ts-group-chat)
205​
206A real-time multi-user chat application with AI integration, demonstrating WebSocket-based communication and TanStack AI.
207​
208**Tech Stack:**
209​
210- TanStack Start (full-stack React framework)
211- TanStack Router (type-safe routing)
212- Cap'n Web RPC (bidirectional WebSocket RPC)
213- `@tanstack/ai` (AI backend)
214- `@tanstack/ai-anthropic` (Claude adapter)
215- `@tanstack/ai-client` (headless client)
216- `@tanstack/ai-react` (React hooks)
217​
218**Features:**
219​
220- ✅ Real-time multi-user chat with WebSocket
221- ✅ Online presence tracking
222- ✅ AI assistant (Claude) integration with queuing
223- ✅ Message broadcasting to all users
224- ✅ Modern chat UI (iMessage-style)
225- ✅ Username-based authentication (no registration)
226​
227**Getting Started:**
228​
229```bash
230cd examples/ts-group-chat
231pnpm install
232cp .env.example .env
233# Edit .env and add your ANTHROPIC_API_KEY
234pnpm dev
235```
236​
237Open `http://localhost:4000` in multiple browser tabs to test multi-user functionality.
238​
239**Key Concepts:**
240​
241- **WebSocket RPC**: Uses Cap'n Web RPC for type-safe bidirectional communication
242- **AI Queuing**: Claude requests are queued and processed sequentially
243- **Real-time Updates**: Messages and online users update in real-time
244- **Message Broadcasting**: Server broadcasts messages to all connected clients
245​
246📖 [Full Documentation](ts-group-chat/README.md)
247​
248---
249​
250### Reranking (ts-react-rerank)
251​
252A single-page app that reorders a fixed set of support articles by relevance to
253a query, showing the original order and the reranked order side by side.
254​
255**Tech Stack:**
256​
257- TanStack Start (full-stack React framework)
258- `@tanstack/ai` (the `rerank()` activity)
259- `@tanstack/ai-cohere` (Cohere rerank adapter)
260- `@tanstack/ai-openrouter` (OpenRouter rerank adapter)
261​
262**Features:**
263​
264- ✅ One `rerank()` call, two providers behind a dropdown
265- ✅ Object documents — the original typed object comes back on each result
266- ✅ Relevance scores and original position per document
267- ✅ `topN` control and search-unit usage reporting
268- ✅ API keys stay on the server
269​
270**Getting Started:**
271​
272```bash
273cd examples/ts-react-rerank
274pnpm install
275cp .env.example .env
276# Add COHERE_API_KEY and/or OPENROUTER_API_KEY — you only need the one you pick
277pnpm dev
278```
279​
280📖 [Full Documentation](ts-react-rerank/README.md)
281​
282---
283​
284### World generation (ts-react-media)
285​
286The media example has a **World** tab. Pick a Reactor model for a live
287steerable stream, or a Marble model for a finished 3D World Labs world.
288​
289```bash
290cd examples/ts-react-media
291pnpm install
292pnpm dev
293```
294​
295Open the World tab. Paste a Reactor key (`REACTOR_API_KEY`) or a World Labs
296key (`WORLDLABS_API_KEY`).
297​
298---
299​
300### Vanilla Chat
301​
302A framework-free chat application using pure JavaScript and `@tanstack/ai-client`.
303​
304**Tech Stack:**
305​
306- Vanilla JavaScript (no frameworks!)
307- `@tanstack/ai-client` (headless client)
308- Vite (dev server)
309​
310**Features:**
311​
312- ✅ Pure vanilla JavaScript
313- ✅ Real-time streaming messages
314- ✅ Beautiful, responsive UI
315- ✅ No framework dependencies
316​
317**Getting Started:**
318​
319```bash
320cd examples/vanilla-chat
321pnpm install
322pnpm start
323```
324​
325📖 [Full Documentation](vanilla-chat/README.md)
326​
327---
328​
329### AG-UI Polyglot Echo (ag-ui)
330​
331A React SPA that connects to **Go, Rust, PHP, Zig, Bash, and Python chat servers** over the AG-UI SSE protocol, with each backend streaming OpenAI or Anthropic completions. Toolchain detection writes `public/servers.json`; unavailable backends show setup instructions in the UI.
332​
333**Tech Stack:**
334​
335- React + Vite (SPA)
336- `@tanstack/ai-react` + `@tanstack/ai-react/ui`
337- Go chat server (`net/http`, `:8001`)
338- Rust chat server (Axum, `:8002`)
339- PHP chat server (built-in server + curl, `:8003`)
340- Zig chat server (stdlib HTTP, `:8004`)
341- Bash chat server (socat + curl + jq, `:8005`)
342- Python chat server (stdlib HTTP + urllib, `:8006`)
343​
344**Features:**
345​
346- ✅ Backend picker (Go | Rust | PHP | Zig | Bash | Python)
347- ✅ Toolchain-gated `dev:all` + `servers.json` availability
348- ✅ Setup instructions when a runtime is missing (or disabled via `AGUI_DISABLE_SERVERS`)
349- ✅ Provider picker (OpenAI | Anthropic)
350- ✅ Hand-rolled AG-UI SSE in six languages
351- ✅ Streaming LLM responses via env API keys
352​
353**Getting Started:**
354​
355```bash
356cd examples/ag-ui
357pnpm install
358cp .env.example .env
359pnpm dev:all
360```
361​
362Install whichever backends you want to run locally (Go, Rust, PHP, Zig, Bash, Python) plus provider API keys. The Bash server uses Bash 4+, curl, jq, and socat (`brew install bash jq socat`). To simulate missing runtimes: `AGUI_DISABLE_SERVERS=php,zig,bash,python pnpm dev:all`.
363​
364📖 [Full Documentation](ag-ui/README.md)
365​
366---
367​
368## Architecture Patterns
369​
370### Full-Stack TypeScript
371​
372Use TanStack AI end-to-end in TypeScript:
373​
374```
375Frontend (React)
376 ↓ (useChat hook)
377@tanstack/ai-react
378 ↓ (ChatClient)
379@tanstack/ai-client
380 ↓ (SSE/HTTP)
381Backend (TanStack Start API Route)
382 ↓ (chat() function)
383@tanstack/ai
384 ↓ (adapter)
385AI Provider (OpenAI/Anthropic/etc.)
386```
387​
388**Example:** [TanStack Chat (ts-react-chat)](ts-react-chat/README.md)
389​
390## Common Patterns
391​
392### Server-Sent Events (SSE) Streaming
393​
394All examples use SSE for real-time streaming:
395​
396**Backend:**
397​
398```typescript
399import { chat, toServerSentEventsResponse } from '@tanstack/ai'
400import { openaiText } from '@tanstack/ai-openai'
401​
402const stream = chat({
403 adapter: openaiText(),
404 model: 'gpt-4o',
405 messages,
406})
407​
408return toServerSentEventsResponse(stream)
409```
410​
411**Frontend:**
412​
413```typescript
414import { ChatClient, fetchServerSentEvents } from '@tanstack/ai-client'
415​
416const client = new ChatClient({
417 connection: fetchServerSentEvents('/api/chat'),
418})
419```
420​
421### Automatic Tool Execution
422​
423The TypeScript backend (`@tanstack/ai`) automatically handles tool execution:
424​
425```typescript
426import { chat, toolDefinition } from '@tanstack/ai'
427import { z } from 'zod'
428​
429// Step 1: Define the tool schema
430const weatherToolDef = toolDefinition({
431 name: 'getWeather',
432 description: 'Get weather for a location',
433 inputSchema: z.object({
434 location: z.string().describe('The city and state, e.g. San Francisco, CA'),
435 }),
436 outputSchema: z.object({
437 temp: z.number(),
438 condition: z.string(),
439 }),
440})
441​
442// Step 2: Create server implementation
443const weatherTool = weatherToolDef.server(async ({ location }) => {
444 // This is called automatically by the SDK
445 return { temp: 72, condition: 'sunny' }
446})
447​
448const stream = chat({
449 adapter: openaiText(),
450 model: 'gpt-4o',
451 messages,
452 tools: [weatherTool], // SDK executes these automatically
453})
454```
455​
456Clients receive:
457​
458- `content` chunks - text from the model
459- `tool_call` chunks - when the model calls a tool
460- `tool_result` chunks - results from tool execution
461- `done` chunk - conversation complete
462​
463---
464​
465## Development Tips
466​
467### Environment Variables
468​
469Each example has an `env.example` file. Copy it to `.env` and add your API keys:
470​
471```bash
472OPENAI_API_KEY=sk-...
473ANTHROPIC_API_KEY=sk-ant-...
474```
475​
476### Building for Production
477​
478```bash
479pnpm build
480```
481​
482---
483​
484## Contributing
485​
486When adding new examples:
487​
4881. **Create a README.md** with setup instructions
4892. **Add an env.example** file with required environment variables
4903. **Document the tech stack** and key features
4914. **Include usage examples** with code snippets
4925. **Update this README** to list your example
493​
494---
495​
496## Learn More
497​
498- 📖 [Main README](../README.md) - Project overview
499- 📖 [Documentation](../docs/) - Comprehensive guides
500- 📖 [TypeScript Packages](../packages/) - Core libraries
501​
502---
503​
504Built with ❤️ by the TanStack community