UNPKG

@coze/api

Version:

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

957 lines 122 kB
import * as __WEBPACK_EXTERNAL_MODULE_axios__ from "axios"; import * as __WEBPACK_EXTERNAL_MODULE_ws__ from "ws"; import * as __WEBPACK_EXTERNAL_MODULE_reconnecting_websocket__ from "reconnecting-websocket"; import * as __WEBPACK_EXTERNAL_MODULE_os__ from "os"; import * as __WEBPACK_EXTERNAL_MODULE_node_fetch__ from "node-fetch"; import * as __WEBPACK_EXTERNAL_MODULE_crypto__ from "crypto"; import * as __WEBPACK_EXTERNAL_MODULE_jsonwebtoken__ from "jsonwebtoken"; 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); } } 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, __WEBPACK_EXTERNAL_MODULE_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. | 可选 工作流执行的附加信息。 * @param params.execute_mode - Optional The mode in which to execute the workflow. | 可选 工作流执行的模式。 * @param params.connector_id - Optional The ID of the connector to use for the workflow. | 可选 用于工作流的连接器 ID。 * @param params.app_id - Optional The ID of the app. | 可选 要进行会话聊天的 App ID * @returns RunWorkflowData | 工作流运行数据 */ async create(params, options) { const apiUrl = '/v1/workflow/run'; const response = await this._client.post(apiUrl, params, false, options); return response; } /** * Streams the workflow run events. | 流式传输工作流运行事件。 * @docs en: https://www.coze.com/docs/developer_guides/workflow_stream_run?_lang=en * @docs zh: https://www.coze.cn/docs/developer_guides/workflow_stream_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. | 可选 工作流执行的附加信息。 * @param params.execute_mode - Optional The mode in which to execute the workflow. | 可选 工作流执行的模式。 * @param params.connector_id - Optional The ID of the connector to use for the workflow. | 可选 用于工作流的连接器 ID。 * @param params.app_id - Optional The ID of the app. | 可选 要进行会话聊天的 App ID * @returns Stream<WorkflowEvent, { id: string; event: string; data: string }> | 工作流事件流 */ async *stream(params, options) { const apiUrl = '/v1/workflow/stream_run'; const result = await this._client.post(apiUrl, params, true, options); for await (const message of result)try { if ("Done" === message.event) yield new WorkflowEvent(Number(message.id), "Done"); else yield new WorkflowEvent(Number(message.id), message.event, JSON.parse(message.data)); } catch (error) { throw new CozeError(`Could not parse message into JSON:${message.data}`); } } /** * Resumes a paused workflow run. | 恢复暂停的工作流运行。 * @docs en: https://www.coze.com/docs/developer_guides/workflow_resume?_lang=en * @docs zh: https://www.coze.cn/docs/developer_guides/workflow_resume?_lang=zh * @param params.workflow_id - Required The ID of the workflow to resume. | 必选 要恢复的工作流 ID。 * @param params.event_id - Required The ID of the event to resume from. | 必选 要从中恢复的事件 ID。 * @param params.resume_data - Required Data needed to resume the workflow. | 必选 恢复工作流所需的数据。 * @param params.interrupt_type - Required The type of interruption to resume from. | 必选 要恢复的中断类型。 * @returns AsyncGenerator<WorkflowEvent, { id: string; event: string; data: string }> | 工作流事件流 */ async *resume(params, options) { const apiUrl = '/v1/workflow/stream_resume'; const result = await this._client.post(apiUrl, params, true, options); for await (const message of result)try { if ("Done" === message.event) yield new WorkflowEvent(Number(message.id), "Done"); else yield new WorkflowEvent(Number(message.id), message.event, JSON.parse(message.data)); } catch (error) { throw new CozeError(`Could not parse message into JSON:${message.data}`); } } /** * Get the workflow run history | 工作流异步运行后,查看执行结果 * @docs zh: https://www.coze.cn/open/docs/developer_guides/workflow_history * @param workflowId - Required The ID of the workflow. | 必选 工作流 ID。 * @param executeId - Required The ID of the workflow execution. | 必选 工作流执行 ID。 * @returns WorkflowExecuteHistory[] | 工作流执行历史 */ async history(workflowId, executeId, options) { const apiUrl = `/v1/workflows/${workflowId}/run_histories/${executeId}`; const response = await this._client.get(apiUrl, void 0, false, options); return response.data; } } var runs_WorkflowEventType = /*#__PURE__*/ function(WorkflowEventType) { // The output message from the workflow node, such as the output message from // the message node or end node. You can view the specific message content in data. WorkflowEventType["MESSAGE"] = "Message"; // An error has occurred. You can view the error_code and error_message in data to // troubleshoot the issue. // 报错。可以在 data 中查看 error_code 和 error_message,排查问题。 WorkflowEventType["ERROR"] = "Error"; // End. Indicates the end of the workflow execution, where data is empty. // 结束。表示工作流执行结束,此时 data 为空。 WorkflowEventType["DONE"] = "Done"; // Interruption. Indicates the workflow has been interrupted, where the data field // contains specific interruption information. // 中断。表示工作流中断,此时 data 字段中包含具体的中断信息。 WorkflowEventType["INTERRUPT"] = "Interrupt"; return WorkflowEventType; }({}); class WorkflowEvent { constructor(id, event, data){ this.id = id; this.event = event; this.data = data; } } class WorkflowChat extends APIResource { /** * Execute a chat workflow. | 执行对话流 * @docs en: https://www.coze.cn/docs/developer_guides/workflow_chat?_lang=en * @docs zh: https://www.coze.cn/docs/developer_guides/workflow_chat?_lang=zh * @param params.workflow_id - Required The ID of the workflow to chat with. | 必选 要对话的工作流 ID。 * @param params.additional_messages - Required Array of messages for the chat. | 必选 对话的消息数组。 * @param params.parameters - Optional Parameters for the workflow execution. | 必选 工作流执行的参数。 * @param params.app_id - Optional The ID of the app. | 可选 应用 ID。 * @param params.bot_id - Optional The ID of the bot. | 可选 Bot ID。 * @param params.conversation_id - Optional The ID of the conversation. | 可选 会话 ID。 * @param params.ext - Optional Additional information for the chat. | 可选 对话的附加信息。 * @returns AsyncGenerator<StreamChatData> | 对话数据流 */ async *stream(params, options) { const apiUrl = '/v1/workflows/chat'; const payload = { ...params, additional_messages: handleAdditionalMessages(params.additional_messages) }; const result = await this._client.post(apiUrl, payload, true, options); for await (const message of result)if (message.event === chat_ChatEventType.DONE) { 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}`); } } } class Workflows extends APIResource { constructor(...args){ super(...args), this.runs = new Runs(this._client), this.chat = new WorkflowChat(this._client); } } class WorkSpaces extends APIResource { /** * View the list of workspaces that the current Coze user has joined. | 查看当前扣子用户加入的空间列表。 * @docs en: https://www.coze.com/docs/developer_guides/list_workspace?_lang=en * @docs zh: https://www.coze.cn/docs/developer_guides/list_workspace?_lang=zh * @param params.page_num - Optional The page number for paginated queries. Default is 1. * | 可选 分页查询时的页码。默认为 1,即从第一页数据开始返回。 * @param params.page_size - Optional The size of pagination. Default is 10. Maximum is 50. | 可选 分页大小。默认为 10,最大为 50。 * @returns OpenSpaceData | 工作空间列表 */ async list(params, options) { const apiUrl = '/v1/workspaces'; const response = await this._client.get(apiUrl, params, false, options); return safeJsonParse(response, response).data; } } // Required header for knowledge APIs const documents_headers = { 'agw-js-conv': 'str' }; class Documents extends APIResource { /** * @deprecated The method is deprecated and will be removed in a future version. Please use 'client.datasets.documents.list' instead. * * View the file list of a specified knowledge base, which includes lists of documents, spreadsheets, or images. * | 调用接口查看指定知识库的内容列表,即文件、表格或图像列表。 * @docs en: https://www.coze.com/docs/developer_guides/list_knowledge_files?_lang=en * @docs zh: https://www.coze.cn/docs/developer_guides/list_knowledge_files?_lang=zh * @param params.dataset_id - Required The ID of the knowledge base. | 必选 待查看文件的知识库 ID。 * @param params.page - Optional The page number for paginated queries. Default is 1. | 可选 分页查询时的页码。默认为 1。 * @param params.page_size - Optional The size of pagination. Default is 10. | 可选 分页大小。默认为 10。 * @returns ListDocumentData | 知识库文件列表 */ list(params, options) { const apiUrl = '/open_api/knowledge/document/list'; const response = this._client.get(apiUrl, params, false, mergeConfig(options, { headers: documents_headers })); return response; } /** * @deprecated The method is deprecated and will be removed in a future version. Please use 'client.datasets.documents.create' instead. * * Upload files to the specific knowledge. | 调用此接口向指定知识库中上传文件。 * @docs en: https://www.coze.com/docs/developer_guides/create_knowledge_files?_lang=en * @docs zh: https://www.coze.cn/docs/developer_guides/create_knowledge_files?_lang=zh * @param params.dataset_id - Required The ID of the knowledge. | 必选 知识库 ID。 * @param params.document_bases - Required The metadata information of the files awaiting upload. | 必选 待上传文件的元数据信息。 * @param params.chunk_strategy - Required when uploading files to a new knowledge for the first time. Chunk strategy. * | 向新知识库首次上传文件时必选 分段规则。 * @returns DocumentInfo[] | 已上传文件的基本信息 */ async create(params, options) { const apiUrl = '/open_api/knowledge/document/create'; const response = await this._client.post(apiUrl, params, false, mergeConfig(options, { headers: documents_headers })); return response.document_infos; } /** * @deprecated The method is deprecated and will be removed in a future version. Please use 'client.datasets.documents.delete' instead. * * Delete text, images, sheets, and other files in the knowledge base, supporting batch deletion. * | 删除知识库中的文本、图像、表格等文件,支持批量删除。 * @docs en: https://www.coze.com/docs/developer_guides/delete_knowledge_files?_lang=en * @docs zh: https://www.coze.cn/docs/developer_guides/delete_knowledge_files?_lang=zh * @param params.document_ids - Required The list of knowledge base files to be deleted. | 必选 待删除的文件 ID。 * @returns void | 无返回 */ async delete(params, options) { const apiUrl = '/open_api/knowledge/document/delete'; await this._client.post(apiUrl, params, false, mergeConfig(options, { headers: documents_headers })); } /** * @deprecated The method is deprecated and will be removed in a future version. Please use 'client.datasets.documents.update' instead. * * Modify the knowledge base file name and update strategy. | 调用接口修改知识库文件名称和更新策略。 * @docs en: https://www.coze.com/docs/developer_guides/modify_knowledge_files?_lang=en * @docs zh: https://www.coze.cn/docs/developer_guides/modify_knowledge_files?_lang=zh * @param params.document_id - Required The ID of the knowledge base file. | 必选 待修改的知识库文件 ID。 * @param params.document_name - Optional The new name of the knowledge base file. | 可选 知识库文件的新名称。 * @param params.update_rule - Optional The update strategy for online web pages. | 可选 在线网页更新策略。 * @returns void | 无返回 */ async update(params, options) { const apiUrl = '/open_api/knowledge/document/update'; await this._client.post(apiUrl, params, false, mergeConfig(options, { headers: documents_headers })); } } class Knowledge extends APIResource { constructor(...args){ super(...args), /** * @deprecated */ this.documents = new Documents(this._client); } } // Required header for knowledge APIs const documents_documents_headers = { 'agw-js-conv': 'str' }; class documents_Documents extends APIResource { /** * View the file list of a specified knowledge base, which includes lists of documents, spreadsheets, or images. * | 调用接口查看指定知识库的内容列表,即文件、表格或图像列表。 * @docs en: https://www.coze.com/docs/developer_guides/list_knowledge_files?_lang=en * @docs zh: https://www.coze.cn/docs/developer_guides/list_knowledge_files?_lang=zh * @param params.dataset_id - Required The ID of the knowledge base. | 必选 待查看文件的知识库 ID。 * @param params.page - Optional The page number for paginated queries. Default is 1. | 可选 分页查询时的页码。默认为 1。 * @param params.page_size - Optional The size of pagination. Default is 10. | 可选 分页大小。默认为 10。 * @returns ListDocumentData | 知识库文件列表 */ async list(params, options) { const apiUrl = '/open_api/knowledge/document/list'; const response = await this._client.post(apiUrl, params, false, mergeConf