Skip to content

Commit 96f394e

Browse files
committed
feat: catch fetch error
1 parent 9ee74f3 commit 96f394e

File tree

1 file changed

+55
-37
lines changed

1 file changed

+55
-37
lines changed

src/v1/chat/completions.ts

Lines changed: 55 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import { gen_ai_hub } from "src/genAI";
1010
import fetch from "src/utils/fetch";
1111
import {
1212
GenerateContentResponse,
13+
GenerateContentResult,
1314
GenerationConfig,
1415
GoogleGenerativeAIError,
1516
GoogleGenerativeAIFetchError,
@@ -438,6 +439,12 @@ class ChatCompletionsHandler {
438439
obj = error.errorDetails;
439440
message = error.message;
440441
name = error.name;
442+
if (!error.errorDetails || error.errorDetails.length === 0) {
443+
obj = {
444+
name,
445+
message,
446+
};
447+
}
441448
}
442449
if (!name) {
443450
// 其他 error
@@ -476,21 +483,21 @@ class ChatCompletionsHandler {
476483
// JSON.stringify({ ...payload, id: this.id }, null, 2)
477484
// );
478485
const abortSignal = new AbortController();
479-
const result = await payload.gen_model.generateContentStream(
480-
{
481-
systemInstruction: payload.systemInstruction,
482-
contents: payload.contents,
483-
generationConfig: payload.generationConfig,
484-
safetySettings: this.is_gemini_2
485-
? all_none_safety_settings.v2
486-
: all_none_safety_settings.v1,
487-
},
488-
{
489-
signal: abortSignal.signal,
490-
}
491-
);
492486

493487
try {
488+
const result = await payload.gen_model.generateContentStream(
489+
{
490+
systemInstruction: payload.systemInstruction,
491+
contents: payload.contents,
492+
generationConfig: payload.generationConfig,
493+
safetySettings: this.is_gemini_2
494+
? all_none_safety_settings.v2
495+
: all_none_safety_settings.v1,
496+
},
497+
{
498+
signal: abortSignal.signal,
499+
}
500+
);
494501
for await (const chunk of result.stream) {
495502
if (this.req.socket.closed) {
496503
abortSignal.abort();
@@ -520,6 +527,8 @@ class ChatCompletionsHandler {
520527
this.reply.raw.write("data: [DONE]\n\n");
521528
this.reply.raw.end();
522529
} catch (error) {
530+
this.ensureFirstChunk();
531+
523532
if (error instanceof DOMException && error.name === "AbortError") {
524533
console.error("Stream aborted:", error);
525534
this.reply.raw.write("data: [DONE]\n\n");
@@ -565,6 +574,32 @@ class ChatCompletionsHandler {
565574

566575
private async handleSingleResponse() {
567576
const payload = await this.buildGeneratePayload();
577+
const buildResponse = (
578+
content: string,
579+
result?: GenerateContentResult
580+
) => ({
581+
id: this.id,
582+
object: "chat.completion",
583+
created: Date.now(),
584+
model: this.body.model,
585+
choices: [
586+
{
587+
index: 0,
588+
message: {
589+
role: "assistant",
590+
content,
591+
},
592+
finish_reason:
593+
result?.response.candidates?.[0].finishReason ?? "stop",
594+
},
595+
],
596+
usage: {
597+
prompt_tokens: result?.response.usageMetadata?.promptTokenCount ?? 0,
598+
completion_tokens:
599+
result?.response.usageMetadata?.candidatesTokenCount ?? 0,
600+
total_tokens: result?.response.usageMetadata?.totalTokenCount ?? 0,
601+
},
602+
});
568603
try {
569604
const result = await payload.gen_model.generateContent({
570605
systemInstruction: payload.systemInstruction,
@@ -576,33 +611,16 @@ class ChatCompletionsHandler {
576611
});
577612

578613
const content = await result.response.text();
579-
const response = {
580-
id: this.id,
581-
object: "chat.completion",
582-
created: Date.now(),
583-
model: this.body.model,
584-
choices: [
585-
{
586-
index: 0,
587-
message: {
588-
role: "assistant",
589-
content,
590-
},
591-
finish_reason:
592-
result.response.candidates?.[0].finishReason ?? "stop",
593-
},
594-
],
595-
usage: {
596-
prompt_tokens: result.response.usageMetadata?.promptTokenCount ?? 0,
597-
completion_tokens:
598-
result.response.usageMetadata?.candidatesTokenCount ?? 0,
599-
total_tokens: result.response.usageMetadata?.totalTokenCount ?? 0,
600-
},
601-
};
602-
614+
const response = buildResponse(content);
603615
this.reply.send(response);
604616
} catch (error) {
605617
console.error("Single response error:", error);
618+
const message = this.buildGErrorResponse(error);
619+
if (message) {
620+
const response = buildResponse(message);
621+
this.reply.send(response);
622+
return;
623+
}
606624
throw error;
607625
}
608626
}

0 commit comments

Comments
 (0)