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 { memoryMiddleware } from '@tanstack/ai-memory'
9import { anthropicText } from '@tanstack/ai-anthropic'
10import { geminiText } from '@tanstack/ai-gemini'
11import { grokText } from '@tanstack/ai-grok'
12import { openaiText } from '@tanstack/ai-openai'
13import { ollamaText } from '@tanstack/ai-ollama'
14import { openRouterText } from '@tanstack/ai-openrouter'
15import {
16 lastRecallByThread,
17 memoryAdapter,
18 panelMemoryScope,
19 panelScopeKey,
20} from '@/lib/memory-store'
21import type { Provider } from '@/lib/model-selection'
22
23const SYSTEM_PROMPT = `You are a helpful, friendly assistant with long-term memory.
24
25Earlier facts the user shared may be injected into your system prompt under a
26"memory" heading. When they are, use them to answer — for example, if the user
27tells you their name in one turn and asks for it in a later turn, recall it from
28memory rather than saying you don't know.`
29
30/**
31 * Chat endpoint for the `/memory` demo. Identical in spirit to `/api/chat`,
32 * minus the guitar tools and trace recording, plus a `memoryMiddleware` wired
33 * to the shared {@link memoryAdapter} singleton so recall/save persist across
34 * requests. The middleware is built per request with a static scope derived
35 * from a client-supplied `threadId` plus server-trusted user/tenant constants
36 * (demo-only — production must derive every Scope field from validated session
37 * state, never from the request body alone).
38 */
39export const Route = createFileRoute('/api/memory-chat')({
40 server: {
41 handlers: {
42 POST: async ({ request }) => {
43 const requestSignal = request.signal
44 if (requestSignal.aborted) {
45 return new Response(null, { status: 499 })
46 }
47
48 const abortController = new AbortController()
49 const body = await request.json()
50 const messages = body.messages
51 const data = body.forwardedProps || {}
52
53 const provider: Provider = data.provider || 'openai'
54 const model: string | undefined = data.model
55 // threadId comes from the client for multi-thread demo UX; user and
56 // tenant are always server-side constants (see panelMemoryScope).
57 const threadId: string = body.threadId
58 const scope = panelMemoryScope(threadId)
59
60 try {
61 const adapterConfig = {
62 anthropic: () =>
63 createChatOptions({
64 adapter: anthropicText((model || 'claude-sonnet-4-5') as any),
65 }),
66 gemini: () =>
67 createChatOptions({
68 adapter: geminiText((model || 'gemini-2.5-flash') as any),
69 }),
70 grok: () =>
71 createChatOptions({
72 adapter: grokText((model || 'grok-build-0.1') as any),
73 }),
74 ollama: () =>
75 createChatOptions({
76 adapter: ollamaText((model || 'mistral:7b') as any),
77 }),
78 openai: () =>
79 createChatOptions({
80 adapter: openaiText((model || 'gpt-4o') as any),
81 }),
82 openrouter: () =>
83 createChatOptions({
84 adapter: openRouterText((model || 'openai/gpt-4o') as any),
85 }),
86 }
87
88 const options = adapterConfig[provider]()
89 const { adapter } = options
90
91 console.log(
92 `>> memory chat: model ${model} on ${provider} (thread ${threadId})`,
93 )
94
95 const memory = memoryMiddleware({
96 adapter: memoryAdapter,
97 scope,
98 onRecall: (info) => {
99 lastRecallByThread.set(panelScopeKey(scope), info.result)
100 },
101 })
102
103 const stream = chat({
104 ...options,
105 threadId,
106 adapter,
107 tools: [],
108 systemPrompts: [SYSTEM_PROMPT],
109 middleware: [memory],
110 agentLoopStrategy: maxIterations(5),
111 messages,
112 abortController,
113 })
114
115 return toServerSentEventsResponse(stream, { abortController })
116 } catch (error: any) {
117 console.error('[api.memory-chat] Error:', error?.message)
118 if (error.name === 'AbortError' || abortController.signal.aborted) {
119 return new Response(null, { status: 499 })
120 }
121 return new Response(
122 JSON.stringify({ error: error.message || 'An error occurred' }),
123 {
124 status: 500,
125 headers: { 'Content-Type': 'application/json' },
126 },
127 )
128 }
129 },
130 },
131 },
132})