Compare commits

...
Author SHA1 Message Date
Sam Saffron a8f54e2709 DEV: adding a concept of prompt builder
This is half baked and not working, but starts demonstrating the idea
2023-08-25 15:54:16 +10:00
Keegan George 7790313b1b DEV: Add review menu state (#159) 2023-08-24 17:49:24 -07:00
Keegan George 65c6b5e16c DEV: Add keybindings (#157)
- Ability to Esc to close context menu
- Ability to Ctrl/Cmd + Z to undo results
2023-08-24 08:35:53 +10:00
Keegan George 78558b9cf5 DEV: Remove context menu timeout (#156) 2023-08-23 15:12:07 -07:00
Keegan George 3cf316fb62 FIX: Context menu not appearing in Firefox (#154) 2023-08-23 14:20:31 -07:00
Sam 7d943be7b2 FIX: automatic bot titles missing sometime (#151)
This fixes 2 big issues:

1. No matter how hard you try, grounding anthropic title prompt
is just too hard. This works around by only looking at the last
sentence it returns and treating as title

2. Non English locales would be stuck with "generic" title, this
ensures every bot message gets a title, using a custom field to
track

Also, slightly tunes some anthropic prompts.
2023-08-24 07:20:24 +10:00
Keegan George 45b7b57726 FIX: Pages with small composers breaking (#155) 2023-08-23 14:20:14 -07:00
Keegan George 1289ae1c57 FIX: Add check for PMs before showing AI helper context menu (#153) 2023-08-23 11:24:51 -07:00
Keegan George 4a00b7eb0e FIX: Show AI helper only if in allowed groups (#152) 2023-08-23 11:06:04 -07:00
Keegan George 6df850d473 FEATURE: AI Helper Context Menu (#148) 2023-08-23 10:35:40 -07:00
Sam f0e1c72aa7 FEATURE: implement command framework for non Open AI (#147)
Open AI support function calling, this has a very specific shape
that other LLMs have not quite adopted.

This simulates a command framework using system prompts on LLMs
that are not open AI.

Features include:

- Smart system prompt to steer the LLM
- Parameter validation (we ensure all the params are specified correctly)

This is being tested on Anthropic at the moment and intial results
are promising.
2023-08-23 07:49:36 +10:00
Discourse Translator Bot 95881fce74 Update translations (#149) 2023-08-22 14:34:48 -03:00
Roman Rizzi f111bcb35b FIX: Display related topics when scrolling to the bottom of a topic. (#150)
Besides updating the connector using the new tracking preference service interface, this PR fixes a bug where due to `ai_embeddings_semantic_related_topics_enabled` not having `client: true` the initializer never ran, and we didn't show the related topics list when scrolling to the bottom of a long topic.
2023-08-22 14:10:21 -03:00
Sam 78f61914c8 FIX: improve token counting (#145)
Previously we were not counting functions correctly and not
accounting for minimum token count per message

This corrects both issues and improves documentation internally
2023-08-22 08:36:41 +10:00
Rafael dos Santos Silva ea5a443588 FEATURE: Try to generate OpenAI Summaries in current language (#146)
* FEATURE: Try to generate OpenAI Summaries in current language

* lint
2023-08-21 15:40:32 -03:00
Penar Musaraj f9105343a6 DEV: Pin plugin for Discourse 3.1 stable (#143) 2023-08-21 14:46:54 -03:00
Martin Brennan 486a130c25 DEV: Categorize plugin settings into discourse_ai (#144)
Moving the plugin settings into a more specific category
makes them easier to find in the plugin UI and removes
them from the generic "Plugins" tab.
2023-08-21 14:46:34 -03:00
Roman Rizzi c0415bb7eb UX: Pill design is the default on both mobile and desktop (#142) 2023-08-17 14:37:14 -03:00
Sam 3e46250f3f UX: Adjust bot warning so it looks better (#141)
This moves the bot warning from `composer-after-composer-editor` to
`after-d-editor` (with a minor adjustment for outlet args to match new name)
2023-08-17 14:43:14 +10:00
Sam b4477ecdcd FEATURE: support 16k and 32k variants for Azure GPT (#140)
Azure requires a single HTTP endpoint per type of completion.

The settings: `ai_openai_gpt35_16k_url` and `ai_openai_gpt4_32k_url` can be
used now to configure the extra endpoints

This amends token limit which was off a bit due to function calls and fixes
a minor JS issue where we were not testing for a property
2023-08-17 11:00:11 +10:00
SamandRafael dos Santos Silva 01f833f86e FEATURE: optional warning attached to all AI bot conversations (#137)
* FEATURE: optional warning attached to all AI bot conversations

This commit introduces `ai_bot_enable_chat_warning` which can be used
to warn people prior to starting a chat with the bot.

In particular this is useful if moderators are regularly reading chat
transcripts as it sets expectations early.

By default this is disabled.

Also:

- Stops making ajax call prior to opening composer
- Hides PM title when starting a bot PM

Co-authored-by: Rafael dos Santos Silva <[email protected]>
2023-08-17 06:29:58 +10:00
Rafael dos Santos Silva 49f2453c2d FEATURE: Tweaks to Anthropic Summarization (#138)
* FEATURE: Tweaks to Anthropic Summarization

* fix specs
2023-08-16 15:09:52 -03:00
Rafael dos Santos Silva 0738f67fa4 FIX: Fix embeddings truncation strategy (#139) 2023-08-16 15:09:41 -03:00
Discourse Translator Bot 525c8b0913 Update translations (#135) 2023-08-15 21:25:07 +02:00
Sam 20c1f2d788 FEATURE: basic progress for image generation (#133)
previously you would have to wait quite a while to see the prompt this implements
a very basic implementation of progress so you can see the API is working.

Also: 

- Fix google progress.
- Handle the incredibly rare, zero results from google.
- Simplify command so it is less error prone
- replace invoke and attache results with a invoke
- ensure invoke can only ever be run once
- pass in all the information a command needs in constructor
- use new pattern throughout
- test invocation in isolation
2023-08-14 16:30:12 +10:00
Roman Rizzi b076e43d67 FEATURE: streaming mode for the FoldContent strategy. (#134) 2023-08-11 15:08:54 -03:00
Régis Hanol 7077c31ab8 Typo in site setting's description (#132) 2023-08-10 14:07:13 -03:00
Sam 7eedbf29e0 FIX: refine image and read command (#131)
- Attempt to hint reading is done by sending complete:true
- Do not include post_number in result unless it was sent in
- Rush visual feedback when a command is run (ensure we always revise)
- Include hyperlink in read command description
- Stop round tripping to GPT after image generation (speeds up images by a lot)
- Add a test for image command
2023-08-09 16:01:48 +10:00
Sam 958dfc360e FEATURE: experimental read command for bot (#129)
This command is useful for reading a topics content. It allows us to perform
critical analysis or suggest answers.

Given 8k token limit in GPT-4 I hardcoded reading to 1500 tokens, but we can
follow up and allow larger windows on models that support more tokens.

On local testing even in this limited form this can be very useful.
2023-08-09 07:19:56 +10:00
Rafael dos Santos Silva 8318c4374c FIX: Remove muted from Similar list (#127)
* FIX: Remove muted from Similar list
2023-08-08 15:44:10 -03:00
Discourse Translator Bot b1987f279d Update translations (#130) 2023-08-08 15:42:39 +02:00
Sam 03e689deb7 FIX: Google command was including full payload (#128)
* FIX: Google command was including full payload

Additionally there was no truncating happening meaning you could blow token
budget easily on a single search.

This made Google search mostly useless and it would mean that after using
Google we would revert to a clean slate which is very confusing.

* no need for nil there
2023-08-08 15:41:57 +10:00
Sam 7edb57c005 DEV: simplify command framework (#125)
The command framework had some confusing dispatching where it would dispatch
JSON blobs, this meant there was lots of parsing required in every command

The refactor handles transforming the args prior to dispatch which makes
consuming far simpler

This is also general prep to supporting some basic command framework in other
llms.
2023-08-04 09:37:58 +10:00
Rafael dos Santos Silva eb7fff3a55 FEATURE: Add support for StableBeluga and Upstage Llama2 instruct (#126)
* FEATURE: Add support for StableBeluga and Upstage Llama2 instruct

This means we support all models in the top3 of the Open LLM Leaderboard

Since some of those models have RoPE, we now have a setting so you can
customize the token limit depending which model you use.
2023-08-03 15:29:30 -03:00
Rafael dos Santos Silva 8b157feea5 FEATURE: Compatibility with protected Hugging Face Endpoints (#123)
* FEATURE: Compatibility with protected Hugging Face Endpoints
2023-08-02 17:00:00 -03:00
Roman Rizzi 58b96eda6c REFACTOR: Build related topics using TopicQuery. (#124)
TopicQuery already provides a lot of safeguards and options for filtering topic, and enforcing permissions. It makes sense to rely on it as other plugins like discourse-assign do.

As a bonus, we now have access to the current_user while serializing these topics, so users will see things like unread posts count just like we do for the lists.
2023-08-02 16:58:09 -03:00
Sam 602bb843ea FEATURE: add support for final stable diffusion xl model (#122) 2023-08-02 16:53:28 -03:00
Roman RizziandDavid Taylor 51fdf21143 DEV: Pin plugin for v3.1 (#121)
* DEV: Pin plugin for v3.1

Changes to the topic recommendations list added by discourse/discourse#22896 were reverted from stable.

* Update .discourse-compatibility

Co-authored-by: David Taylor <[email protected]>

---------

Co-authored-by: David Taylor <[email protected]>
2023-08-01 12:13:00 -03:00
Discourse Translator Bot c26d48e3b1 Update translations (#119) 2023-08-01 16:05:55 +02:00
Roman Rizzi c8de9495c8 UX: Update related-topics to follow <MoreTopics/> conventions (#118) 2023-07-31 18:33:37 -03:00
Rafael dos Santos Silva 3e7c99de89 FEATURE: Support for locally infered embeddings in 100 languages (#115)
* FEATURE: Support for locally infered embeddings in 100 languages

* add table
2023-07-27 15:50:03 -03:00
Rafael dos Santos Silva b25daed60b FEATURE: Llama2 for summarization (#116) 2023-07-27 13:55:32 -03:00
Sam 4b0c077ce5 FEATURE: port to use claude-2 for chat bot (#114)
Claude 1 costs the same and is less good than Claude 2. Make use of Claude
2 in all spots ...

This also fixes streaming so it uses the far more efficient streaming protocol.
2023-07-27 11:24:44 +10:00
Discourse Translator Bot 2031388f9c Update translations (#109) 2023-07-25 17:57:58 +02:00
Roman Rizzi 79289ba231 FIX: Use base 10 when gettings allowed group IDs from settings. (#113)
A missing parameter on the `parseInt` function was causing unexpected UI behavior for the AI helper since it turned an allowed group ID into NaN. We should always use base10 when parsing these IDs.
2023-07-24 11:29:49 -03:00
dependabot[bot] 3f05d3a732 Build(deps): Bump word-wrap from 1.2.3 to 1.2.4 (#112)
Bumps [word-wrap](https://github.com/jonschlinkert/word-wrap) from 1.2.3 to 1.2.4.
- [Release notes](https://github.com/jonschlinkert/word-wrap/releases)
- [Commits](https://github.com/jonschlinkert/word-wrap/compare/1.2.3...1.2.4)

---
updated-dependencies:
- dependency-name: word-wrap
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <[email protected]>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-07-20 10:19:23 +02:00
Rafael dos Santos SilvaandRoman Rizzi f34094f6cc FIX: Show related topics when scrolling long topics (#111)
* FIX: Show related topics when scrolling long topics

* Update assets/javascripts/initializers/related-topics.js

Co-authored-by: Roman Rizzi <[email protected]>

---------

Co-authored-by: Roman Rizzi <[email protected]>
2023-07-19 19:19:38 -03:00
Rafael dos Santos Silva e3b4a73267 FEATURE: Cache Related Topics for longer (#110) 2023-07-18 11:27:06 -03:00
Discourse Translator Bot 7ea468708c DEV: Add Crowdin support (#108) 2023-07-15 00:56:15 +02:00
Rafael dos Santos Silva b82074850e DEV: Add tests to allmpnet tokenizer (#107)
* DEV: Add tests to allmpnet tokenizer

* lint
2023-07-14 11:37:21 -03:00
Roman Rizzi 473732c18a FIX: Return base prompt instead of nil (#106) 2023-07-13 21:48:25 -03:00
Rafael dos Santos Silva d692ecc7de FIX: Disable truncation and padding in all-mpnet-base-v2 tokenizer (#105)
The tokenizer was truncating and padding to 128 tokens, and we try append
new post content until we hit 384 tokens. This was causing the tokenizer
to accept all posts in a topic, wasting CPU and memory.
2023-07-13 21:09:46 -03:00
Rafael dos Santos Silva 703762a7a9 PERF: .find_each instead of .find to save us from memory allocation peaks
also Fix embeddings rake task for new db structure
2023-07-13 18:59:25 -03:00
Roman Rizzi 5f0c617880 REFACTOR: Cohesive narrative for single-chunk summaries. (#103)
Single and multi-chunk summaries end using different prompts for the last summary. This change detects when the summarized content fits in a single chunk and uses a slightly different prompt, which leads to more consistent summary formats.

This PR also moves the chunk-splitting step to the `FoldContent` strategy as preparation for implementing streamed summaries.
2023-07-13 17:05:41 -03:00
David TaylorandRafael dos Santos Silva 48d880d3c8 FIX: Rerender related topics correctly when topic changes (#100)
* FIX: Rerender related topics correctly when topic changes


Co-authored-by: Rafael dos Santos Silva <[email protected]>
2023-07-13 16:34:02 -03:00
Rafael dos Santos Silva 5e3f4e1b78 FEATURE: Embeddings to main db (#99)
* FEATURE: Embeddings to main db

This commit moves our embeddings store from an external configurable PostgreSQL
instance back into the main database. This is done to simplify the setup.

There is a migration that will try to import the external embeddings into
the main DB if it is configured and there are rows.

It removes support from embeddings models that aren't all_mpnet_base_v2 or OpenAI
text_embedding_ada_002. However it will now be easier to add new models.

It also now takes into account:
  - topic title
  - topic category
  - topic tags
  - replies (as much as the model allows)

We introduce an interface so we can eventually support multiple strategies
for handling long topics.

This PR severely damages the semantic search performance, but this is a
temporary until we can get adapt HyDE to make semantic search use the same
embeddings we have for semantic related with good performance.

Here we also have some ground work to add post level embeddings, but this
will be added in a future PR.

Please note that this PR will also block Discourse from booting / updating if 
this plugin is installed and the pgvector extension isn't available on the 
PostgreSQL instance Discourse uses.
2023-07-13 12:41:36 -03:00
Rafael dos Santos Silva 9d10a152b9 FEATURE: Claude 2 for summarization and AIHelper (#101) 2023-07-13 12:32:08 -03:00
dependabot[bot] 1c017c22b0 Build(deps): Bump semver from 6.3.0 to 6.3.1 (#102)
Bumps [semver](https://github.com/npm/node-semver) from 6.3.0 to 6.3.1.
- [Release notes](https://github.com/npm/node-semver/releases)
- [Changelog](https://github.com/npm/node-semver/blob/v6.3.1/CHANGELOG.md)
- [Commits](https://github.com/npm/node-semver/compare/v6.3.0...v6.3.1)

---
updated-dependencies:
- dependency-name: semver
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <[email protected]>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-07-13 09:33:34 +02:00
Roman Rizzi fbe1bab980 FIX: typo while updating a section (#98) 2023-06-27 17:57:58 -03:00
Roman Rizzi 1b568f2391 FIX: Claude's max_tookens_to_sample is a required field (#97) 2023-06-27 14:42:33 -03:00
Roman Rizzi 9a79afcdbf DEV: Better strategies for summarization (#88)
* DEV: Better strategies for summarization

The strategy responsibility needs to be "Given a collection of texts, I know how to summarize them most efficiently, using the minimum amount of requests and maximizing token usage".

There are different token limits for each model, so it all boils down to two different strategies:

Fold all these texts into a single one, doing the summarization in chunks, and then build a summary from those.
Build it by combining texts in a single prompt, and truncate it according to your token limits.

While the latter is less than ideal, we need it for "bart-large-cnn-samsum" and "flan-t5-base-samsum", both with low limits. The rest will rely on folding.

* Expose summarized chunks to users
2023-06-27 12:26:33 -03:00
Sam 9390fba768 FIX: adjust token limits to account for functions (#96)
Reduce maximum replies to 2500 tokens and make them even for both GPT-3.5
and 4

Account for 400+ tokens in function definitions (this was unaccounted for)
2023-06-23 10:02:04 +10:00
Sam f8cabfad6b FEATURE: Try to hone search so it reduces search terms in subsequent rounds (#95)
Teach via system message that you can reduce search terms to get more
results
2023-06-21 20:07:55 +10:00
Sam a028309cbd FEATURE: add ai_bot_enabled_chat commands and tune search (#94)
* FEATURE: add ai_bot_enabled_chat commands and tune search

This allows admins to disable/enable GPT command integrations.

Also hones search results which were looping cause the result did not denote
the failure properly (it lost context)

* include more context for google command
include more context for time command

* type
2023-06-21 17:10:30 +10:00
Sam d1ab79e82f FEATURE: Add Azure cognitive service support (#93)
The new site settings:

ai_openai_gpt35_url : distribution for GPT 16k
ai_openai_gpt4_url: distribution for GPT 4
ai_openai_embeddings_url: distribution for ada2

If untouched we will simply use OpenAI endpoints.

Azure requires 1 URL per model, OpenAI allows a single URL to serve multiple models. Hence the new settings.
2023-06-21 10:39:51 +10:00
Sam 30778d8af8 FIX: avoid storing corrupt prompts (#92)
```
prompt << build_message(bot_user.username, reply)
```

Would store a "cooked" prompt which is invalid, instead just store the raw
values which are later passed to build_message

Additionally:

1. Disable summary command which needs honing
2. Stop storing decorations (searched for X) in prompt which leads to straying
3. Ship username directly to model, avoiding "user: content" in prompts. This
 was causing GPT to stray
2023-06-20 15:44:03 +10:00
Sam 70c158cae1 FEATURE: add full bot support for GPT 3.5 (#87)
Given latest GPT 3.5 16k which is both better steered and supports functions
we can now support rich bot integration.

Clunky system message based steering is removed and instead we use the
function framework provided by Open AI
2023-06-20 08:45:31 +10:00
Rafael dos Santos SilvaandJoffrey JAFFEUX e457c687ca FIX: OpenAI Tokenizer was failing to truncate mid emojis (#91)
* FIX: OpenAI Tokenizer was failing to truncate mid emojis

* Update spec/shared/tokenizer.rb

Co-authored-by: Joffrey JAFFEUX <[email protected]>

---------

Co-authored-by: Joffrey JAFFEUX <[email protected]>
2023-06-16 15:15:36 -03:00
Roman Rizzi 9e901dbfbf FIX: Serialize channel title for DMs (#90) 2023-06-16 14:37:16 -03:00
David Taylor 68bc80e19d DEV: Fix Zeitwerk reloading error (#89)
Using `.append` can lead to a 'two routes with the same name' error
2023-06-16 11:32:54 +01:00
Rafael dos Santos Silva 8742535024 FEATURE: Allow using large context OpenAI models for summarization (#86) 2023-06-13 15:23:48 -03:00
Roman Rizzi 3364fec425 DEV: Remove the summarization feature (#83)
* DEV: Remove the summarization feature

Instead, we'll register summarization implementations for OpenAI, Anthropic, and Discourse AI using the API defined in discourse/discourse#21813.

Core and chat will implement features on top of these implementations instead of this plugin extending them.

* Register instances that contain the model, requiring less site settings
2023-06-13 14:32:26 -03:00
Sam 081231a6eb FIX: support multiple command executions (#85)
Previous to this change we were chaining stuff too late and would execute
commands serially leading to very unexpected results

This corrects this and allows us to run stuff like:

> Search google 3/4 times on various permutations of
QUERY and answer this question.

We limit at 5 commands to ensure there are not pathological user cases
where you lean on the LLM to flood us with results.
2023-06-06 07:09:33 +10:00
Sam 840968630e FEATURE: disable smart commands on Claude and GPT 3.5 (#84)
For the time being smart commands only work consistently on GPT 4.
Avoid using any smart commands on the earlier models.

Additionally adds better error handling to Claude which sometimes streams
partial json and slightly tunes the search command.
2023-06-01 09:10:33 +10:00
SamandKrzysztof Kotlarek 96d521198b FIX: missing localization (#81)
blog.start_gpt_chat -> was on my blog

This also slightly tunes the search prompt to support filtering by oldest
and try a tiny bit harder to guide GPT 3.5 which is a bit of a losing battle

Co-authored-by: Krzysztof Kotlarek <[email protected]>
2023-05-25 11:05:02 +10:00
Rafael dos Santos SilvaandDavid Taylor cfc6e388df FIX: Ensure embeddings database outages are handled gracefully (#80)
The rails_failover middleware will intercept all `PG::ConnectionBad` errors and put the cluster into readonly mode. It does not have any handling for multiple databases. Therefore, an issue with the embeddings database was taking the whole cluster into readonly.

This commit fixes the issue by rescuing `PG::Error` from all AI database accesses, and re-raises errors with a different class. It also adds a spec to ensure that an embeddings database outage does not affect the functionality of the topics/show route.

Co-authored-by: David Taylor <[email protected]>
2023-05-23 22:57:52 +01:00
Rafael dos Santos Silva b213fe7f94 FIX: Give up trying to reuse the DB connection and rely on pgbouncer (#79) 2023-05-23 15:12:59 -03:00
Roman Rizzi c582e3b848 DEV: Fix toxicity test (#78) 2023-05-23 11:02:11 -03:00
Sam d85b503ed4 FIX: guide GPT 3.5 better (#77)
* FIX: guide GPT 3.5 better

This limits search results to 10 cause we were blowing the whole token
budget on search results, additionally it includes a quick exchange at
the start of a session to try and guide GPT 3.5 to follow instructions

Sadly GPT 3.5 drifts off very quickly but this does improve stuff a bit.

It also attempts to correct some issues with anthropic, though it still is
surprisingly hard to ground

* add status:public, this is a bit of a hack but ensures that we can search
for any filter provided

* fix specs
2023-05-23 23:08:17 +10:00
Sam b82fc1e692 FIX: ensure we only attempt embedding once every 15 minutes (#76)
This also heavily reduced log noise and ensures our exception handling is
more surgical.
2023-05-23 10:43:24 +10:00
Sam 074d00ca32 FEATURE: improve search prompt (#75)
- We only support searching public topics - make it clear
- Stop using bug/feature, cause is poisons system - these may not exist
- Add after: and before: which are very handy for bounding search results
2023-05-23 07:52:14 +10:00
Sam e0cf7b7d70 FIX: results will be nil for invalid queries (#74)
Previous to this change invalid searches would break the command.
2023-05-22 15:14:26 +10:00
Sam 92fb84e24d iterate commands (#73)
* FEATURE: introduce a more efficient formatter

Previous formatting style was space inefficient given JSON consumes lots
of tokens, the new format is now used consistently across commands

Also fixes

- search limited to 10
- search breaking on limit: non existent directive

* Slight improvement to summarizer
Stop blowing up context with custom prompts

* ensure we include the guiding message

* correct spec

* langchain style summarizer ...

much more accurate (albeit more expensive)

* lint
2023-05-22 12:09:14 +10:00
SamandRoman Rizzi d59ed1091b FEATURE: add support for GPT <-> Forum integration
This change-set connects GPT based chat with the forum it runs on. Allowing it to perform search, lookup tags and categories and summarize topics. 

The integration is currently restricted to public portions of the forum. 

Changes made:

- Do not run ai reply job for small actions
- Improved composable system prompt
- Trivial summarizer for topics
- Image generator 
- Google command for searching via Google
- Corrected trimming of posts raw (was replacing with numbers) 
- Bypass of problem specs

The feature works best with GPT-4


---------

Co-authored-by: Roman Rizzi <[email protected]>
2023-05-20 17:45:54 +10:00
Rafael dos Santos Silva 262ed4753e FEATURE: Basic StableDiffusion text2img support (#72) 2023-05-20 09:38:08 +10:00
Roman Rizzi ba65d42940 FIX: Hide summarization button from anons (#70) 2023-05-18 12:34:49 -03:00
David Taylor 261fe13599 DEV: Tweaks for drop-down implementation (#69)
- Remove unused 'toggleAiBotPanel' widget action

- Switch from appEvents to closure actions

- Convert widget definition to native class syntax, so that we can use `@action` decorator. (alternatively, we could have done `{ closePanel: this.hideAiBotPanel.bind(this) }` in `RenderGlimmer`
2023-05-18 09:28:43 +01:00
Sam deb34bb52f UX: improve drop down menu for enabled bots (#68)
Previously we were not using using HeaderPanel for drop down, which caused
it not to properly act like a header panel.

- Not styled right
- Not hidden when other buttons clicked

Etc...

Header is sadly full of legacy so this is somewhat hacky weaving widgets.
2023-05-18 16:10:08 +10:00
Rafael dos Santos Silva 739b314312 Fixes for embeddings and truncate (#67) 2023-05-18 09:21:28 +10:00
Roman Rizzi 9ae8f86850 UX: Improvements to the AI Bot header shortcut (#66)
- Humanize model names
- Focus composer editor when starting a PM with a bot
- Correctly close the models dropdown when clicking outside
2023-05-17 15:59:48 -03:00
Rafael dos Santos Silva e9ae28f773 FIX: Non instructor OSS embeddings was broken (#65) 2023-05-17 12:10:10 -03:00
Roman Rizzi 5ade5d7404 UX: Add missing label translation (#64) 2023-05-16 16:56:30 -03:00
Roman RizziandRafael dos Santos Silva 362f6167d1 FEATURE: Less friction for starting a conversation with an AI bot. (#63)
* FEATURE: Less friction for starting a conversation with an AI bot.

This PR adds a new header icon as a shortcut to start a conversation with one of our AI Bots. After clicking and selecting one from the dropdown menu, we'll open the composer with some fields already filled (recipients and title).

If you leave the title as is, we'll queue a job after five minutes to update it using a bot suggestion.

* Update assets/javascripts/initializers/ai-bot-replies.js

Co-authored-by: Rafael dos Santos Silva <[email protected]>

* Update assets/javascripts/initializers/ai-bot-replies.js

Co-authored-by: Rafael dos Santos Silva <[email protected]>

---------

Co-authored-by: Rafael dos Santos Silva <[email protected]>
2023-05-16 14:38:21 -03:00
Rafael dos Santos Silva 2ed1f874c2 Use correct API signature for instructor embeddings (#62) 2023-05-15 17:18:11 -03:00
Rafael dos Santos Silva 3c9513e754 Refinements to embeddings and tokenizers (#61)
* Refinements to embeddings and tokenizers

* lint

* Truncate with tokenizers for summary

* fix
2023-05-15 15:10:42 -03:00
249 changed files with 1103167 additions and 1266 deletions
+2
View File
@@ -1 +1,3 @@
3.1.999: c0415bb7eb878b1b7abf112d65cba981030df8df
< 3.2.0.beta1-dev: 3e7c99de894b03e9161d9481da118fe893991a1d
3.1.0.beta3: 057fbe1ce6
@@ -14,6 +14,15 @@ module DiscourseAi
render json: {}, status: 200
end
def show_bot_username
bot_user_id = DiscourseAi::AiBot::EntryPoint.map_bot_model_to_user_id(params[:username])
raise Discourse::InvalidParameters.new(:username) if !bot_user_id
bot_username_lower = User.find(bot_user_id).username_lower
render json: { bot_username: bot_username_lower }, status: 200
end
end
end
end
@@ -19,13 +19,8 @@ module DiscourseAi
use_pg_headlines_for_excerpt: false,
)
model =
DiscourseAi::Embeddings::Model.instantiate(
SiteSetting.ai_embeddings_semantic_search_model,
)
DiscourseAi::Embeddings::SemanticSearch
.new(guardian, model)
.new(guardian)
.search_for_topics(query, page)
.each { |topic_post| grouped_results.add(topic_post) }
@@ -1,48 +0,0 @@
# frozen_string_literal: true
module DiscourseAi
module Summarization
class SummaryController < ::ApplicationController
requires_plugin ::DiscourseAi::PLUGIN_NAME
requires_login
VALID_SINCE_VALUES = [1, 3, 6, 12, 24, 72, 168]
VALID_TARGETS = %w[chat_channel topic]
def show
raise PluginDisabled unless SiteSetting.ai_summarization_enabled
target_type = params[:target_type]
raise Discourse::InvalidParameters.new(:target_type) if !VALID_TARGETS.include?(target_type)
since = nil
if target_type == "chat_channel"
since = params[:since].to_i
raise Discourse::InvalidParameters.new(:since) if !VALID_SINCE_VALUES.include?(since)
target = Chat::Channel.find_by(id: params[:target_id])
raise Discourse::NotFound.new(:chat_channel) if !target
raise Discourse::InvalidAccess if !guardian.can_join_chat_channel?(target)
else
target = Topic.find_by(id: params[:target_id])
raise Discourse::NotFound.new(:topic) if !target
raise Discourse::InvalidAccess if !guardian.can_see_topic?(target)
end
RateLimiter.new(
current_user,
"ai_summarization",
6,
SiteSetting.ai_summarization_rate_limit_minutes.minutes,
).performed!
hijack do
summary =
DiscourseAi::Summarization::SummaryGenerator.new(target, current_user).summarize!(since)
render json: { summary: summary }, status: 200
end
end
end
end
end
+1
View File
@@ -4,6 +4,7 @@ class AiApiAuditLog < ActiveRecord::Base
module Provider
OpenAI = 1
Anthropic = 2
HuggingFaceTextGeneration = 3
end
end
+9
View File
@@ -0,0 +1,9 @@
# frozen_string_literal: true
class PostCustomPrompt < ActiveRecord::Base
belongs_to :post
end
class ::Post
has_one :post_custom_prompt, dependent: :destroy
end
@@ -1,5 +1,11 @@
# frozen_string_literal: true
class AiChatChannelSerializer < ApplicationSerializer
attributes :id, :chatable, :chatable_type, :chatable_url, :title, :slug
attributes :id, :chatable, :chatable_type, :chatable_url, :slug
def title
# Display all participants for a DM.
# For category channels, the argument is ignored.
object.title(nil)
end
end
@@ -0,0 +1,18 @@
<div class="bot-panel ai-bot-available-bot-options">
<div class="menu-panel drop-down">
<div class="panel-body">
<div class="panel-body-contents">
<div class="sidebar-hamburger-dropdown">
{{#each this.botNames as |bot|}}
<DButton
@class="btn-flat ai-bot-available-bot-content"
@translatedTitle={{bot.humanized}}
@translatedLabel={{bot.humanized}}
@action={{action "composeMessageWithTargetBot" bot.modelName}}
/>
{{/each}}
</div>
</div>
</div>
</div>
</div>
@@ -0,0 +1,34 @@
import { action } from "@ember/object";
import { inject as service } from "@ember/service";
import Component from "@glimmer/component";
import { composeAiBotMessage } from "discourse/plugins/discourse-ai/discourse/lib/ai-bot-helper";
import I18n from "I18n";
export default class AiBotHeaderPanel extends Component {
@service siteSettings;
@service composer;
@action
composeMessageWithTargetBot(target) {
this.#composeAiBotMessage(target);
}
get botNames() {
return this.enabledBotOptions.map((bot) => {
return {
humanized: I18n.t(`discourse_ai.ai_bot.bot_names.${bot}`),
modelName: bot,
};
});
}
get enabledBotOptions() {
return this.siteSettings.ai_bot_enabled_chat_bots.split("|");
}
#composeAiBotMessage(targetBot) {
this.args.closePanel();
composeAiBotMessage(targetBot, this.composer);
}
}
@@ -1,32 +0,0 @@
<DModalBody @title="discourse_ai.summarization.title">
{{#if @allowTimeframe}}
<span>{{i18n "discourse_ai.summarization.description"}}</span>
<ComboBox
@value={{this.sinceHours}}
@content={{this.sinceOptions}}
@onChange={{action this.summarize}}
@valueProperty="value"
@class="summarization-since"
/>
{{/if}}
<div class="channel-summary">
<ConditionalLoadingSpinner @condition={{this.loading}} />
{{#unless this.loading}}
<Textarea @value={{this.summary}} disabled="true" class="summary-area" />
{{/unless}}
</div>
</DModalBody>
<div class="modal-footer">
{{#unless @allowTimeframe}}
<DButton
@class="btn-primary create"
@action={{this.summarize}}
@label="discourse_ai.summarization.summarize"
/>
{{/unless}}
<DModalCancel @close={{route-action "closeModal"}} />
</div>
@@ -1,83 +0,0 @@
import Component from "@glimmer/component";
import { tracked } from "@glimmer/tracking";
import { action } from "@ember/object";
import { ajax } from "discourse/lib/ajax";
import { popupAjaxError } from "discourse/lib/ajax-error";
import I18n from "I18n";
export default class AiSummary extends Component {
@tracked sinceHours = null;
@tracked loading = false;
@tracked availableSummaries = {};
@tracked summary = null;
sinceOptions = [
{
name: I18n.t("discourse_ai.summarization.since", { count: 1 }),
value: 1,
},
{
name: I18n.t("discourse_ai.summarization.since", { count: 3 }),
value: 3,
},
{
name: I18n.t("discourse_ai.summarization.since", { count: 6 }),
value: 6,
},
{
name: I18n.t("discourse_ai.summarization.since", { count: 12 }),
value: 12,
},
{
name: I18n.t("discourse_ai.summarization.since", { count: 24 }),
value: 24,
},
{
name: I18n.t("discourse_ai.summarization.since", { count: 72 }),
value: 72,
},
{
name: I18n.t("discourse_ai.summarization.since", { count: 168 }),
value: 168,
},
];
get canSummarize() {
return (!this.args.allowTimeframe || this.sinceHours) && !this.loading;
}
@action
summarize(value) {
this.loading = true;
const attrs = {
target_id: this.args.targetId,
target_type: this.args.targetType,
};
if (this.args.allowTimeframe) {
this.sinceHours = value;
if (this.availableSummaries[this.sinceHours]) {
this.summary = this.availableSummaries[this.sinceHours];
this.loading = false;
return;
} else {
attrs.since = this.sinceHours;
}
}
ajax("/discourse-ai/summarization/summary", {
method: "POST",
data: attrs,
})
.then((data) => {
if (this.args.allowTimeframe) {
this.availableSummaries[this.sinceHours] = data.summary;
this.summary = this.availableSummaries[this.sinceHours];
} else {
this.summary = data.summary;
}
})
.catch(popupAjaxError)
.finally(() => (this.loading = false));
}
}
@@ -0,0 +1,48 @@
import Component from "@glimmer/component";
import { action } from "@ember/object";
import DButton from "discourse/components/d-button";
import DModal from "discourse/components/d-modal";
import DModalCancel from "discourse/components/d-modal-cancel";
import I18n from "I18n";
import { htmlSafe } from "@ember/template";
const t = I18n.t.bind(I18n);
export default class ModalDiffModal extends Component {
<template>
<DModal
class="composer-ai-helper-modal"
@title={{t "discourse_ai.ai_helper.context_menu.changes"}}
@closeModal={{@closeModal}}
>
<:body>
{{#if @diff}}
{{htmlSafe @diff}}
{{else}}
<div class="composer-ai-helper-modal__old-value">
{{@oldValue}}
</div>
<div class="composer-ai-helper-modal__new-value">
{{@newValue}}
</div>
{{/if}}
</:body>
<:footer>
<DButton
class="btn-primary confirm"
@action={{this.triggerConfirmChanges}}
@label="discourse_ai.ai_helper.context_menu.confirm"
/>
<DModalCancel @close={{@closeModal}} />
</:footer>
</DModal>
</template>
@action
triggerConfirmChanges() {
this.args.closeModal();
this.args.confirm();
}
}
@@ -0,0 +1,116 @@
<div {{did-insert this.setupContextMenu}}>
{{#if this.showContextMenu}}
<div class="ai-helper-context-menu">
{{#if (eq this.menuState this.CONTEXT_MENU_STATES.triggers)}}
<ul class="ai-helper-context-menu__trigger">
<li>
<DButton
@icon="magic"
@action={{this.toggleAiHelperOptions}}
@label="discourse_ai.ai_helper.context_menu.trigger"
class="btn-flat"
/>
</li>
</ul>
{{else if (eq this.menuState this.CONTEXT_MENU_STATES.options)}}
<ul class="ai-helper-context-menu__options">
{{#each this.helperOptions as |option|}}
<li data-name={{option.name}} data-value={{option.value}}>
<DButton
@class="btn-flat"
@translatedLabel={{option.name}}
@action={{this.updateSelected}}
@actionParam={{option.value}}
/>
</li>
{{/each}}
</ul>
{{else if (eq this.menuState this.CONTEXT_MENU_STATES.suggestions)}}
<ul class="ai-helper-context-menu__suggestions">
{{#each this.generatedTitleSuggestions as |suggestion index|}}
<li data-name={{suggestion}} data-value={{index}}>
<DButton
@class="btn-flat"
@translatedLabel={{suggestion}}
@action={{this.updateTopicTitle}}
@actionParam={{suggestion}}
/>
</li>
{{/each}}
</ul>
{{else if (eq this.menuState this.CONTEXT_MENU_STATES.loading)}}
<ul class="ai-helper-context-menu__loading">
<li>
<div class="dot-falling"></div>
<span>
{{i18n "discourse_ai.ai_helper.context_menu.loading"}}
</span>
</li>
</ul>
{{else if (eq this.menuState this.CONTEXT_MENU_STATES.review)}}
<ul class="ai-helper-context-menu__review">
<li>
<DButton
@icon="exchange-alt"
@label="discourse_ai.ai_helper.context_menu.view_changes"
@action={{this.viewChanges}}
class="btn-flat view-changes"
/>
</li>
<li>
<DButton
@icon="undo"
@label="discourse_ai.ai_helper.context_menu.revert"
@action={{this.undoAIAction}}
class="btn-flat revert"
/>
</li>
<li>
<DButton
@icon="check"
@label="discourse_ai.ai_helper.context_menu.confirm"
@action={{this.confirmChanges}}
class="btn-flat confirm"
/>
</li>
</ul>
{{else if (eq this.menuState this.CONTEXT_MENU_STATES.resets)}}
<ul class="ai-helper-context-menu__resets">
<li>
<DButton
@icon="undo"
@label="discourse_ai.ai_helper.context_menu.undo"
@action={{this.undoAIAction}}
class="btn-flat undo"
/>
</li>
<li>
<DButton
@icon="discourse-sparkles"
@label="discourse_ai.ai_helper.context_menu.regen"
@action={{this.updateSelected}}
@actionParam={{this.lastUsedOption}}
class="btn-flat"
/>
</li>
</ul>
{{/if}}
</div>
{{/if}}
</div>
{{#if this.showDiffModal}}
<Modal::DiffModal
@confirm={{this.confirmChanges}}
@diff={{this.diff}}
@oldValue={{this.selectedText}}
@newValue={{this.newSelectedText}}
@closeModal={{fn (mut this.showDiffModal) false}}
/>
{{/if}}
@@ -0,0 +1,292 @@
import Component from "@glimmer/component";
import { action } from "@ember/object";
import { afterRender, bind, debounce } from "discourse-common/utils/decorators";
import { tracked } from "@glimmer/tracking";
import { INPUT_DELAY } from "discourse-common/config/environment";
import { ajax } from "discourse/lib/ajax";
import { popupAjaxError } from "discourse/lib/ajax-error";
import { createPopper } from "@popperjs/core";
import { caretPosition, getCaretPosition } from "discourse/lib/utilities";
import { inject as service } from "@ember/service";
export default class AiHelperContextMenu extends Component {
static shouldRender(outletArgs, helper) {
const helperEnabled =
helper.siteSettings.discourse_ai_enabled &&
helper.siteSettings.composer_ai_helper_enabled;
const allowedGroups = helper.siteSettings.ai_helper_allowed_groups
.split("|")
.map((id) => parseInt(id, 10));
const canUseAssistant = helper.currentUser?.groups.some((g) =>
allowedGroups.includes(g.id)
);
const canShowInPM = helper.siteSettings.ai_helper_allowed_in_pm;
if (outletArgs?.composer?.privateMessage) {
return helperEnabled && canUseAssistant && canShowInPM;
}
return helperEnabled && canUseAssistant;
}
@service siteSettings;
@tracked helperOptions = [];
@tracked showContextMenu = false;
@tracked menuState = this.CONTEXT_MENU_STATES.triggers;
@tracked caretCoords;
@tracked virtualElement;
@tracked selectedText = "";
@tracked newSelectedText;
@tracked loading = false;
@tracked oldEditorValue;
@tracked newEditorValue;
@tracked generatedTitleSuggestions = [];
@tracked lastUsedOption = null;
@tracked showDiffModal = false;
@tracked diff;
CONTEXT_MENU_STATES = {
triggers: "TRIGGERS",
options: "OPTIONS",
resets: "RESETS",
loading: "LOADING",
suggesions: "SUGGESTIONS",
review: "REVIEW",
};
prompts = [];
promptTypes = {};
@tracked _popper;
@tracked _dEditorInput;
@tracked _contextMenu;
willDestroy() {
super.willDestroy(...arguments);
document.removeEventListener("selectionchange", this.selectionChanged);
document.removeEventListener("keydown", this.onKeyDown);
this._popper?.destroy();
}
async loadPrompts() {
let prompts = await ajax("/discourse-ai/ai-helper/prompts");
prompts.map((p) => {
this.prompts[p.id] = p;
});
this.promptTypes = prompts.reduce((memo, p) => {
memo[p.name] = p.prompt_type;
return memo;
}, {});
this.helperOptions = prompts.map((p) => {
return {
name: p.translated_name,
value: p.id,
};
});
}
@bind
selectionChanged() {
if (document.activeElement !== this._dEditorInput) {
return;
}
const canSelect = Boolean(
window.getSelection() &&
document.activeElement &&
document.activeElement.value
);
this.selectedText = canSelect
? document.activeElement.value.substring(
document.activeElement.selectionStart,
document.activeElement.selectionEnd
)
: "";
if (this.selectedText.length === 0) {
if (this.loading || this.menuState === this.CONTEXT_MENU_STATES.review) {
// prevent accidentally closing context menu
// while results loading or in review state
return;
}
this.closeContextMenu();
return;
}
this._onSelectionChanged();
}
@bind
updatePosition() {
if (!this.showContextMenu) {
return;
}
this.positionContextMenu();
}
@bind
onKeyDown(event) {
const cmdOrCtrl = event.ctrlKey || event.metaKey;
if (cmdOrCtrl && event.key === "z" && this.oldEditorValue) {
return this.undoAIAction();
}
if (event.key === "Escape") {
return this.closeContextMenu();
}
}
@debounce(INPUT_DELAY)
_onSelectionChanged() {
this.positionContextMenu();
this.showContextMenu = true;
}
generateGetBoundingClientRect(width = 0, height = 0, x = 0, y = 0) {
return () => ({
width,
height,
top: y,
right: x,
bottom: y,
left: x,
});
}
closeContextMenu() {
this.showContextMenu = false;
this.menuState = this.CONTEXT_MENU_STATES.triggers;
}
_updateSuggestedByAI(data) {
const composer = this.args.outletArgs.composer;
this.oldEditorValue = this._dEditorInput.value;
this.newSelectedText = data.suggestions[0];
this.newEditorValue = this.oldEditorValue.replace(
this.selectedText,
this.newSelectedText
);
if (data.diff) {
this.diff = data.diff;
}
composer.set("reply", this.newEditorValue);
this.menuState = this.CONTEXT_MENU_STATES.review;
}
@afterRender
positionContextMenu() {
this._contextMenu = document.querySelector(".ai-helper-context-menu");
this.caretCoords = getCaretPosition(this._dEditorInput, {
pos: caretPosition(this._dEditorInput),
});
this.virtualElement = {
getBoundingClientRect: this.generateGetBoundingClientRect(
this._contextMenu.clientWidth,
this._contextMenu.clientHeight,
this.caretCoords.x,
this.caretCoords.y
),
};
this._popper = createPopper(this.virtualElement, this._contextMenu, {
placement: "top-start",
modifiers: [
{
name: "offset",
options: {
offset: [10, 0],
},
},
],
});
}
@action
setupContextMenu() {
document.addEventListener("selectionchange", this.selectionChanged);
document.addEventListener("keydown", this.onKeyDown);
this._dEditorInput = document.querySelector(".d-editor-input");
if (this._dEditorInput) {
this._dEditorInput.addEventListener("scroll", this.updatePosition);
}
}
@action
toggleAiHelperOptions() {
// Fetch prompts only if it hasn't been fetched yet
if (this.helperOptions.length === 0) {
this.loadPrompts();
}
this.menuState = this.CONTEXT_MENU_STATES.options;
}
@action
undoAIAction() {
const composer = this.args.outletArgs.composer;
composer.set("reply", this.oldEditorValue);
this.closeContextMenu();
}
@action
async updateSelected(option) {
this.loading = true;
this.lastUsedOption = option;
this._dEditorInput.classList.add("loading");
this.menuState = this.CONTEXT_MENU_STATES.loading;
return ajax("/discourse-ai/ai-helper/suggest", {
method: "POST",
data: { mode: option, text: this.selectedText },
})
.then((data) => {
// resets the values if new suggestion is started:
this.diff = null;
this.newSelectedText = null;
if (this.prompts[option].name === "generate_titles") {
this.menuState = this.CONTEXT_MENU_STATES.suggestions;
this.generatedTitleSuggestions = data.suggestions;
} else {
this._updateSuggestedByAI(data);
}
})
.catch(popupAjaxError)
.finally(() => {
this.loading = false;
this._dEditorInput.classList.remove("loading");
});
}
@action
updateTopicTitle(title) {
const composer = this.args.outletArgs?.composer;
if (composer) {
composer.set("title", title);
this.closeContextMenu();
}
}
@action
viewChanges() {
this.showDiffModal = true;
}
@action
confirmChanges() {
this.menuState = this.CONTEXT_MENU_STATES.resets;
}
}
@@ -0,0 +1,8 @@
{{#if this.isAiBotChat}}
<DSection @bodyClass="ai-bot-chat" />
{{#if this.renderChatWarning}}
<div class="ai-bot-chat-warning">{{i18n
"discourse_ai.ai_bot.pm_warning"
}}</div>
{{/if}}
{{/if}}
@@ -0,0 +1,36 @@
import Component from "@glimmer/component";
import { inject as service } from "@ember/service";
import { computed } from "@ember/object";
export default class extends Component {
static shouldRender() {
return true;
}
@service currentUser;
@service siteSettings;
get composerModel() {
return this.args?.outletArgs?.composer;
}
get renderChatWarning() {
return this.siteSettings.ai_bot_enable_chat_warning;
}
@computed("composerModel.targetRecipients")
get isAiBotChat() {
if (
this.composerModel &&
this.composerModel.targetRecipients &&
this.currentUser.ai_enabled_chat_bots
) {
let reciepients = this.composerModel.targetRecipients.split(",");
return this.currentUser.ai_enabled_chat_bots.any((bot) =>
reciepients.any((username) => username === bot.username)
);
}
return false;
}
}
@@ -1,15 +0,0 @@
export default {
shouldRender(args) {
return (args.model.related_topics?.length || 0) > 0;
},
setupComponent(args, component) {
if (component.model.related_topics) {
component.set(
"relatedTopics",
component.model.related_topics.map((topic) =>
this.store.createRecord("topic", topic)
)
);
}
},
};
@@ -0,0 +1,15 @@
<div
id="related-topics"
class="more-topics__list {{if this.hidden 'hidden'}}"
role="complementary"
aria-labelledby="related-topics-title"
{{did-insert this.registerList}}
{{will-destroy this.removeList}}
>
<h3 id="related-topics-title" class="more-topics__list-title">
{{i18n "discourse_ai.related_topics.title"}}
</h3>
<div class="topics">
<BasicTopicList @topics={{this.relatedTopics}} />
</div>
</div>
@@ -0,0 +1,41 @@
import Component from "@glimmer/component";
import { inject as service } from "@ember/service";
import { action, computed } from "@ember/object";
import I18n from "I18n";
export default class extends Component {
static shouldRender(args) {
return (args.model.related_topics?.length || 0) > 0;
}
@service store;
@service site;
@service moreTopicsPreferenceTracking;
listId = "related-topics";
@computed("moreTopicsPreferenceTracking.selectedTab")
get hidden() {
return this.moreTopicsPreferenceTracking.selectedTab !== this.listId;
}
get relatedTopics() {
return this.args.outletArgs.model.related_topics.map((topic) =>
this.store.createRecord("topic", topic)
);
}
@action
registerList() {
this.moreTopicsPreferenceTracking.registerTopicList({
name: I18n.t("discourse_ai.related_topics.pill"),
id: this.listId,
icon: "magic",
});
}
@action
removeList() {
this.moreTopicsPreferenceTracking.removeTopicList(this.listId);
}
}
@@ -0,0 +1,23 @@
import Composer from "discourse/models/composer";
import I18n from "I18n";
export function composeAiBotMessage(targetBot, composer) {
const currentUser = composer.currentUser;
let botUsername = currentUser.ai_enabled_chat_bots.find(
(bot) => bot.model_name === targetBot
).username;
composer.focusComposer({
fallbackToNewTopic: true,
openOpts: {
action: Composer.PRIVATE_MESSAGE,
recipients: botUsername,
topicTitle: I18n.t("discourse_ai.ai_bot.default_pm_prefix"),
archetypeId: "private_message",
draftKey: Composer.NEW_PRIVATE_MESSAGE_KEY,
hasGroups: false,
warningsDisabled: true,
},
});
}
@@ -1,6 +0,0 @@
<div>
<h3 id="related-topics-title" class="related-topics-title">
{{i18n "discourse_ai.related_topics.title"}}
</h3>
<BasicTopicList @topics={{this.relatedTopics}} />
</div>
@@ -1,6 +0,0 @@
<AiSummary
@targetId={{this.targetId}}
@targetType={{this.targetType}}
@allowTimeframe={{this.allowTimeframe}}
@closeModal={{route-action "closeModal"}}
/>
@@ -0,0 +1,31 @@
import Widget from "discourse/widgets/widget";
import RenderGlimmer from "discourse/widgets/render-glimmer";
import { hbs } from "ember-cli-htmlbars";
import { action } from "@ember/object";
export default class AiBotHeaderPanelWrapper extends Widget {
buildAttributes() {
return { "data-click-outside": true };
}
html() {
return [
new RenderGlimmer(
this,
"div.widget-component-connector",
hbs`<AiBotHeaderPanel @closePanel={{@data.closePanel}} />`,
{ closePanel: this.closePanel }
),
];
}
@action
closePanel() {
this.sendWidgetAction("hideAiBotPanel");
}
@action
clickOutside() {
this.closePanel();
}
}
@@ -3,11 +3,60 @@ import { cookAsync } from "discourse/lib/text";
import { ajax } from "discourse/lib/ajax";
import { popupAjaxError } from "discourse/lib/ajax-error";
import loadScript from "discourse/lib/load-script";
import { composeAiBotMessage } from "discourse/plugins/discourse-ai/discourse/lib/ai-bot-helper";
function isGPTBot(user) {
return user && [-110, -111, -112].includes(user.id);
}
function attachHeaderIcon(api) {
const settings = api.container.lookup("service:site-settings");
const enabledBots = settings.ai_helper_add_ai_pm_to_header
? settings.ai_bot_enabled_chat_bots.split("|").filter(Boolean)
: [];
if (enabledBots.length > 0) {
api.attachWidgetAction("header", "showAiBotPanel", function () {
this.state.botSelectorVisible = true;
});
api.attachWidgetAction("header", "hideAiBotPanel", function () {
this.state.botSelectorVisible = false;
});
api.decorateWidget("header-icons:before", (helper) => {
return helper.attach("header-dropdown", {
title: "discourse_ai.ai_bot.shortcut_title",
icon: "robot",
action: "clickStartAiBotChat",
active: false,
classNames: ["ai-bot-button"],
});
});
if (enabledBots.length === 1) {
api.attachWidgetAction("header", "clickStartAiBotChat", function () {
composeAiBotMessage(
enabledBots[0],
api.container.lookup("service:composer")
);
});
} else {
api.attachWidgetAction("header", "clickStartAiBotChat", function () {
this.sendWidgetAction("showAiBotPanel");
});
}
api.addHeaderPanel(
"ai-bot-header-panel-wrapper",
"botSelectorVisible",
function () {
return {};
}
);
}
}
function initializeAIBotReplies(api) {
api.addPostMenuButton("cancel-gpt", (post) => {
if (isGPTBot(post.user)) {
@@ -94,10 +143,19 @@ export default {
initialize(container) {
const settings = container.lookup("service:site-settings");
const user = container.lookup("service:current-user");
const aiBotEnaled =
settings.discourse_ai_enabled && settings.ai_bot_enabled;
if (aiBotEnaled) {
const aiBotsAllowedGroups = settings.ai_bot_allowed_groups
.split("|")
.map((id) => parseInt(id, 10));
const canInteractWithAIBots = user?.groups.some((g) =>
aiBotsAllowedGroups.includes(g.id)
);
if (aiBotEnaled && canInteractWithAIBots) {
withPluginApi("1.6.0", attachHeaderIcon);
withPluginApi("1.6.0", initializeAIBotReplies);
}
},
@@ -1,43 +0,0 @@
import { withPluginApi } from "discourse/lib/plugin-api";
import showModal from "discourse/lib/show-modal";
import { action } from "@ember/object";
function initializeChatChannelSummary(api) {
const chat = api.container.lookup("service:chat");
if (chat) {
api.registerChatComposerButton?.({
translatedLabel: "discourse_ai.summarization.title",
id: "chat_channel_summary",
icon: "discourse-sparkles",
action: "showChannelSummary",
position: "dropdown",
});
api.modifyClass("component:chat-composer", {
pluginId: "discourse-ai",
@action
showChannelSummary() {
showModal("ai-summary").setProperties({
targetId: this.args.channel.id,
targetType: "chat_channel",
allowTimeframe: true,
});
},
});
}
}
export default {
name: "discourse-ai-chat-channel-summary",
initialize(container) {
const settings = container.lookup("service:site-settings");
const summarizationEnabled =
settings.discourse_ai_enabled && settings.ai_summarization_enabled;
if (summarizationEnabled) {
withPluginApi("1.6.0", initializeChatChannelSummary);
}
},
};
@@ -60,7 +60,7 @@ export default {
const allowedGroups = settings.ai_helper_allowed_groups
.split("|")
.map(parseInt);
.map((id) => parseInt(id, 10));
const canUseAssistant = user?.groups.some((g) =>
allowedGroups.includes(g.id)
);
@@ -0,0 +1,29 @@
import { withPluginApi } from "discourse/lib/plugin-api";
export default {
name: "discourse-ai-related-topics",
initialize(container) {
const settings = container.lookup("service:site-settings");
if (settings.ai_embeddings_semantic_related_topics_enabled) {
withPluginApi("1.1.0", (api) => {
api.modifyClass("model:post-stream", {
pluginId: "discourse-ai",
_setSuggestedTopics(result) {
this._super(...arguments);
if (!result.related_topics) {
return;
}
this.topic.setProperties({
related_topics: result.related_topics,
});
},
});
});
}
},
};
@@ -1,44 +0,0 @@
import { withPluginApi } from "discourse/lib/plugin-api";
import showModal from "discourse/lib/show-modal";
function initializeTopicSummary(api) {
api.modifyClass("component:scrolling-post-stream", {
pluginId: "discourse-ai",
showAiSummary() {
showModal("ai-summary").setProperties({
targetId: this.posts["posts"][0].topic_id,
targetType: "topic",
allowTimeframe: false,
});
},
});
api.addTopicSummaryCallback((html, attrs, widget) => {
html.push(
widget.attach("button", {
className: "btn btn-primary topic-ai-summarization",
icon: "magic",
title: "discourse_ai.summarization.title",
label: "discourse_ai.summarization.title",
action: "showAiSummary",
})
);
return html;
});
}
export default {
name: "discourse-ai-topic-summary",
initialize(container) {
const settings = container.lookup("service:site-settings");
const summarizationEnabled =
settings.discourse_ai_enabled && settings.ai_summarization_enabled;
if (summarizationEnabled) {
withPluginApi("1.6.0", initializeTopicSummary);
}
},
};
@@ -2,6 +2,40 @@ nav.post-controls .actions button.cancel-streaming {
display: none;
}
.ai-bot-chat #reply-control {
.title-and-category {
display: none;
}
}
.ai-bot-chat-warning {
color: var(--tertiary);
background-color: var(--tertiary-low);
border-top: 1px solid var(--tertiary-medium);
opacity: 0.75;
.d-icon {
color: var(--tertiary);
}
margin: 0;
padding: 4px 10px;
width: calc(100% - 20px);
}
article.streaming nav.post-controls .actions button.cancel-streaming {
display: inline-block;
}
.ai-bot-available-bot-options {
.ai-bot-available-bot-content {
color: var(--primary-high);
display: flex;
width: 100%;
.d-button-label {
flex: 1;
text-align: left;
}
&:hover {
background: var(--primary-low);
}
}
}
@@ -5,7 +5,8 @@
margin: 10px 0 10px 0;
}
.text-preview {
.text-preview,
.inline-diff {
ins {
background-color: var(--success-low);
text-decoration: underline;
@@ -20,6 +21,17 @@
}
}
&__old-value {
background-color: var(--danger-low);
color: var(--danger);
margin-bottom: 1rem;
}
&__new-value {
background-color: var(--success-low);
color: var(--success);
}
.selection-hint {
font-size: var(--font-down-2);
margin-bottom: 20px;
@@ -29,3 +41,155 @@
.topic-above-suggested-outlet.related-topics {
margin: 4.5em 0 1em;
}
.ai-helper-context-menu {
background: var(--secondary);
box-shadow: var(--shadow-dropdown);
padding: 0.25rem;
max-width: 25rem;
border: 1px solid var(--primary-low);
list-style: none;
z-index: 999;
ul {
margin: 0;
list-style: none;
}
ul:not(.ai-helper-context-menu__loading) li {
transition: background-color 0.25s ease;
&:hover {
background: var(--primary-low);
}
}
.d-button-label {
color: var(--primary-very-high);
}
&__options {
padding: 0.25rem;
}
&__loading {
.dot-falling {
margin-inline: 1rem;
margin-left: 1.5rem;
}
li {
display: flex;
padding: 0.5rem;
gap: 1rem;
justify-content: flex-start;
align-items: center;
}
}
&__resets {
display: flex;
align-items: center;
flex-flow: row wrap;
}
&__review {
display: flex;
align-items: center;
flex-flow: row wrap;
}
}
.d-editor-input.loading {
animation: loading-text 1.5s infinite linear;
}
@keyframes loading-text {
0% {
color: var(--primary);
}
50% {
color: var(--tertiary);
}
100% {
color: var(--primary);
}
}
// AI Typing indicator (taken from: https://github.com/nzbin/three-dots)
.dot-falling {
position: relative;
left: -9999px;
width: 10px;
height: 10px;
border-radius: 5px;
background-color: var(--tertiary);
color: var(--tertiary);
box-shadow: 9999px 0 0 0 var(--tertiary);
animation: dot-falling 1s infinite linear;
animation-delay: 0.1s;
}
.dot-falling::before,
.dot-falling::after {
content: "";
display: inline-block;
position: absolute;
top: 0;
}
.dot-falling::before {
width: 10px;
height: 10px;
border-radius: 5px;
background-color: var(--tertiary);
color: var(--tertiary);
animation: dot-falling-before 1s infinite linear;
animation-delay: 0s;
}
.dot-falling::after {
width: 10px;
height: 10px;
border-radius: 5px;
background-color: var(--tertiary);
color: var(--tertiary);
animation: dot-falling-after 1s infinite linear;
animation-delay: 0.2s;
}
@keyframes dot-falling {
0% {
box-shadow: 9999px -15px 0 0 rgba(152, 128, 255, 0);
}
25%,
50%,
75% {
box-shadow: 9999px 0 0 0 var(--tertiary);
}
100% {
box-shadow: 9999px 15px 0 0 rgba(152, 128, 255, 0);
}
}
@keyframes dot-falling-before {
0% {
box-shadow: 9984px -15px 0 0 rgba(152, 128, 255, 0);
}
25%,
50%,
75% {
box-shadow: 9984px 0 0 0 var(--tertiary);
}
100% {
box-shadow: 9984px 15px 0 0 rgba(152, 128, 255, 0);
}
}
@keyframes dot-falling-after {
0% {
box-shadow: 10014px -15px 0 0 rgba(152, 128, 255, 0);
}
25%,
50%,
75% {
box-shadow: 10014px 0 0 0 var(--tertiary);
}
100% {
box-shadow: 10014px 15px 0 0 rgba(152, 128, 255, 0);
}
}

Some files were not shown because too many files have changed in this diff Show More