Skip to content

API Reference

Complete reference documentation for the Chat SDK React components, hooks, and types.

Table of Contents

Components

ChatProvider

The main provider component that wraps your application and manages chat state.

Signature:

tsx
function ChatProvider(props: ChatProviderProps): JSX.Element

Props:

typescript
interface ChatProviderProps {
  config: ChatConfig;      // Required: SDK configuration
  children: ReactNode;     // Required: Child components
}

Returns: JSX.Element (Chat context provider and UI)

Example:

tsx
import { ChatProvider } from '@cyborg-sdk/react';

function App() {
  return (
    <ChatProvider config={{ apiKey: 'YOUR_API_KEY' }}>
      <YourApp />
    </ChatProvider>
  );
}

Features:

  • Manages chat state (messages, loading, errors)
  • Provides ChatContext to children
  • Automatically renders chat UI
  • Persists conversation IDs to localStorage
  • Handles SSE streaming from backend

Related Documentation: ChatProvider Guide


Hooks

useChat

Access chat state and methods from any component within ChatProvider.

Signature:

tsx
function useChat(): ChatContextValue

Returns:

typescript
interface ChatContextValue {
  messages: Message[];
  isLoading: boolean;
  error: Error | null;
  conversationId: string | null;
  sendMessage: (content: string) => Promise<void>;
  clearMessages: () => void;
}

Example:

tsx
import { useChat } from '@cyborg-sdk/react';

function MyComponent() {
  const { messages, sendMessage, isLoading } = useChat();

  return (
    <div>
      {messages.map(msg => (
        <div key={msg.id}>{msg.content}</div>
      ))}
      <button onClick={() => sendMessage('Hello')} disabled={isLoading}>
        Send
      </button>
    </div>
  );
}

Throws:

  • Error if used outside of ChatProvider

Related Documentation: useChat Hook Guide


useChatContext (Coming Soon)

Planned hook to provide context about current page and user session.

Status: Phase 2 - Not yet implemented

Planned Signature:

tsx
function useChatContext(context: ChatContextUpdate): void

Planned Parameters:

typescript
interface ChatContextUpdate {
  pageData?: {
    currentPage: string;
    description: string;
    [key: string]: unknown;
  };
  sessionData?: {
    userId?: string;
    [key: string]: unknown;
  };
}

Related Documentation: useChatContext Hook Guide


Types

ChatConfig

Configuration object for ChatProvider.

Definition:

typescript
interface ChatConfig {
  apiKey: string;           // Required: API key for authentication
  apiUrl?: string;          // Optional: Custom API endpoint URL
  debug?: boolean;          // Optional: Enable debug mode
}

Properties:

PropertyTypeRequiredDescription
apiKeystringYesUnique API key for authentication
apiUrlstringNoCustom API endpoint (default: http://localhost:3000/api/v1)
debugbooleanNoEnable debug logging (default: false)

Example:

tsx
import type { ChatConfig } from '@cyborg-sdk/react';

const config: ChatConfig = {
  apiKey: 'sk_abc123def456',
  apiUrl: 'https://api.example.com/v1',
  debug: process.env.NODE_ENV === 'development',
};

Message

Represents a chat message.

Definition:

typescript
interface Message {
  id: string;                          // Unique message identifier
  content: string;                     // Message text content
  role: 'user' | 'assistant' | 'system'; // Message sender role
  timestamp: Date;                     // When the message was created
  metadata?: Record<string, unknown>;  // Optional additional data
}

Properties:

PropertyTypeRequiredDescription
idstringYesUnique identifier (UUID)
contentstringYesMessage text
role'user' | 'assistant' | 'system'YesWho sent the message
timestampDateYesWhen message was created
metadataRecord<string, unknown>NoAdditional message metadata

Example:

tsx
import type { Message } from '@cyborg-sdk/react';

const userMessage: Message = {
  id: 'msg-123',
  content: 'Hello!',
  role: 'user',
  timestamp: new Date(),
};

const aiMessage: Message = {
  id: 'msg-124',
  content: 'Hi! How can I help?',
  role: 'assistant',
  timestamp: new Date(),
  metadata: { model: 'claude-3.5-sonnet', tokensUsed: 42 },
};

ChatContextValue

The value provided by ChatContext.

Definition:

typescript
interface ChatContextValue {
  messages: Message[];                   // Array of chat messages
  isLoading: boolean;                    // Whether a message is being processed
  error: Error | null;                   // Error object if present
  conversationId: string | null;         // Current conversation ID
  sendMessage: (content: string) => Promise<void>; // Send a message
  clearMessages: () => void;             // Clear all messages
}

Properties:

PropertyTypeDescription
messagesMessage[]All messages in the conversation
isLoadingbooleanTrue while sending/receiving message
errorError | nullError object or null if no error
conversationIdstring | nullID of current conversation
sendMessage(content: string) => Promise<void>Send message function
clearMessages() => voidClear messages function

Example:

tsx
import { useChat, type ChatContextValue } from '@cyborg-sdk/react';

function Component() {
  const chatState: ChatContextValue = useChat();

  return (
    <div>
      <p>Messages: {chatState.messages.length}</p>
      <p>Loading: {chatState.isLoading}</p>
      {chatState.error && <p>Error: {chatState.error.message}</p>}
    </div>
  );
}

Interfaces

Complete Type Exports

The following types are exported from the main package:

tsx
import {
  // Components
  ChatProvider,

  // Hooks
  useChat,

  // Types
  ChatConfig,
  Message,
  ChatContextValue,

  // Component - low-level
  AIMessage,
} from '@cyborg-sdk/react';

AIMessage Component

Low-level component for rendering AI messages with markdown support.

Signature:

tsx
function AIMessage(props: { content: string }): JSX.Element

Props:

typescript
interface AIMessageProps {
  content: string;  // Markdown-formatted message content
}

Features:

  • Renders markdown with react-markdown
  • Supports GitHub Flavored Markdown (GFM)
  • Syntax highlighting ready
  • Properly styled within chat interface

Example:

tsx
import { AIMessage } from '@cyborg-sdk/react';

function CustomAIMessage() {
  const markdown = `
# Heading
This is **bold** and *italic* text.
- Bullet point 1
- Bullet point 2

\`\`\`javascript
const x = 42;
\`\`\`
  `;

  return <AIMessage content={markdown} />;
}

Error Handling

Error Types

Errors are standard JavaScript Error objects:

typescript
// From useChat hook
const { error } = useChat();

// Type is Error | null
if (error instanceof Error) {
  console.error('Chat error:', error.message);
}

Common Error Messages

MessageCauseSolution
"useChat must be used within a ChatProvider"Hook used outside providerMove hook usage inside ChatProvider
"HTTP error! status: 401"Invalid or missing API keyCheck API key in config
"HTTP error! status: 403"API key doesn't have permissionVerify key permissions in Admin Dashboard
"HTTP error! status: 500"Backend server errorCheck backend logs and status
"Response body is not readable"Network or stream issueCheck network connection

Streaming Response Format

The SDK expects SSE (Server-Sent Events) format from the backend:

data: {"type":"token","fullContent":"Hello"}

data: {"type":"token","fullContent":"Hello world"}

data: {"type":"done","metadata":{"model":"claude-3.5-sonnet"}}

Expected Response Headers:

  • Content-Type: text/event-stream
  • X-Conversation-Id: &lt;conversation-id&gt; (optional, for new conversations)

Peer Dependencies

The SDK requires the following packages to be installed:

json
{
  "peerDependencies": {
    "react": "^18.0.0",
    "react-dom": "^18.0.0"
  }
}

Install them if not already present:

bash
npm install react react-dom

Dependencies

Runtime dependencies included with the SDK:

json
{
  "dependencies": {
    "react-markdown": "^10.1.0",
    "remark-gfm": "^4.0.1"
  }
}

These are automatically installed when you install the SDK.


Build Targets

The SDK is built for the following environments:

  • JavaScript Version: ES2020
  • Module Formats:
    • CommonJS (CJS) - dist/index.js
    • ECMAScript Modules (ESM) - dist/index.mjs
  • TypeScript Definitions: dist/index.d.ts

Browser Support

Minimum browser versions:

BrowserVersionNotes
Chrome90+Full support
Firefox88+Full support
Safari14+Full support
Edge90+Full support

Requires browser support for:

  • ES2020 JavaScript
  • Fetch API
  • LocalStorage API
  • Web Crypto API (for UUID generation)

Package Information

  • Name: @cyborg-sdk/react
  • Latest Version: 0.1.0
  • License: MIT
  • Repository: GitHub

Next Steps

Built with VitePress