123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155 |
- /**
- * AI服务类
- * 处理与AI模型的通信和响应
- */
- class AIService {
- constructor() {
- this.apiEndpoint = CONFIG.AI_API.ENDPOINT;
- this.model = CONFIG.AI_API.MODEL;
- this.context = [];
- // 使用默认API密钥
- this.apiKey = CONFIG.AI_API.DEFAULT_API_KEY;
- this.controller = null; // 用于中断请求的 AbortController
- }
- /**
- * 初始化AI服务
- */
- async init() {
- try {
- // 尝试从storage中获取用户设置的API密钥
- const result = await Utils.getStorageData("apiKey");
- if (result?.apiKey) {
- this.apiKey = result.apiKey;
- }
- console.log("AI Service initialized");
- } catch (error) {
- console.error("Failed to initialize AI service:", error);
- }
- }
- /**
- * 设置API密钥
- * @param {string} apiKey
- */
- async setApiKey(apiKey) {
- this.apiKey = apiKey;
- await Utils.setStorageData("apiKey", { apiKey });
- }
- /**
- * 发送消息到DeepSeek API
- * @param {string} message 用户消息
- * @returns {Promise<string>} AI响应
- */
- async sendMessage(message) {
- try {
- // 创建新的 AbortController
- this.controller = new AbortController();
- const response = await fetch(this.apiEndpoint, {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- Authorization: `Bearer ${this.apiKey}`,
- },
- body: JSON.stringify({
- model: this.model,
- messages: this.formatMessages(message),
- max_tokens: CONFIG.AI_API.MAX_TOKENS,
- temperature: CONFIG.AI_API.TEMPERATURE,
- }),
- signal: this.controller.signal,
- });
- if (!response.ok) {
- throw new Error(`API request failed: ${response.status}`);
- }
- const data = await response.json();
- const aiResponse = data.choices[0]?.message?.content;
- if (!aiResponse) {
- throw new Error("无效的API响应");
- }
- return aiResponse;
- } catch (error) {
- if (error.name === "AbortError") {
- throw new Error("REQUEST_ABORTED");
- }
- console.error("API call failed:", error);
- throw error;
- } finally {
- this.controller = null;
- }
- }
- /**
- * 格式化消息历史
- * @param {string} currentMessage 当前消息
- * @returns {Array} 格式化后的消息数组
- */
- formatMessages(currentMessage) {
- const messages = this.context.map((msg) => ({
- role: msg.role,
- content: msg.content,
- }));
- messages.push({
- role: "user",
- content: currentMessage,
- });
- return messages;
- }
- /**
- * 更新对话上下文
- * @param {string} message 新消息
- * @param {string} role 消息角色(user/assistant)
- */
- updateContext(message, role) {
- this.context.push({
- role,
- content: message,
- timestamp: new Date().toISOString(),
- });
- // 保持上下文长度在合理范围内
- if (this.context.length > 10) {
- this.context = this.context.slice(-10);
- }
- }
- /**
- * 清除对话上下文
- */
- clearContext() {
- this.context = [];
- }
- /**
- * 获取当前对话上下文
- * @returns {Array} 对话上下文数组
- */
- getContext() {
- return this.context;
- }
- // 添加中断方法
- abortRequest() {
- if (this.controller) {
- this.controller.abort();
- this.controller = null;
- }
- }
- }
- // 确保在DOM加载完成后再创建实例
- document.addEventListener("DOMContentLoaded", () => {
- // 只有在实例不存在时才创建
- if (!window.aiService) {
- window.aiService = new AIService();
- }
- });
|