Skip to content

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

FEATURE: richer API for working with custom tools (#37050)

Samd89e57c55fdb
diff --git a/plugins/discourse-ai/lib/ai_tool_scripts/preamble.js b/plugins/discourse-ai/lib/ai_tool_scripts/preamble.js
index f6f11ff9d5d..f9182d7a52a 100644
--- a/plugins/discourse-ai/lib/ai_tool_scripts/preamble.js
+++ b/plugins/discourse-ai/lib/ai_tool_scripts/preamble.js
@@ -55,11 +55,13 @@
* length (number): Maximum number of tokens.
* Returns: string (truncated text)
*
- * llm.generate(prompt): Generates text using the configured LLM associated with the tool runner.
+ * llm.generate(prompt, options?): Generates text using the configured LLM associated with the tool runner.
* Parameters:
* prompt (string | Object): The prompt. Can be a simple string or an object
* like { messages: [{ type: "system", content: "..." }, { type: "user", content: "..." }] }.
- * Returns: string (generated text)
+ * options (Object, optional):
+ * json (boolean): If true, requests JSON output from the LLM and automatically parses it.
+ * Returns: string | Object (generated text or parsed JSON)
*
* 3. index
* Searches attached RAG (Retrieval-Augmented Generation) documents linked to this tool.
@@ -110,6 +112,8 @@
* 6. discourse
* Interacts with Discourse specific features. Access is generally performed as the SystemUser.
*
+ * discourse.baseUrl: The base URL of the Discourse site (e.g., "https://meta.discourse.org").
+ *
* discourse.search(params): Performs a Discourse search.
* Parameters:
* params (Object): Search parameters (e.g., { search_query: "keyword", with_private: true, max_results: 10 }).
@@ -148,6 +152,24 @@
* The sending user must have permission to post in the channel.
* Returns: { success: boolean, message_id?: number, message?: string, created_at?: string } or { error: string }
*
+ * discourse.setTags(topic_id, tags, options?): Sets tags for a topic.
+ * Parameters:
+ * topic_id (number): The ID of the topic.
+ * tags (Array<string>): The list of tags to apply.
+ * options (Object, optional):
+ * append (boolean): If true, tags are added to existing ones.
+ * username (string): The username of the user performing the action.
+ * Returns: { success: boolean, tags: Array<string> }
+ *
+ * discourse.editPost(post_id, raw, options?): Edits a post's content.
+ * Parameters:
+ * post_id (number): The ID of the post.
+ * raw (string): The new raw Markdown content.
+ * options (Object, optional):
+ * edit_reason (string): Reason for the edit.
+ * username (string): The username of the user performing the action.
+ * Returns: { success: boolean, post_id: number }
+ *
* 7. context
* An object containing information about the environment where the tool is being run.
* Available properties depend on the invocation context, but may include:
diff --git a/plugins/discourse-ai/lib/completions/endpoints/canned_response.rb b/plugins/discourse-ai/lib/completions/endpoints/canned_response.rb
index 2ed892552fc..b99515a7653 100644
--- a/plugins/discourse-ai/lib/completions/endpoints/canned_response.rb
+++ b/plugins/discourse-ai/lib/completions/endpoints/canned_response.rb
@@ -92,6 +92,9 @@ module DiscourseAi
def aggregate_structured_response(response_enum)
schema_properties = model_params[:response_format].dig(:json_schema, :schema, :properties)
+
+ return response_enum.first if schema_properties.blank?
+
output = DiscourseAi::Completions::StructuredOutput.new(schema_properties)
response_enum.each do |chunk|
diff --git a/plugins/discourse-ai/lib/personas/tool_runner.rb b/plugins/discourse-ai/lib/personas/tool_runner.rb
index 07fe12769e9..4d8e8bb80e2 100644
--- a/plugins/discourse-ai/lib/personas/tool_runner.rb
+++ b/plugins/discourse-ai/lib/personas/tool_runner.rb
@@ -35,6 +35,18 @@ module DiscourseAi
@http_requests_made = 0
end
+ def system_guardian
+ @system_guardian ||= Guardian.new(Discourse.system_user)
+ end
+
+ def resolve_user(username)
+ if username.present?
+ User.find_by(username: username)
+ else
+ Discourse.system_user
+ end
+ end
+
def mini_racer_context
@mini_racer_context ||=
begin
@@ -68,7 +80,17 @@ module DiscourseAi
const llm = {
truncate: _llm_truncate,
- generate: function(prompt, options) { return _llm_generate(prompt, options); },
+ generate: function(prompt, options) {
+ const result = _llm_generate(prompt, options);
+ if (options && options.json) {
+ try {
+ return JSON.parse(result);
+ } catch (e) {
+ return result;
+ }
+ }
+ return result;
+ },
};
const index = {
@@ -89,6 +111,7 @@ module DiscourseAi
};
const discourse = {
+ baseUrl: #{Discourse.base_url.to_json},
search: function(params) {
return _discourse_search(params);
},
@@ -154,6 +177,20 @@ module DiscourseAi
}
return result;
},
+ setTags: function(topic_id, tags, options) {
+ const result = _discourse_set_tags(topic_id, tags, options);
+ if (result.error) {
+ return result;
+ }
+ return result;
+ },
+ editPost: function(post_id, raw, options) {
+ const result = _discourse_edit_post(post_id, raw, options);
+ if (result.error) {
+ throw new Error(result.error);
+ }
+ return result;
+ },
};
const context = #{JSON.generate(@context.to_json)};
@@ -289,6 +326,9 @@ module DiscourseAi
in_attached_function do
options ||= {}
response_format = options["response_format"]
+
+ response_format = { "type" => "json_object" } if options["json"]
+
if response_format && !response_format.is_a?(Hash)
raise Discourse::InvalidParameters.new("response_format must be a hash")
end
@@ -396,14 +436,13 @@ module DiscourseAi
in_attached_function do
post = Post.find_by(id: post_id)
return nil if post.nil?
- guardian = Guardian.new(Discourse.system_user)
obj =
recursive_as_json(
- PostSerializer.new(post, scope: guardian, root: false, add_raw: true),
+ PostSerializer.new(post, scope: system_guardian, root: false, add_raw: true),
)
topic_obj =
recursive_as_json(
- ListableTopicSerializer.new(post.topic, scope: guardian, root: false),
+ ListableTopicSerializer.new(post.topic, scope: system_guardian, root: false),
)
obj["topic"] = topic_obj
obj
@@ -417,8 +456,13 @@ module DiscourseAi
in_attached_function do
topic = Topic.find_by(id: topic_id)
return nil if topic.nil?
- guardian = Guardian.new(Discourse.system_user)
- recursive_as_json(ListableTopicSerializer.new(topic, scope: guardian, root: false))
+ data =
+ recursive_as_json(
+ ListableTopicSerializer.new(topic, scope: system_guardian, root: false),
+ )
+ data["tags"] = topic.tags.pluck(:name)
+ data["first_post_id"] = topic.first_post&.id
+ data
end
end,
)
@@ -438,8 +482,7 @@ module DiscourseAi
return nil if user.nil?
- guardian = Guardian.new(Discourse.system_user)
- recursive_as_json(UserSerializer.new(user, scope: guardian, root: false))
+ recursive_as_json(UserSerializer.new(user, scope: system_guardian, root: false))
end
end,
)
@@ -597,12 +640,7 @@ module DiscourseAi
return { error: "Missing required parameter: title" } if title.blank?
return { error: "Missing required parameter: raw" } if raw.blank?
- user =
- if username.present?
- User.find_by(username: username)
- else
- Discourse.system_user
- end
+ user = resolve_user(username)
return { error: "User not found: #{username}" } if user.nil?
category =
@@ -623,7 +661,7 @@ module DiscourseAi
category: category.id,
tags: tags,
skip_validations: true,
- guardian: Guardian.new(Discourse.system_user),
+ guardian: system_guardian,
)
post = post_creator.create
@@ -661,12 +699,7 @@ module DiscourseAi
return { error: "Missing required parameter: raw" } if raw.blank?
# Find the user
- user =
- if username.present?
- User.find_by(username: username)
- else
- Discourse.system_user
- end
+ user = resolve_user(username)
return { error: "User not found: #{username}" } if user.nil?
# Verify topic exists
@@ -681,7 +714,7 @@ module DiscourseAi
topic_id: topic_id,
reply_to_post_number: reply_to_post_number,
skip_validations: true,
- guardian: Guardian.new(Discourse.system_user),
+ guardian: system_guardian,
)
post = post_creator.create
@@ -807,6 +840,58 @@ module DiscourseAi
end
end,
)
+
+ mini_racer_context.attach(
+ "_discourse_set_tags",
+ ->(topic_id, tags, options) do
+ in_attached_function do
+ topic = Topic.find_by(id: topic_id)
+ return { error: "Topic not found" } if topic.nil?
+
+ options ||= {}
+ append = !!options["append"]
+ username = options["username"]
+
+ user = resolve_user(username)
+ return { error: "User not found: #{username}" } if user.nil?
+
+ if DiscourseTagging.tag_topic_by_names(
+ topic,
+ Guardian.new(user),
+ tags,
+ append: append,
+ )
+ { success: true, tags: topic.tags.pluck(:name) }
+ else
+ { error: "Failed to apply tags", details: topic.errors.full_messages }
+ end
+ end
+ end,
+ )
+
+ mini_racer_context.attach(
+ "_discourse_edit_post",
+ ->(post_id, raw, options) do
+ in_attached_function do
+ post = Post.find_by(id: post_id)
+ return { error: "Post not found" } if post.nil?
+
+ options ||= {}
+ edit_reason = options["edit_reason"]
+ username = options["username"]
+
+ user = resolve_user(username)
+ return { error: "User not found: #{username}" } if user.nil?
+
+ revisor = PostRevisor.new(post)
+ if revisor.revise!(user, { raw: raw, edit_reason: edit_reason })
+ { success: true, post_id: post.id }
+ else
+ { error: post.errors.full_messages.join(", ") }
+ end
+ end
+ end,
+ )
end
def attach_upload(mini_racer_context)
diff --git a/plugins/discourse-ai/spec/lib/personas/tool_runner_spec.rb b/plugins/discourse-ai/spec/lib/personas/tool_runner_spec.rb
new file mode 100644
index 00000000000..dc9926b55e4
--- /dev/null
+++ b/plugins/discourse-ai/spec/lib/personas/tool_runner_spec.rb
@@ -0,0 +1,186 @@
+# frozen_string_literal: true
+
+require "rails_helper"
+
+RSpec.describe DiscourseAi::Personas::ToolRunner do
+ fab!(:user)
+ fab!(:bot_user) { Fabricate(:user, admin: true) }
+ fab!(:tool) do
+ AiTool.create!(
+ name: "test_tool",
+ tool_name: "test_tool",
+ description: "a test tool",
+ script: "function invoke(params) { return { result: 'ok' }; }",
+ summary: "test",
+ created_by: user,
+ )
+ end
+ fab!(:llm_model)
+ let(:llm) { DiscourseAi::Completions::Llm.proxy(llm_model.id) }
+
+ before do
+ enable_current_plugin
+ SiteSetting.tagging_enabled = true
+ end
+
+ describe "#invoke" do
+ it "can execute a simple script" do
+ runner = described_class.new(parameters: {}, llm: llm, bot_user: bot_user, tool: tool)
+ result = runner.invoke
+ expect(result).to eq({ "result" => "ok" })
+ end
+
+ it "exposes discourse.baseUrl" do
+ tool.update!(script: "function invoke() { return { baseUrl: discourse.baseUrl }; }")
+ runner = described_class.new(parameters: {}, llm: llm, bot_user: bot_user, tool: tool)
+ result = runner.invoke
+ expect(result["baseUrl"]).to eq(Discourse.base_url)
+ end
+
+ it "can set tags on a topic" do
+ topic = Fabricate(:topic)
+ Fabricate(:tag, name: "tag1")
+ Fabricate(:tag, name: "tag2")
+ tool.update!(
+ script:
+ "function invoke(params) { return discourse.setTags(params.topic_id, ['tag1', 'tag2']); }",
+ )
+ runner =
+ described_class.new(
+ parameters: {
+ topic_id: topic.id,
+ },
+ llm: llm,
+ bot_user: bot_user,
+ tool: tool,
+ )
+ result = runner.invoke
+ expect(result["success"]).to eq(true)
+ expect(topic.reload.tags.pluck(:name)).to contain_exactly("tag1", "tag2")
+ end
+
+ it "can get a topic with tags and first_post_id" do
+ topic = Fabricate(:topic)
+ Fabricate(:post, topic: topic)
+ tag = Fabricate(:tag, name: "test_tag")
+ topic.tags << tag
+ tool.update!(
+ script:
+ "function invoke(params) { const t = discourse.getTopic(params.topic_id); return { tags: t.tags, first_post_id: t.first_post_id }; }",
+ )
+ runner =
+ described_class.new(
+ parameters: {
+ topic_id: topic.id,
+ },
+ llm: llm,
+ bot_user: bot_user,
+ tool: tool,
+ )
+ result = runner.invoke
+ expect(result["tags"]).to contain_exactly("test_tag")
+ expect(result["first_post_id"]).to eq(topic.first_post.id)
+ end
+
+ it "can append tags on a topic" do
+ topic = Fabricate(:topic)
+ old_tag = Fabricate(:tag, name: "old_tag")
+ topic.tags << old_tag
+ Fabricate(:tag, name: "new_tag")
+ tool.update!(
+ script:
+ "function invoke(params) { return discourse.setTags(params.topic_id, ['new_tag'], { append: true }); }",
+ )
+ runner =
+ described_class.new(
+ parameters: {
+ topic_id: topic.id,
+ },
+ llm: llm,
+ bot_user: bot_user,
+ tool: tool,
+ )
+ result = runner.invoke
+ expect(result["success"]).to eq(true)
+ expect(topic.reload.tags.pluck(:name)).to contain_exactly("old_tag", "new_tag")
+ end
+
+ it "can set tags as a specific user" do
+ topic = Fabricate(:topic)
+ Fabricate(:tag, name: "tag1")
+ tool.update!(
+ script:
+ "function invoke(params) { return discourse.setTags(params.topic_id, ['tag1'], { username: 'system' }); }",
+ )
+ runner =
+ described_class.new(
+ parameters: {
+ topic_id: topic.id,
+ },
+ llm: llm,
+ bot_user: bot_user,
+ tool: tool,
+ )
+ result = runner.invoke
+ expect(result).to eq({ "success" => true, "tags" => ["tag1"] })
+ expect(topic.reload.tags.pluck(:name)).to contain_exactly("tag1")
+ end
+
+ it "can edit a post" do
+ post = Fabricate(:post)
+ tool.update!(
+ script:
+ "function invoke(params) { return discourse.editPost(params.post_id, 'new raw content', { edit_reason: 'AI edit' }); }",
+ )
+ runner =
+ described_class.new(
+ parameters: {
+ post_id: post.id,
+ },
+ llm: llm,
+ bot_user: bot_user,
+ tool: tool,
+ )
+ result = runner.invoke
+ expect(result["success"]).to eq(true)
+ expect(post.reload.raw).to eq("new raw content")
+ expect(post.edit_reason).to eq("AI edit")
+ expect(post.last_editor_id).to eq(Discourse.system_user.id)
+ end
+
+ it "can edit a post as a specific user" do
+ other_user = Fabricate(:user, admin: true)
+ post = Fabricate(:post)
+ tool.update!(
+ script:
+ "function invoke(params) { return discourse.editPost(params.post_id, 'new raw content', { username: '#{other_user.username}' }); }",
+ )
+ runner =
+ described_class.new(
+ parameters: {
+ post_id: post.id,
+ },
+ llm: llm,
+ bot_user: bot_user,
+ tool: tool,
+ )
+ result = runner.invoke
+ expect(result["success"]).to eq(true)
+ expect(post.reload.last_editor_id).to eq(other_user.id)
+ end
+
+ it "can generate JSON from LLM" do
+ tool.update!(script: "function invoke() { return llm.generate('test', { json: true }); }")
+
+ DiscourseAi::Completions::Llm.with_prepared_responses(
+ ['{"key": "value"}'],
+ ) do |_, _, _, prompt_options|
+ runner = described_class.new(parameters: {}, llm: llm, bot_user: bot_user, tool: tool)
+ result = runner.invoke
+ expect(result).to eq({ "key" => "value" })
+
+ expect(prompt_options.last[:response_format]).to eq({ "type" => "json_object" })
+ end
+ end
+ end
+end