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

quick-start.md

551 lines14.6 KB

1---
2title: Quick Start
3id: quick-start
4order: 2
5description: "Add a streaming TanStack AI chat to your app. Pick a framework, install, stream from a server route, and render with the matching hook."
6keywords:
7 - tanstack ai
8 - quick start
9 - useChat
10 - injectChat
11 - createChat
12 - streaming chat
13 - openai
14 - react
15 - vue
16 - solid
17 - svelte
18 - preact
19 - angular
20 - octane
21 - remix
22redirect_from:
23 - /getting-started/quick-start-vue
24 - /getting-started/quick-start-svelte
25 - /getting-started/quick-start-angular
26 - /getting-started/quick-start-octane
27---
28​
29You want a streaming chat in your app. TanStack AI streams from a server route. The hook for your framework renders the tokens.
30​
31For a React + Start app with BYOK, open [Basic Chat](../tutorials/basic-chat).
32​
33For an MCP server with a tool, a resource, and a prompt, open [Build an MCP Server](../tutorials/mcp-server).
34​
35For an image from a prompt, open [Generate Image](../tutorials/generate-image).
36​
37For a table that fills as JSON streams, open [Streaming Structured Table](../tutorials/streaming-structured-table).
38​
39For a blog desk where a researcher and an SEO agent run together and a writer uses their notes, open [Subagents](../tutorials/subagents).
40​
41For a model that clicks through a web page from screenshots, open [Computer Use](../tutorials/computer-use).
42​
43> [!TIP]
44> If you do not want a key per provider, [OpenRouter](../adapters/openrouter) gives you 300+ models with one API key.
45​
46React Native or Expo needs an absolute server URL and an XHR transport. See [Quick Start: React Native](./quick-start-react-native).
47​
48No UI: see [Quick Start: Server Only](./quick-start-server).
49​
50## 1. Install
51​
52<!-- ::start:tabs variant="package-manager" mode="install" -->
53​
54react: @tanstack/ai @tanstack/ai-react @tanstack/ai-openai
55vue: @tanstack/ai @tanstack/ai-vue @tanstack/ai-openai
56solid: @tanstack/ai @tanstack/ai-solid @tanstack/ai-openai
57svelte: @tanstack/ai @tanstack/ai-svelte @tanstack/ai-openai
58preact: @tanstack/ai @tanstack/ai-preact @tanstack/ai-openai
59angular: @tanstack/ai @tanstack/ai-angular @tanstack/ai-openai
60vanilla: @tanstack/ai @tanstack/ai-client @tanstack/ai-openai
61octane: @tanstack/ai @tanstack/ai-octane @tanstack/ai-openai octane
62remix: @tanstack/ai @tanstack/ai-remix @tanstack/ai-openai remix
63​
64<!-- ::end:tabs -->
65​
66## 2. Stream from the server
67​
68Call `chat()`. Then wrap the result with `toServerSentEventsResponse`.
69​
70```typescript
71import {
72 chat,
73 chatParamsFromRequest,
74 toServerSentEventsResponse,
75} from "@tanstack/ai";
76import { openaiText } from "@tanstack/ai-openai";
77​
78export async function POST(request: Request) {
79 const { messages, threadId, runId } = await chatParamsFromRequest(request);
80​
81 const stream = chat({
82 adapter: openaiText("gpt-5.6"),
83 messages,
84 threadId,
85 runId,
86 });
87​
88 return toServerSentEventsResponse(stream);
90```
91​
92This works with TanStack Start, Next.js, SvelteKit, Hono, and any host that returns a Web `Response`.
93​
94A Remix controller action can return this same `Response`.
95​
96If your server is Node streams (Express), see [Quick Start: Server Only](./quick-start-server).
97​
98Put the API key on the server:
99​
100```bash
101OPENAI_API_KEY=your-openai-api-key
102```
103​
104The adapter reads `OPENAI_API_KEY` at runtime. Do not send this key to the browser.
105​
106If you do not want a server key, see [Bring Your Own Key](../advanced/byok).
107​
108## 3. Render the chat
109​
110<!-- ::start:framework -->
111​
112# React
113​
114Call `useChat` from `@tanstack/ai-react`. Hold the composer text in `useState`. Pass it to `sendMessage`.
115​
116```tsx
117import { useState } from "react";
118import { useChat, fetchServerSentEvents } from "@tanstack/ai-react";
119​
120export function Chat() {
121 const [input, setInput] = useState("");
122 const { messages, sendMessage, isLoading, stop } = useChat({
123 connection: fetchServerSentEvents("/api/chat"),
124 });
125​
126 return (
127 <>
128 {messages.map((message) => (
129 <div key={message.id}>
130 {message.parts.map((part, index) =>
131 part.type === "text" ? <p key={index}>{part.content}</p> : null,
132 )}
133 </div>
134 ))}
135 <form
136 onSubmit={(event) => {
137 event.preventDefault();
138 if (input.trim() === "") {
139 return;
140 }
141 sendMessage(input);
142 setInput("");
143 }}
144 >
145 <input
146 value={input}
147 onChange={(event) => setInput(event.target.value)}
148 />
149 {isLoading ? (
150 <button type="button" onClick={stop}>
151 Stop
152 </button>
153 ) : (
154 <button type="submit">Send</button>
155 )}
156 </form>
157 </>
158 );
160```
161​
162`messages` updates as chunks arrive. `isLoading` is `true` while the run is in flight.
163​
164See the [React API](../api/ai-react).
165​
166# Vue
167​
168Call `useChat` from `@tanstack/ai-vue`. If you are in `<script setup>`, read refs with `.value`. The template unwraps them.
169​
170```vue
171<script setup lang="ts">
172import { ref } from 'vue'
173import { useChat, fetchServerSentEvents } from '@tanstack/ai-vue'
174​
175const input = ref('')
176​
177const { messages, sendMessage, isLoading, stop } = useChat({
178 connection: fetchServerSentEvents('/api/chat'),
179})
180​
181function handleSubmit() {
182 if (input.value.trim() && !isLoading.value) {
183 sendMessage(input.value)
184 input.value = ''
185 }
187</script>
188​
189<template>
190 <div>
191 <div v-for="message in messages" :key="message.id">
192 <template v-for="(part, index) in message.parts" :key="index">
193 <p v-if="part.type === 'text'">{{ part.content }}</p>
194 </template>
195 </div>
196 <form @submit.prevent="handleSubmit">
197 <input v-model="input" :disabled="isLoading" />
198 <button v-if="isLoading" type="button" @click="stop">Stop</button>
199 <button v-else type="submit" :disabled="!input.trim()">Send</button>
200 </form>
201 </div>
202</template>
203```
204​
205The composable stops in-flight requests when the component unmounts.
206​
207See the [Vue API](../api/ai-vue).
208​
209# Solid
210​
211Call `useChat` from `@tanstack/ai-solid`. `messages` and `isLoading` are accessors. Call them as functions.
212​
213```tsx ignore
214import { For, createSignal } from "solid-js";
215import { useChat, fetchServerSentEvents } from "@tanstack/ai-solid";
216​
217export function Chat() {
218 const [input, setInput] = createSignal("");
219 const { messages, sendMessage, isLoading, stop } = useChat({
220 connection: fetchServerSentEvents("/api/chat"),
221 });
222​
223 return (
224 <>
225 <For each={messages()}>
226 {(message) => (
227 <div>
228 <For each={message.parts}>
229 {(part) =>
230 part.type === "text" ? <p>{part.content}</p> : null
231 }
232 </For>
233 </div>
234 )}
235 </For>
236 <form
237 onSubmit={(event) => {
238 event.preventDefault();
239 if (input().trim() === "") {
240 return;
241 }
242 sendMessage(input());
243 setInput("");
244 }}
245 >
246 <input
247 value={input()}
248 onInput={(event) => setInput(event.currentTarget.value)}
249 />
250 {isLoading() ? (
251 <button type="button" onClick={stop}>
252 Stop
253 </button>
254 ) : (
255 <button type="submit">Send</button>
256 )}
257 </form>
258 </>
259 );
261```
262​
263See the [Solid API](../api/ai-solid).
264​
265# Svelte
266​
267Call `createChat` from `@tanstack/ai-svelte`. The return object uses reactive getters. Read `chat.messages` and `chat.isLoading` with no extra wrapper.
268​
269```svelte
270<script lang="ts">
271import { createChat, fetchServerSentEvents } from '@tanstack/ai-svelte'
272​
273let input = $state('')
274​
275const chat = createChat({
276 connection: fetchServerSentEvents('/api/chat'),
277})
278​
279function handleSubmit() {
280 if (input.trim() && !chat.isLoading) {
281 chat.sendMessage(input)
282 input = ''
283 }
285</script>
286​
287<div>
288 {#each chat.messages as message (message.id)}
289 <div>
290 {#each message.parts as part}
291 {#if part.type === 'text'}
292 <p>{part.content}</p>
293 {/if}
294 {/each}
295 </div>
296 {/each}
297​
298 <form onsubmit={handleSubmit}>
299 <input bind:value={input} disabled={chat.isLoading} />
300 {#if chat.isLoading}
301 <button type="button" onclick={() => chat.stop()}>Stop</button>
302 {:else}
303 <button type="submit" disabled={!input.trim()}>Send</button>
304 {/if}
305 </form>
306</div>
307```
308​
309If the component can unmount while a response streams, call `chat.stop()` in `onDestroy`.
310​
311See the [Svelte API](../api/ai-svelte).
312​
313# Preact
314​
315Call `useChat` from `@tanstack/ai-preact`. Hold the composer text with `useState` from `preact/hooks`.
316​
317```tsx ignore
318import { useState } from "preact/hooks";
319import { useChat, fetchServerSentEvents } from "@tanstack/ai-preact";
320​
321export function Chat() {
322 const [input, setInput] = useState("");
323 const { messages, sendMessage, isLoading, stop } = useChat({
324 connection: fetchServerSentEvents("/api/chat"),
325 });
326​
327 return (
328 <>
329 {messages.map((message) => (
330 <div key={message.id}>
331 {message.parts.map((part, index) =>
332 part.type === "text" ? <p key={index}>{part.content}</p> : null,
333 )}
334 </div>
335 ))}
336 <form
337 onSubmit={(event) => {
338 event.preventDefault();
339 if (input.trim() === "") {
340 return;
341 }
342 sendMessage(input);
343 setInput("");
344 }}
345 >
346 <input
347 value={input}
348 onInput={(event) => setInput(event.currentTarget.value)}
349 />
350 {isLoading ? (
351 <button type="button" onClick={stop}>
352 Stop
353 </button>
354 ) : (
355 <button type="submit">Send</button>
356 )}
357 </form>
358 </>
359 );
361```
362​
363See the [Preact API](../api/ai-preact).
364​
365# Angular
366​
367Call `injectChat` in a field initializer. State is a `Signal`. Read it by calling the function.
368​
369```typescript ignore
370import { Component } from "@angular/core";
371import { FormsModule } from "@angular/forms";
372import { injectChat, fetchServerSentEvents } from "@tanstack/ai-angular";
373​
374@Component({
375 selector: "app-chat",
376 standalone: true,
377 imports: [FormsModule],
378 template: `
379 <div>
380 @for (message of chat.messages(); track message.id) {
381 <div>
382 @for (part of message.parts; track $index) {
383 @if (part.type === "text") {
384 <p>{{ part.content }}</p>
385 }
386 }
387 </div>
388 }
389 <form (submit)="send($event)">
390 <input [(ngModel)]="draft" name="draft" [disabled]="chat.isLoading()" />
391 @if (chat.isLoading()) {
392 <button type="button" (click)="chat.stop()">Stop</button>
393 } @else {
394 <button type="submit" [disabled]="!draft.trim()">Send</button>
395 }
396 </form>
397 </div>
398 `,
399})
400export class ChatComponent {
401 chat = injectChat({
402 connection: fetchServerSentEvents("/api/chat"),
403 });
404​
405 draft = "";
406​
407 send(event: Event) {
408 event.preventDefault();
409 const text = this.draft.trim();
410 if (text && !this.chat.isLoading()) {
411 void this.chat.sendMessage(text);
412 this.draft = "";
413 }
414 }
416```
417​
418Call `injectChat` in a field initializer or the constructor. A call in `ngOnInit` throws.
419​
420`injectChat` subscribes to `DestroyRef`. In-flight requests stop when the component is destroyed.
421​
422See the [Angular API](../api/ai-angular).
423​
424# Octane
425​
426Call `useChat` from `@tanstack/ai-octane`. Hold the composer text in `useState` from `octane`. Octane text controls fire `onInput`.
427​
428`@tanstack/ai-octane` publishes uncompiled `.tsrx` source. Add `octane/compiler/vite` (or the rspack / rspeedy equivalent) to the app build.
429​
430```tsx ignore
431import { useState } from "octane";
432import { useChat, fetchServerSentEvents } from "@tanstack/ai-octane";
433​
434export function Chat() {
435 const [input, setInput] = useState("");
436 const { messages, sendMessage, isLoading, stop } = useChat({
437 connection: fetchServerSentEvents("/api/chat"),
438 });
439​
440 return (
441 <div>
442 {messages.map((message) => (
443 <div key={message.id}>
444 <p>
445 {message.parts
446 .filter((part) => part.type === "text")
447 .map((part) => part.content)
448 .join("")}
449 </p>
450 </div>
451 ))}
452 <form
453 onSubmit={(event) => {
454 event.preventDefault();
455 if (input.trim() === "") {
456 return;
457 }
458 void sendMessage(input);
459 setInput("");
460 }}
461 >
462 <input
463 value={input}
464 disabled={isLoading}
465 onInput={(event) => setInput(event.currentTarget.value)}
466 />
467 {isLoading ? (
468 <button type="button" onClick={stop}>
469 Stop
470 </button>
471 ) : (
472 <button type="submit">Send</button>
473 )}
474 </form>
475 </div>
476 );
478```
479​
480The hook calls `attach()` on mount. It calls `detach()` and `dispose()` on unmount.
481​
482See the [Octane API](../api/ai-octane).
483​
484# Remix
485​
486Call `createChat(handle, options)` from `@tanstack/ai-remix` inside a `clientEntry` island. Put `connection` and `tools` in setup. They are not serializable `clientEntry` props.
487​
488`@tanstack/ai-remix` publishes uncompiled source. Remix compiles JSX through `jsxImportSource` `remix/ui`. Bind the form with the Remix `on` mixin.
489​
490```tsx ignore
491import { createChat, fetchServerSentEvents } from "@tanstack/ai-remix";
492import { clientEntry, on, type Handle } from "remix/ui";
493​
494export const Chat = clientEntry(
495 import.meta.url,
496 function Chat(handle: Handle) {
497 const chat = createChat(handle, {
498 connection: fetchServerSentEvents("/api/chat"),
499 });
500​
501 return () => (
502 <div>
503 {chat.messages.map((message) => (
504 <div key={message.id}>
505 {message.parts.map((part, index) =>
506 part.type === "text" ? <p key={index}>{part.content}</p> : null,
507 )}
508 </div>
509 ))}
510 <form
511 mix={on("submit", (event) => {
512 event.preventDefault();
513 const form = event.currentTarget;
514 const text = String(
515 new FormData(form).get("message") ?? "",
516 ).trim();
517 if (text === "") {
518 return;
519 }
520 form.reset();
521 void chat.sendMessage(text);
522 })}
523 >
524 <input name="message" disabled={chat.isLoading} />
525 {chat.isLoading ? (
526 <button type="button" mix={on("click", () => chat.stop())}>
527 Stop
528 </button>
529 ) : (
530 <button type="submit">Send</button>
531 )}
532 </form>
533 </div>
534 );
535 },
536);
537```
538​
539Read `chat.messages` and `chat.isLoading` in the render function so each paint sees the latest values.
540​
541See the [Remix API](../api/ai-remix). For a typed headless chat UI, see [Remix Chat UI](../ui/remix).
542​
543<!-- ::end:framework -->
544​
545Send a message. Tokens show up in the UI.
546​
547## Later
548​
549- [Tools](../tools/tools) for function calling
550- [Streaming](../chat/streaming) for cancel, callbacks, and transports
551- [Adapters](../adapters/openai) for other providers