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

quick-start-server.md

221 lines6.0 KB

1---
2title: "Quick Start: Server Only"
3id: quick-start-server
4order: 5
5description: "Call a model from Node.js with TanStack AI. Get text back in a script, or serve a streaming chat endpoint. No UI framework needed."
6keywords:
7 - tanstack ai
8 - node.js
9 - server
10 - backend
11 - quick start
12 - streaming chat
13 - openai
14 - sse
15---
16​
17This guide calls a model from a Node.js server. It has no UI framework.
18​
19`chat()` runs on the server and returns a stream. You can read it to the end as text, or send it over HTTP. This takes about 5 minutes.
20​
21## 1. Install
22​
23<!-- ::start:tabs variant="package-manager" mode="install" -->
24​
25react: @tanstack/ai @tanstack/ai-openai
26vue: @tanstack/ai @tanstack/ai-openai
27solid: @tanstack/ai @tanstack/ai-openai
28svelte: @tanstack/ai @tanstack/ai-openai
29preact: @tanstack/ai @tanstack/ai-openai
30angular: @tanstack/ai @tanstack/ai-openai
31vanilla: @tanstack/ai @tanstack/ai-openai
32octane: @tanstack/ai @tanstack/ai-openai
33​
34<!-- ::end:tabs -->
35​
36> [!TIP]
37> If you do not want a key for each provider, use [OpenRouter](../adapters/openrouter). It gives you 300+ models with one API key.
38​
39## 2. Add your API key
40​
41Create a `.env` file:
42​
43```bash
44OPENAI_API_KEY=your-openai-api-key
45```
46​
47The adapter reads `OPENAI_API_KEY` at runtime. Do not send this key to the browser.
48​
49## 3. Get a reply
50​
51Call `chat()`, then read the whole stream with `streamToText`:
52​
53```typescript
54import { chat, streamToText } from '@tanstack/ai'
55import { openaiText } from '@tanstack/ai-openai'
56​
57const stream = chat({
58 adapter: openaiText('gpt-6.1-sol'),
59 messages: [{ role: 'user', content: 'Hello!' }],
60 threadId: 'thread-1',
61})
62​
63const { text } = await streamToText(stream)
64console.log(text)
65```
66​
67Run the file. The reply prints to the terminal.
68​
69## 4. Serve it over HTTP
70​
71This Express server streams the reply as Server-Sent Events on `/api/chat`:
72​
73```typescript ignore
74import express from 'express'
75import {
76 chat,
77 chatParamsFromRequestBody,
78 toServerSentEventsResponse,
79} from '@tanstack/ai'
80import { openaiText } from '@tanstack/ai-openai'
81​
82const app = express()
83app.use(express.json())
84​
85app.post('/api/chat', async (req, res) => {
86 const { messages, threadId, runId } = await chatParamsFromRequestBody(
87 req.body,
88 )
89​
90 const stream = chat({
91 adapter: openaiText('gpt-6.1-sol'),
92 messages,
93 threadId,
94 runId,
95 })
96​
97 const response = toServerSentEventsResponse(stream)
98 res.writeHead(response.status, Object.fromEntries(response.headers))
99​
100 const body = response.body
101 if (body) {
102 const reader = body.getReader()
103 const pump = async () => {
104 const { done, value } = await reader.read()
105 if (done) {
106 res.end()
107 return
108 }
109 res.write(value)
110 await pump()
111 }
112 await pump()
113 }
114})
115​
116app.listen(3000, () => console.log('Server running on port 3000'))
117```
118​
119The client hooks (`useChat` in `@tanstack/ai-react`, `@tanstack/ai-vue`, `@tanstack/ai-svelte`, and the others) can talk to this endpoint. Add a UI later with the [Quick Start](./quick-start).
120​
121You now have a model that answers from your backend.
122​
123## How it works
124​
125- `chat()` returns an `AsyncIterable<StreamChunk>`. Nothing runs until you read it.
126- `streamToText` reads the stream to the end. It returns `{ text, chunks }`. `text` is the full reply. `chunks` holds the rest of the run: tool calls, usage, and interrupts.
127- `toServerSentEventsResponse` turns the stream into a Web `Response` in the TanStack AI SSE format.
128​
129Any backend that returns this format works. Fastify, Hono, and other Node.js frameworks are fine.
130​
131## Next
132​
133- [Tools](../tools/tools): add function calling and agent loops.
134- [Adapters](../adapters/openai): connect to other providers.
135- [Quick Start](./quick-start): add a frontend.
136​
137## Advanced
138​
139### Add a server tool
140​
141Define a tool with `toolDefinition`, then pass it to `chat()`. The agent loop calls the tool and sends the result back to the model:
142​
143```typescript
144import { chat, toolDefinition, streamToText } from '@tanstack/ai'
145import { openaiText } from '@tanstack/ai-openai'
146import { z } from 'zod'
147​
148const getWeather = toolDefinition({
149 name: 'getWeather',
150 description: 'Get weather for a city',
151 inputSchema: z.object({ city: z.string() }),
152 outputSchema: z.object({ temp: z.number(), condition: z.string() }),
153}).server(async ({ city }) => {
154 return { temp: 22, condition: `sunny in ${city}` }
155})
156​
157const stream = chat({
158 adapter: openaiText('gpt-6.1-sol'),
159 messages: [{ role: 'user', content: 'Weather in Tokyo?' }],
160 threadId: 'thread-1',
161 tools: [getWeather],
162})
163​
164const { text } = await streamToText(stream)
165console.log(text)
166```
167​
168The model decides when to call `getWeather`. It gets the result and uses it in its answer, all inside one `chat()` call.
169​
170### Newline-delimited JSON
171​
172`toHttpResponse()` returns a `Response` with newline-delimited JSON instead of SSE. On the client, pair it with `fetchHttpStream`:
173​
174```typescript
175import { chat, chatParamsFromRequest, toHttpResponse } from '@tanstack/ai'
176import { openaiText } from '@tanstack/ai-openai'
177​
178export async function POST(request: Request) {
179 const { messages, threadId, runId } = await chatParamsFromRequest(request)
180 const stream = chat({
181 adapter: openaiText('gpt-6.1-sol'),
182 messages,
183 threadId,
184 runId,
185 })
186 return toHttpResponse(stream)
188```
189​
190### Read the raw stream
191​
192Iterate the stream with `for await` to handle each chunk yourself:
193​
194```typescript
195import { chat } from '@tanstack/ai'
196import { openaiText } from '@tanstack/ai-openai'
197​
198const stream = chat({
199 adapter: openaiText('gpt-6.1-sol'),
200 messages: [{ role: 'user', content: 'Hello!' }],
201 threadId: 'thread-1',
202})
203​
204for await (const chunk of stream) {
205 if (chunk.type === 'TEXT_MESSAGE_CONTENT') {
206 process.stdout.write(chunk.delta ?? '')
207 }
209```
210​
211You see every chunk type: text deltas, tool calls, run lifecycle events, and more. For more control, see [StreamProcessor](../reference/classes/StreamProcessor).
212​
213### OpenRouter key
214​
215To use OpenRouter, put its key in `.env`:
216​
217```bash
218OPENROUTER_API_KEY=sk-or-...
219```
220​
221Then use the adapter from [OpenRouter](../adapters/openrouter).