Complete API documentation for React Hook Form AI.
function useForm<T extends FieldValues>(
options?: UseFormProps<T> & { ai?: AIFormOptions }
): UseFormAIReturn<T>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:
const { register, handleSubmit, aiAutofill } = useForm<FormData>();
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register('name')} />
<button type="button" onClick={() => aiAutofill()}>
AI Autofill
</button>
</form>
);With AI configuration:
const form = useForm<FormData>({
ai: {
enabled: true,
debounceMs: 500,
excludeFields: ['password'],
providers: [
{ type: 'chrome', priority: 10 },
{ type: 'openai', apiKey: 'sk-...', priority: 5 }
]
}
});Handling Chrome AI download:
const { aiAvailability, aiDownloadProgress, aiAutofill } = useForm<FormData>();
if (aiAvailability?.needsDownload) {
return <button onClick={() => aiAutofill()}>Download AI Model</button>;
}
if (aiAvailability?.status === 'downloading') {
return <progress value={aiDownloadProgress || 0} max={100} />;
}function useAIAssistant(options?: AIAssistantOptions): {
suggestValue: (name: string, value: string) => Promise<string | null>;
autofill: (fields: string[], options?: { onDownloadProgress?: (progress: number) => void }) => Promise<AutofillData>;
checkAvailability: () => Promise<{ available: boolean; status: string; needsDownload: boolean }>;
}Low-level AI assistant hook for advanced use cases.
Parameters:
options- Configuration options for the AI assistantenabled?: boolean- Enable AI features (default: true)formContext?: Record<string, any>- Current form values for contextapiUrl?: string- API endpoint for AI fallbackproviders?: AIProvider[]- Override providers from AIFormProviderexecutionOrder?: AIProviderType[]- Override execution orderfallbackOnError?: 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:
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:
const ai = useAIAssistant({
providers: [
{ type: 'openai', apiKey: 'sk-...', priority: 10 }
],
executionOrder: ['openai'],
fallbackOnError: false
});function useAIFormContext(): AIFormContextValueHook 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:
function MyComponent() {
const { providers, executionOrder } = useAIFormContext();
// Use context values...
}function useOptionalAIFormContext(): AIFormContextValue | nullHook 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:
function MyComponent() {
const context = useOptionalAIFormContext();
if (context) {
// Use context values...
} else {
// Use default values...
}
}function AIFormProvider(props: AIFormProviderProps): JSX.ElementGlobal AI configuration provider for React Hook Form AI.
Props: See 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:
<AIFormProvider
providers={[
{ type: 'chrome', priority: 10 },
{ type: 'openai', apiKey: 'sk-...', priority: 5 }
]}
fallbackOnError={true}
>
<App />
</AIFormProvider>With custom execution order:
<AIFormProvider
providers={[
{ type: 'chrome', priority: 10 },
{ type: 'openai', apiKey: 'sk-...', priority: 5 },
{ type: 'custom', apiUrl: 'https://api.example.com', priority: 1 }
]}
executionOrder={['chrome', 'openai', 'custom']}
fallbackOnError={true}
debounceMs={500}
excludeFields={['password', 'ssn']}
>
<App />
</AIFormProvider>Extended return type from useForm hook with AI capabilities.
Type Parameters:
T- The form data type extending FieldValues
Extends: UseFormReturn<T> from React Hook Form
Properties:
Indicates whether AI features are enabled for this form instance.
const { aiEnabled } = useForm({ ai: { enabled: true } });
console.log(aiEnabled); // trueTriggers 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<void> - Resolves when autofill is complete, rejects on error.
Example:
// Autofill all fields
await aiAutofill();
// Autofill specific fields only
await aiAutofill(['firstName', 'lastName']);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<string | null> - The suggested value, or null if no suggestion is available
Example:
const suggestion = await aiSuggest('email');
if (suggestion) {
setValue('email', suggestion);
}Indicates whether an AI operation (autofill or suggest) is currently in progress.
Example:
<button onClick={() => aiAutofill()} disabled={aiLoading}>
{aiLoading ? 'Filling...' : 'AI Autofill'}
</button>Provides information about AI availability status.
Properties:
available:trueif AI is ready to usestatus: Current status string ('readily','downloadable','downloading','unavailable','error')needsDownload:trueif the AI model needs to be downloaded (Chrome AI only)
Example:
if (aiAvailability?.needsDownload) {
return <button onClick={() => aiAutofill()}>Download AI Model & Autofill</button>;
}
if (!aiAvailability?.available) {
return <p>AI unavailable: {aiAvailability?.status}</p>;
}Manually refreshes the AI availability status.
Returns: Promise<void> - Resolves when availability check is complete
Example:
useEffect(() => {
const interval = setInterval(async () => {
if (aiAvailability?.status === 'downloading') {
await refreshAvailability();
}
}, 2000);
return () => clearInterval(interval);
}, [aiAvailability?.status]);Download progress percentage (0-100) when the Chrome AI model is being downloaded. null when not downloading.
Example:
{aiDownloadProgress !== null && (
<div>
<progress value={aiDownloadProgress} max={100} />
<span>{aiDownloadProgress}% downloaded</span>
</div>
)}Configuration options for AI features in the form.
Properties:
Enable or disable AI features for this form. Default: true
API endpoint for custom server provider. Default: 'http://localhost:3001'
Debounce time in milliseconds for AI suggestions on field blur. Default: 800
Array of field names to exclude from AI processing (e.g., passwords, credit cards). Default: []
Automatically check AI availability when the form mounts. Default: true
Override AI providers for this specific form. Inherits from AIFormProvider if not specified.
Override the order in which providers are tried. Inherits from AIFormProvider if not specified.
Automatically try the next provider if one fails. Default: true
Context information for AI to use when generating suggestions. Can be a string description or an object with contextual data.
Example:
const form = useForm<FormData>({
ai: {
enabled: true,
debounceMs: 500,
excludeFields: ['password', 'creditCard'],
providers: [
{ type: 'chrome', priority: 10 },
{ type: 'openai', apiKey: 'sk-...', priority: 5 }
],
executionOrder: ['chrome', 'openai'],
fallbackOnError: true,
formContext: 'Senior software engineer applying for a tech lead position'
}
});Props for the AIFormProvider component.
Properties:
Child components that will have access to the AI context.
Array of AI provider configurations. Required.
Array specifying the order to try providers. If not provided, providers are sorted by priority (highest first).
When true, automatically tries the next provider if one fails. Default: true
Globally enable/disable AI features. Default: true
Debounce time in milliseconds for AI suggestions. Default: 800
Array of field names to exclude from AI processing. Default: []
Global context information for AI to use when generating suggestions. Can be a string description or an object with contextual data. Forms can override this with their own local context.
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 endpointbrowser: Browser-based AI service
type AIProvider = OpenAIConfig | CustomServerConfig | ChromeAIConfig | BrowserAIConfig;Union type of all supported AI provider configurations.
Example:
const providers: AIProvider[] = [
{ type: 'chrome', priority: 10 },
{ type: 'openai', apiKey: 'sk-...', priority: 5 },
{ type: 'custom', apiUrl: 'https://api.example.com', priority: 1 }
];Configuration for OpenAI provider.
Properties:
Must be 'openai'.
OpenAI API key. Required.
Custom API endpoint. Optional, defaults to OpenAI's API.
Model to use. Optional, defaults to 'gpt-3.5-turbo'.
Supported models:
gpt-3.5-turbo(default) - Fast and cost-effectivegpt-4- More accurate but slower and more expensivegpt-4-turbo- Balance of speed and accuracy
OpenAI organization ID. Optional.
Set to false to disable this provider. Optional.
Higher values are tried first. Optional, default: 0.
Example:
const config: OpenAIConfig = {
type: 'openai',
apiKey: 'sk-...',
model: 'gpt-4',
organization: 'org-...',
priority: 5
};Configuration for custom AI server provider.
Properties:
Must be 'custom'.
Custom API endpoint. Required.
Your server must implement these endpoints:
GET /health- Health checkPOST /api/suggest- Field suggestionPOST /api/autofill- Form autofill
Custom HTTP headers for requests. Optional.
Set to false to disable this provider. Optional.
Higher values are tried first. Optional, default: 0.
Example:
const config: CustomServerConfig = {
type: 'custom',
apiUrl: 'https://your-api.com',
headers: {
'Authorization': 'Bearer token',
'X-Custom-Header': 'value'
},
priority: 1
};Configuration for Chrome Built-in AI provider.
Properties:
Must be 'chrome'.
Set to false to disable this provider. Optional.
Higher values are tried first. Optional, default: 0.
Custom prompt template for Chrome AI. Use placeholders {fieldName}, {currentValue}, {formContext}, and {fields} for dynamic values. If not provided, uses the default prompt.
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:
const config: ChromeAIConfig = {
type: 'chrome',
priority: 10,
systemPrompt: 'You are a professional recruiter. For field {fieldName} with value "{currentValue}", suggest a professional response. Context: {formContext}. Return only the value.'
};Configuration for browser-based AI provider.
Properties:
Must be 'browser'.
Browser AI service endpoint. Required.
Custom HTTP headers for requests. Optional.
Set to false to disable this provider. Optional.
Higher values are tried first. Optional, default: 0.
Example:
const config: BrowserAIConfig = {
type: 'browser',
apiUrl: 'https://browser-ai.example.com',
priority: 3
};Context value provided by AIFormProvider.
Properties:
Array of configured AI providers.
Order in which providers should be tried.
Whether to fallback to next provider on error.
Whether AI features are globally enabled.
Debounce time in milliseconds for AI suggestions.
Array of field names to exclude from AI processing.
Response from an AI provider.
Properties:
The AI-generated suggestion.
Which provider generated this response.
Optional confidence score (0-1).