UNPKG

doc_chat_ai

Version:

Backend SDK for ChatAI - Simple and efficient communication with ChatAI API

171 lines 6.45 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.ChatAIClient = void 0; const node_fetch_1 = __importDefault(require("node-fetch")); const types_1 = require("./types"); class ChatAIClient { constructor(config) { this.apiKey = config.apiKey; this.timeout = config.timeout || 30000; this.origin = config.origin || "*"; this.customHeaders = config.headers || {}; if (!this.apiKey) { throw new types_1.ChatAIError("API key is required"); } } /** * Send a chat message and get a complete response */ async chat(query, options = {}) { const requestBody = { apikey: this.apiKey, query: query, stream: false, ...(options.sessionId && { sessionId: options.sessionId }), ...(options.model && { model: options.model }), ...(options.temperature !== undefined && { temperature: options.temperature, }), ...(options.maxTokens && { maxTokens: options.maxTokens }), ...(options.context && { context: options.context }), ...(options.metadata && { metadata: options.metadata }), }; const url = `https://chatai.abstraxn.com/api/v1/chat/?apikey=${this.apiKey}`; const headers = { "Content-Type": "application/json", Accept: "application/json", Origin: this.origin, ...this.customHeaders, }; try { const response = await (0, node_fetch_1.default)(url, { method: "POST", headers, body: JSON.stringify(requestBody), timeout: this.timeout, }); if (!response.ok) { const errorText = await response.text(); throw new types_1.ChatAIError(`API request failed: ${response.status} - ${errorText}`, response.status, errorText); } const data = (await response.json()); if (data.error) { throw new types_1.ChatAIError(`API returned error: ${data.response || "Unknown error"}`); } return data; } catch (error) { if (error instanceof types_1.ChatAIError) { throw error; } throw new types_1.ChatAIError(`Network error: ${error instanceof Error ? error.message : "Unknown error"}`); } } /** * Send a chat message and get a streaming response */ async *chatStream(query, options = {}) { const requestBody = { apikey: this.apiKey, query: query, stream: true, ...(options.sessionId && { sessionId: options.sessionId }), ...(options.model && { model: options.model }), ...(options.temperature !== undefined && { temperature: options.temperature, }), ...(options.maxTokens && { maxTokens: options.maxTokens }), ...(options.context && { context: options.context }), ...(options.metadata && { metadata: options.metadata }), }; const url = `https://chatai.abstraxn.com/api/v1/chat/?apikey=${this.apiKey}`; const headers = { "Content-Type": "application/json", Accept: "text/event-stream", Origin: this.origin, ...this.customHeaders, }; try { const response = await (0, node_fetch_1.default)(url, { method: "POST", headers, body: JSON.stringify(requestBody), timeout: this.timeout, }); if (!response.ok) { const errorText = await response.text(); throw new types_1.ChatAIError(`API request failed: ${response.status} - ${errorText}`, response.status, errorText); } if (!response.body) { throw new types_1.ChatAIError("No response body received"); } yield* this.parseSSE(response.body); } catch (error) { if (error instanceof types_1.ChatAIError) { throw error; } throw new types_1.ChatAIError(`Network error: ${error instanceof Error ? error.message : "Unknown error"}`); } } /** * Parse Server-Sent Events (SSE) stream */ async *parseSSE(body) { const decoder = new TextDecoder(); let buffer = ""; for await (const chunk of body) { buffer += decoder.decode(chunk, { stream: true }); const lines = buffer.split("\n"); buffer = lines.pop() || ""; for (const line of lines) { if (line.startsWith("data: ")) { const data = line.slice(6).trim(); if (data) { try { const parsed = JSON.parse(data); yield parsed; } catch (e) { // Skip malformed JSON console.warn("Failed to parse SSE data:", data); } } } } } // Process any remaining data in buffer if (buffer.trim()) { const lines = buffer.split("\n"); for (const line of lines) { if (line.startsWith("data: ")) { const data = line.slice(6).trim(); if (data) { try { const parsed = JSON.parse(data); yield parsed; } catch (e) { console.warn("Failed to parse SSE data:", data); } } } } } } /** * Get client configuration (for debugging) */ getConfig() { return { timeout: this.timeout, origin: this.origin, headers: { ...this.customHeaders }, }; } } exports.ChatAIClient = ChatAIClient; //# sourceMappingURL=client.js.map