Skip to content

A platform for community discussion. Free, open, simple.

FEATURE: add support for retrying a completion (#36450)

Sam245e782bf2a7
diff --git a/plugins/discourse-ai/app/controllers/discourse_ai/ai_bot/bot_controller.rb b/plugins/discourse-ai/app/controllers/discourse_ai/ai_bot/bot_controller.rb
index 1e300cb9bab..1584adcdd6e 100644
--- a/plugins/discourse-ai/app/controllers/discourse_ai/ai_bot/bot_controller.rb
+++ b/plugins/discourse-ai/app/controllers/discourse_ai/ai_bot/bot_controller.rb
@@ -40,12 +40,67 @@ module DiscourseAi
render json: {}, status: :ok
end
+ def retry_response
+ post = Post.find(params[:post_id])
+ guardian.ensure_can_see!(post)
+
+ if !DiscourseAi::AiBot::EntryPoint.all_bot_ids.include?(post.user_id)
+ raise Discourse::InvalidParameters.new(:post_id)
+ end
+
+ prompt_post = find_prompt_post(post)
+ raise Discourse::NotFound if prompt_post.blank?
+
+ guardian.ensure_can_see!(prompt_post)
+
+ persona_id = retry_persona_id(post, prompt_post)
+
+ Jobs.enqueue(
+ :create_ai_reply,
+ post_id: prompt_post.id,
+ bot_user_id: post.user_id,
+ persona_id: persona_id,
+ reply_post_id: post.id,
+ )
+
+ render json: success_json
+ end
+
def show_bot_username
bot_user = DiscourseAi::AiBot::EntryPoint.find_user_from_model(params[:username])
raise Discourse::InvalidParameters.new(:username) if !bot_user
render json: { bot_username: bot_user.username_lower }, status: :ok
end
+
+ private
+
+ def find_prompt_post(bot_reply_post)
+ bot_ids = DiscourseAi::AiBot::EntryPoint.all_bot_ids
+
+ bot_reply_post
+ .topic
+ .posts
+ .where("post_number < ?", bot_reply_post.post_number)
+ .where.not(user_id: bot_ids)
+ .reorder(post_number: :desc)
+ .first
+ end
+
+ def retry_persona_id(bot_reply_post, prompt_post)
+ persona_id =
+ bot_reply_post.custom_fields[DiscourseAi::AiBot::POST_AI_PERSONA_ID_FIELD].presence
+
+ persona_id ||= prompt_post.topic.custom_fields["ai_persona_id"].presence
+
+ if persona_id.blank?
+ persona_name = prompt_post.topic.custom_fields["ai_persona"].presence
+ persona_id = AiPersona.find_by(name: persona_name)&.id if persona_name.present?
+ end
+
+ persona_id ||= DiscourseAi::Personas::General.id
+ persona_id.to_i
+ end
end
end
end
diff --git a/plugins/discourse-ai/app/jobs/regular/create_ai_reply.rb b/plugins/discourse-ai/app/jobs/regular/create_ai_reply.rb
index 8d32796183a..c505e32a9cf 100644
--- a/plugins/discourse-ai/app/jobs/regular/create_ai_reply.rb
+++ b/plugins/discourse-ai/app/jobs/regular/create_ai_reply.rb
@@ -7,6 +7,9 @@ module Jobs
def execute(args)
return unless bot_user = User.find_by(id: args[:bot_user_id])
return unless post = Post.includes(:topic).find_by(id: args[:post_id])
+ reply_post = Post.find_by(id: args[:reply_post_id]) if args[:reply_post_id].present?
+ return if args[:reply_post_id].present? && reply_post.nil?
+ return if reply_post && reply_post.topic_id != post.topic_id
persona_id = args[:persona_id]
begin
@@ -15,7 +18,11 @@ module Jobs
bot = DiscourseAi::Personas::Bot.as(bot_user, persona: persona.new)
- DiscourseAi::AiBot::Playground.new(bot).reply_to(post, feature_name: "bot")
+ DiscourseAi::AiBot::Playground.new(bot).reply_to(
+ post,
+ feature_name: "bot",
+ existing_reply_post: reply_post,
+ )
rescue DiscourseAi::Personas::Bot::BOT_NOT_FOUND
Rails.logger.warn(
"Bot not found for post #{post.id} - perhaps persona was deleted or bot was disabled",
diff --git a/plugins/discourse-ai/assets/javascripts/discourse/components/post-menu/ai-retry-streaming-button.gjs b/plugins/discourse-ai/assets/javascripts/discourse/components/post-menu/ai-retry-streaming-button.gjs
new file mode 100644
index 00000000000..21f64e3d411
--- /dev/null
+++ b/plugins/discourse-ai/assets/javascripts/discourse/components/post-menu/ai-retry-streaming-button.gjs
@@ -0,0 +1,54 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { action } from "@ember/object";
+import DButton from "discourse/components/d-button";
+import { ajax } from "discourse/lib/ajax";
+import { popupAjaxError } from "discourse/lib/ajax-error";
+
+/**
+ * @component AiRetryStreamingButton
+ * @argument post
+ */
+export default class AiRetryStreamingButton extends Component {
+ /**
+ * Tracks whether a retry request is currently in-flight.
+ *
+ * @type {boolean}
+ */
+ @tracked retrying = false;
+
+ /**
+ * Sends a request to retry streaming the current AI response.
+ *
+ * @returns {Promise<void>}
+ */
+ @action
+ async retry() {
+ if (this.retrying) {
+ return;
+ }
+
+ this.retrying = true;
+
+ try {
+ await ajax(`/discourse-ai/ai-bot/post/${this.args.post.id}/retry`, {
+ type: "POST",
+ });
+ } catch (e) {
+ popupAjaxError(e);
+ } finally {
+ this.retrying = false;
+ }
+ }
+
+ <template>
+ <DButton
+ class="post-action-menu__ai-retry-streaming ai-retry-streaming"
+ ...attributes
+ @action={{this.retry}}
+ @icon={{if this.retrying "spinner" "arrow-rotate-right"}}
+ @title="discourse_ai.ai_bot.try_again"
+ @disabled={{this.retrying}}
+ />
+ </template>
+}
diff --git a/plugins/discourse-ai/assets/javascripts/discourse/components/post/meta-data/ai-cancel-streaming.gjs b/plugins/discourse-ai/assets/javascripts/discourse/components/post/meta-data/ai-cancel-streaming.gjs
new file mode 100644
index 00000000000..117f24e4470
--- /dev/null
+++ b/plugins/discourse-ai/assets/javascripts/discourse/components/post/meta-data/ai-cancel-streaming.gjs
@@ -0,0 +1,39 @@
+import Component from "@glimmer/component";
+import { action } from "@ember/object";
+import DButton from "discourse/components/d-button";
+import { ajax } from "discourse/lib/ajax";
+import { popupAjaxError } from "discourse/lib/ajax-error";
+
+/**
+ * @component AiCancelStreaming
+ * @argument post
+ */
+export default class AiCancelStreaming extends Component {
+ @action
+ async cancelStreaming() {
+ const post = this.args.post;
+
+ try {
+ await ajax(`/discourse-ai/ai-bot/post/${post.id}/stop-streaming`, {
+ type: "POST",
+ });
+
+ document
+ .querySelector(`#post_${post.post_number}`)
+ .classList.remove("streaming");
+ } catch (e) {
+ popupAjaxError(e);
+ }
+ }
+
+ <template>
+ <div class="post-info ai-cancel-streaming-container">
+ <DButton
+ class="btn-transparent ai-cancel-streaming"
+ @action={{this.cancelStreaming}}
+ @icon="pause"
+ @label="discourse_ai.ai_bot.cancel_streaming"
+ />
+ </div>
+ </template>
+}
diff --git a/plugins/discourse-ai/assets/javascripts/discourse/initializers/ai-bot-replies.js b/plugins/discourse-ai/assets/javascripts/discourse/initializers/ai-bot-replies.js
index 1cc085046d1..53c589704ef 100644
--- a/plugins/discourse-ai/assets/javascripts/discourse/initializers/ai-bot-replies.js
+++ b/plugins/discourse-ai/assets/javascripts/discourse/initializers/ai-bot-replies.js
@@ -1,8 +1,10 @@
import { withPluginApi } from "discourse/lib/plugin-api";
import AiBotHeaderIcon from "../components/ai-bot-header-icon";
import AiPersonaFlair from "../components/post/ai-persona-flair";
+import AiCancelStreaming from "../components/post/meta-data/ai-cancel-streaming";
import AiCancelStreamingButton from "../components/post-menu/ai-cancel-streaming-button";
import AiDebugButton from "../components/post-menu/ai-debug-button";
+import AiRetryStreamingButton from "../components/post-menu/ai-retry-streaming-button";
import AiShareButton from "../components/post-menu/ai-share-button";
import { isGPTBot, showShareConversationModal } from "../lib/ai-bot-helper";
import {
@@ -56,6 +58,7 @@ function initializePersonaDecorator(api) {
}
function initializePauseButton(api) {
+ // Add cancel streaming button to post-menu (bottom of post) - hidden by CSS, kept for compatibility
api.registerValueTransformer(
"post-menu-buttons",
({ value: dag, context: { post, firstButtonKey } }) => {
@@ -67,6 +70,32 @@ function initializePauseButton(api) {
}
}
);
+
+ // Add cancel streaming to post-infos (top of post, where date is shown)
+ api.registerValueTransformer(
+ "post-meta-data-infos",
+ ({ value: dag, context: { post, metaDataInfoKeys } }) => {
+ if (isGPTBot(post.user)) {
+ dag.add("ai-cancel-streaming", AiCancelStreaming, {
+ before: metaDataInfoKeys.DATE,
+ });
+ }
+ }
+ );
+}
+
+function initializeRetryButton(api) {
+ api.registerValueTransformer(
+ "post-menu-buttons",
+ ({ value: dag, context: { post, firstButtonKey } }) => {
+ if (isGPTBot(post.user)) {
+ dag.add("ai-retry", AiRetryStreamingButton, {
+ before: firstButtonKey,
+ after: ["ai-cancel-gpt", "ai-share", "ai-debug"],
+ });
+ }
+ }
+ );
}
function initializeDebugButton(api) {
@@ -145,6 +174,7 @@ export default {
initializeDebugButton(api, container);
initializeShareButton(api, container);
initializeShareTopicButton(api, container);
+ initializeRetryButton(api);
});
}
},
diff --git a/plugins/discourse-ai/assets/stylesheets/modules/ai-bot/common/bot-replies.scss b/plugins/discourse-ai/assets/stylesheets/modules/ai-bot/common/bot-replies.scss
index 05d19dec7c7..f45d603a1eb 100644
--- a/plugins/discourse-ai/assets/stylesheets/modules/ai-bot/common/bot-replies.scss
+++ b/plugins/discourse-ai/assets/stylesheets/modules/ai-bot/common/bot-replies.scss
@@ -1,7 +1,43 @@
+@use "lib/viewport";
+
nav.post-controls .actions button.cancel-streaming {
display: none;
}
+.ai-cancel-streaming-container {
+ display: none;
+ opacity: 0;
+ transition: opacity 0.2s ease-out;
+}
+
+.post-info.post-date {
+ opacity: 1;
+ transition: opacity 0.2s ease-out;
+}
+
+article.streaming {
+ .post-info.post-date {
+ opacity: 0;
+ position: absolute;
+ pointer-events: none;
+ }
+
+ .ai-cancel-streaming-container {
+ display: flex;
+ opacity: 1;
+ }
+
+ nav.post-controls .actions button.ai-retry-streaming {
+ display: none;
+ }
+
+ @include viewport.until(sm) {
+ .persona-flair {
+ display: none;
+ }
+ }
+}
+
.ai-bot-pm {
.gpt-persona {
margin-bottom: 5px;
@@ -29,10 +65,6 @@ nav.post-controls .actions button.cancel-streaming {
width: calc(100% - 20px);
}
-article.streaming nav.post-controls .actions button.cancel-streaming {
- display: inline-block;
-}
-
.ai-bot-available-bot-options {
padding: 0.5em;
@@ -57,6 +89,11 @@ article.streaming nav.post-controls .actions button.cancel-streaming {
.topic-body .persona-flair {
order: 2;
font-size: var(--font-down-1);
+ transform: translateY(0.04em);
+
+ @include viewport.until(sm) {
+ transform: translateY(0.1em);
+ }
}
details.ai-quote {
diff --git a/plugins/discourse-ai/config/locales/client.en.yml b/plugins/discourse-ai/config/locales/client.en.yml
index d67544728fb..6f2c29f5c7a 100644
--- a/plugins/discourse-ai/config/locales/client.en.yml
+++ b/plugins/discourse-ai/config/locales/client.en.yml
@@ -926,6 +926,7 @@ en:
llm: "Model"
pm_warning: "AI chatbot messages are monitored regularly by moderators."
cancel_streaming: "Stop reply"
+ try_again: "Try again"
default_pm_prefix: "[Untitled AI bot PM]"
shortcut_title: "Start a PM with an AI bot"
shortcut_link: "AI bot"
diff --git a/plugins/discourse-ai/config/routes.rb b/plugins/discourse-ai/config/routes.rb
index bcd9376ee35..6221796bc52 100644
--- a/plugins/discourse-ai/config/routes.rb
+++ b/plugins/discourse-ai/config/routes.rb
@@ -28,6 +28,7 @@ DiscourseAi::Engine.routes.draw do
get "post/:post_id/show-debug-info" => "bot#show_debug_info"
get "show-debug-info/:id" => "bot#show_debug_info_by_id"
post "post/:post_id/stop-streaming" => "bot#stop_streaming_response"
+ post "post/:post_id/retry" => "bot#retry_response"
end
scope module: :discover, path: "/discoveries", defaults: { format: :json } do
diff --git a/plugins/discourse-ai/lib/ai_bot.rb b/plugins/discourse-ai/lib/ai_bot.rb
index 999f646ef3a..562c2aa3690 100644
--- a/plugins/discourse-ai/lib/ai_bot.rb
+++ b/plugins/discourse-ai/lib/ai_bot.rb
@@ -5,5 +5,6 @@ module DiscourseAi
USER_AGENT = "Discourse AI Bot 1.0 (https://www.discourse.org)"
TOPIC_AI_BOT_PM_FIELD = "is_ai_bot_pm"
POST_AI_LLM_NAME_FIELD = "ai_llm_name"
+ POST_AI_PERSONA_ID_FIELD = "ai_persona_id"
end
end
diff --git a/plugins/discourse-ai/lib/ai_bot/playground.rb b/plugins/discourse-ai/lib/ai_bot/playground.rb
index f12ba66458c..f6ce8c26388 100644
--- a/plugins/discourse-ai/lib/ai_bot/playground.rb
+++ b/plugins/discourse-ai/lib/ai_bot/playground.rb
@@ -388,6 +388,7 @@ module DiscourseAi
auto_set_title: true,
silent_mode: false,
feature_name: nil,
+ existing_reply_post: nil,
cancel_manager: nil,
&blk
)
@@ -459,21 +460,44 @@ module DiscourseAi
end
if stream_reply
- reply_post =
- PostCreator.create!(
- reply_user,
- topic_id: post.topic_id,
- raw: "",
- skip_validations: true,
- skip_jobs: true,
- post_type: post_type,
- skip_guardian: true,
- custom_fields: {
- DiscourseAi::AiBot::POST_AI_LLM_NAME_FIELD => bot.llm.llm_model.display_name,
- },
- )
+ reply_post = existing_reply_post
- publish_update(reply_post, { raw: reply_post.cooked })
+ if reply_post
+ if reply_post.topic_id != post.topic_id
+ raise Discourse::InvalidParameters.new(:reply_post_id)
+ end
+
+ if reply_post.user_id != reply_user.id
+ raise Discourse::InvalidParameters.new(:reply_post_id)
+ end
+
+ reply_post.update_columns(raw: "", cooked: "")
+ reply_post.post_custom_prompt&.destroy
+ else
+ reply_post =
+ PostCreator.create!(
+ reply_user,
+ topic_id: post.topic_id,
+ raw: "",
+ skip_validations: true,
+ skip_jobs: true,
+ post_type: post_type,
+ skip_guardian: true,
+ custom_fields: {
+ DiscourseAi::AiBot::POST_AI_LLM_NAME_FIELD => bot.llm.llm_model.display_name,
+ DiscourseAi::AiBot::POST_AI_PERSONA_ID_FIELD => bot.persona.id,
+ },
+ )
+ end
+
+ reply_post.custom_fields[DiscourseAi::AiBot::POST_AI_LLM_NAME_FIELD] = bot
+ .llm
+ .llm_model
+ .display_name
+ reply_post.custom_fields[DiscourseAi::AiBot::POST_AI_PERSONA_ID_FIELD] = bot.persona.id
+ reply_post.save_custom_fields
+
+ publish_update(reply_post, { raw: "" })
redis_stream_key = "gpt_cancel:#{reply_post.id}"
Discourse.redis.setex(redis_stream_key, MAX_STREAM_DELAY_SECONDS, 1)
@@ -551,6 +575,10 @@ module DiscourseAi
skip_validations: true,
post_type: post_type,
skip_guardian: true,
+ custom_fields: {
+ DiscourseAi::AiBot::POST_AI_LLM_NAME_FIELD => bot.llm.llm_model.display_name,
+ DiscourseAi::AiBot::POST_AI_PERSONA_ID_FIELD => bot.persona.id,
+ },
)
end
diff --git a/plugins/discourse-ai/spec/requests/ai_bot/bot_controller_spec.rb b/plugins/discourse-ai/spec/requests/ai_bot/bot_controller_spec.rb
index 47d3d45aaa0..4a9421fca77 100644
--- a/plugins/discourse-ai/spec/requests/ai_bot/bot_controller_spec.rb
+++ b/plugins/discourse-ai/spec/requests/ai_bot/bot_controller_spec.rb
@@ -106,6 +106,82 @@ RSpec.describe DiscourseAi::AiBot::BotController do
end
end
+ describe "#retry_response" do
+ fab!(:bot_user, :user)
+ let!(:llm_model) { Fabricate(:llm_model, user: bot_user, enabled_chat_bot: true) }
+ let!(:ai_persona) do
+ Fabricate(
+ :ai_persona,
+ user: bot_user,
+ default_llm_id: llm_model.id,
+ allowed_group_ids: [Group::AUTO_GROUPS[:trust_level_0]],
+ )
+ end
+ let(:persona) { ai_persona.class_instance.new }
+ let(:bot) { DiscourseAi::Personas::Bot.as(bot_user, persona: persona) }
+
+ let!(:prompt_post) do
+ Fabricate(:post, topic: pm_topic, user: user, raw: "Hello @#{bot_user.username}")
+ end
+
+ let!(:reply_post) do
+ DiscourseAi::Completions::Llm.with_prepared_responses(["first try"]) do
+ DiscourseAi::AiBot::Playground.new(bot).reply_to(prompt_post)
+ end
+
+ pm_topic.reload.posts.last
+ end
+
+ before do
+ Group.refresh_automatic_groups!
+ SiteSetting.ai_bot_enabled = true
+ AiPersona.persona_cache.flush!
+
+ tl0_group =
+ Group.find_by(name: "trust_level_0") || Group.find(Group::AUTO_GROUPS[:trust_level_0])
+ GroupUser.find_or_create_by!(user: user, group: tl0_group)
+ user.reload
+
+ pm_topic.topic_allowed_users.find_or_create_by!(user: user)
+
+ unless pm_topic.topic_allowed_users.exists?(user: bot_user)
+ pm_topic.topic_allowed_users.create!(user: bot_user)
+ end
+ end
+
+ it "streams a replacement into the existing bot reply" do
+ retry_text = "second attempt"
+
+ DiscourseAi::Completions::Llm.with_prepared_responses([retry_text]) do
+ post "/discourse-ai/ai-bot/post/#{reply_post.id}/retry"
+
+ Jobs::CreateAiReply.new.execute(
+ post_id: prompt_post.id,
+ bot_user_id: bot_user.id,
+ persona_id: reply_post.custom_fields[DiscourseAi::AiBot::POST_AI_PERSONA_ID_FIELD].to_i,
+ reply_post_id: reply_post.id,
+ )
+ end
+
+ expect(response.status).to eq(200)
+ expect(reply_post.reload.raw).to eq(retry_text)
+ expect(reply_post.custom_fields[DiscourseAi::AiBot::POST_AI_PERSONA_ID_FIELD].to_i).to eq(
+ persona.id,
+ )
+ end
+
+ it "returns a 404 when there is no previous non-bot prompt" do
+ lone_topic = Fabricate(:private_message_topic)
+ lone_topic.topic_allowed_users.create!(user: user)
+ lone_topic.topic_allowed_users.create!(user: bot_user)
+ bot_only_post = Fabricate(:post, topic: lone_topic, user: bot_user)
+
+ post "/discourse-ai/ai-bot/post/#{bot_only_post.id}/retry"
+
+ expect(response.status).to eq(404)
+ end
+ end
+
describe "#show_bot_username" do
it "returns the username_lower of the selected bot" do
gpt_35_bot = Fabricate(:llm_model, name: "gpt-3.5-turbo")