File size: 6,160 Bytes
bc0be9c |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 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 |
import { ServerRequest } from "https://deno.land/std@0.224.0/http/server.ts";
interface OpenAIChoice {
index: number;
message?: {
role: string;
content: string;
};
delta?: {
content: string;
};
finish_reason: string | null;
}
interface OpenAIUsage {
prompt_tokens: number;
completion_tokens: number;
total_tokens: number;
}
interface OpenAIResponse {
id: string;
object: string;
created: number;
model: string;
choices: OpenAIChoice[];
usage?: OpenAIUsage;
}
export class ResponseBuilder {
private static log(
level: "info" | "warn" | "error",
message: string,
data?: any
) {
const timestamp = new Date().toISOString();
const logData = data ? ` | Data: ${JSON.stringify(data)}` : "";
console[level](`[${timestamp}] [ResponseBuilder] ${message}${logData}`);
}
// 构建非流式响应
static buildNonStreamResponse(
modelName: string,
fullContent: string,
finishReason: string = "stop"
): Response {
this.log("info", "Building non-stream response", {
modelName,
contentLength: fullContent.length,
});
const response = {
id: "Chat-Nekohy",
object: "chat.completion",
created: Math.floor(Date.now() / 1000),
model: modelName,
choices: [
{
index: 0,
message: { role: "assistant", content: fullContent },
finish_reason: finishReason,
},
],
};
return new Response(JSON.stringify(response), {
status: 200,
headers: { "Content-Type": "application/json" },
});
}
// 构建SSE数据块
static buildSSEChunk(
model: string,
content: string,
isFinish: boolean = false
): string {
const response = {
id: "chatcmpl-Nekohy",
object: "chat.completion.chunk",
created: Math.floor(Date.now() / 1000),
model,
choices: [
{
index: 0,
delta: isFinish ? {} : { content },
finish_reason: isFinish ? "stop" : null,
},
],
};
const chunk = `data: ${JSON.stringify(response)}\n\n`;
return isFinish ? chunk + "data: [DONE]\n\n" : chunk;
}
// 主要响应构建方法
static buildResponse(
readableStream: ReadableStream,
stream: boolean = false,
modelName: string = "default"
): Response {
this.log("info", "Building response", { stream, modelName });
const transformedStream = new ReadableStream({
start: async (controller) => {
const reader = readableStream.getReader();
const decoder = new TextDecoder();
let fullContent = "";
let chunkCount = 0;
try {
while (true) {
const { done, value } = await reader.read();
if (done) break;
const chunk = decoder.decode(value, { stream: true });
const content = this.extractContent(chunk);
if (content) {
chunkCount++;
fullContent += content;
if (stream) {
const sseChunk = this.buildSSEChunk(modelName, content);
controller.enqueue(new TextEncoder().encode(sseChunk));
}
}
}
this.log("info", "Stream processing completed", {
chunkCount,
totalLength: fullContent.length,
stream,
});
if (stream) {
// 发送结束标记
const finishChunk = this.buildSSEChunk(modelName, "", true);
controller.enqueue(new TextEncoder().encode(finishChunk));
} else {
// 发送完整响应
const response = this.buildNonStreamResponse(
modelName,
fullContent
);
const responseText = await response.text();
controller.enqueue(new TextEncoder().encode(responseText));
}
controller.close();
} catch (error) {
this.log("error", "Stream processing failed", {
error: error.message,
});
controller.error(error);
} finally {
reader.releaseLock();
}
},
});
const headers = stream
? {
"Content-Type": "text/event-stream",
Connection: "keep-alive",
"Cache-Control": "no-cache",
}
: { "Content-Type": "application/json" };
return new Response(transformedStream, { status: 200, headers });
}
// 提取SSE数据中的内容
private static extractContent(chunk: string): string {
let content = "";
const lines = chunk.split("\n");
for (const line of lines) {
const trimmedLine = line.trim();
if (trimmedLine.startsWith("data: ") && !trimmedLine.includes("[DONE]")) {
try {
const jsonStr = trimmedLine.slice(6).trim();
if (jsonStr) {
const data = JSON.parse(jsonStr);
if (data.message && typeof data.message === "string") {
content += data.message;
}
}
} catch (e) {
this.log("warn", "Failed to parse SSE data", {
line: trimmedLine,
error: e.message,
});
}
}
}
return content;
}
// 通用JSON响应
static jsonResponse(data: unknown, status = 200): Response {
this.log("info", "Creating JSON response", { status });
return new Response(JSON.stringify(data), {
status,
headers: { "Content-Type": "application/json" },
});
}
}
export function streamResponse(body: ReadableStream): Response {
return new Response(body, {
status: 200,
headers: {
"Content-Type": "text/event-stream",
Connection: "keep-alive",
"Cache-Control": "no-cache",
},
});
}
export function unauthorizedResponse(message: string, status = 401): Response {
return new Response(JSON.stringify({ error: message }), {
status,
headers: {
"Content-Type": "application/json",
"WWW-Authenticate": "Bearer",
},
});
}
export function errorResponse(message: string, status = 500): Response {
return ResponseBuilder.jsonResponse({ error: message }, status);
}
|