Spaces:
Sleeping
Sleeping
docker deploy
Browse filesFiles changed (2)
- DockerfileAdded+35
- main.tsAdded+844
1234567891011121314151617181920212223242526272829303132333435# Venice API 代理服务器 - Dockerfile for Hugging Face SpacesFROM denoland/deno:alpine
# 设置环境变量ENV DENO_DIR=/deno-dirENV IMAGE_DIR=/tmp/public/images
WORKDIR /app
# 创建必要的目录并设置权限RUN mkdir -p /tmp/public/images && \ mkdir -p $DENO_DIR && \ chown -R deno:deno /app && \ chown -R deno:deno $DENO_DIR && \ chown -R deno:deno /tmp/public && \ chmod -R 755 /tmp/public
# 复制文件COPY --chown=deno:deno . .
# 缓存依赖RUN deno cache main.ts
# 切换到非root用户USER deno
# Hugging Face Spaces 默认端口EXPOSE 7860
# 健康检查HEALTHCHECK --interval=30s --timeout=10s --start-period=40s --retries=3 \ CMD deno eval "fetch('http://localhost:7860/v1/models').then(r => r.ok ? Deno.exit(0) : Deno.exit(1))" || exit 1
# 启动命令,包含所有必要权限CMD ["run", "--allow-net", "--allow-env", "--allow-read", "--allow-write", "main.ts"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844// deno run --allow-net --allow-read --allow-write server.ts
import { serve } from "https://deno.land/std@0.203.0/http/server.ts";
// =============================================================================// 配置区 (请根据你的需求修改)// =============================================================================
// --- 服务器配置 ---const API_KEY = Deno.env.get("API_KEY") || "your-api-key-here"; // 设置你的API密钥const SERVER_HOST = Deno.env.get("SERVER_HOST") || "0.0.0.0"; // 服务器地址(Deno Deploy使用0.0.0.0)const SERVER_PORT = parseInt(Deno.env.get("SERVER_PORT") || "7860"); // 服务器监听端口(统一使用7860)
// --- 图片链接配置 ---const CUSTOM_IMAGE_BASE_URL = Deno.env.get("CUSTOM_IMAGE_BASE_URL") || ""; // 自定义图片基础URL,留空则使用自动检测const INCLUDE_PORT_IN_URL = Deno.env.get("INCLUDE_PORT_IN_URL") === "true" || false; // 是否在URL中包含端口号(Deno Deploy通常不需要)const CUSTOM_PORT = parseInt(Deno.env.get("CUSTOM_PORT") || "7860"); // 自定义端口号(当INCLUDE_PORT_IN_URL为true时使用)
// --- 图片服务配置 ---const IMAGE_DIR = Deno.env.get("IMAGE_DIR") || "/tmp/public/images"; // 图片存储目录(使用/tmp目录)const IMAGE_EXPIRE_HOURS = parseInt(Deno.env.get("IMAGE_EXPIRE_HOURS") || "1"); // 图片在本地保存的小时数const ENABLE_IMAGE_STORAGE = Deno.env.get("ENABLE_IMAGE_STORAGE") === "true"; // 是否启用图片存储(Deno Deploy设为false)const RETURN_BASE64_IMAGES = Deno.env.get("RETURN_BASE64_IMAGES") !== "false"; // 是否返回base64格式的图片(默认true)
// --- Venice API 配置 ---const VENICE_CHAT_URL = "https://outerface.venice.ai/api/inference/chat";const VENICE_IMAGE_URL = "https://outerface.venice.ai/api/inference/image";const VENICE_VERSION = "interface@20251007.055834+464da4e";
// --- Cloudflare 优选 IP 配置 ---const CF_IP_API_URL = Deno.env.get("CF_IP_API_URL") || "https://ipdb.api.030101.xyz/?type=cfv4;proxy";const CF_HTTPS_PORTS = [443, 2053, 2083, 2087, 2096, 8443];const CF_HTTP_PORTS = [80, 8080, 8880, 2052, 2082, 2086, 2095];const MAX_REQUESTS_PER_IP = parseInt(Deno.env.get("MAX_REQUESTS_PER_IP") || "5"); // 每个 IP 最多使用次数const ENABLE_DIRECT_IP = Deno.env.get("ENABLE_DIRECT_IP") === "true"; // 是否启用直连IP(Hugging Face Spaces 不支持)
// --- 模型配置 ---const IMAGE_MODELS = ["stable-diffusion-3.5-rev2", "qwen-image", "hidream"]; // 画图模型列表
// =============================================================================// 核心逻辑区 (通常无需修改)// =============================================================================
// --- 全局状态 ---let cfIps: string[] = [];let currentIpIndex = 0;let requestCount = 0;
// --- 内存存储(用于Deno Deploy) ---const imageStore = new Map<string, Uint8Array>();
// --- 随机 User-Agent ---const USER_AGENTS = [ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.1 Safari/605.1.15", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/121.0", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:109.0) Gecko/20100101 Firefox/121.0", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Edge/120.0.0.0", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36",];
// --- 工具函数 ---
function getRandomUserAgent(): string { return USER_AGENTS[Math.floor(Math.random() * USER_AGENTS.length)];}
function validateApiKey(req: Request): boolean { const authHeader = req.headers.get("Authorization"); if (!authHeader) return false; const match = authHeader.match(/^Bearer\s+(.+)$/); if (!match) return false; return match[1] === API_KEY;}
// CORS处理函数function addCorsHeaders(response: Response): Response { response.headers.set("Access-Control-Allow-Origin", "*"); response.headers.set("Access-Control-Allow-Methods", "GET, POST, OPTIONS"); response.headers.set("Access-Control-Allow-Headers", "Content-Type, Authorization"); return response;}
// 生成图片URL的函数function generateImageUrl(filename: string, req?: Request): string { // 如果设置了自定义基础URL,使用它 if (CUSTOM_IMAGE_BASE_URL.trim()) { let baseUrl = CUSTOM_IMAGE_BASE_URL.trim(); // 确保URL不以/结尾 if (baseUrl.endsWith('/')) { baseUrl = baseUrl.slice(0, -1); } // 添加端口(如果需要) if (INCLUDE_PORT_IN_URL && CUSTOM_PORT) { // 检查是否已经有端口 const hasPort = baseUrl.match(/:(\d+)$/); if (!hasPort) { baseUrl += `:${CUSTOM_PORT}`; } } return `${baseUrl}/images/${filename}`; } // 否则使用自动检测的方式 const protocol = "https"; // Deno Deploy通常使用HTTPS let host = "your-domain.deno.dev"; // 默认域名 // 尝试从请求头获取Host if (req) { const reqHost = req.headers.get("host"); if (reqHost) { host = reqHost; } } // 构建URL let url = `${protocol}://${host}`; // 添加端口(如果需要) if (INCLUDE_PORT_IN_URL && CUSTOM_PORT) { // 跳过默认端口 if ((protocol === 'http' && CUSTOM_PORT !== 80) || (protocol === 'https' && CUSTOM_PORT !== 443)) { url += `:${CUSTOM_PORT}`; } } return `${url}/images/${filename}`;}
// 将图片数据转换为base64格式function arrayBufferToBase64(buffer: ArrayBuffer): string { let binary = ''; const bytes = new Uint8Array(buffer); const len = bytes.byteLength; for (let i = 0; i < len; i++) { binary += String.fromCharCode(bytes[i]); } return btoa(binary);}
// --- IP 轮换管理 ---
async function fetchAndUpdateCfIps() { try { console.log("正在从API获取最新的Cloudflare优选IP列表..."); const response = await fetch(CF_IP_API_URL, { headers: { "User-Agent": getRandomUserAgent(), "Accept": "text/plain", } }); if (!response.ok) throw new Error(`API请求失败: ${response.status} ${response.statusText}`); const text = await response.text(); cfIps = text.split('\n').filter(ip => ip.trim() !== ''); console.log(`成功获取 ${cfIps.length} 个优选IP。`); if (cfIps.length === 0) { console.error("警告:获取到的IP列表为空,请检查API或网络连接。"); } } catch (error) { console.error("获取优选IP列表时出错:", error); // 如果获取失败,保留旧列表,避免服务中断 }}
function getNextEndpoint(url: string): { ip: string; port: number } | null { if (cfIps.length === 0) { console.error("优选IP列表为空,无法创建连接。"); return null; } // 根据目标URL的协议选择端口 const isHttps = url.startsWith("https://"); const ports = isHttps ? CF_HTTPS_PORTS : CF_HTTP_PORTS; if (requestCount >= MAX_REQUESTS_PER_IP) { currentIpIndex = (currentIpIndex + 1) % cfIps.length; requestCount = 0; console.log(`[更换IP] 切换到新IP: ${cfIps[currentIpIndex]}`); } requestCount++; const ip = cfIps[currentIpIndex]; const port = ports[Math.floor(Math.random() * ports.length)]; console.log(`[使用IP] ${ip}:${port} (请求计数: ${requestCount}/${MAX_REQUESTS_PER_IP})`); return { ip, port };}
// 适配Deno Deploy的fetch函数async function fetchWithDirectIp(url: string, options: RequestInit = {}): Promise<Response> { // 确保有基本的请求头 const defaultHeaders = { "User-Agent": getRandomUserAgent(), "Accept": "application/json, text/plain, */*", "Accept-Language": "en-US,en;q=0.9", "Accept-Encoding": "gzip, deflate, br", "Connection": "keep-alive", "Sec-Fetch-Dest": "empty", "Sec-Fetch-Mode": "cors", "Sec-Fetch-Site": "cross-site", ...options.headers, }; // 如果禁用直连IP,直接使用标准fetch if (!ENABLE_DIRECT_IP) { console.log(`使用标准fetch请求: ${url}`); try { const response = await fetch(url, { ...options, headers: defaultHeaders, }); return response; } catch (error) { console.error("标准fetch失败:", error); throw error; } } // 尝试使用直连IP(如果可用) try { const endpoint = getNextEndpoint(url); if (!endpoint) throw new Error("无法获取可用的Cloudflare IP端点。"); const { ip, port } = endpoint; console.log(`使用优选IP: ${ip}:${port} 请求: ${url}`); // 检查Deno.createHttpClient是否可用 if (typeof Deno.createHttpClient === 'function') { const client = Deno.createHttpClient({ connect: { hostname: ip, port: port } }); try { const response = await fetch(url, { ...options, client, headers: defaultHeaders, }); return response; } finally { client.close(); } } else { // 如果Deno.createHttpClient不可用,回退到标准fetch console.log("Deno.createHttpClient不可用,使用标准fetch"); return await fetch(url, { ...options, headers: defaultHeaders, }); } } catch (error) { console.error("使用直连IP失败,回���到标准fetch:", error); return await fetch(url, { ...options, headers: defaultHeaders, }); }}
// --- 图片管理 ---
async function ensureImageDir() { if (!ENABLE_IMAGE_STORAGE) { console.log("图片存储已禁用,使用内存存储"); return; } try { await Deno.mkdir(IMAGE_DIR, { recursive: true }); console.log(`图片目录已准备就绪: ${IMAGE_DIR}`); } catch (error) { console.error(`创建图片目录失败: ${error}`); console.log("将使用内存存储替代文件存储"); }}
async function cleanOldImages() { if (!ENABLE_IMAGE_STORAGE) { // 内存存储不需要清理 return; } try { console.log("[清理任务] 开始清理旧图片..."); const expireTime = Date.now() - IMAGE_EXPIRE_HOURS * 60 * 60 * 1000; let deletedCount = 0; for await (const entry of Deno.readDir(IMAGE_DIR)) { if (entry.isFile) { const filePath = `${IMAGE_DIR}/${entry.name}`; const fileInfo = await Deno.stat(filePath); if (fileInfo.mtime?.getTime() && fileInfo.mtime.getTime() < expireTime) { await Deno.remove(filePath); deletedCount++; } } } console.log(`[清理任务] 完成,删除了 ${deletedCount} 个旧图片文件。`); } catch (error) { console.error("[清理任务] 清理失败:", error); }}
// --- API 响应格式 ---
function openaiModels() { return { object: "list", data: [ { id: "dolphin-3.0-mistral-24b-1dot1", object: "model", created: 1690000000, owned_by: "venice.ai" }, { id: "mistral-31-24b", object: "model", created: 1690000001, owned_by: "venice.ai" }, { id: "stable-diffusion-3.5-rev2", object: "model", created: 1690000002, owned_by: "venice.ai" }, { id: "qwen-image", object: "model", created: 1690000003, owned_by: "venice.ai" }, { id: "hidream", object: "model", created: 1690000004, owned_by: "venice.ai" }, ], };}
// --- 请求处理函数 ---
async function handleImageGeneration(model: string, prompt: string, size: string, negativePrompt: string, req: Request): Promise<Response> { try { const [width, height] = size.split('x').map(Number); const venicePayload = { aspectRatio: `${width}:${height}`, embedExifMetadata: true, format: "webp", height, hideWatermark: false, imageToImageCfgScale: 15, imageToImageStrength: 33, loraStrength: 75, matureFilter: true, messageId: crypto.randomUUID().slice(0, 8), modelId: model, negativePrompt, parentMessageId: null, prompt, requestId: crypto.randomUUID().slice(0, 8), seed: Math.floor(Math.random() * 2**31), steps: model === "hidream" || model === "qwen-image" ? 20 : 25, stylePreset: "None", type: "image", userId: "user_anon_1234568910", variants: 1, width, }; const headers = { "Content-Type": "application/json", "Origin": "https://venice.ai", "Referer": "https://venice.ai/", "User-Agent": getRandomUserAgent(), "Accept": "application/json, image/*", "Accept-Language": "en-US,en;q=0.9", "Cache-Control": "no-cache", "Pragma": "no-cache", "x-venice-timestamp": new Date().toISOString(), "x-venice-version": VENICE_VERSION }; console.log(`[图片生成] 请求Venice API: ${VENICE_IMAGE_URL}`); console.log(`[图片生成] Payload:`, JSON.stringify(venicePayload, null, 2)); const veniceResp = await fetchWithDirectIp(VENICE_IMAGE_URL, { method: "POST", headers, body: JSON.stringify(venicePayload) }); console.log(`[图片生成] Venice API响应状态: ${veniceResp.status} ${veniceResp.statusText}`); if (!veniceResp.ok) { const errorText = await veniceResp.text(); console.error(`[错误] Venice API返回错误 (${veniceResp.status}): ${errorText}`); // 返回Markdown格式的错误信息 const errorMarkdown = `# 图片生成失败
**错误信息:**- 状态码:${veniceResp.status}- 详情:${errorText}
请检查请求参数后重试。`; return addCorsHeaders(new Response(errorMarkdown, { status: veniceResp.status, headers: { "Content-Type": "text/markdown; charset=utf-8" } })); } const imageBuffer = await veniceResp.arrayBuffer(); if (imageBuffer.byteLength === 0) { const errorMarkdown = `# 图片生成失败
**错误信息:**- 原因:接收到空的图片数据
请稍后重试。`; return addCorsHeaders(new Response(errorMarkdown, { status: 500, headers: { "Content-Type": "text/markdown; charset=utf-8" } })); }
const filename = `${crypto.randomUUID()}.webp`; const imageData = new Uint8Array(imageBuffer); // 存储图片数据 if (ENABLE_IMAGE_STORAGE) { try { const filePath = `${IMAGE_DIR}/${filename}`; await Deno.writeFile(filePath, imageData); console.log(`[成���] 图片已保存: ${filename}`); } catch (error) { console.error(`保存图片失败: ${error},使用内存存储`); imageStore.set(filename, imageData); } } else { // 使用内存存储 imageStore.set(filename, imageData); console.log(`[成功] 图片已保存到内存: ${filename}`); }
// 根据配置决定返回URL还是base64 if (RETURN_BASE64_IMAGES) { // 将图片转换为base64格式 const base64Image = arrayBufferToBase64(imageBuffer); const dataUrl = `data:image/webp;base64,${base64Image}`; // 返回包含base64图片的Markdown格式响应 const readmeResponse = `
## 图片信息
- **模型**:${model}- **提示词**:${prompt}- **尺寸**:${size}- **负面提示词**:${negativePrompt || '无'}
## 图片数据
Base64编码的图片数据已包含在上方图片中。`;
// 返回Markdown内容,设置Content-Type为text/markdown return addCorsHeaders(new Response(readmeResponse, { headers: { "Content-Type": "text/markdown; charset=utf-8" } })); } else { // 使用原有的URL方式 const imageUrl = generateImageUrl(filename, req); // 直接返回Markdown格式的响应 const readmeResponse = `
## 图片信息
- **模型**:${model}- **提示词**:${prompt}- **尺寸**:${size}- **负面提示词**:${negativePrompt || '无'}
## 图片链接
${imageUrl}`;
// 直接返回Markdown内容,设置Content-Type为text/markdown return addCorsHeaders(new Response(readmeResponse, { headers: { "Content-Type": "text/markdown; charset=utf-8" } })); } } catch (error) { console.error("Image generation request failed:", error); const errorMarkdown = `# 图片生成失败
**错误信息:**- 原因:${error.message || '未知错误'}
请稍后重试。`; return addCorsHeaders(new Response(errorMarkdown, { status: 500, headers: { "Content-Type": "text/markdown; charset=utf-8" } })); }}
async function handleChatCompletion(model: string, messages: any[], temperature: number, topP: number, stream: boolean): Promise<Response> { try { const venicePayload = { characterId: "", clientProcessingTime: 2, conversationType: "text", includeVeniceSystemPrompt: true, isCharacter: false, modelId: model, prompt: messages, reasoning: true, requestId: crypto.randomUUID().slice(0, 8), systemPrompt: "", temperature, topP, userId: "user_anon_proxy", webEnabled: true }; const headers = { "Content-Type": "application/json", "Origin": "https://venice.ai", "Referer": "https://venice.ai/", "User-Agent": getRandomUserAgent(), "Accept": "text/event-stream, application/json, text/plain", "Accept-Language": "en-US,en;q=0.9", "Cache-Control": "no-cache", "Connection": "keep-alive", }; console.log(`[聊天] 请求Venice API: ${VENICE_CHAT_URL}`); console.log(`[聊天] Payload:`, JSON.stringify(venicePayload, null, 2)); const veniceResp = await fetchWithDirectIp(VENICE_CHAT_URL, { method: "POST", headers, body: JSON.stringify(venicePayload) }); console.log(`[聊天] Venice API响应状态: ${veniceResp.status} ${veniceResp.statusText}`); if (!veniceResp.ok) { const errorText = await veniceResp.text(); console.error(`[错误] Venice API返回错误:`, errorText); return addCorsHeaders(new Response(JSON.stringify({ error: { message: `Venice API error: ${veniceResp.status}`, details: errorText, type: "venice_api_error" } }), { status: veniceResp.status, headers: { "Content-Type": "application/json" } })); }
if (stream) { const reader = veniceResp.body?.getReader(); const encoder = new TextEncoder(); const decoder = new TextDecoder(); let buffer = ""; let isFinished = false; const streamResp = new ReadableStream({ async start(controller) { // 设置超时处理 const timeoutId = setTimeout(() => { if (!isFinished) { console.error("Stream timeout, closing connection"); controller.close(); } }, 60000); // 60秒超时 try { while (!isFinished) { if (!reader) { controller.enqueue(encoder.encode("data: [DONE]\n\n")); controller.close(); isFinished = true; break; } const { done, value } = await reader.read(); if (done) { controller.enqueue(encoder.encode("data: [DONE]\n\n")); controller.close(); isFinished = true; break; } const chunk = decoder.decode(value, { stream: true }); buffer += chunk; let idx; while ((idx = buffer.indexOf("\n")) >= 0) { const line = buffer.slice(0, idx).trim(); buffer = buffer.slice(idx + 1); if (!line) continue; try { const data = JSON.parse(line); const content = data.content; if (content) { const chunk = { id: `chatcmpl-${crypto.randomUUID().slice(0, 8)}`, object: "chat.completion.chunk", created: Math.floor(Date.now() / 1000), model, choices: [{ delta: { content }, index: 0, finish_reason: null, }], }; controller.enqueue(encoder.encode(`data: ${JSON.stringify(chunk)}\n\n`)); } } catch (parseError) { console.error("JSON parse error:", parseError, "Line:", line); // 继续处理下一行,不中断流 } } } } catch (error) { console.error("Stream processing error:", error); // 发送错误信息并关闭流 const errorChunk = { id: `chatcmpl-${crypto.randomUUID().slice(0, 8)}`, object: "chat.completion.chunk", created: Math.floor(Date.now() / 1000), model, choices: [ { delta: { content: "\n\n[Stream interrupted due to error]" }, index: 0, finish_reason: "error", }, ], }; controller.enqueue( encoder.encode(`data: ${JSON.stringify(errorChunk)}\n\n`), ); controller.enqueue(encoder.encode("data: [DONE]\n\n")); controller.close(); } finally { clearTimeout(timeoutId); isFinished = true; } } }); const response = new Response(streamResp, { headers: { "Content-Type": "text/event-stream", "Cache-Control": "no-cache", "Connection": "keep-alive", "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Headers": "Content-Type, Authorization", }, }); return response; } else { const text = await veniceResp.text(); console.log(`[聊天] Venice API响应内容:`, text); const contents = text.split("\n").filter((l) => l.trim()).map((l) => JSON.parse(l).content).join(""); const resp = { id: `chatcmpl-${crypto.randomUUID().slice(0, 8)}`, object: "chat.completion", created: Math.floor(Date.now() / 1000), model, choices: [{ index: 0, message: { role: "assistant", content: contents }, finish_reason: "stop", }], }; return addCorsHeaders(new Response(JSON.stringify(resp), { headers: { "Content-Type": "application/json" }, })); } } catch (error) { console.error("Chat completion request failed:", error); return addCorsHeaders(new Response(JSON.stringify({ error: { message: "Failed to process chat completion", type: "request_error", details: error.message } }), { status: 500, headers: { "Content-Type": "application/json" } })); }}
// --- 服务器启动 ---
async function initializeServer() { await ensureImageDir(); await fetchAndUpdateCfIps(); if (cfIps.length === 0) console.error("无法获取任何优选IP,服务将启动但可能无法正常工作。"); // 定时任务(仅在非Deno Deploy环境中启用) if (ENABLE_IMAGE_STORAGE) { setInterval(fetchAndUpdateCfIps, 5 * 60 * 1000); // 每5分钟更新IP setInterval(cleanOldImages, IMAGE_EXPIRE_HOURS * 60 * 60 * 1000); // 定期清理图片 }
console.log(`服务器已启动,监听端口 ${SERVER_PORT}...`); // 显示图片URL配置信息 if (CUSTOM_IMAGE_BASE_URL.trim()) { console.log(`使用自定义图片基础URL: ${CUSTOM_IMAGE_BASE_URL}`); if (INCLUDE_PORT_IN_URL && CUSTOM_PORT) { console.log(`端口配置: 包含端口 ${CUSTOM_PORT}`); } else { console.log(`端口配置: 不包含端口`); } } else { console.log(`图片将通过自动检测的URL访问`); console.log(`当前配置: ${SERVER_HOST}:${SERVER_PORT}`); } console.log(`直连IP功能: ${ENABLE_DIRECT_IP ? '启用' : '禁用'}`); console.log(`图片存储: ${ENABLE_IMAGE_STORAGE ? '文件存储' : '内存存储'}`); console.log(`图片返回格式: ${RETURN_BASE64_IMAGES ? 'Base64' : 'URL'}`); serve(async (req: Request) => { const url = new URL(req.url); // 处理OPTIONS请求(CORS预检) if (req.method === "OPTIONS") { return addCorsHeaders(new Response(null, { status: 200 })); } // --- 静态图片服务 --- if (url.pathname.startsWith("/images/")) { const filename = url.pathname.substring("/images/".length); // 首先尝试从内存存储获取 if (imageStore.has(filename)) { const imageData = imageStore.get(filename); // 如果请求的是base64格式 if (url.searchParams.get('format') === 'base64') { const base64Image = arrayBufferToBase64(imageData.buffer); const dataUrl = `data:image/webp;base64,${base64Image}`; return addCorsHeaders(new Response(JSON.stringify({ dataUrl, filename }), { headers: { "Content-Type": "application/json", "Cache-Control": `public, max-age=${IMAGE_EXPIRE_HOURS * 3600}` } })); } return addCorsHeaders(new Response(imageData, { headers: { "Content-Type": "image/webp", "Cache-Control": `public, max-age=${IMAGE_EXPIRE_HOURS * 3600}` } })); } // 如果内存中没有,尝试从文件系统获取 if (ENABLE_IMAGE_STORAGE) { try { const filePath = `${IMAGE_DIR}/${filename}`; const imageFile = await Deno.readFile(filePath); // 如果请求的是base64格式 if (url.searchParams.get('format') === 'base64') { const base64Image = arrayBufferToBase64(imageFile.buffer); const dataUrl = `data:image/webp;base64,${base64Image}`; return addCorsHeaders(new Response(JSON.stringify({ dataUrl, filename }), { headers: { "Content-Type": "application/json", "Cache-Control": `public, max-age=${IMAGE_EXPIRE_HOURS * 3600}` } })); } return addCorsHeaders(new Response(imageFile, { headers: { "Content-Type": "image/webp", "Cache-Control": `public, max-age=${IMAGE_EXPIRE_HOURS * 3600}` } })); } catch (error) { console.error(`读取图片文件失败: ${error}`); } } return addCorsHeaders(new Response("Image Not Found", { status: 404 })); }
// --- API 密钥验证 --- if (url.pathname === "/v1/models" || url.pathname === "/v1/chat/completions") { if (!validateApiKey(req)) { return addCorsHeaders(new Response(JSON.stringify({ error: { message: "Invalid API key", type: "invalid_request_error", code: "invalid_api_key" } }), { status: 401, headers: { "Content-Type": "application/json" } })); } }
// --- 路由分发 --- if (url.pathname === "/v1/models") { return addCorsHeaders(new Response(JSON.stringify(openaiModels()), { headers: { "Content-Type": "application/json" } })); }
if (url.pathname === "/v1/chat/completions" && req.method === "POST") { try { const body = await req.json(); const model = body.model ?? "dolphin-3.0-mistral-24b-1dot1"; const messages = body.messages ?? []; const temperature = body.temperature ?? 0.7; const topP = body.top_p ?? 0.9; const stream = body.stream ?? false; if (IMAGE_MODELS.includes(model)) { console.log(`[请求类型] 画图 - 模型: ${model}`); const lastUserMessage = messages.filter(m => m.role === 'user').pop(); const prompt = lastUserMessage?.content; if (!prompt || typeof prompt !== 'string') { const errorMarkdown = `# 请求错误
**错误信息:**- 原因:图片生成需要文本提示词- 要求:请在最后一条用户消息中提供提示词
示例:\`\`\`json{ "model": "stable-diffusion-3.5-rev2", "messages": [ {"role": "user", "content": "a beautiful sunset"} ]}\`\`\``; return addCorsHeaders(new Response(errorMarkdown, { status: 400, headers: { "Content-Type": "text/markdown; charset=utf-8" } })); } const size = body.size ?? "1024x1024"; const negativePrompt = body.negative_prompt ?? ""; // 图片生成不支持流式,总是返回完整响应 return await handleImageGeneration(model, prompt, size, negativePrompt, req); } else { console.log(`[请求类型] 聊天 - 模型: ${model}`); return await handleChatCompletion(model, messages, temperature, topP, stream); } } catch (error) { console.error("Request processing error:", error); const errorMarkdown = `# 请求处理失败
**错误信息:**- 原因:${error.message || '未知错误'}
请检查请求格式后重试。`; return addCorsHeaders(new Response(errorMarkdown, { status: 500, headers: { "Content-Type": "text/markdown; charset=utf-8" } })); } }
return addCorsHeaders(new Response("Not Found", { status: 404 })); }, { port: SERVER_PORT });}
// 启动initializeServer();DockerfileAdded+35
main.tsAdded+844