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:
function ChatProvider(props: ChatProviderProps): JSX.ElementProps:
interface ChatProviderProps {
config: ChatConfig; // Required: SDK configuration
children: ReactNode; // Required: Child components
}Returns: JSX.Element (Chat context provider and UI)
Example:
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:
function useChat(): ChatContextValueReturns:
interface ChatContextValue {
messages: Message[];
isLoading: boolean;
error: Error | null;
conversationId: string | null;
sendMessage: (content: string) => Promise<void>;
clearMessages: () => void;
}Example:
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:
function useChatContext(context: ChatContextUpdate): voidPlanned Parameters:
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:
interface ChatConfig {
apiKey: string; // Required: API key for authentication
apiUrl?: string; // Optional: Custom API endpoint URL
debug?: boolean; // Optional: Enable debug mode
}Properties:
| Property | Type | Required | Description |
|---|---|---|---|
apiKey | string | Yes | Unique API key for authentication |
apiUrl | string | No | Custom API endpoint (default: http://localhost:3000/api/v1) |
debug | boolean | No | Enable debug logging (default: false) |
Example:
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:
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:
| Property | Type | Required | Description |
|---|---|---|---|
id | string | Yes | Unique identifier (UUID) |
content | string | Yes | Message text |
role | 'user' | 'assistant' | 'system' | Yes | Who sent the message |
timestamp | Date | Yes | When message was created |
metadata | Record<string, unknown> | No | Additional message metadata |
Example:
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:
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:
| Property | Type | Description |
|---|---|---|
messages | Message[] | All messages in the conversation |
isLoading | boolean | True while sending/receiving message |
error | Error | null | Error object or null if no error |
conversationId | string | null | ID of current conversation |
sendMessage | (content: string) => Promise<void> | Send message function |
clearMessages | () => void | Clear messages function |
Example:
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:
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:
function AIMessage(props: { content: string }): JSX.ElementProps:
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:
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:
// From useChat hook
const { error } = useChat();
// Type is Error | null
if (error instanceof Error) {
console.error('Chat error:', error.message);
}Common Error Messages
| Message | Cause | Solution |
|---|---|---|
| "useChat must be used within a ChatProvider" | Hook used outside provider | Move hook usage inside ChatProvider |
| "HTTP error! status: 401" | Invalid or missing API key | Check API key in config |
| "HTTP error! status: 403" | API key doesn't have permission | Verify key permissions in Admin Dashboard |
| "HTTP error! status: 500" | Backend server error | Check backend logs and status |
| "Response body is not readable" | Network or stream issue | Check 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-streamX-Conversation-Id: <conversation-id>(optional, for new conversations)
Peer Dependencies
The SDK requires the following packages to be installed:
{
"peerDependencies": {
"react": "^18.0.0",
"react-dom": "^18.0.0"
}
}Install them if not already present:
npm install react react-domDependencies
Runtime dependencies included with the SDK:
{
"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
- CommonJS (CJS) -
- TypeScript Definitions:
dist/index.d.ts
Browser Support
Minimum browser versions:
| Browser | Version | Notes |
|---|---|---|
| Chrome | 90+ | Full support |
| Firefox | 88+ | Full support |
| Safari | 14+ | Full support |
| Edge | 90+ | 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
- Installation - Get started
- ChatProvider - Main component
- useChat Hook - Access chat state
- Configuration - Configure options