TypeScript specification and interface definitions for AI language model providers within the Vercel AI SDK ecosystem
—
Comprehensive error system with specific error types for different failure scenarios, providing detailed context for debugging and error recovery.
Foundation error class that all AI SDK errors extend from.
/**
* Base class for all AI SDK errors
*/
class AISDKError extends Error {
/** Optional underlying cause of the error */
readonly cause?: unknown;
/**
* Create a new AI SDK error
* @param name - Error name/type
* @param message - Human-readable error message
* @param cause - Optional underlying cause
*/
constructor({ name, message, cause }: { name: string; message: string; cause?: unknown });
/** Check if an error is an AI SDK error */
static isInstance(error: unknown): error is AISDKError;
/** Check if error has a specific marker */
protected static hasMarker(error: unknown, marker: string): boolean;
}Errors related to HTTP API calls and network issues.
/**
* Error thrown when an API call fails
*/
class APICallError extends AISDKError {
/** The URL that was called */
readonly url: string;
/** The request body values that were sent */
readonly requestBodyValues: unknown;
/** HTTP status code (if response received) */
readonly statusCode?: number;
/** Response headers (if available) */
readonly responseHeaders?: Record<string, string>;
/** Response body content (if available) */
readonly responseBody?: string;
/** Whether this error should be retried */
readonly isRetryable: boolean;
/** Additional error data */
readonly data?: unknown;
static isInstance(error: unknown): error is APICallError;
}
/**
* Error thrown when API returns empty response body
*/
class EmptyResponseBodyError extends AISDKError {
static isInstance(error: unknown): error is EmptyResponseBodyError;
}Errors related to input validation and data type checking.
/**
* Error thrown when function arguments are invalid
*/
class InvalidArgumentError extends AISDKError {
/** Name of the invalid argument */
readonly argument: string;
static isInstance(error: unknown): error is InvalidArgumentError;
}
/**
* Error thrown when prompt is invalid or malformed
*/
class InvalidPromptError extends AISDKError {
/** The invalid prompt data */
readonly prompt: unknown;
static isInstance(error: unknown): error is InvalidPromptError;
}
/**
* Error thrown when response data is invalid
*/
class InvalidResponseDataError extends AISDKError {
/** The invalid response data */
readonly data: unknown;
static isInstance(error: unknown): error is InvalidResponseDataError;
}
/**
* Error thrown when type validation fails
*/
class TypeValidationError extends AISDKError {
/** The value that failed validation */
readonly value: unknown;
static isInstance(error: unknown): error is TypeValidationError;
/** Wrap an error as a type validation error */
static wrap({ value, cause }: { value: unknown; cause: unknown }): TypeValidationError;
}Errors related to data parsing and format conversion.
/**
* Error thrown when JSON parsing fails
*/
class JSONParseError extends AISDKError {
/** The text that failed to parse */
readonly text: string;
static isInstance(error: unknown): error is JSONParseError;
}Errors related to configuration and settings loading.
/**
* Error thrown when API key cannot be loaded
*/
class LoadAPIKeyError extends AISDKError {
static isInstance(error: unknown): error is LoadAPIKeyError;
}
/**
* Error thrown when a setting cannot be loaded
*/
class LoadSettingError extends AISDKError {
static isInstance(error: unknown): error is LoadSettingError;
}Errors related to model availability and provider capabilities.
/**
* Error thrown when a requested model is not found
*/
class NoSuchModelError extends AISDKError {
/** The requested model ID */
readonly modelId: string;
/** The type of model that was requested */
readonly modelType: 'languageModel' | 'textEmbeddingModel' | 'imageModel' | 'transcriptionModel' | 'speechModel';
static isInstance(error: unknown): error is NoSuchModelError;
}
/**
* Error thrown when functionality is not supported
*/
class UnsupportedFunctionalityError extends AISDKError {
/** Description of the unsupported functionality */
readonly functionality: string;
static isInstance(error: unknown): error is UnsupportedFunctionalityError;
}Errors related to content generation and model responses.
/**
* Error thrown when no content is generated
*/
class NoContentGeneratedError extends AISDKError {
static isInstance(error: unknown): error is NoContentGeneratedError;
}
/**
* Error thrown when too many embedding values are requested
*/
class TooManyEmbeddingValuesForCallError extends AISDKError {
/** Provider name */
readonly provider: string;
/** Model ID */
readonly modelId: string;
/** Maximum allowed embeddings per call */
readonly maxEmbeddingsPerCall: number;
/** The values that were requested */
readonly values: Array<unknown>;
static isInstance(error: unknown): error is TooManyEmbeddingValuesForCallError;
}Helper functions for error handling and message extraction.
/**
* Extract a human-readable error message from any error type
* @param error - The error to extract message from
* @returns Human-readable error message
*/
function getErrorMessage(error: unknown | undefined): string;Usage Examples:
import {
AISDKError,
APICallError,
NoSuchModelError,
InvalidArgumentError,
getErrorMessage
} from "@ai-sdk/provider";
// Basic error handling
try {
const result = await model.doGenerate({
prompt: [{ role: 'user', content: [{ type: 'text', text: 'Hello!' }] }]
});
} catch (error) {
if (APICallError.isInstance(error)) {
console.error('API call failed:', {
url: error.url,
status: error.statusCode,
retryable: error.isRetryable
});
if (error.isRetryable) {
// Implement retry logic
await new Promise(resolve => setTimeout(resolve, 1000));
// Retry the call
}
} else if (NoSuchModelError.isInstance(error)) {
console.error(`Model ${error.modelId} not found for ${error.modelType}`);
} else {
console.error('Unknown error:', getErrorMessage(error));
}
}
// Specific error type handling
async function handleModelCall() {
try {
const model = provider.languageModel('non-existent-model');
return await model.doGenerate({
prompt: [{ role: 'user', content: [{ type: 'text', text: 'Test' }] }]
});
} catch (error) {
// Check for specific error types
if (NoSuchModelError.isInstance(error)) {
console.log(`Model "${error.modelId}" is not available`);
console.log(`Requested model type: ${error.modelType}`);
// Fallback to a different model
const fallbackModel = provider.languageModel('gpt-3.5-turbo');
return await fallbackModel.doGenerate({
prompt: [{ role: 'user', content: [{ type: 'text', text: 'Test' }] }]
});
}
if (InvalidArgumentError.isInstance(error)) {
console.error(`Invalid argument: ${error.argument}`);
throw error; // Re-throw if we can't handle it
}
throw error; // Re-throw unknown errors
}
}
// Error recovery patterns
async function robustAPICall<T>(
operation: () => Promise<T>,
maxRetries = 3
): Promise<T> {
let lastError: unknown;
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
return await operation();
} catch (error) {
lastError = error;
if (APICallError.isInstance(error)) {
if (!error.isRetryable) {
throw error; // Don't retry non-retryable errors
}
if (error.statusCode === 429) {
// Rate limit - exponential backoff
const delay = Math.min(1000 * Math.pow(2, attempt - 1), 10000);
await new Promise(resolve => setTimeout(resolve, delay));
continue;
}
if (error.statusCode && error.statusCode >= 500) {
// Server error - shorter delay
await new Promise(resolve => setTimeout(resolve, 1000));
continue;
}
}
if (attempt === maxRetries) {
throw error;
}
// Default retry delay
await new Promise(resolve => setTimeout(resolve, 1000 * attempt));
}
}
throw lastError;
}
// Additional error handling utilities (implementation-specific)
// Error handlers can be customized based on application needs
// Error logging and monitoring
function logError(error: unknown, context: Record<string, unknown> = {}) {
const errorInfo = {
message: getErrorMessage(error),
context,
timestamp: new Date().toISOString()
};
if (AISDKError.isInstance(error)) {
errorInfo.context.aiSDKError = true;
errorInfo.context.cause = error.cause;
}
if (APICallError.isInstance(error)) {
errorInfo.context.apiCall = {
url: error.url,
statusCode: error.statusCode,
isRetryable: error.isRetryable
};
}
console.error('AI SDK Error:', errorInfo);
// Send to monitoring service
// monitoringService.logError(errorInfo);
}
// Error boundary for React-like error handling
class AIOperationManager {
async safeExecute<T>(
operation: () => Promise<T>,
fallback?: T
): Promise<T | undefined> {
try {
return await operation();
} catch (error) {
logError(error, { operation: operation.name });
if (fallback !== undefined) {
return fallback;
}
// Optionally re-throw critical errors
if (InvalidArgumentError.isInstance(error)) {
throw error; // Programming errors should bubble up
}
return undefined; // Return undefined for recoverable errors
}
}
}Install with Tessl CLI
npx tessl i tessl/npm-ai-sdk--provider