Discourse AI — Векторные представления

:bookmark: Эта тема посвящена настройке модуля Embeddings плагина Discourse AI. Здесь объясняется, что такое эмбеддинги, как они используются и как их настроить.

:person_raising_hand: Требуемый уровень пользователя: Администратор

Эмбеддинги являются ключевым компонентом плагина Discourse AI, обеспечивая такие функции, как Связанные темы и Поиск с помощью ИИ. Это руководство проведет вас через процесс настройки и использования эмбеддингов в вашем экземпляре Discourse.

Что такое эмбеддинги?

Эмбеддинги — это числовые представления текста, которые улавливают семантический смысл. В Discourse они используются для:

  1. Генерации связанных тем в нижней части страниц тем
  2. Включения функциональности семантического поиска

Настройка эмбеддингов

Для хостинговых клиентов

Если вы используете хостинг, эмбеддинги уже настроены. Вам достаточно просто включить функции ИИ, которые от них зависят.

Для самостоятельно размещенных экземпляров

Если вы самостоятельно размещаете свой экземпляр, обратитесь к руководству по самостоятельной установке Discourse AI для получения подробных инструкций по настройке.

Настройка определений эмбеддингов

Модели эмбеддингов теперь настраиваются как определения эмбеддингов в интерфейсе администратора. Перейдите в Администрирование → плагин ИИ → вкладка Эмбеддинги. При добавлении нового определения эмбеддинга вы можете выбрать из предварительно настроенных пресетов или настроить его вручную.

Доступные пресеты включают:

  • text-embedding-3-large (OpenAI)
  • text-embedding-3-small (OpenAI)
  • text-embedding-ada-002 (OpenAI)
  • gemini-embedding-001 (Google)
  • bge-large-en (Hugging Face)
  • bge-m3 (Hugging Face)
  • multilingual-e5-large (Hugging Face)

Каждое определение эмбеддинга включает: отображаемое имя, провайдера, URL, API-ключ (или секрет ИИ), токенизатор, размерность, функцию расстояния, максимальную длину последовательности и необязательные промпты для встраивания/поиска.

Настройка эмбеддингов

Перейдите в АдминистрированиеПлагиныDiscourse AI и убедитесь, что включены следующие настройки.

  1. ai embeddings enabled: Включение или отключение модуля эмбеддингов
  2. ai embeddings selected model: Выбор определения эмбеддинга, которое будет использоваться для генерации эмбеддингов

Необязательные настройки, которые можно настроить…

  • AI embeddings generate for pms: Решение о генерации эмбеддингов для личных сообщений
  • AI embeddings semantic related topics enabled: Включение или отключение функции «Связанные темы»
  • AI embeddings semantic related topics: Максимальное количество отображаемых связанных тем
  • AI embeddings semantic related include closed topics: Включение закрытых тем в результаты связанных тем
  • AI embeddings semantic related age penalty: Применение экспоненциального штрафа за возраст к темам в результатах связанных тем (0.0 отключает, более высокие значения сильнее штрафуют старые темы)
  • AI embeddings semantic related age time scale: Масштаб времени в днях для расчета штрафа за возраст (по умолчанию: 365)
  • AI embeddings semantic search enabled: Включение полного поиска с помощью ИИ
  • AI embeddings semantic quick search enabled: Включение опции семантического поиска во всплывающем меню поиска
  • AI embeddings semantic search use hyde: Включение HyDE (Hypothetical Document Embedding) для семантического поиска
  • AI embeddings semantic search hyde agent: Агент ИИ, используемый для расширения поисковых запросов при включенном HyDE

Провайдеры

Discourse AI поддерживает нескольких провайдеров эмбеддингов:

  • OpenAI
  • Google
  • Hugging Face (для моделей с открытым исходным кодом/открытыми весами)
  • Cloudflare Workers AI

Для хостинговых клиентов Discourse предоставляет предварительно настроенные (засеянные) определения эмбеддингов, которые работают сразу после установки.

Функции

Связанные темы

При включении в нижней части страниц тем появляется раздел «Связанные темы», содержащий ссылки на семантически похожие обсуждения.

Поиск с помощью ИИ

Эмбеддинги обеспечивают работу опции семантического поиска на интерфейсе полного поиска.

Семантический поиск может опционально использовать HyDE (Hypothetical Document Embedding). При включении через ai embeddings semantic search use hyde поисковый запрос расширяется с помощью агента ИИ, настроенного в ai embeddings semantic search hyde agent. Расширенный запрос затем преобразуется в вектор и используется для поиска похожих тем. Этот метод добавляет некоторую задержку при поиске, но может улучшить результаты.

При выборе агента для HyDE выбирайте быстрые модели, такие как Gemini Flash, Claude Haiku, GPT-4o Mini или новейшие доступные модели.

Генерация эмбеддингов

Эмбеддинги автоматически генерируются для новых сообщений. Для генерации эмбеддингов для существующего контента:

  1. Discourse автоматически заполнит эмбеддинги для более старых тем с помощью запланированной задачи, которая выполняется каждые 5 минут
  2. Заполнение обрабатывает темы в порядке недавней активности

Часто задаваемые вопросы

В: Как определяются связанные темы?
О: Связанные темы определяются исключительно на основе эмбеддингов, которые включают заголовок, категорию, теги и содержимое сообщений.

В: Можно ли исключить определенные темы из связанных тем?
О: Да, существует настройка сайта для удаления закрытых тем из результатов.

В: Работают ли эмбеддинги для исторических сообщений?
О: Да, система автоматически заполнит эмбеддинги для всего вашего контента.

Дополнительные ресурсы

17 лайков

Great work, thanks first of all, but I can’t see similar topics under the topics, somehow, my settings are like this, I added an openai key. Semantic search works, but how can I show similar articles under topics?

If you want to use OpenAI for embeddings you must set ai embeddings model to text-embedding-ada-002.

3 лайка

How are the jobs to generate embeddings scheduled? From the code it seems like embeddings are only generated when the page is viewed and embeddings are missing. Is there a way to generate embeddings for the whole site when turning the feature on?

2 лайка

You can also run rake ai:embeddings:backfill to generate embeddings for all topics eagerly.

8 лайков

Suggestion

Sometimes reading a topic one knows most of the noted background but there are also some mentions that are not known. While there is summarization for summarizing an entire topic up to that point what would also be of help would be an AI option that inserts a glossary for the topic as a post near the top and updates it if a user selects a word or phrase that it wants the AI to include in the glossary.


Today in reading this topic there was one reference I did not recognize so looked it up and added a reply with a reference for it. While I know the remaining references I am sure there are others, especially those new to LLMs and such, that would have no idea of many of the noted references and if the AI could help them they would visit the site much more often.

While I know what RAG means in this starting post, how many really know that?

What is RAG (Click triangle to expand)

How do domain-specific chatbots work? An Overview of Retrieval Augmented Generation (RAG)


Note: Did not know with which topic to post this but since it needed embeddings to work posted it here. Please move this if it makes more sense elsewhere or as the Discourse AI plugin changes.

1 лайк

Are embeddings the only variable when determining “Related Topics”? Or are there any other factors that are considered (e.g. author, topic score, topic age, category, etc)?

3 лайка

Only the embeddings, but those contain the title, category, tags and posts. There is a site setting to remove closed topics from the results too.

5 лайков

7 posts were split to a new topic: Is full page semantic search only in English?

2 posts were split to a new topic: Differences in search latency between AI semantic and keyword search

I wish I found this a few months ago. I already created embeddings using bge-small-en-v1.5 and hosted them in an external database.

I will see if it can be shoehorned into this ‘standard’ set-up!

I find a little bug in the recent version leading to rake ai:embeddings:backfill failed:

root@nbg-webxj:/var/www/discourse# rake ai:embeddings:backfill
rake aborted!
NameError: uninitialized constant Parallel (NameError)

  Parallel.each(topics.all, in_processes: args[:concurrency].to_i, progress: "Topics") do |t|
  ^^^^^^^^
/var/www/discourse/plugins/discourse-ai/lib/tasks/modules/embeddings/database.rake:27:in `block in <main>'
/usr/local/bin/bundle:25:in `load'
/usr/local/bin/bundle:25:in `<main>'
Tasks: TOP => ai:embeddings:backfill
(See full trace by running task with --trace)

I suspect the culprit is that the parallel gem is neither installed in this plugin, nor in Discourse core(only find one in the if ENV["IMPORT"] == "1" block: gem "parallel", require: false).

I find the ruby-progressbar gem also required to perform rake ai:embeddings:backfill.

I make a simple PR on Github:

2 лайка

Note to others that this rake method seems to have been demoted/semi-deprecated since per Falco on GitHub:

Thanks for the PR @fokx, but I’ve left those out unintentionally as the rake task fell out out favor and should only be used in rare occasions by experienced operators who can easily install those out of band.

Is the semantic search option no longer shown in that dropdown and instead comprehended or enabled through the AI toggle?

1 лайк

Can you confirm for me if the embeddings will only work on posts after installing or will it also allow us to semantic-search all historical posts? I’m hoping the latter! Thanks.

1 лайк

It’s the later, as it will automatically backfill embeddings for all your content.

4 лайка

I’m trying to set up AI Embeddings using Gemini Flash but I can’t get it to work. I can’t find good descriptions/examples of all the settings fields though, so I might have missed one or two that are important. I don’t know if the ‘ai_embeddings_model’ setting is required, but if I set it to ‘gemini’ I get the following error…

I’ve not been able to find the ai_gemini_api_key setting. I do have Gemini Flash set up as an LLM with an API key and that’s working elsewhere, e.g. summarization, but I’m assuming this is wanting the API key entered somewhere else?

I suppose this would work with OpenAI too, wouldn’t it?

It would be great if it could support their Batch API (50% discount)

Yes, but nowadays we backfill automatically in the background, so this isn’t mandatory.

For price conscious peeps, we support great open weights model that you can run on your own hardware.

1 лайк

Thanks. Do I understand it correctly that backfill is when the vectorization happens? When switching between models, do the vectors need to be recalculated (Are they “proprietary”)? I assume yes.

It’d be useful to know how the costs of using the OpenAI API stack up against investing in a GPU-powered server with opensource solution. Is there a formula or any way to estimate the number of tokens used? We’re only using the API to vectorize posts, not for calculating vector distances, right? So, the number of tokens used depends on how much content we have, correct?

I assume that for both related topics and AI-powered search, all posts need to be vectorized only once, so I can calculate the total number of words in posts table and derive the number of tokens needed. The same process would apply to the daily addition of posts. I’m neglecting the search phrases for now.