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

api.capability-demo.ts

151 lines5.6 KB

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
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 })
94​
95 if (provideCapability) {
96 // Happy path: the order-aware builder enforces provider-before-
97 // consumer at COMPILE time and accumulates the provided set.
98 const stream = chat({
99 ...options,
100 middleware: createChatMiddleware()
101 .use(personaProvider)
102 .use(personaConsumer)
103 .use({
104 name: 'logging-middleware',
105 onConfig(_ctx, config) {
106 console.log('onConfig', { config })
107 return config
108 },
109 })
110 .build(),
111 messages: params.messages,
112 threadId: params.threadId,
113 runId: params.runId,
114 abortController,
115 })
116 return toServerSentEventsResponse(stream, { abortController })
117 }
118​
119 // Omit path: a plain `ChatMiddleware[]` (widened, so the compile-time
120 // coverage check can't prove the gap) — the unmet `requires` is caught
121 // by `chat()`'s RUNTIME validation, which throws and is surfaced below.
122 const middleware: Array<ChatMiddleware> = [personaConsumer]
123 const stream = chat({
124 ...options,
125 middleware,
126 messages: params.messages,
127 threadId: params.threadId,
128 runId: params.runId,
129 abortController,
130 })
131 return toServerSentEventsResponse(stream, { abortController })
132 } catch (error) {
133 // Surface the message (capability validation error when the provider
134 // is omitted, or a missing-API-key error) as an SSE RUN_ERROR so the
135 // client shows the real text instead of a generic "HTTP 500".
136 const message =
137 error instanceof Error ? error.message : 'An error occurred'
138 const errorStream = (async function* (): AsyncGenerator<StreamChunk> {
139 yield {
140 type: EventType.RUN_ERROR,
141 message,
142 timestamp: Date.now(),
143 error: { message },
144 }
145 })()
146 return toServerSentEventsResponse(errorStream, { abortController })
147 }
148 },
149 },
150 },
151})