DeepSeek.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import axios from 'axios';
  2. // https://platform.deepseek.com/usage
  3. // https://platform.deepseek.com/api_keys
  4. class DeepSeek {
  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.deepseek.com'; // 默认的API基础URL
  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: 'deepseek-chat', // 使用的模型名称
  33. messages: this.userContexts[userId].concat([{
  34. role: 'user',
  35. content: prompt
  36. }]),
  37. ...options, // 其他选项,如 temperature、max_tokens 等
  38. };
  39. try {
  40. const response = await axios.post(`${this.baseURL}/chat/completions`, payload, {
  41. headers: {
  42. 'Content-Type': 'application/json',
  43. Authorization: `Bearer ${this.apiKey}`, // 使用鉴权信息
  44. },
  45. });
  46. if (response.data && response.data.choices) {
  47. const assistantMessage = response.data.choices[0].message;
  48. this.updateUserContext(userId, assistantMessage); // 更新用户上下文
  49. return assistantMessage.content;
  50. } else {
  51. throw new Error(
  52. `Error from DeepSeek AI: ${response.data.error || 'Unknown error'}`
  53. );
  54. }
  55. } catch (error) {
  56. console.error('Error while communicating with DeepSeek AI:', error.message);
  57. throw error;
  58. }
  59. }
  60. }
  61. export default DeepSeek;