UNPKG

@monsoft/davinci-ai

Version:

Davinci AI Client

139 lines (138 loc) 5.37 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.DavinciClient = void 0; const zod_to_json_schema_1 = __importDefault(require("zod-to-json-schema")); const api_1 = require("../../shared/api"); const axios_1 = __importDefault(require("axios")); class DavinciClient { constructor(config) { this.config = config; this.HOST_ADDRESS = this.config.host ?? 'https://api.davincilabs.cloud'; this.headers = { 'Content-Type': 'application/json', 'Davinci-API-Key': this.config.api_key, 'Davinci-Auth-Token': this.config.auth_token, }; } async request(route, payload) { return this.retryRequest(async () => { const url = `${this.HOST_ADDRESS}/${route.path}`; const result = await (0, axios_1.default)({ method: 'POST', url, headers: this.headers, data: payload, }).catch((error) => { throw new Error(`Network request failed: ${error instanceof Error ? error.message : String(error)}`); }); try { return route.output.parse(result.data); } catch (error) { throw new Error(`Failed to validate response data: ${error.message}`); } }); } async requestGet(route, params) { return this.retryRequest(async () => { const url = `${this.HOST_ADDRESS}/${route.path}`; const result = await (0, axios_1.default)({ method: 'GET', url, params, headers: this.headers, }).catch((error) => { throw new Error(`Network request failed: ${error instanceof Error ? error.message : String(error)}`); }); try { return route.output.parse(result.data); } catch (error) { throw new Error(`Failed to validate response data: ${error.message}`); } }); } async generateSuggestionForReply(payload) { return this.retryRequest(async () => { try { const result = await this.request(api_1.messageInSuggestionRoute, payload); console.debug(`Response from Davinci. \nResult: ${JSON.stringify(result)}`); return result; } catch (error) { throw new Error(`Failed to generate suggestion: ${error.message}`); } }); } async logMessageOut(payload) { await this.request(api_1.messageOutRoute, payload); } async conversationAnalyze({ contactId }) { return this.retryRequest(async () => { try { const result = await this.request(api_1.dataMiningMessagesAllRoute, { contactId, }); console.debug(`Response from Davinci Analyzer\n: ${JSON.stringify(result)}`); return result; } catch (error) { throw new Error(`Failed to analyze conversation: ${error.message}`); } }); } async conversationAnalyzeCustomData({ contactId, dataSchema, }) { return this.retryRequest(async () => { try { const response = await this.request(api_1.conversationAnalyzeCustomDataRoute, { contactId, dataSchema: (0, zod_to_json_schema_1.default)(dataSchema, { $refStrategy: 'none', basePath: [], }), }); const data = dataSchema.safeParse(response).data; console.log(`Response from Davinci Analyzer\n: ${JSON.stringify(data)}`); return data; } catch (error) { throw new Error(`Failed to analyze custom data: ${error.message}`); } }); } async retrieveMessageSuggestions(messageId) { return this.retryRequest(async () => { try { const finalPayload = { message_id: messageId, }; const result = await this.requestGet(api_1.messageRetrieveSuggestionsRoute, finalPayload); return result; } catch (error) { throw new Error(`Failed to retrieve message suggestions: ${error.message}`); } }); } async retryRequest(fn, maxRetries = 3, delayMs = 400) { let lastError; for (let attempt = 0; attempt < maxRetries; attempt++) { try { return await fn(); } catch (error) { lastError = error; await new Promise((resolve) => setTimeout(resolve, delayMs * attempt)); console.warn(`Request failed, attempt ${String(attempt)}/${String(maxRetries)}. Retrying...`); } } if (lastError) { throw lastError; } throw new Error('Failed to make request after multiple attempts'); } } exports.DavinciClient = DavinciClient;