Skip to content

Repository files navigation

Aura Voyager

npm downloads npm monthly downloads

Check out the download trends.

A production-ready AI agent SDK for React applications with plug-and-play chat UI, API integration, and an intelligent interaction layer.

Features

  • Plug-and-Play Chat UI: Beautiful, modern chat component ready to use.
  • Floating Popup Widget: Drop-in popup chat for instant integration.
  • Feedback Collection: Built-in feedback component to gather user insights on response quality.
  • AI Integration: OpenAI and NVIDIA NIM compatible API with a native mock mode for development.
  • Streaming Responses: Real-time server-sent events (SSE) support for progressive text rendering.
  • Markdown & Syntax Highlighting: Native support for Markdown formatting and code block highlighting via react-markdown and highlight.js.
  • Smart Memory Management: Automatic chat history with persistent storage.
  • Theme Support: Built-in light and dark themes.
  • Fully Responsive: Adapts seamlessly perfectly across mobile, tablet, and desktop viewports.
  • TypeScript First: Full type safety and excellent IDE support.
  • Context Aware: Configure conversation context dynamically for personalized responses.
  • Zero Config: Works out of the box with sensible enterprise-grade defaults.

Installation

npm install aura-voyager

Explanation: This command downloads and installs the aura-voyager SDK and its peer dependencies into your node_modules directory, making it available for import in your React application.

Quick Start

Basic Usage

import { AuraChat } from 'aura-voyager';

export default function App() {
  return (
    <AuraChat
      apiKey="sk-your-api-key"
      provider="openai"
      theme="dark"
      placeholder="Ask me anything..."
    />
  );
}

Explanation: The <AuraChat /> component is a fully-styled, plug-and-play chat interface. By providing your exact API key and selecting the target provider (e.g., openai), it automatically handles user inputs, renders responses, manages chat histories, and updates the UI using internal state hooks.

NVIDIA NIM Support

Aura Voyager natively supports NVIDIA NIM models out of the box. Simply set the provider prop to nvidia.

<AuraChat
  apiKey="nvapi-your-nvidia-nim-key"
  provider="nvidia"
  // Defaults to meta/llama3-70b-instruct
  model="google/gemma-2-9b-it" 
/>

Explanation: Setting the provider attribute to nvidia instructs the SDK to route all requests to NVIDIA's NIM endpoints. You can also explicitly assign an NVIDIA catalog model name, enabling enterprise-scale models efficiently within the same component constraint.

Using the Hook

For headless integration, utilize the useAuraVoyager hook which natively handles streaming states and text chunks.

import { useAuraVoyager } from 'aura-voyager';
import ReactMarkdown from 'react-markdown';

export default function MyComponent() {
  const {
    messages,
    loading,
    error,
    sendMessage,
    clearMessages
  } = useAuraVoyager({
    apiKey: 'sk-your-api-key',
    provider: 'openai'
  });

  return (
    <div>
      {messages.map(msg => (
        <div key={msg.id} className={`message-${msg.role}`}>
          <strong>{msg.role}:</strong> 
          <ReactMarkdown>{msg.content}</ReactMarkdown>
        </div>
      ))}
      {loading && <p>Thinking...</p>}
      {error && <p>Error: {error.message}</p>}
    </div>
  );
}

Explanation: Utilizing the useAuraVoyager hook allows deeper integration and absolute layout control. In this example, we map over the internal messages array manually, rendering each model chunk progressively and safely parsing the text strings using ReactMarkdown to support formatting elements natively.

Using the Popup Widget

import { AuraPopup } from 'aura-voyager';

export default function App() {
  return (
    <div className="app">
      <h1>My Site</h1>
      <AuraPopup 
        apiKey="sk-..."
        provider="openai"
        title="AI Assistant"
        position="bottom-right"
      />
    </div>
  );
}

Integration with Non-React Applications

Aura Voyager provides a helper function to easily mount the chat component into any web application (Vanilla JS, Vue, Svelte, etc.) using a simple mounting function.

Standard Installation

  1. Install the package:

    npm install aura-voyager
  2. Mount the chat:

    import { mountAuraChat } from 'aura-voyager';
    import 'aura-voyager/style.css';
    
    const chat = mountAuraChat('chat-container', {
      config: {
        apiKey: 'sk-your-api-key',
        provider: 'openai'
      },
      theme: 'dark',
      title: 'Aura Support'
    });
    
    // To cleanup later
    // chat.unmount();

CDN / HTML Script Tag

You can also use Aura Voyager directly in your HTML without a build step.

<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="https://unpkg.com/aura-voyager/dist/style.css">
</head>
<body>
    <div id="chat-root" style="height: 600px; width: 400px;"></div>

    <script src="https://unpkg.com/react@18/umd/react.production.min.js"></script>
    <script src="https://unpkg.com/react-dom@18/umd/react-dom.production.min.js"></script>
    <script src="https://unpkg.com/aura-voyager/dist/index.umd.js"></script>

    <script>
        const { mountAuraChat } = AuraVoyager;
        
        mountAuraChat('chat-root', {
            config: {
                apiKey: 'your-api-key',
                provider: 'openai'
            },
            theme: 'light',
            title: 'CDN Chat'
        });
    </script>
</body>
</html>

Advanced Usage

Using an Existing Agent Instance

If you want to control the AuraVoyager instance outside of the UI:

import { AuraVoyager, AuraChat } from 'aura-voyager';

const agent = new AuraVoyager({ apiKey: '...' });

function App() {
  return <AuraChat agent={agent} />;
}

Collecting User Feedback

import { AuraFeedback } from 'aura-voyager';
import { useAuraVoyager } from 'aura-voyager';

export default function App() {
  const { messages, sendMessage } = useAuraVoyager({
    apiKey: 'sk-your-api-key'
  });

  const handleFeedbackSubmit = async (feedback) => {
    // Send feedback to your backend
    await fetch('/api/feedback', {
      method: 'POST',
      body: JSON.stringify(feedback)
    });
  };

  return (
    <>
      {/* Your chat component */}
      <AuraChat {...} />
      
      {/* Feedback collection */}
      <AuraFeedback 
        messages={messages}
        onSubmitFeedback={handleFeedbackSubmit}
        theme="dark"
      />
    </>
  );
}

Explanation: The <AuraFeedback /> component captures user satisfaction ratings, optional comments, and email addresses. It integrates seamlessly with your chat interface, allowing you to gather insights on response quality and improve your AI models over time.

Using the Core SDK

import { AuraVoyager } from 'aura-voyager';

const agent = new AuraVoyager({
  apiKey: 'sk-your-api-key',
  provider: 'openai',
  model: 'gpt-4',
  systemPrompt: 'You are a helpful assistant.'
});

// Send a stream and handle chunks
const response = await agent.askStream('What is the capital of France?', (chunk) => {
  console.log('Streaming chunk:', chunk);
});
console.log('Final response:', response);

// Set context for personalized responses
agent.setContext('User is a software developer');

// Manage memory
agent.setMemory(true); // Enable chat history
const messages = agent.getMessages();

Explanation: The core SDK revolves around the AuraVoyager object wrapper. As shown, calling .askStream registers a callback to receive incoming Server-Sent Event (SSE) token chunks in real time, granting direct control over system prompts and internal application memory states independent of React hooks.

API Configuration

Environment Variables

Create a .env file in your project:

VITE_API_KEY=sk-your-api-key
VITE_PROVIDER=openai

Explanation: Storing definitions in your .env protects sensitive values during development. The VITE_API_KEY ensures your private token is dynamically pulled into local builds safely without hardcoding.

Then use it:

<AuraChat
  apiKey={import.meta.env.VITE_API_KEY}
  provider={import.meta.env.VITE_PROVIDER}
/>

Explanation: Accessing import.meta.env dynamically imports your pre-defined global variables into the SDK properties, maintaining operational security standards recommended by modern build tools like Vite.

Mock Mode (Development)

Use apiKey="mock" to test local workflows without an external API key or internet connection:

<AuraChat apiKey="mock" /> // Uses local mock responses

Explanation: Supplying the literal string "mock" as an API key bypasses all HTTP pipeline logic. The internal SDK network client simulates network delays and yields static fallback responses, avoiding API quota expenses during UI prototyping phases.

Component Props

AuraChat

interface AuraChatProps {
  // Pass either apiKey (to auto-create agent) or agent (to use existing instance)
  agent?: AuraVoyager;               // Pre-configured agent instance
  apiKey?: string;                   // API key for auto-created agent

  // Optional
  provider?: 'openai' | 'anthropic' | 'gemini' | 'groq' | 'cohere' | 'nvidia' | 'custom' | 'mock'; // AI Provider
  apiEndpoint?: string;              // Custom API endpoint override
  model?: string;                    // AI model override
  systemPrompt?: string;             // Custom system prompt configuration
  theme?: 'light' | 'dark';          // UI theme (default: 'light')
  placeholder?: string;              // Input placeholder text
  title?: string;                    // Chat header title
  showTypingAnimation?: boolean;     // Show typing animation indicator
  onMessageSent?: (msg: string) => void; // Callback hook when message sent
  onError?: (error: Error) => void;  // Callback hook when error occurs
  initialMessages?: Array<{ role: 'user' | 'assistant'; content: string }>;
  /** Primary accent color for UI elements (default: #667eea) */
  primaryColor?: string;
  /** Secondary accent color for gradients (default: #764ba2) */
  secondaryColor?: string;
}

Explanation: The AuraChatProps TypeScript schema describes all officially supported attributes assignable to the component. Properties handle everything from API overriding to cosmetic adjustments (such as placeholder wording and themes).

AuraPopup

Floating widget designed for easy application integration.

interface AuraPopupProps extends AuraChatProps {
  position?: 'bottom-right' | 'bottom-left' | 'top-right' | 'top-left'; // Layout position
  onClose?: () => void;              // Callback hook when close button clicked
}

Explanation: Built on top of AuraChatProps, the popup attributes structure introduces additional layout definitions, assigning constraints like edge position and establishing the onClose callback hook.

AuraFeedback

Feedback collection component for gathering user insights on response quality.

interface AuraFeedbackProps {
  messages?: Message[];                              // Chat messages context for feedback
  onSubmitFeedback?: (feedback: FeedbackSubmission) => Promise<void>; // Callback when feedback submitted
  theme?: 'light' | 'dark';                          // UI theme (default: 'light')
  /** Primary accent color for UI elements (default: #667eea) */
  primaryColor?: string;
  /** Secondary accent color for gradients (default: #764ba2) */
  secondaryColor?: string;
}

interface FeedbackSubmission {
  rating: 'positive' | 'negative';                   // User satisfaction rating
  comment?: string;                                  // Optional feedback comment
  email?: string;                                    // Optional user email
  messages?: Message[];                              // Associated conversation
  timestamp: number;                                 // Submission timestamp
}

Explanation: The AuraFeedback component enables users to rate responses, provide comments, and share contact information. It's designed for integration with existing chat interfaces to capture quality metrics and user sentiment data for continuous improvement.

Hook API

useAuraVoyager

const {
  messages,           // Array of Message objects
  loading,            // Boolean - request in progress
  error,              // Error object or null
  sendMessage,        // (msg: string) => Promise<void>
  stopGeneration,     // () => void — aborts streaming response
  clearMessages,      // () => void
  setContext,         // (ctx: string) => void
  setMemory,          // (enabled: boolean) => void
  agent               // AuraVoyager | null — underlying agent instance
} = useAuraVoyager(options);

The hook accepts either an apiKey (to auto-create an agent) or a pre-configured agent instance:

// Option 1: Auto-create agent from config
const { sendMessage } = useAuraVoyager({ apiKey: 'sk-...', provider: 'openai' });

// Option 2: Pass existing agent instance
const agent = new AuraVoyager({ apiKey: 'sk-...' });
const { sendMessage } = useAuraVoyager({ agent });

Types

import type {
  Message,              // Chat message protocol object
  AuraVoyagerConfig,    // SDK configuration structure
  MemoryConfig,         // Memory configuration options
  APIResponse,          // External API response structure
  ConversationContext,  // Session context metadata
  UseAuraVoyagerOptions, // Hook configuration options
  UseAuraVoyagerReturn, // Hook return signature
  AuraChatProps,        // Chat component properties
  AuraPopupProps,       // Popup component properties
  AuraFeedbackProps,    // Feedback component properties
  FeedbackSubmission,   // Feedback submission structure
  MountAuraChatOptions  // Non-React mount options
} from 'aura-voyager';

Explanation: Importable TypeScript interfaces allow type-safe validation enforcing standard shapes. Enforcing strict schema guidelines ensures reliable API interaction mappings over unpredictable request objects.

mountAuraChat

Mounts the AuraChat component into any DOM element, enabling integration with non-React applications (Vanilla JS, Vue, Svelte, etc.).

interface MountAuraChatOptions {
  config: AuraVoyagerConfig;  // Agent configuration
  theme?: 'light' | 'dark';
  title?: string;
  placeholder?: string;
}

const { unmount, agent } = mountAuraChat(containerId: string, options: MountAuraChatOptions);

Error Handling

import { AuraVoyagerError, ErrorCodes } from 'aura-voyager';

try {
  await agent.askStream('Hello', (chunk) => {});
} catch (error) {
  if (error instanceof AuraVoyagerError) {
    console.error(`Error [${error.code}]: ${error.message}`);

    // Standardized error codes:
    // - INVALID_CONFIG
    // - API_ERROR
    // - NETWORK_ERROR
    // - TIMEOUT
    // - INVALID_REQUEST
    // - AUTH_ERROR
    // - RATE_LIMIT
    // - UNKNOWN
  }
}

Explanation: Handling exceptions around API interactions relies on the AuraVoyagerError object type. Evaluators can cross-reference the returned .code attribute against documented internal constants preventing unchecked crash loops securely.

Browser Support

  • Chrome (latest)
  • Firefox (latest)
  • Safari (latest)
  • Edge (latest)
  • Mobile browsers (iOS Safari, Chrome Mobile)

Contributing

Contributions are welcome. Please submit a Pull Request following the established code conventions.

License

MIT

Support


Maintained for React developers. Under development.

About

A production-ready AI agent SDK for React applications with plug-and-play chat UI, API integration, and an intelligent interaction layer.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages