-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathvite.config.js
More file actions
166 lines (150 loc) · 6.38 KB
/
Copy pathvite.config.js
File metadata and controls
166 lines (150 loc) · 6.38 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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
// https://vite.dev/config/
export default defineConfig({
plugins: [
react(),
{
name: 'configure-server',
configureServer(server) {
server.middlewares.use(async (req, res, next) => {
if (req.url !== '/api/llm') {
return next();
}
// 处理 CORS 预检请求
if (req.method === 'OPTIONS') {
res.statusCode = 204;
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization, x-api-key, anthropic-version');
res.setHeader('Access-Control-Max-Age', '86400');
res.end();
return;
}
// 只处理 POST 请求
if (req.method !== 'POST') {
res.statusCode = 405;
res.end('Method not allowed');
return;
}
try {
let body = '';
req.on('data', chunk => body += chunk);
req.on('end', async () => {
try {
const data = JSON.parse(body);
const { provider, baseUrl, apiKey, messages, system, max_tokens, model, stream } = data;
console.log('[Local Proxy] 收到请求:', { provider, baseUrl, apiKey: apiKey ? apiKey.substring(0, 10) + '...' : 'null' });
if (!apiKey) {
console.error('[Local Proxy] API Key 为空');
res.statusCode = 400;
res.setHeader('Content-Type', 'application/json');
res.setHeader('Access-Control-Allow-Origin', '*');
res.end(JSON.stringify({ error: 'API Key 不能为空' }));
return;
}
// 根据 provider 构建请求
let targetUrl, headers, requestBody;
if (provider === 'anthropic') {
// 使用 Anthropic 原生格式
targetUrl = `${baseUrl.replace(/\/$/, '')}/messages`;
headers = {
'Content-Type': 'application/json',
'x-api-key': apiKey,
'anthropic-version': '2023-06-01',
};
requestBody = {
model: model || 'claude-sonnet-4-20250514',
max_tokens: max_tokens || 4000,
system,
messages,
stream: stream || false,
};
} else if (provider === 'openai' || provider === 'aliyun') {
// OpenAI 格式
targetUrl = `${baseUrl.replace(/\/$/, '')}/chat/completions`;
headers = {
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKey}`,
};
requestBody = {
model: model || 'gpt-4o-mini',
max_tokens: max_tokens || 4000,
messages: system ? [{ role: 'system', content: system }, ...messages] : messages,
temperature: 0.7,
stream: stream || false,
};
} else {
res.statusCode = 400;
res.setHeader('Content-Type', 'application/json');
res.setHeader('Access-Control-Allow-Origin', '*');
res.end(JSON.stringify({ error: `不支持的 provider: ${provider}` }));
return;
}
console.log('[Local Proxy] 转发请求到:', targetUrl);
console.log('[Local Proxy] Provider:', provider);
console.log('[Local Proxy] Headers:', { ...headers, 'x-api-key': headers['x-api-key'] ? '***' : undefined });
console.log('[Local Proxy] Request Body:', JSON.stringify(requestBody, null, 2));
const response = await fetch(targetUrl, {
method: 'POST',
headers,
body: JSON.stringify(requestBody),
});
console.log('[Local Proxy] 响应状态:', response.status, response.statusText);
console.log('[Local Proxy] 是否流式:', stream);
res.statusCode = response.status;
res.setHeader('Content-Type', response.headers.get('content-type') || 'application/json');
res.setHeader('Access-Control-Allow-Origin', '*');
// 处理流式响应
if (stream && response.ok) {
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
res.setHeader('Connection', 'keep-alive');
console.log('[Local Proxy] 使用流式传输');
const reader = response.body.getReader();
try {
while (true) {
const { done, value } = await reader.read();
if (done) break;
res.write(value);
}
res.end();
} catch (error) {
console.error('[Local Proxy] 流式传输错误:', error);
res.end();
}
return;
}
// 非流式响应:正常读取并返回
const responseData = await response.text();
res.end(responseData);
} catch (error) {
console.error('[Local Proxy] Error:', error);
res.statusCode = 500;
res.setHeader('Content-Type', 'application/json');
res.setHeader('Access-Control-Allow-Origin', '*');
res.end(JSON.stringify({ error: error.message }));
}
});
} catch (error) {
console.error('[Local Proxy] Error:', error);
res.statusCode = 500;
res.setHeader('Content-Type', 'application/json');
res.setHeader('Access-Control-Allow-Origin', '*');
res.end(JSON.stringify({ error: error.message }));
}
});
}
}
],
base: './',
build: {
outDir: 'dist',
assetsDir: 'assets',
sourcemap: true,
},
server: {
port: 5173,
host: true,
},
})