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

README.md

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