Skip to main content
This guide shows you how to build a multi-turn chat interface where users ask questions and follow up with additional context. Make sure you have completed the setup guide before continuing.

Send your first chat completions request

Send a streaming request to the chat completions API route:
curl -N \
  -X POST 'MEILISEARCH_URL/chats/WORKSPACE_NAME/chat/completions' \
  -H 'Authorization: Bearer MEILISEARCH_KEY' \
  -H 'Content-Type: application/json' \
  --data-binary '{
    "model": "PROVIDER_MODEL_UID",
    "messages": [
      {
        "role": "user",
        "content": "USER_PROMPT"
      }
    ],
    "tools": [
      {
        "type": "function",
        "function": {
          "name": "_meiliSearchProgress",
          "description": "Reports real-time search progress to the user"
        }
      },
      {
        "type": "function",
        "function": {
          "name": "_meiliSearchSources",
          "description": "Provides sources and references for the information"
        }
      }
    ]
  }'
  • model is mandatory and must indicate a model supported by your chosen source
  • messages contains the messages exchanged between the conversational search agent and the user
  • tools sets up two optional but highly recommended tools:
    • _meiliSearchProgress: shows users what searches are being performed
    • _meiliSearchSources: displays the actual documents used to generate responses

Maintain conversation context

The chat completions endpoint is stateless. To maintain conversation history across multiple exchanges, you need to accumulate messages and send them with each request.
const messages = [];

async function sendMessage(userMessage) {
  messages.push({ role: 'user', content: userMessage });

  const response = await fetch(
    'MEILISEARCH_URL/chats/WORKSPACE_NAME/chat/completions',
    {
      method: 'POST',
      headers: {
        Authorization: 'Bearer MEILISEARCH_KEY',
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        model: 'PROVIDER_MODEL_UID',
        messages,
      }),
    }
  );

  const reader = response.body.getReader();
  const decoder = new TextDecoder();
  let assistantMessage = '';

  while (true) {
    const { done, value } = await reader.read();
    if (done) break;

    for (const line of decoder.decode(value).split('\n')) {
      if (line.startsWith('data: ') && line !== 'data: [DONE]') {
        const content = JSON.parse(line.slice(6)).choices[0]?.delta?.content;
        if (content) {
          assistantMessage += content;
          // Update the UI progressively
        }
      }
    }
  }

  messages.push({ role: 'assistant', content: assistantMessage });
}

// First question
await sendMessage('What sci-fi movies came out in 2024?');
// Follow-up — the agent remembers the context
await sendMessage('Which one has the best rating?');

Troubleshooting

Empty reply from server (curl error 52)

Causes:
  • Experimental features not enabled
  • Missing authentication in requests
Solution:
  1. Enable experimental features (see setup guide)
  2. Include Authorization header in all requests

”Invalid API key” error

Cause: Using the wrong type of API key Solution:
  • Use the “Default Chat API Key”
  • Don’t 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 OpenAI API key is missing or invalid in workspace settings Solution:
  1. Check workspace configuration:
    curl \
      -X GET 'MEILISEARCH_URL/chats/WORKSPACE_NAME/settings' \
      -H "Authorization: Bearer MEILISEARCH_KEY"
    
  2. Update with valid API key:
    curl \
      -X PATCH 'MEILISEARCH_URL/chats/WORKSPACE_NAME/settings' \
      -H "Authorization: Bearer MEILISEARCH_KEY" \
      -H "Content-Type: application/json" \
      --data-binary '{ "apiKey": "your-valid-api-key" }'
    

Chat not searching the database

Cause: Missing Meilisearch tools in the request Solution:
  • Include _meiliSearchProgress and _meiliSearchSources tools in your request
  • Ensure indexes have proper chat descriptions configured

Next steps

One-shot summarization

Generate single AI answers without conversation history.

Stream chat responses

Handle streaming responses for a real-time experience.

Display source documents

Show users which documents were used to generate responses.

Configure guardrails

Restrict AI responses to topics covered by your data.