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

README.md

497 lines16.2 KB

1Welcome to your new TanStack app!
2​
3# Getting Started
4​
5To run this application:
6​
7```bash
8pnpm install
9pnpm dev
10```
11​
12# Building For Production
13​
14To build this application for production:
15​
16```bash
17pnpm build
18```
19​
20## Testing
21​
22This project uses [Vitest](https://vitest.dev/) for testing. You can run the tests with:
23​
24```bash
25pnpm test
26```
27​
28## Styling
29​
30This project uses [Tailwind CSS](https://tailwindcss.com/) for styling.
31​
32# TanStack Chat Application
33​
34An example chat application built with TanStack Start, TanStack Store, and **TanStack AI** (our open-source AI SDK).
35​
36## .env Updates
37​
38```env
39OPENAI_API_KEY=your_openai_api_key
40```
41​
42## Trying Out Lazy Tool Discovery
43​
44This example includes three **lazy tools** — tools that are not sent to the LLM upfront. Instead, the LLM sees a `__lazy__tool__discovery__` tool that lists their names. When the LLM needs one, it discovers it first (getting the full description and schema), then calls it normally.
45​
46The lazy tools are: `compareGuitars`, `calculateFinancing`, and `searchGuitars`.
47​
48### Test Prompts
49​
50**Compare guitars** — triggers discovery of `compareGuitars`:
51​
52> "Can you compare the Motherboard Guitar and the Racing Guitar for me?"
53​
54**Financing** — triggers discovery of `calculateFinancing`:
55​
56> "How much would it cost per month if I financed the Superhero Guitar over 12 months?"
57​
58**Search** — triggers discovery of `searchGuitars`:
59​
60> "Do you have any guitars with LED lights or tech features?"
61​
62**Multi-discovery** — triggers discovery of multiple lazy tools at once:
63​
64> "I'm looking for acoustic guitars. Can you search for them, then compare the ones you find, and show me financing options for the cheapest one?"
65​
66**Self-correction** — the LLM may try calling a lazy tool directly without discovering it first. It will get an error telling it to discover first, then self-correct:
67​
68> "Compare guitar 1 and guitar 4 right now"
69​
70### What to watch for
71​
72- The LLM calls `__lazy__tool__discovery__` before using a lazy tool for the first time
73- After discovery, the tool is called directly like any normal tool
74- In multi-turn conversations, previously discovered tools are usable immediately without re-discovery
75- If the LLM skips discovery, it gets an error and self-corrects
76​
77## Generic interrupt playground
78​
79Open `/generic-interrupts` to try first-party generic interrupts at each
80lifecycle phase:
81​
82- `beforeModel`
83- `afterModel`
84- `beforeTools`
85- `afterTools`
86​
87Pick a resume policy (`continue`, `cancel`, or `stop`). Each pause shows two
88typed cards (`reviewPlan` and `chooseAudience`). Resolve both, then watch the
89selected policy.
90​
91## ✨ Features
92​
93### AI Capabilities
94​
95- 🤖 Powered by **TanStack AI** with OpenAI GPT-4o
96- 📝 Rich markdown formatting with syntax highlighting
97- 🎯 Customizable system prompts for tailored AI behavior
98- 🔄 Real-time streaming responses with Server-Sent Events
99- 🔌 **Connection adapters** - flexible streaming architecture
100- 🛠️ **Automatic tool execution loop** - tools are executed automatically by the SDK
101- 🎸 Tool/function calling with guitar recommendations
102​
103### User Experience
104​
105- 🎨 Modern UI with Tailwind CSS and Lucide icons
106- 🔍 Conversation management and history
107- 🔐 Secure API key management
108- 📋 Markdown rendering with code highlighting
109​
110### Technical Features
111​
112- 📦 Centralized state management with TanStack Store
113- 🔌 Extensible architecture for multiple AI providers
114- 🛠️ TypeScript for type safety
115​
116## Architecture
117​
118### Tech Stack
119​
120- **Frontend Framework**: TanStack Start
121- **Routing**: TanStack Router
122- **State Management**: TanStack Store
123- **Styling**: Tailwind CSS
124- **AI Integration**: TanStack AI with OpenAI GPT-4o
125- **Chat Client**: `@tanstack/ai-react` with connection adapters
126- **Streaming**: Server-Sent Events via `fetchServerSentEvents`
127- **Tool Execution**: Automatic loop with `ToolCallManager`
128​
129## Routing
130​
131This project uses [TanStack Router](https://tanstack.com/router). The initial setup is a file based router. Which means that the routes are managed as files in `src/routes`.
132​
133### Adding A Route
134​
135To add a new route to your application just add another a new file in the `./src/routes` directory.
136​
137TanStack will automatically generate the content of the route file for you.
138​
139Now that you have two routes you can use a `Link` component to navigate between them.
140​
141### Adding Links
142​
143To use SPA (Single Page Application) navigation you will need to import the `Link` component from `@tanstack/react-router`.
144​
145```tsx
146import { Link } from '@tanstack/react-router'
147```
148​
149Then anywhere in your JSX you can use it like so:
150​
151```tsx
152<Link to="/about">About</Link>
153```
154​
155This will create a link that will navigate to the `/about` route.
156​
157More information on the `Link` component can be found in the [Link documentation](https://tanstack.com/router/v1/docs/framework/react/api/router/linkComponent).
158​
159### Using A Layout
160​
161In the File Based Routing setup the layout is located in `src/routes/__root.tsx`. Anything you add to the root route will appear in all the routes. The route content will appear in the JSX where you use the `<Outlet />` component.
162​
163Here is an example layout that includes a header:
164​
165```tsx
166import { Outlet, createRootRoute } from '@tanstack/react-router'
167import { TanStackRouterDevtools } from '@tanstack/react-router-devtools'
168​
169import { Link } from '@tanstack/react-router'
170​
171export const Route = createRootRoute({
172 component: () => (
173 <>
174 <header>
175 <nav>
176 <Link to="/">Home</Link>
177 <Link to="/about">About</Link>
178 </nav>
179 </header>
180 <Outlet />
181 <TanStackRouterDevtools />
182 </>
183 ),
184})
185```
186​
187The `<TanStackRouterDevtools />` component is not required so you can remove it if you don't want it in your layout.
188​
189More information on layouts can be found in the [Layouts documentation](https://tanstack.com/router/latest/docs/framework/react/guide/routing-concepts#layouts).
190​
191## Data Fetching
192​
193There are multiple ways to fetch data in your application. You can use TanStack Query to fetch data from a server. But you can also use the `loader` functionality built into TanStack Router to load the data for a route before it's rendered.
194​
195For example:
196​
197```tsx
198const peopleRoute = createRoute({
199 getParentRoute: () => rootRoute,
200 path: '/people',
201 loader: async () => {
202 const response = await fetch('https://swapi.dev/api/people')
203 return response.json() as Promise<{
204 results: {
205 name: string
206 }[]
207 }>
208 },
209 component: () => {
210 const data = peopleRoute.useLoaderData()
211 return (
212 <ul>
213 {data.results.map((person) => (
214 <li key={person.name}>{person.name}</li>
215 ))}
216 </ul>
217 )
218 },
219})
220```
221​
222Loaders simplify your data fetching logic dramatically. Check out more information in the [Loader documentation](https://tanstack.com/router/latest/docs/framework/react/guide/data-loading#loader-parameters).
223​
224### React-Query
225​
226React-Query is an excellent addition or alternative to route loading and integrating it into you application is a breeze.
227​
228First add your dependencies:
229​
230```bash
231pnpm add @tanstack/react-query @tanstack/react-query-devtools
232```
233​
234Next we'll need to create a query client and provider. We recommend putting those in `main.tsx`.
235​
236```tsx
237import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
238​
239// ...
240​
241const queryClient = new QueryClient()
242​
243// ...
244​
245if (!rootElement.innerHTML) {
246 const root = ReactDOM.createRoot(rootElement)
247​
248 root.render(
249 <QueryClientProvider client={queryClient}>
250 <RouterProvider router={router} />
251 </QueryClientProvider>,
252 )
254```
255​
256You can also add TanStack Query Devtools to the root route (optional).
257​
258```tsx
259import { ReactQueryDevtools } from '@tanstack/react-query-devtools'
260​
261const rootRoute = createRootRoute({
262 component: () => (
263 <>
264 <Outlet />
265 <ReactQueryDevtools buttonPosition="top-right" />
266 <TanStackRouterDevtools />
267 </>
268 ),
269})
270```
271​
272Now you can use `useQuery` to fetch your data.
273​
274```tsx
275import { useQuery } from '@tanstack/react-query'
276​
277import './App.css'
278​
279function App() {
280 const { data } = useQuery({
281 queryKey: ['people'],
282 queryFn: () =>
283 fetch('https://swapi.dev/api/people')
284 .then((res) => res.json())
285 .then((data) => data.results as { name: string }[]),
286 initialData: [],
287 })
288​
289 return (
290 <div>
291 <ul>
292 {data.map((person) => (
293 <li key={person.name}>{person.name}</li>
294 ))}
295 </ul>
296 </div>
297 )
299​
300export default App
301```
302​
303You can find out everything you need to know on how to use React-Query in the [React-Query documentation](https://tanstack.com/query/latest/docs/framework/react/overview).
304​
305## State Management
306​
307Another common requirement for React applications is state management. There are many options for state management in React. TanStack Store provides a great starting point for your project.
308​
309First you need to add TanStack Store as a dependency:
310​
311```bash
312pnpm add @tanstack/store
313```
314​
315Now let's create a simple counter in the `src/App.tsx` file as a demonstration.
316​
317```tsx
318import { useStore } from '@tanstack/react-store'
319import { Store } from '@tanstack/store'
320import './App.css'
321​
322const countStore = new Store(0)
323​
324function App() {
325 const count = useStore(countStore)
326 return (
327 <div>
328 <button onClick={() => countStore.setState((n) => n + 1)}>
329 Increment - {count}
330 </button>
331 </div>
332 )
334​
335export default App
336```
337​
338One of the many nice features of TanStack Store is the ability to derive state from other state. That derived state will update when the base state updates.
339​
340Let's check this out by doubling the count using derived state.
341​
342```tsx
343import { useStore } from '@tanstack/react-store'
344import { Store, Derived } from '@tanstack/store'
345import './App.css'
346​
347const countStore = new Store(0)
348​
349const doubledStore = new Derived({
350 fn: () => countStore.state * 2,
351 deps: [countStore],
352})
353doubledStore.mount()
354​
355function App() {
356 const count = useStore(countStore)
357 const doubledCount = useStore(doubledStore)
358​
359 return (
360 <div>
361 <button onClick={() => countStore.setState((n) => n + 1)}>
362 Increment - {count}
363 </button>
364 <div>Doubled - {doubledCount}</div>
365 </div>
366 )
368​
369export default App
370```
371​
372We use the `Derived` class to create a new store that is derived from another store. The `Derived` class has a `mount` method that will start the derived store updating.
373​
374Once we've created the derived store we can use it in the `App` component just like we would any other store using the `useStore` hook.
375​
376You can find out everything you need to know on how to use TanStack Store in the [TanStack Store documentation](https://tanstack.com/store/latest).
377​
378# Demo files
379​
380Files prefixed with `demo` can be safely deleted. They are there to provide a starting point for you to play around with the features you've installed.
381​
382# Learn More
383​
384You can learn more about all of the offerings from TanStack in the [TanStack documentation](https://tanstack.com).
385​
386## Persistent chat (`/persistent-chat`)
387​
388A chat that survives a full page reload on both ends. The client writes the
389transcript to `localStorage` (via `localStoragePersistence`), so a reload
390restores the conversation instantly. The server writes the same transcript,
391run records, and interrupt state to SQLite with `withPersistence`, so it
392survives a server restart too — the DB lives at `.data/persistent-chat.db`
393(gitignored). The SQLite backend is `src/lib/sqlite-persistence.ts`, a
394self-contained `node:sqlite` store built on the `@tanstack/ai-persistence`
395core store contracts — a worked example of rolling your own adapter.
396​
397Try it: send a message, wait for the reply, then reload the page. The
398conversation is still there. Needs `OPENAI_API_KEY` in `.env`.
399​
400## Sandboxes — GitHub issue triage (`/sandboxes`)
401​
402Pick a harness adapter (Claude Code, Codex, OpenCode) and a sandbox
403provider (Docker, local process, Vercel, Daytona), paste a GitHub **issue URL**,
404and the agent clones that repo into a sandbox, investigates read-only, and
405reports whether the bug is still relevant and its root cause — streaming tool
406calls and file activity live.
407​
408### Providers
409​
410- **Docker** — needs a running Docker daemon. The agent runs in a `node:22`
411 container; the harness CLI is installed on first create. Heavy investigations
412 can OOM the Docker VM (you'll see `exited with code 137`) — raise Docker
413 Desktop's memory (Settings → Resources) if so.
414- **Local process** — runs the chosen CLI directly on your host (no isolation;
415 dev only). On **Windows** the agent runs through git-bash/WSL `sh` (auto-located
416 from `git` on PATH; override with `TANSTACK_SANDBOX_SH`), since commands use
417 POSIX quoting — install Git for Windows, or set `TANSTACK_SANDBOX_SH`.
418- **Vercel** — `VERCEL_OIDC_TOKEN` (run `vercel env pull`), **or** `VERCEL_TOKEN`
419 - `VERCEL_TEAM_ID` + `VERCEL_PROJECT_ID`. (Token alone falls back to OIDC and
420 fails.) OIDC tokens are short-lived — re-pull when they expire.
421- **Daytona** — `DAYTONA_API_KEY`.
422​
423### Harness keys
424​
425Set the chosen harness's key in `.env.local` (read by the dev server):
426`ANTHROPIC_API_KEY` (Claude Code / OpenCode), `CODEX_API_KEY` (Codex).
427For **sandboxed** providers (Docker/Vercel/Daytona)
428the key is injected into the sandbox; for **local process** the host CLI uses
429your own host auth (the env key, or a `claude login`). Optional `GITHUB_TOKEN`
430for private repos / higher rate limits.
431​
432### Use your Claude subscription instead of the API (no API billing)
433​
434When running **Claude Code on the Local process provider**, tick **“use my
435subscription”** to bill your logged-in Claude Pro/Max account instead of the
436Anthropic API. It works by scrubbing `ANTHROPIC_API_KEY` from the spawned
437`claude`'s environment so the CLI falls back to your `claude login` credentials:
438​
439```ts
440import { localProcessSandbox } from '@tanstack/ai-sandbox-local-process'
441​
442// Drop env vars before spawning so the host CLI uses its own stored auth.
443localProcessSandbox({ scrubEnv: ['ANTHROPIC_API_KEY'] })
444```
445​
446Requires `claude login` (a Pro/Max subscription) on the host. Only local-process
447can do this — sandboxed providers have no host login, so they always use an API
448key. (The `-p` headless flag is unrelated to billing; it's just streaming mode.)
449​
450### Tool bridge & code mode
451​
452The triage run passes two `chat()` tools to the harness to exercise the
453**sandbox tool bridge** (host tools, called by the agent running inside the
454sandbox). The system prompt forces both before any repo work, so a broken
455bridge is obvious:
456​
457- `fetchIssueComments` — a normal server tool (host fetches the issue thread).
458- `searchRelatedIssues` — exposed via **code mode**: the agent calls
459 `execute_typescript`, and the generated code invokes
460 `external_searchRelatedIssues(...)` (run on a host isolate).
461​
462The bridge is a **localhost** HTTP server, so it's only directly reachable from
463same-machine providers (**local process**, **Docker**). For **remote** cloud
464sandboxes (Daytona, Vercel) the agent can't dial your laptop — set
465`NGROK_AUTHTOKEN` and the example tunnels the bridge out over ngrok so the tools
466work there too (the per-run bearer token still gates every call). Without it,
467cloud runs skip the tools and do a plain triage. In production you wouldn't need
468ngrok — your orchestrator already has a public URL to advertise.
469​
470Set keys in `.env.local`, then `pnpm dev` and open `/sandboxes`.
471​
472## App Studio
473​
474A small product page at `/app-studio` on top of portable snapshots. You describe an app. The
475agent scaffolds a TanStack Start app in a Docker sandbox, starts the preview
476server, and shows the live URL. After the first build:
477​
478- **Fork chat** copies the checkpoint and conversation into a new thread.
479 Continue from that copy. The source thread stays unchanged.
480- **Compare two directions** creates two forks. Each fork gets a different
481 visual prompt. Pick **Keep variant A** or **Keep variant B** to continue
482 on that branch.
483​
484Needs:
485​
486- Docker running on the host
487- `XAI_API_KEY` in `.env.local` (Grok Build runs inside the sandbox)
488​
489Stay on the page during the first build. The first run installs the CLI,
490scaffolds the app, and starts the preview. If you leave, the request aborts.
491​
492The snapshot store is `src/lib/sqlite-persistence.ts` at
493`.data/app-studio.db` (gitignored). The server route is `/api/app-studio`.
494The fork route is `/api/app-studio-fork`.
495​
496See [Branch From a Version](../../docs/sandbox/portable-snapshots-fork.md)
497for the `snapshots.fork` contract this page uses.