Kimi.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import axios from 'axios';
  2. // https://platform.moonshot.cn/console/api-keys
  3. // https://platform.moonshot.cn/console/limits
  4. class Kimi {
  5. constructor({apiKey, baseURL}) {
  6. if (!apiKey) {
  7. throw new Error('Missing required configuration parameters.');
  8. }
  9. this.apiKey = apiKey;
  10. this.baseURL = baseURL || 'https://api.moonshot.cn/v1';
  11. this.userContexts = {}; // 存储每个用户的上下文
  12. }
  13. // 初始化用户上下文
  14. initUserContext(userId) {
  15. if (!this.userContexts[userId]) {
  16. this.userContexts[userId] = [
  17. {role: "system", content: "你是一名优秀的AI助手,知道最新的互联网内容,善用搜索引擎和github并总结最贴切的结论来回答我提出的每一个问题"}
  18. ];
  19. }
  20. }
  21. // 更新用户上下文
  22. updateUserContext(userId, message) {
  23. this.userContexts[userId].push(message);
  24. // 控制上下文长度,保留最新的20条消息
  25. if (this.userContexts[userId].length > 20) {
  26. this.userContexts[userId] = this.userContexts[userId].slice(-20);
  27. }
  28. }
  29. async ask(userId, prompt, options = {}) {
  30. this.initUserContext(userId); // 初始化用户上下文
  31. const payload = {
  32. model: 'moonshot-v1-8k', // 使用的模型名称
  33. messages: this.userContexts[userId].concat([{
  34. role: 'user',
  35. content: prompt
  36. }]),
  37. ...options, // 其他选项,如 temperature、max_tokens 等
  38. };
  39. console.log(payload);
  40. try {
  41. const response = await axios.post(`${this.baseURL}/chat/completions`, payload, {
  42. headers: {
  43. 'Content-Type': 'application/json',
  44. Authorization: `Bearer ${this.apiKey}`, // 使用鉴权信息
  45. },
  46. });
  47. if (response.data && response.data.choices) {
  48. const assistantMessage = response.data.choices[0].message;
  49. this.updateUserContext(userId, assistantMessage); // 更新用户上下文
  50. return assistantMessage.content;
  51. } else {
  52. throw new Error(
  53. `Error from Kimi AI: ${response.data.error || 'Unknown error'}`
  54. );
  55. }
  56. } catch (error) {
  57. console.error('Error while communicating with Kimi AI:', error.message);
  58. throw error;
  59. }
  60. }
  61. }
  62. export default Kimi;