UNPKG

@coze/api

Version:

Official Coze Node.js SDK for seamless AI integration into your applications | 扣子官方 Node.js SDK,助您轻松集成 AI 能力到应用中

890 lines (889 loc) 145 kB
(function(root, factory) { if ('object' == typeof exports && 'object' == typeof module) module.exports = factory(require("reconnecting-websocket"), require("jsonwebtoken"), require("axios"), require("ws"), require("node-fetch"), require("os"), require("crypto")); else if ('function' == typeof define && define.amd) define([ "reconnecting-websocket", "jsonwebtoken", "axios", "ws", "node-fetch", "os", "crypto" ], factory); else if ('object' == typeof exports) exports["CozeJs"] = factory(require("reconnecting-websocket"), require("jsonwebtoken"), require("axios"), require("ws"), require("node-fetch"), require("os"), require("crypto")); else root["CozeJs"] = factory(root["reconnecting-websocket"], root["jsonwebtoken"], root["axios"], root["ws"], root["node-fetch"], root["os"], root["crypto"]); })(global, (__WEBPACK_EXTERNAL_MODULE_reconnecting_websocket__, __WEBPACK_EXTERNAL_MODULE_jsonwebtoken__, __WEBPACK_EXTERNAL_MODULE_axios__, __WEBPACK_EXTERNAL_MODULE_ws__, __WEBPACK_EXTERNAL_MODULE_node_fetch__, __WEBPACK_EXTERNAL_MODULE_os__, __WEBPACK_EXTERNAL_MODULE_crypto__)=>(()=>{ "use strict"; var __webpack_modules__ = { axios: function(module1) { module1.exports = __WEBPACK_EXTERNAL_MODULE_axios__; }, crypto: function(module1) { module1.exports = __WEBPACK_EXTERNAL_MODULE_crypto__; }, jsonwebtoken: function(module1) { module1.exports = __WEBPACK_EXTERNAL_MODULE_jsonwebtoken__; }, "node-fetch": function(module1) { module1.exports = __WEBPACK_EXTERNAL_MODULE_node_fetch__; }, os: function(module1) { module1.exports = __WEBPACK_EXTERNAL_MODULE_os__; }, "reconnecting-websocket": function(module1) { module1.exports = __WEBPACK_EXTERNAL_MODULE_reconnecting_websocket__; }, ws: function(module1) { module1.exports = __WEBPACK_EXTERNAL_MODULE_ws__; } }; /************************************************************************/ // The module cache var __webpack_module_cache__ = {}; // The require function function __webpack_require__(moduleId) { // Check if module is in cache var cachedModule = __webpack_module_cache__[moduleId]; if (void 0 !== cachedModule) return cachedModule.exports; // Create a new module (and put it into the cache) var module1 = __webpack_module_cache__[moduleId] = { exports: {} }; // Execute the module function __webpack_modules__[moduleId](module1, module1.exports, __webpack_require__); // Return the exports of the module return module1.exports; } /************************************************************************/ // webpack/runtime/compat_get_default_export (()=>{ // getDefaultExport function for compatibility with non-ESM modules __webpack_require__.n = function(module1) { var getter = module1 && module1.__esModule ? function() { return module1['default']; } : function() { return module1; }; __webpack_require__.d(getter, { a: getter }); return getter; }; })(); // webpack/runtime/define_property_getters (()=>{ __webpack_require__.d = function(exports1, definition) { for(var key in definition)if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, { enumerable: true, get: definition[key] }); }; })(); // webpack/runtime/has_own_property (()=>{ __webpack_require__.o = function(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); }; })(); // webpack/runtime/make_namespace_object (()=>{ // define __esModule on exports __webpack_require__.r = function(exports1) { if ('undefined' != typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports1, Symbol.toStringTag, { value: 'Module' }); Object.defineProperty(exports1, '__esModule', { value: true }); }; })(); /************************************************************************/ var __webpack_exports__ = {}; // ESM COMPAT FLAG __webpack_require__.r(__webpack_exports__); // EXPORTS __webpack_require__.d(__webpack_exports__, { VariableChannel: ()=>/* reexport */ bots_VariableChannel, Transcriptions: ()=>/* reexport */ Transcriptions, InternalServerError: ()=>/* reexport */ InternalServerError, fetchAPI: ()=>/* reexport */ fetchAPI, COZE_CN_BASE_WS_URL: ()=>/* reexport */ COZE_CN_BASE_WS_URL, Websockets: ()=>/* reexport */ Websockets, Knowledge: ()=>/* reexport */ Knowledge, APIError: ()=>/* reexport */ APIError, CozeAPI: ()=>/* binding */ CozeAPI, OldDocuments: ()=>/* reexport */ Documents, POLL_INTERVAL: ()=>/* reexport */ POLL_INTERVAL, WebSocketAPI: ()=>/* reexport */ WebSocketAPI, handleAdditionalMessages: ()=>/* reexport */ handleAdditionalMessages, Documents: ()=>/* reexport */ documents_Documents, Variables: ()=>/* reexport */ Variables, Audio: ()=>/* reexport */ Audio, Files: ()=>/* reexport */ Files, ChatEventType: ()=>/* reexport */ chat_ChatEventType, ChatStatus: ()=>/* reexport */ chat_ChatStatus, NotFoundError: ()=>/* reexport */ NotFoundError, APIConnectionError: ()=>/* reexport */ APIConnectionError, COZE_COM_BASE_WS_URL: ()=>/* reexport */ COZE_COM_BASE_WS_URL, Rooms: ()=>/* reexport */ Rooms, Users: ()=>/* reexport */ Users, VoiceprintGroups: ()=>/* reexport */ VoiceprintGroups, WorkSpaces: ()=>/* reexport */ WorkSpaces, JSONParseError: ()=>/* reexport */ JSONParseError, castToError: ()=>/* reexport */ castToError, getDeviceToken: ()=>/* reexport */ getDeviceToken, getDeviceCode: ()=>/* reexport */ getDeviceCode, getJWTToken: ()=>/* reexport */ getJWTToken, getPKCEOAuthToken: ()=>/* reexport */ getPKCEOAuthToken, getWebAuthenticationUrl: ()=>/* reexport */ getWebAuthenticationUrl, handleParameters: ()=>/* reexport */ handleParameters, COZE_COM_BASE_URL: ()=>/* reexport */ COZE_COM_BASE_URL, AuthenticationError: ()=>/* reexport */ AuthenticationError, COZE_CN_BASE_URL: ()=>/* reexport */ COZE_CN_BASE_URL, VariableType: ()=>/* reexport */ bots_VariableType, getPKCEAuthenticationUrl: ()=>/* reexport */ getPKCEAuthenticationUrl, TemplateEntityType: ()=>/* reexport */ templates_TemplateEntityType, Conversations: ()=>/* reexport */ Conversations, Workflows: ()=>/* reexport */ Workflows, GatewayError: ()=>/* reexport */ GatewayError, RoomMode: ()=>/* reexport */ rooms_RoomMode, PermissionDeniedError: ()=>/* reexport */ PermissionDeniedError, APIUserAbortError: ()=>/* reexport */ APIUserAbortError, Live: ()=>/* reexport */ Live, Bots: ()=>/* reexport */ Bots, Chat: ()=>/* reexport */ Chat, RateLimitError: ()=>/* reexport */ RateLimitError, Runs: ()=>/* reexport */ Runs, SuggestReplyMode: ()=>/* reexport */ bots_SuggestReplyMode, WebsocketsEventType: ()=>/* reexport */ types_WebsocketsEventType, CreateRoomTurnDetectionType: ()=>/* reexport */ rooms_CreateRoomTurnDetectionType, PKCEAuthErrorType: ()=>/* reexport */ auth_PKCEAuthErrorType, TimeoutError: ()=>/* reexport */ TimeoutError, VoiceprintFeature: ()=>/* reexport */ VoiceprintFeature, _getJWTToken: ()=>/* reexport */ _getJWTToken, MAX_POLL_INTERVAL: ()=>/* reexport */ MAX_POLL_INTERVAL, WorkflowChat: ()=>/* reexport */ WorkflowChat, WorkflowEventType: ()=>/* reexport */ runs_WorkflowEventType, Templates: ()=>/* reexport */ Templates, getWebOAuthToken: ()=>/* reexport */ getWebOAuthToken, refreshOAuthToken: ()=>/* reexport */ refreshOAuthToken, Images: ()=>/* reexport */ Images, BadRequestError: ()=>/* reexport */ BadRequestError, CozeError: ()=>/* reexport */ CozeError, RoleType: ()=>/* reexport */ chat_RoleType, Voices: ()=>/* reexport */ Voices, Messages: ()=>/* reexport */ messages_Messages, WorkflowEvent: ()=>/* reexport */ WorkflowEvent, adapterFetch: ()=>/* reexport */ adapterFetch, Datasets: ()=>/* reexport */ Datasets, LiveType: ()=>/* reexport */ live_LiveType }); class APIResource { constructor(client){ this._client = client; } } /* eslint-disable @typescript-eslint/no-namespace */ class Bots extends APIResource { /** * Create a new agent. | 调用接口创建一个新的智能体。 * @docs en:https://www.coze.com/docs/developer_guides/create_bot?_lang=en * @docs zh:https://www.coze.cn/docs/developer_guides/create_bot?_lang=zh * @param params - Required The parameters for creating a bot. | 创建 Bot 的参数。 * @param params.space_id - Required The Space ID of the space where the agent is located. | Bot 所在的空间的 Space ID。 * @param params.name - Required The name of the agent. It should be 1 to 20 characters long. | Bot 的名称。 * @param params.description - Optional The description of the agent. It can be 0 to 500 characters long. | Bot 的描述信息。 * @param params.icon_file_id - Optional The file ID for the agent's avatar. | 作为智能体头像的文件 ID。 * @param params.prompt_info - Optional The personality and reply logic of the agent. | Bot 的提示词配置。 * @param params.onboarding_info - Optional The settings related to the agent's opening remarks. | Bot 的开场白配置。 * @returns Information about the created bot. | 创建的 Bot 信息。 */ async create(params, options) { const apiUrl = '/v1/bot/create'; const result = await this._client.post(apiUrl, params, false, options); return result.data; } /** * Update the configuration of an agent. | 调用接口修改智能体的配置。 * @docs en:https://www.coze.com/docs/developer_guides/update_bot?_lang=en * @docs zh:https://www.coze.cn/docs/developer_guides/update_bot?_lang=zh * @param params - Required The parameters for updating a bot. | 修改 Bot 的参数。 * @param params.bot_id - Required The ID of the agent that the API interacts with. | 待修改配置的智能体ID。 * @param params.name - Optional The name of the agent. | Bot 的名称。 * @param params.description - Optional The description of the agent. | Bot 的描述信息。 * @param params.icon_file_id - Optional The file ID for the agent's avatar. | 作为智能体头像的文件 ID。 * @param params.prompt_info - Optional The personality and reply logic of the agent. | Bot 的提示词配置。 * @param params.onboarding_info - Optional The settings related to the agent's opening remarks. | Bot 的开场白配置。 * @param params.knowledge - Optional Knowledge configurations of the agent. | Bot 的知识库配置。 * @returns Undefined | 无返回值 */ async update(params, options) { const apiUrl = '/v1/bot/update'; const result = await this._client.post(apiUrl, params, false, options); return result.data; } /** * Get the agents published as API service. | 调用接口查看指定空间发布到 Agent as API 渠道的智能体列表。 * @docs en:https://www.coze.com/docs/developer_guides/published_bots_list?_lang=en * @docs zh:https://www.coze.cn/docs/developer_guides/published_bots_list?_lang=zh * @param params - Required The parameters for listing bots. | 列出 Bot 的参数。 * @param params.space_id - Required The ID of the space. | Bot 所在的空间的 Space ID。 * @param params.page_size - Optional Pagination size. | 分页大小。 * @param params.page_index - Optional Page number for paginated queries. | 分页查询时的页码。 * @returns List of published bots. | 已发布的 Bot 列表。 * @deprecated Use listNew instead. */ async list(params, options) { const apiUrl = '/v1/space/published_bots_list'; const result = await this._client.get(apiUrl, params, false, options); return result.data; } /** * Get bots list. | 查看智能体列表 */ async listNew(params, options) { const apiUrl = '/v1/bots'; const result = await this._client.get(apiUrl, params, false, options); return result.data; } /** * Publish the specified agent as an API service. | 调用接口创建一个新的智能体。 * @docs en:https://www.coze.com/docs/developer_guides/publish_bot?_lang=en * @docs zh:https://www.coze.cn/docs/developer_guides/publish_bot?_lang=zh * @param params - Required The parameters for publishing a bot. | 发布 Bot 的参数。 * @param params.bot_id - Required The ID of the agent that the API interacts with. | 要发布的智能体ID。 * @param params.connector_ids - Required The list of publishing channel IDs for the agent. | 智能体的发布渠道 ID 列表。 * @returns Undefined | 无返回值 */ async publish(params, options) { const apiUrl = '/v1/bot/publish'; const result = await this._client.post(apiUrl, params, false, options); return result.data; } /** * Get the configuration information of the agent. | 获取指定智能体的配置信息。 * @docs en:https://www.coze.com/docs/developer_guides/get_metadata?_lang=en * @docs zh:https://www.coze.cn/docs/developer_guides/get_metadata?_lang=zh * @param params - Required The parameters for retrieving a bot. | 获取 Bot 的参数。 * @param params.bot_id - Required The ID of the agent that the API interacts with. | 要查看的智能体ID。 * @returns Information about the bot. | Bot 的配置信息。 * @deprecated Use retrieveNew instead. */ async retrieve(params, options) { const apiUrl = '/v1/bot/get_online_info'; const result = await this._client.get(apiUrl, params, false, options); return result.data; } /** * Get the configuration information of the agent. | 获取指定智能体的配置信息。 * @param botId - Required The ID of the agent that the API interacts with. | 要查看的智能体ID。 * @param params * @param options * @returns */ async retrieveNew(botId, params, options) { const apiUrl = `/v1/bots/${botId}`; const result = await this._client.get(apiUrl, params, false, options); return result.data; } } var bots_SuggestReplyMode = /*#__PURE__*/ function(SuggestReplyMode) { /** * The bot does not suggest replies. */ SuggestReplyMode["DISABLE"] = "disable"; /** * The bot suggests replies. */ SuggestReplyMode["ENABLE"] = "enable"; /** * The bot suggests replies based on the customized prompt. */ SuggestReplyMode["CUSTOMIZED"] = "customized"; return SuggestReplyMode; }({}); var bots_VariableType = /*#__PURE__*/ function(VariableType) { /** * The variable is a key-value pair. */ VariableType["KVVariable"] = "KVVariable"; /** * The variable is a list. */ VariableType["ListVariable"] = "ListVariable"; return VariableType; }({}); var bots_VariableChannel = /*#__PURE__*/ function(VariableChannel) { /** * The variable is a custom variable. */ VariableChannel["Custom"] = "custom"; /** * The variable is a system variable. */ VariableChannel["System"] = "system"; /** * The variable is a location variable. */ VariableChannel["Location"] = "location"; /** * The variable is a Feishu variable. */ VariableChannel["Feishu"] = "feishu"; /** * The variable is an app variable. */ VariableChannel["APP"] = "app"; return VariableChannel; }({}); /* eslint-disable security/detect-object-injection */ /* eslint-disable @typescript-eslint/no-explicit-any */ function safeJsonParse(jsonString) { let defaultValue = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : ''; try { return JSON.parse(jsonString); } catch (error) { return defaultValue; } } function sleep(ms) { return new Promise((resolve)=>{ setTimeout(resolve, ms); }); } function isUniApp() { return 'undefined' != typeof uni; } function isBrowser() { return 'undefined' != typeof window; } function isPlainObject(obj) { if ('object' != typeof obj || null === obj) return false; const proto = Object.getPrototypeOf(obj); if (null === proto) return true; let baseProto = proto; while(null !== Object.getPrototypeOf(baseProto))baseProto = Object.getPrototypeOf(baseProto); return proto === baseProto; } function mergeConfig() { for(var _len = arguments.length, objects = new Array(_len), _key = 0; _key < _len; _key++)objects[_key] = arguments[_key]; return objects.reduce((result, obj)=>{ if (void 0 === obj) return result || {}; for(const key in obj)if (Object.prototype.hasOwnProperty.call(obj, key)) { if (isPlainObject(obj[key]) && !Array.isArray(obj[key])) result[key] = mergeConfig(result[key] || {}, obj[key]); else result[key] = obj[key]; } return result; }, {}); } function isPersonalAccessToken(token) { return !!(null == token ? void 0 : token.startsWith('pat_')); } function buildWebsocketUrl(path, params) { const queryString = Object.entries(params || {}).filter((param)=>{ let [_, value] = param; return null != value && '' !== value; }).map((param)=>{ let [key, value] = param; return `${key}=${value}`; }).join('&'); return `${path}${queryString ? `?${queryString}` : ''}`; } const isBrowserExtension = ()=>'undefined' != typeof chrome && !!chrome.runtime && !!chrome.runtime.id; /* eslint-disable max-params */ class CozeError extends Error { } class APIError extends CozeError { static makeMessage(status, errorBody, message, headers) { if (!errorBody && message) return message; if (errorBody) { const list = []; const { code, msg, error } = errorBody; if (code) list.push(`code: ${code}`); if (msg) list.push(`msg: ${msg}`); if ((null == error ? void 0 : error.detail) && msg !== error.detail) list.push(`detail: ${error.detail}`); const logId = (null == error ? void 0 : error.logid) || (null == headers ? void 0 : headers['x-tt-logid']); if (logId) list.push(`logid: ${logId}`); return list.join(', '); } if (status) return `http status code: ${status} (no body)`; return '(no status code or body)'; } static generate(status, errorResponse, message, headers) { if (!status) return new APIConnectionError({ cause: castToError(errorResponse) }); const error = errorResponse; // https://www.coze.cn/docs/developer_guides/coze_error_codes if (400 === status || (null == error ? void 0 : error.code) === 4000) return new BadRequestError(status, error, message, headers); if (401 === status || (null == error ? void 0 : error.code) === 4100) return new AuthenticationError(status, error, message, headers); if (403 === status || (null == error ? void 0 : error.code) === 4101) return new PermissionDeniedError(status, error, message, headers); if (404 === status || (null == error ? void 0 : error.code) === 4200) return new NotFoundError(status, error, message, headers); if (429 === status || (null == error ? void 0 : error.code) === 4013) return new RateLimitError(status, error, message, headers); if (408 === status) return new TimeoutError(status, error, message, headers); if (502 === status) return new GatewayError(status, error, message, headers); if (status >= 500) return new InternalServerError(status, error, message, headers); return new APIError(status, error, message, headers); } constructor(status, error, message, headers){ var _error_detail, _error_error; super(`${APIError.makeMessage(status, error, message, headers)}`); this.status = status; this.headers = headers; this.logid = (null == error ? void 0 : null === (_error_detail = error.detail) || void 0 === _error_detail ? void 0 : _error_detail.logid) || (null == headers ? void 0 : headers['x-tt-logid']); // this.error = error; this.code = null == error ? void 0 : error.code; this.msg = null == error ? void 0 : error.msg; this.detail = null == error ? void 0 : null === (_error_error = error.error) || void 0 === _error_error ? void 0 : _error_error.detail; this.rawError = error; } } class APIConnectionError extends APIError { constructor({ message }){ super(void 0, void 0, message || 'Connection error.', void 0), this.status = void 0; // if (cause) { // this.cause = cause; // } } } class APIUserAbortError extends APIError { constructor(message){ super(void 0, void 0, message || 'Request was aborted.', void 0), this.name = 'UserAbortError', this.status = void 0; } } class BadRequestError extends APIError { constructor(...args){ super(...args), this.name = 'BadRequestError', this.status = 400; } } class AuthenticationError extends APIError { constructor(...args){ super(...args), this.name = 'AuthenticationError', this.status = 401; } } class PermissionDeniedError extends APIError { constructor(...args){ super(...args), this.name = 'PermissionDeniedError', this.status = 403; } } class NotFoundError extends APIError { constructor(...args){ super(...args), this.name = 'NotFoundError', this.status = 404; } } class TimeoutError extends APIError { constructor(...args){ super(...args), this.name = 'TimeoutError', this.status = 408; } } class RateLimitError extends APIError { constructor(...args){ super(...args), this.name = 'RateLimitError', this.status = 429; } } class InternalServerError extends APIError { constructor(...args){ super(...args), this.name = 'InternalServerError', this.status = 500; } } class GatewayError extends APIError { constructor(...args){ super(...args), this.name = 'GatewayError', this.status = 502; } } const castToError = (err)=>{ if (err instanceof Error) return err; return new Error(err); }; class JSONParseError extends Error { constructor({ message, cause }){ super(message); this.cause = cause; } } class Messages extends APIResource { /** * Get the list of messages in a chat. | 获取对话中的消息列表。 * @docs en:https://www.coze.com/docs/developer_guides/chat_message_list?_lang=en * @docs zh:https://www.coze.cn/docs/developer_guides/chat_message_list?_lang=zh * @param conversation_id - Required The ID of the conversation. | 会话 ID。 * @param chat_id - Required The ID of the chat. | 对话 ID。 * @returns An array of chat messages. | 对话消息数组。 */ async list(conversation_id, chat_id, options) { const apiUrl = `/v3/chat/message/list?conversation_id=${conversation_id}&chat_id=${chat_id}`; const result = await this._client.get(apiUrl, void 0, false, options); return result.data; } } const uuid = ()=>(Math.random() * new Date().getTime()).toString(); const handleAdditionalMessages = (additional_messages)=>null == additional_messages ? void 0 : additional_messages.map((i)=>({ ...i, content: 'object' == typeof i.content ? JSON.stringify(i.content) : i.content })); const handleParameters = (parameters)=>{ if (parameters) { for (const [key, value] of Object.entries(parameters))if ('object' == typeof value) parameters[key] = JSON.stringify(value); } return parameters; }; class Chat extends APIResource { /** * Call the Chat API to send messages to a published Coze agent. | 调用此接口发起一次对话,支持添加上下文 * @docs en:https://www.coze.com/docs/developer_guides/chat_v3?_lang=en * @docs zh:https://www.coze.cn/docs/developer_guides/chat_v3?_lang=zh * @param params - Required The parameters for creating a chat session. | 创建会话的参数。 * @param params.bot_id - Required The ID of the agent. | 要进行会话聊天的 Bot ID。 * @param params.user_id - Optional The ID of the user interacting with the Bot. | 标识当前与 Bot 交互的用户。 * @param params.additional_messages - Optional Additional messages for the conversation. | 对话的附加信息。 * @param params.custom_variables - Optional Variables defined in the Bot. | Bot 中定义变量。 * @param params.auto_save_history - Optional Whether to automatically save the conversation history. | 是否自动保存历史对话记录。 * @param params.meta_data - Optional Additional metadata for the message. | 创建消息时的附加消息。 * @param params.conversation_id - Optional The ID of the conversation. | 标识对话发生在哪一次会话中。 * @param params.extra_params - Optional Extra parameters for the conversation. | 附加参数。 * @param params.shortcut_command - Optional The shortcut command information. | 快捷指令信息。 * @param params.parameters - Optional custom parameters. | 自定义参数。 * @returns The data of the created chat. | 创建的对话数据。 */ async create(params, options) { if (!params.user_id) params.user_id = uuid(); const { conversation_id, ...rest } = params; const apiUrl = `/v3/chat${conversation_id ? `?conversation_id=${conversation_id}` : ''}`; const payload = { ...rest, additional_messages: handleAdditionalMessages(params.additional_messages), shortcut_command: params.shortcut_command ? { ...params.shortcut_command, parameters: handleParameters(params.shortcut_command.parameters) } : void 0, stream: false }; const result = await this._client.post(apiUrl, payload, false, options); return result.data; } /** * Call the Chat API to send messages to a published Coze agent. | 调用此接口发起一次对话,支持添加上下文 * @docs en:https://www.coze.com/docs/developer_guides/chat_v3?_lang=en * @docs zh:https://www.coze.cn/docs/developer_guides/chat_v3?_lang=zh * @param params - Required The parameters for creating a chat session. | 创建会话的参数。 * @param params.bot_id - Required The ID of the agent. | 要进行会话聊天的 Bot ID。 * @param params.user_id - Optional The ID of the user interacting with the Bot. | 标识当前与 Bot 交互的用户。 * @param params.additional_messages - Optional Additional messages for the conversation. | 对话的附加信息。 * @param params.custom_variables - Optional Variables defined in the Bot. | Bot 中定义的变量。 * @param params.auto_save_history - Optional Whether to automatically save the conversation history. | 是否自动保存历史对话记录。 * @param params.meta_data - Optional Additional metadata for the message. | 创建消息时的附加消息。 * @param params.conversation_id - Optional The ID of the conversation. | 标识对话发生在哪一次会话中。 * @param params.extra_params - Optional Extra parameters for the conversation. | 附加参数。 * @param params.shortcut_command - Optional The shortcut command information. | 快捷指令信息。 * @param params.parameters - Optional custom parameters. | 自定义参数。 * @returns */ async createAndPoll(params, options) { if (!params.user_id) params.user_id = uuid(); const { conversation_id, ...rest } = params; const apiUrl = `/v3/chat${conversation_id ? `?conversation_id=${conversation_id}` : ''}`; const payload = { ...rest, additional_messages: handleAdditionalMessages(params.additional_messages), shortcut_command: params.shortcut_command ? { ...params.shortcut_command, parameters: handleParameters(params.shortcut_command.parameters) } : void 0, stream: false }; const result = await this._client.post(apiUrl, payload, false, options); const chatId = result.data.id; const conversationId = result.data.conversation_id; let chat; while(true){ await sleep(100); chat = await this.retrieve(conversationId, chatId); if ('completed' === chat.status || 'failed' === chat.status || 'requires_action' === chat.status) break; } const messageList = await this.messages.list(conversationId, chatId); return { chat, messages: messageList }; } /** * Call the Chat API to send messages to a published Coze agent with streaming response. | 调用此接口发起一次对话,支持流式响应。 * @docs en:https://www.coze.com/docs/developer_guides/chat_v3?_lang=en * @docs zh:https://www.coze.cn/docs/developer_guides/chat_v3?_lang=zh * @param params - Required The parameters for streaming a chat session. | 流式会话的参数。 * @param params.bot_id - Required The ID of the agent. | 要进行会话聊天的 Bot ID。 * @param params.user_id - Optional The ID of the user interacting with the Bot. | 标识当前与 Bot 交互的用户。 * @param params.additional_messages - Optional Additional messages for the conversation. | 对话的附加信息。 * @param params.custom_variables - Optional Variables defined in the Bot. | Bot 中定义的变量。 * @param params.auto_save_history - Optional Whether to automatically save the conversation history. | 是否自动保存历史对话记录。 * @param params.meta_data - Optional Additional metadata for the message. | 创建消息时的附加消息。 * @param params.conversation_id - Optional The ID of the conversation. | 标识对话发生在哪一次会话中。 * @param params.extra_params - Optional Extra parameters for the conversation. | 附加参数。 * @param params.shortcut_command - Optional The shortcut command information. | 快捷指令信息。 * @param params.parameters - Optional custom parameters. | 自定义参数。 * @returns A stream of chat data. | 对话数据流。 */ async *stream(params, options) { if (!params.user_id) params.user_id = uuid(); const { conversation_id, ...rest } = params; const apiUrl = `/v3/chat${conversation_id ? `?conversation_id=${conversation_id}` : ''}`; const payload = { ...rest, additional_messages: handleAdditionalMessages(params.additional_messages), shortcut_command: params.shortcut_command ? { ...params.shortcut_command, parameters: handleParameters(params.shortcut_command.parameters) } : void 0, stream: true }; const result = await this._client.post(apiUrl, payload, true, options); for await (const message of result)if ("done" === message.event) { const ret = { event: message.event, data: '[DONE]' }; yield ret; } else try { const ret = { event: message.event, data: JSON.parse(message.data) }; yield ret; } catch (error) { throw new CozeError(`Could not parse message into JSON:${message.data}`); } } /** * Get the detailed information of the chat. | 查看对话的详细信息。 * @docs en:https://www.coze.com/docs/developer_guides/retrieve_chat?_lang=en * @docs zh:https://www.coze.cn/docs/developer_guides/retrieve_chat?_lang=zh * @param conversation_id - Required The ID of the conversation. | 会话 ID。 * @param chat_id - Required The ID of the chat. | 对话 ID。 * @returns The data of the retrieved chat. | 检索到的对话数据。 */ async retrieve(conversation_id, chat_id, options) { const apiUrl = `/v3/chat/retrieve?conversation_id=${conversation_id}&chat_id=${chat_id}`; const result = await this._client.post(apiUrl, void 0, false, options); return result.data; } /** * Cancel a chat session. | 取消对话会话。 * @docs en:https://www.coze.com/docs/developer_guides/cancel_chat?_lang=en * @docs zh:https://www.coze.cn/docs/developer_guides/cancel_chat?_lang=zh * @param conversation_id - Required The ID of the conversation. | 会话 ID。 * @param chat_id - Required The ID of the chat. | 对话 ID。 * @returns The data of the canceled chat. | 取消的对话数据。 */ async cancel(conversation_id, chat_id, options) { const apiUrl = '/v3/chat/cancel'; const payload = { conversation_id, chat_id }; const result = await this._client.post(apiUrl, payload, false, options); return result.data; } /** * Submit tool outputs for a chat session. | 提交对话会话的工具输出。 * @docs en:https://www.coze.com/docs/developer_guides/chat_submit_tool_outputs?_lang=en * @docs zh:https://www.coze.cn/docs/developer_guides/chat_submit_tool_outputs?_lang=zh * @param params - Required Parameters for submitting tool outputs. | 提交工具输出的参数。 * @param params.conversation_id - Required The ID of the conversation. | 会话 ID。 * @param params.chat_id - Required The ID of the chat. | 对话 ID。 * @param params.tool_outputs - Required The outputs of the tool. | 工具的输出。 * @param params.stream - Optional Whether to use streaming response. | 是否使用流式响应。 * @returns The data of the submitted tool outputs or a stream of chat data. | 提交的工具输出数据或对话数据流。 */ async *submitToolOutputs(params, options) { const { conversation_id, chat_id, ...rest } = params; const apiUrl = `/v3/chat/submit_tool_outputs?conversation_id=${params.conversation_id}&chat_id=${params.chat_id}`; const payload = { ...rest }; if (false === params.stream) { const response = await this._client.post(apiUrl, payload, false, options); return response.data; } { const result = await this._client.post(apiUrl, payload, true, options); for await (const message of result)if ("done" === message.event) { const ret = { event: message.event, data: '[DONE]' }; yield ret; } else try { const ret = { event: message.event, data: JSON.parse(message.data) }; yield ret; } catch (error) { throw new CozeError(`Could not parse message into JSON:${message.data}`); } } } constructor(...args){ super(...args), this.messages = new Messages(this._client); } } var chat_ChatStatus = /*#__PURE__*/ function(ChatStatus) { ChatStatus["CREATED"] = "created"; ChatStatus["IN_PROGRESS"] = "in_progress"; ChatStatus["COMPLETED"] = "completed"; ChatStatus["FAILED"] = "failed"; ChatStatus["REQUIRES_ACTION"] = "requires_action"; ChatStatus["CANCELED"] = "canceled"; ChatStatus["UNKNOWN"] = "unknown"; return ChatStatus; }({}); var chat_ChatEventType = /*#__PURE__*/ function(ChatEventType) { ChatEventType["CONVERSATION_CHAT_CREATED"] = "conversation.chat.created"; ChatEventType["CONVERSATION_CHAT_IN_PROGRESS"] = "conversation.chat.in_progress"; ChatEventType["CONVERSATION_CHAT_COMPLETED"] = "conversation.chat.completed"; ChatEventType["CONVERSATION_CHAT_FAILED"] = "conversation.chat.failed"; ChatEventType["CONVERSATION_CHAT_REQUIRES_ACTION"] = "conversation.chat.requires_action"; ChatEventType["CONVERSATION_MESSAGE_DELTA"] = "conversation.message.delta"; ChatEventType["CONVERSATION_MESSAGE_COMPLETED"] = "conversation.message.completed"; ChatEventType["CONVERSATION_AUDIO_DELTA"] = "conversation.audio.delta"; ChatEventType["DONE"] = "done"; ChatEventType["ERROR"] = "error"; return ChatEventType; }({}); var chat_RoleType = /*#__PURE__*/ function(RoleType) { RoleType["User"] = "user"; RoleType["Assistant"] = "assistant"; return RoleType; }({}); class messages_Messages extends APIResource { /** * Create a message and add it to the specified conversation. | 创建一条消息,并将其添加到指定的会话中。 * @docs en: https://www.coze.com/docs/developer_guides/create_message?_lang=en * @docs zh: https://www.coze.cn/docs/developer_guides/create_message?_lang=zh * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。 * @param params - Required The parameters for creating a message | 创建消息所需的参数 * @param params.role - Required The entity that sent this message. Possible values: user, assistant. | 发送这条消息的实体。取值:user, assistant。 * @param params.content - Required The content of the message. | 消息的内容。 * @param params.content_type - Required The type of the message content. | 消息内容的类型。 * @param params.meta_data - Optional Additional information when creating a message. | 创建消息时的附加消息。 * @returns Information about the new message. | 消息详情。 */ async create(conversation_id, params, options) { const apiUrl = `/v1/conversation/message/create?conversation_id=${conversation_id}`; const response = await this._client.post(apiUrl, params, false, options); return response.data; } /** * Modify a message, supporting the modification of message content, additional content, and message type. | 修改一条消息,支持修改消息内容、附加内容和消息类型。 * @docs en: https://www.coze.com/docs/developer_guides/modify_message?_lang=en * @docs zh: https://www.coze.cn/docs/developer_guides/modify_message?_lang=zh * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。 * @param message_id - Required The ID of the message. | Message ID,即消息的唯一标识。 * @param params - Required The parameters for modifying a message | 修改消息所需的参数 * @param params.meta_data - Optional Additional information when modifying a message. | 修改消息时的附加消息。 * @param params.content - Optional The content of the message. | 消息的内容。 * @param params.content_type - Optional The type of the message content. | 消息内容的类型。 * @returns Information about the modified message. | 消息详情。 */ // eslint-disable-next-line max-params async update(conversation_id, message_id, params, options) { const apiUrl = `/v1/conversation/message/modify?conversation_id=${conversation_id}&message_id=${message_id}`; const response = await this._client.post(apiUrl, params, false, options); return response.message; } /** * Get the detailed information of specified message. | 查看指定消息的详细信息。 * @docs en: https://www.coze.com/docs/developer_guides/retrieve_message?_lang=en * @docs zh: https://www.coze.cn/docs/developer_guides/retrieve_message?_lang=zh * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。 * @param message_id - Required The ID of the message. | Message ID,即消息的唯一标识。 * @returns Information about the message. | 消息详情。 */ async retrieve(conversation_id, message_id, options) { const apiUrl = `/v1/conversation/message/retrieve?conversation_id=${conversation_id}&message_id=${message_id}`; const response = await this._client.get(apiUrl, null, false, options); return response.data; } /** * List messages in a conversation. | 列出会话中的消息。 * @docs en: https://www.coze.com/docs/developer_guides/message_list?_lang=en * @docs zh: https://www.coze.cn/docs/developer_guides/message_list?_lang=zh * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。 * @param params - Optional The parameters for listing messages | 列出消息所需的参数 * @param params.order - Optional The order of the messages. | 消息的顺序。 * @param params.chat_id - Optional The ID of the chat. | 聊天 ID。 * @param params.before_id - Optional The ID of the message before which to list. | 列出此消息之前的消息 ID。 * @param params.after_id - Optional The ID of the message after which to list. | 列出此消息之后的消息 ID。 * @param params.limit - Optional The maximum number of messages to return. | 返回的最大消息数。 * @returns A list of messages. | 消息列表。 */ async list(conversation_id, params, options) { const apiUrl = `/v1/conversation/message/list?conversation_id=${conversation_id}`; const response = await this._client.post(apiUrl, params, false, options); return response; } /** * Call the API to delete a message within a specified conversation. | 调用接口在指定会话中删除消息。 * @docs en: https://www.coze.com/docs/developer_guides/delete_message?_lang=en * @docs zh: https://www.coze.cn/docs/developer_guides/delete_message?_lang=zh * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。 * @param message_id - Required The ID of the message. | Message ID,即消息的唯一标识。 * @returns Details of the deleted message. | 已删除的消息详情。 */ async delete(conversation_id, message_id, options) { const apiUrl = `/v1/conversation/message/delete?conversation_id=${conversation_id}&message_id=${message_id}`; const response = await this._client.post(apiUrl, void 0, false, options); return response.data; } } class Conversations extends APIResource { /** * Create a conversation. Conversation is an interaction between an agent and a user, including one or more messages. | 调用接口创建一个会话。 * @docs en: https://www.coze.com/docs/developer_guides/create_conversation?_lang=en * @docs zh: https://www.coze.cn/docs/developer_guides/create_conversation?_lang=zh * @param params - Required The parameters for creating a conversation | 创建会话所需的参数 * @param params.messages - Optional Messages in the conversation. | 会话中的消息内容。 * @param params.meta_data - Optional Additional information when creating a message. | 创建消息时的附加消息。 * @param params.bot_id - Optional Bind and isolate conversation on different bots. | 绑定和隔离不同Bot的会话。 * @returns Information about the created conversation. | 会话的基础信息。 */ async create(params, options) { const apiUrl = '/v1/conversation/create'; const response = await this._client.post(apiUrl, params, false, options); return response.data; } /** * Get the information of specific conversation. | 通过会话 ID 查看会话信息。 * @docs en: https://www.coze.com/docs/developer_guides/retrieve_conversation?_lang=en * @docs zh: https://www.coze.cn/docs/developer_guides/retrieve_conversation?_lang=zh * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。 * @returns Information about the conversation. | 会话的基础信息。 */ async retrieve(conversation_id, options) { const apiUrl = `/v1/conversation/retrieve?conversation_id=${conversation_id}`; const response = await this._client.get(apiUrl, null, false, options); return response.data; } /** * List all conversations. | 列出 Bot 下所有会话。 * @param params * @param params.bot_id - Required Bot ID. | Bot ID。 * @param params.page_num - Optional The page number. | 页码,默认值为 1。 * @param params.page_size - Optional The number of conversations per page. | 每页的会话数量,默认值为 50。 * @returns Information about the conversations. | 会话的信息。 */ async list(params, options) { const apiUrl = '/v1/conversations'; const response = await this._client.get(apiUrl, params, false, options); return response.data; } /** * Clear a conversation. | 清空会话。 * @param conversation_id - Required The ID of the conversation. | Conversation ID,即会话的唯一标识。 * @returns Information about the conversation session. | 会话的会话 ID。 */ async clear(conversation_id, options) { const apiUrl = `/v1/conversations/${conversation_id}/clear`; const response = await this._client.post(apiUrl, null, false, options); return response.data; } constructor(...args){ super(...args), this.messages = new messages_Messages(this._client); } } // EXTERNAL MODULE: external "axios" var external_axios_ = __webpack_require__("axios"); var external_axios_default = /*#__PURE__*/ __webpack_require__.n(external_axios_); class Files extends APIResource { /** * Upload files to Coze platform. | 调用接口上传文件到扣子。 * @docs en: https://www.coze.com/docs/developer_guides/upload_files?_lang=en * @docs zh: https://www.coze.cn/docs/developer_guides/upload_files?_lang=zh * @param params - Required The parameters for file upload | 上传文件所需的参数 * @param params.file - Required The file to be uploaded. | 需要上传的文件。 * @returns Information about the new file. | 已上传的文件信息。 */ async upload(params, options) { const apiUrl = '/v1/files/upload'; const response = await this._client.post(apiUrl, (0, external_axios_.toFormData)(params), false, options); return response.data; } /** * Get the information of the specific file uploaded to Coze platform. | 查看已上传的文件详情。 * @docs en: https://www.coze.com/docs/developer_guides/retrieve_files?_lang=en * @docs zh: https://www.coze.cn/docs/developer_guides/retrieve_files?_lang=zh * @param file_id - Required The ID of the uploaded file. | 已上传的文件 ID。 * @returns Information about the uploaded file. | 已上传的文件信息。 */ async retrieve(file_id, options) { const apiUrl = `/v1/files/retrieve?file_id=${file_id}`; const response = await this._client.get(apiUrl, null, false, options); return response.data; } } class Runs extends APIResource { /** * Initiates a workflow run. | 启动工作流运行。 * @docs en: https://www.coze.com/docs/developer_guides/workflow_run?_lang=en * @docs zh: https://www.coze.cn/docs/developer_guides/workflow_run?_lang=zh * @param params.workflow_id - Required The ID of the workflow to run. | 必选 要运行的工作流 ID。 * @param params.bot_id - Optional The ID of the bot associated with the workflow. | 可选 与工作流关联的机器人 ID。 * @param params.parameters - Optional Parameters for the workflow execution. | 可选 工作流执行的参数。 * @param params.ext - Optional Additional information for the workflow execution. | 可选 工作流执行的附加信息。