logoRocketFlow

API Reference - Session Initialization

Complete API reference for RKT Chat Client session initialization

API Reference

This document provides complete API reference for the session initialization functionality in RKT Chat Client.

Types

UseChatOptions

Configuration options for the useChat hook.

interface UseChatOptions {
  chatbot?: {
    id?: string;
    prompt?: string;
    allowedDomains?: string[];
    strictDomain?: boolean;
  };
  baseUrl?: string;
  telemetry?: TelemetryProvider;
  errorTracker?: ErrorTracker;
  onReady?: (sessionId: string) => void;
}

Properties

PropertyTypeRequiredDescription
chatbotChatbotConfigNoChatbot configuration object
baseUrlstringNoBase URL for chat API endpoints
telemetryTelemetryProviderNoTelemetry provider for analytics
errorTrackerErrorTrackerNoError tracking service
onReady(sessionId: string) => voidNoCallback when session is ready

ChatbotConfig

Configuration for the chatbot instance.

interface ChatbotConfig {
  id?: string;
  prompt?: string;
  allowedDomains?: string[];
  strictDomain?: boolean;
}

Properties

PropertyTypeRequiredDescription
idstringNoUnique identifier for the chatbot
promptstringNoSystem prompt for the chatbot
allowedDomainsstring[]NoList of allowed domains for the chatbot
strictDomainbooleanNoWhether to enforce domain restrictions

TelemetryProvider

Interface for telemetry and analytics providers.

interface TelemetryProvider {
  initializeSession: (data: SessionInitData) => void;
  trackEvent: (event: string, properties?: Record<string, any>) => void;
  trackError: (error: Error, context?: Record<string, any>) => void;
}

Methods

MethodParametersDescription
initializeSessiondata: SessionInitDataInitialize a new session with device and user data
trackEventevent: string, properties?: Record<string, any>Track custom events
trackErrorerror: Error, context?: Record<string, any>Track errors with context

SessionInitData

Data structure for session initialization.

interface SessionInitData {
  chatbotId: string;
  sessionId: string;
  deviceInfo?: DeviceInfo;
  userPreferences?: UserPreferences;
}

Properties

PropertyTypeRequiredDescription
chatbotIdstringYesID of the chatbot
sessionIdstringYesUnique session identifier
deviceInfoDeviceInfoNoDevice and browser information
userPreferencesUserPreferencesNoUser preference settings

DeviceInfo

Device and browser information collected during initialization.

interface DeviceInfo {
  userAgent: string;
  language: string;
  languages: string[];
  platform: string;
  cookieEnabled: boolean;
  onLine: boolean;
  screenWidth: number;
  screenHeight: number;
  timezone: string;
  timestamp: string;
}

UserPreferences

User preference settings.

interface UserPreferences {
  theme: "light" | "dark";
  language: string;
  timezone: string;
}

ErrorTracker

Interface for error tracking services.

interface ErrorTracker {
  captureException: (error: Error, context?: Record<string, any>) => void;
  captureMessage: (message: string, level?: 'info' | 'warning' | 'error', context?: Record<string, any>) => void;
}

Methods

MethodParametersDescription
captureExceptionerror: Error, context?: Record<string, any>Capture and report exceptions
captureMessagemessage: string, level?: string, context?: Record<string, any>Capture and report messages

Hook Return Values

useChat Return Type

The useChat hook returns an object with the following properties:

interface UseChatReturn {
  // Session management
  sessionId: string;
  isSessionReady: boolean;
  telemetryInitialized: boolean;
  initializeSession: (sessionId: string) => void;
  
  // Chat functionality
  messages: Message[];
  sendMessage: (message: string, body?: Record<string, any>) => void;
  handleSendMessage: (message: string, body?: Record<string, any>) => void;
  clearMessages: () => void;
  finishSession: () => void;
  
  // Status and control
  status: "idle" | "streaming" | "submitted" | "error";
  stop: () => void;
  setMessages: (messages: Message[]) => void;
  regenerate: () => void;
  onCancel: () => void;
  
  // Status flags
  isChatLoading: boolean;
  isError: boolean;
  errorMessage?: string;
}

Session Management Properties

PropertyTypeDescription
sessionIdstringUnique identifier for the current session
isSessionReadybooleanWhether the session is fully initialized
telemetryInitializedbooleanWhether telemetry has been initialized
initializeSession(sessionId: string) => voidManually initialize a session

Chat Functionality Properties

PropertyTypeDescription
messagesMessage[]Array of chat messages
sendMessage(message: string, body?: Record<string, any>) => voidSend a message to the chat
handleSendMessage(message: string, body?: Record<string, any>) => voidWrapper for sendMessage with telemetry
clearMessages() => voidClear all messages and generate new session
finishSession() => voidFinish the current session

Status and Control Properties

PropertyTypeDescription
statusstringCurrent chat status
stop() => voidStop the current chat operation
setMessages(messages: Message[]) => voidSet the messages array
regenerate() => voidRegenerate the last response
onCancel() => voidCancel the current operation

Status Flags

PropertyTypeDescription
isChatLoadingbooleanWhether chat is currently loading
isErrorbooleanWhether there's an error
errorMessagestring?Error message if there's an error

Methods

initializeSession

Manually initialize a session with telemetry data.

initializeSession(sessionId: string): void

Parameters

ParameterTypeDescription
sessionIdstringThe session ID to initialize

Example

const { initializeSession, sessionId } = useChat(options);

// Manually initialize session
useEffect(() => {
  if (sessionId) {
    initializeSession(sessionId);
  }
}, [sessionId, initializeSession]);

sendMessage

Send a message to the chat with optional body data.

sendMessage(message: string, body?: Record<string, any>): void

Parameters

ParameterTypeDescription
messagestringThe message text to send
bodyRecord<string, any>Optional additional data

Example

const { sendMessage } = useChat(options);

// Send a simple message
sendMessage("Hello, how are you?");

// Send a message with additional data
sendMessage("Hello", { 
  userId: "123", 
  context: "support" 
});

clearMessages

Clear all messages and generate a new session ID.

clearMessages(): void

Example

const { clearMessages } = useChat(options);

// Clear messages and start fresh
const handleNewChat = () => {
  clearMessages();
};

finishSession

Finish the current session and track completion.

finishSession(): void

Example

const { finishSession } = useChat(options);

// Finish session when component unmounts
useEffect(() => {
  return () => {
    finishSession();
  };
}, [finishSession]);

Events

onReady

Callback triggered when the session is fully initialized.

onReady?: (sessionId: string) => void

Parameters

ParameterTypeDescription
sessionIdstringThe initialized session ID

Example

const { sessionId } = useChat({
  // ... other options
  onReady: (sessionId) => {
    console.log(`Session ready: ${sessionId}`);
    // Perform any initialization that depends on the session
    initializeUserPreferences(sessionId);
    trackSessionStart(sessionId);
  },
});

Error Handling

Error Tracking

The session initialization system includes comprehensive error handling:

// Error tracking integration
const errorTracker = {
  captureException: (error: Error, context?: Record<string, any>) => {
    // Send to your error tracking service
    console.error("Exception:", error, context);
  },
  captureMessage: (message: string, level?: string, context?: Record<string, any>) => {
    // Log important messages
    console.log(`[${level}] ${message}`, context);
  },
};

Common Error Scenarios

  1. Telemetry Initialization Failure: Gracefully handled with console logging
  2. Network Errors: Tracked and reported through error tracking
  3. Browser Compatibility: Automatic fallbacks for unsupported features
  4. Session ID Generation: Retry logic for failed generation

Browser Support

FeatureChromeFirefoxSafariEdge
requestIdleCallback✅ 47+✅ 55+✅ 13+✅ 79+
Session Management
Telemetry
Error Handling

Last updated on