Upload 150 files
Browse files- src/gemini/client/index.ts +606 -544
- src/gemini/transport/http.ts +133 -128
- src/http/google/stream.ts +154 -152
- src/http/openai/chat-stream.ts +285 -283
- src/http/openai/responses-stream.ts +340 -339
src/gemini/client/index.ts
CHANGED
|
@@ -1,544 +1,606 @@
|
|
| 1 |
-
import { getPageTokens } from "../uploads/index";
|
| 2 |
-
import { httpFetch } from "../transport";
|
| 3 |
-
import { abortError, isAbortError, throwIfAborted } from "../../shared/abort";
|
| 4 |
-
import { log } from "../../shared/logging";
|
| 5 |
-
import { uuid } from "../../shared/crypto";
|
| 6 |
-
import {
|
| 7 |
-
dataAnalysisEmptyResponseError,
|
| 8 |
-
invalidGeminiCookieError,
|
| 9 |
-
isDataAnalysisEmptyResponseError,
|
| 10 |
-
isInvalidGeminiCookieError,
|
| 11 |
-
isLargePromptEmptyResponseError,
|
| 12 |
-
largePromptEmptyResponseError,
|
| 13 |
-
largePromptEmptyResponseThreshold,
|
| 14 |
-
upstreamImageGenerationEmptyError,
|
| 15 |
-
upstreamImageProviderError,
|
| 16 |
-
upstreamEmptyResponseError,
|
| 17 |
-
unverifiedGeminiCookieError,
|
| 18 |
-
} from "./errors";
|
| 19 |
-
import { buildHeaders, buildPayload, getUrl } from "./protocol";
|
| 20 |
-
import {
|
| 21 |
-
createStreamTextExtractor,
|
| 22 |
-
extractResponseParts,
|
| 23 |
-
extractResponseText,
|
| 24 |
-
richResponseShapeSummary,
|
| 25 |
-
wrbResponseShapeSummary,
|
| 26 |
-
} from "./parser";
|
| 27 |
-
import { hydrateGeneratedImages } from "./generated-images";
|
| 28 |
-
import type { GeminiRichImage } from "./generated-images";
|
| 29 |
-
import {
|
| 30 |
-
configWithCachedGeminiBuildLabel,
|
| 31 |
-
refreshGeminiBuildLabelForRetry,
|
| 32 |
-
waitBeforeRetry,
|
| 33 |
-
} from "./retry";
|
| 34 |
-
import {
|
| 35 |
-
configWithFreshGeminiCookie,
|
| 36 |
-
rotateGeminiCookieForRetryWithReason,
|
| 37 |
-
} from "../cookies";
|
| 38 |
-
import type { RuntimeConfig } from "../../config";
|
| 39 |
-
import type { ErrorWithMetadata } from "../../shared/types";
|
| 40 |
-
|
| 41 |
-
type GeminiFileRef =
|
| 42 |
-
| string
|
| 43 |
-
| {
|
| 44 |
-
ref?: unknown;
|
| 45 |
-
fileRef?: unknown;
|
| 46 |
-
id?: unknown;
|
| 47 |
-
name?: unknown;
|
| 48 |
-
filename?: unknown;
|
| 49 |
-
};
|
| 50 |
-
|
| 51 |
-
type GeminiStreamOptions = {
|
| 52 |
-
signal?: AbortSignal;
|
| 53 |
-
};
|
| 54 |
-
|
| 55 |
-
type GeminiRichOptions = {
|
| 56 |
-
hydrateGeneratedImageBytes?: boolean;
|
| 57 |
-
};
|
| 58 |
-
|
| 59 |
-
export type { GeminiRichImage } from "./generated-images";
|
| 60 |
-
|
| 61 |
-
export type GeminiRichOutput = {
|
| 62 |
-
text: string;
|
| 63 |
-
images: GeminiRichImage[];
|
| 64 |
-
};
|
| 65 |
-
|
| 66 |
-
export {
|
| 67 |
-
cleanText,
|
| 68 |
-
extractResponseParts,
|
| 69 |
-
extractResponseText,
|
| 70 |
-
extractTextsFromLine,
|
| 71 |
-
richResponseShapeSummary,
|
| 72 |
-
wrbResponseShapeSummary,
|
| 73 |
-
} from "./parser";
|
| 74 |
-
export { buildHeaders, buildPayload, getUrl } from "./protocol";
|
| 75 |
-
export { getFreshGeminiBuildLabel } from "./retry";
|
| 76 |
-
|
| 77 |
-
async function appendGeminiPageToken(
|
| 78 |
-
cfg: RuntimeConfig,
|
| 79 |
-
body: string,
|
| 80 |
-
): Promise<string> {
|
| 81 |
-
if (cfg.xsrf_token) return `${body}&at=${encodeURIComponent(cfg.xsrf_token)}`;
|
| 82 |
-
if (!cfg.cookie) return body;
|
| 83 |
-
const tokens = await getPageTokens(cfg);
|
| 84 |
-
if (!tokens.at) {
|
| 85 |
-
log(cfg, "gemini cookie verification failed reason=missing_page_at_token");
|
| 86 |
-
throw unverifiedGeminiCookieError("missing_page_at_token");
|
| 87 |
-
}
|
| 88 |
-
return `${body}&at=${encodeURIComponent(tokens.at)}`;
|
| 89 |
-
}
|
| 90 |
-
|
| 91 |
-
async function fetchGeminiStreamGenerate(
|
| 92 |
-
cfg: RuntimeConfig,
|
| 93 |
-
activeCfg: RuntimeConfig,
|
| 94 |
-
body: string,
|
| 95 |
-
signal: AbortSignal | null | undefined = undefined,
|
| 96 |
-
modelHeaders: Record<string, string> | null = null,
|
| 97 |
-
requestId: string | null = null,
|
| 98 |
-
) {
|
| 99 |
-
const url = getUrl(activeCfg);
|
| 100 |
-
const headers = await buildHeaders(activeCfg, modelHeaders, requestId);
|
| 101 |
-
const requestBody = await appendGeminiPageToken(activeCfg, body);
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
}
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
let
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
let
|
| 129 |
-
|
| 130 |
-
const
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
const
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
let
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
let
|
| 225 |
-
|
| 226 |
-
const
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
const
|
| 248 |
-
|
| 249 |
-
if (
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
)
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
|
| 369 |
-
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
|
| 376 |
-
|
| 377 |
-
|
| 378 |
-
|
| 379 |
-
|
| 380 |
-
|
| 381 |
-
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
|
| 385 |
-
|
| 386 |
-
|
| 387 |
-
|
| 388 |
-
|
| 389 |
-
|
| 390 |
-
|
| 391 |
-
|
| 392 |
-
|
| 393 |
-
|
| 394 |
-
|
| 395 |
-
|
| 396 |
-
|
| 397 |
-
|
| 398 |
-
|
| 399 |
-
|
| 400 |
-
|
| 401 |
-
|
| 402 |
-
|
| 403 |
-
|
| 404 |
-
|
| 405 |
-
|
| 406 |
-
|
| 407 |
-
if (!
|
| 408 |
-
|
| 409 |
-
|
| 410 |
-
|
| 411 |
-
|
| 412 |
-
|
| 413 |
-
|
| 414 |
-
|
| 415 |
-
|
| 416 |
-
|
| 417 |
-
|
| 418 |
-
|
| 419 |
-
|
| 420 |
-
|
| 421 |
-
|
| 422 |
-
|
| 423 |
-
|
| 424 |
-
|
| 425 |
-
|
| 426 |
-
|
| 427 |
-
|
| 428 |
-
|
| 429 |
-
|
| 430 |
-
|
| 431 |
-
|
| 432 |
-
|
| 433 |
-
|
| 434 |
-
|
| 435 |
-
|
| 436 |
-
|
| 437 |
-
|
| 438 |
-
|
| 439 |
-
|
| 440 |
-
|
| 441 |
-
|
| 442 |
-
|
| 443 |
-
|
| 444 |
-
|
| 445 |
-
|
| 446 |
-
|
| 447 |
-
|
| 448 |
-
|
| 449 |
-
|
| 450 |
-
|
| 451 |
-
|
| 452 |
-
|
| 453 |
-
|
| 454 |
-
|
| 455 |
-
}
|
| 456 |
-
|
| 457 |
-
|
| 458 |
-
|
| 459 |
-
|
| 460 |
-
|
| 461 |
-
|
| 462 |
-
|
| 463 |
-
|
| 464 |
-
|
| 465 |
-
|
| 466 |
-
|
| 467 |
-
|
| 468 |
-
|
| 469 |
-
|
| 470 |
-
|
| 471 |
-
|
| 472 |
-
|
| 473 |
-
|
| 474 |
-
|
| 475 |
-
if (
|
| 476 |
-
|
| 477 |
-
|
| 478 |
-
|
| 479 |
-
|
| 480 |
-
|
| 481 |
-
);
|
| 482 |
-
|
| 483 |
-
|
| 484 |
-
|
| 485 |
-
|
| 486 |
-
|
| 487 |
-
|
| 488 |
-
|
| 489 |
-
|
| 490 |
-
|
| 491 |
-
|
| 492 |
-
|
| 493 |
-
|
| 494 |
-
|
| 495 |
-
|
| 496 |
-
|
| 497 |
-
|
| 498 |
-
if (
|
| 499 |
-
|
| 500 |
-
|
| 501 |
-
|
| 502 |
-
|
| 503 |
-
|
| 504 |
-
|
| 505 |
-
|
| 506 |
-
|
| 507 |
-
|
| 508 |
-
|
| 509 |
-
|
| 510 |
-
|
| 511 |
-
|
| 512 |
-
|
| 513 |
-
|
| 514 |
-
|
| 515 |
-
|
| 516 |
-
|
| 517 |
-
|
| 518 |
-
|
| 519 |
-
|
| 520 |
-
|
| 521 |
-
|
| 522 |
-
|
| 523 |
-
|
| 524 |
-
|
| 525 |
-
|
| 526 |
-
|
| 527 |
-
}
|
| 528 |
-
|
| 529 |
-
|
| 530 |
-
|
| 531 |
-
|
| 532 |
-
|
| 533 |
-
|
| 534 |
-
|
| 535 |
-
|
| 536 |
-
|
| 537 |
-
|
| 538 |
-
|
| 539 |
-
|
| 540 |
-
|
| 541 |
-
|
| 542 |
-
|
| 543 |
-
|
| 544 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { getPageTokens } from "../uploads/index";
|
| 2 |
+
import { httpFetch } from "../transport";
|
| 3 |
+
import { abortError, isAbortError, sleep, throwIfAborted } from "../../shared/abort";
|
| 4 |
+
import { log } from "../../shared/logging";
|
| 5 |
+
import { uuid } from "../../shared/crypto";
|
| 6 |
+
import {
|
| 7 |
+
dataAnalysisEmptyResponseError,
|
| 8 |
+
invalidGeminiCookieError,
|
| 9 |
+
isDataAnalysisEmptyResponseError,
|
| 10 |
+
isInvalidGeminiCookieError,
|
| 11 |
+
isLargePromptEmptyResponseError,
|
| 12 |
+
largePromptEmptyResponseError,
|
| 13 |
+
largePromptEmptyResponseThreshold,
|
| 14 |
+
upstreamImageGenerationEmptyError,
|
| 15 |
+
upstreamImageProviderError,
|
| 16 |
+
upstreamEmptyResponseError,
|
| 17 |
+
unverifiedGeminiCookieError,
|
| 18 |
+
} from "./errors";
|
| 19 |
+
import { buildHeaders, buildPayload, getUrl } from "./protocol";
|
| 20 |
+
import {
|
| 21 |
+
createStreamTextExtractor,
|
| 22 |
+
extractResponseParts,
|
| 23 |
+
extractResponseText,
|
| 24 |
+
richResponseShapeSummary,
|
| 25 |
+
wrbResponseShapeSummary,
|
| 26 |
+
} from "./parser";
|
| 27 |
+
import { hydrateGeneratedImages } from "./generated-images";
|
| 28 |
+
import type { GeminiRichImage } from "./generated-images";
|
| 29 |
+
import {
|
| 30 |
+
configWithCachedGeminiBuildLabel,
|
| 31 |
+
refreshGeminiBuildLabelForRetry,
|
| 32 |
+
waitBeforeRetry,
|
| 33 |
+
} from "./retry";
|
| 34 |
+
import {
|
| 35 |
+
configWithFreshGeminiCookie,
|
| 36 |
+
rotateGeminiCookieForRetryWithReason,
|
| 37 |
+
} from "../cookies";
|
| 38 |
+
import type { RuntimeConfig } from "../../config";
|
| 39 |
+
import type { ErrorWithMetadata } from "../../shared/types";
|
| 40 |
+
|
| 41 |
+
type GeminiFileRef =
|
| 42 |
+
| string
|
| 43 |
+
| {
|
| 44 |
+
ref?: unknown;
|
| 45 |
+
fileRef?: unknown;
|
| 46 |
+
id?: unknown;
|
| 47 |
+
name?: unknown;
|
| 48 |
+
filename?: unknown;
|
| 49 |
+
};
|
| 50 |
+
|
| 51 |
+
type GeminiStreamOptions = {
|
| 52 |
+
signal?: AbortSignal;
|
| 53 |
+
};
|
| 54 |
+
|
| 55 |
+
type GeminiRichOptions = {
|
| 56 |
+
hydrateGeneratedImageBytes?: boolean;
|
| 57 |
+
};
|
| 58 |
+
|
| 59 |
+
export type { GeminiRichImage } from "./generated-images";
|
| 60 |
+
|
| 61 |
+
export type GeminiRichOutput = {
|
| 62 |
+
text: string;
|
| 63 |
+
images: GeminiRichImage[];
|
| 64 |
+
};
|
| 65 |
+
|
| 66 |
+
export {
|
| 67 |
+
cleanText,
|
| 68 |
+
extractResponseParts,
|
| 69 |
+
extractResponseText,
|
| 70 |
+
extractTextsFromLine,
|
| 71 |
+
richResponseShapeSummary,
|
| 72 |
+
wrbResponseShapeSummary,
|
| 73 |
+
} from "./parser";
|
| 74 |
+
export { buildHeaders, buildPayload, getUrl } from "./protocol";
|
| 75 |
+
export { getFreshGeminiBuildLabel } from "./retry";
|
| 76 |
+
|
| 77 |
+
async function appendGeminiPageToken(
|
| 78 |
+
cfg: RuntimeConfig,
|
| 79 |
+
body: string,
|
| 80 |
+
): Promise<string> {
|
| 81 |
+
if (cfg.xsrf_token) return `${body}&at=${encodeURIComponent(cfg.xsrf_token)}`;
|
| 82 |
+
if (!cfg.cookie) return body;
|
| 83 |
+
const tokens = await getPageTokens(cfg);
|
| 84 |
+
if (!tokens.at) {
|
| 85 |
+
log(cfg, "gemini cookie verification failed reason=missing_page_at_token");
|
| 86 |
+
throw unverifiedGeminiCookieError("missing_page_at_token");
|
| 87 |
+
}
|
| 88 |
+
return `${body}&at=${encodeURIComponent(tokens.at)}`;
|
| 89 |
+
}
|
| 90 |
+
|
| 91 |
+
async function fetchGeminiStreamGenerate(
|
| 92 |
+
cfg: RuntimeConfig,
|
| 93 |
+
activeCfg: RuntimeConfig,
|
| 94 |
+
body: string,
|
| 95 |
+
signal: AbortSignal | null | undefined = undefined,
|
| 96 |
+
modelHeaders: Record<string, string> | null = null,
|
| 97 |
+
requestId: string | null = null,
|
| 98 |
+
) {
|
| 99 |
+
const url = getUrl(activeCfg);
|
| 100 |
+
const headers = await buildHeaders(activeCfg, modelHeaders, requestId);
|
| 101 |
+
const requestBody = await appendGeminiPageToken(activeCfg, body);
|
| 102 |
+
// resin_proxy 时 httpFetch 内部会强制关闭 socket
|
| 103 |
+
return httpFetch(url, {
|
| 104 |
+
method: "POST",
|
| 105 |
+
headers,
|
| 106 |
+
body: requestBody,
|
| 107 |
+
timeoutMs: cfg.request_timeout_sec * 1000,
|
| 108 |
+
socket: cfg.upstream_socket && !activeCfg.resin_proxy,
|
| 109 |
+
socketFallback: cfg.upstream_socket && !activeCfg.resin_proxy ? "never" : "pre-response",
|
| 110 |
+
signal,
|
| 111 |
+
cfg,
|
| 112 |
+
});
|
| 113 |
+
}
|
| 114 |
+
|
| 115 |
+
export async function generate(
|
| 116 |
+
cfg: RuntimeConfig,
|
| 117 |
+
prompt: string,
|
| 118 |
+
modelId: number,
|
| 119 |
+
thinkMode: number,
|
| 120 |
+
extra: Record<number, unknown> | null,
|
| 121 |
+
fileRefs: GeminiFileRef[] | null | undefined,
|
| 122 |
+
modelHeaders: Record<string, string> | null = null,
|
| 123 |
+
): Promise<string> {
|
| 124 |
+
let lastErr: unknown;
|
| 125 |
+
let activeCfg = await configWithCachedGeminiBuildLabel(
|
| 126 |
+
await configWithFreshGeminiCookie(cfg),
|
| 127 |
+
);
|
| 128 |
+
let refreshedBL = false;
|
| 129 |
+
let refreshedCookie = false;
|
| 130 |
+
const requestId = uuid().toUpperCase();
|
| 131 |
+
const body = buildPayload(
|
| 132 |
+
prompt,
|
| 133 |
+
modelId,
|
| 134 |
+
thinkMode,
|
| 135 |
+
fileRefs || null,
|
| 136 |
+
extra,
|
| 137 |
+
requestId,
|
| 138 |
+
);
|
| 139 |
+
for (let attempt = 0; attempt < cfg.retry_attempts; attempt++) {
|
| 140 |
+
try {
|
| 141 |
+
const resp = await fetchGeminiStreamGenerate(
|
| 142 |
+
cfg,
|
| 143 |
+
activeCfg,
|
| 144 |
+
body,
|
| 145 |
+
undefined,
|
| 146 |
+
modelHeaders,
|
| 147 |
+
requestId,
|
| 148 |
+
);
|
| 149 |
+
const cookieErr = invalidGeminiCookieError(cfg, resp.status);
|
| 150 |
+
if (cookieErr) throw cookieErr;
|
| 151 |
+
const raw = await resp.text();
|
| 152 |
+
const text = extractResponseText(raw);
|
| 153 |
+
if (!resp.ok || !text) {
|
| 154 |
+
const shape =
|
| 155 |
+
cfg.log_requests && !text ? ` ${wrbResponseShapeSummary(raw)}` : "";
|
| 156 |
+
log(
|
| 157 |
+
cfg,
|
| 158 |
+
`upstream status=${resp.status} rawLen=${raw.length} parsedLen=${text.length}${shape}`,
|
| 159 |
+
);
|
| 160 |
+
}
|
| 161 |
+
if (!text) {
|
| 162 |
+
const dataAnalysisErr = dataAnalysisEmptyResponseError(raw, fileRefs);
|
| 163 |
+
if (dataAnalysisErr) throw dataAnalysisErr;
|
| 164 |
+
const largePromptErr = largePromptEmptyResponseError(
|
| 165 |
+
prompt,
|
| 166 |
+
resp.status,
|
| 167 |
+
raw.length,
|
| 168 |
+
largePromptEmptyResponseThreshold(cfg),
|
| 169 |
+
);
|
| 170 |
+
if (largePromptErr) throw largePromptErr;
|
| 171 |
+
const refreshedCfg = await refreshGeminiBuildLabelForRetry(
|
| 172 |
+
cfg,
|
| 173 |
+
activeCfg,
|
| 174 |
+
refreshedBL,
|
| 175 |
+
"",
|
| 176 |
+
);
|
| 177 |
+
if (refreshedCfg) {
|
| 178 |
+
refreshedBL = true;
|
| 179 |
+
activeCfg = refreshedCfg;
|
| 180 |
+
continue;
|
| 181 |
+
}
|
| 182 |
+
throw upstreamEmptyResponseError(resp.status, raw.length, "non-stream");
|
| 183 |
+
}
|
| 184 |
+
return text;
|
| 185 |
+
} catch (e) {
|
| 186 |
+
if (isInvalidGeminiCookieError(e) && !refreshedCookie) {
|
| 187 |
+
const rotated = await rotateGeminiCookieForRetryWithReason(activeCfg);
|
| 188 |
+
if (rotated.config) {
|
| 189 |
+
refreshedCookie = true;
|
| 190 |
+
activeCfg = await configWithCachedGeminiBuildLabel(rotated.config);
|
| 191 |
+
continue;
|
| 192 |
+
}
|
| 193 |
+
throw invalidCookieErrorWithRotationReason(cfg, e, rotated.reason);
|
| 194 |
+
}
|
| 195 |
+
if (isInvalidGeminiCookieError(e) && refreshedCookie)
|
| 196 |
+
throw invalidCookieErrorWithRotationReason(cfg, e, "rotation_updated");
|
| 197 |
+
if (
|
| 198 |
+
isLargePromptEmptyResponseError(e) ||
|
| 199 |
+
isDataAnalysisEmptyResponseError(e) ||
|
| 200 |
+
isInvalidGeminiCookieError(e)
|
| 201 |
+
)
|
| 202 |
+
throw e;
|
| 203 |
+
lastErr = e;
|
| 204 |
+
await waitBeforeRetry(cfg, attempt, e, "Retry");
|
| 205 |
+
}
|
| 206 |
+
}
|
| 207 |
+
throw lastErr;
|
| 208 |
+
}
|
| 209 |
+
|
| 210 |
+
export async function generateRich(
|
| 211 |
+
cfg: RuntimeConfig,
|
| 212 |
+
prompt: string,
|
| 213 |
+
modelId: number,
|
| 214 |
+
thinkMode: number,
|
| 215 |
+
extra: Record<number, unknown> | null,
|
| 216 |
+
fileRefs: GeminiFileRef[] | null | undefined,
|
| 217 |
+
modelHeaders: Record<string, string> | null = null,
|
| 218 |
+
options: GeminiRichOptions = {},
|
| 219 |
+
): Promise<GeminiRichOutput> {
|
| 220 |
+
let lastErr: unknown;
|
| 221 |
+
let activeCfg = await configWithCachedGeminiBuildLabel(
|
| 222 |
+
await configWithFreshGeminiCookie(cfg),
|
| 223 |
+
);
|
| 224 |
+
let refreshedBL = false;
|
| 225 |
+
let refreshedCookie = false;
|
| 226 |
+
const requestId = uuid().toUpperCase();
|
| 227 |
+
const body = buildPayload(
|
| 228 |
+
prompt,
|
| 229 |
+
modelId,
|
| 230 |
+
thinkMode,
|
| 231 |
+
fileRefs || null,
|
| 232 |
+
extra,
|
| 233 |
+
requestId,
|
| 234 |
+
);
|
| 235 |
+
for (let attempt = 0; attempt < cfg.retry_attempts; attempt++) {
|
| 236 |
+
try {
|
| 237 |
+
const resp = await fetchGeminiStreamGenerate(
|
| 238 |
+
cfg,
|
| 239 |
+
activeCfg,
|
| 240 |
+
body,
|
| 241 |
+
undefined,
|
| 242 |
+
modelHeaders,
|
| 243 |
+
requestId,
|
| 244 |
+
);
|
| 245 |
+
const cookieErr = invalidGeminiCookieError(cfg, resp.status);
|
| 246 |
+
if (cookieErr) throw cookieErr;
|
| 247 |
+
const raw = await resp.text();
|
| 248 |
+
const parts = extractResponseParts(raw);
|
| 249 |
+
if (parts.fatalCode) throw upstreamImageProviderError(parts.fatalCode);
|
| 250 |
+
if (!resp.ok || (!parts.text && !parts.images.length)) {
|
| 251 |
+
const shape = cfg.log_requests
|
| 252 |
+
? ` ${richResponseShapeSummary(raw)}`
|
| 253 |
+
: "";
|
| 254 |
+
log(
|
| 255 |
+
cfg,
|
| 256 |
+
`rich upstream status=${resp.status} rawLen=${raw.length} parsedTextLen=${parts.text.length} images=${parts.images.length}${shape}`,
|
| 257 |
+
);
|
| 258 |
+
}
|
| 259 |
+
if (!parts.text && !parts.images.length) {
|
| 260 |
+
const dataAnalysisErr = dataAnalysisEmptyResponseError(raw, fileRefs);
|
| 261 |
+
if (dataAnalysisErr) throw dataAnalysisErr;
|
| 262 |
+
const largePromptErr = largePromptEmptyResponseError(
|
| 263 |
+
prompt,
|
| 264 |
+
resp.status,
|
| 265 |
+
raw.length,
|
| 266 |
+
largePromptEmptyResponseThreshold(cfg),
|
| 267 |
+
);
|
| 268 |
+
if (largePromptErr) throw largePromptErr;
|
| 269 |
+
const refreshedCfg = await refreshGeminiBuildLabelForRetry(
|
| 270 |
+
cfg,
|
| 271 |
+
activeCfg,
|
| 272 |
+
refreshedBL,
|
| 273 |
+
"",
|
| 274 |
+
);
|
| 275 |
+
if (refreshedCfg) {
|
| 276 |
+
refreshedBL = true;
|
| 277 |
+
activeCfg = refreshedCfg;
|
| 278 |
+
continue;
|
| 279 |
+
}
|
| 280 |
+
throw upstreamImageGenerationEmptyError(
|
| 281 |
+
resp.status,
|
| 282 |
+
raw.length,
|
| 283 |
+
"non-stream",
|
| 284 |
+
);
|
| 285 |
+
}
|
| 286 |
+
const images =
|
| 287 |
+
options.hydrateGeneratedImageBytes === false
|
| 288 |
+
? parts.images
|
| 289 |
+
: await hydrateGeneratedImages(cfg, activeCfg, parts.images);
|
| 290 |
+
return { text: parts.text, images };
|
| 291 |
+
} catch (e) {
|
| 292 |
+
if (isInvalidGeminiCookieError(e) && !refreshedCookie) {
|
| 293 |
+
const rotated = await rotateGeminiCookieForRetryWithReason(activeCfg);
|
| 294 |
+
if (rotated.config) {
|
| 295 |
+
refreshedCookie = true;
|
| 296 |
+
activeCfg = await configWithCachedGeminiBuildLabel(rotated.config);
|
| 297 |
+
continue;
|
| 298 |
+
}
|
| 299 |
+
throw invalidCookieErrorWithRotationReason(cfg, e, rotated.reason);
|
| 300 |
+
}
|
| 301 |
+
if (isInvalidGeminiCookieError(e) && refreshedCookie)
|
| 302 |
+
throw invalidCookieErrorWithRotationReason(cfg, e, "rotation_updated");
|
| 303 |
+
if (
|
| 304 |
+
isLargePromptEmptyResponseError(e) ||
|
| 305 |
+
isDataAnalysisEmptyResponseError(e) ||
|
| 306 |
+
isInvalidGeminiCookieError(e)
|
| 307 |
+
)
|
| 308 |
+
throw e;
|
| 309 |
+
lastErr = e;
|
| 310 |
+
await waitBeforeRetry(cfg, attempt, e, "Rich retry");
|
| 311 |
+
}
|
| 312 |
+
}
|
| 313 |
+
throw lastErr;
|
| 314 |
+
}
|
| 315 |
+
|
| 316 |
+
|
| 317 |
+
// Resin 反代常把上游细粒度流合成大块;在本地按码点切回小片并加微延迟,
|
| 318 |
+
// 恢复接近直连的打字机效果。未配 resin_proxy 时原样透传。
|
| 319 |
+
const RESIN_STREAM_CHUNK_CHARS = 16;
|
| 320 |
+
const RESIN_STREAM_CHUNK_MS = 12;
|
| 321 |
+
|
| 322 |
+
async function* resinSmoothedPieces(
|
| 323 |
+
text: string,
|
| 324 |
+
enabled: boolean,
|
| 325 |
+
signal?: AbortSignal | null,
|
| 326 |
+
): AsyncGenerator<string> {
|
| 327 |
+
const raw = String(text || "");
|
| 328 |
+
if (!raw) return;
|
| 329 |
+
if (!enabled) {
|
| 330 |
+
yield raw;
|
| 331 |
+
return;
|
| 332 |
+
}
|
| 333 |
+
let i = 0;
|
| 334 |
+
const n = raw.length;
|
| 335 |
+
let first = true;
|
| 336 |
+
while (i < n) {
|
| 337 |
+
throwIfAborted(signal);
|
| 338 |
+
let end = i;
|
| 339 |
+
let count = 0;
|
| 340 |
+
while (end < n && count < RESIN_STREAM_CHUNK_CHARS) {
|
| 341 |
+
const cp = raw.codePointAt(end)!;
|
| 342 |
+
end += cp > 0xffff ? 2 : 1;
|
| 343 |
+
count += 1;
|
| 344 |
+
}
|
| 345 |
+
if (!first) await sleep(RESIN_STREAM_CHUNK_MS, signal);
|
| 346 |
+
first = false;
|
| 347 |
+
yield raw.slice(i, end);
|
| 348 |
+
i = end;
|
| 349 |
+
}
|
| 350 |
+
}
|
| 351 |
+
|
| 352 |
+
export async function* generateStream(
|
| 353 |
+
cfg: RuntimeConfig,
|
| 354 |
+
prompt: string,
|
| 355 |
+
modelId: number,
|
| 356 |
+
thinkMode: number,
|
| 357 |
+
extra: Record<number, unknown> | null,
|
| 358 |
+
fileRefs: GeminiFileRef[] | null | undefined,
|
| 359 |
+
options: GeminiStreamOptions = {},
|
| 360 |
+
modelHeaders: Record<string, string> | null = null,
|
| 361 |
+
): AsyncIterable<string> {
|
| 362 |
+
let lastErr: unknown;
|
| 363 |
+
let yielded = false;
|
| 364 |
+
let activeCfg = await configWithCachedGeminiBuildLabel(
|
| 365 |
+
await configWithFreshGeminiCookie(cfg),
|
| 366 |
+
);
|
| 367 |
+
let refreshedBL = false;
|
| 368 |
+
let refreshedCookie = false;
|
| 369 |
+
const requestId = uuid().toUpperCase();
|
| 370 |
+
const body = buildPayload(
|
| 371 |
+
prompt,
|
| 372 |
+
modelId,
|
| 373 |
+
thinkMode,
|
| 374 |
+
fileRefs || null,
|
| 375 |
+
extra,
|
| 376 |
+
requestId,
|
| 377 |
+
);
|
| 378 |
+
const signal = options?.signal;
|
| 379 |
+
const resinSmooth = !!cfg.resin_proxy;
|
| 380 |
+
|
| 381 |
+
for (let attempt = 0; attempt < cfg.retry_attempts; attempt++) {
|
| 382 |
+
try {
|
| 383 |
+
throwIfAborted(signal);
|
| 384 |
+
const resp = await fetchGeminiStreamGenerate(
|
| 385 |
+
cfg,
|
| 386 |
+
activeCfg,
|
| 387 |
+
body,
|
| 388 |
+
signal,
|
| 389 |
+
modelHeaders,
|
| 390 |
+
requestId,
|
| 391 |
+
);
|
| 392 |
+
const cookieErr = invalidGeminiCookieError(cfg, resp.status);
|
| 393 |
+
if (cookieErr) throw cookieErr;
|
| 394 |
+
if (!resp.body) {
|
| 395 |
+
const raw = await resp.text();
|
| 396 |
+
const text = extractResponseText(raw);
|
| 397 |
+
if (text) {
|
| 398 |
+
for await (const piece of resinSmoothedPieces(
|
| 399 |
+
text,
|
| 400 |
+
resinSmooth,
|
| 401 |
+
signal,
|
| 402 |
+
)) {
|
| 403 |
+
yielded = true;
|
| 404 |
+
yield piece;
|
| 405 |
+
}
|
| 406 |
+
}
|
| 407 |
+
if (!text) {
|
| 408 |
+
const shape = cfg.log_requests
|
| 409 |
+
? ` ${wrbResponseShapeSummary(raw)}`
|
| 410 |
+
: "";
|
| 411 |
+
log(
|
| 412 |
+
cfg,
|
| 413 |
+
`stream upstream produced no text without body (status=${resp.status}) rawLen=${raw.length}${shape}`,
|
| 414 |
+
);
|
| 415 |
+
const dataAnalysisErr = dataAnalysisEmptyResponseError(raw, fileRefs);
|
| 416 |
+
if (dataAnalysisErr) throw dataAnalysisErr;
|
| 417 |
+
const largePromptErr = largePromptEmptyResponseError(
|
| 418 |
+
prompt,
|
| 419 |
+
resp.status,
|
| 420 |
+
raw.length,
|
| 421 |
+
largePromptEmptyResponseThreshold(cfg),
|
| 422 |
+
);
|
| 423 |
+
if (largePromptErr) throw largePromptErr;
|
| 424 |
+
const refreshedCfg = await refreshGeminiBuildLabelForRetry(
|
| 425 |
+
cfg,
|
| 426 |
+
activeCfg,
|
| 427 |
+
refreshedBL,
|
| 428 |
+
"stream without body",
|
| 429 |
+
);
|
| 430 |
+
if (refreshedCfg) {
|
| 431 |
+
refreshedBL = true;
|
| 432 |
+
activeCfg = refreshedCfg;
|
| 433 |
+
continue;
|
| 434 |
+
}
|
| 435 |
+
throw upstreamEmptyResponseError(
|
| 436 |
+
resp.status,
|
| 437 |
+
raw.length,
|
| 438 |
+
"stream without body",
|
| 439 |
+
);
|
| 440 |
+
}
|
| 441 |
+
return;
|
| 442 |
+
}
|
| 443 |
+
const reader = resp.body.getReader();
|
| 444 |
+
const decoder = new TextDecoder();
|
| 445 |
+
const extractor = createStreamTextExtractor();
|
| 446 |
+
const lineChunks: string[] = [];
|
| 447 |
+
let lineLength = 0;
|
| 448 |
+
let rawSnippet = "";
|
| 449 |
+
let rawLength = 0;
|
| 450 |
+
const takeLine = (piece: string): string => {
|
| 451 |
+
if (!lineChunks.length) return piece;
|
| 452 |
+
if (piece) {
|
| 453 |
+
lineChunks.push(piece);
|
| 454 |
+
lineLength += piece.length;
|
| 455 |
+
}
|
| 456 |
+
const line = lineChunks.join("");
|
| 457 |
+
lineChunks.length = 0;
|
| 458 |
+
lineLength = 0;
|
| 459 |
+
return line;
|
| 460 |
+
};
|
| 461 |
+
const appendLineRemainder = (piece: string): void => {
|
| 462 |
+
if (!piece) return;
|
| 463 |
+
lineChunks.push(piece);
|
| 464 |
+
lineLength += piece.length;
|
| 465 |
+
};
|
| 466 |
+
const consumeDecoded = function* (decoded: string): Generator<string> {
|
| 467 |
+
let lineStart = 0;
|
| 468 |
+
let idx = decoded.indexOf("\n", lineStart);
|
| 469 |
+
while (idx >= 0) {
|
| 470 |
+
const line = takeLine(decoded.slice(lineStart, idx));
|
| 471 |
+
for (const delta of extractor.consumeLine(line)) yield delta;
|
| 472 |
+
lineStart = idx + 1;
|
| 473 |
+
idx = decoded.indexOf("\n", lineStart);
|
| 474 |
+
}
|
| 475 |
+
if (lineStart < decoded.length)
|
| 476 |
+
appendLineRemainder(decoded.slice(lineStart));
|
| 477 |
+
};
|
| 478 |
+
while (true) {
|
| 479 |
+
throwIfAborted(signal);
|
| 480 |
+
const { done, value } = await reader.read();
|
| 481 |
+
if (done) break;
|
| 482 |
+
const decoded = decoder.decode(value, { stream: true });
|
| 483 |
+
rawLength += decoded.length;
|
| 484 |
+
if (rawSnippet.length < 500)
|
| 485 |
+
rawSnippet += decoded.slice(0, 500 - rawSnippet.length);
|
| 486 |
+
for (const delta of consumeDecoded(decoded)) {
|
| 487 |
+
for await (const piece of resinSmoothedPieces(
|
| 488 |
+
delta,
|
| 489 |
+
resinSmooth,
|
| 490 |
+
signal,
|
| 491 |
+
)) {
|
| 492 |
+
yielded = true;
|
| 493 |
+
yield piece;
|
| 494 |
+
}
|
| 495 |
+
}
|
| 496 |
+
}
|
| 497 |
+
const tail = decoder.decode();
|
| 498 |
+
if (tail) {
|
| 499 |
+
rawLength += tail.length;
|
| 500 |
+
if (rawSnippet.length < 500)
|
| 501 |
+
rawSnippet += tail.slice(0, 500 - rawSnippet.length);
|
| 502 |
+
for (const delta of consumeDecoded(tail)) {
|
| 503 |
+
for await (const piece of resinSmoothedPieces(
|
| 504 |
+
delta,
|
| 505 |
+
resinSmooth,
|
| 506 |
+
signal,
|
| 507 |
+
)) {
|
| 508 |
+
yielded = true;
|
| 509 |
+
yield piece;
|
| 510 |
+
}
|
| 511 |
+
}
|
| 512 |
+
}
|
| 513 |
+
if (lineLength > 0) {
|
| 514 |
+
for (const delta of extractor.consumeLine(takeLine(""))) {
|
| 515 |
+
for await (const piece of resinSmoothedPieces(
|
| 516 |
+
delta,
|
| 517 |
+
resinSmooth,
|
| 518 |
+
signal,
|
| 519 |
+
)) {
|
| 520 |
+
yielded = true;
|
| 521 |
+
yield piece;
|
| 522 |
+
}
|
| 523 |
+
}
|
| 524 |
+
}
|
| 525 |
+
if (!yielded) {
|
| 526 |
+
const shape = cfg.log_requests
|
| 527 |
+
? ` ${wrbResponseShapeSummary(rawSnippet)}`
|
| 528 |
+
: "";
|
| 529 |
+
log(
|
| 530 |
+
cfg,
|
| 531 |
+
`stream upstream produced no text (status=${resp.status}) rawLen=${rawLength}${shape}`,
|
| 532 |
+
);
|
| 533 |
+
const dataAnalysisErr = dataAnalysisEmptyResponseError(
|
| 534 |
+
rawSnippet,
|
| 535 |
+
fileRefs,
|
| 536 |
+
);
|
| 537 |
+
if (dataAnalysisErr) throw dataAnalysisErr;
|
| 538 |
+
const largePromptErr = largePromptEmptyResponseError(
|
| 539 |
+
prompt,
|
| 540 |
+
resp.status,
|
| 541 |
+
null,
|
| 542 |
+
largePromptEmptyResponseThreshold(cfg),
|
| 543 |
+
);
|
| 544 |
+
if (largePromptErr) throw largePromptErr;
|
| 545 |
+
const refreshedCfg = await refreshGeminiBuildLabelForRetry(
|
| 546 |
+
cfg,
|
| 547 |
+
activeCfg,
|
| 548 |
+
refreshedBL,
|
| 549 |
+
"stream",
|
| 550 |
+
);
|
| 551 |
+
if (refreshedCfg) {
|
| 552 |
+
refreshedBL = true;
|
| 553 |
+
activeCfg = refreshedCfg;
|
| 554 |
+
continue;
|
| 555 |
+
}
|
| 556 |
+
throw upstreamEmptyResponseError(resp.status, rawLength, "stream");
|
| 557 |
+
}
|
| 558 |
+
return;
|
| 559 |
+
} catch (e) {
|
| 560 |
+
if (isAbortError(e) || signal?.aborted) throw abortError(signal);
|
| 561 |
+
if (isInvalidGeminiCookieError(e) && !yielded && !refreshedCookie) {
|
| 562 |
+
const rotated = await rotateGeminiCookieForRetryWithReason(activeCfg);
|
| 563 |
+
if (rotated.config) {
|
| 564 |
+
refreshedCookie = true;
|
| 565 |
+
activeCfg = await configWithCachedGeminiBuildLabel(rotated.config);
|
| 566 |
+
continue;
|
| 567 |
+
}
|
| 568 |
+
throw invalidCookieErrorWithRotationReason(cfg, e, rotated.reason);
|
| 569 |
+
}
|
| 570 |
+
if (isInvalidGeminiCookieError(e) && !yielded && refreshedCookie)
|
| 571 |
+
throw invalidCookieErrorWithRotationReason(cfg, e, "rotation_updated");
|
| 572 |
+
if (
|
| 573 |
+
isLargePromptEmptyResponseError(e) ||
|
| 574 |
+
isDataAnalysisEmptyResponseError(e) ||
|
| 575 |
+
isInvalidGeminiCookieError(e)
|
| 576 |
+
)
|
| 577 |
+
throw e;
|
| 578 |
+
lastErr = e;
|
| 579 |
+
if (
|
| 580 |
+
!yielded &&
|
| 581 |
+
(await waitBeforeRetry(cfg, attempt, e, "Stream retry", signal))
|
| 582 |
+
) {
|
| 583 |
+
continue;
|
| 584 |
+
}
|
| 585 |
+
throw e;
|
| 586 |
+
}
|
| 587 |
+
}
|
| 588 |
+
if (lastErr) throw lastErr;
|
| 589 |
+
}
|
| 590 |
+
|
| 591 |
+
function invalidCookieErrorWithRotationReason(
|
| 592 |
+
cfg: RuntimeConfig,
|
| 593 |
+
err: unknown,
|
| 594 |
+
reason: unknown,
|
| 595 |
+
): unknown {
|
| 596 |
+
const meta =
|
| 597 |
+
err && typeof err === "object" ? (err as Partial<ErrorWithMetadata>) : {};
|
| 598 |
+
return (
|
| 599 |
+
invalidGeminiCookieError(
|
| 600 |
+
cfg,
|
| 601 |
+
meta.upstreamStatus || meta.status || 401,
|
| 602 |
+
typeof meta.rawLength === "number" ? meta.rawLength : null,
|
| 603 |
+
reason,
|
| 604 |
+
) || err
|
| 605 |
+
);
|
| 606 |
+
}
|
src/gemini/transport/http.ts
CHANGED
|
@@ -1,128 +1,133 @@
|
|
| 1 |
-
import {
|
| 2 |
-
abortError,
|
| 3 |
-
isAbortError,
|
| 4 |
-
throwIfAborted,
|
| 5 |
-
timeoutSignal,
|
| 6 |
-
} from "../../shared/abort";
|
| 7 |
-
import {
|
| 8 |
-
canFallbackAfterSocketError,
|
| 9 |
-
errorLogSummary,
|
| 10 |
-
} from "../../shared/errors";
|
| 11 |
-
import { log } from "../../shared/logging";
|
| 12 |
-
import { getDefaultSocketPool, resolveConnect, socketHttp } from "./socket";
|
| 13 |
-
import type { SocketHttpResponse } from "./socket";
|
| 14 |
-
|
| 15 |
-
type HttpBodyInit = BodyInit | ArrayBufferView;
|
| 16 |
-
|
| 17 |
-
type HttpFetchOptions = {
|
| 18 |
-
method?: string;
|
| 19 |
-
headers?: Record<string, string>;
|
| 20 |
-
body?: HttpBodyInit | null | undefined;
|
| 21 |
-
bodyLength?: number | null | undefined;
|
| 22 |
-
timeoutMs?: number;
|
| 23 |
-
socket?: boolean;
|
| 24 |
-
socketFallback?: "pre-response" | "never";
|
| 25 |
-
signal?: AbortSignal | null | undefined;
|
| 26 |
-
cfg?: { log_requests?: unknown } | null;
|
| 27 |
-
acceptCompressed?: boolean;
|
| 28 |
-
};
|
| 29 |
-
|
| 30 |
-
// 统一上游入口:socket 优先,失败/不可用则回退 fetch。返回类 Response 对象。
|
| 31 |
-
export async function httpFetch(
|
| 32 |
-
url: string,
|
| 33 |
-
{
|
| 34 |
-
method = "GET",
|
| 35 |
-
headers = {},
|
| 36 |
-
body,
|
| 37 |
-
bodyLength = null,
|
| 38 |
-
timeoutMs = 180000,
|
| 39 |
-
socket = true,
|
| 40 |
-
socketFallback = "pre-response",
|
| 41 |
-
signal,
|
| 42 |
-
cfg,
|
| 43 |
-
acceptCompressed,
|
| 44 |
-
}: HttpFetchOptions = {},
|
| 45 |
-
): Promise<Response | SocketHttpResponse> {
|
| 46 |
-
throwIfAborted(signal);
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import {
|
| 2 |
+
abortError,
|
| 3 |
+
isAbortError,
|
| 4 |
+
throwIfAborted,
|
| 5 |
+
timeoutSignal,
|
| 6 |
+
} from "../../shared/abort";
|
| 7 |
+
import {
|
| 8 |
+
canFallbackAfterSocketError,
|
| 9 |
+
errorLogSummary,
|
| 10 |
+
} from "../../shared/errors";
|
| 11 |
+
import { log } from "../../shared/logging";
|
| 12 |
+
import { getDefaultSocketPool, resolveConnect, socketHttp } from "./socket";
|
| 13 |
+
import type { SocketHttpResponse } from "./socket";
|
| 14 |
+
|
| 15 |
+
type HttpBodyInit = BodyInit | ArrayBufferView;
|
| 16 |
+
|
| 17 |
+
type HttpFetchOptions = {
|
| 18 |
+
method?: string;
|
| 19 |
+
headers?: Record<string, string>;
|
| 20 |
+
body?: HttpBodyInit | null | undefined;
|
| 21 |
+
bodyLength?: number | null | undefined;
|
| 22 |
+
timeoutMs?: number;
|
| 23 |
+
socket?: boolean;
|
| 24 |
+
socketFallback?: "pre-response" | "never";
|
| 25 |
+
signal?: AbortSignal | null | undefined;
|
| 26 |
+
cfg?: { log_requests?: unknown; resin_proxy?: unknown } | null;
|
| 27 |
+
acceptCompressed?: boolean;
|
| 28 |
+
};
|
| 29 |
+
|
| 30 |
+
// 统一上游入口:socket 优先,失败/不可用则回退 fetch。返回类 Response 对象。
|
| 31 |
+
export async function httpFetch(
|
| 32 |
+
url: string,
|
| 33 |
+
{
|
| 34 |
+
method = "GET",
|
| 35 |
+
headers = {},
|
| 36 |
+
body,
|
| 37 |
+
bodyLength = null,
|
| 38 |
+
timeoutMs = 180000,
|
| 39 |
+
socket = true,
|
| 40 |
+
socketFallback = "pre-response",
|
| 41 |
+
signal,
|
| 42 |
+
cfg,
|
| 43 |
+
acceptCompressed,
|
| 44 |
+
}: HttpFetchOptions = {},
|
| 45 |
+
): Promise<Response | SocketHttpResponse> {
|
| 46 |
+
throwIfAborted(signal);
|
| 47 |
+
// Resin 反代已提供干净出口;裸 socket 仅用于直连 Gemini 绕 429。
|
| 48 |
+
// 配了 resin_proxy 时强制 fetch,避免 CF socket 路径空响应。
|
| 49 |
+
if (cfg?.resin_proxy) {
|
| 50 |
+
socket = false;
|
| 51 |
+
}
|
| 52 |
+
if (socket) {
|
| 53 |
+
const connect = await resolveConnect();
|
| 54 |
+
if (connect) {
|
| 55 |
+
try {
|
| 56 |
+
const resp = await socketHttp(connect, url, {
|
| 57 |
+
method,
|
| 58 |
+
headers,
|
| 59 |
+
body,
|
| 60 |
+
bodyLength,
|
| 61 |
+
timeoutMs,
|
| 62 |
+
signal,
|
| 63 |
+
keepAlive: true,
|
| 64 |
+
pool: getDefaultSocketPool(),
|
| 65 |
+
acceptCompressed: acceptCompressed ?? method.toUpperCase() === "GET",
|
| 66 |
+
});
|
| 67 |
+
return resp;
|
| 68 |
+
} catch (e) {
|
| 69 |
+
if (isAbortError(e) || signal?.aborted) throw abortError(signal);
|
| 70 |
+
if (socketFallback === "never") {
|
| 71 |
+
log(
|
| 72 |
+
cfg,
|
| 73 |
+
`socket upstream failed; fallback disabled for ${method}: ${errorLogSummary(e)}`,
|
| 74 |
+
);
|
| 75 |
+
throw e;
|
| 76 |
+
}
|
| 77 |
+
if (
|
| 78 |
+
body instanceof ReadableStream &&
|
| 79 |
+
socketErrorConsumedRequestBody(e)
|
| 80 |
+
) {
|
| 81 |
+
log(
|
| 82 |
+
cfg,
|
| 83 |
+
`socket upstream failed; not falling back with streaming request body for ${method}: ${errorLogSummary(e)}`,
|
| 84 |
+
);
|
| 85 |
+
throw e;
|
| 86 |
+
}
|
| 87 |
+
if (!canFallbackAfterSocketError(method, e)) {
|
| 88 |
+
log(
|
| 89 |
+
cfg,
|
| 90 |
+
`socket upstream failed; not falling back after upstream response for ${method}: ${errorLogSummary(e)}`,
|
| 91 |
+
);
|
| 92 |
+
throw e;
|
| 93 |
+
}
|
| 94 |
+
log(
|
| 95 |
+
cfg,
|
| 96 |
+
`socket upstream failed; falling back to fetch: ${errorLogSummary(e)}`,
|
| 97 |
+
);
|
| 98 |
+
}
|
| 99 |
+
}
|
| 100 |
+
}
|
| 101 |
+
const linked = linkedFetchSignal(signal, timeoutSignal(timeoutMs));
|
| 102 |
+
try {
|
| 103 |
+
const init: RequestInit = { method, headers };
|
| 104 |
+
if (body !== undefined) init.body = body as BodyInit;
|
| 105 |
+
if (body instanceof ReadableStream)
|
| 106 |
+
(init as RequestInit & { duplex?: "half" }).duplex = "half";
|
| 107 |
+
if (linked.signal) init.signal = linked.signal;
|
| 108 |
+
return await fetch(url, init);
|
| 109 |
+
} finally {
|
| 110 |
+
linked.cleanup();
|
| 111 |
+
}
|
| 112 |
+
}
|
| 113 |
+
|
| 114 |
+
function socketErrorConsumedRequestBody(error: unknown): boolean {
|
| 115 |
+
const err = error as
|
| 116 |
+
| { requestBodyStarted?: unknown; code?: unknown }
|
| 117 |
+
| null
|
| 118 |
+
| undefined;
|
| 119 |
+
return (
|
| 120 |
+
!!err &&
|
| 121 |
+
(err.requestBodyStarted === true ||
|
| 122 |
+
err.code === "socket_stream_body_length_required")
|
| 123 |
+
);
|
| 124 |
+
}
|
| 125 |
+
|
| 126 |
+
function linkedFetchSignal(
|
| 127 |
+
signal: AbortSignal | null | undefined,
|
| 128 |
+
timeout: AbortSignal | undefined,
|
| 129 |
+
): { signal: AbortSignal | undefined; cleanup: () => void } {
|
| 130 |
+
if (!signal) return { signal: timeout, cleanup() {} };
|
| 131 |
+
if (!timeout) return { signal, cleanup() {} };
|
| 132 |
+
return { signal: AbortSignal.any([signal, timeout]), cleanup() {} };
|
| 133 |
+
}
|
src/http/google/stream.ts
CHANGED
|
@@ -1,152 +1,154 @@
|
|
| 1 |
-
import {
|
| 2 |
-
createCompletionStreamLifecycle,
|
| 3 |
-
recordCompletionStreamEvent,
|
| 4 |
-
streamPlainCompletionEvents,
|
| 5 |
-
} from "../../completion";
|
| 6 |
-
import type { CompletionProvider } from "../../completion";
|
| 7 |
-
import type { RuntimeConfig } from "../../config";
|
| 8 |
-
import type { ResolvedModel } from "../../models";
|
| 9 |
-
import type { FileRef, LooseRequest } from "../../completion/types";
|
| 10 |
-
import { streamGoogleToolCompletionEvents } from "../../completion/google";
|
| 11 |
-
import { tokenCountFromCounts } from "../../shared/tokens";
|
| 12 |
-
import { errorLogSummary, upstreamErrorCode } from "../../shared/errors";
|
| 13 |
-
import { log } from "../../shared/logging";
|
| 14 |
-
import type { SSEWrite } from "../core/sse";
|
| 15 |
-
import {
|
| 16 |
-
streamInterruptedWarningText,
|
| 17 |
-
writeStreamWarningEvent,
|
| 18 |
-
} from "../core/stream-errors";
|
| 19 |
-
import { createDeltaCoalescer } from "../stream/coalescer";
|
| 20 |
-
import {
|
| 21 |
-
googleStreamDonePayload,
|
| 22 |
-
writeGoogleCandidate,
|
| 23 |
-
writeGoogleDone,
|
| 24 |
-
writeGoogleStreamError,
|
| 25 |
-
} from "./format";
|
| 26 |
-
|
| 27 |
-
type ResolvedCompletionModel = Extract<ResolvedModel, { name: string }>;
|
| 28 |
-
type GooglePlainStreamParams = {
|
| 29 |
-
provider: CompletionProvider;
|
| 30 |
-
prompt: string;
|
| 31 |
-
rm: ResolvedCompletionModel;
|
| 32 |
-
fileRefs: FileRef[] | null;
|
| 33 |
-
promptTokens: number;
|
| 34 |
-
signal: AbortSignal;
|
| 35 |
-
};
|
| 36 |
-
type GoogleToolStreamParams = GooglePlainStreamParams & {
|
| 37 |
-
tools: LooseRequest[] | null;
|
| 38 |
-
effectiveReq: LooseRequest;
|
| 39 |
-
};
|
| 40 |
-
|
| 41 |
-
export async function streamGooglePlain(
|
| 42 |
-
write: SSEWrite,
|
| 43 |
-
cfg: RuntimeConfig,
|
| 44 |
-
params: GooglePlainStreamParams,
|
| 45 |
-
) {
|
| 46 |
-
const { provider, prompt, rm, fileRefs, promptTokens, signal } = params;
|
| 47 |
-
const lifecycle = createCompletionStreamLifecycle();
|
| 48 |
-
const
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
undefined,
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
{
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
if (
|
| 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 |
-
}
|
|
|
|
|
|
|
|
|
| 1 |
+
import {
|
| 2 |
+
createCompletionStreamLifecycle,
|
| 3 |
+
recordCompletionStreamEvent,
|
| 4 |
+
streamPlainCompletionEvents,
|
| 5 |
+
} from "../../completion";
|
| 6 |
+
import type { CompletionProvider } from "../../completion";
|
| 7 |
+
import type { RuntimeConfig } from "../../config";
|
| 8 |
+
import type { ResolvedModel } from "../../models";
|
| 9 |
+
import type { FileRef, LooseRequest } from "../../completion/types";
|
| 10 |
+
import { streamGoogleToolCompletionEvents } from "../../completion/google";
|
| 11 |
+
import { tokenCountFromCounts } from "../../shared/tokens";
|
| 12 |
+
import { errorLogSummary, upstreamErrorCode } from "../../shared/errors";
|
| 13 |
+
import { log } from "../../shared/logging";
|
| 14 |
+
import type { SSEWrite } from "../core/sse";
|
| 15 |
+
import {
|
| 16 |
+
streamInterruptedWarningText,
|
| 17 |
+
writeStreamWarningEvent,
|
| 18 |
+
} from "../core/stream-errors";
|
| 19 |
+
import { createDeltaCoalescer } from "../stream/coalescer";
|
| 20 |
+
import {
|
| 21 |
+
googleStreamDonePayload,
|
| 22 |
+
writeGoogleCandidate,
|
| 23 |
+
writeGoogleDone,
|
| 24 |
+
writeGoogleStreamError,
|
| 25 |
+
} from "./format";
|
| 26 |
+
|
| 27 |
+
type ResolvedCompletionModel = Extract<ResolvedModel, { name: string }>;
|
| 28 |
+
type GooglePlainStreamParams = {
|
| 29 |
+
provider: CompletionProvider;
|
| 30 |
+
prompt: string;
|
| 31 |
+
rm: ResolvedCompletionModel;
|
| 32 |
+
fileRefs: FileRef[] | null;
|
| 33 |
+
promptTokens: number;
|
| 34 |
+
signal: AbortSignal;
|
| 35 |
+
};
|
| 36 |
+
type GoogleToolStreamParams = GooglePlainStreamParams & {
|
| 37 |
+
tools: LooseRequest[] | null;
|
| 38 |
+
effectiveReq: LooseRequest;
|
| 39 |
+
};
|
| 40 |
+
|
| 41 |
+
export async function streamGooglePlain(
|
| 42 |
+
write: SSEWrite,
|
| 43 |
+
cfg: RuntimeConfig,
|
| 44 |
+
params: GooglePlainStreamParams,
|
| 45 |
+
) {
|
| 46 |
+
const { provider, prompt, rm, fileRefs, promptTokens, signal } = params;
|
| 47 |
+
const lifecycle = createCompletionStreamLifecycle();
|
| 48 |
+
const resinSmooth = !!cfg.resin_proxy;
|
| 49 |
+
const textCoalescer = createDeltaCoalescer(
|
| 50 |
+
(delta) => {
|
| 51 |
+
const text = delta.text || "";
|
| 52 |
+
return write(
|
| 53 |
+
`data: ${JSON.stringify({ candidates: [{ content: { parts: [{ text }], role: "model" }, index: 0 }], modelVersion: rm.name })}\n\n`,
|
| 54 |
+
);
|
| 55 |
+
},
|
| 56 |
+
resinSmooth ? 1 : undefined,
|
| 57 |
+
resinSmooth ? 0 : undefined,
|
| 58 |
+
{ emitFirstImmediately: true },
|
| 59 |
+
);
|
| 60 |
+
for await (const event of streamPlainCompletionEvents(
|
| 61 |
+
provider,
|
| 62 |
+
{ prompt, rm, fileRefs },
|
| 63 |
+
{ signal, coalesceTextDeltas: !resinSmooth },
|
| 64 |
+
)) {
|
| 65 |
+
recordCompletionStreamEvent(lifecycle, event);
|
| 66 |
+
if (event.type === "text_delta") {
|
| 67 |
+
const appended = textCoalescer.append("text", event.text);
|
| 68 |
+
if (appended) await appended;
|
| 69 |
+
}
|
| 70 |
+
}
|
| 71 |
+
const flushed = textCoalescer.flush();
|
| 72 |
+
if (flushed) await flushed;
|
| 73 |
+
if (lifecycle.issue) {
|
| 74 |
+
if (!lifecycle.emittedText) {
|
| 75 |
+
log(
|
| 76 |
+
cfg,
|
| 77 |
+
`google stream failed before output model=${rm.name} code=${upstreamErrorCode(lifecycle.issue.error) || "upstream_error"} error=${errorLogSummary(lifecycle.issue.error)}`,
|
| 78 |
+
);
|
| 79 |
+
await writeGoogleStreamError(write, rm.name, lifecycle.issue.error);
|
| 80 |
+
return;
|
| 81 |
+
}
|
| 82 |
+
const warning = `\n\n${streamInterruptedWarningText(lifecycle.issue.error)}`;
|
| 83 |
+
log(
|
| 84 |
+
cfg,
|
| 85 |
+
`google stream interrupted after partial output model=${rm.name} code=${upstreamErrorCode(lifecycle.issue.error) || "stream_interrupted"} error=${errorLogSummary(lifecycle.issue.error)}`,
|
| 86 |
+
);
|
| 87 |
+
await writeStreamWarningEvent(write, lifecycle.issue.error, warning.trim());
|
| 88 |
+
}
|
| 89 |
+
const candidateTokens = tokenCountFromCounts(lifecycle.completionCounts);
|
| 90 |
+
await write(
|
| 91 |
+
`data: ${JSON.stringify(googleStreamDonePayload(rm.name, promptTokens, candidateTokens, lifecycle.issue ? lifecycle.issue.error : null))}\n\n`,
|
| 92 |
+
);
|
| 93 |
+
}
|
| 94 |
+
|
| 95 |
+
export async function streamGoogleTools(
|
| 96 |
+
write: SSEWrite,
|
| 97 |
+
cfg: RuntimeConfig,
|
| 98 |
+
params: GoogleToolStreamParams,
|
| 99 |
+
) {
|
| 100 |
+
const resinSmooth = !!cfg.resin_proxy;
|
| 101 |
+
const {
|
| 102 |
+
provider,
|
| 103 |
+
prompt,
|
| 104 |
+
rm,
|
| 105 |
+
fileRefs,
|
| 106 |
+
tools,
|
| 107 |
+
effectiveReq,
|
| 108 |
+
promptTokens,
|
| 109 |
+
signal,
|
| 110 |
+
} = params;
|
| 111 |
+
for await (const event of streamGoogleToolCompletionEvents(provider, {
|
| 112 |
+
prompt,
|
| 113 |
+
rm,
|
| 114 |
+
fileRefs,
|
| 115 |
+
tools,
|
| 116 |
+
effectiveReq,
|
| 117 |
+
promptTokens,
|
| 118 |
+
signal,
|
| 119 |
+
})) {
|
| 120 |
+
if (event.type === "candidate") {
|
| 121 |
+
await writeGoogleCandidate(
|
| 122 |
+
write,
|
| 123 |
+
rm.name,
|
| 124 |
+
event.parts,
|
| 125 |
+
event.finishReason,
|
| 126 |
+
);
|
| 127 |
+
} else if (event.type === "error") {
|
| 128 |
+
log(
|
| 129 |
+
cfg,
|
| 130 |
+
`google tool stream failed before output model=${rm.name} code=${upstreamErrorCode(event.error) || "upstream_error"} error=${errorLogSummary(event.error)}`,
|
| 131 |
+
);
|
| 132 |
+
await writeGoogleStreamError(write, rm.name, event.error);
|
| 133 |
+
return;
|
| 134 |
+
} else if (event.type === "warning") {
|
| 135 |
+
log(
|
| 136 |
+
cfg,
|
| 137 |
+
`google tool stream interrupted after partial output model=${rm.name} code=${upstreamErrorCode(event.error) || "stream_interrupted"} error=${errorLogSummary(event.error)}`,
|
| 138 |
+
);
|
| 139 |
+
await writeStreamWarningEvent(write, event.error, event.message);
|
| 140 |
+
} else if (event.type === "tool_policy_violation") {
|
| 141 |
+
log(
|
| 142 |
+
cfg,
|
| 143 |
+
`google tool stream policy violation model=${rm.name} code=${event.violation.code}`,
|
| 144 |
+
);
|
| 145 |
+
await writeGoogleStreamError(write, rm.name, {
|
| 146 |
+
message: event.violation.message,
|
| 147 |
+
code: event.violation.code,
|
| 148 |
+
});
|
| 149 |
+
return;
|
| 150 |
+
} else if (event.type === "done") {
|
| 151 |
+
await writeGoogleDone(write, rm.name, event.usageMetadata);
|
| 152 |
+
}
|
| 153 |
+
}
|
| 154 |
+
}
|
src/http/openai/chat-stream.ts
CHANGED
|
@@ -1,283 +1,285 @@
|
|
| 1 |
-
import { parseJsonObject } from "../core/json";
|
| 2 |
-
import type { SSEWrite } from "../core/sse";
|
| 3 |
-
import {
|
| 4 |
-
streamInterruptedWarningText,
|
| 5 |
-
writeStreamWarningEvent,
|
| 6 |
-
} from "../core/stream-errors";
|
| 7 |
-
import { createDeltaCoalescer } from "../stream/coalescer";
|
| 8 |
-
import {
|
| 9 |
-
EMPTY_UPSTREAM_MSG,
|
| 10 |
-
createCompletionStreamLifecycle,
|
| 11 |
-
recordCompletionStreamEvent,
|
| 12 |
-
streamPlainCompletionEvents,
|
| 13 |
-
streamToolSieveCompletionEvents,
|
| 14 |
-
} from "../../completion";
|
| 15 |
-
import type {
|
| 16 |
-
CompletionProvider,
|
| 17 |
-
CompletionStreamEvent,
|
| 18 |
-
} from "../../completion";
|
| 19 |
-
import type { RuntimeConfig } from "../../config";
|
| 20 |
-
import type { ResolvedModel } from "../../models";
|
| 21 |
-
import type { FileRef } from "../../completion/types";
|
| 22 |
-
import { errorLogSummary, upstreamErrorCode } from "../../shared/errors";
|
| 23 |
-
import { log } from "../../shared/logging";
|
| 24 |
-
import {
|
| 25 |
-
combinedTokenCount,
|
| 26 |
-
createTokenCounter,
|
| 27 |
-
tokenCountFromCounts,
|
| 28 |
-
} from "../../shared/tokens";
|
| 29 |
-
import { formatOpenAIStreamToolCalls } from "../../toolcall/openai-format";
|
| 30 |
-
import type { OpenAIToolCall } from "../../toolcall/openai-format";
|
| 31 |
-
import type { ToolChoicePolicy } from "../../toolcall/policy-openai";
|
| 32 |
-
import { openAIChatChunk, writeOpenAIChatUsageTokenChunk } from "./format";
|
| 33 |
-
import { writeOpenAIChatStreamError } from "./format";
|
| 34 |
-
|
| 35 |
-
type StreamIssue = Extract<
|
| 36 |
-
CompletionStreamEvent,
|
| 37 |
-
{ type: "warning" } | { type: "stream_error" }
|
| 38 |
-
>;
|
| 39 |
-
type ResolvedCompletionModel = Extract<ResolvedModel, { name: string }>;
|
| 40 |
-
type OpenAIChatChunkWriter = (
|
| 41 |
-
delta: Record<string, unknown>,
|
| 42 |
-
finish: string | null,
|
| 43 |
-
) => void | Promise<void>;
|
| 44 |
-
type OpenAIChatDeltaCoalescer = ReturnType<typeof createDeltaCoalescer>;
|
| 45 |
-
type OpenAIChatPlainStreamParams = {
|
| 46 |
-
provider: CompletionProvider;
|
| 47 |
-
id: string;
|
| 48 |
-
model: string;
|
| 49 |
-
prompt: string;
|
| 50 |
-
rm: ResolvedCompletionModel;
|
| 51 |
-
fileRefs: FileRef[] | null;
|
| 52 |
-
includeUsage: boolean;
|
| 53 |
-
promptTokens: number;
|
| 54 |
-
signal: AbortSignal;
|
| 55 |
-
};
|
| 56 |
-
type OpenAIChatToolSieveStreamParams = OpenAIChatPlainStreamParams & {
|
| 57 |
-
tools: unknown[];
|
| 58 |
-
toolPolicy: ToolChoicePolicy | null | undefined;
|
| 59 |
-
};
|
| 60 |
-
|
| 61 |
-
export async function streamOpenAIChatPlain(
|
| 62 |
-
write: SSEWrite,
|
| 63 |
-
cfg: RuntimeConfig,
|
| 64 |
-
params: OpenAIChatPlainStreamParams,
|
| 65 |
-
) {
|
| 66 |
-
const {
|
| 67 |
-
provider,
|
| 68 |
-
id,
|
| 69 |
-
model,
|
| 70 |
-
prompt,
|
| 71 |
-
rm,
|
| 72 |
-
fileRefs,
|
| 73 |
-
includeUsage,
|
| 74 |
-
promptTokens,
|
| 75 |
-
signal,
|
| 76 |
-
} = params;
|
| 77 |
-
const lifecycle = createCompletionStreamLifecycle();
|
| 78 |
-
const
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
undefined,
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
{
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
lifecycle.
|
| 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 |
-
const
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
}
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
|
|
|
|
|
|
|
|
| 1 |
+
import { parseJsonObject } from "../core/json";
|
| 2 |
+
import type { SSEWrite } from "../core/sse";
|
| 3 |
+
import {
|
| 4 |
+
streamInterruptedWarningText,
|
| 5 |
+
writeStreamWarningEvent,
|
| 6 |
+
} from "../core/stream-errors";
|
| 7 |
+
import { createDeltaCoalescer } from "../stream/coalescer";
|
| 8 |
+
import {
|
| 9 |
+
EMPTY_UPSTREAM_MSG,
|
| 10 |
+
createCompletionStreamLifecycle,
|
| 11 |
+
recordCompletionStreamEvent,
|
| 12 |
+
streamPlainCompletionEvents,
|
| 13 |
+
streamToolSieveCompletionEvents,
|
| 14 |
+
} from "../../completion";
|
| 15 |
+
import type {
|
| 16 |
+
CompletionProvider,
|
| 17 |
+
CompletionStreamEvent,
|
| 18 |
+
} from "../../completion";
|
| 19 |
+
import type { RuntimeConfig } from "../../config";
|
| 20 |
+
import type { ResolvedModel } from "../../models";
|
| 21 |
+
import type { FileRef } from "../../completion/types";
|
| 22 |
+
import { errorLogSummary, upstreamErrorCode } from "../../shared/errors";
|
| 23 |
+
import { log } from "../../shared/logging";
|
| 24 |
+
import {
|
| 25 |
+
combinedTokenCount,
|
| 26 |
+
createTokenCounter,
|
| 27 |
+
tokenCountFromCounts,
|
| 28 |
+
} from "../../shared/tokens";
|
| 29 |
+
import { formatOpenAIStreamToolCalls } from "../../toolcall/openai-format";
|
| 30 |
+
import type { OpenAIToolCall } from "../../toolcall/openai-format";
|
| 31 |
+
import type { ToolChoicePolicy } from "../../toolcall/policy-openai";
|
| 32 |
+
import { openAIChatChunk, writeOpenAIChatUsageTokenChunk } from "./format";
|
| 33 |
+
import { writeOpenAIChatStreamError } from "./format";
|
| 34 |
+
|
| 35 |
+
type StreamIssue = Extract<
|
| 36 |
+
CompletionStreamEvent,
|
| 37 |
+
{ type: "warning" } | { type: "stream_error" }
|
| 38 |
+
>;
|
| 39 |
+
type ResolvedCompletionModel = Extract<ResolvedModel, { name: string }>;
|
| 40 |
+
type OpenAIChatChunkWriter = (
|
| 41 |
+
delta: Record<string, unknown>,
|
| 42 |
+
finish: string | null,
|
| 43 |
+
) => void | Promise<void>;
|
| 44 |
+
type OpenAIChatDeltaCoalescer = ReturnType<typeof createDeltaCoalescer>;
|
| 45 |
+
type OpenAIChatPlainStreamParams = {
|
| 46 |
+
provider: CompletionProvider;
|
| 47 |
+
id: string;
|
| 48 |
+
model: string;
|
| 49 |
+
prompt: string;
|
| 50 |
+
rm: ResolvedCompletionModel;
|
| 51 |
+
fileRefs: FileRef[] | null;
|
| 52 |
+
includeUsage: boolean;
|
| 53 |
+
promptTokens: number;
|
| 54 |
+
signal: AbortSignal;
|
| 55 |
+
};
|
| 56 |
+
type OpenAIChatToolSieveStreamParams = OpenAIChatPlainStreamParams & {
|
| 57 |
+
tools: unknown[];
|
| 58 |
+
toolPolicy: ToolChoicePolicy | null | undefined;
|
| 59 |
+
};
|
| 60 |
+
|
| 61 |
+
export async function streamOpenAIChatPlain(
|
| 62 |
+
write: SSEWrite,
|
| 63 |
+
cfg: RuntimeConfig,
|
| 64 |
+
params: OpenAIChatPlainStreamParams,
|
| 65 |
+
) {
|
| 66 |
+
const {
|
| 67 |
+
provider,
|
| 68 |
+
id,
|
| 69 |
+
model,
|
| 70 |
+
prompt,
|
| 71 |
+
rm,
|
| 72 |
+
fileRefs,
|
| 73 |
+
includeUsage,
|
| 74 |
+
promptTokens,
|
| 75 |
+
signal,
|
| 76 |
+
} = params;
|
| 77 |
+
const lifecycle = createCompletionStreamLifecycle();
|
| 78 |
+
const resinSmooth = !!cfg.resin_proxy;
|
| 79 |
+
const writeChunk = (delta: Record<string, unknown>, finish: string | null) =>
|
| 80 |
+
write(
|
| 81 |
+
`data: ${JSON.stringify(openAIChatChunk(id, model, delta, finish))}\n\n`,
|
| 82 |
+
);
|
| 83 |
+
const deltaCoalescer = createDeltaCoalescer(
|
| 84 |
+
(delta) => writeChunk(delta, null),
|
| 85 |
+
resinSmooth ? 1 : undefined,
|
| 86 |
+
resinSmooth ? 0 : undefined,
|
| 87 |
+
{ emitFirstImmediately: true },
|
| 88 |
+
);
|
| 89 |
+
await writeChunk({ role: "assistant" }, null);
|
| 90 |
+
|
| 91 |
+
for await (const event of streamPlainCompletionEvents(
|
| 92 |
+
provider,
|
| 93 |
+
{ prompt, rm, fileRefs },
|
| 94 |
+
{ signal, coalesceTextDeltas: !resinSmooth },
|
| 95 |
+
)) {
|
| 96 |
+
recordCompletionStreamEvent(lifecycle, event);
|
| 97 |
+
if (event.type === "text_delta") {
|
| 98 |
+
const appended = deltaCoalescer.append("content", event.text);
|
| 99 |
+
if (appended) await appended;
|
| 100 |
+
}
|
| 101 |
+
}
|
| 102 |
+
await flushOpenAIChatDeltas(deltaCoalescer);
|
| 103 |
+
|
| 104 |
+
if (
|
| 105 |
+
(lifecycle.issue && lifecycle.issue.type === "stream_error") ||
|
| 106 |
+
lifecycle.empty
|
| 107 |
+
) {
|
| 108 |
+
const error = lifecycle.issue?.error || {
|
| 109 |
+
message: EMPTY_UPSTREAM_MSG,
|
| 110 |
+
code: "upstream_empty",
|
| 111 |
+
};
|
| 112 |
+
log(
|
| 113 |
+
cfg,
|
| 114 |
+
lifecycle.issue
|
| 115 |
+
? `openai chat stream failed before output model=${rm.name} code=${upstreamErrorCode(error) || "upstream_error"} error=${errorLogSummary(error)}`
|
| 116 |
+
: `openai chat stream produced no content model=${rm.name}`,
|
| 117 |
+
);
|
| 118 |
+
await writeOpenAIChatStreamError(write, id, model, error);
|
| 119 |
+
return;
|
| 120 |
+
} else if (lifecycle.issue) {
|
| 121 |
+
await writeOpenAIChatInterrupted(write, cfg, rm, lifecycle.issue);
|
| 122 |
+
}
|
| 123 |
+
await finishOpenAIChatStream(
|
| 124 |
+
write,
|
| 125 |
+
writeChunk,
|
| 126 |
+
id,
|
| 127 |
+
model,
|
| 128 |
+
includeUsage,
|
| 129 |
+
promptTokens,
|
| 130 |
+
lifecycle.completionCounts,
|
| 131 |
+
);
|
| 132 |
+
}
|
| 133 |
+
|
| 134 |
+
export async function streamOpenAIChatWithToolSieve(
|
| 135 |
+
write: SSEWrite,
|
| 136 |
+
_cfg: RuntimeConfig,
|
| 137 |
+
params: OpenAIChatToolSieveStreamParams,
|
| 138 |
+
) {
|
| 139 |
+
const {
|
| 140 |
+
provider,
|
| 141 |
+
id,
|
| 142 |
+
model,
|
| 143 |
+
prompt,
|
| 144 |
+
rm,
|
| 145 |
+
fileRefs,
|
| 146 |
+
tools,
|
| 147 |
+
toolPolicy,
|
| 148 |
+
includeUsage,
|
| 149 |
+
promptTokens,
|
| 150 |
+
signal,
|
| 151 |
+
} = params;
|
| 152 |
+
const extraTokenCounter = createTokenCounter();
|
| 153 |
+
const writeChunk = (delta: Record<string, unknown>, finish: string | null) =>
|
| 154 |
+
write(
|
| 155 |
+
`data: ${JSON.stringify(openAIChatChunk(id, model, delta, finish))}\n\n`,
|
| 156 |
+
);
|
| 157 |
+
const resinSmooth = !!_cfg.resin_proxy;
|
| 158 |
+
const deltaCoalescer = createDeltaCoalescer(
|
| 159 |
+
(delta) => writeChunk(delta, null),
|
| 160 |
+
resinSmooth ? 1 : undefined,
|
| 161 |
+
resinSmooth ? 0 : undefined,
|
| 162 |
+
{ emitFirstImmediately: true },
|
| 163 |
+
);
|
| 164 |
+
const toolLifecycle = createCompletionStreamLifecycle();
|
| 165 |
+
await writeChunk({ role: "assistant" }, null);
|
| 166 |
+
|
| 167 |
+
for await (const event of streamToolSieveCompletionEvents(
|
| 168 |
+
provider,
|
| 169 |
+
{ prompt, rm, fileRefs, tools, toolPolicy },
|
| 170 |
+
{ signal, coalesceTextDeltas: !resinSmooth },
|
| 171 |
+
)) {
|
| 172 |
+
recordCompletionStreamEvent(toolLifecycle, event);
|
| 173 |
+
if (event.type === "text_delta") {
|
| 174 |
+
const appended = deltaCoalescer.append("content", event.text);
|
| 175 |
+
if (appended) await appended;
|
| 176 |
+
}
|
| 177 |
+
}
|
| 178 |
+
await flushOpenAIChatDeltas(deltaCoalescer);
|
| 179 |
+
|
| 180 |
+
if (toolLifecycle.violation) {
|
| 181 |
+
await flushOpenAIChatDeltas(deltaCoalescer);
|
| 182 |
+
log(
|
| 183 |
+
_cfg,
|
| 184 |
+
`openai chat stream tool policy violation model=${rm.name} code=${toolLifecycle.violation.code}`,
|
| 185 |
+
);
|
| 186 |
+
await writeOpenAIChatStreamError(write, id, model, toolLifecycle.violation);
|
| 187 |
+
return;
|
| 188 |
+
}
|
| 189 |
+
if (toolLifecycle.toolCalls?.length) {
|
| 190 |
+
await flushOpenAIChatDeltas(deltaCoalescer);
|
| 191 |
+
if (toolLifecycle.issue) {
|
| 192 |
+
log(
|
| 193 |
+
_cfg,
|
| 194 |
+
`openai chat stream interrupted after tool calls model=${rm.name} code=${upstreamErrorCode(toolLifecycle.issue.error) || "stream_interrupted"} error=${errorLogSummary(toolLifecycle.issue.error)}`,
|
| 195 |
+
);
|
| 196 |
+
await writeStreamWarningEvent(write, toolLifecycle.issue.error);
|
| 197 |
+
}
|
| 198 |
+
const toolCallDeltas = formatOpenAIStreamToolCalls(
|
| 199 |
+
toolLifecycle.toolCalls.map(openAIStreamToolCallInput),
|
| 200 |
+
new Map(),
|
| 201 |
+
tools,
|
| 202 |
+
);
|
| 203 |
+
await writeChunk({ tool_calls: toolCallDeltas }, "tool_calls");
|
| 204 |
+
extraTokenCounter.append(JSON.stringify(toolLifecycle.toolCalls));
|
| 205 |
+
} else {
|
| 206 |
+
if (!toolLifecycle.emittedText || toolLifecycle.empty) {
|
| 207 |
+
const error = toolLifecycle.issue?.error || {
|
| 208 |
+
message: EMPTY_UPSTREAM_MSG,
|
| 209 |
+
code: "upstream_empty",
|
| 210 |
+
};
|
| 211 |
+
log(
|
| 212 |
+
_cfg,
|
| 213 |
+
toolLifecycle.issue
|
| 214 |
+
? `openai chat stream failed before output model=${rm.name} code=${upstreamErrorCode(error) || "upstream_error"} error=${errorLogSummary(error)}`
|
| 215 |
+
: `openai chat stream produced no content model=${rm.name}`,
|
| 216 |
+
);
|
| 217 |
+
await writeOpenAIChatStreamError(write, id, model, error);
|
| 218 |
+
return;
|
| 219 |
+
} else if (toolLifecycle.issue) {
|
| 220 |
+
await writeOpenAIChatInterrupted(write, _cfg, rm, toolLifecycle.issue);
|
| 221 |
+
}
|
| 222 |
+
await writeChunk({}, "stop");
|
| 223 |
+
}
|
| 224 |
+
if (includeUsage)
|
| 225 |
+
await writeOpenAIChatUsageTokenChunk(
|
| 226 |
+
write,
|
| 227 |
+
id,
|
| 228 |
+
model,
|
| 229 |
+
promptTokens,
|
| 230 |
+
combinedTokenCount(toolLifecycle.completionCounts, extraTokenCounter),
|
| 231 |
+
);
|
| 232 |
+
await write("data: [DONE]\n\n");
|
| 233 |
+
}
|
| 234 |
+
|
| 235 |
+
async function flushOpenAIChatDeltas(
|
| 236 |
+
coalescer: OpenAIChatDeltaCoalescer,
|
| 237 |
+
): Promise<void> {
|
| 238 |
+
const flushed = coalescer.flush();
|
| 239 |
+
if (flushed) await flushed;
|
| 240 |
+
}
|
| 241 |
+
|
| 242 |
+
async function finishOpenAIChatStream(
|
| 243 |
+
write: SSEWrite,
|
| 244 |
+
writeChunk: OpenAIChatChunkWriter,
|
| 245 |
+
id: string,
|
| 246 |
+
model: string,
|
| 247 |
+
includeUsage: boolean,
|
| 248 |
+
promptTokens: number,
|
| 249 |
+
completionCounts: Parameters<typeof tokenCountFromCounts>[0],
|
| 250 |
+
): Promise<void> {
|
| 251 |
+
await writeChunk({}, "stop");
|
| 252 |
+
if (includeUsage)
|
| 253 |
+
await writeOpenAIChatUsageTokenChunk(
|
| 254 |
+
write,
|
| 255 |
+
id,
|
| 256 |
+
model,
|
| 257 |
+
promptTokens,
|
| 258 |
+
tokenCountFromCounts(completionCounts),
|
| 259 |
+
);
|
| 260 |
+
await write("data: [DONE]\n\n");
|
| 261 |
+
}
|
| 262 |
+
|
| 263 |
+
async function writeOpenAIChatInterrupted(
|
| 264 |
+
write: SSEWrite,
|
| 265 |
+
cfg: RuntimeConfig,
|
| 266 |
+
rm: ResolvedCompletionModel,
|
| 267 |
+
issue: StreamIssue,
|
| 268 |
+
): Promise<void> {
|
| 269 |
+
const warning = `\n\n${streamInterruptedWarningText(issue.error)}`;
|
| 270 |
+
log(
|
| 271 |
+
cfg,
|
| 272 |
+
`openai chat stream interrupted after partial output model=${rm.name} code=${upstreamErrorCode(issue.error) || "stream_interrupted"} error=${errorLogSummary(issue.error)}`,
|
| 273 |
+
);
|
| 274 |
+
await writeStreamWarningEvent(write, issue.error, warning.trim());
|
| 275 |
+
}
|
| 276 |
+
|
| 277 |
+
function openAIStreamToolCallInput(toolCall: OpenAIToolCall): {
|
| 278 |
+
name: unknown;
|
| 279 |
+
input: unknown;
|
| 280 |
+
} {
|
| 281 |
+
return {
|
| 282 |
+
name: toolCall.function.name,
|
| 283 |
+
input: parseJsonObject(toolCall.function.arguments),
|
| 284 |
+
};
|
| 285 |
+
}
|
src/http/openai/responses-stream.ts
CHANGED
|
@@ -1,339 +1,340 @@
|
|
| 1 |
-
import type { CompletionProvider } from "../../completion";
|
| 2 |
-
import {
|
| 3 |
-
createCompletionStreamLifecycle,
|
| 4 |
-
EMPTY_UPSTREAM_MSG,
|
| 5 |
-
recordCompletionStreamEvent,
|
| 6 |
-
streamPlainCompletionEvents,
|
| 7 |
-
streamToolSieveCompletionEvents,
|
| 8 |
-
} from "../../completion";
|
| 9 |
-
import type { FileRef } from "../../completion/types";
|
| 10 |
-
import type { RuntimeConfig } from "../../config";
|
| 11 |
-
import type { ResolvedModel } from "../../models";
|
| 12 |
-
import { randHex } from "../../shared/crypto";
|
| 13 |
-
import {
|
| 14 |
-
errorLogSummary,
|
| 15 |
-
upstreamErrorCode,
|
| 16 |
-
upstreamErrorMessage,
|
| 17 |
-
} from "../../shared/errors";
|
| 18 |
-
import { log } from "../../shared/logging";
|
| 19 |
-
import { tokenCountFromCounts } from "../../shared/tokens";
|
| 20 |
-
import type { ToolChoicePolicy } from "../../toolcall/policy-openai";
|
| 21 |
-
import type { SSEWrite } from "../core/sse";
|
| 22 |
-
import {
|
| 23 |
-
streamInterruptedWarningText,
|
| 24 |
-
streamWarningObject,
|
| 25 |
-
} from "../core/stream-errors";
|
| 26 |
-
import { createDeltaCoalescer } from "../stream/coalescer";
|
| 27 |
-
import { isPromiseLike } from "../stream/promise";
|
| 28 |
-
|
| 29 |
-
type ResponseOutputItem = Record<string, unknown> & {
|
| 30 |
-
id?: string;
|
| 31 |
-
status?: string;
|
| 32 |
-
content?: unknown;
|
| 33 |
-
arguments?: string;
|
| 34 |
-
call_id?: string;
|
| 35 |
-
name?: string;
|
| 36 |
-
};
|
| 37 |
-
type StreamResponsesParams = {
|
| 38 |
-
provider: CompletionProvider;
|
| 39 |
-
rid: string;
|
| 40 |
-
rm: Extract<ResolvedModel, { name: string }>;
|
| 41 |
-
prompt: string;
|
| 42 |
-
fileRefs: FileRef[] | null;
|
| 43 |
-
tools: unknown;
|
| 44 |
-
toolPolicy: ToolChoicePolicy | null | undefined;
|
| 45 |
-
promptTokens: unknown;
|
| 46 |
-
signal: AbortSignal;
|
| 47 |
-
};
|
| 48 |
-
|
| 49 |
-
export async function writeResponsesEvent(
|
| 50 |
-
write: SSEWrite,
|
| 51 |
-
event: string,
|
| 52 |
-
payload: Record<string, unknown> | null | undefined,
|
| 53 |
-
): Promise<void> {
|
| 54 |
-
const result = write(
|
| 55 |
-
`event: ${event}\ndata: ${JSON.stringify({ type: event, ...(payload || {}) })}\n\n`,
|
| 56 |
-
);
|
| 57 |
-
if (isPromiseLike(result)) await result;
|
| 58 |
-
}
|
| 59 |
-
|
| 60 |
-
export async function streamResponsesWithToolSieve(
|
| 61 |
-
write: SSEWrite,
|
| 62 |
-
cfg: RuntimeConfig,
|
| 63 |
-
params: StreamResponsesParams,
|
| 64 |
-
) {
|
| 65 |
-
const {
|
| 66 |
-
provider,
|
| 67 |
-
rid,
|
| 68 |
-
rm,
|
| 69 |
-
prompt,
|
| 70 |
-
fileRefs,
|
| 71 |
-
tools,
|
| 72 |
-
toolPolicy,
|
| 73 |
-
promptTokens,
|
| 74 |
-
signal,
|
| 75 |
-
} = params;
|
| 76 |
-
const output: ResponseOutputItem[] = [];
|
| 77 |
-
const mid = `msg_${randHex(12)}`;
|
| 78 |
-
const textParts: string[] = [];
|
| 79 |
-
let messageStarted = false;
|
| 80 |
-
let contentStarted = false;
|
| 81 |
-
let outputIndex = 0;
|
| 82 |
-
const
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
undefined,
|
| 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 |
-
const
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
item.
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
{
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
{
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
const
|
| 278 |
-
const
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
item.
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
const
|
| 324 |
-
const
|
| 325 |
-
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
}
|
|
|
|
|
|
| 1 |
+
import type { CompletionProvider } from "../../completion";
|
| 2 |
+
import {
|
| 3 |
+
createCompletionStreamLifecycle,
|
| 4 |
+
EMPTY_UPSTREAM_MSG,
|
| 5 |
+
recordCompletionStreamEvent,
|
| 6 |
+
streamPlainCompletionEvents,
|
| 7 |
+
streamToolSieveCompletionEvents,
|
| 8 |
+
} from "../../completion";
|
| 9 |
+
import type { FileRef } from "../../completion/types";
|
| 10 |
+
import type { RuntimeConfig } from "../../config";
|
| 11 |
+
import type { ResolvedModel } from "../../models";
|
| 12 |
+
import { randHex } from "../../shared/crypto";
|
| 13 |
+
import {
|
| 14 |
+
errorLogSummary,
|
| 15 |
+
upstreamErrorCode,
|
| 16 |
+
upstreamErrorMessage,
|
| 17 |
+
} from "../../shared/errors";
|
| 18 |
+
import { log } from "../../shared/logging";
|
| 19 |
+
import { tokenCountFromCounts } from "../../shared/tokens";
|
| 20 |
+
import type { ToolChoicePolicy } from "../../toolcall/policy-openai";
|
| 21 |
+
import type { SSEWrite } from "../core/sse";
|
| 22 |
+
import {
|
| 23 |
+
streamInterruptedWarningText,
|
| 24 |
+
streamWarningObject,
|
| 25 |
+
} from "../core/stream-errors";
|
| 26 |
+
import { createDeltaCoalescer } from "../stream/coalescer";
|
| 27 |
+
import { isPromiseLike } from "../stream/promise";
|
| 28 |
+
|
| 29 |
+
type ResponseOutputItem = Record<string, unknown> & {
|
| 30 |
+
id?: string;
|
| 31 |
+
status?: string;
|
| 32 |
+
content?: unknown;
|
| 33 |
+
arguments?: string;
|
| 34 |
+
call_id?: string;
|
| 35 |
+
name?: string;
|
| 36 |
+
};
|
| 37 |
+
type StreamResponsesParams = {
|
| 38 |
+
provider: CompletionProvider;
|
| 39 |
+
rid: string;
|
| 40 |
+
rm: Extract<ResolvedModel, { name: string }>;
|
| 41 |
+
prompt: string;
|
| 42 |
+
fileRefs: FileRef[] | null;
|
| 43 |
+
tools: unknown;
|
| 44 |
+
toolPolicy: ToolChoicePolicy | null | undefined;
|
| 45 |
+
promptTokens: unknown;
|
| 46 |
+
signal: AbortSignal;
|
| 47 |
+
};
|
| 48 |
+
|
| 49 |
+
export async function writeResponsesEvent(
|
| 50 |
+
write: SSEWrite,
|
| 51 |
+
event: string,
|
| 52 |
+
payload: Record<string, unknown> | null | undefined,
|
| 53 |
+
): Promise<void> {
|
| 54 |
+
const result = write(
|
| 55 |
+
`event: ${event}\ndata: ${JSON.stringify({ type: event, ...(payload || {}) })}\n\n`,
|
| 56 |
+
);
|
| 57 |
+
if (isPromiseLike(result)) await result;
|
| 58 |
+
}
|
| 59 |
+
|
| 60 |
+
export async function streamResponsesWithToolSieve(
|
| 61 |
+
write: SSEWrite,
|
| 62 |
+
cfg: RuntimeConfig,
|
| 63 |
+
params: StreamResponsesParams,
|
| 64 |
+
) {
|
| 65 |
+
const {
|
| 66 |
+
provider,
|
| 67 |
+
rid,
|
| 68 |
+
rm,
|
| 69 |
+
prompt,
|
| 70 |
+
fileRefs,
|
| 71 |
+
tools,
|
| 72 |
+
toolPolicy,
|
| 73 |
+
promptTokens,
|
| 74 |
+
signal,
|
| 75 |
+
} = params;
|
| 76 |
+
const output: ResponseOutputItem[] = [];
|
| 77 |
+
const mid = `msg_${randHex(12)}`;
|
| 78 |
+
const textParts: string[] = [];
|
| 79 |
+
let messageStarted = false;
|
| 80 |
+
let contentStarted = false;
|
| 81 |
+
let outputIndex = 0;
|
| 82 |
+
const resinSmooth = !!cfg.resin_proxy;
|
| 83 |
+
const textDeltaCoalescer = createDeltaCoalescer(
|
| 84 |
+
(delta) => {
|
| 85 |
+
const piece = delta.output_text || "";
|
| 86 |
+
return writeResponsesEvent(write, "response.output_text.delta", {
|
| 87 |
+
item_id: mid,
|
| 88 |
+
output_index: outputIndex,
|
| 89 |
+
content_index: 0,
|
| 90 |
+
delta: piece,
|
| 91 |
+
});
|
| 92 |
+
},
|
| 93 |
+
resinSmooth ? 1 : undefined,
|
| 94 |
+
resinSmooth ? 0 : undefined,
|
| 95 |
+
{ emitFirstImmediately: true },
|
| 96 |
+
);
|
| 97 |
+
|
| 98 |
+
const fail = async (message: unknown, code: unknown) => {
|
| 99 |
+
await writeResponsesEvent(write, "response.failed", {
|
| 100 |
+
response: {
|
| 101 |
+
id: rid,
|
| 102 |
+
object: "response",
|
| 103 |
+
status: "failed",
|
| 104 |
+
model: rm.name,
|
| 105 |
+
output,
|
| 106 |
+
error: { message, code: code || "upstream_error" },
|
| 107 |
+
},
|
| 108 |
+
});
|
| 109 |
+
};
|
| 110 |
+
const startMessage = async () => {
|
| 111 |
+
if (!messageStarted) {
|
| 112 |
+
messageStarted = true;
|
| 113 |
+
const item: ResponseOutputItem = {
|
| 114 |
+
type: "message",
|
| 115 |
+
id: mid,
|
| 116 |
+
role: "assistant",
|
| 117 |
+
status: "in_progress",
|
| 118 |
+
content: [],
|
| 119 |
+
};
|
| 120 |
+
output.push(item);
|
| 121 |
+
await writeResponsesEvent(write, "response.output_item.added", {
|
| 122 |
+
output_index: outputIndex,
|
| 123 |
+
item,
|
| 124 |
+
});
|
| 125 |
+
}
|
| 126 |
+
if (!contentStarted) {
|
| 127 |
+
contentStarted = true;
|
| 128 |
+
await writeResponsesEvent(write, "response.content_part.added", {
|
| 129 |
+
item_id: mid,
|
| 130 |
+
output_index: outputIndex,
|
| 131 |
+
content_index: 0,
|
| 132 |
+
part: { type: "output_text", text: "", annotations: [] },
|
| 133 |
+
});
|
| 134 |
+
}
|
| 135 |
+
};
|
| 136 |
+
const emitText = async (piece: unknown) => {
|
| 137 |
+
if (!piece) return;
|
| 138 |
+
const textPiece = String(piece);
|
| 139 |
+
await startMessage();
|
| 140 |
+
textParts.push(textPiece);
|
| 141 |
+
const appended = textDeltaCoalescer.append("output_text", textPiece);
|
| 142 |
+
if (appended) await appended;
|
| 143 |
+
};
|
| 144 |
+
const finishMessage = async () => {
|
| 145 |
+
if (!messageStarted) return;
|
| 146 |
+
const flushed = textDeltaCoalescer.flush();
|
| 147 |
+
if (flushed) await flushed;
|
| 148 |
+
const item = output.find((it) => it.id === mid);
|
| 149 |
+
const text =
|
| 150 |
+
textParts.length === 1 ? textParts[0] || "" : textParts.join("");
|
| 151 |
+
const part = { type: "output_text", text, annotations: [] };
|
| 152 |
+
if (item) {
|
| 153 |
+
item.status = "completed";
|
| 154 |
+
item.content = [part];
|
| 155 |
+
}
|
| 156 |
+
if (contentStarted) {
|
| 157 |
+
await writeResponsesEvent(write, "response.output_text.done", {
|
| 158 |
+
item_id: mid,
|
| 159 |
+
content_index: 0,
|
| 160 |
+
text,
|
| 161 |
+
});
|
| 162 |
+
await writeResponsesEvent(write, "response.content_part.done", {
|
| 163 |
+
item_id: mid,
|
| 164 |
+
output_index: outputIndex,
|
| 165 |
+
content_index: 0,
|
| 166 |
+
part,
|
| 167 |
+
});
|
| 168 |
+
}
|
| 169 |
+
await writeResponsesEvent(write, "response.output_item.done", {
|
| 170 |
+
output_index: outputIndex,
|
| 171 |
+
item,
|
| 172 |
+
});
|
| 173 |
+
outputIndex += 1;
|
| 174 |
+
};
|
| 175 |
+
|
| 176 |
+
await writeResponsesEvent(write, "response.created", {
|
| 177 |
+
response: {
|
| 178 |
+
id: rid,
|
| 179 |
+
object: "response",
|
| 180 |
+
status: "in_progress",
|
| 181 |
+
model: rm.name,
|
| 182 |
+
output: [],
|
| 183 |
+
},
|
| 184 |
+
});
|
| 185 |
+
await writeResponsesEvent(write, "response.in_progress", {
|
| 186 |
+
response: {
|
| 187 |
+
id: rid,
|
| 188 |
+
object: "response",
|
| 189 |
+
status: "in_progress",
|
| 190 |
+
model: rm.name,
|
| 191 |
+
output: [],
|
| 192 |
+
},
|
| 193 |
+
});
|
| 194 |
+
const lifecycle = createCompletionStreamLifecycle();
|
| 195 |
+
if (tools) {
|
| 196 |
+
for await (const event of streamToolSieveCompletionEvents(
|
| 197 |
+
provider,
|
| 198 |
+
{ prompt, rm, fileRefs, tools, toolPolicy },
|
| 199 |
+
{ signal, coalesceTextDeltas: !resinSmooth },
|
| 200 |
+
)) {
|
| 201 |
+
recordCompletionStreamEvent(lifecycle, event);
|
| 202 |
+
if (event.type === "text_delta") {
|
| 203 |
+
await emitText(event.text);
|
| 204 |
+
}
|
| 205 |
+
}
|
| 206 |
+
if (lifecycle.issue) {
|
| 207 |
+
if (!lifecycle.emittedText && !lifecycle.toolCalls) {
|
| 208 |
+
log(
|
| 209 |
+
cfg,
|
| 210 |
+
`openai responses stream failed before output model=${rm.name} code=${upstreamErrorCode(lifecycle.issue.error) || "upstream_error"} error=${errorLogSummary(lifecycle.issue.error)}`,
|
| 211 |
+
);
|
| 212 |
+
await fail(
|
| 213 |
+
`upstream error: ${upstreamErrorMessage(lifecycle.issue.error)}`,
|
| 214 |
+
upstreamErrorCode(lifecycle.issue.error) || "upstream_error",
|
| 215 |
+
);
|
| 216 |
+
return;
|
| 217 |
+
}
|
| 218 |
+
const warning = `\n\n${streamInterruptedWarningText(lifecycle.issue.error)}`;
|
| 219 |
+
log(
|
| 220 |
+
cfg,
|
| 221 |
+
`openai responses stream interrupted after partial output model=${rm.name} code=${upstreamErrorCode(lifecycle.issue.error) || "stream_interrupted"} error=${errorLogSummary(lifecycle.issue.error)}`,
|
| 222 |
+
);
|
| 223 |
+
await writeResponsesEvent(write, "response.warning", {
|
| 224 |
+
warning: streamWarningObject(lifecycle.issue.error, warning.trim()),
|
| 225 |
+
});
|
| 226 |
+
}
|
| 227 |
+
if (lifecycle.violation) {
|
| 228 |
+
log(
|
| 229 |
+
cfg,
|
| 230 |
+
`openai responses stream tool policy violation model=${rm.name} code=${lifecycle.violation.code}`,
|
| 231 |
+
);
|
| 232 |
+
await fail(lifecycle.violation.message, lifecycle.violation.code);
|
| 233 |
+
return;
|
| 234 |
+
}
|
| 235 |
+
} else {
|
| 236 |
+
for await (const event of streamPlainCompletionEvents(
|
| 237 |
+
provider,
|
| 238 |
+
{ prompt, rm, fileRefs },
|
| 239 |
+
{ signal, coalesceTextDeltas: !resinSmooth },
|
| 240 |
+
)) {
|
| 241 |
+
recordCompletionStreamEvent(lifecycle, event);
|
| 242 |
+
if (event.type === "text_delta") {
|
| 243 |
+
await emitText(event.text);
|
| 244 |
+
}
|
| 245 |
+
}
|
| 246 |
+
if (lifecycle.issue) {
|
| 247 |
+
if (!lifecycle.emittedText) {
|
| 248 |
+
log(
|
| 249 |
+
cfg,
|
| 250 |
+
`openai responses stream failed before output model=${rm.name} code=${upstreamErrorCode(lifecycle.issue.error) || "upstream_error"} error=${errorLogSummary(lifecycle.issue.error)}`,
|
| 251 |
+
);
|
| 252 |
+
await fail(
|
| 253 |
+
`upstream error: ${upstreamErrorMessage(lifecycle.issue.error)}`,
|
| 254 |
+
upstreamErrorCode(lifecycle.issue.error) || "upstream_error",
|
| 255 |
+
);
|
| 256 |
+
return;
|
| 257 |
+
}
|
| 258 |
+
const warning = `\n\n${streamInterruptedWarningText(lifecycle.issue.error)}`;
|
| 259 |
+
log(
|
| 260 |
+
cfg,
|
| 261 |
+
`openai responses stream interrupted after partial output model=${rm.name} code=${upstreamErrorCode(lifecycle.issue.error) || "stream_interrupted"} error=${errorLogSummary(lifecycle.issue.error)}`,
|
| 262 |
+
);
|
| 263 |
+
await writeResponsesEvent(write, "response.warning", {
|
| 264 |
+
warning: streamWarningObject(lifecycle.issue.error, warning.trim()),
|
| 265 |
+
});
|
| 266 |
+
}
|
| 267 |
+
}
|
| 268 |
+
if (!lifecycle.emittedText && !lifecycle.toolCalls) {
|
| 269 |
+
log(cfg, `openai responses stream produced no content model=${rm.name}`);
|
| 270 |
+
await fail(EMPTY_UPSTREAM_MSG, "upstream_empty");
|
| 271 |
+
return;
|
| 272 |
+
}
|
| 273 |
+
await finishMessage();
|
| 274 |
+
|
| 275 |
+
if (lifecycle.toolCalls?.length) {
|
| 276 |
+
for (const tc of lifecycle.toolCalls) {
|
| 277 |
+
const args = tc.function.arguments || "";
|
| 278 |
+
const id = tc.id || "";
|
| 279 |
+
const item: ResponseOutputItem = {
|
| 280 |
+
type: "function_call",
|
| 281 |
+
id,
|
| 282 |
+
call_id: id,
|
| 283 |
+
name: String(tc.function.name || ""),
|
| 284 |
+
arguments: "",
|
| 285 |
+
status: "in_progress",
|
| 286 |
+
};
|
| 287 |
+
output.push(item);
|
| 288 |
+
await writeResponsesEvent(write, "response.output_item.added", {
|
| 289 |
+
output_index: outputIndex,
|
| 290 |
+
item,
|
| 291 |
+
});
|
| 292 |
+
if (args)
|
| 293 |
+
await writeResponsesEvent(
|
| 294 |
+
write,
|
| 295 |
+
"response.function_call_arguments.delta",
|
| 296 |
+
{
|
| 297 |
+
item_id: item.id,
|
| 298 |
+
output_index: outputIndex,
|
| 299 |
+
call_id: item.call_id,
|
| 300 |
+
delta: args,
|
| 301 |
+
},
|
| 302 |
+
);
|
| 303 |
+
item.arguments = args;
|
| 304 |
+
item.status = "completed";
|
| 305 |
+
await writeResponsesEvent(
|
| 306 |
+
write,
|
| 307 |
+
"response.function_call_arguments.done",
|
| 308 |
+
{
|
| 309 |
+
item_id: item.id,
|
| 310 |
+
call_id: item.call_id,
|
| 311 |
+
name: item.name,
|
| 312 |
+
arguments: item.arguments,
|
| 313 |
+
},
|
| 314 |
+
);
|
| 315 |
+
await writeResponsesEvent(write, "response.output_item.done", {
|
| 316 |
+
output_index: outputIndex,
|
| 317 |
+
item,
|
| 318 |
+
});
|
| 319 |
+
outputIndex += 1;
|
| 320 |
+
}
|
| 321 |
+
}
|
| 322 |
+
|
| 323 |
+
const inputTokens = Math.max(0, Number(promptTokens) || 0);
|
| 324 |
+
const outputTokens = tokenCountFromCounts(lifecycle.completionCounts);
|
| 325 |
+
const usage = {
|
| 326 |
+
input_tokens: inputTokens,
|
| 327 |
+
output_tokens: outputTokens,
|
| 328 |
+
total_tokens: inputTokens + outputTokens,
|
| 329 |
+
};
|
| 330 |
+
await writeResponsesEvent(write, "response.completed", {
|
| 331 |
+
response: {
|
| 332 |
+
id: rid,
|
| 333 |
+
object: "response",
|
| 334 |
+
status: "completed",
|
| 335 |
+
model: rm.name,
|
| 336 |
+
output,
|
| 337 |
+
usage,
|
| 338 |
+
},
|
| 339 |
+
});
|
| 340 |
+
}
|