Tanstack ai Integration

Heads up: the workspace has been reverted to the state before the showNoteCard client-tool work — src/lib/ai/note-tools.ts is gone, and the chat route/API no longer reference it. So the article below documents the TanStack AI code that's actually in the repo right now (the notes assistant with a server tool + streaming chat). Copy from here down.
Building a Streaming, Tool-Calling AI Assistant with TanStack AI
TanStack AI is a type-safe, provider-agnostic AI SDK. In this post I'll show exactly how our note-taking app ("Notapp") wires it up: a Gemini-backed chat endpoint that streams responses over Server-Sent Events and can call a server-side tool to read the user's notes.
The stack
| Package | Version | Role |
|---|---|---|
@tanstack/ai | 0.28.0 | Core: chat(), toolDefinition(), SSE helpers |
@tanstack/ai-gemini | 0.15.1 | Google Gemini adapter (geminiText) |
@tanstack/ai-react | 0.15.4 | React hook (useChat) + client connection |
@tanstack/react-start | 1.16x | Full-stack framework (file routes + server handlers) |
zod | 4.x | Tool input/output schemas |
The whole thing has four moving parts:
- A server tool the model can call (
getAllNotes). - A system prompt that tells the model how to behave.
- An API route that runs
chat()and streams the result. - A client component that renders the conversation with
useChat.
1. Defining a server tool
TanStack AI tools are defined once with toolDefinition() (name + description + Zod schemas), then given an implementation. A server tool runs on the server via .server(). The model sees the name, description, and output shape, and decides when to call it.
// src/lib/server/chat.ts
import { toolDefinition } from '@tanstack/ai'
import { z } from 'zod'
import { noteSchema } from '#/lib/schemas/notes'
import { getNotes } from './notes'
const getAllNotesToolDef = toolDefinition({
name: 'getAllNotes',
description: 'Load all notes belonging to the current user',
outputSchema: z.array(noteSchema),
})
export const getAllNotes = getAllNotesToolDef.server(async () => {
const notes = await getNotes({ data: { sort: 'newest' } })
return notes
})
The key idea: outputSchema is a Zod schema, so the tool's return value is fully typed and validated. getNotes here is a normal TanStack Start server function that pulls the current user's notes from the database.
2. The system prompt
Kept as a plain string in its own module so it's easy to iterate on:
// src/routes/api/chat/conts.ts
export const SYSTEM_PROMPT = `You are Notapp's dedicated AI Note Assistant. Your primary responsibility is to help users interact with, analyze, and manage their personal notes saved within this application.
### CRITICAL WORKFLOW & CONSTRAINTS:
1. **Always Check Notes First:** For ANY user query that could potentially rely on personal context, history, or facts, you MUST call the \`getAllNotes\` tool immediately. Do not attempt to answer, speculate, or use general knowledge until you have successfully executed this tool and reviewed the notes.
2. **Synthesize & Answer:** If the information is found, answer using their note content. Help them summarize, connect ideas across notes, suggest edits, or draft new content based on their existing data.
3. **Information Not Found Protocol:** If the required information is completely missing from their notes after reviewing the tool output, you must strictly follow these two steps:
- Step A: Explicitly state to the user that you could not find this information within their existing notes.
- Step B: Ask the user directly if they would like you to look it up on the internet or answer using your general knowledge instead.
### TONE & STYLE:
- Be concise, direct, and practical.
- Avoid repeating these backend instructions to the user.
- Do not make assumptions about the user's life outside of what is documented in their notes.`
3. The streaming API route
This is where TanStack AI does the heavy lifting. chat() takes an adapter, the message history, system prompts, and the available tools, and returns a stream. toServerSentEventsResponse() turns that stream into an SSE Response the browser can consume.
We use a TanStack Start file route with a server.handlers.POST handler:
// src/routes/api/chat/index.tsx
import { getAllNotes } from '#/lib/server/chat'
import { chat, toServerSentEventsResponse } from '@tanstack/ai'
import { geminiText } from '@tanstack/ai-gemini'
import { createFileRoute } from '@tanstack/react-router'
import { SYSTEM_PROMPT } from './conts'
export const Route = createFileRoute('/api/chat/')({
server: {
handlers: {
POST: async ({ request }) => {
if (!process.env.GEMINI_API_KEY && !process.env.GOOGLE_API_KEY) {
return new Response(
JSON.stringify({ error: 'GEMINI_API_KEY not configured' }),
{ status: 500, headers: { 'Content-Type': 'application/json' } },
)
}
const body = await request.json()
try {
const stream = chat({
adapter: geminiText('gemini-2.5-flash-lite'),
messages: body.messages,
systemPrompts: [SYSTEM_PROMPT],
tools: [getAllNotes],
})
return toServerSentEventsResponse(stream)
} catch (error) {
return new Response(
JSON.stringify({
error:
error instanceof Error ? error.message : 'An error occurred',
}),
{ status: 500, headers: { 'Content-Type': 'application/json' } },
)
}
},
},
},
})
A few things worth calling out:
geminiText('gemini-2.5-flash-lite')readsGEMINI_API_KEY/GOOGLE_API_KEYfrom the environment. Swapping providers is a one-line change (e.g.openaiText(...)oranthropicText(...)).tools: [getAllNotes]is what lets the model call our tool mid-conversation. TanStack AI handles the tool-call loop automatically: it streams the call, runsgetAllNoteson the server, feeds the result back to the model, and continues.- The API-key guard returns a clean 500 instead of throwing deep in the SDK.
4. The client: useChat
On the client, useChat manages the message list, loading state, and sending. fetchServerSentEvents('/api/chat') tells it to POST to our route and read the SSE stream.
// src/routes/_authenticated/chat/index.tsx
import { createFileRoute } from '@tanstack/react-router'
import { useState } from 'react'
import { useChat, fetchServerSentEvents } from '@tanstack/ai-react'
import { Info } from 'lucide-react'
import styles from './Chat.module.css'
import { ProgressCircle } from '#/shared/ui/ProgressCircle/ProgressCircle'
const PREDEFINED_PROMPTS = [
'Summarize my latest notes',
'What have I been writing about lately?',
'Find themes across my notes',
] as const
export const Route = createFileRoute('/_authenticated/chat/')({
staticData: { title: 'Chat' },
component: RouteComponent,
})
function RouteComponent() {
const [input, setInput] = useState('')
const { messages, sendMessage, isLoading } = useChat({
connection: fetchServerSentEvents('/api/chat'),
})
const sendUserMessage = (text: string) => {
const trimmed = text.trim()
if (trimmed && !isLoading) {
sendMessage(trimmed)
setInput('')
}
}
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault()
sendUserMessage(input)
}
const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault()
sendUserMessage(input)
}
}
return (
<div className={styles.chat}>
<div className={styles.messages}>
{messages.map((message) => {
const isUser = message.role === 'user'
return (
<div
key={message.id}
className={`${styles.message} ${
isUser ? styles.messageUser : styles.messageAssistant
}`}
>
<span className={styles.role}>{isUser ? 'You' : 'Assistant'}</span>
<div
className={`${styles.bubble} ${
isUser ? styles.bubbleUser : styles.bubbleAssistant
}`}
>
{message.parts.map((part, idx) => {
if (part.type === 'thinking') {
return (
<div key={idx} className={styles.thinking}>
Thinking: {part.content}
</div>
)
}
if (part.type === 'text') {
return <div key={idx}>{part.content}</div>
}
return null
})}
</div>
</div>
)
})}
</div>
<form onSubmit={handleSubmit} className={styles.inputArea}>
<textarea
value={input}
onChange={(e) => setInput(e.target.value)}
onKeyDown={handleKeyDown}
placeholder="Ask your notes anything..."
disabled={isLoading}
rows={1}
/>
<button type="submit" disabled={!input.trim() || isLoading}>
{isLoading ? <ProgressCircle isIndeterminate size={24} /> : 'Send'}
</button>
</form>
</div>
)
}
Note: I trimmed the empty-state banner and predefined-prompt buttons from the JSX above to keep the example focused on the TanStack AI parts. In the real file they live inside the
messages.length === 0branch.
Messages are made of typed "parts"
The most important client concept: each message has a parts array, and each part has a type. We render text parts as the reply, and thinking parts (the model's reasoning stream) in a muted style. Other part types—like tool-call—flow through the same array, which is exactly the extension point you'd use to render custom UI when a tool runs.
How a single turn flows
User types ─▶ useChat.sendMessage()
─▶ POST /api/chat (SSE)
─▶ chat({ adapter: geminiText, tools: [getAllNotes] })
│
├─ model decides to call getAllNotes
├─ getAllNotes runs on the server (reads DB)
├─ result streamed back into the model
└─ model streams its final answer
─▶ SSE chunks ─▶ useChat updates `messages`
─▶ UI re-renders text/thinking parts live
Takeaways
toolDefinition()+.server()gives you type-safe, Zod-validated tools the model can call, with the tool-call loop handled for you.chat()+toServerSentEventsResponse()on a TanStack Startserver.handlers.POSTroute is all you need for streaming.useChat()+fetchServerSentEvents()wires the UI to that endpoint with almost no boilerplate; you just rendermessage.parts.- Provider-agnostic: switching from Gemini to OpenAI/Anthropic/Ollama is a one-line adapter swap.
Want me to also include the showNoteCard client-side tool (rendering a rich React component inside the chat) as a follow-up section? That code isn't currently in the repo — I can re-add it and document it, or write it up as a "next step" based on what we built earlier.