本指南将引导您实现 Meilisearch 的聊天补全功能,以在您的应用程序中创建对话式搜索体验。

先决条件

开始之前,请确保您拥有:
  • 一个 安全 Meilisearch >= v1.15.1 项目
  • 来自 LLM 提供商的 API 密钥
  • 至少一个包含可搜索内容的索引

启用聊天补全功能

首先,启用聊天补全实验性功能
curl \
  -X PATCH 'https://:7700/experimental-features/' \
  -H 'Authorization: Bearer MEILISEARCH_KEY' \
  -H 'Content-Type: application/json' \
  --data-binary '{
    "chatCompletions": true
  }'

查找您的聊天 API 密钥

当 Meilisearch 使用主密钥在 v1.15.1 后创建的实例上运行时,它会自动生成一个“默认聊天 API 密钥”,该密钥在所有索引上具有 chatCompletionssearch 权限。使用以下命令检查您是否拥有该密钥:
curl https://:7700/keys \
  -H "Authorization: Bearer MEILISEARCH_KEY"
查找描述为“Default Chat API Key”的密钥。在查询 /chats 端点时使用此密钥。

故障排除:缺少默认聊天 API 密钥

如果您的实例没有默认聊天 API 密钥,请手动创建一个
curl \
  -X POST 'https://:7700/keys' \
  -H 'Authorization: Bearer MEILISEARCH_KEY' \
  -H 'Content-Type: application/json' \
  --data-binary '{
    "name": "Chat API Key",
    "description": "API key for chat completions",
    "actions": ["search", "chatCompletions"],
    "indexes": ["*"],
    "expiresAt": null
  }'

为聊天配置您的索引

您希望通过聊天进行搜索的每个索引都需要特定配置
curl \
  -X PATCH 'https://:7700/indexes/movies/settings' \
  -H 'Authorization: Bearer MEILISEARCH_KEY' \
  -H 'Content-Type: application/json' \
  --data-binary '{
    "chat": {
      "description": "A comprehensive movie database containing titles, descriptions, genres, and release dates to help users find movies",
      "documentTemplate": "{% for field in fields %}{% if field.is_searchable and field.value != nil %}{{ field.name }}: {{ field.value }}\n{% endif %}{% endfor %}",
      "documentTemplateMaxBytes": 400,
      "searchParameters": {}
    }
  }'
description 字段有助于 LLM 理解索引中的数据,从而提高搜索相关性。

配置聊天补全工作区

使用您的 LLM 提供商设置创建工作区。以下是不同提供商的示例:
curl \
  -X PATCH 'https://:7700/chats/my-assistant/settings' \
  -H 'Authorization: Bearer MEILISEARCH_KEY' \
  -H 'Content-Type: application/json' \
  --data-binary '{
    "source": "openAi",
    "apiKey": "sk-abc...",
    "baseUrl": "https://api.openai.com/v1",
    "prompts": {
      "system": "You are a helpful assistant. Answer questions based only on the provided context."
    }
  }'

发送您的第一个聊天补全请求

现在您可以开始对话了。请注意用于处理流式响应的 -N 标志
curl -N \
  -X POST 'https://:7700/chats/my-assistant/chat/completions' \
  -H 'Authorization: Bearer <chat-api-key>' \
  -H 'Content-Type: application/json' \
  --data-binary '{
    "model": "gpt-3.5-turbo",
    "messages": [
      {
        "role": "user",
        "content": "What movies do you have about space exploration?"
      }
    ],
    "stream": true,
    "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"
        }
      }
    ]
  }'
特别注意 tools 数组。这些设置是可选的,但可以极大地改善用户体验
  • _meiliSearchProgress:显示用户正在执行的搜索
  • _meiliSearchSources:显示用于生成响应的实际文档

使用 OpenAI SDK 构建聊天界面

由于 Meilisearch 的聊天端点与 OpenAI 兼容,您可以使用官方 OpenAI SDK
import OpenAI from 'openai';

const client = new OpenAI({
  baseURL: 'https://:7700/chats/my-assistant',
  apiKey: 'YOUR_CHAT_API_KEY',
});

const completion = await client.chat.completions.create({
  model: 'gpt-3.5-turbo',
  messages: [{ role: 'user', content: 'What is Meilisearch?' }],
  stream: true,
});

for await (const chunk of completion) {
  console.log(chunk.choices[0]?.delta?.content || '');
}

错误处理

当使用 OpenAI SDK 和 Meilisearch 的聊天补全端点时,流式响应中的错误由 OpenAI 原生处理。这意味着您可以使用 SDK 内置的错误处理机制,无需额外配置
import OpenAI from 'openai';

const client = new OpenAI({
  baseURL: 'https://:7700/chats/my-assistant',
  apiKey: 'MEILISEARCH_KEY',
});

try {
  const stream = await client.chat.completions.create({
    model: 'gpt-3.5-turbo',
    messages: [{ role: 'user', content: 'What is Meilisearch?' }],
    stream: true,
  });

  for await (const chunk of stream) {
    console.log(chunk.choices[0]?.delta?.content || '');
  }
} catch (error) {
  // OpenAI SDK automatically handles streaming errors
  console.error('Chat completion error:', error);
}

故障排除

常见问题与解决方案

服务器回复为空(curl 错误 52)

原因
  • Meilisearch 未使用主密钥启动
  • 实验性功能未启用
  • 请求中缺少身份验证
解决方案
  1. 使用主密钥重新启动 Meilisearch:meilisearch --master-key yourKey
  2. 启用实验性功能(参见上文设置说明)
  3. 在所有请求中包含 Authorization 标头

“API 密钥无效”错误

原因:使用了错误类型的 API 密钥 解决方案:
  • 使用主密钥或“默认聊天 API 密钥”
  • 不要将搜索或管理员 API 密钥用于聊天端点
  • 查找您的聊天密钥:curl https://:7700/keys -H "Authorization: Bearer MEILISEARCH_KEY"

“套接字连接意外关闭”

原因:通常表示工作区设置中缺少 OpenAI API 密钥或密钥无效 解决方案:
  1. 检查工作区配置
    curl https://:7700/chats/my-assistant/settings \
      -H "Authorization: Bearer MEILISEARCH_KEY"
    
  2. 使用有效 API 密钥更新
    curl -X PATCH https://:7700/chats/my-assistant/settings \
      -H "Authorization: Bearer MEILISEARCH_KEY" \
      -H "Content-Type: application/json" \
      -d '{"apiKey": "your-valid-api-key"}'
    

聊天未搜索数据库

原因:请求中缺少 Meilisearch 工具 解决方案:
  • 在您的请求中包含 _meiliSearchProgress_meiliSearchSources 工具
  • 确保索引已配置正确的聊天描述

“stream: false 不受支持”错误

原因:尝试使用非流式响应 解决方案:
  • 始终在您的请求中设置 "stream": true
  • 暂不支持非流式响应

下一步

© . This site is unofficial and not affiliated with Meilisearch.