From 36b06f56a3e62d81e3d82c82801e8f07a7e91e8d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=BA=AF?= <893917884@qq.com> Date: Wed, 16 Jul 2025 10:13:48 +0800 Subject: [PATCH] Update worker.mjs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 简单来说用过url中的模型名来替换 请求体的模型,好处可以强制模型名 你的代码片段意图是: 用正则 /^\/([\w.-]+)\/v1\/(chat\/completions|embeddings)$/ 匹配 /模型名/v1/chat/completions 或 /模型名/v1/embeddings 这样的路径, 并从中提取模型名(如 gemini-1.5-pro), 如果不匹配则抛出 404。 这段代码的作用和你刚才的需求完全一致,并且更通用(支持 chat/completions 和 embeddings 两种 endpoint)。 --- src/worker.mjs | 36 +++++++++++++++++++++--------------- 1 file changed, 21 insertions(+), 15 deletions(-) diff --git a/src/worker.mjs b/src/worker.mjs index 719858d..98d34ad 100644 --- a/src/worker.mjs +++ b/src/worker.mjs @@ -18,21 +18,27 @@ export default { } }; const { pathname } = new URL(request.url); - switch (true) { - case pathname.endsWith("/chat/completions"): - assert(request.method === "POST"); - return handleCompletions(await request.json(), apiKey) - .catch(errHandler); - case pathname.endsWith("/embeddings"): - assert(request.method === "POST"); - return handleEmbeddings(await request.json(), apiKey) - .catch(errHandler); - case pathname.endsWith("/models"): - assert(request.method === "GET"); - return handleModels(apiKey) - .catch(errHandler); - default: - throw new HttpError("404 Not Found", 404); + const routeRegex = /^\/([\w.-]+)\/v1\/(chat\/completions|embeddings)$/; + const match = pathname.match(routeRegex); + + if (!match) { + throw new HttpError("404 Not Found. Use format: //v1/chat/completions", 404); + } + + const modelFromUrl = match[1]; + const endpoint = match[2]; + let body; + try { + body = await request.json(); + } catch (e) { + body = {}; + } + body.model = modelFromUrl; + + if (endpoint === "chat/completions") { + return handleCompletions(body, apiKey).catch(errHandler); + } else if (endpoint === "embeddings") { + return handleEmbeddings(body, apiKey).catch(errHandler); } } catch (err) { return errHandler(err);