import EventSource from "react-native-sse"; import AsyncStorage from "@react-native-async-storage/async-storage"; import type { OperoChatMessage, OperoChatError, OperoApiFilters, } from "../types"; import { DEFAULT_API_ENDPOINT } from "../utils/constants"; import { log } from "../utils/helpers"; export class OperoChatAPI { private apiEndpoint: string; private apiKey: string; private userEmail?: string; private userRole?: string; private userIdentifier: string | null = null; constructor( apiEndpoint: string = DEFAULT_API_ENDPOINT, apiKey: string, userEmail?: string, userRole?: string, ) { this.apiEndpoint = apiEndpoint; this.apiKey = apiKey; this.userEmail = userEmail; this.userRole = userRole; // Initialize user identifier for conversation persistence this.initializeUserIdentifier(); } private async initializeUserIdentifier(): Promise { if (this.userEmail) { this.userIdentifier = this.userEmail; return; } try { let sdkUserId = await AsyncStorage.getItem("@opero:user_id"); if (!sdkUserId) { sdkUserId = `sdk_${Date.now()}_${Math.random().toString(36).substring(2, 11)}`; await AsyncStorage.setItem("@opero:user_id", sdkUserId); } this.userIdentifier = sdkUserId; } catch (error) { log("Failed to initialize user identifier", "error"); this.userIdentifier = null; } } // Getters for analytics access get getUserEmail(): string | undefined { return this.userEmail; } get getApiEndpoint(): string { return this.apiEndpoint; } get getUserIdentifier(): string | null { return this.userIdentifier; } async sendMessage( messages: Array<{ role: string; content: string }>, conversationId?: string, filters?: OperoApiFilters, onChunk?: (chunk: string) => void, onError?: (error: OperoChatError) => void, onProgress?: (progress: string) => void, onSources?: (sources: any[]) => void, onMessageId?: (messageId: string, role: "user" | "assistant") => void, ): Promise<{ conversationId?: string; fullMessage: string }> { return new Promise((resolve, reject) => { let fullMessage = ""; let newConversationId: string | undefined; let eventSource: EventSource | null = null; let isResolved = false; const cleanup = () => { if (eventSource) { eventSource.removeAllEventListeners(); eventSource.close(); eventSource = null; } }; const resolvePromise = (result: { conversationId?: string; fullMessage: string; }) => { if (!isResolved) { isResolved = true; cleanup(); resolve(result); } }; const rejectPromise = (error: OperoChatError) => { if (!isResolved) { isResolved = true; cleanup(); reject(error); } }; try { const headers: Record = { "Content-Type": "application/json", "X-API-Key": this.apiKey, ...(this.userIdentifier && { "X-User-Id": this.userIdentifier }), ...(this.userEmail && { "X-User-Email": this.userEmail }), ...(this.userRole && { "X-User-Role": this.userRole }), }; const requestBody = { messages: messages, stream: true, conversationId, ...(filters && { filters }), }; eventSource = new EventSource(`${this.apiEndpoint}/chat/completions`, { headers, method: "POST", body: JSON.stringify(requestBody), pollingInterval: 0, // Disable reconnections }); eventSource.addEventListener("open", () => { log("SSE connection opened", "debug"); }); eventSource.addEventListener("message", (event) => { try { if (event.data === "[DONE]") { resolvePromise({ conversationId: newConversationId, fullMessage, }); return; } const parsed = JSON.parse(event.data || "{}"); // Handle conversation ID from SSE stream // Note: We use SSE stream instead of response headers because EventSource // cannot access response headers. Web apps can use X-Conversation-Id header, // but Native SDK must use this streamed approach if (parsed.type === "conversation_id" && parsed.content) { newConversationId = parsed.content; return; } // Handle message ID from SSE stream if (parsed.type === "message_id" && parsed.content && parsed.role) { onMessageId?.(parsed.content, parsed.role); return; } if (parsed.type === "progress") { onProgress?.(parsed.content); return; } if (parsed.type === "sources") { onSources?.(parsed.content || []); return; } if (parsed.choices?.[0]?.delta?.content) { const content = parsed.choices[0].delta.content; fullMessage += content; onChunk?.(content); } } catch (e) { log(`Error parsing event data: ${e}`, "debug"); // Skip invalid JSON } }); eventSource.addEventListener("error", (event) => { // Try to parse error response let errorMessage = "Failed to send message"; let errorType: "auth" | "api" | "validation" | "network" = "network"; let errorDetails: any = event; // Check if we have HTTP status information if (event.type === "error" && event.message) { try { const errorInfo = JSON.parse(event.message); if (errorInfo.status) { switch (errorInfo.status) { case 401: errorMessage = errorInfo.detail || "Invalid API key or credentials."; errorType = "auth"; break; case 403: errorMessage = errorInfo.detail || "You do not have permission to access this resource."; errorType = "auth"; break; case 422: if (Array.isArray(errorInfo.detail)) { const validationErrors = errorInfo.detail .map((err: any) => { const location = err.loc ? err.loc.join(".") : "unknown"; return `${location}: ${err.msg}`; }) .join("; "); errorMessage = `Validation error: ${validationErrors}`; errorType = "validation"; } else if ( typeof errorInfo.detail === "string" && errorInfo.detail.includes("Invalid filters") ) { errorMessage = `Filter validation error: ${errorInfo.detail}`; errorType = "validation"; } else { errorMessage = errorInfo.detail || "Bad Request: Invalid request data."; } break; case 429: errorMessage = errorInfo.detail || "Rate limit exceeded. Please try again later."; break; case 500: errorMessage = errorInfo.detail || "Internal server error. Please try again later."; break; default: errorMessage = errorInfo.detail || `HTTP ${errorInfo.status}: ${errorInfo.statusText}`; } errorDetails = errorInfo; } } catch (parseError) { // Couldn't parse error info, use default network error log( `Could not parse EventSource error info: ${parseError}`, "error", ); errorMessage = "Network error occurred"; errorType = "network"; } } const error: OperoChatError = { type: errorType, message: errorMessage, details: errorDetails, }; log(`EventSource Error: ${errorMessage}`, "error"); onError?.(error); rejectPromise(error); }); } catch (error) { const networkError: OperoChatError = { type: "network", message: error instanceof Error ? error.message : "Unknown error occurred", details: error, }; onError?.(networkError); rejectPromise(networkError); } }); } async checkConnectivity(): Promise { try { log(`Checking API connectivity to ${this.apiEndpoint}`, "debug"); const response = await fetch(`${this.apiEndpoint}/`, { method: "GET" }); if (!response.ok) { throw new Error(`HTTP ${response.status}: ${response.statusText}`); } log("API connectivity check successful", "debug"); return true; } catch (error) { log(`API connectivity check failed: ${error}`, "error"); return false; } } async generateTitle( messages: OperoChatMessage[], conversationId: string, ): Promise { try { const headers: Record = { "Content-Type": "application/json", "X-API-Key": this.apiKey, ...(this.userIdentifier && { "X-User-Id": this.userIdentifier }), ...(this.userEmail && { "X-User-Email": this.userEmail }), ...(this.userRole && { "X-User-Role": this.userRole }), }; const response = await fetch(`${this.apiEndpoint}/generate-title`, { method: "POST", headers, body: JSON.stringify({ messages: messages.map((msg) => ({ role: msg.role, content: msg.content, })), conversation_id: conversationId, }), }); if (!response.ok) { throw new Error(`HTTP ${response.status}: ${response.statusText}`); } const data = await response.json(); return data.title || "New Conversation"; } catch (error) { log(`Error generating title: ${error}`, "warn"); return "New Conversation"; } } /** * Add or update a reaction to a message */ async addReaction( messageId: string, reactionType: "thumbs_up" | "thumbs_down", ): Promise { const headers: Record = { "Content-Type": "application/json", "X-API-Key": this.apiKey, ...(this.userIdentifier && { "X-User-Id": this.userIdentifier }), ...(this.userEmail && { "X-User-Email": this.userEmail }), ...(this.userRole && { "X-User-Role": this.userRole }), }; const response = await fetch( `${this.apiEndpoint}/messages/${messageId}/reactions`, { method: "POST", headers, body: JSON.stringify({ reaction_type: reactionType }), }, ); if (!response.ok) { const errorData = await response.json().catch(() => ({})); throw new Error( errorData.detail || `Failed to add reaction: ${response.statusText}`, ); } } /** * Remove a reaction from a message */ async removeReaction(messageId: string): Promise { const headers: Record = { "X-API-Key": this.apiKey, ...(this.userIdentifier && { "X-User-Id": this.userIdentifier }), ...(this.userEmail && { "X-User-Email": this.userEmail }), ...(this.userRole && { "X-User-Role": this.userRole }), }; const response = await fetch( `${this.apiEndpoint}/messages/${messageId}/reactions`, { method: "DELETE", headers, }, ); if (!response.ok) { const errorData = await response.json().catch(() => ({})); throw new Error( errorData.detail || `Failed to remove reaction: ${response.statusText}`, ); } } }