Самостоятельное хостинг Sentiment и Emotion для DiscourseAI

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

Discourse AI поддерживает два типа классификации, для каждого из которых требуется своя модель:

  • Тональность (Sentiment) — классифицирует сообщения как позитивные, негативные или нейтральные (с использованием cardiffnlp/twitter-roberta-base-sentiment-latest)
  • Эмоции (Emotion) — классифицирует сообщения по 28 меткам эмоций, таким как радость, гнев, удивление и т. д. (с использованием SamLowe/roberta-base-go_emotions)

Чтобы получить данные как по тональности, так и по эмоциям в своих панелях, необходимо запустить обе модели.

Запуск с использованием HuggingFace TEI

HuggingFace предоставляет отличное контейнерное изображение, которое позволит быстро начать работу.

Модель тональности

mkdir -p /opt/tei-sentiment-cache
docker run --rm --gpus all --shm-size 1g -p 8081:80 \
  -v /opt/tei-sentiment-cache:/data \
  ghcr.io/huggingface/text-embeddings-inference:latest \
  --model-id cardiffnlp/twitter-roberta-base-sentiment-latest

Это позволит запустить локальный экземпляр cardiffnlp/twitter-roberta-base-sentiment-latest — открытой модели, способной классифицировать сообщения как позитивные, негативные или нейтральные.

Вы можете проверить работоспособность с помощью команды:

curl http://localhost:8081/ \
    -X POST \
    -H 'Content-Type: application/json' \
    -d "{ \"inputs\": \"I am happy\" }"

При штатной работе должен вернуться массив значений уверенности для каждой метки.

Модель эмоций

Чтобы также получить классификацию по эмоциям, запустите второй контейнер с моделью эмоций:

mkdir -p /opt/tei-emotion-cache
docker run --rm --gpus all --shm-size 1g -p 8082:80 \
  -v /opt/tei-emotion-cache:/data \
  ghcr.io/huggingface/text-embeddings-inference:latest \
  --model-id SamLowe/roberta-base-go_emotions

Поддерживаемые модели

Доступность для вашего экземпляра Discourse

В большинстве случаев из-за ускорения работы GPU эту систему запускают на выделенном сервере. В таком случае рекомендуется использовать обратный прокси-сервер, завершение TLS-соединений и защиту конечной точки, чтобы к ней мог подключаться только ваш экземпляр Discourse.

Настройка Discourse AI

Discourse AI включает параметры сайта для настройки сервера вывода (inference server) для моделей с открытым исходным кодом. Укажите адрес вашего сервера с помощью параметра ai_sentiment_model_configs.

Этот параметр принимает JSON-массив конфигураций моделей. Каждая запись требует:

Поле Описание
model_name Идентификатор модели HuggingFace (например, cardiffnlp/twitter-roberta-base-sentiment-latest)
endpoint URL-адрес вашего экземпляра TEI (например, https://your-server:8081)
api_key Ключ API для конечной точки (можно оставить пустым, если не требуется)

Чтобы получить панели как для тональности, так и для эмоций, добавьте запись для каждой запущенной модели. Например, если вы запускаете обе модели локально:

  • Запись 1: model_name cardiffnlp/twitter-roberta-base-sentiment-latest, endpoint https://your-server:8081
  • Запись 2: model_name SamLowe/roberta-base-go_emotions, endpoint https://your-server:8082

После этого включите классификацию, переключив параметр ai_sentiment_enabled.}

3 лайка

Are there plans to support other models in languages ​​other than English?

1 лайк

@Falco if one decides to run this on the same server running discourse (e.g. we have a very small deployment with a few thousand posts), could you update the instructions to outline

  1. How can discourse integrate with a local instance of HuggingFace TEI container image
  2. Suggestions on how much additional RAM/disk is required to run the above (e.g. if the base Discourse is running on 2GB RAM with 20GB disk)

So I have setup a new self hosted Discourse instance and trying to setup sentiments. This is my ai_sentiment_model_configs -

Key Value
model name cardiffnlp/twitter-roberta-base-sentiment-latest
endpoint https://my_own_instance
api_key [blank]

And it works, sort of, I get the sentiment bar graph.

However, the Emotion table is empty. This doc looks incomplete, or poorly worded for me to grasp what needs to be done.

Do I run another Docker container, with a different model ID (roberta-base-go_emotions?), or something else? What do I need to do get that emotion table filled up?

Would prefer to self host these services if possible. TIA if anybody can point me in the right direction.

For emotions you need to run the

too.

3 лайка

Thank you. So I just run a second docker container with some tweaks, like so:

mkdir -p /opt/tei-cache2
docker run --detach --rm --gpus all --shm-size 1g -p 8082:80 \
  -v /opt/tei-cache2:/data \
  ghcr.io/huggingface/text-embeddings-inference:latest \
  --model-id SamLowe/roberta-base-go_emotions

and add a new entry in ai_sentiment_model_configs and it’s all working now. Thank you. :slight_smile:

1 лайк

Ran face-first into a brick wall of not knowing what the hell I’m doing in trying to get this working on an EC2 instance without a GPU. At least to the best of my extremely limited abilities and understanding here, trying to do this with a CPU-only instance means a lot more configuration work than I can understand. The cpu versions of ghcr.io/huggingface/text-embeddings-inference refuse to load either of the two listed models; Claude and GPT5 both tell me I need to convert them to ONNX models with a bunch of python tools, and that’s where I noped out.

(It’s also very possible I’m just dumb and missing an obvious step!)

One thing we are planning is allowing LLMs to act as sentiment analysis

That way you can plug in a cheap model like Gemini Flash 2.5 (or even nano) and use it for sentiment analysis.

6 лайков

We are trying to use this feature with Azure AI Language (from our self-hosted Discourse instance) - as we are already using our Azure subscription to integrate GPT-4.5 with Discourse (for summarization and chat-bot functionality):

  • but we are getting no data in the the sentiment dashboard, and can see these errors in the logs:

Discourse AI: Errors during bulk classification: Failed to classify 208 posts (example ids: 2256, 909, 2270, 2260, 2797) : JSON::ParserError : An empty string is not a valid JSON string.

The backtrace shows that Discourse might be trying to use HuggingFace - are these the only models supported at the moment?

Thanks,

N

Yeah we have a very specific implementation, we are thinking about how to make it more generic

I am bullish on just letting LLMs return structured output for sentiment, cause it opens the doors to many options there and I feel that as a trend “hyper specific” APIs are being replaced by “hyper general” APIs LLMs provide.

3 лайка

Is there any straightforward way to get this up and running on self-hosted WP without setting up your own instance for the sentiment classification?

Thanks Sam - that would be great. In the meantime, we will look into running one of the supported HuggingFace models on an Azure VM…