Open History to see the last commit
1import { createFileRoute } from '@tanstack/react-router'
2import {
3 EventType,
4 chat,
5 chatParamsFromRequestBody,
6 createCapability,
7 createChatMiddleware,
8 createChatOptions,
9 defineChatMiddleware,
10 toServerSentEventsResponse,
11} from '@tanstack/ai'
12import { openaiText } from '@tanstack/ai-openai'
13import type { ChatMiddleware, StreamChunk } from '@tanstack/ai'
14
15/**
16 * Capability middleware demo.
17 *
18 * Shows the new capability primitives end-to-end:
19 * - `createCapability<T>()('name')` returns a `[get, provide]` tuple that is
20 * also its own identity for `requires`/`provides`.
21 * - a PROVIDER middleware supplies the value in `setup` (runs first),
22 * - a CONSUMER middleware reads it in `onConfig` and injects a system prompt,
23 * - `chat()` validates coverage. With the provider present we wire the
24 * middleware through the type-safe `createChatMiddleware().use().build()`
25 * builder (compile-time order check). With it absent we pass a plain
26 * middleware array, so `chat()` throws the runtime validation error.
27 */
28
29// The capability: a "persona" string the assistant should adopt. The value
30// type is explicit; the name literal is inferred from the argument.
31const personaCapability = createCapability<string>()('demo-persona')
32const [getPersona, providePersona] = personaCapability
33
34function readForwardedString(value: unknown, fallback: string): string {
35 return typeof value === 'string' && value.trim() ? value : fallback
36}
37
38export const Route = createFileRoute('/api/capability-demo')({
39 server: {
40 handlers: {
41 POST: async ({ request }) => {
42 const abortController = new AbortController()
43
44 let params
45 try {
46 params = await chatParamsFromRequestBody(await request.json())
47 } catch (error) {
48 return new Response(
49 error instanceof Error ? error.message : 'Bad request',
50 { status: 400 },
51 )
52 }
53
54 const persona = readForwardedString(
55 params.forwardedProps.capabilityValue,
56 'a cheerful pirate captain',
57 )
58 // When false, the provider middleware is omitted so the consumer's
59 // `requires: [personaCapability]` is unmet — demonstrating the runtime
60 // validation error.
61 const provideCapability =
62 params.forwardedProps.provideCapability !== false
63
64 // PROVIDER — supplies the persona capability in `setup` (runs first,
65 // before `onConfig`, so later middleware can consume it).
66 const personaProvider = defineChatMiddleware({
67 name: 'persona-provider',
68 provides: [personaCapability],
69 setup(ctx) {
70 providePersona(ctx, persona)
71 },
72 })
73
74 // CONSUMER — reads the persona in `onConfig` and injects a system
75 // prompt. `getPersona(ctx)` is typed `string` (throws if unprovided).
76 const personaConsumer = defineChatMiddleware({
77 name: 'persona-consumer',
78 requires: [personaCapability],
79 onConfig(ctx, config) {
80 const activePersona = getPersona(ctx)
81 return {
82 systemPrompts: [
83 ...config.systemPrompts,
84 `You are ${activePersona}. Stay fully in character for the entire reply, and open by introducing yourself in that persona.`,
85 ],
86 }
87 },
88 })
89
90 try {
91 const options = createChatOptions({
92 adapter: openaiText('gpt-5.5'),
93 threadId: params.threadId,
94 })
95
96 if (provideCapability) {
97 // Happy path: the order-aware builder enforces provider-before-
98 // consumer at COMPILE time and accumulates the provided set.
99 const stream = chat({
100 ...options,
101 middleware: createChatMiddleware()
102 .use(personaProvider)
103 .use(personaConsumer)
104 .use({
105 name: 'logging-middleware',
106 onConfig(_ctx, config) {
107 console.log('onConfig', { config })
108 return config
109 },
110 })
111 .build(),
112 messages: params.messages,
113 threadId: params.threadId,
114 runId: params.runId,
115 abortController,
116 })
117 return toServerSentEventsResponse(stream, { abortController })
118 }
119
120 // Omit path: a plain `ChatMiddleware[]` (widened, so the compile-time
121 // coverage check can't prove the gap) — the unmet `requires` is caught
122 // by `chat()`'s RUNTIME validation, which throws and is surfaced below.
123 const middleware: Array<ChatMiddleware> = [personaConsumer]
124 const stream = chat({
125 ...options,
126 middleware,
127 messages: params.messages,
128 threadId: params.threadId,
129 runId: params.runId,
130 abortController,
131 })
132 return toServerSentEventsResponse(stream, { abortController })
133 } catch (error) {
134 // Surface the message (capability validation error when the provider
135 // is omitted, or a missing-API-key error) as an SSE RUN_ERROR so the
136 // client shows the real text instead of a generic "HTTP 500".
137 const message =
138 error instanceof Error ? error.message : 'An error occurred'
139 const errorStream = (async function* (): AsyncGenerator<StreamChunk> {
140 yield {
141 type: EventType.RUN_ERROR,
142 message,
143 timestamp: Date.now(),
144 error: { message },
145 }
146 })()
147 return toServerSentEventsResponse(errorStream, { abortController })
148 }
149 },
150 },
151 },
152})