/chats API: an engine-managed endpoint that consolidates retrieval, context management, and generation into a single call. For most agentic and conversational search projects, start with the AI SDK getting started guide instead, and come back to this page only if you specifically need to call /chats directly.
In code examples, replace
WORKSPACE_NAME with the name of your workspace. On Meilisearch Cloud, the default workspace name is cloud.Setup
Enable the feature, configure your indexes, and create a workspace before you send chat completions.Enable the chat completions feature
Enable chat completions from your Meilisearch Cloud project in one of two ways:- Go to your project’s Settings page and enable it under Experimental features
- Or open the Chat tab in your project and activate the feature directly from there
For self-hosted instances, enable the feature through the experimental features API by sending a
PATCH request with chatCompletions set to true:Find your chat API key
Meilisearch automatically generates a “Default Chat API Key” that combineschatCompletions and search permissions on all indexes. Conversational search requires both actions: chatCompletions authorizes the LLM call, and search authorizes the retrieval step that feeds documents to the model. Any key you use with the /chats routes must carry both actions, so prefer the default chat API key unless you have a specific reason to create a custom one.
Check if you have the key using:
- Create a new API key with both
chatCompletionsandsearchactions, scoped to the exact indexes you want exposed. See manage API keys for the full workflow. - Generate a tenant token from the default chat API key. Tenant tokens inherit both the
chatCompletionsandsearchactions from their parent key and let you narrow index access or attach search rules per user.
A tenant token cannot grant access to an index its parent API key does not already cover. Make sure the parent key is scoped to every index the token should be allowed to reach.
Configure your indexes
Configure chat settings for each index you want the agent to search:descriptiontells the LLM what the index containsdocumentTemplateis a Liquid template that defines the text sent to the LLM for each documentdocumentTemplateMaxBytestruncates the rendered template. The default of 400 bytes balances context quality and speed
Configure a workspace
A workspace holds your LLM provider configuration and system prompt. The model itself is chosen per request in the/chat/completions call, not in the workspace settings.
On Meilisearch Cloud, your project comes with a single default workspace named cloud. Use cloud as WORKSPACE_NAME in all API calls. If you need additional workspaces, contact us.
On self-hosted instances, you can create as many workspaces as you need. If the workspace does not exist, Meilisearch creates it when you first PATCH its settings:
baseUrl is required for all providers except OpenAI. See workspace settings for the provider matrix, then configure guardrails and optimize chat prompts for the system prompt.
Chat patterns
Both patterns usePOST /chats/{workspace}/chat/completions. The difference is the prompt strategy and whether you keep conversation history.
Chat interface
Build a multi-turn interface where users ask follow-up questions. Meilisearch searches your indexes, then passes the retrieved documents to the LLM to generate a grounded response.Streaming is required
All requests to the chat completions endpoint must include"stream": true. Non-streaming (stream: false) is not yet supported and returns a 501 Not Implemented error.
Message roles
Every entry in themessages array carries a role that tells the LLM who authored it:
Send a streaming request
Send aPOST request to /chats/{workspace}/chat/completions with stream: true:
_meiliAppendConversationMessage is the key to multi-turn conversations. The endpoint is stateless, so Meilisearch uses this tool to expose internal search tool calls and their results back to the client. Push those messages into your messages array before the next request, or the LLM loses the context from previous searches.
Complete example: progress, sources, and history
The following example combines all three tools: streaming progress, displaying sources, and maintaining conversation history.JavaScript (Fetch)
Summarized answers
One-shot summarization uses the same/chats API, but with a different prompt strategy: you send a single question and receive a concise answer based on your indexed documents. This is useful for displaying an AI-generated answer alongside traditional search results.
Configure a dedicated workspace prompt that asks for short, self-contained answers and avoids follow-up questions:
_meiliSearchSources lets you display the source documents next to the summary. In a real application, run this in parallel with a standard Meilisearch search request and display both results together.
For more deterministic answers, pass a lower temperature (for example, 0.1 or 0.2). Meilisearch forwards these parameters to your LLM provider.
Configuration shortcuts
Workspace settings connect Meilisearch to an LLM. Index chat settings describe each index to the agent. Both are required.Workspace settings
Create or update a workspace withPATCH /chats/{workspace_uid}/settings. If the workspace does not exist, Meilisearch creates it.
The source field selects the LLM provider:
A few provider-specific rules:
orgId,projectId, andapiVersionare required for Azure OpenAI and are incompatible with every othersourcebaseUrlis required for Azure OpenAI and vLLM. For Mistral it points to the Mistral API endpoint. For OpenAI it is optional and only needed when routing through a custom endpointapiKeyis optional for vLLM and mandatory for every other provider
prompts.system. The prompts object also accepts tool-facing fields (searchDescription, searchQParam, searchFilterParam, searchIndexUidParam) that help the LLM decide when and how to search. See optimize chat prompts for how to tune them.
Retrieve the current settings at any time:
- Get settings of a chat workspace
- Update settings of a chat workspace
- Reset the settings of a chat workspace
LLM provider parameters passthrough
Meilisearch forwards standard chat completion parameters such astemperature, top_p, frequency_penalty, or presence_penalty to the configured provider. Available parameters depend on the provider. See the chat completions API reference.
Index chat settings
chat is an index-level setting, distinct from workspace settings. Configure it on every index the agent should access:
Write
description as if you were explaining the index to someone who has never seen your data. If you have multiple indexes, make each description specific enough that the LLM can distinguish them.
A good documentTemplate includes only the fields relevant to answering questions. See document template best practices.
searchParameters can enable hybrid search, limit results, or apply default sorting:
For conversational queries, a higher
semanticRatio (0.6 to 0.8) and a lower limit (3 to 5) often work better than keyword-oriented defaults. See optimize chat prompts.
For the full HTTP parameter list, see:
Streaming
Meilisearch uses Server-Sent Events (SSE) to stream chat completions. The wire format is OpenAI-compatible, so you can point the official OpenAI SDKs, the Vercel AI SDK, or any other SSE-aware client at the endpoint. For the request itself, reuse the examples in chat interface. The-N flag in cURL disables output buffering so you see each chunk as it arrives.
Understand the SSE response format
Each event on the wire follows three rules:- Every event is a line that begins with the literal prefix
data: - The payload after
data:is a single JSON object shaped like an OpenAIchat.completion.chunk - The stream terminates with the sentinel line
data: [DONE]. The[DONE]marker is a literal string, not JSON, so parsers must check for it before callingJSON.parse
[DONE], close the reader.
Content chunks
Regular content chunks contain the AI-generated text inchoices[0].delta.content:
Tool call chunks
When you include Meilisearch tools, the stream also contains tool call chunks inchoices[0].delta.tool_calls:
End of stream
The stream ends with afinish_reason of "stop" followed by the [DONE] marker:
Handle streaming in JavaScript
Use the Fetch API to process the SSE stream. Parsedata: lines, skip [DONE], then handle delta.content and delta.tool_calls:
_meiliAppendConversationMessage. See the complete example.
Tools reference
Meilisearch intercepts three special tools and never forwards them to the LLM provider. Declare them in thetools array of your request.
Recommended usage order:
- Handle progress updates with
_meiliSearchProgress - Append conversation messages with
_meiliAppendConversationMessage - Display source documents with
_meiliSearchSources - Use
call_idto associate progress updates with their corresponding source results
_meiliSearchProgress
Reports real-time progress of internal search operations.
Arguments:
call_id: Unique identifier to track the search operationfunction_name: Name of the internal function being executed (for example,_meiliSearchInIndex)function_parameters: JSON-encoded string containing search parameters such asqandindex_uid
_meiliAppendConversationMessage
Asks the client to append internal tool calls and results to the conversation history.
Arguments:
role: Message author role (userorassistant)content: Message content (for tool results)tool_calls: Array of tool calls made by the assistanttool_call_id: ID of the tool call this message responds to
_meiliSearchSources
Returns the documents used by the LLM to generate the answer. The call_id matches _meiliSearchProgress so you can associate queries with results.
Arguments:
call_id: Matches thecall_idfrom_meiliSearchProgressdocuments: Source documents with only displayed attributes
call_id. See the complete example for a request that declares all three tools.
Display source documents with the Chats API
To display source documents using this API, declare the_meiliSearchProgress and _meiliSearchSources tools in your request (see tools reference for their exact schemas), then correlate the two by the call_id they share as they stream in.
Understand the response order
During a streamed response, tool calls arrive as chunks alongside content chunks, in this order:_meiliSearchProgress: sent when the agent decides to search an index. Reports the query and index, and assigns acall_idto the search._meiliSearchSources: sent once the search completes, with the matching documents. Itscall_idmatches the progress event, so you can associate the documents with the query that produced them.- Content chunks: the AI-generated answer, based on the retrieved documents.
call_id value abc123, linking the “best sci-fi movies” search on the movies index to its two documents.
Correlate sources by call_id
Parse thetool_calls chunks from the SSE stream and group them by call_id as they arrive:
sources contains every search query and its documents, keyed by call_id. Pass this map to the UI patterns described in display source documents.
Handle errors and fallbacks with the Chats API
To handle errors and fallbacks using this API, check the HTTP status before consuming the stream: Meilisearch forwards errors from your LLM provider on the chat completions endpoint. For generic fallback UX, user-facing messages, and AI SDK patterns, see the linked guide. This section covers what’s specific to calling/chats directly.
Check the response status before streaming
Wrap requests to the chat completions endpoint in error handling, and branch on the HTTP status before reading the response body. Once you start consuming the SSE stream, you can no longer branch on the status:Retry on rate limiting
The chat completions endpoint returns429 when your LLM provider rate limits the request. Implement exponential backoff around the fetch call:
Fall back to regular search
When conversational search fails, fall back to a standard keyword or hybrid search against/indexes/{index_uid}/search:
Detect empty results from _meiliSearchSources
Unlike a regular tool result, _meiliSearchSources arrives as a tool call chunk in the stream (see tools reference for its schema). Parse its documents argument and, if it is empty, show a fallback message instead of relying on the model’s answer:
Troubleshooting
Missing default chat API key
If your instance does not have a Default Chat API Key, create one manually.Empty reply from server (curl error 52)
Causes:- Chat completions feature not enabled
- Missing authentication in requests
- Enable the feature
- Include the
Authorizationheader in all requests
”Invalid API key” error
Cause: Using the wrong type of API key Solution:- Use the “Default Chat API Key”
- Do not use search or admin API keys for chat endpoints
- Find your chat key with the list keys endpoint
”Socket connection closed unexpectedly”
Cause: Usually means the LLM provider API key is missing or invalid in workspace settings Solution:-
Check workspace configuration:
-
Update with a valid API key:
No search progress visible
Cause: The_meiliSearchProgress tool is not declared in the request
Solution:
The search still runs and the LLM still answers, but without _meiliSearchProgress you receive no visibility into what searches are being performed. Add all three Meilisearch tools as shown in the complete example.
For HTTP status handling, rate limits, empty results, and falling back to regular search when calling /chats directly, see handle errors and fallbacks with the Chats API. For generic fallback UX and AI SDK patterns, see handle errors and fallbacks.
Next steps
Agentic search getting started
Build agentic and conversational search with the recommended AI SDK.
Display source documents
Show users which documents were used to generate responses.
Configure guardrails
Restrict AI responses to topics covered by your data.
Optimize chat prompts
Tune system prompts, tool prompts, and index chat settings.
Reduce hallucination
Techniques to keep AI responses grounded in your data.
Chat completions API reference
Full reference for the chat completions endpoint.