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

api.skills-chat.ts

121 lines4.5 KB

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.data || {}
42​
43 const provider: Provider = data.provider || 'openai'
44 const model: string | undefined = data.model
45 const threadId: string =
46 typeof data.threadId === 'string' && data.threadId.length > 0
47 ? data.threadId
48 : 'panel-default-thread'
49​
50 try {
51 const adapterConfig = {
52 anthropic: () =>
53 createChatOptions({
54 adapter: anthropicText((model || 'claude-sonnet-4-5') as any),
55 }),
56 gemini: () =>
57 createChatOptions({
58 adapter: geminiText((model || 'gemini-2.5-flash') as any),
59 }),
60 grok: () =>
61 createChatOptions({
62 adapter: grokText((model || 'grok-build-0.1') as any),
63 }),
64 ollama: () =>
65 createChatOptions({
66 adapter: ollamaText((model || 'mistral:7b') as any),
67 }),
68 openai: () =>
69 createChatOptions({
70 adapter: openaiText((model || 'gpt-4o') as any),
71 }),
72 openrouter: () =>
73 createChatOptions({
74 adapter: openRouterText((model || 'openai/gpt-4o') as any),
75 }),
76 }
77​
78 const options = adapterConfig[provider]()
79 const { adapter } = options
80​
81 // Record which skills the model loads so the inspector can show them.
82 const observer: ChatMiddleware = {
83 name: 'skills-observer',
84 onBeforeToolCall: (_ctx, hookCtx) => {
85 if (hookCtx.toolName === 'load_skill') {
86 const args = hookCtx.args
87 const name =
88 args && typeof args === 'object' && 'name' in args
89 ? String((args as { name: unknown }).name)
90 : undefined
91 if (name) recordActivation(threadId, name)
92 }
93 },
94 }
95​
96 const stream = chat({
97 ...options,
98 adapter,
99 systemPrompts: [SYSTEM_PROMPT],
100 tools: [createResourceTool(skillsSource)],
101 middleware: [withSkills(skillsSource), observer],
102 agentLoopStrategy: maxIterations(5),
103 messages,
104 abortController,
105 })
106​
107 return toServerSentEventsResponse(stream, { abortController })
108 } catch (error: any) {
109 console.error('[api.skills-chat] Error:', error?.message)
110 if (error.name === 'AbortError' || abortController.signal.aborted) {
111 return new Response(null, { status: 499 })
112 }
113 return new Response(
114 JSON.stringify({ error: error.message || 'An error occurred' }),
115 { status: 500, headers: { 'Content-Type': 'application/json' } },
116 )
117 }
118 },
119 },
120 },
121})