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

headless-ui.tsx

267 lines7.1 KB

1import { useEffect, useState } from 'react'
2import { createFileRoute } from '@tanstack/react-router'
3import {
4 defineInterrupt,
5 hashSchemaInput,
6 INTERRUPT_BINDING_VERSION,
7 normalizeApprovalSchema,
8 toolDefinition,
9} from '@tanstack/ai'
10import { useChat } from '@tanstack/ai-react'
11import { createChatHookContexts, createChatUI } from '@tanstack/ai-react/ui'
12import { EventType } from '@tanstack/ai/client'
13import type { ChatFetcher } from '@tanstack/ai-client'
14import { z } from 'zod'
15​
16const purchaseItem = toolDefinition({
17 name: 'purchaseItem',
18 description: 'Purchase an item',
19 needsApproval: true,
20 inputSchema: z.object({ item: z.string() }),
21 outputSchema: z.object({ ok: z.boolean() }),
22}).client(async () => ({ ok: true }))
23​
24const purchaseApproval = normalizeApprovalSchema(
25 purchaseItem.approvalSchema,
26 purchaseItem.inputSchema,
28​
29const fetcher: ChatFetcher = async function* (input) {
30 const runId = input.runId
31 const threadId = input.threadId
32 const messageId = 'asst-headless'
33 if (input.resume && input.resume.length > 0) {
34 yield {
35 type: EventType.RUN_STARTED,
36 runId,
37 threadId,
38 timestamp: Date.now(),
39 }
40 yield {
41 type: EventType.TOOL_CALL_RESULT,
42 toolCallId: 'call-purchase',
43 messageId,
44 content: '{"ok":true}',
45 timestamp: Date.now(),
46 }
47 yield {
48 type: EventType.RUN_FINISHED,
49 runId,
50 threadId,
51 timestamp: Date.now(),
52 outcome: { type: 'success' },
53 }
54 return
55 }
56 yield {
57 type: EventType.RUN_STARTED,
58 runId,
59 threadId,
60 timestamp: Date.now(),
61 }
62 yield {
63 type: EventType.TEXT_MESSAGE_START,
64 messageId,
65 role: 'assistant',
66 timestamp: Date.now(),
67 }
68 yield {
69 type: EventType.TOOL_CALL_START,
70 toolCallId: 'call-purchase',
71 toolCallName: 'purchaseItem',
72 parentMessageId: messageId,
73 timestamp: Date.now(),
74 }
75 yield {
76 type: EventType.TOOL_CALL_ARGS,
77 toolCallId: 'call-purchase',
78 delta: '{"item":"keyboard"}',
79 timestamp: Date.now(),
80 }
81 yield {
82 type: EventType.TOOL_CALL_END,
83 toolCallId: 'call-purchase',
84 timestamp: Date.now(),
85 }
86 yield {
87 type: EventType.TEXT_MESSAGE_END,
88 messageId,
89 timestamp: Date.now(),
90 }
91 yield {
92 type: EventType.RUN_FINISHED,
93 runId,
94 threadId,
95 timestamp: Date.now(),
96 outcome: {
97 type: 'interrupt',
98 interrupts: [
99 {
100 id: 'approval-purchase',
101 reason: 'tool_call',
102 toolCallId: 'call-purchase',
103 message: 'Approve purchase',
104 metadata: {
105 kind: 'approval',
106 toolName: 'purchaseItem',
107 'tanstack:interruptBinding': {
108 v: INTERRUPT_BINDING_VERSION,
109 kind: 'tool-approval',
110 interruptId: 'approval-purchase',
111 interruptedRunId: runId,
112 generation: 0,
113 toolName: 'purchaseItem',
114 toolCallId: 'call-purchase',
115 originalArgs: { item: 'keyboard' },
116 inputSchemaHash: hashSchemaInput(purchaseItem.inputSchema),
117 approvalSchemaHash: purchaseApproval.approvalSchemaHash,
118 responseSchemaHash: purchaseApproval.responseSchemaHash,
119 },
120 },
121 },
122 ],
123 },
124 }
126​
127const chatOptions = {
128 tools: [purchaseItem],
129 initialMessages: [
130 {
131 id: 'seed-orphan',
132 role: 'assistant' as const,
133 parts: [
134 {
135 type: 'tool-result' as const,
136 toolCallId: 'orphan-result',
137 content: 'standalone-result',
138 state: 'complete' as const,
139 },
140 ],
141 },
142 ],
143 interrupts: [
144 defineInterrupt({
145 id: 'choosePlan',
146 payloadSchema: z.object({ title: z.string() }),
147 responseSchema: z.string(),
148 }),
149 ],
150 fetcher,
152​
153// Counts mounts of the purchase tool widget. The `Parts` component handed to
154// `message` must be one stable reference, so this stays at 1 for the life of a
155// message no matter how many chunks arrive.
156let purchaseToolMounts = 0
157​
158// Standalone contexts instead of `UI.useChatContext()`: referencing `UI`
159// inside its own config is circular and blocks `input` inference.
160const { chatContext, partContext, interruptContext, useChatContext } =
161 createChatHookContexts()
162​
163const UI = createChatUI(chatOptions, {
164 context: {
165 chatContext,
166 partContext,
167 interruptContext,
168 },
169 components: {
170 input: function ChatComposer() {
171 const chat = useChatContext()
172 const [ready, setReady] = useState(false)
173 useEffect(() => {
174 setReady(true)
175 }, [])
176 return (
177 <form
178 onSubmit={(event) => {
179 event.preventDefault()
180 const field = event.currentTarget.elements.namedItem('message')
181 if (!(field instanceof HTMLInputElement)) return
182 const text = field.value.trim()
183 if (!text) return
184 field.value = ''
185 void chat.sendMessage(text)
186 }}
187 >
188 <label>
189 Message
190 <input
191 aria-label="Message"
192 name="message"
193 data-testid="chat-input"
194 />
195 </label>
196 <button type="submit" data-testid="send-button" disabled={!ready}>
197 Send
198 </button>
199 </form>
200 )
201 },
202 layout: ({ Messages, Interrupts, Input }) => {
203 const chat = useChatContext()
204 return (
205 <main>
206 {chat.error ? (
207 <pre data-testid="chat-error">{chat.error.message}</pre>
208 ) : null}
209 <Messages />
210 <Interrupts />
211 <Input />
212 </main>
213 )
214 },
215 message: ({ Parts }) => (
216 <article>
217 <Parts />
218 </article>
219 ),
220 },
221 partsComponents: {
222 text: ({ part }) => (part.type === 'text' ? <p>{part.content}</p> : null),
223 toolResult: ({ part }) =>
224 part.type === 'tool-result' ? (
225 <div data-testid="standalone-tool-result">{String(part.content)}</div>
226 ) : null,
227 fallback: () => null,
228 },
229 toolsComponents: {
230 purchaseItem: function PurchaseTool({ part, interrupt }) {
231 // Stamped once per mount. The stream re-renders this widget on every
232 // chunk, so a rebuilt `Parts` would remount the subtree and bump this.
233 const [mountSeq] = useState(() => ++purchaseToolMounts)
234 return (
235 <div data-testid="purchase-tool" data-mount-seq={mountSeq}>
236 {part.input?.item}
237 {interrupt?.status === 'pending' ? (
238 <button
239 data-testid="purchase-approval"
240 type="button"
241 onClick={() => interrupt.resolveInterrupt(true)}
242 >
243 Approve purchase
244 </button>
245 ) : null}
246 {part.output ? (
247 <div data-testid="purchase-output">
248 {part.output.ok ? 'approved' : 'denied'}
249 </div>
250 ) : null}
251 </div>
252 )
253 },
254 },
255 interruptsComponents: {
256 generic: { choosePlan: () => null, fallback: () => null },
257 },
258})
259​
260function HeadlessUIPage() {
261 const chat = useChat(chatOptions)
262 return <UI.Chat chat={chat} />
264​
265export const Route = createFileRoute('/headless-ui')({
266 component: HeadlessUIPage,
267})