Skip to main content
This page documents direct use of the Meilisearch /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 combines chatCompletions 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:
Look for the key with the description “Default Chat API Key”. Chat queries only search the indexes that the API key can access. The default chat API key is scoped to all indexes. To limit which indexes a chat client can reach, you have two options:
  • Create a new API key with both chatCompletions and search actions, 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 chatCompletions and search actions 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.
If your instance does not have a Default Chat API Key, create one manually:

Configure your indexes

Configure chat settings for each index you want the agent to search:
  • description tells the LLM what the index contains
  • documentTemplate is a Liquid template that defines the text sent to the LLM for each document
  • documentTemplateMaxBytes truncates the rendered template. The default of 400 bytes balances context quality and speed
See index chat settings for the remaining fields, then consult optimize chat prompts and document template best practices for tuning.

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 use POST /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 the messages array carries a role that tells the LLM who authored it:

Send a streaming request

Send a POST request to /chats/{workspace}/chat/completions with stream: true:
This basic request works, but without Meilisearch tools you get no visibility into what is being searched and no way to keep conversation context across follow-up questions. Declare the three tools listed in tools reference. _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)
For UI patterns that surface those source documents, see display source documents.

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:
Use a dedicated workspace for summarization rather than reusing a chat workspace, so the prompts stay separate. On Meilisearch Cloud, if you need a second workspace, contact support. Send one user message and do not maintain conversation history:
Including _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 with PATCH /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, and apiVersion are required for Azure OpenAI and are incompatible with every other source
  • baseUrl is 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 endpoint
  • apiKey is optional for vLLM and mandatory for every other provider
The apiKey field is write-only. Meilisearch stores it for outbound LLM calls but redacts it in every response from the workspace settings endpoint. To rotate the key, PATCH the workspace with the new value.
Set baseline agent instructions with 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:
Update only the fields you want to change. Fields you omit remain unchanged:
For the full HTTP parameter list, see:

LLM provider parameters passthrough

Meilisearch forwards standard chat completion parameters such as temperature, 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 OpenAI chat.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 calling JSON.parse
Events are separated by blank lines. After consuming [DONE], close the reader.

Content chunks

Regular content chunks contain the AI-generated text in choices[0].delta.content:

Tool call chunks

When you include Meilisearch tools, the stream also contains tool call chunks in choices[0].delta.tool_calls:

End of stream

The stream ends with a finish_reason of "stop" followed by the [DONE] marker:

Handle streaming in JavaScript

Use the Fetch API to process the SSE stream. Parse data: lines, skip [DONE], then handle delta.content and delta.tool_calls:
The endpoint is stateless. Accumulate messages and send the full history with each request, including payloads from _meiliAppendConversationMessage. See the complete example.

Tools reference

Meilisearch intercepts three special tools and never forwards them to the LLM provider. Declare them in the tools array of your request.
These tool definitions must include the exact parameter schemas below. Missing or incorrect parameters will prevent the tools from working.
Recommended usage order:
  1. Handle progress updates with _meiliSearchProgress
  2. Append conversation messages with _meiliAppendConversationMessage
  3. Display source documents with _meiliSearchSources
  4. Use call_id to 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 operation
  • function_name: Name of the internal function being executed (for example, _meiliSearchInIndex)
  • function_parameters: JSON-encoded string containing search parameters such as q and index_uid

_meiliAppendConversationMessage

Asks the client to append internal tool calls and results to the conversation history. Arguments:
  • role: Message author role (user or assistant)
  • content: Message content (for tool results)
  • tool_calls: Array of tool calls made by the assistant
  • tool_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 the call_id from _meiliSearchProgress
  • documents: Source documents with only displayed attributes
See display source documents for UI patterns, and display source documents with the Chats API for how to correlate the two tools by 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:
  1. _meiliSearchProgress: sent when the agent decides to search an index. Reports the query and index, and assigns a call_id to the search.
  2. _meiliSearchSources: sent once the search completes, with the matching documents. Its call_id matches the progress event, so you can associate the documents with the query that produced them.
  3. Content chunks: the AI-generated answer, based on the retrieved documents.
Both events share the 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 the tool_calls chunks from the SSE stream and group them by call_id as they arrive:
After the stream finishes, 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 returns 429 when your LLM provider rate limits the request. Implement exponential backoff around the fetch call:
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:
Combine this with guardrails in your workspace’s system prompt, so the model itself also acknowledges when it found nothing relevant.

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
Solution:
  1. Enable the feature
  2. Include the Authorization header 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:
  1. Check workspace configuration:
  2. 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.