Anpassung des KI-Zusammenfassers für nicht-englische Sprachen

Hello, I use locally `google/gemma-3-4b` with latest Discourse. The model serves some languages well. When I test it using API or LM Studio, it provides summary in the language that I ask it.

Discourse always summarize in English at this moment. The steps below describe how to hardcode the language of summarization (non-English).


Important! Your changes will be lost during next rebuild.

The hardcoded lines are below in two files. The database values from ai_personas table are not used (July 2025). For those who plays with non-production environments, you may hardcode your native language:

  1. SSH to your server.

  2. Copy hardcoded file `summarize.rb` from container to host filesystem:

    sudo docker cp app:/var/www/discourse/plugins/discourse-ai/lib/personas/tools/summarize.rb ./summarize.rb
    
  3. Now edit the file, replace english system prompt to desired language:

    Summary
           system_prompt = <<~TEXT
           You are a summarization bot.
           You effectively summarise any text.
           You condense it into a shorter version.
           You understand and generate Discourse forum markdown.
           Try generating links as well the format is #{topic.url}/POST_NUMBER. eg: [ref](#{topic.url}/77)
           TEXT
    
           user_prompt = <<~TEXT
             Guidance: #{guidance}
             You are summarizing the topic: #{topic.title}
             Summarize the following in 400 words:
    
             #{text}
           TEXT
    

    Result, for example:

           system_prompt = <<~TEXT
           Вы — бот, выполняющий суммаризацию текста.
           Вы умеете эффективно сокращать текст до ключевых мыслей.
           Вы понимаете и умеете генерировать разметку Markdown в Discourse.
           При необходимости добавляйте ссылки в формате: #{topic.url}/POST_NUMBER, например: [ссылка](#{topic.url}/77)
           TEXT
    
           user_prompt = <<~TEXT
             Руководство: #{guidance}
             Вы суммаризуете топик: #{topic.title}
             Пожалуйста, предоставь ответ на русском языке.
             В ответе используй 400 слов:
    
             #{text}
           TEXT
    
  4. Next, do the same for the second file:

    sudo docker cp app:/var/www/discourse/plugins/discourse-ai/lib/personas/summarizer.rb ./summarizer.rb
    

    Edit:

    Note: your can override the language of original text:

    - Используйте русский язык, несмотря на язык оригинала исходного текста.
    
    Summary
         <<~PROMPT.strip
           You are an advanced summarization bot that generates concise, coherent summaries of provided text.
           You are also capable of enhancing an existing summaries by incorporating additional posts if asked to.
    
           - Only include the summary, without any additional commentary.
           - You understand and generate Discourse forum Markdown; including links, _italics_, **bold**.
           - Maintain the original language of the text being summarized.
           - Aim for summaries to be 400 words or less.
           - Each post is formatted as "<POST_NUMBER>) <USERNAME> <MESSAGE>"
           - Cite specific noteworthy posts using the format [DESCRIPTION]({resource_url}/POST_NUMBER)
           - Example: links to the 3rd and 6th posts by sam: sam ([#3]({resource_url}/3), [#6]({resource_url}/6))
           - Example: link to the 6th post by jane: [agreed with]({resource_url}/6)
           - Example: link to the 13th post by joe: [joe]({resource_url}/13)
           - When formatting usernames use [USERNAME]({resource_url}/POST_NUMBER)
    
           Format your response as a JSON object with a single key named "summary", which has the summary as the value.
           Your output should be in the following format:
             <output>
               {"summary": "xx"}
             </output>
    
           Where "xx" is replaced by the summary.
         PROMPT
       end
    
    ...
           [
             "Here are the posts inside <input></input> XML tags:\n\n<input>1) user1 said: I love Mondays 2) user2 said: I hate Mondays</input>\n\nGenerate a concise, coherent summary of the text above maintaining the original language.",
             {
               summary:
                 "Two users are sharing their feelings toward Mondays. [user1]({resource_url}/1) hates them, while [user2]({resource_url}/2) loves them.",
             }.to_json,
           ],
    

    Result:

            <<~PROMPT.strip
           Вы являетесь продвинутым ботом для составления краткого содержания, который генерирует краткие, связные выдержки из предоставленного текста.
           Вы также можете дополнить существующее резюме, добавив дополнительные сообщения, если вас попросят.
    
           - Включайте только краткую сводку, без каких-либо дополнительных комментариев.
           - Вы понимаете и создаете разметку Markdown на форуме Discourse, включая ссылки, _курсив_, **жирный_текст**.
           - Используйте русский язык, несмотря на язык оригинала исходного текста.
           - Старайтесь, чтобы объем резюме не превышал 400 слов.
           - Каждая запись оформляется как "<POST_NUMBER>) <USERNAME> <MESSAGE>"
           - Цитируйте конкретные заслуживающие внимания публикации, используя формат [DESCRIPTION]({resource_url}/POST_NUMBER)
           - Пример: ссылки на 3-й и 6-й посты пользователя sam: sam ([#3]({resource_url}/3), [#6]({resource_url}/6))
           - Пример: ссылка на 6-е сообщение пользователя jane: [согласовано с]({resource_url}/6)
           - Пример: ссылка на 13-е сообщение Джо: [Джо]({resource_url}/13)
           - При форматировании имен пользователей используйте [USERNAME]({resource_url}/POST_NUMBER)
    
           Отформатируйте свой ответ в виде объекта JSON с помощью единственного ключа с именем "summary", который имеет значение "summary".
           Ваши выходные данные должны быть в следующем формате:
             <output>
               {"summary": "xx"}
             </output>
    
           Где "xx" заменяется на текст краткой сводки.
         PROMPT
       end
    
       def response_format
         [{ "key" => "summary", "type" => "string" }]
       end
    
       def examples
         [
           [
             "Вот записи внутри XML-тегов <input></input>:\n\n<input>1) user1 сказал: Я люблю понедельники 2) user2 сказал: А я ненавижу понедельники</input>\n\nСформулируйте краткое, связное изложение текста выше, сохранив язык оригинала.",
             {
               summary:
                 "Два пользователя делятся своими чувствами к понедельникам. [user1]({resource_url}/1) ненавидит их, тогда как [user2]({resource_url}/2) любит их.",
             }.to_json,
           ],
    
  5. Copy modified files into container:

    sudo docker cp summarize.rb app:/var/www/discourse/plugins/discourse-ai/lib/personas/tools/summarize.rb
    sudo docker cp summarizer.rb app:/var/www/discourse/plugins/discourse-ai/lib/personas/summarizer.rb
    
  6. Then commit and restart the container:

    sudo docker commit app
    sudo /var/discourse/launcher restart app
    
  7. Check the result (for new topics):

There is no need to do all this, you can change the Persona doing the summarization on the admin settings now.

Create a new Persona following the pre-existing one settings, change the system prompt as you want and set the summarization feature to use it at /admin/plugins/discourse-ai/ai-features/1/edit.

2 „Gefällt mir“

Well… The latest words about language support were found in this topic. Thanks for reply.

The first attempt to create proper summarization bot as a clone of an existent bot has failed. It still produces English. Probably I do something wrong.

I am not sure how well you will do with this model, it is not that powerful

1 „Gefällt mir“