akhaliq HF Staff commited on
Commit
2883812
·
verified ·
1 Parent(s): 3824d5a

Upload pages/api/chat.js with huggingface_hub

Browse files
Files changed (1) hide show
  1. pages/api/chat.js +82 -0
pages/api/chat.js ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { OpenAI } from 'openai'
2
+
3
+ const client = new OpenAI({
4
+ baseURL: 'https://router.huggingface.co/v1',
5
+ apiKey: process.env.HF_TOKEN,
6
+ })
7
+
8
+ export default async function handler(req, res) {
9
+ if (req.method !== 'POST') {
10
+ return res.status(405).json({ error: 'Method not allowed' })
11
+ }
12
+
13
+ try {
14
+ const { messages } = req.body
15
+
16
+ if (!messages || !Array.isArray(messages)) {
17
+ return res.status(400).json({ error: 'Messages array is required' })
18
+ }
19
+
20
+ // Transform messages to OpenAI format
21
+ const openAIMessages = messages.map(msg => {
22
+ if (msg.image) {
23
+ return {
24
+ role: msg.role,
25
+ content: [
26
+ {
27
+ type: 'text',
28
+ text: msg.content || 'Analyze this image'
29
+ },
30
+ {
31
+ type: 'image_url',
32
+ image_url: {
33
+ url: msg.image
34
+ }
35
+ }
36
+ ]
37
+ }
38
+ }
39
+ return {
40
+ role: msg.role,
41
+ content: msg.content
42
+ }
43
+ })
44
+
45
+ // Create streaming response
46
+ res.writeHead(200, {
47
+ 'Content-Type': 'text/event-stream',
48
+ 'Cache-Control': 'no-cache',
49
+ 'Connection': 'keep-alive',
50
+ 'Access-Control-Allow-Origin': '*',
51
+ 'Access-Control-Allow-Headers': 'Cache-Control',
52
+ })
53
+
54
+ try {
55
+ const stream = await client.chat.completions.create({
56
+ model: 'Qwen/Qwen3-VL-8B-Instruct:novita',
57
+ messages: openAIMessages,
58
+ stream: true,
59
+ max_tokens: 1000,
60
+ temperature: 0.7,
61
+ })
62
+
63
+ for await (const chunk of stream) {
64
+ const content = chunk.choices[0]?.delta?.content || ''
65
+ if (content) {
66
+ res.write(`data: ${JSON.stringify({ content })}\n\n`)
67
+ }
68
+ }
69
+
70
+ res.write('data: [DONE]\n\n')
71
+ res.end()
72
+ } catch (streamError) {
73
+ console.error('Streaming error:', streamError)
74
+ res.write(`data: ${JSON.stringify({ error: streamError.message })}\n\n`)
75
+ res.end()
76
+ }
77
+
78
+ } catch (error) {
79
+ console.error('API error:', error)
80
+ res.status(500).json({ error: error.message || 'Internal server error' })
81
+ }
82
+ }