Развертывание OpenSource LLM для DiscourseAI на собственном сервере

Плагин Discourse AI включает множество функций, требующих включения LLM, таких как, например, суммаризация, AI Helper, AI Search и AI Bot. Хотя вы можете использовать сторонний API, например, настроить ключи API для OpenAI или настроить ключи API для Anthropic, мы создали Discourse AI с самого начала так, чтобы не зависеть от этих провайдеров.

Запуск с HuggingFace TGI

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

Например:

mkdir -p /opt/tgi-cache
docker run --rm --gpus all --shm-size 1g -p 8080:80 \
  -v /opt/tgi-cache:/data \
  ghcr.io/huggingface/text-generation-inference:latest \
  --model-id mistralai/Mistral-7B-Instruct-v0.2

Это позволит запустить локальный экземпляр Mistral 7B Instruct на localhost в порту 8080, который можно протестировать с помощью:

curl http://localhost:8080/ \
    -X POST \
    -H 'Content-Type: application/json' \
    -d '{"inputs":"<s>[INST] What is your favourite condiment? [/INST] Well, I'm quite partial to a good squeeze of fresh lemon juice. It adds just the right amount of zesty flavour to whatever I'm cooking up in the kitchen!</s> [INST] Do you have mayonnaise recipes? [/INST]","parameters":{"max_new_tokens":500, "temperature":0.5,"top_p": 0.9}}'

Запуск с vLLM

Другой вариант для самостоятельного размещения LLM, поддерживаемый Discourse AI, — это vLLM, очень популярный проект, распространяемый под лицензией Apache.

Вот как начать работу с моделью:

mkdir -p /opt/vllm-cache
docker run --gpus all \
  -v /opt/vllm-cache:/root/.cache/huggingface \
  -e "MODEL=mistralai/Mistral-7B-Instruct-v0.2" \
  -p 8080:8000 --ipc=host vllm/vllm-openai:latest

Тестирование можно выполнить с помощью:

curl -X POST http://localhost:8080/v1/completions \
-H "Content-Type: application/json" \
-d '{
"model": "mistralai/Mistral-7B-Instruct-v0.2",
"prompt": "<s> [INST] What was the latest released hero for Dota 2? [/INST] The latest released hero for Dota 2 was", "max_tokens": 200}'

Запуск с Ollama

Ollama — ещё один популярный вариант для запуска моделей с открытым исходным кодом локально. Он упрощает управление моделями и предоставляет API, совместимый с OpenAI.

ollama pull mistral
ollama serve

Это запускает локальный сервер по адресу http://localhost:11434, к которому Discourse AI может подключиться, используя провайдера Ollama.

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

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

Настройка Discourse AI

Подключения к LLM теперь настраиваются через административный интерфейс, а не через настройки сайта. Перейдите по адресу /admin/plugins/discourse-ai/ai-llms и добавьте новый LLM:

  1. Нажмите New, чтобы добавить модель.
  2. Выберите Provider — в зависимости от вашего сервера инференса выберите vLLM, Hugging Face или Ollama.
  3. Введите URL вашего конечного пункта инференса (например, http://your-server:8080).
  4. Введите API-ключ, если ваш конечный пункт требует его.
  5. Заполните название модели, токенизатор, максимальное количество токенов запроса и другие детали модели.

После добавления вашего LLM установите его как модель по умолчанию через настройку сайта ai_default_llm_model или назначьте его для конкретных функций через конфигурацию агента в /admin/plugins/discourse-ai/ai-features.

17 лайков

For anyone searching this topic with/for:
#Llava-Api-keys

I’m using vLLM too. I also would recommend the openchat v3.5 0106 model, which is a 7B parameter model which performs very well.

I actually am running it in 4bit quantized so that it runs faster.

I am assigning this task to an intern. Are there recommendations from anyone on what specific service to sign up for? This is for a test. The intern currently has a test configured with OpenAI. It runs fine. They’re interested in trying the HuggingFace TGI, but it seems that I need to give them a dedicated server with GPU? What’s the minimal specs for a test?

Are there links I can give the intern?

I haven’t looked at this project in depth yet. I am just anticipating that the intern will need some resources and I am trying to make some reasonable recommendations on services for the intern in research.

Hey there, while exposing with a self-signed certificate vllm container on a GPU box on-prem, I did not find a good way to add the Root CA to the discourse container so it can access securely this on-prem service over https.

e.g.:

./launcher enter app
curl -L  https://vllm.infra.example.com/v1/models
curl: (60) SSL certificate problem: unable to get local issuer certificate
More details here: https://curl.se/docs/sslcerts.html

curl failed to verify the legitimacy of the server and therefore could not
establish a secure connection to it. To learn more about this situation and
how to fix it, please visit the web page mentioned above.

Is there a good way to add a self-signed root ca-certificate in the discourse container which would survive container image updates?

As far as I know adding it in the app.yml

run:
  - exec: wget ... && update-ca-certificates

would only work well while building/rebuilding the app.

Any hint welcomed.

14 posts were split to a new topic: Getting discourse ai to work with ollama locally

Would there be any way to add a custom HTTP header to the Discourse AI requests? We have a GPU-equipped server which we use for a variety of purposes, it has an OpenAI-compatible API but for security we have put it behind an API Management gateway, which requires a custom HTTP header (something like SubscriptionKey) and we supply our auth key here.

Note that this auth key is to get through the APIM, and is different from the API key one would supply for a service like the OpenAI API.

It would be great if there was a way to add Custom Headers in the setup of each LLM in the admin/plugins/discourse-ai/ai-llms setup page. Perhaps a 'Custom option in the ‘Provider’ dropdown, with additional options for use-cases like this?

1 лайк

The quick answer is a plugin to add that header. A work-around might be a local proxy server that you’d hit from Discourse and it’d add the header and ferry the data back to Discourse. An untrusted source suggests that you might be able to get NGINX to do that for you with something like

server {
    listen 80;
    
    location / {
        proxy_pass https://api.example.com;
        proxy_set_header SubscriptionKey xyz;
        proxy_set_header Host $host;
    }
}

There could be a clever way to add that to Discourse’s nginx config at some secret path (that also listened only to your server)

1 лайк