diff --git a/ai_server_action/README.rst b/ai_server_action/README.rst new file mode 100644 index 00000000..1201c26b --- /dev/null +++ b/ai_server_action/README.rst @@ -0,0 +1,106 @@ +============= +Ai Automation +============= + +.. + !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + !! This file is generated by oca-gen-addon-readme !! + !! changes will be overwritten. !! + !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + !! source digest: sha256:9db8aa67499c9f7efc73ff5f14809ca6d3df0f99e4eb35df8fff7f4cd3de79d1 + !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + +.. |badge1| image:: https://img.shields.io/badge/maturity-Beta-yellow.png + :target: https://odoo-community.org/page/development-status + :alt: Beta +.. |badge2| image:: https://img.shields.io/badge/licence-AGPL--3-blue.png + :target: http://www.gnu.org/licenses/agpl-3.0-standalone.html + :alt: License: AGPL-3 +.. |badge3| image:: https://img.shields.io/badge/github-OCA%2Fai-lightgray.png?logo=github + :target: https://github.com/OCA/ai/tree/18.0/ai_server_action + :alt: OCA/ai +.. |badge4| image:: https://img.shields.io/badge/weblate-Translate%20me-F47D42.png + :target: https://translation.odoo-community.org/projects/ai-18-0/ai-18-0-ai_server_action + :alt: Translate me on Weblate +.. |badge5| image:: https://img.shields.io/badge/runboat-Try%20me-875A7B.png + :target: https://runboat.odoo-community.org/builds?repo=OCA/ai&target_branch=18.0 + :alt: Try me on Runboat + +|badge1| |badge2| |badge3| |badge4| |badge5| + +This module integrates AI connections with Odoo server actions, allowing +you to define AI-powered automations. By default it provides Ollama +support, but it can be extended with additional providers by adding new +``kind`` options to ``ai.connection``. + +**Table of contents** + +.. contents:: + :local: + +Usage +===== + +This module adds a new server action type: **AI OCA Action**. + +To use it: + +1. Go to ``Settings > Technical > Actions > Server Actions`` +2. Create a new action and select **AI OCA Action** as the state +3. Select an AI Connection (Ollama) +4. Define the prompt — supports dynamic placeholders using Qweb syntax + (e.g. ``{{ object.name }}``) +5. Optionally select tools the AI can call during execution +6. Define what to do with the result: + + - **Post Message**: posts the AI response as a chatter message on the + record + - **Update Record**: writes the AI response to a specific field + +To extend with a new AI provider, inherit ``ai.connection`` and add a +new selection value to ``kind``, then implement the corresponding +``_run_{kind}`` method. + +Bug Tracker +=========== + +Bugs are tracked on `GitHub Issues `_. +In case of trouble, please check there if your issue has already been reported. +If you spotted it first, help us to smash it by providing a detailed and welcomed +`feedback `_. + +Do not contact contributors directly about support or help with technical issues. + +Credits +======= + +Authors +------- + +* Dixmit + +Contributors +------------ + +- `Dixmit `__ + + - Enric Tobella + +- [SDi] (https://sdi.es) + +Maintainers +----------- + +This module is maintained by the OCA. + +.. image:: https://odoo-community.org/logo.png + :alt: Odoo Community Association + :target: https://odoo-community.org + +OCA, or the Odoo Community Association, is a nonprofit organization whose +mission is to support the collaborative development of Odoo features and +promote its widespread use. + +This module is part of the `OCA/ai `_ project on GitHub. + +You are welcome to contribute. To learn how please visit https://odoo-community.org/page/Contribute. diff --git a/ai_server_action/__init__.py b/ai_server_action/__init__.py new file mode 100644 index 00000000..0650744f --- /dev/null +++ b/ai_server_action/__init__.py @@ -0,0 +1 @@ +from . import models diff --git a/ai_server_action/__manifest__.py b/ai_server_action/__manifest__.py new file mode 100644 index 00000000..ff283ad0 --- /dev/null +++ b/ai_server_action/__manifest__.py @@ -0,0 +1,16 @@ +# Copyright 2026 Dixmit +# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). + +{ + "name": "Ai Automation", + "summary": "Integrate `ai_tools` with server actions to automate tasks using AI.", + "version": "18.0.1.0.0", + "license": "AGPL-3", + "author": "Dixmit,Odoo Community Association (OCA)", + "website": "https://github.com/OCA/ai", + "depends": ["ai_connection", "ai_tool"], + "data": [ + "views/ir_actions_server.xml", + ], + "demo": [], +} diff --git a/ai_server_action/models/__init__.py b/ai_server_action/models/__init__.py new file mode 100644 index 00000000..4ab5cb10 --- /dev/null +++ b/ai_server_action/models/__init__.py @@ -0,0 +1 @@ +from . import ir_actions_server diff --git a/ai_server_action/models/ir_actions_server.py b/ai_server_action/models/ir_actions_server.py new file mode 100644 index 00000000..13b47954 --- /dev/null +++ b/ai_server_action/models/ir_actions_server.py @@ -0,0 +1,116 @@ +# Copyright 2026 Dixmit +# Copyright 2026 SDi - Ángel Moya +# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). + +from odoo import api, fields, models +from odoo.tools.mail import html2plaintext, html_sanitize, plaintext2html + +try: + import markdown +except ImportError: + markdown = None + + +class IrActionsServer(models.Model): + _inherit = "ir.actions.server" + + state = fields.Selection( + selection_add=[("ai_oca", "Run AI Prompt")], + ondelete={"ai_oca": "cascade"}, + ) + ai_connection_id = fields.Many2one( + "ai.connection", + string="AI Connection", + groups="base.group_system", + ) + ai_tool_ids = fields.Many2many( + "ai.tool", + string="AI Tools", + groups="base.group_system", + ) + ai_prompt = fields.Html( + string="AI Prompt", + sanitize=False, + ) + mailing_model_real = fields.Char( + compute="_compute_mailing_model_real", + ) + ai_output_mode = fields.Selection( + [ + ("post_message", "Post Message"), + ("update_record", "Update Record"), + ("store_variable", "Store in Context Variable"), + ("none", "None"), + ], + string="Output Mode", + default="none", + groups="base.group_system", + ) + ai_update_record_field_id = fields.Many2one( + "ir.model.fields", + string="Update Record Field", + domain=( + "[('model_id', '=', model_id), " + "('ttype', 'in', ['char', 'text', 'html'])]" + ), + groups="base.group_system", + ) + ai_context_variable = fields.Char( + string="Context Variable", + groups="base.group_system", + help=( + "Name of the variable where the response will be stored " + "in the evaluation context." + ), + ) + + @api.depends("model_id") + def _compute_mailing_model_real(self): + for record in self: + record.mailing_model_real = ( + record.model_id.model if record.model_id else False + ) + + def _run_action_ai_oca(self, eval_context=None): + self.ensure_one() + eval_context = eval_context or {} + record = eval_context.get("record") + prompt = self._get_ai_prompt(record) + result = self.ai_connection_id._run( + prompt, + tools=self.ai_tool_ids, + record=record, + )[0] + self._post_run_action_ai_run(result, eval_context, record) + + def _get_ai_prompt(self, record): + self.ensure_one() + prompt = self.ai_prompt or "" + if record: + prompt = str( + self.env["mail.render.mixin"]._render_template_qweb( + prompt, record._name, record.ids + )[record.id] + ) + return html2plaintext(prompt) + + def _post_run_action_ai_run(self, result, eval_context, record): + self.ensure_one() + if self.ai_output_mode == "post_message" and record and record.exists(): + body = self._prepare_message_body(result) + record.message_post(body=body) + elif self.ai_output_mode == "update_record": + if record and self.ai_update_record_field_id: + if markdown and self.ai_update_record_field_id.ttype == "html": + value = self._prepare_message_body(result) + else: + value = result + record.write({self.ai_update_record_field_id.name: value}) + elif self.ai_output_mode == "store_variable": + if self.ai_context_variable: + eval_context[self.ai_context_variable] = result + + def _prepare_message_body(self, result): + if markdown: + return html_sanitize(markdown.markdown(result)) + return plaintext2html(result) diff --git a/ai_server_action/pyproject.toml b/ai_server_action/pyproject.toml new file mode 100644 index 00000000..4231d0cc --- /dev/null +++ b/ai_server_action/pyproject.toml @@ -0,0 +1,3 @@ +[build-system] +requires = ["whool"] +build-backend = "whool.buildapi" diff --git a/ai_server_action/readme/CONTRIBUTORS.md b/ai_server_action/readme/CONTRIBUTORS.md new file mode 100644 index 00000000..fed46661 --- /dev/null +++ b/ai_server_action/readme/CONTRIBUTORS.md @@ -0,0 +1,3 @@ +- [Dixmit](https://www.dixmit.com) + - Enric Tobella +- [SDi] (https://sdi.es) \ No newline at end of file diff --git a/ai_server_action/readme/DESCRIPTION.md b/ai_server_action/readme/DESCRIPTION.md new file mode 100644 index 00000000..7fa64139 --- /dev/null +++ b/ai_server_action/readme/DESCRIPTION.md @@ -0,0 +1,3 @@ +This module integrates AI connections with Odoo server actions, allowing you to +define AI-powered automations. By default it provides Ollama support, but it can +be extended with additional providers by adding new `kind` options to `ai.connection`. diff --git a/ai_server_action/readme/USAGE.md b/ai_server_action/readme/USAGE.md new file mode 100644 index 00000000..e597ad9a --- /dev/null +++ b/ai_server_action/readme/USAGE.md @@ -0,0 +1,14 @@ +This module adds a new server action type: **AI OCA Action**. + +To use it: +1. Go to `Settings > Technical > Actions > Server Actions` +2. Create a new action and select **AI OCA Action** as the state +3. Select an AI Connection (Ollama) +4. Define the prompt — supports dynamic placeholders using Qweb syntax (e.g. `{{ object.name }}`) +5. Optionally select tools the AI can call during execution +6. Define what to do with the result: + - **Post Message**: posts the AI response as a chatter message on the record + - **Update Record**: writes the AI response to a specific field + +To extend with a new AI provider, inherit `ai.connection` and add a new selection +value to `kind`, then implement the corresponding `_run_{kind}` method. \ No newline at end of file diff --git a/ai_server_action/static/description/icon.png b/ai_server_action/static/description/icon.png new file mode 100644 index 00000000..3a0328b5 Binary files /dev/null and b/ai_server_action/static/description/icon.png differ diff --git a/ai_server_action/static/description/index.html b/ai_server_action/static/description/index.html new file mode 100644 index 00000000..2a64c80f --- /dev/null +++ b/ai_server_action/static/description/index.html @@ -0,0 +1,453 @@ + + + + + +Ai Automation + + + +
+

Ai Automation

+ + +

Beta License: AGPL-3 OCA/ai Translate me on Weblate Try me on Runboat

+

This module integrates AI connections with Odoo server actions, allowing +you to define AI-powered automations. By default it provides Ollama +support, but it can be extended with additional providers by adding new +kind options to ai.connection.

+

Table of contents

+ +
+

Usage

+

This module adds a new server action type: AI OCA Action.

+

To use it:

+
    +
  1. Go to Settings > Technical > Actions > Server Actions
  2. +
  3. Create a new action and select AI OCA Action as the state
  4. +
  5. Select an AI Connection (Ollama)
  6. +
  7. Define the prompt — supports dynamic placeholders using Qweb syntax +(e.g. {{ object.name }})
  8. +
  9. Optionally select tools the AI can call during execution
  10. +
  11. Define what to do with the result:
      +
    • Post Message: posts the AI response as a chatter message on the +record
    • +
    • Update Record: writes the AI response to a specific field
    • +
    +
  12. +
+

To extend with a new AI provider, inherit ai.connection and add a +new selection value to kind, then implement the corresponding +_run_{kind} method.

+
+
+

Bug Tracker

+

Bugs are tracked on GitHub Issues. +In case of trouble, please check there if your issue has already been reported. +If you spotted it first, help us to smash it by providing a detailed and welcomed +feedback.

+

Do not contact contributors directly about support or help with technical issues.

+
+
+

Credits

+
+

Authors

+
    +
  • Dixmit
  • +
+
+
+

Contributors

+ +
+
+

Maintainers

+

This module is maintained by the OCA.

+ +Odoo Community Association + +

OCA, or the Odoo Community Association, is a nonprofit organization whose +mission is to support the collaborative development of Odoo features and +promote its widespread use.

+

This module is part of the OCA/ai project on GitHub.

+

You are welcome to contribute. To learn how please visit https://odoo-community.org/page/Contribute.

+
+
+
+ + diff --git a/ai_server_action/tests/__init__.py b/ai_server_action/tests/__init__.py new file mode 100644 index 00000000..1460b40b --- /dev/null +++ b/ai_server_action/tests/__init__.py @@ -0,0 +1 @@ +from . import test_ai_server_action diff --git a/ai_server_action/tests/test_ai_server_action.py b/ai_server_action/tests/test_ai_server_action.py new file mode 100644 index 00000000..8bdce4fb --- /dev/null +++ b/ai_server_action/tests/test_ai_server_action.py @@ -0,0 +1,125 @@ +from unittest.mock import patch + +from odoo.tests.common import TransactionCase + +from odoo.addons.ai_server_action.models import ir_actions_server + + +class TestAiServerAction(TransactionCase): + @classmethod + def setUpClass(cls): + super().setUpClass() + cls.partner_model = cls.env["ir.model"].search( + [("model", "=", "res.partner")], limit=1 + ) + cls.partner = cls.env["res.partner"].create({"name": "Test Partner"}) + + def _create_action(self, output_mode="none"): + return self.env["ir.actions.server"].create( + { + "name": "Test AI Action", + "model_id": self.partner_model.id, + "state": "ai_oca", + "ai_prompt": "Say hello", + "ai_output_mode": output_mode, + } + ) + + def _run_action_with_mock(self, action): + """Execute action with _run patched on the ai.connection model.""" + with patch( + "odoo.addons.ai_connection.models.ai_connection.AiConnection._run", + return_value=("This is a mocked response", 10, 5, 1), + ): + return action.with_context( + active_id=self.partner.id, active_model="res.partner" + ).run() + + def test_action_state_added(self): + states = self.env["ir.actions.server"].fields_get(["state"]) + self.assertTrue(any(s[0] == "ai_oca" for s in states["state"]["selection"])) + + def test_mailing_model_real(self): + action = self._create_action() + self.assertEqual(action.mailing_model_real, "res.partner") + action_without_model = self.env["ir.actions.server"].new( + {"name": "Test AI Action", "state": "ai_oca"} + ) + self.assertFalse(action_without_model.mailing_model_real) + + def test_get_ai_prompt_without_record(self): + action = self._create_action() + self.assertEqual(action._get_ai_prompt(None), "Say hello") + + def test_get_ai_prompt_with_record(self): + action = self._create_action() + action.ai_prompt = "

Hello

" + self.assertEqual(action._get_ai_prompt(self.partner), "Hello Test Partner") + + def test_action_post_message(self): + action = self._create_action("post_message") + messages = self.partner.message_ids + self._run_action_with_mock(action) + new_msgs = self.partner.message_ids - messages + self.assertEqual(len(new_msgs), 1) + self.assertIn("mocked response", new_msgs.body) + + def test_action_post_message_with_markdown(self): + action = self._create_action("post_message") + messages = self.partner.message_ids + with patch.object(ir_actions_server, "markdown") as mock_markdown: + mock_markdown.markdown.side_effect = lambda text: f"

{text}

" + self._run_action_with_mock(action) + new_msgs = self.partner.message_ids - messages + self.assertEqual(len(new_msgs), 1) + self.assertIn("

", new_msgs.body) + self.assertIn("mocked response", new_msgs.body) + + def test_action_update_record(self): + field = self.env["ir.model.fields"].search( + [("model_id", "=", self.partner_model.id), ("name", "=", "comment")], + limit=1, + ) + action = self._create_action("update_record") + action.ai_update_record_field_id = field.id + self._run_action_with_mock(action) + self.assertIn("mocked response", self.partner.comment) + + def test_action_update_record_html_with_markdown(self): + field = self.env["ir.model.fields"].search( + [("model_id", "=", self.partner_model.id), ("name", "=", "comment")], + limit=1, + ) + self.assertEqual(field.ttype, "html") + action = self._create_action("update_record") + action.ai_update_record_field_id = field.id + with patch.object(ir_actions_server, "markdown") as mock_markdown: + mock_markdown.markdown.side_effect = lambda text: f"

{text}

" + self._run_action_with_mock(action) + self.assertIn("

", self.partner.comment) + self.assertIn("mocked response", self.partner.comment) + + def test_action_none(self): + action = self._create_action("none") + self._run_action_with_mock(action) + + def test_action_store_variable(self): + action = self._create_action("store_variable") + action.ai_context_variable = "ai_result" + eval_context = {"record": self.partner} + with patch( + "odoo.addons.ai_connection.models.ai_connection.AiConnection._run", + return_value=("This is a mocked response", 10, 5, 1), + ): + action._run_action_ai_oca(eval_context) + self.assertEqual(eval_context["ai_result"], "This is a mocked response") + + def test_action_store_variable_without_variable(self): + action = self._create_action("store_variable") + eval_context = {"record": self.partner} + with patch( + "odoo.addons.ai_connection.models.ai_connection.AiConnection._run", + return_value=("This is a mocked response", 10, 5, 1), + ): + action._run_action_ai_oca(eval_context) + self.assertNotIn("ai_result", eval_context) diff --git a/ai_server_action/views/ir_actions_server.xml b/ai_server_action/views/ir_actions_server.xml new file mode 100644 index 00000000..a67cb1e2 --- /dev/null +++ b/ai_server_action/views/ir_actions_server.xml @@ -0,0 +1,42 @@ + + + + + ir.actions.server + + + + + + + + + + + + + + + + +