@aiapi/dify
Version:
⚙ A simple api for dify
95 lines (92 loc) • 2.97 kB
JavaScript
require("core-js/modules/es.promise.js");
Object.defineProperty(exports, '__esModule', {
value: true
});
var https = require('https');
function _interopDefaultLegacy(e) {
return e && typeof e === 'object' && 'default' in e ? e : {
'default': e
};
}
var https__default = /*#__PURE__*/_interopDefaultLegacy(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__default["default"].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();
});
}
exports.difyCompletion = difyCompletion;
exports.setupDifyApi = setupDifyApi;
;