UNPKG

@aiapi/dify

Version:

⚙ A simple api for dify

83 lines (81 loc) 2.64 kB
import "core-js/modules/es.promise.js"; import https from 'https'; let config = { customHost: 'api.dify.ai' }; /** * ### Dify Custom Configuration * Setup dify-compatible service with custom host settings * * @param {DifyAppApiConfig} conf - Configuration parameters * @return {void} * */ function setupDifyApi(conf) { if (conf !== null && conf !== void 0 && conf.customHost) { config.customHost = conf.customHost; } } function getDifyApiConfig() { return config; } /** * ### Dify Completion API【Experimental Version】 * Returns a Promise that resolves to a string using the provided parameters. * * @param {DifyCompletionCallParamsExp} params - Parameters for the API call. * * @param {string} params.query - The text content to be supplemented * @param {string} params.bearerKey - AIDA application AppId * @param {object} params.inputs - Variable content, formatted as a key-value pair object * @param {string} params.response_mode - Response mode, default is 'blocking' * @param {string} params.user - Username, if not filled, a random string will be generated * @param {string} params.conversationId - Conversation ID, if not filled, a random one will be generated * @return {Promise<string>} A Promise that resolves to a string, representing the API's response. * */ function difyCompletion(params) { const { query, bearerKey, inputs, response_mode, user, conversationId } = params; return new Promise((resolve, reject) => { const postData = JSON.stringify({ inputs: inputs !== null && inputs !== void 0 ? inputs : {}, query: query, response_mode: response_mode !== null && response_mode !== void 0 ? response_mode : 'blocking', user: user !== null && user !== void 0 ? user : Math.random().toString(36).slice(3), conversation_id: conversationId !== null && conversationId !== void 0 ? conversationId : undefined }); const options = { hostname: getDifyApiConfig().customHost, path: '/v1/chat-messages', method: 'POST', headers: { 'Authorization': `Bearer ${bearerKey}`, 'Content-Type': 'application/json; chatset=utf-8', 'Content-Length': Buffer.byteLength(postData) } }; const req = https.request(options, res => { let data = ''; res.setEncoding('utf-8'); res.on('data', chunk => { data += chunk; }); res.on('end', () => { resolve(JSON.parse(data)); }); }); req.on('error', error => { reject(error); }); req.write(postData); req.end(); }); } export { difyCompletion, setupDifyApi };