-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchat.ts
More file actions
59 lines (48 loc) · 1.61 KB
/
Copy pathchat.ts
File metadata and controls
59 lines (48 loc) · 1.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import { Router, Request, Response } from 'express'
import { getAnthropicClient } from '../services/claude'
import { supabase } from '../services/supabase'
const router = Router()
router.post('/', async (req: Request, res: Response) => {
const { messages, systemPrompt, sessionId } = req.body
if (!messages || !systemPrompt) {
res.status(400).json({ error: 'messages and systemPrompt are required' })
return
}
// Set headers so the browser knows this is a streaming text response
res.setHeader('Content-Type', 'text/event-stream')
res.setHeader('Cache-Control', 'no-cache')
res.setHeader('Connection', 'keep-alive')
try {
const anthropic = getAnthropicClient(req.headers['x-api-key'] as string | undefined)
const stream = anthropic.messages.stream({
model: 'claude-sonnet-4-6',
max_tokens: 2048,
system: systemPrompt,
messages,
})
let fullResponse = ''
// Send each chunk to the frontend as it arrives
for await (const chunk of stream) {
if (
chunk.type === 'content_block_delta' &&
chunk.delta.type === 'text_delta'
) {
fullResponse += chunk.delta.text
res.write(chunk.delta.text)
}
}
// Save the assistant response to the database if we have a session
if (sessionId) {
await supabase.from('messages').insert({
session_id: sessionId,
role: 'assistant',
content: fullResponse,
})
}
res.end()
} catch (error) {
console.error('Claude API error:', error)
res.status(500).json({ error: 'Failed to get response from Claude' })
}
})
export default router