A drop-in replacement for React Hook Form with AI-powered autofill and field suggestions. Supports Chrome Built-in AI, OpenAI, and custom AI providers with automatic fallback.
-### Features
+## Features
-- **AI-Powered Autofill**: Generate realistic form data using AI
-- **Smart Field Suggestions**: Get AI suggestions for individual fields with debounced blur events
-- **Multiple Provider Support**: Chrome Built-in AI, OpenAI, Custom Server, or Browser AI
-- **Provider Fallback**: Automatic fallback to next provider on failure
-- **Download Progress**: Monitor Chrome AI model download progress
-- **Availability Checking**: Check AI availability before use
-- **Global Configuration**: Configure providers once with AIFormProvider
-- **Full TypeScript Support**: Complete type definitions included
-- **Drop-in Replacement**: 100% compatible with React Hook Form API
+- 🤖 **AI-Powered Autofill** - Generate realistic form data using AI
+- 💡 **Smart Field Suggestions** - Get AI suggestions for individual fields
+- 🔄 **Multiple Provider Support** - Chrome Built-in AI, OpenAI, Custom Server, or Browser AI
+- 🛡️ **Provider Fallback** - Automatic fallback to next provider on failure
+- 📊 **Download Progress** - Monitor Chrome AI model download progress
+- ✅ **Availability Checking** - Check AI availability before use
+- 🌐 **Global Configuration** - Configure providers once with AIFormProvider
+- 📘 **Full TypeScript Support** - Complete type definitions included
+- 🔌 **Drop-in Replacement** - 100% compatible with React Hook Form API
-### Install
+## Installation
```bash
npm install react-hook-form-ai
@@ -37,7 +36,7 @@ pnpm add react-hook-form-ai
yarn add react-hook-form-ai
```
-### Quickstart
+## Quick Start
```tsx
import { useForm } from 'react-hook-form-ai';
@@ -46,7 +45,6 @@ interface FormData {
firstName: string;
lastName: string;
email: string;
- age: number;
}
function App() {
@@ -55,56 +53,36 @@ function App() {
handleSubmit,
aiAutofill,
aiLoading,
- aiAvailability,
formState: { errors },
} = useForm();
- const handleAutofill = async () => {
- try {
- await aiAutofill();
- } catch (error) {
- console.error('Autofill failed:', error);
- }
- };
-
return (
);
}
```
-Learn more about [React Hook Form](https://react-hook-form.com/). This library only adds the _AI_ part.
-
-## Provider Configuration
+## Global Configuration
-### Using AIFormProvider (Global Configuration)
-
-The `AIFormProvider` component allows you to configure AI providers globally for your entire application or a specific part of your component tree. This is the recommended approach for most applications.
+Configure AI providers globally for your entire application:
```tsx
import { AIFormProvider } from 'react-hook-form-ai';
-import App from './App';
function Root() {
return (
@@ -113,7 +91,7 @@ function Root() {
{ type: 'chrome', priority: 10 },
{
type: 'openai',
- apiKey: 'sk-...',
+ apiKey: process.env.REACT_APP_OPENAI_KEY || '',
model: 'gpt-3.5-turbo',
priority: 5
},
@@ -123,7 +101,6 @@ function Root() {
priority: 1
}
]}
- executionOrder={['chrome', 'openai', 'custom']}
fallbackOnError={true}
>
@@ -132,218 +109,75 @@ function Root() {
}
```
-**Configuration Options:**
+## Documentation
-- `providers`: Array of AI provider configurations (required)
-- `executionOrder`: Array specifying the order to try providers. If not provided, providers are sorted by priority (highest first)
-- `fallbackOnError`: When `true`, automatically tries the next provider if one fails (default: `true`)
-- `enabled`: Globally enable/disable AI features (default: `true`)
-- `debounceMs`: Debounce time in milliseconds for AI suggestions (default: `800`)
-- `excludeFields`: Array of field names to exclude from AI processing (default: `[]`)
+### Getting Started
+- 📖 [Getting Started Guide](./docs/GETTING_STARTED.md) - Installation and basic usage
+- 🔧 [Provider Configuration](./docs/PROVIDERS.md) - Detailed provider setup
+- 🌐 [Browser Compatibility](./docs/BROWSER_COMPATIBILITY.md) - Browser requirements
-### Chrome Built-in AI Provider
+### API & Examples
+- 📚 [API Reference](./docs/API_REFERENCE.md) - Complete API documentation
+- 💻 [Examples](./docs/EXAMPLES.md) - Practical usage examples
-The Chrome Built-in AI provider uses Chrome's experimental on-device AI capabilities. This provider is privacy-friendly as all processing happens locally in the browser.
+### Resources
+- 🔗 [React Hook Form Documentation](https://react-hook-form.com/get-started) - Learn about the underlying form library
+- 🤖 [Chrome Built-in AI Documentation](https://developer.chrome.com/docs/ai/built-in) - Official Chrome AI documentation
-```tsx
-{
- type: 'chrome',
- priority: 10 // Optional: higher priority = tried first
-}
-```
-
-**Features:**
-- ✅ No API key required
-- ✅ Browser-based and privacy-friendly
-- ✅ Free to use
-- ⚠️ Requires Chrome 139+ with AI features enabled and Chrome Origin Tials Token
-- ⚠️ May require downloading the AI model on first use
+## Key Concepts
-**Note:** The AI model download requires user interaction. Use `aiAvailability` and `aiDownloadProgress` to handle the download flow gracefully.
+### AI Providers
-### OpenAI Provider
+React Hook Form AI supports multiple AI providers:
-The OpenAI provider connects to OpenAI's API for AI-powered form features.
-
-```tsx
-{
- type: 'openai',
- apiKey: 'sk-...', // Required: Your OpenAI API key
- model: 'gpt-3.5-turbo', // Optional: defaults to 'gpt-3.5-turbo'
- organization: 'org-...', // Optional: Your OpenAI organization ID
- apiUrl: 'https://api.openai.com/v1/chat/completions', // Optional: custom API URL for proxies
- priority: 5
-}
-```
+- **Chrome Built-in AI** - Free, privacy-friendly, on-device AI (requires Chrome 127+)
+- **OpenAI** - Cloud-based AI using GPT models (requires API key)
+- **Custom Server** - Your own AI backend
+- **Browser AI** - Browser-based AI services
-**Supported Models:**
-- `gpt-3.5-turbo` (default) - Fast and cost-effective
-- `gpt-4` - More accurate but slower and more expensive
-- `gpt-4-turbo` - Balance of speed and accuracy
+### Provider Priority and Fallback
-**Custom API URL:**
-You can use a custom `apiUrl` to route requests through a proxy or use OpenAI-compatible APIs:
+Providers are tried in order based on priority or execution order. When `fallbackOnError` is `true`, the next provider is automatically tried if one fails.
```tsx
-{
- type: 'openai',
- apiKey: 'sk-...',
- apiUrl: 'https://your-proxy.com/v1/chat/completions',
- model: 'gpt-3.5-turbo'
-}
+// Chrome AI → OpenAI → Custom Server
+providers={[
+ { type: 'chrome', priority: 10 },
+ { type: 'openai', apiKey: 'sk-...', priority: 5 },
+ { type: 'custom', apiUrl: 'https://api.example.com', priority: 1 }
+]}
```
-### Custom Server Provider
+### Security
-The Custom Server provider allows you to connect to your own AI backend or any custom API endpoint.
+Always exclude sensitive fields from AI processing:
```tsx
-{
- type: 'custom',
- apiUrl: 'https://your-api.com',
- headers: {
- 'Authorization': 'Bearer your-token',
- 'X-Custom-Header': 'value'
- },
- priority: 1
-}
-```
-
-**Required API Endpoints:**
-
-Your custom server must implement these endpoints:
-
-#### 1. Health Check
-```
-GET /health
-Response: 200 OK
-```
-
-#### 2. Field Suggestion
-```
-POST /api/suggest
-Content-Type: application/json
-
-Request Body:
-{
- "fieldName": "email",
- "currentValue": "john@",
- "formContext": { "firstName": "John", "lastName": "Doe" }
-}
-
-Response:
-{
- "suggestion": "john@example.com"
-}
-```
-
-#### 3. Form Autofill
-```
-POST /api/autofill
-Content-Type: application/json
-
-Request Body:
-{
- "fields": ["firstName", "lastName", "email"],
- "formContext": {}
-}
-
-Response:
-{
- "autofillData": {
- "firstName": "John",
- "lastName": "Doe",
- "email": "john.doe@example.com"
+const form = useForm({
+ ai: {
+ excludeFields: ['password', 'ssn', 'creditCard']
}
-}
-```
-
-### Local Configuration (Per-Form Override)
-
-You can override global provider settings for individual forms by passing options to the `useForm` hook:
-
-```tsx
-import { useForm } from 'react-hook-form-ai';
-
-function MyForm() {
- const { register, aiAutofill } = useForm({
- ai: {
- enabled: true,
- providers: [
- { type: 'openai', apiKey: 'sk-...', priority: 10 }
- ],
- executionOrder: ['openai'],
- fallbackOnError: false,
- debounceMs: 500,
- excludeFields: ['password', 'creditCard']
- }
- });
-
- return (
-
- );
-}
-```
-
-**Local options override global settings:**
-- `enabled`: Enable/disable AI for this form only
-- `providers`: Use different providers for this form
-- `executionOrder`: Custom provider order for this form
-- `fallbackOnError`: Override fallback behavior
-- `debounceMs`: Custom debounce timing
-- `excludeFields`: Fields to exclude from AI processing (e.g., passwords, credit cards)
-
-## API Reference
-
-### UseFormAIReturn Interface
-
-The `useForm` hook returns all standard React Hook Form properties plus the following AI-specific properties:
-
-#### `aiEnabled: boolean`
-
-Indicates whether AI features are enabled for this form instance.
-
-```tsx
-const { aiEnabled } = useForm({ ai: { enabled: true } });
-console.log(aiEnabled); // true
+});
```
-#### `aiAutofill: (fields?: string[]) => Promise`
-
-Triggers AI-powered autofill for all form fields or specific fields.
-
-**Parameters:**
-- `fields` (optional): Array of field names to autofill. If omitted, all fields are autofilled.
+## Common Use Cases
-**Returns:** `Promise` - Resolves when autofill is complete, rejects on error.
+### Multi-Provider Setup
-**Example:**
```tsx
-const { aiAutofill } = useForm();
-
-// Autofill all fields
-await aiAutofill();
-
-// Autofill specific fields only
-await aiAutofill(['firstName', 'lastName']);
+
+
+
```
-#### `aiSuggest: (fieldName: string) => Promise`
-
-Gets an AI suggestion for a specific field based on its current value and form context.
-
-**Parameters:**
-- `fieldName`: The name of the field to get a suggestion for
+### Field-Level Suggestions
-**Returns:** `Promise` - The suggested value, or `null` if no suggestion is available
-
-**Example:**
```tsx
const { aiSuggest, setValue } = useForm();
@@ -353,945 +187,80 @@ if (suggestion) {
}
```
-#### `aiLoading: boolean`
-
-Indicates whether an AI operation (autofill or suggest) is currently in progress.
-
-**Example:**
-```tsx
-const { aiLoading, aiAutofill } = useForm();
-
-
-```
-
-#### `aiAvailability: { available: boolean; status: string; needsDownload: boolean } | null`
-
-Provides information about AI availability status. This is particularly useful for Chrome Built-in AI which may require model download.
-
-**Properties:**
-- `available`: `true` if AI is ready to use
-- `status`: Current status string (`'readily'`, `'downloadable'`, `'downloading'`, `'unavailable'`, `'error'`)
-- `needsDownload`: `true` if the AI model needs to be downloaded (Chrome AI only)
+### Chrome AI Download Handling
-**Example:**
```tsx
-const { aiAvailability, aiAutofill } = useForm();
+const { aiAvailability, aiDownloadProgress } = useForm();
if (aiAvailability?.needsDownload) {
- // User interaction required to start download
- return ;
+ return ;
}
-if (!aiAvailability?.available) {
- return
AI unavailable: {aiAvailability?.status}
;
+if (aiAvailability?.status === 'downloading') {
+ return ;
}
```
-#### `refreshAvailability: () => Promise`
-
-Manually refreshes the AI availability status. Useful after user interactions or when checking if a download has completed.
+See [Examples](./docs/EXAMPLES.md) for more use cases.
-**Returns:** `Promise` - Resolves when availability check is complete
+## API Overview
-**Example:**
-```tsx
-const { refreshAvailability, aiAvailability } = useForm();
+### useForm Hook
-useEffect(() => {
- const interval = setInterval(async () => {
- if (aiAvailability?.status === 'downloading') {
- await refreshAvailability();
- }
- }, 2000);
+```typescript
+const {
+ // Standard React Hook Form properties
+ register,
+ handleSubmit,
+ formState,
+ // ... all other RHF properties
- return () => clearInterval(interval);
-}, [aiAvailability?.status]);
-```
-
-#### `aiDownloadProgress: number | null`
-
-Download progress percentage (0-100) when the Chrome AI model is being downloaded. `null` when not downloading.
-
-**Example:**
-```tsx
-const { aiDownloadProgress } = useForm();
-
-{aiDownloadProgress !== null && (
-
-
- {aiDownloadProgress}% downloaded
-
-)}
-```
-
-### AIFormOptions Interface
-
-Configuration options for AI features, passed to the `useForm` hook via the `ai` property.
-
-```tsx
-interface AIFormOptions {
- enabled?: boolean;
- apiUrl?: string;
- debounceMs?: number;
- excludeFields?: string[];
- autoCheckAvailability?: boolean;
- providers?: AIProvider[];
- executionOrder?: AIProviderType[];
- fallbackOnError?: boolean;
-}
-```
-
-#### Configuration Properties
-
-**`enabled?: boolean`**
-- **Default:** `true`
-- Enable or disable AI features for this form
-- **Example:** `{ ai: { enabled: false } }`
-
-**`apiUrl?: string`**
-- **Default:** `'http://localhost:3001'`
-- Fallback API endpoint for custom server provider
-- **Example:** `{ ai: { apiUrl: 'https://api.example.com' } }`
-
-**`debounceMs?: number`**
-- **Default:** `800`
-- Debounce time in milliseconds for AI suggestions on field blur
-- **Example:** `{ ai: { debounceMs: 500 } }`
-
-**`excludeFields?: string[]`**
-- **Default:** `[]`
-- Array of field names to exclude from AI processing (e.g., passwords, credit cards)
-- **Example:** `{ ai: { excludeFields: ['password', 'ssn', 'creditCard'] } }`
-
-**`autoCheckAvailability?: boolean`**
-- **Default:** `true`
-- Automatically check AI availability when the form mounts
-- **Example:** `{ ai: { autoCheckAvailability: false } }`
-
-**`providers?: AIProvider[]`**
-- **Default:** Inherited from `AIFormProvider` or `undefined`
-- Override AI providers for this specific form
-- **Example:** `{ ai: { providers: [{ type: 'openai', apiKey: 'sk-...' }] } }`
-
-**`executionOrder?: AIProviderType[]`**
-- **Default:** Inherited from `AIFormProvider` or sorted by priority
-- Override the order in which providers are tried
-- **Example:** `{ ai: { executionOrder: ['chrome', 'openai'] } }`
-
-**`fallbackOnError?: boolean`**
-- **Default:** `true`
-- Automatically try the next provider if one fails
-- **Example:** `{ ai: { fallbackOnError: false } }`
-
-**Complete Example:**
-```tsx
-const form = useForm({
+ // AI-specific properties
+ aiEnabled,
+ aiAutofill,
+ aiSuggest,
+ aiLoading,
+ aiAvailability,
+ refreshAvailability,
+ aiDownloadProgress
+} = useForm({
ai: {
enabled: true,
- debounceMs: 500,
- excludeFields: ['password', 'creditCard'],
- autoCheckAvailability: true,
- providers: [
- { type: 'chrome', priority: 10 },
- { type: 'openai', apiKey: 'sk-...', priority: 5 }
- ],
- executionOrder: ['chrome', 'openai'],
- fallbackOnError: true
+ providers: [...],
+ excludeFields: ['password']
}
});
```
-### AIProvider Type Definitions
-
-The library supports multiple AI provider types, each with its own configuration interface.
-
-#### `AIProviderType`
-
-Union type of all supported provider types:
-
-```tsx
-type AIProviderType = 'chrome' | 'openai' | 'custom' | 'browser';
-```
-
-#### `ChromeAIConfig`
-
-Configuration for Chrome Built-in AI provider.
-
-```tsx
-interface ChromeAIConfig {
- type: 'chrome';
- enabled?: boolean;
- priority?: number;
-}
-```
-
-**Example:**
-```tsx
-const chromeProvider: ChromeAIConfig = {
- type: 'chrome',
- priority: 10
-};
-```
-
-**Properties:**
-- `type`: Must be `'chrome'`
-- `enabled`: Optional. Set to `false` to disable this provider
-- `priority`: Optional. Higher values are tried first (default: 0)
-
-#### `OpenAIConfig`
-
-Configuration for OpenAI API provider.
-
-```tsx
-interface OpenAIConfig {
- type: 'openai';
- apiKey: string;
- apiUrl?: string;
- model?: string;
- organization?: string;
- enabled?: boolean;
- priority?: number;
-}
-```
-
-**Example:**
-```tsx
-const openaiProvider: OpenAIConfig = {
- type: 'openai',
- apiKey: 'sk-...',
- model: 'gpt-4',
- organization: 'org-...',
- priority: 5
-};
-```
-
-**Properties:**
-- `type`: Must be `'openai'`
-- `apiKey`: **Required.** Your OpenAI API key
-- `apiUrl`: Optional. Custom API endpoint (default: OpenAI's API)
-- `model`: Optional. Model to use (default: `'gpt-3.5-turbo'`)
-- `organization`: Optional. Your OpenAI organization ID
-- `enabled`: Optional. Set to `false` to disable this provider
-- `priority`: Optional. Higher values are tried first (default: 0)
-
-#### `CustomServerConfig`
-
-Configuration for custom AI server provider.
-
-```tsx
-interface CustomServerConfig {
- type: 'custom';
- apiUrl: string;
- headers?: Record;
- enabled?: boolean;
- priority?: number;
-}
-```
-
-**Example:**
-```tsx
-const customProvider: CustomServerConfig = {
- type: 'custom',
- apiUrl: 'https://your-api.com',
- headers: {
- 'Authorization': 'Bearer token',
- 'X-Custom-Header': 'value'
- },
- priority: 1
-};
-```
-
-**Properties:**
-- `type`: Must be `'custom'`
-- `apiUrl`: **Required.** Your custom API endpoint
-- `headers`: Optional. Custom HTTP headers for requests
-- `enabled`: Optional. Set to `false` to disable this provider
-- `priority`: Optional. Higher values are tried first (default: 0)
-
-#### `BrowserAIConfig`
-
-Configuration for browser-based AI provider.
-
-```tsx
-interface BrowserAIConfig {
- type: 'browser';
- apiUrl: string;
- headers?: Record;
- enabled?: boolean;
- priority?: number;
-}
-```
-
-**Example:**
-```tsx
-const browserProvider: BrowserAIConfig = {
- type: 'browser',
- apiUrl: 'https://browser-ai.example.com',
- priority: 3
-};
-```
-
-**Properties:**
-- `type`: Must be `'browser'`
-- `apiUrl`: **Required.** Browser AI service endpoint
-- `headers`: Optional. Custom HTTP headers for requests
-- `enabled`: Optional. Set to `false` to disable this provider
-- `priority`: Optional. Higher values are tried first (default: 0)
-
-#### `AIProvider` Union Type
-
-The `AIProvider` type is a union of all provider configuration types:
-
-```tsx
-type AIProvider = ChromeAIConfig | OpenAIConfig | CustomServerConfig | BrowserAIConfig;
-```
-
-**Usage in AIFormProvider:**
-```tsx
-const providers: AIProvider[] = [
- { type: 'chrome', priority: 10 },
- { type: 'openai', apiKey: 'sk-...', model: 'gpt-4', priority: 5 },
- { type: 'custom', apiUrl: 'https://api.example.com', priority: 1 }
-];
-
-
-
-
-```
-
-## Advanced Examples
-
-### Multi-Provider Setup with Fallback
-
-This example demonstrates how to configure multiple AI providers with priority-based execution and automatic fallback when a provider fails.
-
-```tsx
-import { AIFormProvider, useForm } from 'react-hook-form-ai';
-
-// Root component with provider configuration
-function Root() {
- return (
-
-
-
- );
-}
-
-// Form component that uses the configured providers
-function App() {
- const {
- register,
- handleSubmit,
- aiAutofill,
- aiLoading,
- aiAvailability
- } = useForm<{
- name: string;
- email: string;
- company: string;
- }>();
-
- const [error, setError] = React.useState(null);
-
- const handleAutofill = async () => {
- setError(null);
- try {
- // Will try Chrome first, then OpenAI, then Custom if previous ones fail
- await aiAutofill();
- } catch (err) {
- setError('All AI providers failed. Please fill the form manually.');
- console.error('Autofill error:', err);
- }
- };
-
- return (
-
- );
-}
-```
-
-**How Fallback Works:**
-
-1. **Chrome AI is tried first** (priority: 10)
- - If Chrome AI is unavailable or fails, automatically falls back to OpenAI
-
-2. **OpenAI is tried second** (priority: 5)
- - If OpenAI fails (e.g., API key invalid, rate limit), falls back to Custom server
-
-3. **Custom server is tried last** (priority: 1)
- - If all providers fail, the promise rejects and you can handle the error
-
-**Benefits:**
-- Free Chrome AI when available
-- Reliable fallback to cloud providers
-- Graceful degradation
-- No single point of failure
-
-### Field-Level AI Suggestions
-
-This example shows how to use AI suggestions for individual fields, with custom debounce timing and field exclusions for sensitive data.
-
-```tsx
-import { useForm } from 'react-hook-form-ai';
-import { useState } from 'react';
-
-interface ProfileForm {
- username: string;
- email: string;
- bio: string;
- password: string;
- website: string;
-}
-
-function ProfileEditor() {
- const {
- register,
- handleSubmit,
- aiSuggest,
- setValue,
- watch
- } = useForm({
- ai: {
- enabled: true,
- debounceMs: 500, // Faster suggestions (default is 800ms)
- excludeFields: ['password'], // Never send password to AI
- providers: [
- { type: 'chrome', priority: 10 },
- { type: 'openai', apiKey: process.env.REACT_APP_OPENAI_KEY || '', priority: 5 }
- ]
- }
- });
-
- const [suggestions, setSuggestions] = useState>({});
- const [loadingField, setLoadingField] = useState(null);
-
- // Get AI suggestion for a specific field
- const getSuggestion = async (fieldName: keyof ProfileForm) => {
- setLoadingField(fieldName);
- try {
- const suggestion = await aiSuggest(fieldName);
- if (suggestion) {
- setSuggestions(prev => ({ ...prev, [fieldName]: suggestion }));
- }
- } catch (error) {
- console.error(`Failed to get suggestion for ${fieldName}:`, error);
- } finally {
- setLoadingField(null);
- }
- };
-
- // Accept a suggestion and apply it to the field
- const acceptSuggestion = (fieldName: keyof ProfileForm) => {
- const suggestion = suggestions[fieldName];
- if (suggestion) {
- setValue(fieldName, suggestion);
- setSuggestions(prev => {
- const updated = { ...prev };
- delete updated[fieldName];
- return updated;
- });
- }
- };
-
- const currentValues = watch();
-
- return (
-
- );
-}
-```
-
-**Key Features:**
-
-- **Custom Debounce:** Set to 500ms for faster suggestions (default is 800ms)
-- **Field Exclusion:** Password field is excluded from AI processing for security
-- **User Control:** Users can review suggestions before accepting them
-- **Context-Aware:** AI considers other field values when making suggestions
-- **Individual Field Targeting:** Get suggestions for specific fields on demand
-
-**Use Cases:**
-- Improving email formatting based on username
-- Enhancing bio text for better readability
-- Suggesting professional website URLs
-- Formatting names consistently
-
-### Chrome AI Download Handling
-
-Chrome's Built-in AI requires downloading a language model (~1-2GB) on first use. This example shows how to handle the download flow gracefully with progress tracking.
-
-```tsx
-import { useForm } from 'react-hook-form-ai';
-import { useEffect, useState } from 'react';
-
-interface FormData {
- name: string;
- email: string;
- message: string;
-}
-
-function ContactForm() {
- const {
- register,
- handleSubmit,
- aiAutofill,
- aiLoading,
- aiAvailability,
- refreshAvailability,
- aiDownloadProgress
- } = useForm({
- ai: {
- providers: [{ type: 'chrome', priority: 10 }],
- autoCheckAvailability: true
- }
- });
-
- const [downloadStarted, setDownloadStarted] = useState(false);
-
- // Poll availability during download
- useEffect(() => {
- if (aiAvailability?.status === 'downloading') {
- const interval = setInterval(async () => {
- await refreshAvailability();
- }, 2000); // Check every 2 seconds
-
- return () => clearInterval(interval);
- }
- }, [aiAvailability?.status, refreshAvailability]);
-
- const handleAutofillClick = async () => {
- // If model needs download, this will trigger the download
- if (aiAvailability?.needsDownload) {
- setDownloadStarted(true);
- }
-
- try {
- await aiAutofill();
- } catch (error) {
- console.error('Autofill failed:', error);
- }
- };
-
- // Render different UI based on availability status
- const renderAIStatus = () => {
- if (!aiAvailability) {
- return
Downloading AI model... Please keep this tab open.
-
-
{Math.round(aiDownloadProgress || 0)}% complete
-
- );
-}
-```
-
-#### Fallback for Unsupported Browsers
-
-For browsers that don't support Chrome AI, configure fallback providers to ensure your forms remain functional:
-
-```tsx
-
-
-
-```
-
-**Fallback Behavior:**
-- If Chrome AI is unavailable, the library automatically tries the next provider in the execution order
-- Users on unsupported browsers (Safari, Firefox, older Chrome) will seamlessly use alternative providers
-- No code changes needed - fallback is automatic when `fallbackOnError={true}`
-
-#### Checking Availability Programmatically
-
-You can check AI availability and handle different states in your component:
-
-```tsx
-const { aiAvailability, refreshAvailability } = useForm();
-
-useEffect(() => {
- // Check availability on mount
- refreshAvailability();
-}, []);
-
-if (!aiAvailability) {
- return
diff --git a/docs/API_REFERENCE.md b/docs/API_REFERENCE.md
new file mode 100644
index 0000000..4c516e5
--- /dev/null
+++ b/docs/API_REFERENCE.md
@@ -0,0 +1,750 @@
+# API Reference
+
+Complete API documentation for React Hook Form AI.
+
+## Table of Contents
+
+- [Hooks](#hooks)
+ - [useForm](#useform)
+ - [useAIAssistant](#useaiassistant)
+ - [useAIFormContext](#useaiformcontext)
+ - [useOptionalAIFormContext](#useoptionalaiformcontext)
+- [Components](#components)
+ - [AIFormProvider](#aiformprovider)
+- [Interfaces](#interfaces)
+ - [UseFormAIReturn](#useformaireturnt)
+ - [AIFormOptions](#aiformoptions)
+ - [AIFormProviderProps](#aiformproviderprops)
+- [Types](#types)
+ - [AIProviderType](#aiprovidertype)
+ - [AIProvider](#aiprovider)
+ - [OpenAIConfig](#openaiconfig)
+ - [CustomServerConfig](#customserverconfig)
+ - [ChromeAIConfig](#chromeaiconfig)
+ - [BrowserAIConfig](#browseraiconfig)
+ - [AIFormContextValue](#aiformcontextvalue)
+ - [AIResponse](#airesponse)
+
+---
+
+## Hooks
+
+### useForm
+
+```typescript
+function useForm(
+ options?: UseFormProps & { ai?: AIFormOptions }
+): UseFormAIReturn
+```
+
+Enhanced React Hook Form with AI-powered autofill and field suggestions.
+
+**Type Parameters:**
+- `T` - The form data type extending FieldValues
+
+**Parameters:**
+- `options` - Standard React Hook Form options plus optional AI configuration
+
+**Returns:** Extended form object with AI capabilities
+
+**Description:**
+
+A drop-in replacement for React Hook Form's `useForm` hook that adds AI capabilities including autofill, field suggestions, and availability checking. Supports multiple AI providers (Chrome Built-in AI, OpenAI, Custom Server) with automatic fallback.
+
+**Examples:**
+
+Basic usage:
+```tsx
+const { register, handleSubmit, aiAutofill } = useForm();
+
+return (
+
+);
+```
+
+With AI configuration:
+```tsx
+const form = useForm({
+ ai: {
+ enabled: true,
+ debounceMs: 500,
+ excludeFields: ['password'],
+ providers: [
+ { type: 'chrome', priority: 10 },
+ { type: 'openai', apiKey: 'sk-...', priority: 5 }
+ ]
+ }
+});
+```
+
+Handling Chrome AI download:
+```tsx
+const { aiAvailability, aiDownloadProgress, aiAutofill } = useForm();
+
+if (aiAvailability?.needsDownload) {
+ return ;
+}
+
+if (aiAvailability?.status === 'downloading') {
+ return ;
+}
+```
+
+---
+
+### useAIAssistant
+
+```typescript
+function useAIAssistant(options?: AIAssistantOptions): {
+ suggestValue: (name: string, value: string) => Promise;
+ autofill: (fields: string[], options?: { onDownloadProgress?: (progress: number) => void }) => Promise;
+ checkAvailability: () => Promise<{ available: boolean; status: string; needsDownload: boolean }>;
+}
+```
+
+Low-level AI assistant hook for advanced use cases.
+
+**Parameters:**
+- `options` - Configuration options for the AI assistant
+ - `enabled?: boolean` - Enable AI features (default: true)
+ - `formContext?: Record` - Current form values for context
+ - `apiUrl?: string` - API endpoint for AI fallback
+ - `providers?: AIProvider[]` - Override providers from AIFormProvider
+ - `executionOrder?: AIProviderType[]` - Override execution order
+ - `fallbackOnError?: boolean` - Override fallback behavior
+
+**Returns:** Object with AI methods
+
+**Description:**
+
+This hook provides direct access to AI capabilities without form integration. It uses configured providers from AIFormProvider or accepts local overrides. Most users should use the `useForm` hook instead, which includes this functionality.
+
+**Examples:**
+
+Basic usage:
+```tsx
+const ai = useAIAssistant({
+ enabled: true,
+ formContext: { firstName: 'John' }
+});
+
+// Get suggestion for a field
+const suggestion = await ai.suggestValue('email', 'john@');
+
+// Autofill multiple fields
+const data = await ai.autofill(['firstName', 'lastName', 'email']);
+
+// Check availability
+const status = await ai.checkAvailability();
+```
+
+With custom providers:
+```tsx
+const ai = useAIAssistant({
+ providers: [
+ { type: 'openai', apiKey: 'sk-...', priority: 10 }
+ ],
+ executionOrder: ['openai'],
+ fallbackOnError: false
+});
+```
+
+---
+
+### useAIFormContext
+
+```typescript
+function useAIFormContext(): AIFormContextValue
+```
+
+Hook to access AI form context from AIFormProvider.
+
+**Returns:** The AI form context value
+
+**Throws:** Error if used outside of AIFormProvider
+
+**Description:**
+
+This hook must be used within an AIFormProvider. It provides access to the global AI configuration including providers, execution order, and other settings.
+
+**Example:**
+
+```tsx
+function MyComponent() {
+ const { providers, executionOrder } = useAIFormContext();
+ // Use context values...
+}
+```
+
+---
+
+### useOptionalAIFormContext
+
+```typescript
+function useOptionalAIFormContext(): AIFormContextValue | null
+```
+
+Hook to optionally access AI form context from AIFormProvider.
+
+**Returns:** The AI form context value or null if not within provider
+
+**Description:**
+
+Similar to `useAIFormContext` but returns null instead of throwing an error when used outside of AIFormProvider. Useful for components that work with or without the provider.
+
+**Example:**
+
+```tsx
+function MyComponent() {
+ const context = useOptionalAIFormContext();
+ if (context) {
+ // Use context values...
+ } else {
+ // Use default values...
+ }
+}
+```
+
+---
+
+## Components
+
+### AIFormProvider
+
+```typescript
+function AIFormProvider(props: AIFormProviderProps): JSX.Element
+```
+
+Global AI configuration provider for React Hook Form AI.
+
+**Props:** See [AIFormProviderProps](#aiformproviderprops)
+
+**Description:**
+
+Wrap your application or component tree with this provider to configure AI settings globally. All `useForm` hooks within the provider will inherit these settings unless overridden with local options.
+
+**Examples:**
+
+Basic setup:
+```tsx
+
+
+
+```
+
+With custom execution order:
+```tsx
+
+
+
+```
+
+---
+
+## Interfaces
+
+### UseFormAIReturn\
+
+Extended return type from `useForm` hook with AI capabilities.
+
+**Type Parameters:**
+- `T` - The form data type extending FieldValues
+
+**Extends:** `UseFormReturn` from React Hook Form
+
+**Properties:**
+
+#### `aiEnabled: boolean`
+
+Indicates whether AI features are enabled for this form instance.
+
+```tsx
+const { aiEnabled } = useForm({ ai: { enabled: true } });
+console.log(aiEnabled); // true
+```
+
+#### `aiAutofill: (fields?: Path[]) => Promise`
+
+Triggers AI-powered autofill for all form fields or specific fields.
+
+**Parameters:**
+- `fields` (optional): Array of field names to autofill. If omitted, all fields are autofilled.
+
+**Returns:** `Promise` - Resolves when autofill is complete, rejects on error.
+
+**Example:**
+```tsx
+// Autofill all fields
+await aiAutofill();
+
+// Autofill specific fields only
+await aiAutofill(['firstName', 'lastName']);
+```
+
+#### `aiSuggest: (fieldName: Path) => Promise`
+
+Gets an AI suggestion for a specific field based on its current value and form context.
+
+**Parameters:**
+- `fieldName`: The name of the field to get a suggestion for
+
+**Returns:** `Promise` - The suggested value, or `null` if no suggestion is available
+
+**Example:**
+```tsx
+const suggestion = await aiSuggest('email');
+if (suggestion) {
+ setValue('email', suggestion);
+}
+```
+
+#### `aiLoading: boolean`
+
+Indicates whether an AI operation (autofill or suggest) is currently in progress.
+
+**Example:**
+```tsx
+
+```
+
+#### `aiAvailability: { available: boolean; status: string; needsDownload: boolean } | null`
+
+Provides information about AI availability status.
+
+**Properties:**
+- `available`: `true` if AI is ready to use
+- `status`: Current status string (`'readily'`, `'downloadable'`, `'downloading'`, `'unavailable'`, `'error'`)
+- `needsDownload`: `true` if the AI model needs to be downloaded (Chrome AI only)
+
+**Example:**
+```tsx
+if (aiAvailability?.needsDownload) {
+ return ;
+}
+
+if (!aiAvailability?.available) {
+ return
AI unavailable: {aiAvailability?.status}
;
+}
+```
+
+#### `refreshAvailability: () => Promise`
+
+Manually refreshes the AI availability status.
+
+**Returns:** `Promise` - Resolves when availability check is complete
+
+**Example:**
+```tsx
+useEffect(() => {
+ const interval = setInterval(async () => {
+ if (aiAvailability?.status === 'downloading') {
+ await refreshAvailability();
+ }
+ }, 2000);
+
+ return () => clearInterval(interval);
+}, [aiAvailability?.status]);
+```
+
+#### `aiDownloadProgress: number | null`
+
+Download progress percentage (0-100) when the Chrome AI model is being downloaded. `null` when not downloading.
+
+**Example:**
+```tsx
+{aiDownloadProgress !== null && (
+
+
+ {aiDownloadProgress}% downloaded
+
+)}
+```
+
+---
+
+### AIFormOptions
+
+Configuration options for AI features in the form.
+
+**Properties:**
+
+#### `enabled?: boolean`
+
+Enable or disable AI features for this form. Default: `true`
+
+#### `apiUrl?: string`
+
+API endpoint for custom server provider. Default: `'http://localhost:3001'`
+
+#### `debounceMs?: number`
+
+Debounce time in milliseconds for AI suggestions on field blur. Default: `800`
+
+#### `excludeFields?: string[]`
+
+Array of field names to exclude from AI processing (e.g., passwords, credit cards). Default: `[]`
+
+#### `autoCheckAvailability?: boolean`
+
+Automatically check AI availability when the form mounts. Default: `true`
+
+#### `providers?: AIProvider[]`
+
+Override AI providers for this specific form. Inherits from `AIFormProvider` if not specified.
+
+#### `executionOrder?: AIProviderType[]`
+
+Override the order in which providers are tried. Inherits from `AIFormProvider` if not specified.
+
+#### `fallbackOnError?: boolean`
+
+Automatically try the next provider if one fails. Default: `true`
+
+**Example:**
+
+```tsx
+const form = useForm({
+ ai: {
+ enabled: true,
+ debounceMs: 500,
+ excludeFields: ['password', 'creditCard'],
+ providers: [
+ { type: 'chrome', priority: 10 },
+ { type: 'openai', apiKey: 'sk-...', priority: 5 }
+ ],
+ executionOrder: ['chrome', 'openai'],
+ fallbackOnError: true
+ }
+});
+```
+
+---
+
+### AIFormProviderProps
+
+Props for the AIFormProvider component.
+
+**Properties:**
+
+#### `children: ReactNode`
+
+Child components that will have access to the AI context.
+
+#### `providers: AIProvider[]`
+
+Array of AI provider configurations. **Required.**
+
+#### `executionOrder?: AIProviderType[]`
+
+Array specifying the order to try providers. If not provided, providers are sorted by priority (highest first).
+
+#### `fallbackOnError?: boolean`
+
+When `true`, automatically tries the next provider if one fails. Default: `true`
+
+#### `enabled?: boolean`
+
+Globally enable/disable AI features. Default: `true`
+
+#### `debounceMs?: number`
+
+Debounce time in milliseconds for AI suggestions. Default: `800`
+
+#### `excludeFields?: string[]`
+
+Array of field names to exclude from AI processing. Default: `[]`
+
+---
+
+## Types
+
+### AIProviderType
+
+```typescript
+type AIProviderType = 'chrome' | 'openai' | 'custom' | 'browser';
+```
+
+Supported AI provider types.
+
+- `chrome`: Chrome Built-in AI (on-device, privacy-friendly, free)
+- `openai`: OpenAI API (GPT-3.5, GPT-4, etc.)
+- `custom`: Custom AI server endpoint
+- `browser`: Browser-based AI service
+
+---
+
+### AIProvider
+
+```typescript
+type AIProvider = OpenAIConfig | CustomServerConfig | ChromeAIConfig | BrowserAIConfig;
+```
+
+Union type of all supported AI provider configurations.
+
+**Example:**
+
+```tsx
+const providers: AIProvider[] = [
+ { type: 'chrome', priority: 10 },
+ { type: 'openai', apiKey: 'sk-...', priority: 5 },
+ { type: 'custom', apiUrl: 'https://api.example.com', priority: 1 }
+];
+```
+
+---
+
+### OpenAIConfig
+
+Configuration for OpenAI provider.
+
+**Properties:**
+
+#### `type: 'openai'`
+
+Must be `'openai'`.
+
+#### `apiKey: string`
+
+OpenAI API key. **Required.**
+
+#### `apiUrl?: string`
+
+Custom API endpoint. Optional, defaults to OpenAI's API.
+
+#### `model?: string`
+
+Model to use. Optional, defaults to `'gpt-3.5-turbo'`.
+
+Supported models:
+- `gpt-3.5-turbo` (default) - Fast and cost-effective
+- `gpt-4` - More accurate but slower and more expensive
+- `gpt-4-turbo` - Balance of speed and accuracy
+
+#### `organization?: string`
+
+OpenAI organization ID. Optional.
+
+#### `enabled?: boolean`
+
+Set to `false` to disable this provider. Optional.
+
+#### `priority?: number`
+
+Higher values are tried first. Optional, default: 0.
+
+**Example:**
+
+```tsx
+const config: OpenAIConfig = {
+ type: 'openai',
+ apiKey: 'sk-...',
+ model: 'gpt-4',
+ organization: 'org-...',
+ priority: 5
+};
+```
+
+---
+
+### CustomServerConfig
+
+Configuration for custom AI server provider.
+
+**Properties:**
+
+#### `type: 'custom'`
+
+Must be `'custom'`.
+
+#### `apiUrl: string`
+
+Custom API endpoint. **Required.**
+
+Your server must implement these endpoints:
+- `GET /health` - Health check
+- `POST /api/suggest` - Field suggestion
+- `POST /api/autofill` - Form autofill
+
+#### `headers?: Record`
+
+Custom HTTP headers for requests. Optional.
+
+#### `enabled?: boolean`
+
+Set to `false` to disable this provider. Optional.
+
+#### `priority?: number`
+
+Higher values are tried first. Optional, default: 0.
+
+**Example:**
+
+```tsx
+const config: CustomServerConfig = {
+ type: 'custom',
+ apiUrl: 'https://your-api.com',
+ headers: {
+ 'Authorization': 'Bearer token',
+ 'X-Custom-Header': 'value'
+ },
+ priority: 1
+};
+```
+
+---
+
+### ChromeAIConfig
+
+Configuration for Chrome Built-in AI provider.
+
+**Properties:**
+
+#### `type: 'chrome'`
+
+Must be `'chrome'`.
+
+#### `enabled?: boolean`
+
+Set to `false` to disable this provider. Optional.
+
+#### `priority?: number`
+
+Higher values are tried first. Optional, default: 0.
+
+**Features:**
+- ✅ No API key required
+- ✅ Browser-based and privacy-friendly
+- ✅ Free to use
+- ⚠️ Requires Chrome 127+ with AI features enabled
+- ⚠️ May require downloading the AI model on first use
+
+**Example:**
+
+```tsx
+const config: ChromeAIConfig = {
+ type: 'chrome',
+ priority: 10
+};
+```
+
+---
+
+### BrowserAIConfig
+
+Configuration for browser-based AI provider.
+
+**Properties:**
+
+#### `type: 'browser'`
+
+Must be `'browser'`.
+
+#### `apiUrl: string`
+
+Browser AI service endpoint. **Required.**
+
+#### `headers?: Record`
+
+Custom HTTP headers for requests. Optional.
+
+#### `enabled?: boolean`
+
+Set to `false` to disable this provider. Optional.
+
+#### `priority?: number`
+
+Higher values are tried first. Optional, default: 0.
+
+**Example:**
+
+```tsx
+const config: BrowserAIConfig = {
+ type: 'browser',
+ apiUrl: 'https://browser-ai.example.com',
+ priority: 3
+};
+```
+
+---
+
+### AIFormContextValue
+
+Context value provided by AIFormProvider.
+
+**Properties:**
+
+#### `providers: AIProvider[]`
+
+Array of configured AI providers.
+
+#### `executionOrder: AIProviderType[]`
+
+Order in which providers should be tried.
+
+#### `fallbackOnError: boolean`
+
+Whether to fallback to next provider on error.
+
+#### `enabled: boolean`
+
+Whether AI features are globally enabled.
+
+#### `debounceMs: number`
+
+Debounce time in milliseconds for AI suggestions.
+
+#### `excludeFields: string[]`
+
+Array of field names to exclude from AI processing.
+
+---
+
+### AIResponse
+
+Response from an AI provider.
+
+**Properties:**
+
+#### `suggestion: string`
+
+The AI-generated suggestion.
+
+#### `provider: AIProviderType`
+
+Which provider generated this response.
+
+#### `confidence?: number`
+
+Optional confidence score (0-1).
+
+---
+
+## See Also
+
+- [Getting Started Guide](./GETTING_STARTED.md)
+- [Provider Configuration](./PROVIDERS.md)
+- [Examples](./EXAMPLES.md)
+- [Main README](../README.md)
diff --git a/docs/BROWSER_COMPATIBILITY.md b/docs/BROWSER_COMPATIBILITY.md
new file mode 100644
index 0000000..feba2fd
--- /dev/null
+++ b/docs/BROWSER_COMPATIBILITY.md
@@ -0,0 +1,263 @@
+# Browser Compatibility
+
+Browser requirements and compatibility information for React Hook Form AI.
+
+## Overview
+
+React Hook Form AI works in all modern browsers. However, the Chrome Built-in AI provider has specific requirements.
+
+## Chrome Built-in AI Requirements
+
+The Chrome Built-in AI provider requires **Chrome version 127 or higher** with experimental AI features enabled.
+
+### Browser Requirements
+
+- **Chrome**: Version 127+ (recommended: 139+)
+- **Edge**: Not supported (Chromium-based Edge doesn't include AI features)
+- **Safari**: Not supported
+- **Firefox**: Not supported
+- **Opera**: Not supported
+
+### Enabling Chrome AI
+
+1. **Update Chrome**
+ - Ensure you're running Chrome 127 or later
+ - Check version: `chrome://settings/help`
+
+2. **Enable AI Features**
+ - Visit `chrome://flags/#optimization-guide-on-device-model`
+ - Set to "Enabled"
+ - Restart Chrome
+
+3. **Verify Availability**
+ ```tsx
+ const { aiAvailability } = useForm();
+ console.log(aiAvailability);
+ // { available: true, status: 'readily', needsDownload: false }
+ ```
+
+### Model Download
+
+On first use, Chrome AI requires downloading a language model (~1-2GB).
+
+**Requirements:**
+- User interaction (button click) to start download
+- Stable internet connection
+- ~1-2GB of free disk space
+- User must keep the tab open during download
+
+**Handling Download:**
+
+```tsx
+const { aiAvailability, aiDownloadProgress, aiAutofill } = useForm({
+ ai: { providers: [{ type: 'chrome' }] }
+});
+
+if (aiAvailability?.needsDownload) {
+ return (
+
+
Chrome AI requires a one-time model download (~1-2GB)
Downloading AI model... Please keep this tab open.
+
+
{Math.round(aiDownloadProgress || 0)}% complete
+
+ );
+}
+```
+
+## Other AI Providers
+
+### OpenAI Provider
+
+**Browser Requirements:**
+- Any modern browser with JavaScript enabled
+- Internet connection required
+
+**Compatibility:**
+- ✅ Chrome
+- ✅ Firefox
+- ✅ Safari
+- ✅ Edge
+- ✅ Opera
+- ✅ Mobile browsers
+
+### Custom Server Provider
+
+**Browser Requirements:**
+- Any modern browser with JavaScript enabled
+- Internet connection required
+- CORS must be configured on your server
+
+**Compatibility:**
+- ✅ Chrome
+- ✅ Firefox
+- ✅ Safari
+- ✅ Edge
+- ✅ Opera
+- ✅ Mobile browsers
+
+### Browser AI Provider
+
+**Browser Requirements:**
+- Depends on the specific browser AI service
+- Internet connection required
+
+## Fallback Strategy
+
+For maximum compatibility, configure multiple providers with fallback:
+
+```tsx
+
+
+
+```
+
+**Fallback Behavior:**
+- Chrome users: Use Chrome AI (free, fast, private)
+- Other browsers: Automatically use OpenAI or Custom server
+- No code changes needed
+
+## Checking Browser Support
+
+Programmatically check if Chrome AI is available:
+
+```tsx
+const { aiAvailability, refreshAvailability } = useForm();
+
+useEffect(() => {
+ refreshAvailability();
+}, []);
+
+if (!aiAvailability) {
+ return