ai
semver
>=2.0.0 <7.0.0postconditions45functions14last verified2026-06-23coverage score94%Postconditions — what we check
- generateText · api-error-rate-limiterrorWhenAPI provider returns 429 (rate limit exceeded)Throws
Error with API error detailsRequired handlingCaller MUST wrap in try-catch and implement retry logic with exponential backoff. Check error response for Retry-After header. Consider using maxRetries parameter.costmediumin prodimmediate exceptionusers seeservice unavailablevisibilityvisibleSources[1] - generateText · api-error-autherrorWhenAPI provider returns 401/403 (authentication/authorization failure)Throws
Error with authentication error detailsRequired handlingCaller MUST wrap in try-catch and verify API key configuration. Do not retry authentication errors automatically.costmediumin prodimmediate exceptionusers seeservice unavailablevisibilityvisibleSources[1] - generateText · api-error-networkerrorWhenNetwork error or connection timeout occursThrows
Error with network error detailsRequired handlingCaller MUST wrap in try-catch to handle network failures gracefully. Consider using maxRetries parameter for transient network errors.costmediumin prodimmediate exceptionusers seeservice unavailablevisibilityvisibleSources[1] - generateText · api-error-invalid-requesterrorWhenAPI provider returns 400 (invalid request parameters)Throws
Error with validation error detailsRequired handlingCaller MUST wrap in try-catch and validate input parameters before calling. Check error message for specific validation failures.costmediumin prodimmediate exceptionusers seeservice unavailablevisibilityvisibleSources[1] - generateText · model-error-content-filtererrorWhenModel response triggers content filtering/safety checksThrows
Error indicating content was filteredRequired handlingCaller MUST wrap in try-catch and handle content filtering errors appropriately. Consider implementing content pre-screening or alternative prompts.costmediumin prodimmediate exceptionusers seeservice unavailablevisibilityvisibleSources[1] - streamText · stream-error-no-handlererrorWhenError occurs during streaming but no onError handler is providedThrows
Error is included in stream without being caught, may crash serverRequired handlingCaller MUST provide an onError callback to handle stream errors gracefully. Without onError, errors can crash the application. Errors do NOT throw in streamText.costmediumin prodimmediate exceptionusers seeservice unavailablevisibilityvisibleSources[2] - streamText · stream-error-rate-limiterrorWhenAPI provider returns 429 during streamingThrows
Error passed to onError callbackRequired handlingCaller MUST provide onError callback to handle rate limit errors. Return appropriate error message to include in stream.costmediumin prodimmediate exceptionusers seeservice unavailablevisibilityvisibleSources[2] - streamText · stream-error-networkerrorWhenNetwork error occurs during streamingThrows
Error passed to onError callbackRequired handlingCaller MUST provide onError callback to handle network failures during streaming. Return appropriate error message to include in stream.costmediumin prodimmediate exceptionusers seeservice unavailablevisibilityvisibleSources[2] - generateObject · schema-validation-errorerrorWhenGenerated output does not match provided Zod schemaThrows
Error with schema validation detailsRequired handlingCaller MUST wrap in try-catch to handle schema validation failures. Model may generate invalid JSON or data that doesn't conform to schema.costmediumin prodimmediate exceptionusers seeservice unavailablevisibilityvisibleSources[3] - generateObject · api-error-rate-limiterrorWhenAPI provider returns 429 (rate limit exceeded)Throws
Error with API error detailsRequired handlingCaller MUST wrap in try-catch and implement retry logic with exponential backoff. Consider using maxRetries parameter.costmediumin prodimmediate exceptionusers seeservice unavailablevisibilityvisibleSources[3] - generateObject · api-error-autherrorWhenAPI provider returns 401/403 (authentication failure)Throws
Error with authentication error detailsRequired handlingCaller MUST wrap in try-catch and verify API key configuration. Do not retry authentication errors automatically.costmediumin prodimmediate exceptionusers seeservice unavailablevisibilityvisibleSources[3] - generateObject · api-error-networkerrorWhenNetwork error or connection timeout occursThrows
Error with network error detailsRequired handlingCaller MUST wrap in try-catch to handle network failures gracefully. Consider using maxRetries for transient errors.costmediumin prodimmediate exceptionusers seeservice unavailablevisibilityvisibleSources[3] - generateObject · json-parsing-errorerrorWhenModel generates invalid JSON that cannot be parsedThrows
Error with JSON parsing detailsRequired handlingCaller MUST wrap in try-catch to handle JSON parsing failures. Model may generate malformed JSON despite JSON mode being enabled.costmediumin prodimmediate exceptionusers seeservice unavailablevisibilityvisibleSources[3] - streamObject · stream-error-no-handlererrorWhenError occurs during streaming but no onError handler is providedThrows
Error is included in stream without being caughtRequired handlingCaller MUST provide an onError callback to handle stream errors gracefully. Schema validation and API errors will be passed to onError.costmediumin prodimmediate exceptionusers seeservice unavailablevisibilityvisibleSources[3] - streamObject · stream-schema-validation-errorerrorWhenStreamed output does not match provided Zod schemaThrows
Error passed to onError callbackRequired handlingCaller MUST provide onError callback to handle schema validation failures. Partial streamed objects may fail validation.costmediumin prodimmediate exceptionusers seeservice unavailablevisibilityvisibleSources[3] - streamObject · stream-error-rate-limiterrorWhenAPI provider returns 429 during streamingThrows
Error passed to onError callbackRequired handlingCaller MUST provide onError callback to handle rate limit errors.costmediumin prodimmediate exceptionusers seeservice unavailablevisibilityvisibleSources[3] - embed · api-error-rate-limiterrorWhenAPI provider returns 429 (rate limit exceeded)Throws
Error with API error detailsRequired handlingCaller MUST wrap in try-catch and implement retry logic with exponential backoff.costmediumin prodimmediate exceptionusers seeservice unavailablevisibilityvisibleSources[4] - embed · api-error-autherrorWhenAPI provider returns 401/403 (authentication failure)Throws
Error with authentication error detailsRequired handlingCaller MUST wrap in try-catch and verify API key configuration.costmediumin prodimmediate exceptionusers seeservice unavailablevisibilityvisibleSources[4] - embed · api-error-networkerrorWhenNetwork error or connection timeout occursThrows
Error with network error detailsRequired handlingCaller MUST wrap in try-catch to handle network failures gracefully.costmediumin prodimmediate exceptionusers seeservice unavailablevisibilityvisibleSources[4] - embed · input-too-longerrorWhenInput text exceeds model's maximum token limitThrows
Error indicating input is too longRequired handlingCaller MUST wrap in try-catch and validate input length before calling. Chunk large inputs or use appropriate model with longer context.costmediumin prodimmediate exceptionusers seeservice unavailablevisibilityvisibleSources[4] - embedMany · api-error-rate-limiterrorWhenAPI provider returns 429 (rate limit exceeded)Throws
Error with API error detailsRequired handlingCaller MUST wrap in try-catch and implement retry logic with exponential backoff. Consider processing batch in smaller chunks to avoid rate limits.costmediumin prodimmediate exceptionusers seeservice unavailablevisibilityvisibleSources[4] - embedMany · api-error-autherrorWhenAPI provider returns 401/403 (authentication failure)Throws
Error with authentication error detailsRequired handlingCaller MUST wrap in try-catch and verify API key configuration.costmediumin prodimmediate exceptionusers seeservice unavailablevisibilityvisibleSources[4] - embedMany · api-error-networkerrorWhenNetwork error or connection timeout occursThrows
Error with network error detailsRequired handlingCaller MUST wrap in try-catch to handle network failures gracefully.costmediumin prodimmediate exceptionusers seeservice unavailablevisibilityvisibleSources[4] - embedMany · batch-size-exceedederrorWhenBatch size exceeds API provider's maximumThrows
Error indicating batch is too largeRequired handlingCaller MUST wrap in try-catch and split large batches into smaller chunks. Check API provider's batch size limits.costmediumin prodimmediate exceptionusers seeservice unavailablevisibilityvisibleSources[4] - embedMany · partial-batch-failureerrorWhenSome embeddings in batch fail but others succeedThrows
Error with details about which inputs failedRequired handlingCaller MUST wrap in try-catch and handle partial batch failures. May need to retry failed items individually.costmediumin prodimmediate exceptionusers seeservice unavailablevisibilityvisibleSources[4] - tool · tool-execution-errorerrorWhenTool function throws an error during executionThrows
Error from tool function executionRequired handlingCaller MUST wrap tool.execute in try-catch to handle execution errors. Tool errors should be reported back to the model appropriately.costmediumin prodimmediate exceptionusers seeservice unavailablevisibilityvisibleSources[5] - tool · tool-schema-validation-errorerrorWhenTool arguments do not match provided Zod schemaThrows
Error with schema validation detailsRequired handlingCaller MUST validate tool parameters with Zod schema. Model may provide invalid arguments despite schema being specified.costmediumin prodimmediate exceptionusers seeservice unavailablevisibilityvisibleSources[5] - generateImage · generateimage-no-image-generatederrorWhenThe image model returns an empty response — zero images in the provider response. Triggered by content policy violations (prompt filtered), model capacity issues, or provider returning an empty images array.Throws
NoImageGeneratedError (AI_NoImageGeneratedError extends AISDKError)Required handlingCaller MUST wrap in try-catch and use NoImageGeneratedError.isInstance(error) to detect this specific failure. Check error.responses for provider metadata and error.cause for the underlying reason. Common in SaaS apps: image generation pipelines that silently drop user-submitted prompts when the model rejects them.costmediumin prodsilent failureusers seedegraded performancevisibilitysilent - generateImage · generateimage-api-call-errorerrorWhenProvider API returns HTTP error: 401/403 (invalid/expired API key or quota exceeded), 429 (rate limit), 400 (invalid parameters such as unsupported size format), or 5xx (provider outage). Thrown by the underlying APICallError with statusCode set.Throws
APICallError (from @ai-sdk/provider) wrapping the HTTP errorRequired handlingCaller MUST wrap in try-catch. APICallError includes statusCode, responseBody, and isRetryable (true for 429/5xx, false for 401/400). Check APICallError.isInstance(error) to distinguish from NoImageGeneratedError. Rate-limited callers should inspect error.statusCode === 429 and implement backoff.costhighin prodimmediate exceptionusers seeservice unavailablevisibilityvisible - generateImage · generateimage-retry-exhaustedwarningWhenAll retry attempts fail (default maxRetries=2). Wrapped errors are returned as RetryError with reason='maxRetriesExceeded'. Only retryable errors (429, 5xx) are retried; auth errors (401/403) surface immediately as APICallError.Throws
RetryError (extends AISDKError) with reason='maxRetriesExceeded' and errors arrayRequired handlingCaller MUST catch RetryError to distinguish transient failures (network issues, rate limits that exhausted retries) from permanent failures. RetryError.errors contains all underlying errors for diagnostic logging.costmediumin proddegraded serviceusers seedegraded performancevisibilityvisibleSources[7] - generateSpeech · generatespeech-no-speech-generatederrorWhenThe speech model returns an empty or null audio response. Triggered by unsupported voice names, invalid outputFormat values, text exceeding model limits, or provider returning empty audio data.Throws
NoSpeechGeneratedError (AI_NoSpeechGeneratedError extends AISDKError)Required handlingCaller MUST wrap in try-catch and use NoSpeechGeneratedError.isInstance(error). Check error.responses for provider response metadata including timestamp and modelId. Common failure mode: TTS pipelines in AI-powered apps that process user text without validating voice/format parameters first.costmediumin prodsilent failureusers seedegraded performancevisibilitysilent - generateSpeech · generatespeech-api-call-errorerrorWhenProvider API returns HTTP error: 401/403 (invalid API key), 429 (rate limit), 400 (invalid voice name, unsupported language, or invalid outputFormat), or 5xx (provider outage).Throws
APICallError (from @ai-sdk/provider) with statusCode and isRetryableRequired handlingCaller MUST wrap in try-catch. Check APICallError.isInstance(error) and inspect error.statusCode. Rate-limited callers (429) should wait and retry. Auth failures (401) should surface as configuration errors, not silent failures.costhighin prodimmediate exceptionusers seeservice unavailablevisibilityvisible - transcribe · transcribe-no-transcript-generatederrorWhenThe transcription model returns an empty or null text response. Triggered by empty/silent audio files, audio formats unsupported by the model, audio too short to transcribe, or model returning empty text.Throws
NoTranscriptGeneratedError (AI_NoTranscriptGeneratedError extends AISDKError)Required handlingCaller MUST wrap in try-catch and use NoTranscriptGeneratedError.isInstance(error). Check error.responses for provider metadata. Common failure mode: silent audio files or very short clips passed to Whisper that return empty transcripts.costmediumin prodsilent failureusers seelost datavisibilitysilent - transcribe · transcribe-download-errorerrorWhenAudio is provided as a URL and the download fails or exceeds the 2 GiB default size limit. DownloadError includes the URL and cause. Customizable with createDownload({ maxBytes: N }).Throws
DownloadError (from @ai-sdk/provider-utils)Required handlingCaller MUST wrap in try-catch when passing audio as a URL. Use DownloadError.isInstance(error) to detect download failures specifically. Validate audio file size before calling transcribe() with URL inputs. Consider using createDownload() to configure size limits.costmediumin prodimmediate exceptionusers seeservice unavailablevisibilityvisible - transcribe · transcribe-api-call-errorerrorWhenProvider API returns HTTP error: 401/403 (invalid API key), 429 (rate limit), 400 (unsupported audio format or invalid parameters), or 5xx (provider outage). Whisper specifically returns 400 for audio files it cannot decode.Throws
APICallError (from @ai-sdk/provider) with statusCode and isRetryableRequired handlingCaller MUST wrap in try-catch. Check APICallError.isInstance(error) and inspect error.statusCode. 400 errors from Whisper often indicate corrupt or unsupported audio formats — validate format before retrying.costhighin prodimmediate exceptionusers seeservice unavailablevisibilityvisible - rerank · rerank-api-call-errorerrorWhenProvider API returns HTTP error: 401/403 (invalid API key), 429 (rate limit), 400 (invalid parameters such as topN > documents.length), or 5xx (outage). Cohere Rerank specifically returns 400 for empty document arrays.Throws
APICallError (from @ai-sdk/provider) with statusCode and isRetryableRequired handlingCaller MUST wrap in try-catch. Check APICallError.isInstance(error) and inspect error.statusCode to distinguish auth failures (401) from rate limits (429) from invalid inputs (400). Do not retry 400 errors — fix the input first.costmediumin proddegraded serviceusers seedegraded performancevisibilitysilent - rerank · rerank-retry-exhaustedwarningWhenAll retry attempts for transient errors (429, 5xx) are exhausted. maxRetries defaults to 2. RetryError wraps all underlying errors.Throws
RetryError (extends AISDKError) with reason='maxRetriesExceeded'Required handlingCaller MUST catch RetryError for RAG pipelines to implement graceful degradation: fall back to returning documents in original order rather than failing the entire search request. RetryError.errors contains the full error history.costlowin proddegraded serviceusers seedegraded performancevisibilityvisibleSources[7] - ToolLoopAgent · agent-api-errorerrorWhenToolLoopAgent.generate() / ToolLoopAgent.stream() throw APICallError (or one of its subclasses) when the underlying provider call fails: 401/403 authentication, 429 rate limit, 5xx outage, 400 invalid request. The agent delegates to generateText / streamText so the full provider error surface propagates.Throws
APICallError (from @ai-sdk/provider) with statusCode and isRetryableRequired handlingCaller MUST wrap agent.generate() / agent.stream() in try-catch. Long-running agent loops magnify the cost of an unhandled provider error: every step burns tokens, and an uncaught error halfway through a 10-step loop loses all prior progress. Use APICallError.isInstance(error) to distinguish from tool-level errors. For 429, honor the Retry-After header before retrying the whole loop.costmediumin prodimmediate exceptionusers seeservice unavailablevisibilityvisible - ToolLoopAgent · agent-invalid-argumenterrorWhenToolLoopAgent.generate() and .stream() throw InvalidArgumentError when the caller-supplied options fail the agent's callOptionsSchema validation. Added in ai@6.0.0 (changelog 48f842a) — prior versions silently accepted any options shape because the schema was declared but never invoked. Common trigger: drifting client/server contracts on agent options after a model rev.Throws
InvalidArgumentError (AI_InvalidArgumentError from @ai-sdk/provider)Required handlingCaller MUST wrap agent.generate() / agent.stream() in try-catch. An unhandled InvalidArgumentError aborts the entire request handler and surfaces as a 500 to the client, when the correct behavior is to return a 400 with a structured validation message so the caller can fix the options shape.costlowin prodimmediate exceptionusers seeservice unavailablevisibilityvisibleSources[7] - ToolLoopAgent · agent-no-output-generatedwarningWhenToolLoopAgent.generate() throws NoOutputGeneratedError when the loop terminates without producing any text or structured output. This can happen if the stop condition trips before the model emits text (e.g. stepCountIs(0) misconfiguration, or a model that returns only tool calls with no final answer).Throws
NoOutputGeneratedError (AI_NoOutputGeneratedError, extends AISDKError)Required handlingCaller MUST catch NoOutputGeneratedError and either re-prompt with a stronger system message, return an explicit "no answer" UX state, or fall back to a non-agent generateText call. Treating absent output as empty string causes downstream "why is the assistant silent?" support tickets.costlowin prodimmediate exceptionusers seedegraded performancevisibilityvisibleSources[7] - ToolLoopAgent · agent-missing-tool-resultserrorWhenToolLoopAgent.generate() / .stream() throw MissingToolResultsError when the loop body emits a tool call but the harness fails to feed back a tool result before the next model step. Most common when a tool's execute callback throws an uncaught error and the caller has not configured experimental_repairToolCall.Throws
MissingToolResultsError (extends AISDKError)Required handlingCaller MUST wrap agent.generate() / .stream() in try-catch AND either (a) make every tool.execute() bullet-proof with its own try-catch that returns a structured error result, or (b) configure experimental_repairToolCall to synthesize a tool result when the execute callback throws.costmediumin prodimmediate exceptionusers seeservice unavailablevisibilityvisible - ToolLoopAgent · agent-retry-exhaustedwarningWhenToolLoopAgent.generate() / .stream() throw RetryError when every retry attempt for transient provider failures (429, 5xx) is exhausted. The underlying generateText / streamText delegation uses maxRetries=2 by default; a long agent loop amplifies this because every step is its own retry budget.Throws
RetryError (extends AISDKError) with reason='maxRetriesExceeded'Required handlingCaller MUST catch RetryError. For agent-driven user-facing features, partial step results from the loop are still useful — read them off the agent state and present a "stopped early due to provider issues" UX rather than failing the whole interaction.costlowin proddegraded serviceusers seedegraded performancevisibilityvisibleSources[7] - validateUIMessages · validate-ui-messages-type-validationerrorWhenvalidateUIMessages() throws TypeValidationError (AI_TypeValidationError) when any persisted UIMessage fails schema validation. Common triggers: schema migration without a backfill of stored messages, a removed tool whose persisted tool calls are now unknown, an output-error part whose runtime shape drifted from the validator schema (fixed in 6.0.205-ish via changelogs af580ea and 9667780).Throws
TypeValidationError (AI_TypeValidationError) from @ai-sdk/providerRequired handlingCaller MUST wrap validateUIMessages in try-catch. The documented recommendation (https://ai-sdk.dev/docs/ai-sdk-ui/chatbot-message-persistence) is to log the validation error, then EITHER start the chat with an empty history OR run a one-shot migration that filters incompatible messages. NEVER let the error propagate to the request handler — it will surface as a 500 and lock the user out of the entire chat thread. Prefer safeValidateUIMessages() if branching on success/failure feels cleaner than try-catch.costmediumin prodimmediate exceptionusers seelost datavisibilityvisible - createUIMessageStream · create-ui-message-stream-error-leakerrorWhencreateUIMessageStream is called WITHOUT an explicit onError handler in an application that runs against ai < 6.0.207, OR with an onError that returns the raw Error object / a JSON.stringify of the error. Either shape allows server-side exception details (stack traces, file paths, API keys leaked into error messages, provider request payloads) to flow into the client-facing { type: 'error', errorText } chunk.Throws
Does not throw at the createUIMessageStream call site — the security failure is data exposure on the wire, not a thrown exception. Functionally equivalent to a thrown error from the perspective of contracting because the postcondition is "caller must explicitly configure error redaction".Required handlingCaller MUST pass an explicit onError handler that returns ONLY a generic, application-controlled error string (e.g. "An error occurred while processing your request"). Do NOT return error.message, error.toString(), or JSON.stringify(error). For ai versions < 6.0.207, this is mandatory even when the docs would imply a safe default. For ai >= 6.0.207, the default is already safe but relying on the default in shared code paths is brittle — pin the behavior with an explicit handler.costhighin prodsilent failureusers seedegraded performancevisibilitysilent - createUIMessageStream · create-ui-message-stream-execute-throwerrorWhenThe execute callback passed to createUIMessageStream throws an unhandled error (most often from an inner streamText call hitting a provider 5xx or RetryError). When this happens the stream emits an error chunk via the onError handler and terminates. Callers that await the stream (rather than piping it to a Response) must catch the rethrown error or risk an unhandled promise rejection at the edge.Throws
UIMessageStreamError (AI_UIMessageStreamError) wrapping the underlying errorRequired handlingCaller MUST either (a) pipe the stream to a Response via createUIMessageStreamResponse / pipeUIMessageStreamToResponse and let the framework drive consumption, OR (b) wrap the consumer in try-catch and treat UIMessageStreamError.isInstance(error) as a terminal stream signal. Do not assume the stream "just ends" — a mid-stream failure must be observable to the request handler so the server can emit appropriate logging / metrics.costmediumin proddegraded serviceusers seeservice unavailablevisibilitysilentSources[7]
Sources
Every postcondition cites at least one of these. Numbered to match the footnotes above.
- [1]ai-sdk.dev/docs/ai-sdk-corehttps://ai-sdk.dev/docs/ai-sdk-core/generating-text
- [2]ai-sdk.dev/docs/referencehttps://ai-sdk.dev/docs/reference/ai-sdk-core/stream-text
- [3]ai-sdk.dev/docs/ai-sdk-corehttps://ai-sdk.dev/docs/ai-sdk-core/generating-structured-data
- [4]ai-sdk.dev/docs/ai-sdk-corehttps://ai-sdk.dev/docs/ai-sdk-core/embeddings
- [5]ai-sdk.dev/docs/ai-sdk-corehttps://ai-sdk.dev/docs/ai-sdk-core/tools-and-tool-calling
- [6]ai-sdk.dev/docs/ai-sdk-corehttps://ai-sdk.dev/docs/ai-sdk-core/image-generation
- [7]ai-sdk.dev/docs/referencehttps://ai-sdk.dev/docs/reference/ai-sdk-errors
- [8]ai-sdk.dev/docs/ai-sdk-corehttps://ai-sdk.dev/docs/ai-sdk-core/speech
- [9]ai-sdk.dev/docs/ai-sdk-corehttps://ai-sdk.dev/docs/ai-sdk-core/transcription
- [10]ai-sdk.dev/docs/referencehttps://ai-sdk.dev/docs/reference/ai-sdk-core/rerank
- [11]ai-sdk.dev/docs/agentshttps://ai-sdk.dev/docs/agents/overview
- [12]ai-sdk.dev/docs/ai-sdk-uihttps://ai-sdk.dev/docs/ai-sdk-ui/chatbot-message-persistence
- [13]github.com/vercel/aihttps://github.com/vercel/ai/blob/main/packages/ai/CHANGELOG.md
Need a different package?
Request a profile