akhaliq HF Staff commited on
Commit
819d504
·
verified ·
1 Parent(s): fd2c3f5

Upload pages/api/chat.js with huggingface_hub

Browse files
Files changed (1) hide show
  1. pages/api/chat.js +64 -0
pages/api/chat.js ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { OpenAI } from 'openai'
2
+
3
+ export default async function handler(req, res) {
4
+ if (req.method !== 'POST') {
5
+ return res.status(405).json({ error: 'Method not allowed' })
6
+ }
7
+
8
+ try {
9
+ const { messages, stream = true } = req.body
10
+
11
+ if (!process.env.HF_TOKEN) {
12
+ return res.status(500).json({ error: 'HF_TOKEN environment variable is not set' })
13
+ }
14
+
15
+ const client = new OpenAI({
16
+ baseURL: "https://router.huggingface.co/v1",
17
+ apiKey: process.env.HF_TOKEN,
18
+ defaultHeaders: {
19
+ "X-HF-Bill-To": "huggingface"
20
+ }
21
+ })
22
+
23
+ if (stream) {
24
+ // Set headers for streaming response
25
+ res.setHeader('Content-Type', 'text/plain')
26
+ res.setHeader('Cache-Control', 'no-cache')
27
+ res.setHeader('Connection', 'keep-alive')
28
+
29
+ const stream = await client.chat.completions.create({
30
+ model: "Qwen/Qwen3-VL-30B-A3B-Instruct:novita",
31
+ messages,
32
+ stream: true,
33
+ })
34
+
35
+ try {
36
+ for await (const chunk of stream) {
37
+ const delta = chunk.choices?.[0]?.delta?.content
38
+ if (delta) {
39
+ res.write(`data: ${JSON.stringify(chunk)}\n\n`)
40
+ }
41
+ }
42
+ res.write(`data: [DONE]\n\n`)
43
+ } catch (error) {
44
+ console.error('Streaming error:', error)
45
+ res.write(`data: ${JSON.stringify({ error: error.message })}\n\n`)
46
+ } finally {
47
+ res.end()
48
+ }
49
+ } else {
50
+ const completion = await client.chat.completions.create({
51
+ model: "Qwen/Qwen3-VL-30B-A3B-Instruct:novita",
52
+ messages,
53
+ stream: false,
54
+ })
55
+
56
+ res.status(200).json(completion)
57
+ }
58
+ } catch (error) {
59
+ console.error('API Error:', error)
60
+ res.status(500).json({
61
+ error: error.message || 'Internal server error'
62
+ })
63
+ }
64
+ }