@meilisearch/ai-sdk involves multiple systems: Meilisearch, an LLM provider, and your application. Any of these can fail. This guide covers common failure modes and how to handle them gracefully.
Common error scenarios
Handle LLM provider errors
generateText throws regular errors that you can catch with try/catch. Use APICallError.isInstance to distinguish provider errors from other failures and branch on the status code:
streamText handles errors differently: it starts streaming immediately and turns errors into error parts of the stream instead of throwing, so a failing provider does not crash your server. Log them with the onError callback:
Fall back to regular search
When agentic search fails, fall back to a standard keyword or hybrid search usingmeilisearch-js. This ensures users still get results:
Handle empty search results
When the search tool returns no matches, the LLM may hallucinate an answer or give a vague response. Use guardrails in your system prompt to handle this:System prompt
hits is empty, display a helpful message instead of relying on the model:
Handle rate limiting
LLM providers enforce rate limits based on requests per minute or tokens per minute.generateText and streamText retry transient errors automatically (maxRetries defaults to 2), but for full control over backoff timing and user feedback, disable the built-in retries and implement your own:
- Use a higher-tier API key with your LLM provider
- Implement client-side debouncing to avoid sending requests on every keystroke
- Cache responses for repeated questions
Manage context window limits
Long conversations can exceed the LLM’s context window, which surfaces as anAPICallError with statusCode 400. Trim older messages before passing them to generateText or streamText to stay within limits:
Display errors in your UI
When an error occurs, give users clear feedback and actionable next steps. Avoid exposing raw error messages or stack traces:Using the experimental Chats API
When using the experimental Chats API, Meilisearch forwards HTTP status codes from your LLM provider on the completions endpoint, and you detect empty results by parsing the_meiliSearchSources tool call. See handle errors and fallbacks with the Chats API for implementation.
Next steps
Configure guardrails
Reduce hallucination with system prompts
Display source documents
Show users which documents were used to generate responses