Merge branch 'binary-test' into binary-build
Browse files- public/index.html +18 -11
- public/style.css +52 -20
- src/api/client.js +28 -15
- src/server/index.js +513 -3
- src/utils/httpClient.js +7 -0
- src/utils/utils.js +868 -1
public/index.html
CHANGED
|
@@ -27,17 +27,24 @@
|
|
| 27 |
})();
|
| 28 |
</script>
|
| 29 |
<style>
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 41 |
</style>
|
| 42 |
<!-- 主样式表 - 优先加载 -->
|
| 43 |
<link rel="stylesheet" href="style.css">
|
|
|
|
| 27 |
})();
|
| 28 |
</script>
|
| 29 |
<style>
|
| 30 |
+
/* 防止闪烁的关键样式 - 来自 binary-build */
|
| 31 |
+
html:not(.auth-ready) #loginForm,
|
| 32 |
+
html:not(.auth-ready) #mainContent { visibility: hidden; }
|
| 33 |
+
/* 登录状态显示控制 - 合并两个分支 *
|
| 34 |
+
.logged-in #loginForm { display: none !important; }
|
| 35 |
+
.logged-in #mainContent { display: flex !important; }
|
| 36 |
+
html:not(.logged-in) #mainContent { display: none !important; }
|
| 37 |
+
/* Tab状态管理 - 来自 binary-build */
|
| 38 |
+
html.tab-settings #tokensPage { display: none !important; }
|
| 39 |
+
html.tab-settings #settingsPage { display: block !important; }
|
| 40 |
+
html.tab-settings .tab[data-tab="tokens"] {
|
| 41 |
+
background: transparent !important;
|
| 42 |
+
color: var(--text-light, #888) !important;
|
| 43 |
+
}
|
| 44 |
+
html.tab-settings .tab[data-tab="settings"] {
|
| 45 |
+
background: var(--primary, #4f46e5) !important;
|
| 46 |
+
color: white !important;
|
| 47 |
+
}
|
| 48 |
</style>
|
| 49 |
<!-- 主样式表 - 优先加载 -->
|
| 50 |
<link rel="stylesheet" href="style.css">
|
public/style.css
CHANGED
|
@@ -93,7 +93,8 @@ body {
|
|
| 93 |
background: var(--bg);
|
| 94 |
color: var(--text);
|
| 95 |
line-height: 1.5;
|
| 96 |
-
|
|
|
|
| 97 |
font-size: 1rem;
|
| 98 |
/* 字体渲染优化 */
|
| 99 |
-webkit-font-smoothing: antialiased;
|
|
@@ -117,18 +118,20 @@ code, pre, .mono, .token-display {
|
|
| 117 |
font-family: 'Ubuntu Mono', 'Consolas', 'Monaco', monospace !important;
|
| 118 |
}
|
| 119 |
|
| 120 |
-
.container {
|
| 121 |
-
max-width: 1400px;
|
| 122 |
-
margin: 0 auto;
|
| 123 |
-
padding: 0.5rem;
|
| 124 |
-
height: 100vh;
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
justify-content: center;
|
|
|
|
| 128 |
}
|
| 129 |
|
| 130 |
/* 登录表单 */
|
| 131 |
.login-form {
|
|
|
|
| 132 |
background: rgba(255, 255, 255, 0.6);
|
| 133 |
backdrop-filter: blur(24px) saturate(180%);
|
| 134 |
-webkit-backdrop-filter: blur(24px) saturate(180%);
|
|
@@ -215,6 +218,7 @@ button.loading::after {
|
|
| 215 |
|
| 216 |
/* 主内容区 */
|
| 217 |
.main-content {
|
|
|
|
| 218 |
background: rgba(255, 255, 255, 0.6);
|
| 219 |
backdrop-filter: blur(24px) saturate(180%);
|
| 220 |
-webkit-backdrop-filter: blur(24px) saturate(180%);
|
|
@@ -226,6 +230,7 @@ button.loading::after {
|
|
| 226 |
display: flex;
|
| 227 |
flex-direction: column;
|
| 228 |
border: 1px solid rgba(255, 255, 255, 0.5);
|
|
|
|
| 229 |
}
|
| 230 |
@media (prefers-color-scheme: dark) {
|
| 231 |
.main-content {
|
|
@@ -285,7 +290,24 @@ button.loading::after {
|
|
| 285 |
.content {
|
| 286 |
padding: 1rem;
|
| 287 |
flex: 1;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 288 |
overflow-y: auto;
|
|
|
|
| 289 |
}
|
| 290 |
|
| 291 |
/* 顶部栏 - 统计+操作 */
|
|
@@ -298,6 +320,7 @@ button.loading::after {
|
|
| 298 |
border-radius: 0.75rem;
|
| 299 |
margin-bottom: 1rem;
|
| 300 |
border: 1.5px solid var(--border);
|
|
|
|
| 301 |
}
|
| 302 |
@media (prefers-color-scheme: dark) {
|
| 303 |
.top-bar {
|
|
@@ -363,6 +386,12 @@ button.loading::after {
|
|
| 363 |
display: grid;
|
| 364 |
grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
|
| 365 |
gap: 0.75rem;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 366 |
}
|
| 367 |
.token-card {
|
| 368 |
background: rgba(255, 255, 255, 0.6);
|
|
@@ -706,6 +735,7 @@ button.loading::after {
|
|
| 706 |
box-shadow: 0 16px 48px rgba(0,0,0,0.2);
|
| 707 |
animation: scaleIn 0.2s;
|
| 708 |
border: 1px solid rgba(255, 255, 255, 0.5);
|
|
|
|
| 709 |
}
|
| 710 |
@media (prefers-color-scheme: dark) {
|
| 711 |
.modal-content {
|
|
@@ -741,14 +771,15 @@ button.loading::after {
|
|
| 741 |
.form-modal .modal-content { max-width: 480px; }
|
| 742 |
.form-modal input { margin-bottom: 0.75rem; }
|
| 743 |
.form-modal .form-row { display: flex; flex-direction: column; gap: 0.75rem; margin-bottom: 1rem; }
|
| 744 |
-
.form-modal .oauth-steps {
|
| 745 |
-
background: rgba(59,130,246,0.1);
|
| 746 |
-
padding: 0.875rem;
|
| 747 |
-
border-radius: 0.5rem;
|
| 748 |
-
margin-bottom: 1rem;
|
| 749 |
-
border: 1.5px solid var(--info);
|
|
|
|
| 750 |
}
|
| 751 |
-
.form-modal .oauth-steps p { margin-bottom: 0.5rem; font-size: 0.8rem; }
|
| 752 |
.form-modal .oauth-steps p:last-child { margin-bottom: 0; }
|
| 753 |
|
| 754 |
@keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
|
|
@@ -1026,6 +1057,7 @@ input:checked + .slider:before {
|
|
| 1026 |
border: 1.5px solid var(--border);
|
| 1027 |
transition: transform 0.15s ease, box-shadow 0.15s ease, border-color 0.15s ease, background 0.15s ease;
|
| 1028 |
cursor: default;
|
|
|
|
| 1029 |
}
|
| 1030 |
.quota-item:hover {
|
| 1031 |
transform: scale(1.02);
|
|
@@ -1222,7 +1254,7 @@ input:checked + .slider:before {
|
|
| 1222 |
font-size: 0.7rem;
|
| 1223 |
}
|
| 1224 |
|
| 1225 |
-
.hidden { display: none; }
|
| 1226 |
|
| 1227 |
/* 敏感信息模糊 */
|
| 1228 |
.sensitive-info.blurred {
|
|
@@ -1233,10 +1265,10 @@ input:checked + .slider:before {
|
|
| 1233 |
|
| 1234 |
/* 响应式 */
|
| 1235 |
@media (max-width: 768px) {
|
| 1236 |
-
.container { padding: 0; height: 100vh; }
|
| 1237 |
-
.login-form { margin: 0.5rem; padding: 1.5rem; }
|
| 1238 |
.login-form h2 { font-size: 1.25rem; }
|
| 1239 |
-
.main-content { height: 100vh; border-radius: 0; }
|
| 1240 |
.header {
|
| 1241 |
padding: 0.5rem 0.75rem;
|
| 1242 |
flex-wrap: nowrap;
|
|
|
|
| 93 |
background: var(--bg);
|
| 94 |
color: var(--text);
|
| 95 |
line-height: 1.5;
|
| 96 |
+
height: 100vh;
|
| 97 |
+
overflow: hidden;
|
| 98 |
font-size: 1rem;
|
| 99 |
/* 字体渲染优化 */
|
| 100 |
-webkit-font-smoothing: antialiased;
|
|
|
|
| 118 |
font-family: 'Ubuntu Mono', 'Consolas', 'Monaco', monospace !important;
|
| 119 |
}
|
| 120 |
|
| 121 |
+
.container {
|
| 122 |
+
max-width: 1400px;
|
| 123 |
+
margin: 0 auto;
|
| 124 |
+
padding: 0.5rem;
|
| 125 |
+
height: 100vh;
|
| 126 |
+
overflow: hidden;
|
| 127 |
+
display: flex;
|
| 128 |
+
justify-content: center;
|
| 129 |
+
align-items: flex-start;
|
| 130 |
}
|
| 131 |
|
| 132 |
/* 登录表单 */
|
| 133 |
.login-form {
|
| 134 |
+
margin: auto;
|
| 135 |
background: rgba(255, 255, 255, 0.6);
|
| 136 |
backdrop-filter: blur(24px) saturate(180%);
|
| 137 |
-webkit-backdrop-filter: blur(24px) saturate(180%);
|
|
|
|
| 218 |
|
| 219 |
/* 主内容区 */
|
| 220 |
.main-content {
|
| 221 |
+
margin: 0;
|
| 222 |
background: rgba(255, 255, 255, 0.6);
|
| 223 |
backdrop-filter: blur(24px) saturate(180%);
|
| 224 |
-webkit-backdrop-filter: blur(24px) saturate(180%);
|
|
|
|
| 230 |
display: flex;
|
| 231 |
flex-direction: column;
|
| 232 |
border: 1px solid rgba(255, 255, 255, 0.5);
|
| 233 |
+
overflow: hidden;
|
| 234 |
}
|
| 235 |
@media (prefers-color-scheme: dark) {
|
| 236 |
.main-content {
|
|
|
|
| 290 |
.content {
|
| 291 |
padding: 1rem;
|
| 292 |
flex: 1;
|
| 293 |
+
overflow: hidden;
|
| 294 |
+
display: flex;
|
| 295 |
+
flex-direction: column;
|
| 296 |
+
}
|
| 297 |
+
|
| 298 |
+
#tokensPage {
|
| 299 |
+
display: flex;
|
| 300 |
+
flex-direction: column;
|
| 301 |
+
flex: 1;
|
| 302 |
+
min-height: 0;
|
| 303 |
+
overflow: hidden;
|
| 304 |
+
}
|
| 305 |
+
|
| 306 |
+
#settingsPage {
|
| 307 |
+
flex: 1;
|
| 308 |
+
min-height: 0;
|
| 309 |
overflow-y: auto;
|
| 310 |
+
padding-right: 4px;
|
| 311 |
}
|
| 312 |
|
| 313 |
/* 顶部栏 - 统计+操作 */
|
|
|
|
| 320 |
border-radius: 0.75rem;
|
| 321 |
margin-bottom: 1rem;
|
| 322 |
border: 1.5px solid var(--border);
|
| 323 |
+
flex-shrink: 0;
|
| 324 |
}
|
| 325 |
@media (prefers-color-scheme: dark) {
|
| 326 |
.top-bar {
|
|
|
|
| 386 |
display: grid;
|
| 387 |
grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
|
| 388 |
gap: 0.75rem;
|
| 389 |
+
align-items: start;
|
| 390 |
+
flex: 1;
|
| 391 |
+
overflow-y: auto;
|
| 392 |
+
padding-right: 4px;
|
| 393 |
+
padding-bottom: 0.5rem;
|
| 394 |
+
min-height: 0;
|
| 395 |
}
|
| 396 |
.token-card {
|
| 397 |
background: rgba(255, 255, 255, 0.6);
|
|
|
|
| 735 |
box-shadow: 0 16px 48px rgba(0,0,0,0.2);
|
| 736 |
animation: scaleIn 0.2s;
|
| 737 |
border: 1px solid rgba(255, 255, 255, 0.5);
|
| 738 |
+
color: var(--text);
|
| 739 |
}
|
| 740 |
@media (prefers-color-scheme: dark) {
|
| 741 |
.modal-content {
|
|
|
|
| 771 |
.form-modal .modal-content { max-width: 480px; }
|
| 772 |
.form-modal input { margin-bottom: 0.75rem; }
|
| 773 |
.form-modal .form-row { display: flex; flex-direction: column; gap: 0.75rem; margin-bottom: 1rem; }
|
| 774 |
+
.form-modal .oauth-steps {
|
| 775 |
+
background: rgba(59,130,246,0.1);
|
| 776 |
+
padding: 0.875rem;
|
| 777 |
+
border-radius: 0.5rem;
|
| 778 |
+
margin-bottom: 1rem;
|
| 779 |
+
border: 1.5px solid var(--info);
|
| 780 |
+
color: var(--text);
|
| 781 |
}
|
| 782 |
+
.form-modal .oauth-steps p { margin-bottom: 0.5rem; font-size: 0.8rem; color: var(--text); }
|
| 783 |
.form-modal .oauth-steps p:last-child { margin-bottom: 0; }
|
| 784 |
|
| 785 |
@keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
|
|
|
|
| 1057 |
border: 1.5px solid var(--border);
|
| 1058 |
transition: transform 0.15s ease, box-shadow 0.15s ease, border-color 0.15s ease, background 0.15s ease;
|
| 1059 |
cursor: default;
|
| 1060 |
+
color: var(--text);
|
| 1061 |
}
|
| 1062 |
.quota-item:hover {
|
| 1063 |
transform: scale(1.02);
|
|
|
|
| 1254 |
font-size: 0.7rem;
|
| 1255 |
}
|
| 1256 |
|
| 1257 |
+
.hidden { display: none !important; }
|
| 1258 |
|
| 1259 |
/* 敏感信息模糊 */
|
| 1260 |
.sensitive-info.blurred {
|
|
|
|
| 1265 |
|
| 1266 |
/* 响应式 */
|
| 1267 |
@media (max-width: 768px) {
|
| 1268 |
+
.container { padding: 0; height: 100vh; align-items: stretch; }
|
| 1269 |
+
.login-form { margin: auto 0.5rem; padding: 1.5rem; }
|
| 1270 |
.login-form h2 { font-size: 1.25rem; }
|
| 1271 |
+
.main-content { height: 100vh; border-radius: 0; margin: 0; }
|
| 1272 |
.header {
|
| 1273 |
padding: 0.5rem 0.75rem;
|
| 1274 |
flex-wrap: nowrap;
|
src/api/client.js
CHANGED
|
@@ -1,4 +1,3 @@
|
|
| 1 |
-
import axios from 'axios';
|
| 2 |
import tokenManager from '../auth/token_manager.js';
|
| 3 |
import config from '../config/config.js';
|
| 4 |
import AntigravityRequester from '../AntigravityRequester.js';
|
|
@@ -15,6 +14,10 @@ import {
|
|
| 15 |
convertToToolCall,
|
| 16 |
registerStreamMemoryCleanup
|
| 17 |
} from './stream_parser.js';
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
|
| 19 |
// 请求客户端:优先使用 AntigravityRequester,失败则降级到 axios
|
| 20 |
let requester = null;
|
|
@@ -118,15 +121,6 @@ function buildHeaders(token) {
|
|
| 118 |
};
|
| 119 |
}
|
| 120 |
|
| 121 |
-
function buildAxiosConfig(url, headers, body = null) {
|
| 122 |
-
return buildAxiosRequestConfig({
|
| 123 |
-
method: 'POST',
|
| 124 |
-
url,
|
| 125 |
-
headers,
|
| 126 |
-
data: body
|
| 127 |
-
});
|
| 128 |
-
}
|
| 129 |
-
|
| 130 |
function buildRequesterConfig(headers, body = null) {
|
| 131 |
const reqConfig = {
|
| 132 |
method: 'POST',
|
|
@@ -191,8 +185,12 @@ export async function generateAssistantResponse(requestBody, token, callback) {
|
|
| 191 |
|
| 192 |
try {
|
| 193 |
if (useAxios) {
|
| 194 |
-
const
|
| 195 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 196 |
|
| 197 |
// 使用 Buffer 直接处理,避免 toString 的内存分配
|
| 198 |
response.data.on('data', chunk => {
|
|
@@ -242,7 +240,12 @@ export async function generateAssistantResponse(requestBody, token, callback) {
|
|
| 242 |
async function fetchRawModels(headers, token) {
|
| 243 |
try {
|
| 244 |
if (useAxios) {
|
| 245 |
-
const response = await
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 246 |
return response.data;
|
| 247 |
}
|
| 248 |
const response = await requester.antigravity_fetch(config.api.modelsUrl, buildRequesterConfig(headers, {}));
|
|
@@ -345,7 +348,12 @@ export async function generateAssistantResponseNoStream(requestBody, token) {
|
|
| 345 |
|
| 346 |
try {
|
| 347 |
if (useAxios) {
|
| 348 |
-
data = (await
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 349 |
} else {
|
| 350 |
const response = await requester.antigravity_fetch(config.api.noStreamUrl, buildRequesterConfig(headers, requestBody));
|
| 351 |
if (response.status !== 200) {
|
|
@@ -427,7 +435,12 @@ export async function generateImageForSD(requestBody, token) {
|
|
| 427 |
|
| 428 |
try {
|
| 429 |
if (useAxios) {
|
| 430 |
-
data = (await
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 431 |
} else {
|
| 432 |
const response = await requester.antigravity_fetch(config.api.noStreamUrl, buildRequesterConfig(headers, requestBody));
|
| 433 |
if (response.status !== 200) {
|
|
|
|
|
|
|
| 1 |
import tokenManager from '../auth/token_manager.js';
|
| 2 |
import config from '../config/config.js';
|
| 3 |
import AntigravityRequester from '../AntigravityRequester.js';
|
|
|
|
| 14 |
convertToToolCall,
|
| 15 |
registerStreamMemoryCleanup
|
| 16 |
} from './stream_parser.js';
|
| 17 |
+
import memoryManager, { MemoryPressure, registerMemoryPoolCleanup } from '../utils/memoryManager.js';
|
| 18 |
+
import { buildAxiosRequestConfig, httpRequest, httpStreamRequest } from '../utils/httpClient.js';
|
| 19 |
+
import { setReasoningSignature, setToolSignature } from '../utils/thoughtSignatureCache.js';
|
| 20 |
+
import { getOriginalToolName } from '../utils/toolNameCache.js';
|
| 21 |
|
| 22 |
// 请求客户端:优先使用 AntigravityRequester,失败则降级到 axios
|
| 23 |
let requester = null;
|
|
|
|
| 121 |
};
|
| 122 |
}
|
| 123 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 124 |
function buildRequesterConfig(headers, body = null) {
|
| 125 |
const reqConfig = {
|
| 126 |
method: 'POST',
|
|
|
|
| 185 |
|
| 186 |
try {
|
| 187 |
if (useAxios) {
|
| 188 |
+
const response = await httpStreamRequest({
|
| 189 |
+
method: 'POST',
|
| 190 |
+
url: config.api.url,
|
| 191 |
+
headers,
|
| 192 |
+
data: requestBody
|
| 193 |
+
});
|
| 194 |
|
| 195 |
// 使用 Buffer 直接处理,避免 toString 的内存分配
|
| 196 |
response.data.on('data', chunk => {
|
|
|
|
| 240 |
async function fetchRawModels(headers, token) {
|
| 241 |
try {
|
| 242 |
if (useAxios) {
|
| 243 |
+
const response = await httpRequest({
|
| 244 |
+
method: 'POST',
|
| 245 |
+
url: config.api.modelsUrl,
|
| 246 |
+
headers,
|
| 247 |
+
data: {}
|
| 248 |
+
});
|
| 249 |
return response.data;
|
| 250 |
}
|
| 251 |
const response = await requester.antigravity_fetch(config.api.modelsUrl, buildRequesterConfig(headers, {}));
|
|
|
|
| 348 |
|
| 349 |
try {
|
| 350 |
if (useAxios) {
|
| 351 |
+
data = (await httpRequest({
|
| 352 |
+
method: 'POST',
|
| 353 |
+
url: config.api.noStreamUrl,
|
| 354 |
+
headers,
|
| 355 |
+
data: requestBody
|
| 356 |
+
})).data;
|
| 357 |
} else {
|
| 358 |
const response = await requester.antigravity_fetch(config.api.noStreamUrl, buildRequesterConfig(headers, requestBody));
|
| 359 |
if (response.status !== 200) {
|
|
|
|
| 435 |
|
| 436 |
try {
|
| 437 |
if (useAxios) {
|
| 438 |
+
data = (await httpRequest({
|
| 439 |
+
method: 'POST',
|
| 440 |
+
url: config.api.noStreamUrl,
|
| 441 |
+
headers,
|
| 442 |
+
data: requestBody
|
| 443 |
+
})).data;
|
| 444 |
} else {
|
| 445 |
const response = await requester.antigravity_fetch(config.api.noStreamUrl, buildRequesterConfig(headers, requestBody));
|
| 446 |
if (response.status !== 200) {
|
src/server/index.js
CHANGED
|
@@ -2,7 +2,7 @@ import express from 'express';
|
|
| 2 |
import cors from 'cors';
|
| 3 |
import path from 'path';
|
| 4 |
import { generateAssistantResponse, generateAssistantResponseNoStream, getAvailableModels, generateImageForSD, closeRequester } from '../api/client.js';
|
| 5 |
-
import { generateRequestBody, prepareImageRequest } from '../utils/utils.js';
|
| 6 |
import logger from '../utils/logger.js';
|
| 7 |
import config from '../config/config.js';
|
| 8 |
import tokenManager from '../auth/token_manager.js';
|
|
@@ -122,6 +122,72 @@ const endStream = (res) => {
|
|
| 122 |
};
|
| 123 |
|
| 124 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 125 |
app.use(cors());
|
| 126 |
app.use(express.json({ limit: config.security.maxRequestSize }));
|
| 127 |
|
|
@@ -151,10 +217,10 @@ app.use((req, res, next) => {
|
|
| 151 |
if (req.path.startsWith('/v1/')) {
|
| 152 |
const apiKey = config.security?.apiKey;
|
| 153 |
if (apiKey) {
|
| 154 |
-
const authHeader = req.headers.authorization;
|
| 155 |
const providedKey = authHeader?.startsWith('Bearer ') ? authHeader.slice(7) : authHeader;
|
| 156 |
if (providedKey !== apiKey) {
|
| 157 |
-
logger.warn(`API Key 验证失败: ${req.method} ${req.path}`);
|
| 158 |
return res.status(401).json({ error: 'Invalid API Key' });
|
| 159 |
}
|
| 160 |
}
|
|
@@ -329,6 +395,450 @@ app.post('/v1/chat/completions', async (req, res) => {
|
|
| 329 |
}
|
| 330 |
});
|
| 331 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 332 |
const server = app.listen(config.server.port, config.server.host, () => {
|
| 333 |
logger.info(`服务器已启动: ${config.server.host}:${config.server.port}`);
|
| 334 |
});
|
|
|
|
| 2 |
import cors from 'cors';
|
| 3 |
import path from 'path';
|
| 4 |
import { generateAssistantResponse, generateAssistantResponseNoStream, getAvailableModels, generateImageForSD, closeRequester } from '../api/client.js';
|
| 5 |
+
import { generateRequestBody, generateGeminiRequestBody, generateClaudeRequestBody, prepareImageRequest } from '../utils/utils.js';
|
| 6 |
import logger from '../utils/logger.js';
|
| 7 |
import config from '../config/config.js';
|
| 8 |
import tokenManager from '../auth/token_manager.js';
|
|
|
|
| 122 |
};
|
| 123 |
|
| 124 |
|
| 125 |
+
// Gemini 兼容错误响应构造
|
| 126 |
+
const buildGeminiErrorPayload = (error, statusCode) => {
|
| 127 |
+
// 尝试解析原始错误信息
|
| 128 |
+
let message = error.message || 'Internal server error';
|
| 129 |
+
if (error.isUpstreamApiError && error.rawBody) {
|
| 130 |
+
try {
|
| 131 |
+
const raw = typeof error.rawBody === 'string' ? JSON.parse(error.rawBody) : error.rawBody;
|
| 132 |
+
message = raw.error?.message || raw.message || message;
|
| 133 |
+
} catch {}
|
| 134 |
+
}
|
| 135 |
+
|
| 136 |
+
return {
|
| 137 |
+
error: {
|
| 138 |
+
code: statusCode,
|
| 139 |
+
message: message,
|
| 140 |
+
status: "INTERNAL" // 简单映射,实际可根据 statusCode 细化
|
| 141 |
+
}
|
| 142 |
+
};
|
| 143 |
+
};
|
| 144 |
+
|
| 145 |
+
// Gemini 响应构建工具
|
| 146 |
+
const createGeminiResponse = (content, reasoning, toolCalls, finishReason, usage) => {
|
| 147 |
+
const parts = [];
|
| 148 |
+
if (reasoning) {
|
| 149 |
+
parts.push({ text: reasoning, thought: true });
|
| 150 |
+
}
|
| 151 |
+
if (content) {
|
| 152 |
+
parts.push({ text: content });
|
| 153 |
+
}
|
| 154 |
+
if (toolCalls && toolCalls.length > 0) {
|
| 155 |
+
toolCalls.forEach(tc => {
|
| 156 |
+
try {
|
| 157 |
+
parts.push({
|
| 158 |
+
functionCall: {
|
| 159 |
+
name: tc.function.name,
|
| 160 |
+
args: JSON.parse(tc.function.arguments)
|
| 161 |
+
}
|
| 162 |
+
});
|
| 163 |
+
} catch (e) {
|
| 164 |
+
// 忽略解析错误
|
| 165 |
+
}
|
| 166 |
+
});
|
| 167 |
+
}
|
| 168 |
+
|
| 169 |
+
const response = {
|
| 170 |
+
candidates: [{
|
| 171 |
+
content: {
|
| 172 |
+
parts: parts,
|
| 173 |
+
role: "model"
|
| 174 |
+
},
|
| 175 |
+
finishReason: finishReason || "STOP",
|
| 176 |
+
index: 0
|
| 177 |
+
}]
|
| 178 |
+
};
|
| 179 |
+
|
| 180 |
+
if (usage) {
|
| 181 |
+
response.usageMetadata = {
|
| 182 |
+
promptTokenCount: usage.prompt_tokens,
|
| 183 |
+
candidatesTokenCount: usage.completion_tokens,
|
| 184 |
+
totalTokenCount: usage.total_tokens
|
| 185 |
+
};
|
| 186 |
+
}
|
| 187 |
+
|
| 188 |
+
return response;
|
| 189 |
+
};
|
| 190 |
+
|
| 191 |
app.use(cors());
|
| 192 |
app.use(express.json({ limit: config.security.maxRequestSize }));
|
| 193 |
|
|
|
|
| 217 |
if (req.path.startsWith('/v1/')) {
|
| 218 |
const apiKey = config.security?.apiKey;
|
| 219 |
if (apiKey) {
|
| 220 |
+
const authHeader = req.headers.authorization || req.headers['x-api-key'];
|
| 221 |
const providedKey = authHeader?.startsWith('Bearer ') ? authHeader.slice(7) : authHeader;
|
| 222 |
if (providedKey !== apiKey) {
|
| 223 |
+
logger.warn(`API Key 验证失败: ${req.method} ${req.path} (提供的Key: ${providedKey ? providedKey.substring(0, 10) + '...' : '无'})`);
|
| 224 |
return res.status(401).json({ error: 'Invalid API Key' });
|
| 225 |
}
|
| 226 |
}
|
|
|
|
| 395 |
}
|
| 396 |
});
|
| 397 |
|
| 398 |
+
// Gemini 模型列表格式转换
|
| 399 |
+
const convertToGeminiModelList = (openaiModels) => {
|
| 400 |
+
const models = openaiModels.data.map(model => ({
|
| 401 |
+
name: `models/${model.id}`,
|
| 402 |
+
version: "001",
|
| 403 |
+
displayName: model.id,
|
| 404 |
+
description: "Imported model",
|
| 405 |
+
inputTokenLimit: 32768, // 默认值
|
| 406 |
+
outputTokenLimit: 8192, // 默认值
|
| 407 |
+
supportedGenerationMethods: ["generateContent", "countTokens"],
|
| 408 |
+
temperature: 0.9,
|
| 409 |
+
topP: 1.0,
|
| 410 |
+
topK: 40
|
| 411 |
+
}));
|
| 412 |
+
return { models };
|
| 413 |
+
};
|
| 414 |
+
|
| 415 |
+
// Gemini API 路由
|
| 416 |
+
app.get('/v1beta/models', async (req, res) => {
|
| 417 |
+
try {
|
| 418 |
+
const openaiModels = await getAvailableModels();
|
| 419 |
+
const geminiModels = convertToGeminiModelList(openaiModels);
|
| 420 |
+
res.json(geminiModels);
|
| 421 |
+
} catch (error) {
|
| 422 |
+
logger.error('获取模型列表失败:', error.message);
|
| 423 |
+
res.status(500).json({ error: { code: 500, message: error.message, status: "INTERNAL" } });
|
| 424 |
+
}
|
| 425 |
+
});
|
| 426 |
+
|
| 427 |
+
app.get('/v1beta/models/:model', async (req, res) => {
|
| 428 |
+
try {
|
| 429 |
+
const modelId = req.params.model.replace(/^models\//, '');
|
| 430 |
+
const openaiModels = await getAvailableModels();
|
| 431 |
+
const model = openaiModels.data.find(m => m.id === modelId);
|
| 432 |
+
|
| 433 |
+
if (model) {
|
| 434 |
+
const geminiModel = {
|
| 435 |
+
name: `models/${model.id}`,
|
| 436 |
+
version: "001",
|
| 437 |
+
displayName: model.id,
|
| 438 |
+
description: "Imported model",
|
| 439 |
+
inputTokenLimit: 32768,
|
| 440 |
+
outputTokenLimit: 8192,
|
| 441 |
+
supportedGenerationMethods: ["generateContent", "countTokens"],
|
| 442 |
+
temperature: 0.9,
|
| 443 |
+
topP: 1.0,
|
| 444 |
+
topK: 40
|
| 445 |
+
};
|
| 446 |
+
res.json(geminiModel);
|
| 447 |
+
} else {
|
| 448 |
+
res.status(404).json({ error: { code: 404, message: `Model ${modelId} not found`, status: "NOT_FOUND" } });
|
| 449 |
+
}
|
| 450 |
+
} catch (error) {
|
| 451 |
+
logger.error('获取模型详情失败:', error.message);
|
| 452 |
+
res.status(500).json({ error: { code: 500, message: error.message, status: "INTERNAL" } });
|
| 453 |
+
}
|
| 454 |
+
});
|
| 455 |
+
|
| 456 |
+
const handleGeminiRequest = async (req, res, modelName, isStream) => {
|
| 457 |
+
try {
|
| 458 |
+
const token = await tokenManager.getToken();
|
| 459 |
+
if (!token) {
|
| 460 |
+
throw new Error('没有可用的token,请运行 npm run login 获取token');
|
| 461 |
+
}
|
| 462 |
+
|
| 463 |
+
const requestBody = generateGeminiRequestBody(req.body, modelName, token);
|
| 464 |
+
const maxRetries = Number(config.retryTimes || 0);
|
| 465 |
+
const safeRetries = maxRetries > 0 ? Math.floor(maxRetries) : 0;
|
| 466 |
+
|
| 467 |
+
if (isStream) {
|
| 468 |
+
setStreamHeaders(res);
|
| 469 |
+
const heartbeatTimer = createHeartbeat(res);
|
| 470 |
+
|
| 471 |
+
try {
|
| 472 |
+
let usageData = null;
|
| 473 |
+
let hasToolCall = false;
|
| 474 |
+
|
| 475 |
+
await with429Retry(
|
| 476 |
+
() => generateAssistantResponse(requestBody, token, (data) => {
|
| 477 |
+
if (data.type === 'usage') {
|
| 478 |
+
usageData = data.usage;
|
| 479 |
+
} else if (data.type === 'reasoning') {
|
| 480 |
+
// Gemini 思考内容
|
| 481 |
+
const chunk = createGeminiResponse(null, data.reasoning_content, null, null, null);
|
| 482 |
+
writeStreamData(res, chunk);
|
| 483 |
+
} else if (data.type === 'tool_calls') {
|
| 484 |
+
hasToolCall = true;
|
| 485 |
+
// Gemini 工具调用
|
| 486 |
+
const chunk = createGeminiResponse(null, null, data.tool_calls, null, null);
|
| 487 |
+
writeStreamData(res, chunk);
|
| 488 |
+
} else {
|
| 489 |
+
// 普通文本
|
| 490 |
+
const chunk = createGeminiResponse(data.content, null, null, null, null);
|
| 491 |
+
writeStreamData(res, chunk);
|
| 492 |
+
}
|
| 493 |
+
}),
|
| 494 |
+
safeRetries,
|
| 495 |
+
'gemini.stream '
|
| 496 |
+
);
|
| 497 |
+
|
| 498 |
+
// 发送结束块和 usage
|
| 499 |
+
const finishReason = hasToolCall ? "STOP" : "STOP"; // Gemini 工具调用也是 STOP
|
| 500 |
+
const finalChunk = createGeminiResponse(null, null, null, finishReason, usageData);
|
| 501 |
+
writeStreamData(res, finalChunk);
|
| 502 |
+
|
| 503 |
+
clearInterval(heartbeatTimer);
|
| 504 |
+
endStream(res);
|
| 505 |
+
} catch (error) {
|
| 506 |
+
clearInterval(heartbeatTimer);
|
| 507 |
+
throw error;
|
| 508 |
+
}
|
| 509 |
+
} else {
|
| 510 |
+
// 非流式
|
| 511 |
+
req.setTimeout(0);
|
| 512 |
+
res.setTimeout(0);
|
| 513 |
+
|
| 514 |
+
const { content, reasoningContent, toolCalls, usage } = await with429Retry(
|
| 515 |
+
() => generateAssistantResponseNoStream(requestBody, token),
|
| 516 |
+
safeRetries,
|
| 517 |
+
'gemini.no_stream '
|
| 518 |
+
);
|
| 519 |
+
|
| 520 |
+
const finishReason = toolCalls.length > 0 ? "STOP" : "STOP";
|
| 521 |
+
const response = createGeminiResponse(content, reasoningContent, toolCalls, finishReason, usage);
|
| 522 |
+
res.json(response);
|
| 523 |
+
}
|
| 524 |
+
} catch (error) {
|
| 525 |
+
logger.error('Gemini 请求失败:', error.message);
|
| 526 |
+
if (res.headersSent) return;
|
| 527 |
+
|
| 528 |
+
const statusCode = Number(error.status) || 500;
|
| 529 |
+
const errorPayload = buildGeminiErrorPayload(error, statusCode);
|
| 530 |
+
res.status(statusCode).json(errorPayload);
|
| 531 |
+
}
|
| 532 |
+
};
|
| 533 |
+
|
| 534 |
+
app.post('/v1beta/models/:model\\:streamGenerateContent', (req, res) => {
|
| 535 |
+
const modelName = req.params.model;
|
| 536 |
+
handleGeminiRequest(req, res, modelName, true);
|
| 537 |
+
});
|
| 538 |
+
|
| 539 |
+
app.post('/v1beta/models/:model\\:generateContent', (req, res) => {
|
| 540 |
+
const modelName = req.params.model;
|
| 541 |
+
const isStream = req.query.alt === 'sse';
|
| 542 |
+
handleGeminiRequest(req, res, modelName, isStream);
|
| 543 |
+
});
|
| 544 |
+
|
| 545 |
+
// ==================== Claude API ====================
|
| 546 |
+
|
| 547 |
+
// Claude 错误响应构造
|
| 548 |
+
const buildClaudeErrorPayload = (error, statusCode) => {
|
| 549 |
+
let message = error.message || 'Internal server error';
|
| 550 |
+
if (error.isUpstreamApiError && error.rawBody) {
|
| 551 |
+
try {
|
| 552 |
+
const raw = typeof error.rawBody === 'string' ? JSON.parse(error.rawBody) : error.rawBody;
|
| 553 |
+
message = raw.error?.message || raw.message || message;
|
| 554 |
+
} catch {}
|
| 555 |
+
}
|
| 556 |
+
|
| 557 |
+
return {
|
| 558 |
+
type: "error",
|
| 559 |
+
error: {
|
| 560 |
+
type: statusCode === 401 ? "authentication_error" :
|
| 561 |
+
statusCode === 429 ? "rate_limit_error" :
|
| 562 |
+
statusCode === 400 ? "invalid_request_error" :
|
| 563 |
+
"api_error",
|
| 564 |
+
message: message
|
| 565 |
+
}
|
| 566 |
+
};
|
| 567 |
+
};
|
| 568 |
+
|
| 569 |
+
// Claude 流式响应工具
|
| 570 |
+
const createClaudeStreamEvent = (eventType, data) => {
|
| 571 |
+
return `event: ${eventType}\ndata: ${JSON.stringify(data)}\n\n`;
|
| 572 |
+
};
|
| 573 |
+
|
| 574 |
+
// Claude 非流式响应构建
|
| 575 |
+
const createClaudeResponse = (id, model, content, reasoning, toolCalls, stopReason, usage) => {
|
| 576 |
+
const contentBlocks = [];
|
| 577 |
+
|
| 578 |
+
// 思维链内容(如果有)- Claude 格式用 thinking 类型
|
| 579 |
+
if (reasoning) {
|
| 580 |
+
contentBlocks.push({
|
| 581 |
+
type: "thinking",
|
| 582 |
+
thinking: reasoning
|
| 583 |
+
});
|
| 584 |
+
}
|
| 585 |
+
|
| 586 |
+
// 文本内容
|
| 587 |
+
if (content) {
|
| 588 |
+
contentBlocks.push({
|
| 589 |
+
type: "text",
|
| 590 |
+
text: content
|
| 591 |
+
});
|
| 592 |
+
}
|
| 593 |
+
|
| 594 |
+
// 工具调用
|
| 595 |
+
if (toolCalls && toolCalls.length > 0) {
|
| 596 |
+
for (const tc of toolCalls) {
|
| 597 |
+
try {
|
| 598 |
+
contentBlocks.push({
|
| 599 |
+
type: "tool_use",
|
| 600 |
+
id: tc.id,
|
| 601 |
+
name: tc.function.name,
|
| 602 |
+
input: JSON.parse(tc.function.arguments)
|
| 603 |
+
});
|
| 604 |
+
} catch (e) {
|
| 605 |
+
// 解析失败时传入空对象
|
| 606 |
+
contentBlocks.push({
|
| 607 |
+
type: "tool_use",
|
| 608 |
+
id: tc.id,
|
| 609 |
+
name: tc.function.name,
|
| 610 |
+
input: {}
|
| 611 |
+
});
|
| 612 |
+
}
|
| 613 |
+
}
|
| 614 |
+
}
|
| 615 |
+
|
| 616 |
+
return {
|
| 617 |
+
id: id,
|
| 618 |
+
type: "message",
|
| 619 |
+
role: "assistant",
|
| 620 |
+
content: contentBlocks,
|
| 621 |
+
model: model,
|
| 622 |
+
stop_reason: stopReason,
|
| 623 |
+
stop_sequence: null,
|
| 624 |
+
usage: usage ? {
|
| 625 |
+
input_tokens: usage.prompt_tokens || 0,
|
| 626 |
+
output_tokens: usage.completion_tokens || 0
|
| 627 |
+
} : { input_tokens: 0, output_tokens: 0 }
|
| 628 |
+
};
|
| 629 |
+
};
|
| 630 |
+
|
| 631 |
+
// Claude API 处理函数
|
| 632 |
+
const handleClaudeRequest = async (req, res, isStream) => {
|
| 633 |
+
const { messages, model, system, tools, max_tokens, temperature, top_p, top_k, ...otherParams } = req.body;
|
| 634 |
+
|
| 635 |
+
try {
|
| 636 |
+
if (!messages) {
|
| 637 |
+
return res.status(400).json(buildClaudeErrorPayload({ message: 'messages is required' }, 400));
|
| 638 |
+
}
|
| 639 |
+
|
| 640 |
+
const token = await tokenManager.getToken();
|
| 641 |
+
if (!token) {
|
| 642 |
+
throw new Error('没有可用的token,请运行 npm run login 获取token');
|
| 643 |
+
}
|
| 644 |
+
|
| 645 |
+
// 构建参数
|
| 646 |
+
const parameters = {
|
| 647 |
+
max_tokens: max_tokens || config.defaults.max_tokens,
|
| 648 |
+
temperature: temperature ?? config.defaults.temperature,
|
| 649 |
+
top_p: top_p ?? config.defaults.top_p,
|
| 650 |
+
top_k: top_k ?? config.defaults.top_k,
|
| 651 |
+
...otherParams
|
| 652 |
+
};
|
| 653 |
+
|
| 654 |
+
const requestBody = generateClaudeRequestBody(messages, model, parameters, tools, system, token);
|
| 655 |
+
|
| 656 |
+
const msgId = `msg_${Date.now()}`;
|
| 657 |
+
const maxRetries = Number(config.retryTimes || 0);
|
| 658 |
+
const safeRetries = maxRetries > 0 ? Math.floor(maxRetries) : 0;
|
| 659 |
+
|
| 660 |
+
if (isStream) {
|
| 661 |
+
setStreamHeaders(res);
|
| 662 |
+
const heartbeatTimer = createHeartbeat(res);
|
| 663 |
+
|
| 664 |
+
try {
|
| 665 |
+
let contentIndex = 0;
|
| 666 |
+
let usageData = null;
|
| 667 |
+
let hasToolCall = false;
|
| 668 |
+
let currentBlockType = null;
|
| 669 |
+
let reasoningSent = false;
|
| 670 |
+
|
| 671 |
+
// 发送 message_start
|
| 672 |
+
res.write(createClaudeStreamEvent('message_start', {
|
| 673 |
+
type: "message_start",
|
| 674 |
+
message: {
|
| 675 |
+
id: msgId,
|
| 676 |
+
type: "message",
|
| 677 |
+
role: "assistant",
|
| 678 |
+
content: [],
|
| 679 |
+
model: model,
|
| 680 |
+
stop_reason: null,
|
| 681 |
+
stop_sequence: null,
|
| 682 |
+
usage: { input_tokens: 0, output_tokens: 0 }
|
| 683 |
+
}
|
| 684 |
+
}));
|
| 685 |
+
|
| 686 |
+
await with429Retry(
|
| 687 |
+
() => generateAssistantResponse(requestBody, token, (data) => {
|
| 688 |
+
if (data.type === 'usage') {
|
| 689 |
+
usageData = data.usage;
|
| 690 |
+
} else if (data.type === 'reasoning') {
|
| 691 |
+
// 思维链内容 - 使用 thinking 类型
|
| 692 |
+
if (!reasoningSent) {
|
| 693 |
+
// 开始思维块
|
| 694 |
+
res.write(createClaudeStreamEvent('content_block_start', {
|
| 695 |
+
type: "content_block_start",
|
| 696 |
+
index: contentIndex,
|
| 697 |
+
content_block: { type: "thinking", thinking: "" }
|
| 698 |
+
}));
|
| 699 |
+
currentBlockType = 'thinking';
|
| 700 |
+
reasoningSent = true;
|
| 701 |
+
}
|
| 702 |
+
// 发送思维增量
|
| 703 |
+
res.write(createClaudeStreamEvent('content_block_delta', {
|
| 704 |
+
type: "content_block_delta",
|
| 705 |
+
index: contentIndex,
|
| 706 |
+
delta: { type: "thinking_delta", thinking: data.reasoning_content || '' }
|
| 707 |
+
}));
|
| 708 |
+
} else if (data.type === 'tool_calls') {
|
| 709 |
+
hasToolCall = true;
|
| 710 |
+
// 结束之前的块(如果有)
|
| 711 |
+
if (currentBlockType) {
|
| 712 |
+
res.write(createClaudeStreamEvent('content_block_stop', {
|
| 713 |
+
type: "content_block_stop",
|
| 714 |
+
index: contentIndex
|
| 715 |
+
}));
|
| 716 |
+
contentIndex++;
|
| 717 |
+
}
|
| 718 |
+
// 工具调用
|
| 719 |
+
for (const tc of data.tool_calls) {
|
| 720 |
+
try {
|
| 721 |
+
const inputObj = JSON.parse(tc.function.arguments);
|
| 722 |
+
res.write(createClaudeStreamEvent('content_block_start', {
|
| 723 |
+
type: "content_block_start",
|
| 724 |
+
index: contentIndex,
|
| 725 |
+
content_block: { type: "tool_use", id: tc.id, name: tc.function.name, input: {} }
|
| 726 |
+
}));
|
| 727 |
+
// 发送 input 增量
|
| 728 |
+
res.write(createClaudeStreamEvent('content_block_delta', {
|
| 729 |
+
type: "content_block_delta",
|
| 730 |
+
index: contentIndex,
|
| 731 |
+
delta: { type: "input_json_delta", partial_json: JSON.stringify(inputObj) }
|
| 732 |
+
}));
|
| 733 |
+
res.write(createClaudeStreamEvent('content_block_stop', {
|
| 734 |
+
type: "content_block_stop",
|
| 735 |
+
index: contentIndex
|
| 736 |
+
}));
|
| 737 |
+
contentIndex++;
|
| 738 |
+
} catch (e) {
|
| 739 |
+
// 解析失败,跳过
|
| 740 |
+
}
|
| 741 |
+
}
|
| 742 |
+
currentBlockType = null;
|
| 743 |
+
} else {
|
| 744 |
+
// 普通文本内容
|
| 745 |
+
if (currentBlockType === 'thinking') {
|
| 746 |
+
// 结束思维块
|
| 747 |
+
res.write(createClaudeStreamEvent('content_block_stop', {
|
| 748 |
+
type: "content_block_stop",
|
| 749 |
+
index: contentIndex
|
| 750 |
+
}));
|
| 751 |
+
contentIndex++;
|
| 752 |
+
currentBlockType = null;
|
| 753 |
+
}
|
| 754 |
+
if (currentBlockType !== 'text') {
|
| 755 |
+
// 开始文本块
|
| 756 |
+
res.write(createClaudeStreamEvent('content_block_start', {
|
| 757 |
+
type: "content_block_start",
|
| 758 |
+
index: contentIndex,
|
| 759 |
+
content_block: { type: "text", text: "" }
|
| 760 |
+
}));
|
| 761 |
+
currentBlockType = 'text';
|
| 762 |
+
}
|
| 763 |
+
// 发送文本增量
|
| 764 |
+
res.write(createClaudeStreamEvent('content_block_delta', {
|
| 765 |
+
type: "content_block_delta",
|
| 766 |
+
index: contentIndex,
|
| 767 |
+
delta: { type: "text_delta", text: data.content || '' }
|
| 768 |
+
}));
|
| 769 |
+
}
|
| 770 |
+
}),
|
| 771 |
+
safeRetries,
|
| 772 |
+
'claude.stream '
|
| 773 |
+
);
|
| 774 |
+
|
| 775 |
+
// 结束最后一个内容块
|
| 776 |
+
if (currentBlockType) {
|
| 777 |
+
res.write(createClaudeStreamEvent('content_block_stop', {
|
| 778 |
+
type: "content_block_stop",
|
| 779 |
+
index: contentIndex
|
| 780 |
+
}));
|
| 781 |
+
}
|
| 782 |
+
|
| 783 |
+
// 发送 message_delta
|
| 784 |
+
const stopReason = hasToolCall ? 'tool_use' : 'end_turn';
|
| 785 |
+
res.write(createClaudeStreamEvent('message_delta', {
|
| 786 |
+
type: "message_delta",
|
| 787 |
+
delta: { stop_reason: stopReason, stop_sequence: null },
|
| 788 |
+
usage: usageData ? { output_tokens: usageData.completion_tokens || 0 } : { output_tokens: 0 }
|
| 789 |
+
}));
|
| 790 |
+
|
| 791 |
+
// 发送 message_stop
|
| 792 |
+
res.write(createClaudeStreamEvent('message_stop', {
|
| 793 |
+
type: "message_stop"
|
| 794 |
+
}));
|
| 795 |
+
|
| 796 |
+
clearInterval(heartbeatTimer);
|
| 797 |
+
res.end();
|
| 798 |
+
} catch (error) {
|
| 799 |
+
clearInterval(heartbeatTimer);
|
| 800 |
+
throw error;
|
| 801 |
+
}
|
| 802 |
+
} else {
|
| 803 |
+
// 非流式请求
|
| 804 |
+
req.setTimeout(0);
|
| 805 |
+
res.setTimeout(0);
|
| 806 |
+
|
| 807 |
+
const { content, reasoningContent, toolCalls, usage } = await with429Retry(
|
| 808 |
+
() => generateAssistantResponseNoStream(requestBody, token),
|
| 809 |
+
safeRetries,
|
| 810 |
+
'claude.no_stream '
|
| 811 |
+
);
|
| 812 |
+
|
| 813 |
+
const stopReason = toolCalls.length > 0 ? 'tool_use' : 'end_turn';
|
| 814 |
+
const response = createClaudeResponse(
|
| 815 |
+
msgId,
|
| 816 |
+
model,
|
| 817 |
+
content,
|
| 818 |
+
reasoningContent,
|
| 819 |
+
toolCalls,
|
| 820 |
+
stopReason,
|
| 821 |
+
usage
|
| 822 |
+
);
|
| 823 |
+
|
| 824 |
+
res.json(response);
|
| 825 |
+
}
|
| 826 |
+
} catch (error) {
|
| 827 |
+
logger.error('Claude 请求失败:', error.message);
|
| 828 |
+
if (res.headersSent) return;
|
| 829 |
+
|
| 830 |
+
const statusCode = Number(error.status) || 500;
|
| 831 |
+
const errorPayload = buildClaudeErrorPayload(error, statusCode);
|
| 832 |
+
res.status(statusCode).json(errorPayload);
|
| 833 |
+
}
|
| 834 |
+
};
|
| 835 |
+
|
| 836 |
+
// Claude Messages API 端点
|
| 837 |
+
app.post('/v1/messages', (req, res) => {
|
| 838 |
+
const isStream = req.body.stream === true;
|
| 839 |
+
handleClaudeRequest(req, res, isStream);
|
| 840 |
+
});
|
| 841 |
+
|
| 842 |
const server = app.listen(config.server.port, config.server.host, () => {
|
| 843 |
logger.info(`服务器已启动: ${config.server.host}:${config.server.port}`);
|
| 844 |
});
|
src/utils/httpClient.js
CHANGED
|
@@ -68,3 +68,10 @@ export async function httpRequest(configOverrides) {
|
|
| 68 |
const axiosConfig = buildAxiosRequestConfig(configOverrides);
|
| 69 |
return axios(axiosConfig);
|
| 70 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 68 |
const axiosConfig = buildAxiosRequestConfig(configOverrides);
|
| 69 |
return axios(axiosConfig);
|
| 70 |
}
|
| 71 |
+
|
| 72 |
+
// 流式请求封装
|
| 73 |
+
export async function httpStreamRequest(configOverrides) {
|
| 74 |
+
const axiosConfig = buildAxiosRequestConfig(configOverrides);
|
| 75 |
+
axiosConfig.responseType = 'stream';
|
| 76 |
+
return axios(axiosConfig);
|
| 77 |
+
}
|
src/utils/utils.js
CHANGED
|
@@ -1 +1,868 @@
|
|
| 1 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import config from '../config/config.js';
|
| 2 |
+
import tokenManager from '../auth/token_manager.js';
|
| 3 |
+
import { generateRequestId } from './idGenerator.js';
|
| 4 |
+
import os from 'os';
|
| 5 |
+
import { getReasoningSignature, getToolSignature } from './thoughtSignatureCache.js';
|
| 6 |
+
import { setToolNameMapping } from './toolNameCache.js';
|
| 7 |
+
|
| 8 |
+
// 思维链签名常量 - 暂时123占位
|
| 9 |
+
// Claude 模型签名
|
| 10 |
+
const CLAUDE_THOUGHT_SIGNATURE = 'RXFRRENrZ0lDaEFDR0FJcVFKV1Bvcy9GV20wSmtMV2FmWkFEbGF1ZTZzQTdRcFlTc1NvbklmemtSNFo4c1dqeitIRHBOYW9hS2NYTE1TeTF3bjh2T1RHdE1KVjVuYUNQ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|
+
// 兜底签名(非 Claude/Gemini 时)
|
| 16 |
+
const DEFAULT_THOUGHT_SIGNATURE = CLAUDE_THOUGHT_SIGNATURE;
|
| 17 |
+
|
| 18 |
+
function getThoughtSignatureForModel(actualModelName) {
|
| 19 |
+
if (!actualModelName) return DEFAULT_THOUGHT_SIGNATURE;
|
| 20 |
+
const lower = actualModelName.toLowerCase();
|
| 21 |
+
if (lower.includes('claude')) return CLAUDE_THOUGHT_SIGNATURE;
|
| 22 |
+
if (lower.includes('gemini')) return GEMINI_THOUGHT_SIGNATURE;
|
| 23 |
+
return DEFAULT_THOUGHT_SIGNATURE;
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
function extractImagesFromContent(content) {
|
| 27 |
+
const result = { text: '', images: [] };
|
| 28 |
+
|
| 29 |
+
// 如果content是字符串,直接返回
|
| 30 |
+
if (typeof content === 'string') {
|
| 31 |
+
result.text = content;
|
| 32 |
+
return result;
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
// 如果content是数组(multimodal格式)
|
| 36 |
+
if (Array.isArray(content)) {
|
| 37 |
+
for (const item of content) {
|
| 38 |
+
if (item.type === 'text') {
|
| 39 |
+
result.text += item.text;
|
| 40 |
+
} else if (item.type === 'image_url') {
|
| 41 |
+
// 提取base64图片数据
|
| 42 |
+
const imageUrl = item.image_url?.url || '';
|
| 43 |
+
|
| 44 |
+
// 匹配 data:image/{format};base64,{data} 格式
|
| 45 |
+
const match = imageUrl.match(/^data:image\/(\w+);base64,(.+)$/);
|
| 46 |
+
if (match) {
|
| 47 |
+
const format = match[1]; // 例如 png, jpeg, jpg
|
| 48 |
+
const base64Data = match[2];
|
| 49 |
+
result.images.push({
|
| 50 |
+
inlineData: {
|
| 51 |
+
mimeType: `image/${format}`,
|
| 52 |
+
data: base64Data
|
| 53 |
+
}
|
| 54 |
+
})
|
| 55 |
+
}
|
| 56 |
+
}
|
| 57 |
+
}
|
| 58 |
+
}
|
| 59 |
+
|
| 60 |
+
return result;
|
| 61 |
+
}
|
| 62 |
+
function handleUserMessage(extracted, antigravityMessages){
|
| 63 |
+
antigravityMessages.push({
|
| 64 |
+
role: "user",
|
| 65 |
+
parts: [
|
| 66 |
+
{
|
| 67 |
+
text: extracted.text
|
| 68 |
+
},
|
| 69 |
+
...extracted.images
|
| 70 |
+
]
|
| 71 |
+
})
|
| 72 |
+
}
|
| 73 |
+
// 将工具名称规范为 Vertex 要求的格式:^[a-zA-Z0-9_-]{1,128}$
|
| 74 |
+
function sanitizeToolName(name) {
|
| 75 |
+
if (!name || typeof name !== 'string') {
|
| 76 |
+
return 'tool';
|
| 77 |
+
}
|
| 78 |
+
// 替换非法字符为下划线
|
| 79 |
+
let cleaned = name.replace(/[^a-zA-Z0-9_-]/g, '_');
|
| 80 |
+
// 去掉首尾多余下划线
|
| 81 |
+
cleaned = cleaned.replace(/^_+|_+$/g, '');
|
| 82 |
+
if (!cleaned) {
|
| 83 |
+
cleaned = 'tool';
|
| 84 |
+
}
|
| 85 |
+
// 限制最大长度 128
|
| 86 |
+
if (cleaned.length > 128) {
|
| 87 |
+
cleaned = cleaned.slice(0, 128);
|
| 88 |
+
}
|
| 89 |
+
return cleaned;
|
| 90 |
+
}
|
| 91 |
+
function handleAssistantMessage(message, antigravityMessages, enableThinking, actualModelName, sessionId){
|
| 92 |
+
const lastMessage = antigravityMessages[antigravityMessages.length - 1];
|
| 93 |
+
const hasToolCalls = message.tool_calls && message.tool_calls.length > 0;
|
| 94 |
+
const hasContent = message.content && message.content.trim() !== '';
|
| 95 |
+
|
| 96 |
+
const antigravityTools = hasToolCalls ? message.tool_calls.map(toolCall => {
|
| 97 |
+
const originalName = toolCall.function.name;
|
| 98 |
+
const safeName = sanitizeToolName(originalName);
|
| 99 |
+
|
| 100 |
+
const part = {
|
| 101 |
+
functionCall: {
|
| 102 |
+
id: toolCall.id,
|
| 103 |
+
name: safeName,
|
| 104 |
+
args: {
|
| 105 |
+
query: toolCall.function.arguments
|
| 106 |
+
}
|
| 107 |
+
}
|
| 108 |
+
};
|
| 109 |
+
|
| 110 |
+
// 记录原始工具名到安全名的映射(仅当确实发生了变化时)
|
| 111 |
+
if (sessionId && actualModelName && safeName !== originalName) {
|
| 112 |
+
setToolNameMapping(sessionId, actualModelName, safeName, originalName);
|
| 113 |
+
}
|
| 114 |
+
|
| 115 |
+
// 启用思考模型时,工具调用优先使用实时签名(如果上游带了),否则兜底用常量
|
| 116 |
+
if (enableThinking) {
|
| 117 |
+
const cachedToolSig = getToolSignature(sessionId, actualModelName);
|
| 118 |
+
part.thoughtSignature = toolCall.thoughtSignature || cachedToolSig || TOOL_THOUGHT_SIGNATURE;
|
| 119 |
+
}
|
| 120 |
+
|
| 121 |
+
return part;
|
| 122 |
+
}) : [];
|
| 123 |
+
|
| 124 |
+
if (lastMessage?.role === "model" && hasToolCalls && !hasContent){
|
| 125 |
+
lastMessage.parts.push(...antigravityTools)
|
| 126 |
+
}else{
|
| 127 |
+
const parts = [];
|
| 128 |
+
|
| 129 |
+
// 对于启用思考的模型,在历史 assistant 消息中补一个思考块 + 签名块
|
| 130 |
+
// 结构示例:
|
| 131 |
+
// {
|
| 132 |
+
// "role": "model",
|
| 133 |
+
// "parts": [
|
| 134 |
+
// { "text": "␈", "thought": true },
|
| 135 |
+
// { "text": "␈", "thoughtSignature": "..." },
|
| 136 |
+
// { "text": "正常回复..." }
|
| 137 |
+
// ]
|
| 138 |
+
// }
|
| 139 |
+
if (enableThinking) {
|
| 140 |
+
// 普通思维链签名:
|
| 141 |
+
// 1. 优先使用消息自身携带的 thoughtSignature
|
| 142 |
+
// 2. 其次使用缓存中的最新签名(同 session + model)
|
| 143 |
+
// 3. 最后按模型类型选择内置兜底签名
|
| 144 |
+
const cachedSig = getReasoningSignature(sessionId, actualModelName);
|
| 145 |
+
const thoughtSignature = message.thoughtSignature || cachedSig || getThoughtSignatureForModel(actualModelName);
|
| 146 |
+
// 默认思考内容不能是完全空字符串,否则上游会要求 thinking 字段
|
| 147 |
+
// 这里用一个不可见的退格符作为占位,实际展示时等价于“空思考块”
|
| 148 |
+
let reasoningText = '';
|
| 149 |
+
if (typeof message.reasoning_content === 'string' && message.reasoning_content.length > 0) {
|
| 150 |
+
reasoningText = message.reasoning_content;
|
| 151 |
+
} else {
|
| 152 |
+
reasoningText = ' '; // 退格符占位
|
| 153 |
+
}
|
| 154 |
+
parts.push({ text: reasoningText, thought: true });
|
| 155 |
+
// 思维链签名占位,避免上游校验缺少签名字段
|
| 156 |
+
parts.push({ text: ' ', thoughtSignature });
|
| 157 |
+
}
|
| 158 |
+
|
| 159 |
+
if (hasContent) parts.push({ text: message.content.trimEnd() });
|
| 160 |
+
parts.push(...antigravityTools);
|
| 161 |
+
|
| 162 |
+
antigravityMessages.push({
|
| 163 |
+
role: "model",
|
| 164 |
+
parts
|
| 165 |
+
})
|
| 166 |
+
}
|
| 167 |
+
}
|
| 168 |
+
function handleToolCall(message, antigravityMessages){
|
| 169 |
+
// 从之前的 model 消息中找到对应的 functionCall name
|
| 170 |
+
let functionName = '';
|
| 171 |
+
for (let i = antigravityMessages.length - 1; i >= 0; i--) {
|
| 172 |
+
if (antigravityMessages[i].role === 'model') {
|
| 173 |
+
const parts = antigravityMessages[i].parts;
|
| 174 |
+
for (const part of parts) {
|
| 175 |
+
if (part.functionCall && part.functionCall.id === message.tool_call_id) {
|
| 176 |
+
functionName = part.functionCall.name;
|
| 177 |
+
break;
|
| 178 |
+
}
|
| 179 |
+
}
|
| 180 |
+
if (functionName) break;
|
| 181 |
+
}
|
| 182 |
+
}
|
| 183 |
+
|
| 184 |
+
const lastMessage = antigravityMessages[antigravityMessages.length - 1];
|
| 185 |
+
const functionResponse = {
|
| 186 |
+
functionResponse: {
|
| 187 |
+
id: message.tool_call_id,
|
| 188 |
+
name: functionName,
|
| 189 |
+
response: {
|
| 190 |
+
output: message.content
|
| 191 |
+
}
|
| 192 |
+
}
|
| 193 |
+
};
|
| 194 |
+
|
| 195 |
+
// 如果上一条消息是 user 且包含 functionResponse,则合并
|
| 196 |
+
if (lastMessage?.role === "user" && lastMessage.parts.some(p => p.functionResponse)) {
|
| 197 |
+
lastMessage.parts.push(functionResponse);
|
| 198 |
+
} else {
|
| 199 |
+
antigravityMessages.push({
|
| 200 |
+
role: "user",
|
| 201 |
+
parts: [functionResponse]
|
| 202 |
+
});
|
| 203 |
+
}
|
| 204 |
+
}
|
| 205 |
+
function openaiMessageToAntigravity(openaiMessages, enableThinking, actualModelName, sessionId){
|
| 206 |
+
const antigravityMessages = [];
|
| 207 |
+
for (const message of openaiMessages) {
|
| 208 |
+
if (message.role === "user" || message.role === "system") {
|
| 209 |
+
// system 消息作为 user 处理(开头的 system 已在 generateRequestBody 中过滤)
|
| 210 |
+
const extracted = extractImagesFromContent(message.content);
|
| 211 |
+
handleUserMessage(extracted, antigravityMessages);
|
| 212 |
+
} else if (message.role === "assistant") {
|
| 213 |
+
handleAssistantMessage(message, antigravityMessages, enableThinking, actualModelName, sessionId);
|
| 214 |
+
} else if (message.role === "tool") {
|
| 215 |
+
handleToolCall(message, antigravityMessages);
|
| 216 |
+
}
|
| 217 |
+
}
|
| 218 |
+
|
| 219 |
+
return antigravityMessages;
|
| 220 |
+
}
|
| 221 |
+
|
| 222 |
+
/**
|
| 223 |
+
* 从 OpenAI 消息中提取并合并 system 指令
|
| 224 |
+
* 规则:
|
| 225 |
+
* 1. SYSTEM_INSTRUCTION 作为基础 system,可为空
|
| 226 |
+
* 2. 根据 useContextSystemPrompt 配置决定是否收集请求中的 system 消息
|
| 227 |
+
* 3. 如果 useContextSystemPrompt=true,收集开头连续的 system 消息并合并
|
| 228 |
+
* 4. 如果 useContextSystemPrompt=false,只使用基础 SYSTEM_INSTRUCTION
|
| 229 |
+
*/
|
| 230 |
+
function extractSystemInstruction(openaiMessages) {
|
| 231 |
+
const baseSystem = config.systemInstruction || '';
|
| 232 |
+
|
| 233 |
+
// 如果不使用上下文 system,只返回基础 system
|
| 234 |
+
if (!config.useContextSystemPrompt) {
|
| 235 |
+
return baseSystem;
|
| 236 |
+
}
|
| 237 |
+
|
| 238 |
+
// 收集开头连续的 system 消息
|
| 239 |
+
const systemTexts = [];
|
| 240 |
+
for (const message of openaiMessages) {
|
| 241 |
+
if (message.role === 'system') {
|
| 242 |
+
const content = typeof message.content === 'string'
|
| 243 |
+
? message.content
|
| 244 |
+
: (Array.isArray(message.content)
|
| 245 |
+
? message.content.filter(item => item.type === 'text').map(item => item.text).join('')
|
| 246 |
+
: '');
|
| 247 |
+
if (content.trim()) {
|
| 248 |
+
systemTexts.push(content.trim());
|
| 249 |
+
}
|
| 250 |
+
} else {
|
| 251 |
+
// 遇到非 system 消息就停止收集
|
| 252 |
+
break;
|
| 253 |
+
}
|
| 254 |
+
}
|
| 255 |
+
|
| 256 |
+
// 合并:基础 system + 用户的 system 消息
|
| 257 |
+
const parts = [];
|
| 258 |
+
if (baseSystem.trim()) {
|
| 259 |
+
parts.push(baseSystem.trim());
|
| 260 |
+
}
|
| 261 |
+
if (systemTexts.length > 0) {
|
| 262 |
+
parts.push(systemTexts.join('\n\n'));
|
| 263 |
+
}
|
| 264 |
+
|
| 265 |
+
return parts.join('\n\n');
|
| 266 |
+
}
|
| 267 |
+
// reasoning_effort 到 thinkingBudget 的映射
|
| 268 |
+
const REASONING_EFFORT_MAP = {
|
| 269 |
+
'low': 1024,
|
| 270 |
+
'medium': 16000,
|
| 271 |
+
'high': 32000
|
| 272 |
+
};
|
| 273 |
+
|
| 274 |
+
function generateGenerationConfig(parameters, enableThinking, actualModelName){
|
| 275 |
+
// 获取思考预算:
|
| 276 |
+
// 1. 优先使用 thinking_budget(直接数值)
|
| 277 |
+
// 2. 其次使用 reasoning_effort(OpenAI 格式:low/medium/high)
|
| 278 |
+
// 3. 最后使用配置默认值或硬编码默认值
|
| 279 |
+
const defaultThinkingBudget = config.defaults.thinking_budget ?? 1024;
|
| 280 |
+
|
| 281 |
+
let thinkingBudget = 0;
|
| 282 |
+
if (enableThinking) {
|
| 283 |
+
if (parameters.thinking_budget !== undefined) {
|
| 284 |
+
thinkingBudget = parameters.thinking_budget;
|
| 285 |
+
} else if (parameters.reasoning_effort !== undefined) {
|
| 286 |
+
thinkingBudget = REASONING_EFFORT_MAP[parameters.reasoning_effort] ?? defaultThinkingBudget;
|
| 287 |
+
} else {
|
| 288 |
+
thinkingBudget = defaultThinkingBudget;
|
| 289 |
+
}
|
| 290 |
+
}
|
| 291 |
+
|
| 292 |
+
const generationConfig = {
|
| 293 |
+
topP: parameters.top_p ?? config.defaults.top_p,
|
| 294 |
+
topK: parameters.top_k ?? config.defaults.top_k,
|
| 295 |
+
temperature: parameters.temperature ?? config.defaults.temperature,
|
| 296 |
+
candidateCount: 1,
|
| 297 |
+
maxOutputTokens: parameters.max_tokens ?? config.defaults.max_tokens,
|
| 298 |
+
stopSequences: [
|
| 299 |
+
"<|user|>",
|
| 300 |
+
"<|bot|>",
|
| 301 |
+
"<|context_request|>",
|
| 302 |
+
"<|endoftext|>",
|
| 303 |
+
"<|end_of_turn|>"
|
| 304 |
+
],
|
| 305 |
+
thinkingConfig: {
|
| 306 |
+
includeThoughts: enableThinking,
|
| 307 |
+
thinkingBudget: thinkingBudget
|
| 308 |
+
}
|
| 309 |
+
}
|
| 310 |
+
if (enableThinking && actualModelName.includes("claude")){
|
| 311 |
+
delete generationConfig.topP;
|
| 312 |
+
}
|
| 313 |
+
return generationConfig
|
| 314 |
+
}
|
| 315 |
+
// 不被 Google 工具参数 Schema 支持的字段,在这里统一过滤掉
|
| 316 |
+
// 包括:
|
| 317 |
+
// - JSON Schema 的元信息字段:$schema, additionalProperties
|
| 318 |
+
// - 长度/数量约束:minLength, maxLength, minItems, maxItems, uniqueItems(不必传给后端)
|
| 319 |
+
// - 严格上下界 / 常量:exclusiveMaximum, exclusiveMinimum, const(Google Schema 不支持)
|
| 320 |
+
// - 组合约束:anyOf/oneOf/allOf 以及其非标准写法 any_of/one_of/all_of(为避免上游实现差异,这里一律去掉)
|
| 321 |
+
const EXCLUDED_KEYS = new Set([
|
| 322 |
+
'$schema',
|
| 323 |
+
'additionalProperties',
|
| 324 |
+
'minLength',
|
| 325 |
+
'maxLength',
|
| 326 |
+
'minItems',
|
| 327 |
+
'maxItems',
|
| 328 |
+
'uniqueItems',
|
| 329 |
+
'exclusiveMaximum',
|
| 330 |
+
'exclusiveMinimum',
|
| 331 |
+
'const',
|
| 332 |
+
'anyOf',
|
| 333 |
+
'oneOf',
|
| 334 |
+
'allOf',
|
| 335 |
+
'any_of',
|
| 336 |
+
'one_of',
|
| 337 |
+
'all_of'
|
| 338 |
+
]);
|
| 339 |
+
|
| 340 |
+
function cleanParameters(obj) {
|
| 341 |
+
if (!obj || typeof obj !== 'object') return obj;
|
| 342 |
+
|
| 343 |
+
const cleaned = Array.isArray(obj) ? [] : {};
|
| 344 |
+
|
| 345 |
+
for (const [key, value] of Object.entries(obj)) {
|
| 346 |
+
if (EXCLUDED_KEYS.has(key)) continue;
|
| 347 |
+
const cleanedValue = (value && typeof value === 'object') ? cleanParameters(value) : value;
|
| 348 |
+
cleaned[key] = cleanedValue;
|
| 349 |
+
}
|
| 350 |
+
|
| 351 |
+
return cleaned;
|
| 352 |
+
}
|
| 353 |
+
|
| 354 |
+
function convertOpenAIToolsToAntigravity(openaiTools, sessionId, actualModelName){
|
| 355 |
+
if (!openaiTools || openaiTools.length === 0) return [];
|
| 356 |
+
return openaiTools.map((tool)=>{
|
| 357 |
+
// 先清洗一遍参数,过滤/规范化不兼容字段
|
| 358 |
+
const rawParams = tool.function?.parameters || {};
|
| 359 |
+
const cleanedParams = cleanParameters(rawParams) || {};
|
| 360 |
+
|
| 361 |
+
// 确保顶层是一个合法的 JSON Schema 对象
|
| 362 |
+
// 如果用户没显式指定 type,则默认按 OpenAI 习惯设为 object
|
| 363 |
+
if (cleanedParams.type === undefined) {
|
| 364 |
+
cleanedParams.type = 'object';
|
| 365 |
+
}
|
| 366 |
+
// 对于 object 类型,至少保证有 properties 字段
|
| 367 |
+
if (cleanedParams.type === 'object' && cleanedParams.properties === undefined) {
|
| 368 |
+
cleanedParams.properties = {};
|
| 369 |
+
}
|
| 370 |
+
|
| 371 |
+
const originalName = tool.function?.name;
|
| 372 |
+
const safeName = sanitizeToolName(originalName);
|
| 373 |
+
|
| 374 |
+
// 仅当发生转换时才缓存映射
|
| 375 |
+
if (sessionId && actualModelName && safeName !== originalName) {
|
| 376 |
+
setToolNameMapping(sessionId, actualModelName, safeName, originalName);
|
| 377 |
+
}
|
| 378 |
+
|
| 379 |
+
return {
|
| 380 |
+
functionDeclarations: [
|
| 381 |
+
{
|
| 382 |
+
name: safeName,
|
| 383 |
+
description: tool.function.description,
|
| 384 |
+
parameters: cleanedParams
|
| 385 |
+
}
|
| 386 |
+
]
|
| 387 |
+
}
|
| 388 |
+
})
|
| 389 |
+
}
|
| 390 |
+
|
| 391 |
+
function modelMapping(modelName){
|
| 392 |
+
if (modelName === "claude-sonnet-4-5-thinking"){
|
| 393 |
+
return "claude-sonnet-4-5";
|
| 394 |
+
} else if (modelName === "claude-opus-4-5"){
|
| 395 |
+
return "claude-opus-4-5-thinking";
|
| 396 |
+
} else if (modelName === "gemini-2.5-flash-thinking"){
|
| 397 |
+
return "gemini-2.5-flash";
|
| 398 |
+
}
|
| 399 |
+
return modelName;
|
| 400 |
+
}
|
| 401 |
+
|
| 402 |
+
function isEnableThinking(modelName){
|
| 403 |
+
// 只要模型名里包含 -thinking(例如 gemini-2.0-flash-thinking-exp),就认为支持思考配置
|
| 404 |
+
return modelName.includes('-thinking') ||
|
| 405 |
+
modelName === 'gemini-2.5-pro' ||
|
| 406 |
+
modelName.startsWith('gemini-3-pro-') ||
|
| 407 |
+
modelName === "rev19-uic3-1p" ||
|
| 408 |
+
modelName === "gpt-oss-120b-medium";
|
| 409 |
+
}
|
| 410 |
+
|
| 411 |
+
function generateRequestBody(openaiMessages,modelName,parameters,openaiTools,token){
|
| 412 |
+
|
| 413 |
+
const enableThinking = isEnableThinking(modelName);
|
| 414 |
+
const actualModelName = modelMapping(modelName);
|
| 415 |
+
|
| 416 |
+
// 提取合并后的 system 指令
|
| 417 |
+
const mergedSystemInstruction = extractSystemInstruction(openaiMessages);
|
| 418 |
+
|
| 419 |
+
// 根据 useContextSystemPrompt 配置决定如何处理 system 消息
|
| 420 |
+
let startIndex = 0;
|
| 421 |
+
if (config.useContextSystemPrompt) {
|
| 422 |
+
// 过滤掉开头连续的 system 消息,避免重复作为 user 发送
|
| 423 |
+
for (let i = 0; i < openaiMessages.length; i++) {
|
| 424 |
+
if (openaiMessages[i].role === 'system') {
|
| 425 |
+
startIndex = i + 1;
|
| 426 |
+
} else {
|
| 427 |
+
break;
|
| 428 |
+
}
|
| 429 |
+
}
|
| 430 |
+
}
|
| 431 |
+
const filteredMessages = openaiMessages.slice(startIndex);
|
| 432 |
+
|
| 433 |
+
const requestBody = {
|
| 434 |
+
project: token.projectId,
|
| 435 |
+
requestId: generateRequestId(),
|
| 436 |
+
request: {
|
| 437 |
+
contents: openaiMessageToAntigravity(filteredMessages, enableThinking, actualModelName, token.sessionId),
|
| 438 |
+
tools: convertOpenAIToolsToAntigravity(openaiTools, token.sessionId, actualModelName),
|
| 439 |
+
toolConfig: {
|
| 440 |
+
functionCallingConfig: {
|
| 441 |
+
mode: "VALIDATED"
|
| 442 |
+
}
|
| 443 |
+
},
|
| 444 |
+
generationConfig: generateGenerationConfig(parameters, enableThinking, actualModelName),
|
| 445 |
+
sessionId: token.sessionId
|
| 446 |
+
},
|
| 447 |
+
model: actualModelName,
|
| 448 |
+
userAgent: "antigravity"
|
| 449 |
+
};
|
| 450 |
+
|
| 451 |
+
// 只有当有 system 指令时才添加 systemInstruction 字段
|
| 452 |
+
if (mergedSystemInstruction) {
|
| 453 |
+
requestBody.request.systemInstruction = {
|
| 454 |
+
role: "user",
|
| 455 |
+
parts: [{ text: mergedSystemInstruction }]
|
| 456 |
+
};
|
| 457 |
+
}
|
| 458 |
+
|
| 459 |
+
return requestBody;
|
| 460 |
+
}
|
| 461 |
+
/**
|
| 462 |
+
* 将通用文本对话请求体转换为图片生成请求体
|
| 463 |
+
* 统一配置 image_gen 所需字段,避免在各处手动删除/覆盖字段
|
| 464 |
+
*/
|
| 465 |
+
function prepareImageRequest(requestBody) {
|
| 466 |
+
if (!requestBody || !requestBody.request) return requestBody;
|
| 467 |
+
|
| 468 |
+
requestBody.request.generationConfig = { candidateCount: 1 };
|
| 469 |
+
requestBody.requestType = 'image_gen';
|
| 470 |
+
|
| 471 |
+
// image_gen 模式下不需要这些字段
|
| 472 |
+
delete requestBody.request.systemInstruction;
|
| 473 |
+
delete requestBody.request.tools;
|
| 474 |
+
delete requestBody.request.toolConfig;
|
| 475 |
+
|
| 476 |
+
return requestBody;
|
| 477 |
+
}
|
| 478 |
+
|
| 479 |
+
function getDefaultIp(){
|
| 480 |
+
const interfaces = os.networkInterfaces();
|
| 481 |
+
for (const iface of Object.values(interfaces)){
|
| 482 |
+
for (const inter of iface){
|
| 483 |
+
if (inter.family === 'IPv4' && !inter.internal){
|
| 484 |
+
return inter.address;
|
| 485 |
+
}
|
| 486 |
+
}
|
| 487 |
+
}
|
| 488 |
+
return '127.0.0.1';
|
| 489 |
+
}
|
| 490 |
+
|
| 491 |
+
function generateGeminiRequestBody(geminiBody, modelName, token){
|
| 492 |
+
const enableThinking = isEnableThinking(modelName);
|
| 493 |
+
const actualModelName = modelMapping(modelName);
|
| 494 |
+
|
| 495 |
+
// 深拷贝 body,避免修改原始对象
|
| 496 |
+
const request = JSON.parse(JSON.stringify(geminiBody));
|
| 497 |
+
//console.log(JSON.stringify(request,null,2));
|
| 498 |
+
|
| 499 |
+
// 处理 contents 中的 functionCall 和 functionResponse,确保有 id 字段
|
| 500 |
+
if (request.contents && Array.isArray(request.contents)) {
|
| 501 |
+
// 第一遍:收集所有 functionCall 的 name -> id 映射
|
| 502 |
+
const functionCallIds = new Map();
|
| 503 |
+
request.contents.forEach(content => {
|
| 504 |
+
if (content.role === 'model' && content.parts && Array.isArray(content.parts)) {
|
| 505 |
+
content.parts.forEach(part => {
|
| 506 |
+
if (part.functionCall) {
|
| 507 |
+
if (!part.functionCall.id) {
|
| 508 |
+
part.functionCall.id = `call_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
|
| 509 |
+
}
|
| 510 |
+
// 记录 name -> id 映射
|
| 511 |
+
functionCallIds.set(part.functionCall.name, part.functionCall.id);
|
| 512 |
+
}
|
| 513 |
+
});
|
| 514 |
+
}
|
| 515 |
+
});
|
| 516 |
+
|
| 517 |
+
// 第二遍:为 functionResponse 匹配对应的 id
|
| 518 |
+
request.contents.forEach(content => {
|
| 519 |
+
if (content.role === 'user' && content.parts && Array.isArray(content.parts)) {
|
| 520 |
+
content.parts.forEach(part => {
|
| 521 |
+
if (part.functionResponse && !part.functionResponse.id) {
|
| 522 |
+
// 尝试从映射中找到对应的 id
|
| 523 |
+
const matchedId = functionCallIds.get(part.functionResponse.name);
|
| 524 |
+
part.functionResponse.id = matchedId || `call_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
|
| 525 |
+
}
|
| 526 |
+
});
|
| 527 |
+
}
|
| 528 |
+
});
|
| 529 |
+
}
|
| 530 |
+
|
| 531 |
+
// 确保 generationConfig 存在
|
| 532 |
+
if (!request.generationConfig) {
|
| 533 |
+
request.generationConfig = {};
|
| 534 |
+
}
|
| 535 |
+
|
| 536 |
+
// 处理思考模型配置
|
| 537 |
+
if (enableThinking) {
|
| 538 |
+
const defaultThinkingBudget = config.defaults.thinking_budget ?? 1024;
|
| 539 |
+
// 如果没有 thinkingConfig,尝试注入
|
| 540 |
+
if (!request.generationConfig.thinkingConfig) {
|
| 541 |
+
request.generationConfig.thinkingConfig = {
|
| 542 |
+
includeThoughts: true,
|
| 543 |
+
thinkingBudget: defaultThinkingBudget
|
| 544 |
+
};
|
| 545 |
+
}
|
| 546 |
+
}
|
| 547 |
+
|
| 548 |
+
// 强制 candidateCount 为 1
|
| 549 |
+
request.generationConfig.candidateCount = 1;
|
| 550 |
+
|
| 551 |
+
// 注入 sessionId
|
| 552 |
+
request.sessionId = token.sessionId;
|
| 553 |
+
delete request.safetySettings;
|
| 554 |
+
|
| 555 |
+
// 构造 Antigravity 请求体
|
| 556 |
+
const requestBody = {
|
| 557 |
+
project: token.projectId,
|
| 558 |
+
requestId: generateRequestId(),
|
| 559 |
+
request: request,
|
| 560 |
+
model: actualModelName,
|
| 561 |
+
userAgent: "antigravity"
|
| 562 |
+
};
|
| 563 |
+
|
| 564 |
+
return requestBody;
|
| 565 |
+
}
|
| 566 |
+
|
| 567 |
+
// ==================== Claude API 转换函数 ====================
|
| 568 |
+
|
| 569 |
+
/**
|
| 570 |
+
* 从 Claude 消息内容中提取图片
|
| 571 |
+
* Claude 格式: { type: "image", source: { type: "base64", media_type: "image/png", data: "..." } }
|
| 572 |
+
*/
|
| 573 |
+
function extractImagesFromClaudeContent(content) {
|
| 574 |
+
const result = { text: '', images: [] };
|
| 575 |
+
|
| 576 |
+
if (typeof content === 'string') {
|
| 577 |
+
result.text = content;
|
| 578 |
+
return result;
|
| 579 |
+
}
|
| 580 |
+
|
| 581 |
+
if (Array.isArray(content)) {
|
| 582 |
+
for (const item of content) {
|
| 583 |
+
if (item.type === 'text') {
|
| 584 |
+
result.text += item.text || '';
|
| 585 |
+
} else if (item.type === 'image') {
|
| 586 |
+
// Claude 格式的图片
|
| 587 |
+
const source = item.source;
|
| 588 |
+
if (source && source.type === 'base64' && source.data) {
|
| 589 |
+
result.images.push({
|
| 590 |
+
inlineData: {
|
| 591 |
+
mimeType: source.media_type || 'image/png',
|
| 592 |
+
data: source.data
|
| 593 |
+
}
|
| 594 |
+
});
|
| 595 |
+
}
|
| 596 |
+
}
|
| 597 |
+
}
|
| 598 |
+
}
|
| 599 |
+
|
| 600 |
+
return result;
|
| 601 |
+
}
|
| 602 |
+
|
| 603 |
+
/**
|
| 604 |
+
* 处理 Claude 用户消息
|
| 605 |
+
*/
|
| 606 |
+
function handleClaudeUserMessage(extracted, antigravityMessages) {
|
| 607 |
+
antigravityMessages.push({
|
| 608 |
+
role: "user",
|
| 609 |
+
parts: [
|
| 610 |
+
{ text: extracted.text },
|
| 611 |
+
...extracted.images
|
| 612 |
+
]
|
| 613 |
+
});
|
| 614 |
+
}
|
| 615 |
+
|
| 616 |
+
/**
|
| 617 |
+
* 处理 Claude 助手消息(包含 tool_use)
|
| 618 |
+
*/
|
| 619 |
+
function handleClaudeAssistantMessage(message, antigravityMessages, enableThinking, actualModelName, sessionId) {
|
| 620 |
+
const lastMessage = antigravityMessages[antigravityMessages.length - 1];
|
| 621 |
+
const content = message.content;
|
| 622 |
+
|
| 623 |
+
// 解析 content 数组
|
| 624 |
+
let textContent = '';
|
| 625 |
+
const toolCalls = [];
|
| 626 |
+
|
| 627 |
+
if (typeof content === 'string') {
|
| 628 |
+
textContent = content;
|
| 629 |
+
} else if (Array.isArray(content)) {
|
| 630 |
+
for (const item of content) {
|
| 631 |
+
if (item.type === 'text') {
|
| 632 |
+
textContent += item.text || '';
|
| 633 |
+
} else if (item.type === 'tool_use') {
|
| 634 |
+
// Claude 的 tool_use 格式
|
| 635 |
+
const originalName = item.name;
|
| 636 |
+
const safeName = sanitizeToolName(originalName);
|
| 637 |
+
|
| 638 |
+
const part = {
|
| 639 |
+
functionCall: {
|
| 640 |
+
id: item.id,
|
| 641 |
+
name: safeName,
|
| 642 |
+
args: {
|
| 643 |
+
query: JSON.stringify(item.input || {})
|
| 644 |
+
}
|
| 645 |
+
}
|
| 646 |
+
};
|
| 647 |
+
|
| 648 |
+
// 记录工具名映射
|
| 649 |
+
if (sessionId && actualModelName && safeName !== originalName) {
|
| 650 |
+
setToolNameMapping(sessionId, actualModelName, safeName, originalName);
|
| 651 |
+
}
|
| 652 |
+
|
| 653 |
+
toolCalls.push(part);
|
| 654 |
+
}
|
| 655 |
+
}
|
| 656 |
+
}
|
| 657 |
+
|
| 658 |
+
const hasToolCalls = toolCalls.length > 0;
|
| 659 |
+
const hasContent = textContent && textContent.trim() !== '';
|
| 660 |
+
|
| 661 |
+
if (lastMessage?.role === "model" && hasToolCalls && !hasContent) {
|
| 662 |
+
lastMessage.parts.push(...toolCalls);
|
| 663 |
+
} else {
|
| 664 |
+
const parts = [];
|
| 665 |
+
|
| 666 |
+
// 思维链处理(与 OpenAI 相同)
|
| 667 |
+
if (enableThinking) {
|
| 668 |
+
const cachedSig = getReasoningSignature(sessionId, actualModelName);
|
| 669 |
+
const thoughtSignature = cachedSig || getThoughtSignatureForModel(actualModelName);
|
| 670 |
+
parts.push({ text: ' ', thought: true });
|
| 671 |
+
parts.push({ text: ' ', thoughtSignature });
|
| 672 |
+
}
|
| 673 |
+
|
| 674 |
+
if (hasContent) parts.push({ text: textContent.trimEnd() });
|
| 675 |
+
parts.push(...toolCalls);
|
| 676 |
+
|
| 677 |
+
antigravityMessages.push({
|
| 678 |
+
role: "model",
|
| 679 |
+
parts
|
| 680 |
+
});
|
| 681 |
+
}
|
| 682 |
+
}
|
| 683 |
+
|
| 684 |
+
/**
|
| 685 |
+
* 处理 Claude tool_result 消息
|
| 686 |
+
*/
|
| 687 |
+
function handleClaudeToolResult(message, antigravityMessages) {
|
| 688 |
+
const content = message.content;
|
| 689 |
+
|
| 690 |
+
if (!Array.isArray(content)) return;
|
| 691 |
+
|
| 692 |
+
for (const item of content) {
|
| 693 |
+
if (item.type !== 'tool_result') continue;
|
| 694 |
+
|
| 695 |
+
const toolUseId = item.tool_use_id;
|
| 696 |
+
|
| 697 |
+
// 从之前的 model 消息中找到对应的 functionCall name
|
| 698 |
+
let functionName = '';
|
| 699 |
+
for (let i = antigravityMessages.length - 1; i >= 0; i--) {
|
| 700 |
+
if (antigravityMessages[i].role === 'model') {
|
| 701 |
+
const parts = antigravityMessages[i].parts;
|
| 702 |
+
for (const part of parts) {
|
| 703 |
+
if (part.functionCall && part.functionCall.id === toolUseId) {
|
| 704 |
+
functionName = part.functionCall.name;
|
| 705 |
+
break;
|
| 706 |
+
}
|
| 707 |
+
}
|
| 708 |
+
if (functionName) break;
|
| 709 |
+
}
|
| 710 |
+
}
|
| 711 |
+
|
| 712 |
+
const lastMessage = antigravityMessages[antigravityMessages.length - 1];
|
| 713 |
+
|
| 714 |
+
// 提取工具结果内容
|
| 715 |
+
let resultContent = '';
|
| 716 |
+
if (typeof item.content === 'string') {
|
| 717 |
+
resultContent = item.content;
|
| 718 |
+
} else if (Array.isArray(item.content)) {
|
| 719 |
+
resultContent = item.content
|
| 720 |
+
.filter(c => c.type === 'text')
|
| 721 |
+
.map(c => c.text)
|
| 722 |
+
.join('');
|
| 723 |
+
}
|
| 724 |
+
|
| 725 |
+
const functionResponse = {
|
| 726 |
+
functionResponse: {
|
| 727 |
+
id: toolUseId,
|
| 728 |
+
name: functionName,
|
| 729 |
+
response: {
|
| 730 |
+
output: resultContent
|
| 731 |
+
}
|
| 732 |
+
}
|
| 733 |
+
};
|
| 734 |
+
|
| 735 |
+
// 如果上一条消息是 user 且包含 functionResponse,则合并
|
| 736 |
+
if (lastMessage?.role === "user" && lastMessage.parts.some(p => p.functionResponse)) {
|
| 737 |
+
lastMessage.parts.push(functionResponse);
|
| 738 |
+
} else {
|
| 739 |
+
antigravityMessages.push({
|
| 740 |
+
role: "user",
|
| 741 |
+
parts: [functionResponse]
|
| 742 |
+
});
|
| 743 |
+
}
|
| 744 |
+
}
|
| 745 |
+
}
|
| 746 |
+
|
| 747 |
+
/**
|
| 748 |
+
* 将 Claude 消息转换为 Antigravity 格式
|
| 749 |
+
*/
|
| 750 |
+
function claudeMessageToAntigravity(claudeMessages, enableThinking, actualModelName, sessionId) {
|
| 751 |
+
const antigravityMessages = [];
|
| 752 |
+
|
| 753 |
+
for (const message of claudeMessages) {
|
| 754 |
+
if (message.role === "user") {
|
| 755 |
+
// 检查是否包含 tool_result
|
| 756 |
+
const content = message.content;
|
| 757 |
+
if (Array.isArray(content) && content.some(item => item.type === 'tool_result')) {
|
| 758 |
+
handleClaudeToolResult(message, antigravityMessages);
|
| 759 |
+
} else {
|
| 760 |
+
const extracted = extractImagesFromClaudeContent(content);
|
| 761 |
+
handleClaudeUserMessage(extracted, antigravityMessages);
|
| 762 |
+
}
|
| 763 |
+
} else if (message.role === "assistant") {
|
| 764 |
+
handleClaudeAssistantMessage(message, antigravityMessages, enableThinking, actualModelName, sessionId);
|
| 765 |
+
}
|
| 766 |
+
}
|
| 767 |
+
|
| 768 |
+
return antigravityMessages;
|
| 769 |
+
}
|
| 770 |
+
|
| 771 |
+
/**
|
| 772 |
+
* 将 Claude 工具格式转换为 Antigravity 格式
|
| 773 |
+
* Claude: { name, description, input_schema: {...} }
|
| 774 |
+
* Antigravity/Gemini: { functionDeclarations: [{ name, description, parameters: {...} }] }
|
| 775 |
+
*/
|
| 776 |
+
function convertClaudeToolsToAntigravity(claudeTools, sessionId, actualModelName) {
|
| 777 |
+
if (!claudeTools || claudeTools.length === 0) return [];
|
| 778 |
+
|
| 779 |
+
return claudeTools.map((tool) => {
|
| 780 |
+
// 清洗参数
|
| 781 |
+
const rawParams = tool.input_schema || {};
|
| 782 |
+
const cleanedParams = cleanParameters(rawParams) || {};
|
| 783 |
+
|
| 784 |
+
// 确保顶层是合法的 JSON Schema 对象
|
| 785 |
+
if (cleanedParams.type === undefined) {
|
| 786 |
+
cleanedParams.type = 'object';
|
| 787 |
+
}
|
| 788 |
+
if (cleanedParams.type === 'object' && cleanedParams.properties === undefined) {
|
| 789 |
+
cleanedParams.properties = {};
|
| 790 |
+
}
|
| 791 |
+
|
| 792 |
+
const originalName = tool.name;
|
| 793 |
+
const safeName = sanitizeToolName(originalName);
|
| 794 |
+
|
| 795 |
+
// 缓存映射
|
| 796 |
+
if (sessionId && actualModelName && safeName !== originalName) {
|
| 797 |
+
setToolNameMapping(sessionId, actualModelName, safeName, originalName);
|
| 798 |
+
}
|
| 799 |
+
|
| 800 |
+
return {
|
| 801 |
+
functionDeclarations: [
|
| 802 |
+
{
|
| 803 |
+
name: safeName,
|
| 804 |
+
description: tool.description || '',
|
| 805 |
+
parameters: cleanedParams
|
| 806 |
+
}
|
| 807 |
+
]
|
| 808 |
+
};
|
| 809 |
+
});
|
| 810 |
+
}
|
| 811 |
+
|
| 812 |
+
/**
|
| 813 |
+
* 生成 Claude 请求体并转换为 Antigravity 格式
|
| 814 |
+
*/
|
| 815 |
+
function generateClaudeRequestBody(claudeMessages, modelName, parameters, claudeTools, systemPrompt, token) {
|
| 816 |
+
const enableThinking = isEnableThinking(modelName);
|
| 817 |
+
const actualModelName = modelMapping(modelName);
|
| 818 |
+
|
| 819 |
+
// 合并 system 指令
|
| 820 |
+
const baseSystem = config.systemInstruction || '';
|
| 821 |
+
let mergedSystem = '';
|
| 822 |
+
|
| 823 |
+
if (config.useContextSystemPrompt && systemPrompt) {
|
| 824 |
+
const parts = [];
|
| 825 |
+
if (baseSystem.trim()) parts.push(baseSystem.trim());
|
| 826 |
+
if (systemPrompt.trim()) parts.push(systemPrompt.trim());
|
| 827 |
+
mergedSystem = parts.join('\n\n');
|
| 828 |
+
} else {
|
| 829 |
+
mergedSystem = baseSystem;
|
| 830 |
+
}
|
| 831 |
+
|
| 832 |
+
const requestBody = {
|
| 833 |
+
project: token.projectId,
|
| 834 |
+
requestId: generateRequestId(),
|
| 835 |
+
request: {
|
| 836 |
+
contents: claudeMessageToAntigravity(claudeMessages, enableThinking, actualModelName, token.sessionId),
|
| 837 |
+
tools: convertClaudeToolsToAntigravity(claudeTools, token.sessionId, actualModelName),
|
| 838 |
+
toolConfig: {
|
| 839 |
+
functionCallingConfig: {
|
| 840 |
+
mode: "VALIDATED"
|
| 841 |
+
}
|
| 842 |
+
},
|
| 843 |
+
generationConfig: generateGenerationConfig(parameters, enableThinking, actualModelName),
|
| 844 |
+
sessionId: token.sessionId
|
| 845 |
+
},
|
| 846 |
+
model: actualModelName,
|
| 847 |
+
userAgent: "antigravity"
|
| 848 |
+
};
|
| 849 |
+
|
| 850 |
+
// 只有当有 system 指令时才添加
|
| 851 |
+
if (mergedSystem) {
|
| 852 |
+
requestBody.request.systemInstruction = {
|
| 853 |
+
role: "user",
|
| 854 |
+
parts: [{ text: mergedSystem }]
|
| 855 |
+
};
|
| 856 |
+
}
|
| 857 |
+
|
| 858 |
+
return requestBody;
|
| 859 |
+
}
|
| 860 |
+
|
| 861 |
+
export{
|
| 862 |
+
generateRequestId,
|
| 863 |
+
generateRequestBody,
|
| 864 |
+
generateGeminiRequestBody,
|
| 865 |
+
generateClaudeRequestBody,
|
| 866 |
+
prepareImageRequest,
|
| 867 |
+
getDefaultIp
|
| 868 |
+
}
|