Резюме темы Discourse AI 🤖

:information_source: Резюме Использует удаленную языковую модель ИИ для подготовки и публикации краткого изложения темы.
:hammer_and_wrench: Ссылка на репозиторий GitHub - merefield/discourse-ai-topic-summary: Uses a remote AI language model to prepare and post a summary of a Topic · GitHub
:open_book: Руководство по установке Как установить плагины в Discourse
:heart: Спонсорство Пожалуйста, рассмотрите возможность стать постоянным спонсором моей работы с открытым исходным кодом на уровне, который соответствует вашим или ресурсам и потребностям вашей организации, чтобы этот плагин получил необходимое обслуживание и продолжал работать на вашем сайте в будущем.

Понравился этот плагин? Пожалуйста, поставьте ему :star: на GitHub! :pray:

Возможности

  • Сгенерированные ИИ краткие изложения тем:
    • Вы можете выбрать момент их первой генерации и количество новых сообщений, необходимых для их пересоздания, что делает плагин экономически эффективным.
    • Выбор места отображения темы: либо вверху, либо в боковой панели (требуется компонент темы Bars).
    • Система голосования, позволяющая сообществу снижать оценку плохих резюме. Если голоса превысят порог, будет запрошено новое резюме.
    • Отображение в списке тем — при наличии ИИ-резюме они показываются вместо отрывков.
  • Система автоматического тегирования:
    • повторно использует резюме для интеллектуального тегирования вашей темы.
    • выберите одну из двух стратегий, чтобы лучше всего соответствовать вашему случаю использования.
  • Автоматическая генерация миниатюры темы, изображающей её содержание.
  • Все подсказки можно редактировать в разделе Настройки → Текст.
  • Этот плагин стал первым плагин с ИИ для Discourse :1st_place_medal:

(Примечание: это лишь предварительный просмотр интерфейса, использующий ужасные случайные тестовые данные; результаты на реальных данных значительно лучше)

После минимального количества сообщений, если тема находится в категории, входящей в охват, плагин отправит текст темы в большую языковую модель Open AI с подсказкой и опубликует ответ, который, как предполагается, является кратким изложением содержания, и он успешно справляется с этой задачей довольно хорошо. Есть выбор модели.

Резюме часто удивительно хороши, иногда даже возвышенны. Однако, когда одно из них недостаточно хорошее, я добавил механизм снижения оценки сообществом, чтобы принудительно обновлять плохие резюме после достижения определенного порога.

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

Вы можете изменить подсказку и пороги.

ВАЖНОЕ ПРИМЕЧАНИЕ: резюме никогда не отображаются для анонимных пользователей, поэтому текст не будет доступен для индексации поисковыми системами (вы можете считать это хорошим или плохим, но, по крайней мере, сканеры будут работать только с вашими подлинными данными, созданными людьми).

Поддержка автоматического тегирования:

Устали тегировать темы? Пусть это сделает ИИ! (Относительно интеллектуально!)

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

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

rake admin:create (не давайте этому пользователю права администратора)

(Это немного хакерское решение, поскольку текущий «внутренний API» Discourse для тегирования не позволяет указать «без новых тегов», поэтому единственный способ легко предотвратить это на данный момент — создать пользователя, у которого нет этого права (т.е. уровень доверия ниже min_trust_to_create_tag).

Опциональная замена отрывков в списке тем ИИ-резюме

Настройка ai_topic_summary_expose_as_excerpt при включении заменит отрывки в списках тем, где отображаются отрывки (например, через компонент темы, такой как Предварительный просмотр списка тем или Отрывки списка тем), на ИИ-резюме, если оно доступно.

Переключение отрывков:

Вы можете использовать его для моего компонента темы: Topic List Previews (TLP) - #592 by merefield

Опциональное изображение, иллюстрирующее тему

Добавлена опциональная функция генерации миниатюр для этого плагина.

Она будет отображать резюме в виде изображения, которое автоматически добавляется в начало первого сообщения.

  • Вы должны включить её в настройках плагина.
  • Вы можете опционально выбрать автоматическое удаление последнего верхнего изображения каждый раз.
  • Вы можете редактировать подсказку через ссылку в настройках плагина, чтобы влиять на стиль и содержание (но это будет применяться ко всем последующим сгенерированным изображениям).

Наслаждайтесь :framed_picture:

Ограничения

Из-за ограничений токенов сейчас плагин подходит только для примерно 160 сообщений максимум (зависит от модели!), поэтому он не будет включать материал в сообщениях после определенной точки. Это, скорее всего, изменится в будущем, когда модели станут более мощными, а сервисы — более совершенными.

Ограничения скорости и затраты

Получение данных от Open AI не бесплатно. Однако ограничения скорости неявно основаны на публикации сообщений. Вы контролируете, сколько сообщений требуется, прежде чем будут запрошены новые резюме. Это вряд ли станет проблемой.

Поддержка боковой панели «Bars»!!

Теперь в комплекте с плагином поставляется виджет, совместимый с Bars. Вам просто нужно установить компонент темы Bars и настроить его:

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

Примечания

Отказ от ответственности: Я не отвечаю за то, что отвечает LLM. Пожалуйста, ознакомьтесь с плюсами и минусами LLM, их возможностями и ограничениями. Они очень хороши в создании убедительного, контекстно-зависимого текста, но могут быть фактологически неверными.

Важное примечание о конфиденциальности: Данные вашего форума отправляются в Open AI. Хотя они, скорее всего, не будут включены в их предварительно обученные модели, они будут использовать эти данные для аналитики и ведения логов. Обязательно включите этот факт в Условия использования и политику конфиденциальности вашего форума. Ссылки: Условия использования, Политика конфиденциальности

Авторское право: Open AI сделала заявление об авторском праве здесь: Заберет ли OpenAI авторские права на то, что я генерирую с помощью API? | Справочный центр OpenAI

TODO

  • Добавить фронтенд- и бэкенд-тесты :construction:
  • Добавить больше пользовательских настроек для влияния на стиль ответа :white_check_mark:
  • Добавить поддержку пользовательских имен моделей :white_check_mark:
  • Добавить поддержку GPT-4, когда она станет доступна :white_check_mark:
  • Сделать выбор модели выпадающим списком :white_check_mark:
  • Добавить поддержку виджетов для плагина Layouts :white_check_mark:
30 лайков

This was just a matter of time until we got this!

But my primary question is how expensive can this get for us?

4 лайка

It’s been live on one of my forums for a few days now. It’s active on nearly all public categories.

It’s hard to answer because I don’t know how active your forum is.

My suggestion is give it a go in one Category and see how you get on.

There’s a decent dashboard.

After developing two plugins based on GPT3 (the most expensive model) and going live on one site late last month, mine looks like this for Feb:

So probably less than your email costs.

10 лайков

Oh, that could be good to grow our glossary topics.

It should work in Spanish?

3 лайка

I have no idea, you might need to change the prompt in settings. But give it a go!

(this should be a localised string, I’ll change that soon)

4 лайка

Thanks @merefield - this looks like a great plugin!

I’ve enabled it and entered my API key, enabled categories etc, but haven’t seen any summaries yet. Is there some way I can monitor its progress on my Discourse forum? Can’t see anything in logs or sidekiq (although admittedly haven’t had a deep look yet)

3 лайка

Hey Chris, it reacts to new Posts. If they are within the thresholds and fits the Category location criteria, it will create a summary.

3 лайка

I see, thanks for clarifying @merefield

2 лайка

Hi,

My rebuild fails when I enable this summary plugin. I don’t know if this is something to do with my underlying setup or conflicting plugins. I attach some details in case it is helpful.

Commenting out the ai-topic-summary plugin resolves the issue and the build is successful.

Many thanks for any guidance.

I, [2023-03-12T17:24:25.390052 #1]  INFO -- : > cd /var/www/discourse && su discourse -c 'LOAD_PLUGINS=0 bundle exec rake plugin:pull_compatible_all'
I, [2023-03-12T17:24:31.668769 #1]  INFO -- : discourse-ai-topic-summary is already at latest compatible version
discourse-assign is already at latest compatible version
discourse-chat-integration is already at latest compatible version
discourse-chatbot is already at latest compatible version
discourse-checklist is already at latest compatible version
discourse-solved is already at latest compatible version
docker_manager is already at latest compatible version

I, [2023-03-12T17:24:31.677801 #1]  INFO -- : > cd /var/www/discourse && su discourse -c 'bundle exec rake db:migrate'
rake aborted!
Gem::LoadError: can't activate ruby-openai-3.4.0, already activated ruby-openai-3.3.0
/var/www/discourse/lib/plugin_gem.rb:26:in `load'
/var/www/discourse/lib/plugin/instance.rb:796:in `gem'
/var/www/discourse/plugins/discourse-chatbot/plugin.rb:9:in `activate!'
/var/www/discourse/lib/plugin/instance.rb:693:in `instance_eval'
/var/www/discourse/lib/plugin/instance.rb:693:in `activate!'
/var/www/discourse/lib/discourse.rb:352:in `block in activate_plugins!'
/var/www/discourse/lib/discourse.rb:349:in `each'
/var/www/discourse/lib/discourse.rb:349:in `activate_plugins!'
/var/www/discourse/config/application.rb:216:in `block in <class:Application>'
/var/www/discourse/lib/plugin.rb:6:in `initialization_guard'
/var/www/discourse/config/application.rb:216:in `<class:Application>'
/var/www/discourse/config/application.rb:75:in `<module:Discourse>'
/var/www/discourse/config/application.rb:74:in `<top (required)>'
/var/www/discourse/Rakefile:7:in `require'
/var/www/discourse/Rakefile:7:in `<top (required)>'
/var/www/discourse/vendor/bundle/ruby/3.2.0/gems/rake-13.0.6/exe/rake:27:in `<top (required)>'
/usr/local/bin/bundle:25:in `load'
/usr/local/bin/bundle:25:in `<main>'
(See full trace by running task with --trace)
I, [2023-03-12T17:24:38.020166 #1]  INFO -- : gem install httparty -v 0.21.0 -i /var/www/discourse/plugins/discourse-ai-topic-summary/gems/3.2.1 --no-document --ignore-dependencies --no-user-install
When you HTTParty, you must party hard!
Successfully installed httparty-0.21.0
1 gem installed
gem install ruby-openai -v 3.3.0 -i /var/www/discourse/plugins/discourse-ai-topic-summary/gems/3.2.1 --no-document --ignore-dependencies --no-user-install
Note if upgrading: The `::Ruby::OpenAI` module has been removed and all classes have been moved under the top level `::OpenAI` module. To upgrade, change `require 'ruby/openai'` to `require 'openai'` and change all references to `Ruby::OpenAI` to `OpenAI`.
Successfully installed ruby-openai-3.3.0
1 gem installed
gem install httparty -v 0.21.0 -i /var/www/discourse/plugins/discourse-chatbot/gems/3.2.1 --no-document --ignore-dependencies --no-user-install
When you HTTParty, you must party hard!
Successfully installed httparty-0.21.0
1 gem installed
gem install ruby-openai -v 3.4.0 -i /var/www/discourse/plugins/discourse-chatbot/gems/3.2.1 --no-document --ignore-dependencies --no-user-install
Note if upgrading: The `::Ruby::OpenAI` module has been removed and all classes have been moved under the top level `::OpenAI` module. To upgrade, change `require 'ruby/openai'` to `require 'openai'` and change all references to `Ruby::OpenAI` to `OpenAI`.
Successfully installed ruby-openai-3.4.0
1 gem installed

I, [2023-03-12T17:24:38.021523 #1]  INFO -- : Terminating async processes
I, [2023-03-12T17:24:38.022106 #1]  INFO -- : Sending INT to HOME=/var/lib/postgresql USER=postgres exec chpst -u postgres:postgres:ssl-cert -U postgres:postgres:ssl-cert /usr/lib/postgresql/13/bin/postmaster -D /etc/postgresql/13/main pid: 41
2023-03-12 17:24:38.022 UTC [41] LOG:  received fast shutdown request
I, [2023-03-12T17:24:38.022874 #1]  INFO -- : Sending TERM to exec chpst -u redis -U redis /usr/bin/redis-server /etc/redis/redis.conf pid: 102
102:signal-handler (1678641878) Received SIGTERM scheduling shutdown...
2023-03-12 17:24:38.035 UTC [41] LOG:  aborting any active transactions
2023-03-12 17:24:38.046 UTC [41] LOG:  background worker "logical replication launcher" (PID 50) exited with exit code 1
2023-03-12 17:24:38.049 UTC [45] LOG:  shutting down
102:M 12 Mar 2023 17:24:38.053 # User requested shutdown...
102:M 12 Mar 2023 17:24:38.054 * Saving the final RDB snapshot before exiting.
102:M 12 Mar 2023 17:24:38.120 * DB saved on disk
102:M 12 Mar 2023 17:24:38.122 # Redis is now ready to exit, bye bye...
2023-03-12 17:24:38.153 UTC [41] LOG:  database system is shut down


FAILED
--------------------
Pups::ExecError: cd /var/www/discourse && su discourse -c 'bundle exec rake db:migrate' failed with return #<Process::Status: pid 1043 exit 1>
Location of failure: /usr/local/lib/ruby/gems/3.2.0/gems/pups-1.1.1/lib/pups/exec_command.rb:117:in `spawn'
exec failed with the params {"cd"=>"$home", "hook"=>"db_migrate", "cmd"=>["su discourse -c 'bundle exec rake db:migrate'"]}
bootstrap failed with exit code 1
3 лайка

Oops my bad. It’s a conflict between my two AI plugins. Will resolve and revert! :sweat_smile: Apologies!

5 лайков

Try that: FIX: conflict with chatbot · merefield/discourse-ai-topic-summary@0067eaf · GitHub

5 лайков

Many thanks for getting back so quickly. I will try this tomorrow. I’m looking forward to seeing this plugin in action!

3 лайка

Quick update I had my first real summary triggered and it did a pretty reasonable job. @merefield I think you’ve nailed this plugin :-). I think in fact putting chatgpt to work like this has far better future potential than just adding into a discussion thread.

Here’s the summary that was generated which placed at the top of the topic does a great job at encouraging others to read - or not.

I did get an error (error 500) on posting an update that would have triggered the summary. This was because I’d tried to use gpt-3.5-turbo in settings. Perhaps if there is a chatgpt api error it would be better to allow the post submission rather than the user getting a 500 error they don’t know what to do with.

In the logs it was clear what I’d done wrong

StandardError (This is a chat model and not supported in the v1/completions endpoint. Did you mean to use v1/chat/completions?)

Potential evolutions:

  • Allow topic owner / admin to remove summary if it isn’t relevant / appropriate?
  • Perhaps a place to go to view all summaries in a category / overall

Other than that I look forward to seeing how this evolves. Many thanks for what you’ve done so far. My site is very small with only a few users but I can really see it’s potential.

4 лайка

Great feedback thanks. Those are nice ideas.

Yeah an admin/author button might be quite nice. I’ll add to roadmap.

Nice!

I wonder if “the place to see the summaries” list is actually an alternative excerpt on the topic list?

I’ll add to roadmap.

Yeah I should convert this to a drop-down like I did with Chatbot. Good try though :wink:

GPT-4 is coming btw which will vastly improve the summaries and cope with much longer Topics.

6 лайков

Can you tell me if the plugin currently supports ChatGPT 4 and the API of the POE application (AI chat platform developed by Quora)?

3 лайка

Lol, give me a chance! :sweat_smile: afaia it was only announced yesterday?

Very few developers have been given access to the API so far. There is a waiting list. So users of the plugin are unlikely to be able to connect in any case.

(Did you notice the Topic title btw?)

No and no plans to at present. What would be the benefit? Is it known to excel at summarisation?

2 лайка

^^
sorry for being unclear ^^ i just wanted to know if you are interested about integrating them in the future? I’m following the news around GPT 04 and it’s surprising and special to us Vietnamese community

3 лайка

Thanks for you interest. As far as GPT-4 support is concerned, let me respond this way:

Hell Yeah Dcuniverse GIF by DC

I will probably be adding it to Chatbot first, but will surely get around to AI Topic Summary soon after.

I’m waiting for the email from Open AI … (and then a little spare time!)

5 лайков

Actually, I’ve thought of a slightly simpler solution to this so we don’t have to crowd the UI:

How about we just give settings for “vote weight” for Admin and Author?

So you can set the Author voting weight to 3 and if the threshold is 3 that results in a new summary being generated.

The downside of both solutions (button, or weighting that matches the threshold) is that the Author could just spam for new summaries, costing you a lot in API calls.

So I suggest you make the authors vote carry a weight just below the threshold (but more than a regular user) and the admin at threshold?

Then we don’t have to change the UI and just bake this into the back-end logic and settings.

Admin downvotes will always create a new summary and reset the count.

Thoughts @JamesPick ?

4 лайка

I agree with your concern about spamming of new summaries.
I think it’s less about the ai providing a bad summary and more that the topic is not conducive to a good summary. Perhaps the topic lost it’s focus or became more a chat and the key posts get lost from what is sent to chatgpt.

Ultimately when admin / topic owner clearly sees that the summary is not going to produce anything of meaning for the topic they are able to cancel it.

I suppose in time the features could be added to select the specific posts that could be chosen to send to api for summary.

I was thinking of this for something like this thread. You could flag your first post to be the one that always gets included in a summary? And then perhaps add a few more that most suit a summary.

You could even have a ‘generate summary’ option where even when a topic only has one post a summary can be generated. This fits well with your earlier comment

4 лайка