import express from "express"; import bodyParser from "body-parser"; import dotenv from "dotenv"; import fetch from "node-fetch"; import fs from "fs"; import path from "path"; dotenv.config(); const app = express(); app.use(bodyParser.json()); // 创建图片保存目录 const imageDir = path.join(process.cwd(), "images"); if (!fs.existsSync(imageDir)) { fs.mkdirSync(imageDir); } // 静态文件服务 app.use("/images", express.static(imageDir)); app.get("/", (req, res) => { res.send(` OPENAI

OpenAI

Congratulations! Your project has been successfully deployed.

`); }); app.post("/deem/v1/chat/completions", async (req, res) => { try { const data = req.body; const messages = data.messages; const lastMessage = messages[messages.length - 1]; const messagesContent = lastMessage.content; const apiUrl = `https://api-flux1.api4gpt.com/?prompt=${messagesContent}`; const apiResponse = await fetch(apiUrl); if (!apiResponse.ok) { throw new Error("文生图服务失效:" + apiResponse.status); } const imageBuffer = await apiResponse.buffer(); // 生成唯一的文件名 const fileName = `image_${Date.now()}.jpg`; const filePath = path.join(imageDir, fileName); // 保存图片到本地 fs.writeFileSync(filePath, imageBuffer); // 构建本地图片URL const imgUrl = `/images/${fileName}`; console.log(imgUrl); if (imgUrl) { const chunkId = `chatcmpl-${Date.now()}`; const chunkCreated = Math.floor(Date.now() / 1000); res.write( "data: " + JSON.stringify({ id: chunkId, object: "chat.completion.chunk", created: chunkCreated, model: req.body.model, choices: [ { index: 0, delta: { content: `![](${imgUrl})`, }, finish_reason: null, }, ], }) + "\n\n" ); res.write("data: [DONE]\n\n"); res.end(); } else { res.status(500).json({ error: "图片保存失败" }); } } catch (error) { console.error("Error:", error); res.status(500).json({ error: error.message }); } }); app.post("/deem/v1/images/generations", async (req, res) => { try { const data = req.body; const messages = data.prompt; const apiUrl = `https://api-flux1.api4gpt.com/?prompt=${messages}`; const apiResponse = await fetch(apiUrl); if (!apiResponse.ok) { throw new Error("文生图服务失效:" + apiResponse.status); } const imageBuffer = await apiResponse.buffer(); // 生成唯一的文件名 const fileName = `image_${Date.now()}.jpg`; const filePath = path.join(imageDir, fileName); // 保存图片到本地 fs.writeFileSync(filePath, imageBuffer); // 构建本地图片URL const imgUrl = `/images/${fileName}`; console.log(imgUrl); if (imgUrl) { const chunkCreated = Math.floor(Date.now() / 1000); res.json({ created: chunkCreated, data: [ { url: imgUrl, }, ], }); } else { res.status(500).json({ error: "图片保存失败" }); } } catch (error) { console.error("Error:", error); res.status(500).json({ error: error.message }); } }); app.listen(process.env.PORT || 3000);