diff --git a/DOCUMENTATION_STRUCTURE.md b/DOCUMENTATION_STRUCTURE.md new file mode 100644 index 0000000..7afd6bd --- /dev/null +++ b/DOCUMENTATION_STRUCTURE.md @@ -0,0 +1,314 @@ +# Documentation Structure + +This document explains the new documentation structure for React Hook Form AI, designed for easy LLM consumption and better developer experience. + +## Overview + +The documentation has been restructured following the react-hook-form approach: + +- **Modular** - Separate files for different topics +- **LLM-Friendly** - Structured for AI-assisted coding +- **Comprehensive** - Complete API coverage with examples +- **Maintainable** - Auto-generated from TSDoc comments + +## File Structure + +``` +react-hook-form-ai/ +├── README.md # Concise overview with links +├── docs/ +│ ├── README.md # Documentation index +│ ├── GETTING_STARTED.md # Installation & basic usage +│ ├── API_REFERENCE.md # Complete API documentation +│ ├── PROVIDERS.md # Provider configuration guide +│ ├── EXAMPLES.md # Practical examples +│ ├── BROWSER_COMPATIBILITY.md # Browser requirements +│ └── logo.png # Logo image +├── src/ +│ ├── useForm.ts # Enhanced with TSDoc +│ ├── AIFormProvider.tsx # Enhanced with TSDoc +│ ├── utils/useAIAssistant.ts # Enhanced with TSDoc +│ └── types/ai.ts # Enhanced with TSDoc +├── tsdoc.json # TSDoc configuration +├── tsdoc-markdown.config.js # API generator config +└── package.json # Added generate:api-reference script +``` + +## Documentation Files + +### README.md (Root) + +**Purpose:** Quick overview and navigation hub + +**Content:** +- Feature highlights +- Quick start example +- Links to detailed documentation +- API overview +- Browser compatibility table + +**Target Audience:** New users, quick reference + +### docs/GETTING_STARTED.md + +**Purpose:** Onboarding guide for new users + +**Content:** +- Installation instructions +- Basic usage examples +- Key concepts explanation +- Next steps + +**Target Audience:** Developers new to the library + +### docs/API_REFERENCE.md + +**Purpose:** Complete API documentation + +**Content:** +- All hooks with signatures +- All components with props +- All interfaces and types +- Usage examples for each API +- Parameter descriptions +- Return value descriptions + +**Target Audience:** Developers needing detailed API information, LLMs + +**Generation:** Auto-generated from TSDoc comments via `npm run generate:api-reference` + +### docs/PROVIDERS.md + +**Purpose:** Detailed provider configuration guide + +**Content:** +- Chrome Built-in AI setup +- OpenAI configuration +- Custom server setup +- Browser AI configuration +- Multi-provider setup +- Security best practices + +**Target Audience:** Developers configuring AI providers + +### docs/EXAMPLES.md + +**Purpose:** Practical usage examples + +**Content:** +- Multi-provider setup +- Field-level suggestions +- Chrome AI download handling +- Excluding sensitive fields +- Custom debounce timing +- Partial form autofill +- Context-aware suggestions + +**Target Audience:** Developers implementing specific features + +### docs/BROWSER_COMPATIBILITY.md + +**Purpose:** Browser requirements and compatibility + +**Content:** +- Chrome AI requirements +- Other provider compatibility +- Fallback strategies +- Mobile support +- Troubleshooting + +**Target Audience:** Developers dealing with browser compatibility + +## TSDoc Annotations + +All public APIs now have comprehensive TSDoc comments: + +### Example Structure + +```typescript +/** + * Brief description of the function/interface. + * + * @public + * @remarks + * Detailed explanation of the API, its purpose, and behavior. + * + * @typeParam T - Description of type parameter + * @param paramName - Description of parameter + * @returns Description of return value + * + * @example Basic usage + * ```tsx + * // Example code + * ``` + * + * @example Advanced usage + * ```tsx + * // More complex example + * ``` + */ +``` + +### Files with TSDoc + +- `src/useForm.ts` - useForm hook and related interfaces +- `src/AIFormProvider.tsx` - AIFormProvider component and hooks +- `src/utils/useAIAssistant.ts` - useAIAssistant hook +- `src/types/ai.ts` - All AI-related types + +## Generating API Reference + +### Command + +```bash +npm run generate:api-reference +# or +pnpm run generate:api-reference +``` + +### Process + +1. Parses TSDoc comments from source files +2. Generates markdown documentation +3. Outputs to `docs/API_REFERENCE.md` + +### When to Regenerate + +- After adding new public APIs +- After updating TSDoc comments +- After changing function signatures +- Before releasing new versions + +## Benefits for LLM Consumption + +### 1. Modular Structure + +Each document covers a specific topic, making it easy for LLMs to: +- Find relevant information quickly +- Provide focused answers +- Reference specific sections + +### 2. Consistent Format + +All documentation follows consistent patterns: +- Clear headings and subheadings +- Code examples with syntax highlighting +- Parameter descriptions +- Return value descriptions + +### 3. Complete Examples + +Every API includes working examples that LLMs can: +- Reference for code generation +- Adapt to user needs +- Combine for complex scenarios + +### 4. Cross-References + +Documents link to related content: +- API Reference ↔ Examples +- Getting Started → Provider Configuration +- Browser Compatibility → Provider Configuration + +## Maintenance Workflow + +### Adding New Features + +1. **Write Code** with TSDoc comments + ```typescript + /** + * New feature description + * @example + * ```tsx + * // Usage example + * ``` + */ + export function newFeature() { } + ``` + +2. **Generate API Docs** + ```bash + npm run generate:api-reference + ``` + +3. **Update Relevant Guides** + - Add to GETTING_STARTED.md if it's a core feature + - Add to EXAMPLES.md with practical examples + - Update PROVIDERS.md if it affects configuration + +4. **Update README.md** + - Add to features list if significant + - Update quick start if relevant + +### Updating Existing Features + +1. **Update TSDoc** in source files +2. **Regenerate API docs** +3. **Update examples** if behavior changed +4. **Update guides** if configuration changed + +## Best Practices + +### For Contributors + +1. **Always add TSDoc** to public APIs +2. **Include examples** in TSDoc comments +3. **Regenerate API docs** before committing +4. **Test examples** to ensure they work +5. **Update guides** for significant changes + +### For Maintainers + +1. **Review TSDoc** in pull requests +2. **Ensure examples work** before merging +3. **Keep docs in sync** with code +4. **Update version** in documentation +5. **Announce breaking changes** clearly + +## Comparison with Old Structure + +### Before + +- Single large README.md (~1300 lines) +- All content in one file +- Hard to navigate +- Difficult for LLMs to parse +- No auto-generation + +### After + +- Modular documentation (6 focused files) +- Easy navigation with links +- LLM-friendly structure +- Auto-generated API reference +- Comprehensive examples + +## Future Improvements + +### Planned + +- [ ] Interactive examples with CodeSandbox +- [ ] Video tutorials +- [ ] Migration guide from React Hook Form +- [ ] Performance optimization guide +- [ ] Advanced patterns guide + +### Under Consideration + +- [ ] Translations (i18n) +- [ ] API playground +- [ ] Visual diagrams +- [ ] Changelog integration + +## Feedback + +Documentation improvements are always welcome! Please: + +1. Open an issue for suggestions +2. Submit PRs for corrections +3. Share your use cases for better examples + +--- + +**Last Updated:** November 2025 +**Maintained By:** React Hook Form AI Team diff --git a/README.md b/README.md index a3ddb3c..7fad371 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@
- - React Hook AI Form Logo - React hook custom hook for form validation, with AI - + + React Hook AI Form Logo - React hook custom hook for form validation, with AI +
@@ -9,25 +9,24 @@ [![npm downloads](https://img.shields.io/npm/dm/react-hook-form-ai.svg?style=for-the-badge)](https://www.npmjs.com/package/react-hook-form-ai) [![npm](https://img.shields.io/npm/dt/react-hook-form-ai.svg?style=for-the-badge)](https://www.npmjs.com/package/react-hook-form-ai) [![npm](https://img.shields.io/npm/l/react-hook-form-ai?style=for-the-badge)](https://github.com/SaadBazaz/react-hook-form-ai/blob/master/LICENSE) -
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 (
console.log(data))}> {errors.lastName &&

Last name is required.

} - - {errors.age &&

Please enter number for age.

} - {aiAvailability && !aiAvailability.available && ( -

AI is not available. Status: {aiAvailability.status}

- )} -
); } ``` -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 ( -
console.log(data))}> - - - - - - - {error &&

{error}

} - - {aiAvailability && !aiAvailability.available && ( -

AI Status: {aiAvailability.status}

- )} - - -
- ); -} -``` - -**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 ( -
console.log(data))}> -
- - - - {suggestions.username && ( -
- Suggestion: {suggestions.username} - - -
- )} -
- -
- - - - {suggestions.email && ( -
- Suggestion: {suggestions.email} - - -
- )} -
- -
- -