npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

genai-hooks

v2.0.0

Published

Production-ready React hooks for OpenAI integration with TypeScript support

Readme

genai-hooks

Production-ready React hooks for OpenAI integration with full TypeScript support, secure API key management, and comprehensive error handling.

npm version License: MIT TypeScript

Features

  • 🚀 Production-Ready: Built with enterprise-grade patterns and best practices
  • 🔐 Secure API Management: Support for backend proxies to protect API keys
  • 📝 Full TypeScript Support: Complete type definitions for excellent DX
  • 🔄 Advanced Error Handling: Automatic retries, cancellation, and error recovery
  • Performance Optimized: Tree-shakeable, minimal bundle size
  • 🧪 Well Tested: Comprehensive test coverage
  • 🎯 Modern React: Supports React 16.8+, 17, and 18

Installation

npm install genai-hooks
# or
yarn add genai-hooks
# or
pnpm add genai-hooks

Quick Start

Basic Usage (Development Only)

import { AIHooksProvider, useTextGeneration } from 'genai-hooks';

function App() {
  return (
    <AIHooksProvider config={{ apiKey: process.env.REACT_APP_OPENAI_API_KEY }}>
      <TextGenerator />
    </AIHooksProvider>
  );
}

function TextGenerator() {
  const { generateText, data, isLoading, error } = useTextGeneration();
  
  const handleGenerate = () => {
    generateText('Write a short poem about React hooks');
  };

  return (
    <div>
      <button onClick={handleGenerate} disabled={isLoading}>
        {isLoading ? 'Generating...' : 'Generate Text'}
      </button>
      {error && <p>Error: {error.message}</p>}
      {data && <p>{data}</p>}
    </div>
  );
}

Production Usage (Recommended)

For production applications, use a backend proxy to secure your API keys:

import { AIHooksProvider } from 'genai-hooks';

function App() {
  return (
    <AIHooksProvider config={{ 
      baseURL: '/api/ai', // Your backend proxy endpoint
      headers: {
        'Authorization': `Bearer ${userToken}` // Your auth token
      }
    }}>
      <YourApp />
    </AIHooksProvider>
  );
}

Available Hooks

useTextGeneration

Generate text using OpenAI's completion models.

const {
  generateText,  // Function to trigger generation
  data,          // Generated text
  isLoading,     // Loading state
  error,         // Error object
  cancel,        // Cancel ongoing request
  reset          // Reset hook state
} = useTextGeneration();

// With options
generateText('Your prompt', {
  model: 'gpt-3.5-turbo-instruct',
  maxTokens: 150,
  temperature: 0.7,
  topP: 1,
  frequencyPenalty: 0,
  presencePenalty: 0,
  stop: ['\n']
});

useImageGeneration

Generate images using DALL-E.

const {
  generateImage,
  data,         // Image URL or base64 data
  isLoading,
  error,
  cancel,
  reset
} = useImageGeneration();

// With options
generateImage('A futuristic city at sunset', {
  model: 'dall-e-3',
  size: '1024x1024',
  quality: 'hd',
  style: 'vivid',
  n: 1,
  responseFormat: 'url' // or 'b64_json'
});

usePredictiveCompletion

Get real-time text suggestions as users type.

const {
  suggestions,      // Array of suggestions
  isLoading,
  error,
  fetchSuggestions, // Debounced function
  cancel,
  reset
} = usePredictiveCompletion({
  maxSuggestions: 3,
  debounceMs: 300,
  temperature: 0.7
});

// In your input handler
const handleInputChange = (e) => {
  setText(e.target.value);
  fetchSuggestions(e.target.value);
};

useLanguageTranslation

Translate text between languages.

const {
  translateText,
  data,          // Translated text
  isLoading,
  error,
  cancel,
  reset
} = useLanguageTranslation();

// Translate
translateText('Hello world', 'Spanish', {
  model: 'gpt-3.5-turbo',
  temperature: 0.3
});

Configuration

Provider Configuration

<AIHooksProvider config={{
  // API Configuration
  apiKey: string,           // OpenAI API key (use env vars)
  baseURL: string,          // API base URL (default: OpenAI)
  
  // Request Configuration  
  timeout: number,          // Request timeout in ms (default: 30000)
  retries: number,          // Number of retries (default: 3)
  retryDelay: number,       // Delay between retries (default: 1000)
  
  // Custom headers
  headers: Record<string, string>,
  
  // Error handler
  onError: (error: AIHookError) => void
}}>

Dynamic Configuration

function App() {
  const { updateConfig } = useAIHooksConfig();
  
  // Update configuration at runtime
  const switchToProduction = () => {
    updateConfig({
      baseURL: 'https://api.mycompany.com/ai',
      headers: { 'X-API-Version': 'v2' }
    });
  };
}

Security Best Practices

1. Backend Proxy (Recommended)

Never expose your OpenAI API key in client-side code. Use a backend proxy:

// Express.js example
app.post('/api/ai/completions', authenticate, async (req, res) => {
  const response = await openai.completions.create({
    ...req.body,
    // Override any sensitive fields
    api_key: process.env.OPENAI_API_KEY
  });
  res.json(response);
});

2. Environment Variables

If you must use client-side API keys (development only):

# .env.local
REACT_APP_OPENAI_API_KEY=your_api_key_here

3. Rate Limiting

Implement rate limiting on your backend:

const rateLimit = require('express-rate-limit');

const limiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15 minutes
  max: 100 // limit each IP to 100 requests per windowMs
});

app.use('/api/ai', limiter);

Advanced Usage

Custom Error Handling

<AIHooksProvider config={{
  onError: (error) => {
    // Log to error tracking service
    console.error('AI Hook Error:', error);
    
    // Show user-friendly message
    if (error.statusCode === 429) {
      toast.error('Rate limit exceeded. Please try again later.');
    }
  }
}}>

Request Cancellation

function InterruptibleGenerator() {
  const { generateText, cancel, isLoading } = useTextGeneration();
  
  return (
    <>
      <button onClick={() => generateText('Long prompt...')}>
        Generate
      </button>
      {isLoading && (
        <button onClick={cancel}>Cancel</button>
      )}
    </>
  );
}

Streaming Responses (Coming Soon)

const { streamText, data, isStreaming } = useTextStream();

streamText('Write a story...', {
  onChunk: (chunk) => console.log('Received:', chunk),
  onComplete: (fullText) => console.log('Complete:', fullText)
});

TypeScript

All hooks are fully typed. Import types as needed:

import type { 
  TextGenerationOptions,
  ImageGenerationOptions,
  AIHookError,
  AIHooksConfig 
} from 'genai-hooks';

Error Handling

The library provides detailed error information:

interface AIHookError {
  message: string;
  code?: string;
  statusCode?: number;
  details?: unknown;
}

Common error codes:

  • 429: Rate limit exceeded
  • 401: Invalid API key
  • 500: Server error
  • ECONNABORTED: Request timeout

Contributing

We welcome contributions! Please see our Contributing Guide for details.

License

MIT © Harsh Joshi

Support