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

solid.md

353 lines11.0 KB

1---
2title: Solid Chat UI
3id: typed-headless-ui-solid
4order: 2
5description: "Render a streaming chat in Solid with your own components. createChatHook types every tool, part, and interrupt, and props stay tracked."
6keywords:
7 - tanstack ai
8 - createChatHook
9 - solid
10 - headless ui
11 - ToolProps
12---
13​
14`createChatHook` from `@tanstack/ai-solid/ui` binds your chat options and components once. Tool calls and approvals stay typed.
15​
16Each screen then renders the chat with one hook call. You supply every visible component. There is no default markup or style.
17​
18> [!NOTE]
19> Upgrading from `@tanstack/ai-solid-ui`? Read [Upgrade to 1.0](../migration/v1#chat-ui-components).
20​
21## Quick setup
22​
231. Install the packages:
24​
25<!-- ::start:tabs variant="package-manager" mode="install" -->
26​
27solid: @tanstack/ai @tanstack/ai-solid @tanstack/ai-openai
28​
29<!-- ::end:tabs -->
30​
312. Put `OPENAI_API_KEY` in your server environment. Then add a `POST` route at `/api/chat`:
32​
33```ts
34import {
35 chat,
36 chatParamsFromRequest,
37 toServerSentEventsResponse,
38} from '@tanstack/ai'
39import { openaiText } from '@tanstack/ai-openai'
40​
41export async function POST(request: Request) {
42 const { messages, threadId, runId } = await chatParamsFromRequest(request)
43​
44 const stream = chat({
45 adapter: openaiText('gpt-6.1-sol'),
46 messages,
47 threadId,
48 runId,
49 })
50​
51 return toServerSentEventsResponse(stream)
53```
54​
553. Create `src/chat.tsx`:
56​
57```tsx
58import { fetchServerSentEvents } from '@tanstack/ai-solid'
59import { createChatHook } from '@tanstack/ai-solid/ui'
60​
61const chatOptions = {
62 connection: fetchServerSentEvents('/api/chat'),
64​
65const { useAppChat } = createChatHook({
66 options: chatOptions,
67 components: {
68 layout: (props) => (
69 <section>
70 <props.Messages />
71 </section>
72 ),
73 message: (props) => (
74 <article data-role={props.message.role}>
75 <props.Parts />
76 </article>
77 ),
78 },
79 partsComponents: {
80 text: (props) => <p>{props.part.content}</p>,
81 fallback: () => null,
82 },
83})
84​
85export function ChatScreen() {
86 const chat = useAppChat({ threadId: 'support-chat' })
87​
88 return (
89 <main>
90 <chat.AppChat />
91 <form
92 onSubmit={(event) => {
93 event.preventDefault()
94 const field = event.currentTarget.elements.namedItem('message')
95 if (!(field instanceof HTMLInputElement)) return
96 const text = field.value.trim()
97 if (!text) return
98 field.value = ''
99 void chat.sendMessage(text)
100 }}
101 >
102 <input name="message" />
103 <button type="submit">Send</button>
104 </form>
105 </main>
106 )
108```
109​
1104. Render `<ChatScreen />` and send a message.
111​
112The reply streams into the page as the model writes it.
113​
114## How it works
115​
116- `createChatHook` runs once, at module scope. It binds `chatOptions` to your components.
117- `useAppChat({ threadId })` creates one chat instance. `chat.AppChat` renders that instance with your components.
118- `layout` places the message list. `message` wraps one message. `Parts` picks a component for each part of that message.
119- `partsComponents.text` renders text. `fallback` catches every part type that you did not register.
120​
121Read props as `props.part` and `props.Messages`. Do not destructure them, or Solid stops tracking the values.
122​
123## Next steps
124​
125Each step adds one thing to the quick setup. The [chat UI recipes](./recipes/index) have the full file for each one. The recipes use React, and the option names are the same in Solid.
126​
127### Render a tool
128​
129Add the tool to `tools` in `chatOptions`. Then register a component under the tool name in `toolsComponents`. `part.input` and `part.output` are typed from the tool schemas.
130​
131```tsx ignore
132toolsComponents: {
133 getWeather: (props) =>
134 props.part.state === 'complete' ? (
135 <p>
136 {props.part.input?.city}: {props.part.output?.temperature}
137 </p>
138 ) : (
139 <p>Looking up weather</p>
140 ),
141},
142```
143​
144The factory needs one entry for every tool in `chatOptions`. Full example: [Make a tool look right](./recipes/format-a-tool).
145​
146### Ask before a tool runs
147​
148Set `needsApproval: true` on the tool. The tool component then gets an `interrupt` prop:
149​
150```tsx ignore
151toolsComponents: {
152 deleteFile: (props) =>
153 props.interrupt?.status === 'pending' ? (
154 <button onClick={() => props.interrupt?.resolveInterrupt(true)}>
155 Delete {props.part.input?.path}
156 </button>
157 ) : (
158 <p>{props.part.input?.path}</p>
159 ),
160},
161```
162​
163`resolveInterrupt(true)` approves. `resolveInterrupt(false)` denies. Full example: [Ask before a tool runs](./recipes/tool-approval).
164​
165### Ask the user your own question
166​
167Define the question with `defineInterrupt`. Add it to `interrupts` in `chatOptions`. Register a component under its id in `interruptsComponents.generic`, and render `props.Interrupts` in the layout:
168​
169```tsx ignore
170const choosePlan = defineInterrupt({
171 id: 'choosePlan',
172 payloadSchema: z.object({ title: z.string() }),
173 responseSchema: z.string(),
174})
175​
176// In createChatHook:
177interruptsComponents: {
178 generic: {
179 choosePlan: (props) => (
180 <button onClick={() => props.interrupt.resolveInterrupt('pro')}>
181 {props.interrupt.payload?.title}
182 </button>
183 ),
184 fallback: (props) => <p>{props.interrupt.reason}</p>,
185 },
186},
187```
188​
189The factory needs one entry for every interrupt id in `chatOptions`. Full example: [Ask the user your own question](./recipes/custom-interrupt).
190​
191### Read chat state inside a widget
192​
193Mapped components do not get `chat` as a prop. Call `useChatContext()` inside the widget. This also moves the composer into the layout: register it as `input`, then render `props.Input`.
194​
195```tsx
196import { createSignal } from 'solid-js'
197import { fetchServerSentEvents } from '@tanstack/ai-solid'
198import { createChatHook } from '@tanstack/ai-solid/ui'
199​
200const chatOptions = {
201 connection: fetchServerSentEvents('/api/chat'),
203​
204const { useAppChat, useChatContext } = createChatHook({
205 options: chatOptions,
206 components: {
207 input: () => {
208 const chat = useChatContext()
209 const [draft, setDraft] = createSignal('')
210 return (
211 <form
212 onSubmit={(event) => {
213 event.preventDefault()
214 void chat.sendMessage(draft())
215 setDraft('')
216 }}
217 >
218 <input
219 value={draft()}
220 disabled={chat.isLoading()}
221 onInput={(event) => setDraft(event.currentTarget.value)}
222 />
223 <button type="submit">Send</button>
224 </form>
225 )
226 },
227 layout: (props) => (
228 <main>
229 <props.Messages />
230 <props.Input />
231 </main>
232 ),
233 message: (props) => (
234 <article>
235 <props.Parts />
236 </article>
237 ),
238 },
239 partsComponents: {
240 text: (props) => <p>{props.part.content}</p>,
241 fallback: () => null,
242 },
243})
244​
245export function ChatScreen() {
246 const chat = useAppChat({ threadId: 'support-chat' })
247 return <chat.AppChat />
249```
250​
251In Solid, `chat.messages`, `chat.isLoading`, and `chat.error` are accessors. Call them, such as `chat.messages().length`. Call `useChatContext()` only inside `chat.AppChat`. A call outside that tree throws.
252​
253### Render markdown
254​
255Model replies arrive as markdown. Register `TextPart` from `@tanstack/ai-solid/ui` as the text part:
256​
257```tsx ignore
258import { TextPart } from '@tanstack/ai-solid/ui'
259​
260partsComponents: {
261 text: (props) => <TextPart content={props.part.content} />,
262 fallback: () => null,
263},
264```
265​
266`TextPart` uses [TanStack Markdown](https://tanstack.com/markdown). It escapes raw HTML and removes executable URLs. To color fenced code, read [Highlight markdown code](./markdown).
267​
268### Type a widget in its own file
269​
270Move a widget to its own file and type its props with `ToolProps`, `PartProps`, or `InterruptProps`. Pass `typeof chatOptions` and a name. Keep the `props` object so Solid can track it:
271​
272```tsx
273import { fetchServerSentEvents } from '@tanstack/ai-solid'
274import { createChatHook, type ToolProps } from '@tanstack/ai-solid/ui'
275import { toolDefinition } from '@tanstack/ai'
276import { z } from 'zod'
277​
278const getWeather = toolDefinition({
279 name: 'getWeather',
280 description: 'Look up weather',
281 inputSchema: z.object({ city: z.string() }),
282 outputSchema: z.object({ temperature: z.number() }),
283}).client()
284​
285const chatOptions = {
286 connection: fetchServerSentEvents('/api/chat'),
287 tools: [getWeather],
289​
290export function WeatherTool(
291 props: ToolProps<typeof chatOptions, 'getWeather'>,
292) {
293 return <strong>{props.part.input?.city}</strong>
295​
296export const { useAppChat } = createChatHook({
297 options: chatOptions,
298 components: {
299 layout: (props) => <props.Messages />,
300 message: (props) => (
301 <article>
302 <props.Parts />
303 </article>
304 ),
305 },
306 partsComponents: { fallback: () => null },
307 toolsComponents: { getWeather: WeatherTool },
308})
309```
310​
311Put `chatOptions` in a shared module so every widget file can import its type.
312​
313You now have a typed chat UI in Solid. Each widget is your own component.
314​
315## Advanced
316​
317### Slots and props
318​
319The config keys, part keys, and prop types are the same as in React. See [Every widget slot](./react#every-widget-slot). In Solid, `layout` gets `Messages`, `Interrupts`, and `Queue`, plus `Input` when you register `input`.
320​
321`useAppChat()` takes per-instance options: `threadId` (required), `initialMessages`, `live`, and `forwardedProps`.
322​
323### Approvals and generic interrupts
324​
325- A tool approval renders in the tool when you read `props.interrupt`.
326- To show it in the list instead, register a component under `interruptsComponents.tools` and render `props.Interrupts`.
327- Generic interrupts always render in the list. `generic.fallback` renders an unregistered id and an unbound interrupt. If the copy must be different, branch on `interrupt.kind === 'unbound'`.
328​
329### List `input` before `layout`
330​
331If `input` is an inline `function` expression written after `layout`, TypeScript cannot see that an input is registered. Then `Input` is missing from the layout props.
332​
333To prevent this, put `input` first, or use an arrow function or a named component. If it still slips through, `<props.Input />` without a registered `input` warns once in development.
334​
335### Widgets in other files
336​
337Call `createChatHookContexts()` in its own module. Pass `chatContext`, `partContext`, and `interruptContext` to `createChatHook` under `context`. Widget files then import `useChatContext` from the contexts module, with no circular import.
338​
339### Walk messages yourself
340​
341`createChatUI` is the lower-level kit. The `UI.Messages` render callback gets an accessor:
342​
343```tsx ignore
344<UI.Messages>{(messages) => <span>{messages().length}</span>}</UI.Messages>
345```
346​
347### `TextPart` options
348​
349- `highlighter`: a synchronous `CodeHighlighter`. Its output is trusted HTML, so use `createTanStackMarkdownHighlighter` or another highlighter that escapes source text.
350- `extensions`: more TanStack Markdown extensions. The streaming extension is always on.
351- `class`, `userClass`, `assistantClass`: classes for the wrapper. Pass `role` to apply the role class.
352​
353If you still pass `remarkPlugins`, `rehypePlugins`, `disableDefaultPlugins`, or `components`, read [TextPart markdown](../migration/text-part-markdown).