class Coze this.BOT_ID = BOT_ID; this.API_KEY = API_KEY; this.conversation = {}; Coze.instance = this; } async CreateConversation(user) try { const response = await fetch("https://api.coze.cn/v1/conversation/create", { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${this.API_KEY}` }, body: JSON.stringify({ bot_id: this.BOT_ID, user_id: user, stream: false, auto_save_history: true, additional_messages: [] }) }); const data = await response.json(); if (data.code !== 0) { throw new Error(data.msg || 'Failed to create conversation'); } this.conversation[user] = data.data.id; return data.data.id; } catch (error) { console.error("创建会话失败:", error); return ""; } } async ChatCozeV3(conversation_id, user, query, messages = []) else { return this._pollingChat(conversation_id, user, query, messages); } } async _streamChat(conversation_id, user, query, messages) { const url = `${Coze.API_URL}?conversation_id=${conversation_id}`; const message = { role: "user", content: query, content_type: "text" }; messages.push(message); const params = { bot_id: this.BOT_ID, user_id: user, query: query, additional_messages: messages, stream: true, auto_save_history: true }; try { const response = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${this.API_KEY}` }, body: JSON.stringify(params) }); const reader = response.body.getReader(); let result = ""; while (true) { const { done, value } = await reader.read(); if (done) break; const decoder = new TextDecoder(); const chunk = decoder.decode(value, { stream: true }); const lines = chunk.split(" "); for (let i = 0; i < lines.length; i++) } } } return result; } catch (error) { console.error("流式请求失败:", error); return ""; } } async _pollingChat(conversation_id, user, query) { try { // 1. 发送消息 const response = await fetch(Coze.API_URL, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${this.API_KEY}` }, body: JSON.stringify({ bot_id: this.BOT_ID, user_id: user, additional_messages: [{ "role": "user", "content": query, "content_type": "text" }], stream: false, auto_save_history: true, conversation_id: conversation_id }) }); const data = await response.json(); if (data.code !== 0) { throw new Error(data.msg || 'API请求失败'); } const chatId = data.data.id; conversation_id = data.data.conversation_id; // 2. 等待处理完成 await this._waitForCompletion(chatId, conversation_id); // 3. 获取最终回复 return await this._getFinalResponse(chatId, conversation_id); } catch (error) } async _waitForCompletion(chatId, conversationId, maxRetries = 30, interval = 1000) { const url = `${Coze.API_URL}/retrieve`; for (let i = 0; i < maxRetries; i++) { try { const response = await fetch(`${url}?chat_id=${chatId}&conversation_id=${conversationId}`, { headers: { 'Authorization': `Bearer ${this.API_KEY}` } }); const data = await response.json(); if (data.code !== 0) { throw new Error(data.msg || 'API请求失败'); } if (data.data.status === "completed") { return true; } await new Promise(resolve => setTimeout(resolve, interval)); } catch (error) { throw error; } } throw new Error("等待响应超时"); } async _getFinalResponse(chatId, conversationId) { const url = `${Coze.API_URL}/message/list`; try { const response = await fetch(`${url}?chat_id=${chatId}&conversation_id=${conversationId}`, { headers: { 'Authorization': `Bearer ${this.API_KEY}` } }); const data = await response.json(); if (data.code !== 0) { throw new Error(data.msg || 'API请求失败'); } // 提取助手的回复 const assistantReplies = data.data.filter(msg => msg.role === "assistant 扣子 Coze 教程" && msg.type === "answer" ); return assistantReplies.length > 0 ? assistantReplies[assistantReplies.length - 1].content : ""; } catch (error) { throw error; } } } // 完全兼容原使用方式 async function chatCozeAPI(botId, apiKey, query) { const coze = new Coze(botId, apiKey); const user = "test_user"; const messages = []; const response = await coze.ChatCozeV3("", user, query, messages); console.log("Chat Response:", response); return response; } // 也可以使用新的轮询模式 async function chatCozeAPIPolling(botId, apiKey, query) { const coze = new Coze(botId, apiKey); const user = "test_user"; const messages = []; // 临时关闭流式模式 const originalChat = coze.ChatCozeV3.bind(coze); coze.ChatCozeV3 = async function(...args) { return this._pollingChat(...args); }; try { const response = await coze.ChatCozeV3("", user, query, messages); console.log("Chat Response (Polling):", response); return response; } finally { // 恢复原方法 coze.ChatCozeV3 = originalChat; } }
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/267459.html原文链接:https://javaforall.net
