Open History to see the last commit
1import { createFileRoute } from '@tanstack/react-router'
2import {
3 chat,
4 createChatOptions,
5 maxIterations,
6 toServerSentEventsResponse,
7} from '@tanstack/ai'
8import { anthropicText } from '@tanstack/ai-anthropic'
9import { geminiText } from '@tanstack/ai-gemini'
10import { grokText } from '@tanstack/ai-grok'
11import { openaiText } from '@tanstack/ai-openai'
12import { ollamaText } from '@tanstack/ai-ollama'
13import { openRouterText } from '@tanstack/ai-openrouter'
14import { createResourceTool, withSkills } from '@tanstack/ai-skills'
15import { recordActivation, skillsSource } from '@/lib/skills-store'
16import type { ChatMiddleware } from '@tanstack/ai'
17import type { Provider } from '@/lib/model-selection'
18
19const SYSTEM_PROMPT = `You are a helpful assistant with a library of skills.
20
21A catalog of available skills is provided. When the user's request matches a
22skill, call the load_skill tool to load its instructions, then follow them for
23your answer. If no skill fits, just answer normally.`
24
25/**
26 * Chat endpoint for the `/skills` demo. Wires `withSkills` over the demo
27 * `skills/` folder so the model can load a skill (pirate-speak, haiku,
28 * emoji-storyteller) on demand. A tiny observer middleware records each
29 * load_skill activation per thread so the inspector at /api/skills-inspect can
30 * highlight what was loaded.
31 */
32export const Route = createFileRoute('/api/skills-chat')({
33 server: {
34 handlers: {
35 POST: async ({ request }) => {
36 if (request.signal.aborted) return new Response(null, { status: 499 })
37
38 const abortController = new AbortController()
39 const body = await request.json()
40 const messages = body.messages
41 const data = body.forwardedProps || {}
42
43 const provider: Provider = data.provider || 'openai'
44 const model: string | undefined = data.model
45 const threadId: string = body.threadId
46
47 try {
48 const adapterConfig = {
49 anthropic: () =>
50 createChatOptions({
51 adapter: anthropicText((model || 'claude-sonnet-4-5') as any),
52 }),
53 gemini: () =>
54 createChatOptions({
55 adapter: geminiText((model || 'gemini-2.5-flash') as any),
56 }),
57 grok: () =>
58 createChatOptions({
59 adapter: grokText((model || 'grok-build-0.1') as any),
60 }),
61 ollama: () =>
62 createChatOptions({
63 adapter: ollamaText((model || 'mistral:7b') as any),
64 }),
65 openai: () =>
66 createChatOptions({
67 adapter: openaiText((model || 'gpt-4o') as any),
68 }),
69 openrouter: () =>
70 createChatOptions({
71 adapter: openRouterText((model || 'openai/gpt-4o') as any),
72 }),
73 }
74
75 const options = adapterConfig[provider]()
76 const { adapter } = options
77
78 // Record which skills the model loads so the inspector can show them.
79 const observer: ChatMiddleware = {
80 name: 'skills-observer',
81 onBeforeToolCall: (_ctx, hookCtx) => {
82 if (hookCtx.toolName === 'load_skill') {
83 const args = hookCtx.args
84 const name =
85 args && typeof args === 'object' && 'name' in args
86 ? String((args as { name: unknown }).name)
87 : undefined
88 if (name) recordActivation(threadId, name)
89 }
90 },
91 }
92
93 const stream = chat({
94 ...options,
95 threadId,
96 adapter,
97 systemPrompts: [SYSTEM_PROMPT],
98 tools: [createResourceTool(skillsSource)],
99 middleware: [withSkills(skillsSource), observer],
100 agentLoopStrategy: maxIterations(5),
101 messages,
102 abortController,
103 })
104
105 return toServerSentEventsResponse(stream, { abortController })
106 } catch (error: any) {
107 console.error('[api.skills-chat] Error:', error?.message)
108 if (error.name === 'AbortError' || abortController.signal.aborted) {
109 return new Response(null, { status: 499 })
110 }
111 return new Response(
112 JSON.stringify({ error: error.message || 'An error occurred' }),
113 { status: 500, headers: { 'Content-Type': 'application/json' } },
114 )
115 }
116 },
117 },
118 },
119})