ZhipuAPIModel.js 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. const request = require("../../../../utils/request");
  2. const { generateToken } = require("../utils/zhiputoken");
  3. class ZhipuAI {
  4. constructor(apiKey) {
  5. if (!apiKey) {
  6. throw new Error("API Key is required");
  7. }
  8. this.apiKey = apiKey;
  9. this.cacheToken = true;
  10. this.baseUrl = "https://open.bigmodel.cn/api/paas/v4/chat/completions";
  11. }
  12. async createCompletion(params) {
  13. if (!params.model) {
  14. throw new Error("Model name is required");
  15. }
  16. if (!params.messages || !Array.isArray(params.messages)) {
  17. throw new Error("Messages array is required");
  18. }
  19. const token = await generateToken(this.apiKey, this.cacheToken);
  20. const headers = {
  21. baseUrl: this.baseUrl,
  22. Authorization: token,
  23. timeout: 10000,
  24. };
  25. try {
  26. const response = await request.post(this.baseUrl, JSON.stringify(params), { headers });
  27. return response.data;
  28. } catch (error) {
  29. console.error("Error calling ZhipuAI API:", error.response?.data || error.message);
  30. throw error;
  31. }
  32. }
  33. }
  34. module.exports = ZhipuAI;