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

README.md

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