server.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. const express = require("express");
  2. const OpenAI = require("openai");
  3. const cors = require("cors");
  4. const app = express();
  5. const PORT = process.env.PORT || 3000;
  6. // 中间件
  7. app.use(cors());
  8. app.use(express.json());
  9. // POST 路由处理OpenAI请求
  10. app.post("/api/openai", async (req, res) => {
  11. try {
  12. const { open_ai_url, api_key, payload } = req.body;
  13. console.debug("request", open_ai_url);
  14. // 验证必需的参数
  15. if (!open_ai_url || !api_key || !payload) {
  16. return res.status(400).json({
  17. error: "Missing required parameters: open_ai_url, api_key, or payload",
  18. });
  19. }
  20. // 初始化OpenAI客户端
  21. const openai = new OpenAI({
  22. apiKey: api_key,
  23. baseURL: open_ai_url,
  24. });
  25. // 检查是否需要流式响应
  26. const isStreaming = payload.stream === true;
  27. if (isStreaming) {
  28. // 流式响应
  29. res.setHeader("Content-Type", "text/event-stream");
  30. res.setHeader("Cache-Control", "no-cache");
  31. res.setHeader("Connection", "keep-alive");
  32. res.setHeader("Access-Control-Allow-Origin", "*");
  33. try {
  34. const stream = await openai.chat.completions.create({
  35. ...payload,
  36. stream: true,
  37. });
  38. console.info("waiting response");
  39. for await (const chunk of stream) {
  40. const data = JSON.stringify(chunk);
  41. res.write(`data: ${data}\n\n`);
  42. }
  43. res.write("data: [DONE]\n\n");
  44. res.end();
  45. } catch (streamError) {
  46. console.error("Streaming error:", streamError);
  47. res.write(
  48. `data: ${JSON.stringify({ error: streamError.message })}\n\n`
  49. );
  50. res.end();
  51. }
  52. } else {
  53. // 非流式响应
  54. const completion = await openai.chat.completions.create(payload);
  55. res.json(completion);
  56. }
  57. } catch (error) {
  58. console.error("API Error:", error);
  59. // 处理不同类型的错误
  60. if (error.status) {
  61. return res.status(error.status).json({
  62. error: error.message,
  63. type: error.type || "api_error",
  64. });
  65. }
  66. res.status(500).json({
  67. error: "Internal server error",
  68. message: error.message,
  69. });
  70. }
  71. });
  72. // 健康检查端点
  73. app.get("/health", (req, res) => {
  74. res.json({ status: "OK", timestamp: new Date().toISOString() });
  75. });
  76. // 启动服务器
  77. app.listen(PORT, () => {
  78. console.log(`Server is running on port ${PORT}`);
  79. console.log(`Health check: http://localhost:${PORT}/health`);
  80. console.log(`API endpoint: http://localhost:${PORT}/api/openai`);
  81. });
  82. module.exports = app;