Aller au contenu

Forra React SDK

@mirego/forra-react is Forra's React component library and design system: UI components, hooks, and ready-made chat experiences for building AI apps on top of the Forra platform. This page focuses on its chat experience — a complete chat UI/UX that can be embedded as a chatbot widget or a full-page conversation.

Installation

bun install @mirego/forra-react @mirego/forra-api

Required Peer Dependencies:

  • react >= 19.0.0
  • react-dom >= 19.0.0
  • @mirego/forra-api (automatically installed)

Quick Start

1. Basic Integration

import {
  ScoutChat,
  StatelessScoutChatProvider,
  HardcodedAuthProvider,
  setTokenManager,
  AssistantPresentation,
  useScoutChatContext,
} from "@mirego/forra-react";
import "@mirego/forra-react/style.css";

// Configure authentication
setTokenManager({
  getAccessToken: async () => "your-auth-token",
  getRefreshToken: async () => "your-refresh-token",
  setAccessToken: (token) => localStorage.setItem("access_token", token),
  setRefreshToken: (token) => localStorage.setItem("refresh_token", token),
  removeAllTokens: () => {
    localStorage.removeItem("access_token");
    localStorage.removeItem("refresh_token");
  },
});

const ChatComponent = () => {
  const { assistant, assistantQueryIsLoading, sendMessage, messages } =
    useScoutChatContext();

  const onStarterPromptSelect = (starter: string) => {
    sendMessage([{ role: "user", content: starter }]);
  };

  return (
    <ScoutChat
      showNewConversationPresentation={!messages.length}
      maxWidth="100%"
      newConversationPresentation={
        <AssistantPresentation
          assistant={assistant}
          assistantIsLoading={assistantQueryIsLoading}
          onStarterPromptSelect={onStarterPromptSelect}
        />
      }
    />
  );
};

const App = () => (
  <HardcodedAuthProvider
    user={{
      id: "user-123",
      firstName: "John",
      lastName: "Doe",
      picture_url: "/avatar.png",
    }}
  >
    <StatelessScoutChatProvider
      baseUrl="https://your-forra-api.com"
      assistantId="your-assistant-id"
      language="en"
    >
      <ChatComponent />
    </StatelessScoutChatProvider>
  </HardcodedAuthProvider>
);

2. Embedded Widget

import { ScoutChat, StatelessScoutChatProvider } from "@mirego/forra-react";
import "@mirego/forra-react/style.css";

const ChatWidget = () => (
  <div
    style={{
      width: "400px",
      height: "600px",
      borderRadius: "12px",
      overflow: "hidden",
    }}
  >
    <StatelessScoutChatProvider
      baseUrl="https://your-api.com"
      assistantId="assistant-id"
      language="en"
      theme="light"
    >
      <ScoutChat maxWidth="100%" />
    </StatelessScoutChatProvider>
  </div>
);

Adding System Messages

You can provide a system message to guide the AI assistant's behavior using the systemMessage prop:

const ChatWidgetWithSystemMessage = () => {
  const systemMessage = `You are a helpful customer support assistant. 
Always be polite and professional in your responses. 
When users ask about pricing, direct them to our pricing page.`;

  return (
    <StatelessScoutChatProvider
      baseUrl="https://your-api.com"
      assistantId="assistant-id"
      language="en"
      systemMessage={systemMessage}
    >
      <ScoutChat maxWidth="100%" />
    </StatelessScoutChatProvider>
  );
};

Core Components

ScoutChat

The main chat interface component that renders the complete chat experience.

interface ScoutChatProps {
  maxWidth?: string;
  innerHeader?: React.ReactNode;
  outerHeader?: React.ReactNode;
  showNewConversationPresentation?: boolean;
  newConversationPresentation?: React.ReactNode;
  loadingSpinner?: React.ReactNode;
  realtimeTalkEnabled?: boolean;
  onRealtimeTalkClick?: () => void;
}

Example:

<ScoutChat
  maxWidth="800px"
  innerHeader={<CustomHeader />}
  showNewConversationPresentation={true}
  realtimeTalkEnabled={true}
  onRealtimeTalkClick={() => console.log("Voice chat requested")}
/>

Providers

StatelessScoutChatProvider

For embedded chat experiences without conversation persistence.

interface StatelessScoutChatProviderProps {
  children: React.ReactNode;
  baseUrl: string;
  assistantId?: string;
  mentionAssistantEnabled?: boolean;
  initialMessages?: ConversationMessage[];
  language: "en" | "fr";
  theme?: "light" | "dark";
  forceModelId?: string;
  systemMessage?: string;
  tools?: Record<string, ToolDefinition>;
}

ConversationScoutChatProvider

For chat within existing conversation contexts. Also supports custom tools like StatelessScoutChatProvider.

(API Reference: ConversationScoutChatProvider)

interface ConversationScoutChatProviderProps {
  children: React.ReactNode;
  conversationId: string;
  baseUrl: string;
  language: "en" | "fr";
  theme?: "light" | "dark";
  tools?: Record<string, ToolDefinition>;
}

UI Components

For a complete reference of all available UI components, see the Forra Chat Reference.

Hooks

For a complete reference of all available hooks, see the Forra Chat Reference.

Custom Functions (Tools)

The Forra React Chat SDK supports custom functions (also called tools) that allow the AI assistant to interact with your application's data and functionality. This enables powerful integrations where the AI can perform actions beyond just text conversation.

Basic Custom Functions Setup

Custom functions are passed to the StatelessScoutChatProvider via the tools prop as ToolDefinition objects. Each function must include:

  • description: What the function does
  • callable: The actual function to execute
  • params: Array of parameter (JSON Schema) definitions
import { StatelessScoutChatProvider, ToolDefinition } from "@mirego/forra-react";

  const tools: Record<string, ToolDefinition> = {
    getCurrentTime: {
      description: 'Gets the current time in a specific timezone',
      callable: getCurrentTime,
      params: [
        { 
          name: 'timezone', 
          type: 'string', 
          description: 'Timezone identifier (e.g., "America/New_York")' 
        }
      ],
    },
    searchDocuments: {
      description: 'Searches through documents by keyword',
      callable: searchDocuments,
      params: [
        { name: 'query', type: 'string', description: 'Search query' },
        { name: 'limit', type: 'number', description: 'Maximum results to return' }
      ],
    }
  };

  const getCurrentTime = (args) => {
    const { timezone } = args;
    return {
      success: true,
      currentTime: new Date().toLocaleString("en-US", { timeZone: timezone })
    };
  };

  const searchDocuments = async (args) => {
    const { query, limit = 10 } = args;
    try {
      const results = await myDocumentSearchAPI(query, limit);
      return {
        success: true,
        results: results
      };
    } catch (error) {
      return {
        success: false,
        message: error.message
      };
    }
  };

  return (
    <StatelessScoutChatProvider
      baseUrl="https://your-api.com"
      assistantId="assistant-id"
      language="en"
      tools={tools}
    >
      <ScoutChat />
    </StatelessScoutChatProvider>
  );
};

Theming & Styling

Theme Configuration

The SDK supports light and dark themes with CSS custom properties.

// Set theme programmatically
const { setThemePreference } = useTheme();
setThemePreference("dark");

// Or pass as prop
<StatelessScoutChatProvider theme="dark">
  <ScoutChat />
</StatelessScoutChatProvider>;

Custom Styling

The SDK uses CSS custom properties that can be overridden:

:root {
  --color-accent: #b5a6ff;
  --color-accent-inverse: #292929 !important;
  --color-background: #f7f7fa;
  --color-surface-01: #ffffff;
  --color-surface-02: #f0f0f0;
  --color-text-primary: #000000;
  --color-text-secondary: #666666;
}

Real-World Examples

Chatbot Widget

const ChatbotWidget = ({ isOpen, onClose }) => {
  if (!isOpen) return null;

  return (
    <div className="chatbot-overlay">
      <div className="chatbot-container">
        <StatelessScoutChatProvider
          baseUrl={process.env.REACT_APP_FORRA_API_URL}
          assistantId={process.env.REACT_APP_ASSISTANT_ID}
          language="en"
          theme="light"
        >
          <ScoutChat
            maxWidth="100%"
            outerHeader={
              <div className="chat-header">
                <h3>Customer Support</h3>
                <button onClick={onClose}>×</button>
              </div>
            }
          />
        </StatelessScoutChatProvider>
      </div>
    </div>
  );
};

Full-Page Chat Application

const ChatApp = () => (
  <div className="chat-app">
    <HardcodedAuthProvider user={currentUser}>
      <ScoutAppProvider
        baseUrl="https://api.forra.com"
        language="en"
        theme="dark"
      >
        <div className="app-layout">
          <aside className="sidebar">
            <ConversationList />
          </aside>
          <main className="chat-main">
            <ScoutChat
              maxWidth="none"
              innerHeader={<ConversationHeader />}
              realtimeTalkEnabled={true}
            />
          </main>
        </div>
      </ScoutAppProvider>
    </HardcodedAuthProvider>
  </div>
);

Multi-Language Support

const MultiLanguageChat = () => {
  const [language, setLanguage] = useState("en");

  return (
    <StatelessScoutChatProvider
      language={language}
      assistantId="multilingual-assistant"
    >
      <div className="language-selector">
        <button onClick={() => setLanguage("en")}>English</button>
        <button onClick={() => setLanguage("fr")}>Français</button>
      </div>
      <ScoutChat />
    </StatelessScoutChatProvider>
  );
};

Best Practices

1. Provider Hierarchy

Always wrap your chat components in the correct provider hierarchy:

// Correct hierarchy
<HardcodedAuthProvider user={user}>
  <StatelessScoutChatProvider {...config}>
    <YourChatComponent />
  </StatelessScoutChatProvider>
</HardcodedAuthProvider>

2. Error Handling

Implement proper error boundaries and error handling:

import { ErrorBoundary } from "react-error-boundary";

<ErrorBoundary fallback={<ChatErrorFallback />}>
  <ScoutChat />
</ErrorBoundary>;

Forra design system components

Design-system components live under components/forra and are published for external apps. Prefer these over the older root-level UI primitives when building custom UI.

Import the stylesheet once:

import "@mirego/forra-react/style.css";

Subpath (recommended for tree-shaking and to avoid name clashes with legacy exports):

import { Button, Icon, Input } from "@mirego/forra-react/components/forra";

<Button variant="primary">Save</Button>
<Icon name="Search" size="md" />

Namespaced root export (same components, grouped under Forra):

import { Forra } from "@mirego/forra-react";

<Forra.Button variant="primary">Save</Forra.Button>
<Forra.Icon name="Search" size="md" />

Do not import deep file paths such as @mirego/forra-react/components/forra/Button/Button from the published package — only the root barrel and @mirego/forra-react/components/forra are part of the public export map.

Troubleshooting

Common Issues

Chat not rendering

  • Ensure all required providers are present
  • Check authentication token is valid
  • Verify assistant ID is correct

Styling issues

  • Import the CSS file: import '@mirego/forra-react/style.css'
  • Check for CSS conflicts with your application styles
  • Verify container has proper dimensions

Authentication errors

  • Ensure setTokenManager is called before rendering
  • Check token manager implementation
  • Verify API base URL is correct

TypeScript errors

  • Ensure React types are installed: @types/react
  • Check peer dependency versions match requirements

The Forra React Chat SDK provides a complete, customizable chat experience that can be easily integrated into any React application. Whether you need a simple chatbot widget or a full-featured conversational AI interface, the SDK offers the flexibility and features to meet your requirements.