server.js 2.5 KB

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