Skip to content

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

FEATURE: add custom tools and resume support for stream replies (#37912)

Sam479686ced397
diff --git a/lib/discourse_redis.rb b/lib/discourse_redis.rb
index dbd644b4ae0..bb28b7a94f4 100644
--- a/lib/discourse_redis.rb
+++ b/lib/discourse_redis.rb
@@ -53,6 +53,7 @@ class DiscourseRedis
expireat
get
getbit
+ getdel
getrange
getset
hdel
diff --git a/plugins/discourse-ai/app/controllers/discourse_ai/admin/ai_personas_controller.rb b/plugins/discourse-ai/app/controllers/discourse_ai/admin/ai_personas_controller.rb
index 119e57f8d42..9f74e20d0b9 100644
--- a/plugins/discourse-ai/app/controllers/discourse_ai/admin/ai_personas_controller.rb
+++ b/plugins/discourse-ai/app/controllers/discourse_ai/admin/ai_personas_controller.rb
@@ -140,6 +140,45 @@ module DiscourseAi
end
def stream_reply
+ custom_tools = nil
+ tool_results = nil
+ resume_token = params[:resume_token].to_s
+
+ begin
+ custom_tools = stream_reply_custom_tools
+ tool_results = stream_reply_tool_results
+ rescue ArgumentError => e
+ return render_json_error e.message
+ end
+
+ if resume_token.present?
+ # This is a best-effort fast-fail check. The token can still expire between this
+ # check and async execution, which is handled again inside the session loader.
+ if !DiscourseAi::AiBot::StreamReplyCustomToolsSession.resume_state_exists?(resume_token)
+ return render_json_error(I18n.t("discourse_ai.errors.invalid_stream_resume_token"))
+ end
+
+ if tool_results.blank?
+ return render_json_error(I18n.t("discourse_ai.errors.no_tool_results_specified"))
+ end
+
+ hijack = request.env["rack.hijack"]
+ io = hijack.call
+
+ DiscourseAi::AiBot::ResponseHttpStreamer.queue_streamed_reply(
+ io: io,
+ persona: nil,
+ user: nil,
+ topic: nil,
+ query: "",
+ custom_instructions: "",
+ current_user: current_user,
+ resume_token: resume_token,
+ tool_results: tool_results,
+ )
+ return
+ end
+
persona =
AiPersona.find_by(name: params[:persona_name]) ||
AiPersona.find_by(id: params[:persona_id])
@@ -196,12 +235,17 @@ module DiscourseAi
query: params[:query].to_s,
custom_instructions: params[:custom_instructions].to_s,
current_user: current_user,
+ custom_tools: custom_tools,
)
end
private
AI_STREAM_CONVERSATION_UNIQUE_ID = "ai-stream-conversation-unique-id"
+ MAX_STREAM_REPLY_CUSTOM_TOOLS = 20
+ MAX_STREAM_REPLY_TOOL_RESULTS = 20
+ MAX_STREAM_REPLY_CUSTOM_TOOL_DEFINITION_BYTES = 10_000
+ MAX_STREAM_REPLY_TOOL_RESULT_CONTENT_BYTES = 100 * 1024
def stage_user
unique_id = params[:user_unique_id].to_s
@@ -226,6 +270,134 @@ module DiscourseAi
end
end
+ def stream_reply_custom_tools
+ return [] if !params.key?(:custom_tools)
+
+ raw_tools = params[:custom_tools]
+ return [] if raw_tools.blank?
+
+ if !raw_tools.is_a?(Array)
+ raise ArgumentError,
+ I18n.t(
+ "discourse_ai.errors.invalid_custom_tools",
+ details: I18n.t("discourse_ai.errors.expected_array"),
+ )
+ end
+
+ if raw_tools.size > MAX_STREAM_REPLY_CUSTOM_TOOLS
+ raise ArgumentError,
+ I18n.t(
+ "discourse_ai.errors.too_many_custom_tools",
+ max: MAX_STREAM_REPLY_CUSTOM_TOOLS,
+ )
+ end
+
+ parsed =
+ raw_tools.map do |tool|
+ hash = normalize_hash_param(tool, key: :custom_tools)
+ parameters = hash["parameters"]
+ hash["parameters"] = parameters.reject(&:blank?) if parameters.is_a?(Array)
+ definition = nil
+ begin
+ definition =
+ DiscourseAi::Completions::ToolDefinition.from_hash(hash.deep_symbolize_keys)
+ rescue ArgumentError, NoMethodError => e
+ raise ArgumentError,
+ I18n.t("discourse_ai.errors.invalid_custom_tools", details: e.message)
+ end
+ definition_hash = definition.to_h.stringify_keys
+ if definition_hash.to_json.bytesize > MAX_STREAM_REPLY_CUSTOM_TOOL_DEFINITION_BYTES
+ raise ArgumentError,
+ I18n.t(
+ "discourse_ai.errors.custom_tool_definition_too_large",
+ max: MAX_STREAM_REPLY_CUSTOM_TOOL_DEFINITION_BYTES,
+ )
+ end
+ definition_hash
+ end
+
+ names = parsed.map { |tool| tool["name"] }
+ duplicate_names = names.tally.select { |_, count| count > 1 }.keys
+ if duplicate_names.present?
+ raise ArgumentError,
+ I18n.t(
+ "discourse_ai.errors.duplicate_custom_tools",
+ names: duplicate_names.join(", "),
+ )
+ end
+
+ parsed
+ end
+
+ def stream_reply_tool_results
+ if params.key?(:tool_results) && params.key?(:tool_result)
+ raise ArgumentError, I18n.t("discourse_ai.errors.ambiguous_tool_results")
+ end
+
+ raw_results = params.key?(:tool_results) ? params[:tool_results] : params[:tool_result]
+ return [] if raw_results.blank?
+
+ raw_results = [raw_results] if !raw_results.is_a?(Array)
+
+ if raw_results.size > MAX_STREAM_REPLY_TOOL_RESULTS
+ raise ArgumentError,
+ I18n.t(
+ "discourse_ai.errors.too_many_tool_results",
+ max: MAX_STREAM_REPLY_TOOL_RESULTS,
+ )
+ end
+
+ raw_results.map do |tool_result|
+ hash = normalize_hash_param(tool_result, key: :tool_results)
+ id = hash["tool_call_id"].presence || hash["id"].presence
+ if id.blank?
+ raise ArgumentError,
+ I18n.t("discourse_ai.errors.invalid_tool_results", details: "tool_call_id")
+ end
+
+ if !hash.key?("content")
+ raise ArgumentError,
+ I18n.t("discourse_ai.errors.invalid_tool_results", details: "content")
+ end
+
+ content = hash["content"]
+ if content.nil?
+ raise ArgumentError,
+ I18n.t("discourse_ai.errors.invalid_tool_results", details: "content")
+ end
+ content_bytesize = content.is_a?(String) ? content.bytesize : content.to_json.bytesize
+
+ if content_bytesize > MAX_STREAM_REPLY_TOOL_RESULT_CONTENT_BYTES
+ raise ArgumentError,
+ I18n.t(
+ "discourse_ai.errors.tool_result_content_too_large",
+ max: MAX_STREAM_REPLY_TOOL_RESULT_CONTENT_BYTES,
+ )
+ end
+
+ { "tool_call_id" => id.to_s, "content" => content }
+ rescue JSON::GeneratorError
+ raise ArgumentError,
+ I18n.t("discourse_ai.errors.invalid_tool_results", details: "content")
+ end
+ end
+
+ def normalize_hash_param(raw, key:)
+ hash = raw
+ hash = hash.to_unsafe_h if hash.is_a?(ActionController::Parameters)
+
+ if !hash.is_a?(Hash)
+ raise ArgumentError,
+ I18n.t(
+ "discourse_ai.errors.invalid_stream_param",
+ key: key,
+ details: I18n.t("discourse_ai.errors.expected_object"),
+ )
+ end
+
+ hash.stringify_keys
+ end
+
def find_ai_persona
@ai_persona = AiPersona.find(params[:id])
end
diff --git a/plugins/discourse-ai/config/locales/server.en.yml b/plugins/discourse-ai/config/locales/server.en.yml
index e0151f9fe2a..f145d67123e 100644
--- a/plugins/discourse-ai/config/locales/server.en.yml
+++ b/plugins/discourse-ai/config/locales/server.en.yml
@@ -708,6 +708,26 @@ en:
persona_disabled: The persona specified is disabled. Check the persona_name or persona_id params.
no_default_llm: The persona must have a default_llm defined.
user_not_allowed: The user is not allowed to participate in the topic.
+ invalid_stream_resume_token: The resume_token is invalid or has expired.
+ no_tool_results_specified: The tool_results parameter is required when resuming a stream.
+ invalid_custom_tools: "The custom_tools parameter is invalid: %{details}"
+ duplicate_custom_tools: "The custom_tools parameter contains duplicate tool names: %{names}"
+ too_many_custom_tools: "The custom_tools parameter can include at most %{max} tools."
+ custom_tool_definition_too_large: "Each custom tool definition must be at most %{max} bytes."
+ invalid_stream_param: "The %{key} parameter is invalid: %{details}"
+ expected_array: "expected an array"
+ expected_object: "expected an object"
+ ambiguous_tool_results: "Specify either tool_results or tool_result, not both."
+ invalid_tool_results: "The tool_results parameter is invalid: %{details}"
+ too_many_tool_results: "The tool_results parameter can include at most %{max} items."
+ no_pending_tool_calls: There are no pending tool calls for this resume token.
+ missing_tool_results: "Missing tool results for tool_call_id(s): %{ids}"
+ unexpected_tool_results: "Unexpected tool results for tool_call_id(s): %{ids}"
+ invalid_tool_result_content: "The tool result for %{id} must include content"
+ tool_result_content_too_large: "Each tool result content payload must be at most %{max} bytes."
+ stream_reply_max_resume_rounds_reached: Reached maximum custom tool resume rounds (%{max}).
+ stream_reply_state_too_large: "The stream state is too large to persist (max %{max} bytes)."
+ stream_reply_unexpected_error: An unexpected error occurred while streaming the reply.
prompt_message_length: The message %{idx} is over the 1000 character limit.
persona_already_exists: Persona with the name %{name} already exists.
custom_tool_exists:
diff --git a/plugins/discourse-ai/lib/ai_bot/response_http_streamer.rb b/plugins/discourse-ai/lib/ai_bot/response_http_streamer.rb
index 565484bec5f..c682e770f3d 100644
--- a/plugins/discourse-ai/lib/ai_bot/response_http_streamer.rb
+++ b/plugins/discourse-ai/lib/ai_bot/response_http_streamer.rb
@@ -36,84 +36,37 @@ module DiscourseAi
topic:,
query:,
custom_instructions:,
- current_user:
+ current_user:,
+ custom_tools: nil,
+ resume_token: nil,
+ tool_results: nil
)
schedule_block do
begin
- post_params = {
- raw: query,
- skip_validations: true,
- custom_fields: {
- DiscourseAi::AiBot::Playground::BYPASS_AI_REPLY_CUSTOM_FIELD => true,
- },
- }
-
- if topic
- post_params[:topic_id] = topic.id
+ if custom_tools.present? || resume_token.present?
+ stream_custom_tool_reply(
+ io: io,
+ persona: persona,
+ user: user,
+ topic: topic,
+ query: query,
+ custom_instructions: custom_instructions,
+ current_user: current_user,
+ custom_tools: custom_tools,
+ resume_token: resume_token,
+ tool_results: tool_results,
+ )
else
- post_params[:title] = I18n.t("discourse_ai.ai_bot.default_pm_prefix")
- post_params[:archetype] = Archetype.private_message
- post_params[:target_usernames] = "#{user.username},#{persona.user.username}"
+ stream_standard_reply(
+ io: io,
+ persona: persona,
+ user: user,
+ topic: topic,
+ query: query,
+ custom_instructions: custom_instructions,
+ current_user: current_user,
+ )
end
-
- post = PostCreator.create!(user, post_params)
- topic = post.topic
-
- io.write "HTTP/1.1 200 OK"
- io.write CRLF
- io.write "Content-Type: text/plain; charset=utf-8"
- io.write CRLF
- io.write "Transfer-Encoding: chunked"
- io.write CRLF
- io.write "Cache-Control: no-cache, no-store, must-revalidate"
- io.write CRLF
- io.write "Connection: close"
- io.write CRLF
- io.write "X-Accel-Buffering: no"
- io.write CRLF
- io.write "X-Content-Type-Options: nosniff"
- io.write CRLF
- io.write CRLF
- io.flush
-
- persona_class =
- DiscourseAi::Personas::Persona.find_by(id: persona.id, user: current_user)
- bot = DiscourseAi::Personas::Bot.as(persona.user, persona: persona_class.new)
-
- data =
- {
- topic_id: topic.id,
- bot_user_id: persona.user.id,
- persona_id: persona.id,
- }.to_json + "\n\n"
-
- io.write data.bytesize.to_s(16)
- io.write CRLF
- io.write data
- io.write CRLF
-
- DiscourseAi::AiBot::Playground
- .new(bot)
- .reply_to(post, custom_instructions: custom_instructions) do |partial|
- next if partial.length == 0
-
- data = { partial: partial }.to_json + "\n\n"
-
- data.force_encoding("UTF-8")
-
- io.write data.bytesize.to_s(16)
- io.write CRLF
- io.write data
- io.write CRLF
- io.flush
- end
-
- io.write "0"
- io.write CRLF
- io.write CRLF
-
- io.flush
- io.done if io.respond_to?(:done)
rescue StandardError => e
# make it a tiny bit easier to debug in dev, this is tricky
# multi-threaded code that exhibits various limitations in rails
@@ -124,6 +77,156 @@ module DiscourseAi
end
end
end
+
+ def stream_standard_reply(
+ io:,
+ persona:,
+ user:,
+ topic:,
+ query:,
+ custom_instructions:,
+ current_user:
+ )
+ post_params = {
+ raw: query,
+ skip_validations: true,
+ custom_fields: {
+ DiscourseAi::AiBot::Playground::BYPASS_AI_REPLY_CUSTOM_FIELD => true,
+ },
+ }
+
+ if topic
+ post_params[:topic_id] = topic.id
+ else
+ post_params[:title] = I18n.t("discourse_ai.ai_bot.default_pm_prefix")
+ post_params[:archetype] = Archetype.private_message
+ post_params[:target_usernames] = "#{user.username},#{persona.user.username}"
+ end
+
+ post = PostCreator.create!(user, post_params)
+ topic = post.topic
+
+ write_headers(io)
+
+ persona_class = DiscourseAi::Personas::Persona.find_by(id: persona.id, user: current_user)
+ bot = DiscourseAi::Personas::Bot.as(persona.user, persona: persona_class.new)
+
+ write_chunk(
+ io,
+ { topic_id: topic.id, bot_user_id: persona.user.id, persona_id: persona.id },
+ )
+
+ DiscourseAi::AiBot::Playground
+ .new(bot)
+ .reply_to(post, custom_instructions: custom_instructions) do |partial|
+ next if partial.empty?
+
+ write_chunk(io, { partial: partial })
+ end
+
+ finish_chunks(io)
+ end
+
+ def stream_custom_tool_reply(
+ io:,
+ persona:,
+ user:,
+ topic:,
+ query:,
+ custom_instructions:,
+ current_user:,
+ custom_tools:,
+ resume_token:,
+ tool_results:
+ )
+ # Custom-tool streams always report errors in-band using error events once headers
+ # have been emitted.
+ write_headers(io)
+
+ session =
+ DiscourseAi::AiBot::StreamReplyCustomToolsSession.new(
+ persona: persona,
+ user: user,
+ topic: topic,
+ query: query,
+ custom_instructions: custom_instructions,
+ current_user: current_user,
+ custom_tools: custom_tools,
+ resume_token: resume_token,
+ tool_results: tool_results,
+ )
+
+ session.run do |event_type, payload|
+ if event_type == :partial
+ write_chunk(io, { partial: payload })
+ else
+ write_chunk(io, payload)
+ end
+ end
+
+ finish_chunks(io)
+ rescue DiscourseAi::AiBot::StreamReplyCustomToolsSession::ProtocolError => e
+ Discourse.warn_exception(
+ e,
+ message: "Discourse AI: Stream reply custom tool protocol error",
+ )
+ write_chunk(io, { event: "error", error: e.message })
+ finish_chunks(io)
+ rescue StandardError => e
+ # Headers were already sent. Emit an error frame and chunk terminator so clients can
+ # safely parse this as a completed stream, then re-raise for centralized logging.
+ begin
+ write_chunk(
+ io,
+ {
+ event: "error",
+ error: I18n.t("discourse_ai.errors.stream_reply_unexpected_error"),
+ },
+ )
+ finish_chunks(io)
+ rescue StandardError
+ end
+ raise e
+ end
+
+ def write_headers(io)
+ io.write "HTTP/1.1 200 OK"
+ io.write CRLF
+ io.write "Content-Type: text/plain; charset=utf-8"
+ io.write CRLF
+ io.write "Transfer-Encoding: chunked"
+ io.write CRLF
+ io.write "Cache-Control: no-cache, no-store, must-revalidate"
+ io.write CRLF
+ io.write "Connection: close"
+ io.write CRLF
+ io.write "X-Accel-Buffering: no"
+ io.write CRLF
+ io.write "X-Content-Type-Options: nosniff"
+ io.write CRLF
+ io.write CRLF
+ io.flush
+ end
+
+ def write_chunk(io, payload)
+ data = payload.to_json + "\n\n"
+ data.force_encoding("UTF-8")
+
+ io.write data.bytesize.to_s(16)
+ io.write CRLF
+ io.write data
+ io.write CRLF
+ io.flush
+ end
+
+ def finish_chunks(io)
+ io.write "0"
+ io.write CRLF
+ io.write CRLF
+
+ io.flush
+ io.done if io.respond_to?(:done)
+ end
end
end
end
diff --git a/plugins/discourse-ai/lib/ai_bot/stream_reply_custom_tools_session.rb b/plugins/discourse-ai/lib/ai_bot/stream_reply_custom_tools_session.rb
new file mode 100644
index 00000000000..1cc32d92bb5
--- /dev/null
+++ b/plugins/discourse-ai/lib/ai_bot/stream_reply_custom_tools_session.rb
@@ -0,0 +1,439 @@
+# frozen_string_literal: true
+
+module DiscourseAi
+ module AiBot
+ class StreamReplyCustomToolsSession
+ RESUME_STATE_PREFIX = "discourse_ai:stream_reply:custom_tools:"
+ RESUME_STATE_TTL_SECONDS = 15.minutes.to_i
+ MAX_RESUME_ROUNDS = 10
+ MAX_REDIS_STATE_BYTES = 500 * 1024
+
+ class ProtocolError < StandardError
+ end
+
+ class ResumeTokenNotFound < ProtocolError
+ end
+
+ class InvalidToolResults < ProtocolError
+ end
+
+ def self.resume_state_exists?(resume_token)
+ return false if resume_token.blank?
+ Discourse.redis.exists?(redis_key(resume_token))
+ end
+
+ def self.redis_key(resume_token)
+ "#{RESUME_STATE_PREFIX}#{resume_token}"
+ end
+
+ def initialize(
+ persona:,
+ user:,
+ topic:,
+ query:,
+ custom_instructions:,
+ current_user:,
+ custom_tools:,
+ resume_token:,
+ tool_results:
+ )
+ @persona = persona
+ @user = user
+ @topic = topic
+ @query = query
+ @custom_instructions = custom_instructions
+ @current_user = current_user
+ @custom_tools = custom_tools || []
+ @resume_token = resume_token
+ @tool_results = Array(tool_results).map(&:stringify_keys)
+ @accumulated_reply = +""
+ @round_count = 0
+ end
+
+ def run(&event_blk)
+ if resuming?
+ load_resume_state!
+ apply_tool_results!
+ else
+ setup_initial_request!
+ end
+
+ event_blk.call(
+ :context,
+ { topic_id: @topic.id, bot_user_id: @reply_user.id, persona_id: @persona.id },
+ )
+
+ run_single_completion_round!(&event_blk)
+ end
+
+ private
+
+ def resuming?
+ @resume_token.present?
+ end
+
+ def setup_initial_request!
+ post_params = {
+ raw: @query,
+ skip_validations: true,
+ custom_fields: {
+ DiscourseAi::AiBot::Playground::BYPASS_AI_REPLY_CUSTOM_FIELD => true,
+ },
+ }
+
+ if @topic
+ post_params[:topic_id] = @topic.id
+ else
+ post_params[:title] = I18n.t("discourse_ai.ai_bot.default_pm_prefix")
+ post_params[:archetype] = Archetype.private_message
+ post_params[:target_usernames] = "#{@user.username},#{@persona.user.username}"
+ end
+
+ @source_post = PostCreator.create!(@user, post_params)
+ @topic = @source_post.topic
+ @source_post_number = @source_post.post_number
+
+ persona_class = DiscourseAi::Personas::Persona.find_by(id: @persona.id, user: @current_user)
+ raise ProtocolError, I18n.t("discourse_ai.errors.persona_not_found") if persona_class.nil?
+
+ @bot = DiscourseAi::Personas::Bot.as(@persona.user, persona: persona_class.new)
+ @reply_user = @bot.bot_user
+ @llm_model_id = @bot.model.id
+
+ max_context_posts = @bot.persona.class.max_context_posts || 40
+ context =
+ DiscourseAi::Personas::BotContext.new(
+ post: @source_post,
+ user: @user,
+ custom_instructions: @custom_instructions,
+ messages:
+ DiscourseAi::Completions::PromptMessagesBuilder.messages_from_post(
+ @source_post,
+ max_posts: max_context_posts,
+ include_uploads: @bot.persona.class.vision_enabled,
+ bot_usernames: available_bot_usernames,
+ ),
+ )
+
+ @prompt = @bot.persona.craft_prompt(context, llm: @bot.llm)
+ # This endpoint supports caller-owned tool execution. We replace persona tools so every
+ # emitted tool call can be completed through the resume protocol.
+ @prompt.tools =
+ @custom_tools.map do |tool|
+ DiscourseAi::Completions::ToolDefinition.from_hash(tool.deep_symbolize_keys)
+ end
+ @temperature = @bot.persona.temperature
+ @top_p = @bot.persona.top_p
+ end
+
+ def load_resume_state!
+ payload = resume_payload
+ if payload.blank?
+ raise ResumeTokenNotFound, I18n.t("discourse_ai.errors.invalid_stream_resume_token")
+ end
+
+ saved_current_user_id = payload["current_user_id"]
+ if saved_current_user_id.blank? || @current_user.blank? ||
+ @current_user.id != saved_current_user_id
+ raise ResumeTokenNotFound, I18n.t("discourse_ai.errors.invalid_stream_resume_token")
+ end
+
+ @persona = AiPersona.find(payload["persona_id"])
+ @user = User.find(payload["user_id"])
+ @topic = Topic.find(payload["topic_id"])
+ @reply_user = User.find(payload["reply_user_id"])
+ @llm_model_id = payload["llm_model_id"]
+ @source_post_number = payload["source_post_number"]
+ @temperature = payload["temperature"]
+ @top_p = payload["top_p"]
+ @accumulated_reply = payload["accumulated_reply"].to_s
+ @expected_tool_calls = payload["expected_tool_calls"] || []
+ @round_count = payload["round_count"].to_i
+
+ @prompt = prompt_from_payload(payload.fetch("prompt"))
+ rescue ActiveRecord::RecordNotFound
+ raise ResumeTokenNotFound, I18n.t("discourse_ai.errors.invalid_stream_resume_token")
+ end
+
+ def run_single_completion_round!
+ llm = DiscourseAi::Completions::Llm.proxy(@llm_model_id)
+ turn_reply = +""
+ streamed_tool_calls = []
+
+ result =
+ llm.generate(@prompt, user: @user, temperature: @temperature, top_p: @top_p) do |partial|
+ if partial.is_a?(String)
+ next if partial.empty?
+
+ turn_reply << partial
+ yield(:partial, partial)
+ elsif partial.is_a?(DiscourseAi::Completions::ToolCall) && !partial.partial?
+ streamed_tool_calls << partial.dup
+ end
+ end
+
+ @accumulated_reply << turn_reply
+ normalized_result = normalize_result(result)
+ tool_calls = unique_tool_calls(streamed_tool_calls + extract_tool_calls(normalized_result))
+
+ if tool_calls.present?
+ non_tool_result =
+ normalized_result.reject do |item|
+ item.is_a?(DiscourseAi::Completions::ToolCall) && !item.partial?
+ end
+
+ if non_tool_result.present?
+ @prompt.push_model_response(
+ non_tool_result.length == 1 ? non_tool_result.first : non_tool_result,
+ )
+ end
+ elsif normalized_result.present?
+ @prompt.push_model_response(
+ normalized_result.length == 1 ? normalized_result.first : normalized_result,
+ )
+ end
+
+ if tool_calls.present?
+ token = persist_state!(tool_calls: tool_calls)
+ yield(
+ :tool_calls,
+ {
+ event: "tool_calls",
+ tool_calls: serialize_tool_calls(tool_calls),
+ resume_token: token,
+ }
+ )
+ return
+ end
+
+ persist_reply_post!
+ clear_resume_state!
+ end
+
+ def extract_tool_calls(result_items)
+ result_items.filter do |item|
+ item.is_a?(DiscourseAi::Completions::ToolCall) && !item.partial?
+ end
+ end
+
+ def unique_tool_calls(calls)
+ seen = {}
+ calls.filter do |call|
+ key = [call.id.to_s, call.name.to_s, call.parameters.to_json, call.provider_data.to_json]
+ !seen[key] && (seen[key] = true)
+ end
+ end
+
+ def normalize_result(result)
+ result = [result] if !result.is_a?(Array)
+
+ result.compact.filter do |item|
+ item.is_a?(String) || item.is_a?(DiscourseAi::Completions::ToolCall) ||
+ item.is_a?(DiscourseAi::Completions::Thinking)
+ end
+ end
+
+ def serialize_tool_calls(tool_calls)
+ tool_calls.map do |call|
+ {
+ id: call.id,
+ name: call.name,
+ parameters: call.parameters,
+ provider_data: call.provider_data.presence,
+ }.compact
+ end
+ end
+
+ def apply_tool_results!
+ expected = @expected_tool_calls || []
+ if expected.blank?
+ raise InvalidToolResults, I18n.t("discourse_ai.errors.no_pending_tool_calls")
+ end
+
+ supplied =
+ @tool_results.index_by do |result|
+ result["tool_call_id"].presence || result["id"].presence
+ end
+
+ supplied_ids = supplied.keys.compact.map(&:to_s)
+ expected_ids = expected.map { |call| call["id"].to_s }
+
+ missing_ids = expected_ids - supplied_ids
+ if missing_ids.present?
+ raise InvalidToolResults,
+ I18n.t("discourse_ai.errors.missing_tool_results", ids: missing_ids.join(", "))
+ end
+
+ extra_ids = supplied_ids - expected_ids
+ if extra_ids.present?
+ raise InvalidToolResults,
+ I18n.t("discourse_ai.errors.unexpected_tool_results", ids: extra_ids.join(", "))
+ end
+
+ expected.each do |tool_call|
+ id = tool_call["id"].to_s
+ result = supplied[id]
+ has_content = result.key?("content")
+ content = result["content"]
+
+ if !has_content || content.nil?
+ raise InvalidToolResults,
+ I18n.t("discourse_ai.errors.invalid_tool_result_content", id: id)
+ end
+
+ content = content.to_json if !content.is_a?(String)
+
+ @prompt.push(
+ type: :tool_call,
+ id: id,
+ name: tool_call["name"],
+ content: { arguments: tool_call["parameters"] || {} }.to_json,
+ provider_data: tool_call["provider_data"],
+ )
+ @prompt.push(type: :tool, id: id, name: tool_call["name"], content: content)
+ end
+ end
+
+ def persist_state!(tool_calls:)
+ next_round_count = @round_count + 1
+ if next_round_count > MAX_RESUME_ROUNDS
+ raise ProtocolError,
+ I18n.t(
+ "discourse_ai.errors.stream_reply_max_resume_rounds_reached",
+ max: MAX_RESUME_ROUNDS,
+ )
+ end
+
+ token = @resume_token.presence || SecureRandom.hex(32)
+ payload = {
+ version: 1,
+ current_user_id: @current_user&.id,
+ persona_id: @persona.id,
+ user_id: @user.id,
+ topic_id: @topic.id,
+ reply_user_id: @reply_user.id,
+ llm_model_id: @llm_model_id,
+ source_post_number: @source_post_number,
+ prompt: {
+ messages: @prompt.messages,
+ tools: @prompt.tools.map(&:to_h),
+ tool_choice: @prompt.tool_choice,
+ },
+ accumulated_reply: @accumulated_reply,
+ expected_tool_calls: serialize_tool_calls(tool_calls),
+ temperature: @temperature,
+ top_p: @top_p,
+ round_count: next_round_count,
+ }
+
+ payload_json = payload.to_json
+ if payload_json.bytesize > MAX_REDIS_STATE_BYTES
+ raise ProtocolError,
+ I18n.t(
+ "discourse_ai.errors.stream_reply_state_too_large",
+ max: MAX_REDIS_STATE_BYTES,
+ )
+ end
+
+ Discourse.redis.setex(self.class.redis_key(token), RESUME_STATE_TTL_SECONDS, payload_json)
+ @resume_token = token
+ @round_count = next_round_count
+ token
+ end
+
+ def clear_resume_state!
+ return if @resume_token.blank?
+
+ Discourse.redis.del(self.class.redis_key(@resume_token))
+ end
+
+ def resume_payload
+ return if @resume_token.blank?
+
+ raw = Discourse.redis.getdel(self.class.redis_key(@resume_token))
+ return if raw.blank?
+
+ JSON.parse(raw)
+ rescue JSON::ParserError
+ nil
+ end
+
+ def prompt_from_payload(payload)
+ messages =
+ deep_symbolize(payload["messages"] || []).map do |message|
+ next message if !message.is_a?(Hash)
+
+ message[:type] = message[:type].to_sym if message[:type].is_a?(String)
+ message
+ end
+ tools = payload["tools"] || []
+
+ prompt =
+ DiscourseAi::Completions::Prompt.new(
+ messages: messages,
+ tools:
+ tools.map do |tool|
+ DiscourseAi::Completions::ToolDefinition.from_hash(tool.deep_symbolize_keys)
+ end,
+ )
+
+ tool_choice = payload["tool_choice"]
+ prompt.tool_choice = tool_choice.to_sym if tool_choice.is_a?(String)
+
+ prompt
+ end
+
+ def deep_symbolize(value)
+ return value.deep_symbolize_keys if value.is_a?(Hash)
+ return value.map { |item| deep_symbolize(item) } if value.is_a?(Array)
+
+ value
+ end
+
+ def available_bot_usernames
+ @available_bot_usernames ||=
+ AiPersona.joins(:user).pluck(:username).concat(available_bot_users.map(&:username))
+ end
+
+ def available_bot_users
+ @available_bot_users ||=
+ User.joins("INNER JOIN llm_models llm ON llm.user_id = users.id").where(active: true)
+ end
+
+ def persist_reply_post!
+ llm_model = LlmModel.find(@llm_model_id)
+ reply_post =
+ PostCreator.create!(
+ @reply_user,
+ topic_id: @topic.id,
+ raw: @accumulated_reply,
+ skip_validations: true,
+ skip_guardian: true,
+ custom_fields: {
+ DiscourseAi::AiBot::POST_AI_LLM_NAME_FIELD => llm_model.display_name,
+ DiscourseAi::AiBot::POST_AI_LLM_MODEL_ID_FIELD => @llm_model_id,
+ DiscourseAi::AiBot::POST_AI_PERSONA_ID_FIELD => @persona.id,
+ },
+ )
+
+ if @source_post_number == 1 && @topic.private_message?
+ persona_class =
+ DiscourseAi::Personas::Persona.find_by(id: @persona.id, user: @current_user)
+ if persona_class
+ bot =
+ DiscourseAi::Personas::Bot.as(
+ @reply_user,
+ persona: persona_class.new,
+ model: llm_model,
+ )
+ begin
+ DiscourseAi::AiBot::Playground.new(bot).title_playground(reply_post, @user)
+ rescue StandardError => e
+ Discourse.warn_exception(e, message: "Discourse AI: Unable to generate stream title")
+ end
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-ai/lib/completions/endpoints/fake.rb b/plugins/discourse-ai/lib/completions/endpoints/fake.rb
index edc0b1bdb3c..e1019520f74 100644
--- a/plugins/discourse-ai/lib/completions/endpoints/fake.rb
+++ b/plugins/discourse-ai/lib/completions/endpoints/fake.rb
@@ -138,6 +138,14 @@ module DiscourseAi
if block_given?
if content.is_a?(DiscourseAi::Completions::ToolCall)
yield(content, -> {})
+ elsif content.is_a?(Array) &&
+ content.all? { |item| item.is_a?(DiscourseAi::Completions::ToolCall) }
+ cancel = false
+ cancel_proc = -> { cancel = true }
+ content.each do |tool_call|
+ break if cancel
+ yield(tool_call, cancel_proc)
+ end
else
split_indices = (1...content.length).to_a.sample(self.class.chunk_count - 1).sort
indexes = [0, *split_indices, content.length]
diff --git a/plugins/discourse-ai/spec/requests/admin/ai_personas_controller_spec.rb b/plugins/discourse-ai/spec/requests/admin/ai_personas_controller_spec.rb
index 9077a28e296..fe8d53a66fc 100644
--- a/plugins/discourse-ai/spec/requests/admin/ai_personas_controller_spec.rb
+++ b/plugins/discourse-ai/spec/requests/admin/ai_personas_controller_spec.rb
@@ -2,6 +2,7 @@
RSpec.describe DiscourseAi::Admin::AiPersonasController do
fab!(:admin)
+ fab!(:admin_2, :admin)
fab!(:ai_persona)
fab!(:embedding_definition)
fab!(:llm_model)
@@ -832,7 +833,7 @@ RSpec.describe DiscourseAi::Admin::AiPersonasController do
expect(response.body).to include("associated")
end
- def validate_streamed_response(raw_http, expected)
+ def parse_streamed_response(raw_http)
lines = raw_http.split("\r\n")
header_lines, _, payload_lines = lines.chunk { |l| l == "" }.map(&:last)
@@ -850,7 +851,7 @@ RSpec.describe DiscourseAi::Admin::AiPersonasController do
expect(header_lines.join("\n")).to eq(preamble)
parsed = +""
-
+ chunks = []
context_info = nil
payload_lines.each_slice(2) do |size, data|
@@ -860,15 +861,20 @@ RSpec.describe DiscourseAi::Admin::AiPersonasController do
if size > 0
json = JSON.parse(data)
+ chunks << json
parsed << json["partial"].to_s
context_info = json if json["topic_id"]
end
end
- expect(parsed).to eq(expected)
+ { parsed: parsed, context_info: context_info, chunks: chunks }
+ end
- context_info
+ def validate_streamed_response(raw_http, expected)
+ response = parse_streamed_response(raw_http)
+ expect(response[:parsed]).to eq(expected)
+ response[:context_info]
end
it "is able to create a new conversation" do
@@ -980,5 +986,559 @@ RSpec.describe DiscourseAi::Admin::AiPersonasController do
expect(topic.posts.count).to eq(4)
end
+
+ it "supports custom injected tools with resume tokens" do
+ Jobs.run_immediately!
+ SiteSetting.ai_bot_allowed_groups = "10"
+
+ ai_persona.create_user!
+ ai_persona.update!(
+ allowed_group_ids: [Group::AUTO_GROUPS[:trust_level_0]],
+ default_llm_id: llm.id,
+ allow_personal_messages: true,
+ system_prompt: "you are a helpful bot",
+ )
+
+ fake_endpoint.fake_content = [
+ DiscourseAi::Completions::ToolCall.new(
+ name: "client_weather",
+ parameters: {
+ city: "Austin",
+ },
+ id: "tool_1",
+ ),
+ "This is the response after a client tool call.",
+ "Tool flow title",
+ ]
+ fake_endpoint.chunk_count = 1
+
+ io_out, io_in = IO.pipe
+
+ post "/admin/plugins/discourse-ai/ai-personas/stream-reply.json",
+ params: {
+ persona_id: ai_persona.id,
+ query: "What's the weather?",
+ user_unique_id: "site:test.com:user_id:42",
+ preferred_username: "tool_user",
+ custom_tools: [
+ {
+ name: "client_weather",
+ description: "Gets weather from the client runtime",
+ parameters: [
+ {
+ name: "city",
+ description: "City to fetch weather for",
+ type: "string",
+ required: true,
+ },
+ ],
+ },
+ ],
+ },
+ env: {
+ "rack.hijack" => lambda { io_in },
+ }
+
+ expect(response).to have_http_status(:no_content)
+
+ parsed = parse_streamed_response(io_out.read)
+ context = parsed[:context_info]
+ tool_event = parsed[:chunks].find { |chunk| chunk["event"] == "tool_calls" }
+
+ expect(parsed[:parsed]).to eq("")
+ expect(context["topic_id"]).to be_present
+ expect(tool_event).to be_present
+ expect(tool_event.dig("tool_calls", 0, "name")).to eq("client_weather")
+ expect(tool_event["resume_token"]).to be_present
+
+ topic = Topic.find(context["topic_id"])
+ expect(topic.posts.count).to eq(1)
+ expect(topic.posts.first.raw).to eq("What's the weather?")
+
+ io_out, io_in = IO.pipe
+
+ post "/admin/plugins/discourse-ai/ai-personas/stream-reply.json",
+ params: {
+ resume_token: tool_event["resume_token"],
+ tool_results: [{ tool_call_id: "tool_1", content: { temperature_c: 23 } }],
+ },
+ env: {
+ "rack.hijack" => lambda { io_in },
+ }
+
+ expect(response).to have_http_status(:no_content)
+
+ resumed = parse_streamed_response(io_out.read)
+ expect(resumed[:parsed]).to eq("This is the response after a client tool call.")
+
+ topic.reload
+ expect(topic.posts.count).to eq(2)
+ expect(topic.posts.order(:created_at).last.raw).to eq(
+ "This is the response after a client tool call.",
+ )
+ expect(topic.title).to eq("Tool flow title")
+ end
+
+ it "validates resume requests include tool_results" do
+ resume_token = SecureRandom.hex(12)
+ Discourse.redis.setex(
+ DiscourseAi::AiBot::StreamReplyCustomToolsSession.redis_key(resume_token),
+ 60,
+ { prompt: { messages: [], tools: [] } }.to_json,
+ )
+
+ post "/admin/plugins/discourse-ai/ai-personas/stream-reply.json",
+ params: {
+ resume_token: resume_token,
+ }
+
+ expect(response).to have_http_status(:unprocessable_entity)
+ expect(response.parsed_body["errors"].join).to include("tool_results")
+ end
+
+ it "supports parallel tool calls in one completion turn" do
+ Jobs.run_immediately!
+ SiteSetting.ai_bot_allowed_groups = "10"
+
+ ai_persona.create_user!
+ ai_persona.update!(
+ allowed_group_ids: [Group::AUTO_GROUPS[:trust_level_0]],
+ default_llm_id: llm.id,
+ allow_personal_messages: true,
+ system_prompt: "you are a helpful bot",
+ )
+
+ user = Fabricate(:user)
+ Group.user_trust_level_change!(user.id, user.trust_level)
+
+ first_post =
+ PostCreator.create!(
+ user,
+ title: "Parallel Tool Topic",
+ archetype: Archetype.private_message,
+ target_usernames: ai_persona.user.username,
+ raw: "Initial context message",
+ custom_fields: {
+ DiscourseAi::AiBot::Playground::BYPASS_AI_REPLY_CUSTOM_FIELD => true,
+ },
+ )
+ topic = first_post.topic
+
+ tool_1 =
+ DiscourseAi::Completions::ToolCall.new(
+ name: "client_weather",
+ parameters: {
+ city: "Austin",
+ },
+ id: "tool_1",
+ )
+
+ tool_2 =
+ DiscourseAi::Completions::ToolCall.new(
+ name: "client_time",
+ parameters: {
+ timezone: "America/Chicago",
+ },
+ id: "tool_2",
+ )
+
+ fake_endpoint.fake_content = [[tool_1, tool_2], "Parallel tool response finished."]
+
+ io_out, io_in = IO.pipe
+
+ post "/admin/plugins/discourse-ai/ai-personas/stream-reply.json",
+ params: {
+ persona_id: ai_persona.id,
+ username: user.username,
+ topic_id: topic.id,
+ query: "Need weather and local time.",
+ custom_tools: [
+ {
+ name: "client_weather",
+ description: "Gets weather from a client runtime",
+ parameters: [
+ {
+ name: "city",
+ description: "City to fetch weather for",
+ type: "string",
+ required: true,
+ },
+ ],
+ },
+ {
+ name: "client_time",
+ description: "Gets local time from a client runtime",
+ parameters: [
+ {
+ name: "timezone",
+ description: "IANA timezone string",
+ type: "string",
+ required: true,
+ },
+ ],
+ },
+ ],
+ },
+ env: {
+ "rack.hijack" => lambda { io_in },
+ }
+
+ expect(response).to have_http_status(:no_content)
+
+ parsed = parse_streamed_response(io_out.read)
+ tool_event = parsed[:chunks].find { |chunk| chunk["event"] == "tool_calls" }
+
+ expect(parsed[:parsed]).to eq("")
+ expect(tool_event).to be_present
+ expect(tool_event["tool_calls"].length).to eq(2)
+ expect(tool_event["tool_calls"].map { |call| call["id"] }).to contain_exactly(
+ "tool_1",
+ "tool_2",
+ )
+ expect(tool_event["resume_token"]).to be_present
+
+ io_out, io_in = IO.pipe
+
+ post "/admin/plugins/discourse-ai/ai-personas/stream-reply.json",
+ params: {
+ resume_token: tool_event["resume_token"],
+ tool_results: [
+ { tool_call_id: "tool_2", content: { local_time: "10:15" } },
+ { tool_call_id: "tool_1", content: { temperature_c: 23 } },
+ ],
+ },
+ env: {
+ "rack.hijack" => lambda { io_in },
+ }
+
+ expect(response).to have_http_status(:no_content)
+
+ resumed = parse_streamed_response(io_out.read)
+ expect(resumed[:parsed]).to eq("Parallel tool response finished.")
+
+ topic.reload
+ expect(topic.posts.count).to eq(3)
+ expect(topic.posts.order(:created_at).last.raw).to eq("Parallel tool response finished.")
+ end
+
+ it "rejects too many custom tools" do
+ tools =
+ Array.new(21) do |index|
+ { name: "tool_#{index}", description: "test tool #{index}", parameters: [] }
+ end
+
+ post "/admin/plugins/discourse-ai/ai-personas/stream-reply.json",
+ params: {
+ custom_tools: tools,
+ }
+
+ expect(response).to have_http_status(:unprocessable_entity)
+ expect(response.parsed_body["errors"].join).to include("custom_tools")
+ end
+
+ it "rejects ambiguous tool_results params" do
+ post "/admin/plugins/discourse-ai/ai-personas/stream-reply.json",
+ params: {
+ tool_result: {
+ tool_call_id: "tool_1",
+ content: "single",
+ },
+ tool_results: [{ tool_call_id: "tool_2", content: "plural" }],
+ }
+
+ expect(response).to have_http_status(:unprocessable_entity)
+ expect(response.parsed_body["errors"].join).to include("either tool_results or tool_result")
+ end
+
+ it "rejects oversized tool result content" do
+ post "/admin/plugins/discourse-ai/ai-personas/stream-reply.json",
+ params: {
+ resume_token: "ignored-by-validation",
+ tool_results: [{ tool_call_id: "tool_1", content: "a" * 103_000 }],
+ }
+
+ expect(response).to have_http_status(:unprocessable_entity)
+ expect(response.parsed_body["errors"].join).to include("at most")
+ end
+
+ it "rejects nil tool result content" do
+ post "/admin/plugins/discourse-ai/ai-personas/stream-reply.json",
+ params: {
+ tool_results: [{ tool_call_id: "tool_1", content: nil }],
+ }
+
+ expect(response).to have_http_status(:unprocessable_entity)
+ expect(response.parsed_body["errors"].join).to include("tool_results")
+ end
+
+ it "handles resume token TOCTOU expiration during session load" do
+ allow(DiscourseAi::AiBot::StreamReplyCustomToolsSession).to receive(
+ :resume_state_exists?,
+ ).and_call_original
+ allow(DiscourseAi::AiBot::StreamReplyCustomToolsSession).to receive(
+ :resume_state_exists?,
+ ).with("toctou-token").and_return(true)
+
+ io_out, io_in = IO.pipe
+
+ post "/admin/plugins/discourse-ai/ai-personas/stream-reply.json",
+ params: {
+ resume_token: "toctou-token",
+ tool_results: [{ tool_call_id: "tool_1", content: { ok: true } }],
+ },
+ env: {
+ "rack.hijack" => lambda { io_in },
+ }
+
+ expect(response).to have_http_status(:no_content)
+
+ parsed = parse_streamed_response(io_out.read)
+ error_event = parsed[:chunks].find { |chunk| chunk["event"] == "error" }
+
+ expect(error_event).to be_present
+ expect(error_event["error"]).to include("resume_token")
+ end
+
+ it "rejects resume tokens from a different admin user" do
+ Jobs.run_immediately!
+ SiteSetting.ai_bot_allowed_groups = "10"
+
+ ai_persona.create_user!
+ ai_persona.update!(
+ allowed_group_ids: [Group::AUTO_GROUPS[:trust_level_0]],
+ default_llm_id: llm.id,
+ allow_personal_messages: true,
+ system_prompt: "you are a helpful bot",
+ )
+
+ fake_endpoint.fake_content = [
+ DiscourseAi::Completions::ToolCall.new(
+ name: "client_weather",
+ parameters: {
+ city: "Austin",
+ },
+ id: "tool_1",
+ ),
+ ]
+
+ io_out, io_in = IO.pipe
+
+ post "/admin/plugins/discourse-ai/ai-personas/stream-reply.json",
+ params: {
+ persona_id: ai_persona.id,
+ query: "Need weather",
+ user_unique_id: "site:test.com:user_id:mismatch",
+ preferred_username: "mismatch_user",
+ custom_tools: [
+ {
+ name: "client_weather",
+ description: "Gets weather from the client runtime",
+ parameters: [
+ {
+ name: "city",
+ description: "City to fetch weather for",
+ type: "string",
+ required: true,
+ },
+ ],
+ },
+ ],
+ },
+ env: {
+ "rack.hijack" => lambda { io_in },
+ }
+
+ expect(response).to have_http_status(:no_content)
+ parsed = parse_streamed_response(io_out.read)
+ resume_token = parsed[:chunks].find { |chunk| chunk["event"] == "tool_calls" }["resume_token"]
+
+ sign_in(admin_2)
+ io_out, io_in = IO.pipe
+
+ post "/admin/plugins/discourse-ai/ai-personas/stream-reply.json",
+ params: {
+ resume_token: resume_token,
+ tool_results: [{ tool_call_id: "tool_1", content: { temp_c: 22 } }],
+ },
+ env: {
+ "rack.hijack" => lambda { io_in },
+ }
+
+ expect(response).to have_http_status(:no_content)
+ resumed = parse_streamed_response(io_out.read)
+ error_event = resumed[:chunks].find { |chunk| chunk["event"] == "error" }
+
+ expect(error_event).to be_present
+ expect(error_event["error"]).to include("resume_token")
+ end
+
+ it "rejects unexpected tool_call_ids in tool results" do
+ Jobs.run_immediately!
+ SiteSetting.ai_bot_allowed_groups = "10"
+
+ ai_persona.create_user!
+ ai_persona.update!(
+ allowed_group_ids: [Group::AUTO_GROUPS[:trust_level_0]],
+ default_llm_id: llm.id,
+ allow_personal_messages: true,
+ system_prompt: "you are a helpful bot",
+ )
+
+ fake_endpoint.fake_content = [
+ DiscourseAi::Completions::ToolCall.new(
+ name: "client_weather",
+ parameters: {
+ },
+ id: "tool_1",
+ ),
+ ]
+
+ io_out, io_in = IO.pipe
+ post "/admin/plugins/discourse-ai/ai-personas/stream-reply.json",
+ params: {
+ persona_id: ai_persona.id,
+ query: "Need weather",
+ user_unique_id: "site:test.com:user_id:unexpected",
+ preferred_username: "unexpected_user",
+ custom_tools: [
+ {
+ name: "client_weather",
+ description: "Gets weather from the client runtime",
+ parameters: [],
+ },
+ ],
+ },
+ env: {
+ "rack.hijack" => lambda { io_in },
+ }
+
+ expect(response).to have_http_status(:no_content)
+ parsed = parse_streamed_response(io_out.read)
+ resume_token = parsed[:chunks].find { |chunk| chunk["event"] == "tool_calls" }["resume_token"]
+
+ io_out, io_in = IO.pipe
+ post "/admin/plugins/discourse-ai/ai-personas/stream-reply.json",
+ params: {
+ resume_token: resume_token,
+ tool_results: [
+ { tool_call_id: "tool_1", content: { ok: true } },
+ { tool_call_id: "tool_extra", content: { bad: true } },
+ ],
+ },
+ env: {
+ "rack.hijack" => lambda { io_in },
+ }
+
+ expect(response).to have_http_status(:no_content)
+ resumed = parse_streamed_response(io_out.read)
+ error_event = resumed[:chunks].find { |chunk| chunk["event"] == "error" }
+
+ expect(error_event).to be_present
+ expect(error_event["error"]).to include("Unexpected")
+ end
+
+ it "supports multi-round tool calling with resume" do
+ Jobs.run_immediately!
+ SiteSetting.ai_bot_allowed_groups = "10"
+
+ ai_persona.create_user!
+ ai_persona.update!(
+ allowed_group_ids: [Group::AUTO_GROUPS[:trust_level_0]],
+ default_llm_id: llm.id,
+ allow_personal_messages: true,
+ system_prompt: "you are a helpful bot",
+ )
+
+ user = Fabricate(:user)
+ Group.user_trust_level_change!(user.id, user.trust_level)
+
+ first_post =
+ PostCreator.create!(
+ user,
+ title: "Multi Round Tool Topic",
+ archetype: Archetype.private_message,
+ target_usernames: ai_persona.user.username,
+ raw: "Initial context message",
+ custom_fields: {
+ DiscourseAi::AiBot::Playground::BYPASS_AI_REPLY_CUSTOM_FIELD => true,
+ },
+ )
+ topic = first_post.topic
+
+ fake_endpoint.fake_content = [
+ DiscourseAi::Completions::ToolCall.new(
+ name: "client_weather",
+ parameters: {
+ },
+ id: "tool_1",
+ ),
+ DiscourseAi::Completions::ToolCall.new(name: "client_time", parameters: {}, id: "tool_2"),
+ "Finished after two tool rounds.",
+ ]
+
+ io_out, io_in = IO.pipe
+ post "/admin/plugins/discourse-ai/ai-personas/stream-reply.json",
+ params: {
+ persona_id: ai_persona.id,
+ username: user.username,
+ topic_id: topic.id,
+ query: "Need weather and time.",
+ custom_tools: [
+ {
+ name: "client_weather",
+ description: "Gets weather from a client runtime",
+ parameters: [],
+ },
+ {
+ name: "client_time",
+ description: "Gets local time from a client runtime",
+ parameters: [],
+ },
+ ],
+ },
+ env: {
+ "rack.hijack" => lambda { io_in },
+ }
+
+ expect(response).to have_http_status(:no_content)
+ first_round = parse_streamed_response(io_out.read)
+ first_tool_event = first_round[:chunks].find { |chunk| chunk["event"] == "tool_calls" }
+
+ expect(first_tool_event.dig("tool_calls", 0, "id")).to eq("tool_1")
+
+ io_out, io_in = IO.pipe
+ post "/admin/plugins/discourse-ai/ai-personas/stream-reply.json",
+ params: {
+ resume_token: first_tool_event["resume_token"],
+ tool_results: [{ tool_call_id: "tool_1", content: { temp_c: 22 } }],
+ },
+ env: {
+ "rack.hijack" => lambda { io_in },
+ }
+
+ expect(response).to have_http_status(:no_content)
+ second_round = parse_streamed_response(io_out.read)
+ second_tool_event = second_round[:chunks].find { |chunk| chunk["event"] == "tool_calls" }
+
+ expect(second_tool_event.dig("tool_calls", 0, "id")).to eq("tool_2")
+
+ io_out, io_in = IO.pipe
+ post "/admin/plugins/discourse-ai/ai-personas/stream-reply.json",
+ params: {
+ resume_token: second_tool_event["resume_token"],
+ tool_results: [{ tool_call_id: "tool_2", content: { time: "10:15" } }],
+ },
+ env: {
+ "rack.hijack" => lambda { io_in },
+ }
+
+ expect(response).to have_http_status(:no_content)
+ final_round = parse_streamed_response(io_out.read)
+
+ expect(final_round[:parsed]).to eq("Finished after two tool rounds.")
+ topic.reload
+ expect(topic.posts.count).to eq(3)
+ expect(topic.posts.order(:created_at).last.raw).to eq("Finished after two tool rounds.")
+ end
end
end