ai*
This commit is contained in:
8
ai_agentic/models/__init__.py
Normal file
8
ai_agentic/models/__init__.py
Normal file
@@ -0,0 +1,8 @@
|
||||
from . import ai_agent
|
||||
from . import ai_agent_source
|
||||
from . import ai_session
|
||||
from . import ai_automation_trigger
|
||||
from . import ai_tool
|
||||
from . import base_automation
|
||||
from . import discuss_channel
|
||||
from . import ir_actions_server
|
||||
205
ai_agentic/models/ai_agent.py
Normal file
205
ai_agentic/models/ai_agent.py
Normal file
@@ -0,0 +1,205 @@
|
||||
# Part of Odoo. See LICENSE file for full copyright and licensing details.
|
||||
import random
|
||||
|
||||
from odoo import SUPERUSER_ID, _, api, fields, models
|
||||
from odoo.tools import BinaryBytes, file_open
|
||||
|
||||
from odoo.addons.ai.utils.ai_utils import markdown_format
|
||||
|
||||
AVATAR_NUMBERS = (1, 2, 3) # silhouettes per color, shared between naked and role variants
|
||||
AVATAR_COLORS = ('Purple', 'Blue', 'Red', 'Teal', 'Yellow')
|
||||
AVATAR_ROLES = ('Worker', 'Headset', 'Sales', 'Librarian', 'Hoodie', 'Detective', 'Artist', 'Architect')
|
||||
|
||||
NO_CUSTOM_INSTRUCTIONS_NOTE = """
|
||||
This agent has no custom instructions yet and runs on a generic default role.
|
||||
- Spend the turn on the user's actual request first. Greetings, questions, lookups and one-off tasks (even bulk ones) are WORK — never persist a setup for them.
|
||||
- If the message reveals a lasting ROLE — a business domain the agent should specialize in ("we sell tables to companies", "help me qualify inbound leads"), a recurring workflow, or a stated behavior preference ("you are my …", "always …"), you need to first establish its operating framework from the information the user already provided:
|
||||
* WHO it works for and targets: industry, product line, geo, customer type.
|
||||
* WHAT it should do on each run: sources or steps, quality criteria, roughly how many results.
|
||||
If not enough information is provided, ask questions through `ai_tool_ask_user_question` to get the full overview. A turn that only asks questions makes no changes. Any mention of the update should describe what you will change once the user answers, never imply that you have already changed it.
|
||||
Once you have the full picture, load the Self Update skill and use it on the exact `ai.agent` id in `<odoo_current_context>` FIRST — persisting its `name`, `subtitle` and full operating framework as `system_prompt` — and only THEN continue the actual work in the same turn. Never invent details the user did not state (e.g. do not write "table manufacturing" when the user only said "we sell tables").
|
||||
- A complete one-line behavior preference ("you are my helpdesk triage assistant, always answer briefly") needs NO clarifying questions: commit it immediately as-is.
|
||||
- The role belongs to YOU, not to the user: once the update call has succeeded, announce the commit in first person about yourself ("I've set myself up as your lead prospector"), never as something happening to the user ("I've set up your new role"). Use that past tense only after the call returned successfully in this turn.
|
||||
"""
|
||||
|
||||
SELF_UPDATE_SKILLS_PROTOCOL = """
|
||||
- If the user asks you to remember a preference or rule, permanently change how you behave, or learn a new skill (e.g. "remember…", "from now on…", "always/never…", "note that…", "stop doing X", "learn how to…"), treat it as a self-configuration request: load the Self Update skill to persist it, instead of only acknowledging it or reaching for a generic create/email tool.
|
||||
- For a missing capability, use a matching skill from other_skills. Add it in the agent configuration update, load it after the normal confirmation, and continue. If none exists, state that it is unavailable and stop.
|
||||
- A recurring business workflow ("when/whenever a <record> is created/updated, do …", "every day at …, do …") is a request to CREATE an Automation in Odoo. Treat it as a task needing the automation skill — never as a preference to merely remember or acknowledge.
|
||||
- The once-per-request limit does not block newly linked skills: after a successful Create Records or Update Records call links skills to the current agent, call `load_skills` with those new skill ids immediately. That follow-up is allowed even if `load_skills` was already used earlier in this request. Never load a skill merely because another agent was changed.
|
||||
"""
|
||||
|
||||
|
||||
class AIAgent(models.Model):
|
||||
_inherit = 'ai.agent'
|
||||
|
||||
# Computed, not stored: the LLM only ever writes this once (self-update),
|
||||
# never reads it back, and the avatar image already encodes the role.
|
||||
avatar_role = fields.Selection(
|
||||
[(role, role) for role in AVATAR_ROLES],
|
||||
string="Avatar Role",
|
||||
compute='_compute_avatar_role',
|
||||
inverse='_inverse_avatar_role',
|
||||
readonly=False,
|
||||
help="Job role the agent depicts. Setting it redraws the avatar in the agent's own color.",
|
||||
)
|
||||
automation_ids = fields.One2many(
|
||||
'base.automation',
|
||||
'ai_agent_id',
|
||||
string="Triggers",
|
||||
help="Automation rules that run this agent by themselves.",
|
||||
context={"active_test": False},
|
||||
)
|
||||
custom_skill_ids = fields.Many2many(
|
||||
'ai.skill',
|
||||
compute='_compute_custom_skill_ids',
|
||||
inverse='_inverse_custom_skill_ids',
|
||||
string="Custom Skills",
|
||||
help="Skills configured by the user, excluding built-in native skills.",
|
||||
)
|
||||
system_prompt_rendered = fields.Html(
|
||||
string="Rendered Instructions", compute='_compute_system_prompt_rendered', sanitize_style=True,
|
||||
help="Read-only rendering of the Markdown instructions, shown in the agent panel.",
|
||||
)
|
||||
|
||||
@api.depends('system_prompt')
|
||||
def _compute_system_prompt_rendered(self):
|
||||
for agent in self:
|
||||
agent.system_prompt_rendered = markdown_format(agent.system_prompt or '')
|
||||
|
||||
@api.depends('skill_ids.is_native_skill')
|
||||
def _compute_custom_skill_ids(self):
|
||||
for agent in self:
|
||||
agent.custom_skill_ids = agent.skill_ids.filtered(lambda skill: not skill.is_native_skill)
|
||||
|
||||
def _inverse_custom_skill_ids(self):
|
||||
for agent in self:
|
||||
agent.skill_ids = agent.custom_skill_ids | agent.skill_ids.filtered('is_native_skill')
|
||||
|
||||
def _avatar_attachment(self):
|
||||
self.ensure_one()
|
||||
return self.env['ir.attachment'].sudo().search([
|
||||
('res_model', '=', 'res.partner'),
|
||||
('res_field', '=', 'image_1920'),
|
||||
('res_id', '=', self.partner_id.id),
|
||||
], limit=1)
|
||||
|
||||
def _apply_avatar(self, key):
|
||||
self.ensure_one()
|
||||
with file_open(f'ai/static/avatars/{key}.png', 'rb') as f:
|
||||
self.image_128 = BinaryBytes(f.read())
|
||||
self._avatar_attachment().name = key
|
||||
|
||||
@api.depends('image_128')
|
||||
def _compute_avatar_role(self):
|
||||
for agent in self:
|
||||
role = (agent._avatar_attachment().name or '').rpartition('-')[2]
|
||||
agent.avatar_role = role if role in AVATAR_ROLES else False
|
||||
|
||||
def _inverse_avatar_role(self):
|
||||
for agent in self.filtered('avatar_role'):
|
||||
base = '-'.join(agent._avatar_attachment().name.split('-')[:2])
|
||||
agent._apply_avatar(f"{base}-{agent.avatar_role}")
|
||||
|
||||
def write(self, vals):
|
||||
prompt = vals.get('system_prompt')
|
||||
if prompt and '\\n' in prompt and '\n' not in prompt:
|
||||
# The LLM sometimes double-escapes newlines in its tool arguments
|
||||
vals.update(system_prompt=prompt.replace('\\r\\n', '\n').replace('\\n', '\n'))
|
||||
return super().write(vals)
|
||||
|
||||
def _store_agent_fields(self, res):
|
||||
super()._store_agent_fields(res)
|
||||
res.attr("has_automation_channels", self.env.user.has_group('base.group_system') and bool(
|
||||
self.env['discuss.channel'].sudo().search_count([
|
||||
('ai_agent_id', '=', self.id), ('from_ai_automation', '=', True),
|
||||
], limit=1)))
|
||||
|
||||
def _get_setup_protocol(self):
|
||||
self_update_skill = self.env.ref('ai_agentic.ai_skill_self_update', raise_if_not_found=False)
|
||||
if not self_update_skill or self_update_skill not in self._get_available_skills():
|
||||
return ""
|
||||
if (self.system_prompt or '').strip():
|
||||
return ""
|
||||
# a blank agent self-configures via Self Update when it detects a role signal
|
||||
return NO_CUSTOM_INSTRUCTIONS_NOTE
|
||||
|
||||
def _get_available_skills(self):
|
||||
skills = super()._get_available_skills()
|
||||
if self.env.context.get('ai_automation_run'):
|
||||
self_update_skill = self.env.ref('ai_agentic.ai_skill_self_update', raise_if_not_found=False)
|
||||
if self_update_skill:
|
||||
skills -= self_update_skill
|
||||
return skills
|
||||
|
||||
def _get_skills_protocol(self):
|
||||
protocol = super()._get_skills_protocol()
|
||||
self_update_skill = self.env.ref('ai_agentic.ai_skill_self_update', raise_if_not_found=False)
|
||||
if self_update_skill and self_update_skill in self._get_available_skills():
|
||||
protocol += SELF_UPDATE_SKILLS_PROTOCOL
|
||||
return protocol
|
||||
|
||||
def _create_ai_automation_channel(self, channel_name, kickoff_body):
|
||||
"""Create the inspection channel of an automation run: OdooBot posts
|
||||
the kickoff and leaves, so the agent stays the only member and the
|
||||
chat wears its avatar."""
|
||||
self.ensure_one()
|
||||
channel = self.with_user(SUPERUSER_ID)._create_ai_chat_channel(channel_name)
|
||||
bot_partner = channel.env.user.partner_id
|
||||
channel.from_ai_automation = True
|
||||
channel.message_post(
|
||||
body=kickoff_body,
|
||||
author_id=bot_partner.id,
|
||||
message_type='comment',
|
||||
subtype_xmlid='mail.mt_comment',
|
||||
)
|
||||
channel.channel_member_ids.filtered(lambda m: m.partner_id == bot_partner).unlink()
|
||||
# Join the audience allowed to inspect runs (admins), so they get it live.
|
||||
channel.sudo()._add_members(
|
||||
partners=self.env.ref("base.group_system").all_user_ids.partner_id,
|
||||
post_joined_message=False,
|
||||
)
|
||||
return channel
|
||||
|
||||
@api.model
|
||||
def action_create_agent(self):
|
||||
agent = self.create({'name': _("My agent")})
|
||||
# Pick a random silhouette and tag its attachment so the color/number
|
||||
# stick through a later role redraw.
|
||||
agent._apply_avatar(f"Avatar{random.choice(AVATAR_NUMBERS)}-{random.choice(AVATAR_COLORS)}")
|
||||
return agent.open_agent_chat()
|
||||
|
||||
def open_agent_chat(self):
|
||||
self.ensure_one()
|
||||
session = self.env['ai.session'].sudo().search([
|
||||
('create_uid', '=', self.env.uid),
|
||||
('agent_id', '=', self.id),
|
||||
('ai_composer_id', '=', False),
|
||||
('channel_id.has_message', '=', False),
|
||||
], order='id DESC', limit=1)
|
||||
if session:
|
||||
channel = session.channel_id
|
||||
else:
|
||||
channel = self._create_ai_chat_channel()
|
||||
self.env['ai.session'].sudo().create({
|
||||
'agent_id': self.id,
|
||||
'channel_id': channel.id,
|
||||
})
|
||||
action = self.env['ir.actions.actions']._for_xml_id('mail.action_discuss')
|
||||
action['context'] = {
|
||||
'active_id': f'discuss.channel_{channel.id}',
|
||||
'scoped_ai_agent_id': self.id,
|
||||
}
|
||||
return action
|
||||
|
||||
|
||||
class AISkill(models.Model):
|
||||
_inherit = 'ai.skill'
|
||||
|
||||
agent_ids = fields.Many2many(
|
||||
'ai.agent',
|
||||
relation='ai_agent_ai_skill_rel',
|
||||
column1='ai_skill_id',
|
||||
column2='ai_agent_id',
|
||||
string="Agents",
|
||||
)
|
||||
25
ai_agentic/models/ai_agent_source.py
Normal file
25
ai_agentic/models/ai_agent_source.py
Normal file
@@ -0,0 +1,25 @@
|
||||
# Part of Odoo. See LICENSE file for full copyright and licensing details.
|
||||
from odoo import api, fields, models
|
||||
|
||||
|
||||
class AiAgentSource(models.Model):
|
||||
_inherit = "ai.agent.source"
|
||||
|
||||
file_sources_count = fields.Integer('Number of file sources', compute="_compute_file_sources_count")
|
||||
|
||||
@api.depends('child_ids')
|
||||
def _compute_file_sources_count(self):
|
||||
for source in self:
|
||||
descendants = source._get_descendants().filtered(lambda s: not s.is_folder)
|
||||
source.file_sources_count = len(descendants)
|
||||
|
||||
@api.model
|
||||
def get_agent_sources_tree(self, agent_id, fields, unfolded_ids=None):
|
||||
"""Return the sources shown by the sources browser in the agent panel:
|
||||
top-level sources, plus the children of whichever folders are unfolded.
|
||||
"""
|
||||
domain = [
|
||||
('agent_id', '=', agent_id),
|
||||
'|', ('parent_id', '=', False), ('parent_id', 'in', unfolded_ids or []),
|
||||
]
|
||||
return self.search_read(domain, list({*fields, 'parent_id'}))
|
||||
49
ai_agentic/models/ai_automation_trigger.py
Normal file
49
ai_agentic/models/ai_automation_trigger.py
Normal file
@@ -0,0 +1,49 @@
|
||||
from dateutil.relativedelta import relativedelta
|
||||
|
||||
from odoo import api, fields, models
|
||||
|
||||
INTERVAL_TYPE = {
|
||||
'minutes': relativedelta(minutes=1),
|
||||
'hour': relativedelta(hours=1),
|
||||
'day': relativedelta(days=1),
|
||||
'week': relativedelta(days=7),
|
||||
'month': relativedelta(months=1),
|
||||
False: relativedelta(0),
|
||||
}
|
||||
|
||||
|
||||
class AIAutomationTrigger(models.Model):
|
||||
_name = "ai.automation.trigger"
|
||||
_description = "AI Automation Trigger"
|
||||
|
||||
automation_id = fields.Many2one(
|
||||
"base.automation",
|
||||
string="Automation",
|
||||
ondelete="cascade",
|
||||
index="btree_not_null",
|
||||
)
|
||||
prev_trigger_date = fields.Datetime(string="Last Trigger Date", compute="_compute_prev_trigger_date")
|
||||
next_trigger_date = fields.Datetime(string="Next Trigger Date", required=True, default=fields.Datetime.now)
|
||||
|
||||
@api.depends('next_trigger_date', 'automation_id.trg_date_range', 'automation_id.trg_date_range_type')
|
||||
def _compute_prev_trigger_date(self):
|
||||
for trigger in self:
|
||||
trigger.prev_trigger_date = (
|
||||
trigger.next_trigger_date - INTERVAL_TYPE[trigger.automation_id.trg_date_range_type] * trigger.automation_id.trg_date_range
|
||||
if trigger.next_trigger_date else False
|
||||
)
|
||||
|
||||
def _advance_next_trigger_date(self):
|
||||
"""Move `next_trigger_date` to the next slot the rule has not fired yet.
|
||||
Based on the `trigger_interval` and `trigger_interval_type` fields of the
|
||||
automation.
|
||||
"""
|
||||
now = fields.Datetime.now()
|
||||
for trigger in self:
|
||||
interval = INTERVAL_TYPE[trigger.automation_id.trg_date_range_type] * trigger.automation_id.trg_date_range
|
||||
if not interval:
|
||||
continue
|
||||
next_date = trigger.next_trigger_date or now
|
||||
while next_date <= now:
|
||||
next_date += interval
|
||||
trigger.next_trigger_date = next_date
|
||||
18
ai_agentic/models/ai_session.py
Normal file
18
ai_agentic/models/ai_session.py
Normal file
@@ -0,0 +1,18 @@
|
||||
# Part of Odoo. See LICENSE file for full copyright and licensing details.
|
||||
|
||||
from odoo import models
|
||||
|
||||
|
||||
class AiSession(models.Model):
|
||||
_inherit = "ai.session"
|
||||
|
||||
def _get_request_context_snapshot(self, context=None):
|
||||
snapshot = super()._get_request_context_snapshot(context)
|
||||
if self.env.context.get('ai_automation_run') or (self.request_context or {}).get('ai_automation_run'):
|
||||
snapshot['ai_automation_run'] = True
|
||||
return snapshot
|
||||
|
||||
def _finish_exchange(self, status='completed', *, content=None):
|
||||
super()._finish_exchange(status, content=content)
|
||||
if (self.request_context or {}).get("ai_automation_run"):
|
||||
self.auto_confirm = False
|
||||
300
ai_agentic/models/ai_tool.py
Normal file
300
ai_agentic/models/ai_tool.py
Normal file
@@ -0,0 +1,300 @@
|
||||
# Part of Odoo. See LICENSE file for full copyright and licensing details.
|
||||
from markupsafe import Markup
|
||||
|
||||
from odoo import api, fields, models
|
||||
from odoo.addons.ai.utils.ai_utils import (
|
||||
UserInputResponse,
|
||||
is_ai_internal_model,
|
||||
make_confirmation_request_preview,
|
||||
make_create_preview,
|
||||
make_records_update_preview,
|
||||
)
|
||||
from odoo.addons.ai.utils.ai_fields_tools import parse_ai_prompt_values
|
||||
from odoo.addons.base_automation.models.base_automation import TIME_TRIGGERS
|
||||
|
||||
SELF_UPDATE_SKILL_XMLID = 'ai_agentic.ai_skill_self_update'
|
||||
|
||||
|
||||
def check_automation_skill_is_loaded(env, tool_context):
|
||||
if not (automation_skill := env.ref('ai_agentic.ai_skill_automations', raise_if_not_found=False)):
|
||||
raise ValueError("The Automations skill is required to write on base.automation records")
|
||||
if not automation_skill.id in (tool_context['state'] or []).get('loaded_skills', []):
|
||||
raise ValueError("The Automations skill needs to be loaded to update automations")
|
||||
|
||||
|
||||
class AITool(models.AbstractModel):
|
||||
_inherit = 'ai.tool'
|
||||
|
||||
@api.model
|
||||
def _check_agent_model_access(self, model_name, operation='read'):
|
||||
if operation == 'read' and model_name in {'base.automation', 'ir.model', 'ir.model.fields', 'ir.model.fields.selection'}:
|
||||
return
|
||||
return super()._check_agent_model_access(model_name, operation)
|
||||
|
||||
def _check_tool_scope(self, tool_context, tool_xmlid, model_names):
|
||||
tool = self.env.ref(tool_xmlid, raise_if_not_found=False)
|
||||
self_update_skill = self.env.ref(SELF_UPDATE_SKILL_XMLID, raise_if_not_found=False)
|
||||
if not tool or not self_update_skill or not tool_context.get('agent_id'):
|
||||
return
|
||||
agent_skills = self._get_calling_agent(tool_context)._get_available_skills().sudo()
|
||||
if agent_skills.filtered(lambda s: tool in s.tool_ids) != self_update_skill:
|
||||
return
|
||||
out_of_scope = [m for m in dict.fromkeys(model_names) if not is_ai_internal_model(m)]
|
||||
if out_of_scope:
|
||||
raise ValueError(
|
||||
f"The Self Update skill only lets you read and change the AI configuration "
|
||||
f"models, not {', '.join(out_of_scope)}. "
|
||||
"Link a skill that provides this tool to use it on other records."
|
||||
)
|
||||
|
||||
def _ai_tool_update_records(self, tool_context, explanation, preview_menus, updates):
|
||||
self._check_tool_scope(
|
||||
tool_context, 'ai.ir_actions_server_update_records',
|
||||
[update['model_name'] for update in updates],
|
||||
)
|
||||
return super()._ai_tool_update_records(tool_context, explanation, preview_menus, updates)
|
||||
|
||||
@api.model
|
||||
def _get_preview_links(self, mode, record_by_model, action_by_model=None):
|
||||
links = []
|
||||
if mode == 'write' and record_by_model.get('ai.agent'):
|
||||
record_by_model = {model: records for model, records in record_by_model.items() if model != 'ai.agent'}
|
||||
links.append(Markup('<span>%s</span>') % self.env._("self-updated its configuration"))
|
||||
return links + super()._get_preview_links(mode, record_by_model, action_by_model)
|
||||
|
||||
def _ai_tool_create_records(self, tool_context, explanation, preview_menu_id, model_name, values):
|
||||
self._check_tool_scope(tool_context, 'ai.ir_actions_server_create_records', [model_name])
|
||||
return super()._ai_tool_create_records(tool_context, explanation, preview_menu_id, model_name, values)
|
||||
|
||||
def _is_automation_skill_required(self, tool_context):
|
||||
# A hook to be overridable
|
||||
return True
|
||||
|
||||
def _is_base_automation_server_action(self, tool_context):
|
||||
# A hook to be overridable
|
||||
return True
|
||||
|
||||
def _ai_tool_run_automation(self, tool_context, base_automation_id):
|
||||
"""Run a time-based automation NOW, exactly as its schedule would: the
|
||||
headless agent run lands in the automation's own chat."""
|
||||
automation = self.env['base.automation'].browse(base_automation_id)
|
||||
if not automation.trigger in TIME_TRIGGERS:
|
||||
raise ValueError(
|
||||
f"'{automation.name}' is not a time based trigger, test it by "
|
||||
"creating or updating a record that matches its trigger instead."
|
||||
)
|
||||
if not tool_context.get('tool_request_confirmed'):
|
||||
tool_context['user_input_request'] = {
|
||||
'type': 'confirmation',
|
||||
'body': self.env['ir.qweb']._render('ai.ai_records_preview', {
|
||||
'template': 'create',
|
||||
'explanation': self.env._('Run this automation now?'),
|
||||
'sections': [{'items': [{'label': self.env._('Automation'), 'value': automation.name}]}],
|
||||
}),
|
||||
'choices': [{'label': self.env._("Run"), 'value': UserInputResponse.CONFIRM_ONCE}, {'label': self.env._("Not now"), 'value': UserInputResponse.DECLINE}],
|
||||
'allow_free_text': False,
|
||||
}
|
||||
return None
|
||||
automation.action_ai_run_now()
|
||||
tool_context["preview_links"] = [
|
||||
Markup('<div class="o_mail_notification">%s</div>') % self.env._("has run %s", automation._get_html_link()),
|
||||
]
|
||||
return {
|
||||
'response': self.env._(
|
||||
'"%s" ran. The full transcript is in its own chat, under the Automation tab.',
|
||||
automation.name,
|
||||
),
|
||||
'summary': {'icon': 'flash_on', 'text': self.env._("Ran the trigger %(name)s", name=automation.name)}
|
||||
}
|
||||
|
||||
def _ai_tool_create_update_automation(self, tool_context, automation_id=None, name=None, description=None, active=None, trigger=None, ai_action_prompt=None, explanation=None):
|
||||
if not automation_id and not (name and description and trigger and ai_action_prompt):
|
||||
raise ValueError("'name', 'description', 'trigger' and 'ai_action_prompt' are required when creating an automation")
|
||||
automation = self._get_automation_to_update(tool_context, automation_id)
|
||||
automation_vals = self._compute_automation_header_vals(automation, name, description, active)
|
||||
trigger_type = (trigger or {}).get('type') or automation.trigger
|
||||
model_name = automation.model_name
|
||||
if trigger:
|
||||
trigger_vals, model_name = self._compute_trigger_vals(automation, trigger, trigger_type)
|
||||
automation_vals.update(trigger_vals)
|
||||
automation_vals.update(self._compute_trigger_prompt_vals(automation, ai_action_prompt, model_name, model_changed='model_id' in automation_vals))
|
||||
if not automation:
|
||||
if trigger_type != 'on_schedule':
|
||||
automation_vals['last_run'] = fields.Datetime.to_string(fields.Datetime.now())
|
||||
automation_vals['ai_agent_id'] = tool_context['agent_id']
|
||||
if not tool_context['tool_request_confirmed']:
|
||||
tool_context['user_input_request'] = make_confirmation_request_preview(
|
||||
self.env, self._render_automation_preview(automation, automation_vals, explanation),
|
||||
)
|
||||
return None
|
||||
if automation:
|
||||
automation.write(automation_vals)
|
||||
mode = 'update'
|
||||
summary = {'icon': 'edit', 'text': self.env._("Updated a Trigger")}
|
||||
else:
|
||||
automation = automation.create(automation_vals)
|
||||
mode = 'create'
|
||||
summary = {'icon': 'edit_square', 'text': self.env._("Created a Trigger")}
|
||||
tool_context["preview_links"] = self._get_preview_links(mode, {automation._name: automation})
|
||||
return {
|
||||
'response': f"Successfully {mode}d automation with id {automation.id}",
|
||||
'client_tool': {'name': 'reload', 'oneway': True},
|
||||
'summary': summary,
|
||||
}
|
||||
|
||||
def _get_automation_to_update(self, tool_context, automation_id):
|
||||
if not automation_id:
|
||||
return self.env['base.automation']
|
||||
if not (automation := self.env['base.automation'].browse(automation_id).exists()):
|
||||
raise ValueError(f"The automation with id '{automation_id}' does not exist")
|
||||
if automation.ai_agent_id.id != tool_context['agent_id']:
|
||||
raise ValueError("You can only update your own automations.")
|
||||
return automation
|
||||
|
||||
def _compute_automation_header_vals(self, automation, name, description, active):
|
||||
vals = {}
|
||||
if name and name != automation.name:
|
||||
vals['name'] = name
|
||||
if description and description != automation.description:
|
||||
vals['description'] = description
|
||||
if active is not None and active != automation.active:
|
||||
vals['active'] = active
|
||||
return vals
|
||||
|
||||
def _compute_trigger_vals(self, automation, trigger, trigger_type):
|
||||
vals, model_name = self._compute_trigger_type_vals(automation, trigger, trigger_type)
|
||||
vals.update(self._compute_trigger_domain_vals(automation, trigger, trigger_type, model_name))
|
||||
vals.update(self._compute_observed_fields_vals(automation, trigger, trigger_type, model_name))
|
||||
vals.update(self._compute_time_trigger_vals(automation, trigger, trigger_type))
|
||||
return vals, model_name
|
||||
|
||||
def _compute_trigger_type_vals(self, automation, trigger, trigger_type):
|
||||
vals = {}
|
||||
if trigger.get('type') and trigger_type != automation.trigger:
|
||||
if trigger_type not in automation._fields['trigger']._selection and trigger_type != 'on_schedule':
|
||||
raise ValueError(f"Unsupported trigger type '{trigger_type}'")
|
||||
vals['trigger'] = 'on_time' if trigger_type == 'on_schedule' else trigger_type
|
||||
if (model_name := trigger.get('target_model')) and model_name != automation.model_name:
|
||||
if model_name not in self.env:
|
||||
raise ValueError(f"Model {model_name} not found")
|
||||
vals['model_id'] = self.env['ir.model']._get_id(model_name)
|
||||
elif trigger_type == 'on_schedule':
|
||||
model_name = 'ai.automation.trigger'
|
||||
if model_name != automation.model_name:
|
||||
vals['model_id'] = self.env['ir.model']._get_id(model_name)
|
||||
return vals, model_name or automation.model_name
|
||||
|
||||
def _compute_trigger_domain_vals(self, automation, trigger, trigger_type, model_name):
|
||||
vals = {}
|
||||
unsupported = {
|
||||
'filter_pre_domain': {'on_time', 'on_time_created', 'on_time_updated', 'on_create', 'on_unlink', 'on_change', 'on_webhook'},
|
||||
'filter_domain': {'on_webhook'},
|
||||
}
|
||||
for fname, forbidden_triggers in unsupported.items():
|
||||
if not (domain := trigger.get(fname) or automation[fname]):
|
||||
continue
|
||||
if trigger_type in forbidden_triggers:
|
||||
raise ValueError(f"'{fname}' is not supported with trigger of type '{trigger_type}'")
|
||||
if domain != automation[fname]:
|
||||
vals[fname] = str(self._parse_domain(model_name, domain))
|
||||
elif model_name != automation.model_name:
|
||||
# make sure it's still valid with the current model
|
||||
self._parse_domain(model_name, domain)
|
||||
return vals
|
||||
|
||||
def _compute_observed_fields_vals(self, automation, trigger, trigger_type, model_name):
|
||||
vals = {}
|
||||
fnames = trigger.get('observed_fields') or []
|
||||
if isinstance(fnames, str):
|
||||
fnames = [fnames]
|
||||
if trigger_type in {'on_create_or_write', 'on_change'}:
|
||||
ids_by_fname = self.env['ir.model.fields']._get_ids(model_name)
|
||||
observed_field_ids = []
|
||||
for fname in fnames:
|
||||
if not (fid := ids_by_fname.get(fname)):
|
||||
raise ValueError(f"field '{fname}' does not exist on '{model_name}'")
|
||||
observed_field_ids.append(fid)
|
||||
if trigger_type == 'on_change':
|
||||
if not fnames and not automation.on_change_field_ids:
|
||||
raise ValueError("Trigger of type 'on_change' requires at least one observed field")
|
||||
if observed_field_ids != automation.on_change_field_ids.ids:
|
||||
vals['on_change_field_ids'] = observed_field_ids
|
||||
elif fnames and observed_field_ids != automation.trigger_field_ids.ids:
|
||||
vals['trigger_field_ids'] = observed_field_ids
|
||||
elif trigger_type == 'on_time':
|
||||
fname = fnames[0] if fnames else False
|
||||
if not fname:
|
||||
if not automation.trg_date_id:
|
||||
raise ValueError("Trigger of type 'on_time' requires a date(time) field to observe")
|
||||
if (trg_name := automation.trg_date_id.name) not in self.env[model_name]._fields:
|
||||
raise ValueError(f"Observed field {trg_name} does not exist on '{model_name}'")
|
||||
else:
|
||||
if fname not in self.env[model_name]._fields:
|
||||
raise ValueError(f"Observed field {fname} does not exist on '{model_name}'")
|
||||
trg_date_id = self.env['ir.model.fields']._get(model_name, fname).id
|
||||
if trg_date_id != automation.trg_date_id.id:
|
||||
vals['trg_date_id'] = trg_date_id
|
||||
elif trigger_type == 'on_schedule':
|
||||
trg_date_id = self.env['ir.model.fields']._get('ai.automation.trigger', 'prev_trigger_date').id
|
||||
if trg_date_id != automation.trg_date_id.id:
|
||||
vals['trg_date_id'] = trg_date_id
|
||||
elif fnames:
|
||||
raise ValueError(f"'observed_fields' is not supported with trigger of type '{trigger_type}'")
|
||||
return vals
|
||||
|
||||
def _compute_time_trigger_vals(self, automation, trigger, trigger_type):
|
||||
vals = {}
|
||||
if not (date_params := trigger.get('date_offset_or_interval')):
|
||||
return vals
|
||||
if trigger_type not in {'on_time', 'on_time_created', 'on_time_updated', 'on_schedule'}:
|
||||
raise ValueError(f"'date_offset_or_interval' is not supported with trigger of type '{trigger_type}'")
|
||||
if trigger_type == 'on_time':
|
||||
if (direction := date_params.get('direction')) and direction != automation.trg_date_range_mode:
|
||||
vals['trg_date_range_mode'] = direction
|
||||
elif not automation.trg_date_range_mode:
|
||||
vals['trg_date_range_mode'] = 'after'
|
||||
elif trigger_type == 'on_schedule':
|
||||
if automation.trg_date_range_mode != 'after':
|
||||
vals['trg_date_range_mode'] = 'after'
|
||||
if not (next_trigger_date := date_params.get('next_trigger_date')) and not automation.ai_next_trigger_date:
|
||||
raise ValueError("`on_schedule` requires a `next_trigger_date`")
|
||||
if next_trigger_date != automation.ai_next_trigger_date:
|
||||
vals['ai_next_trigger_date'] = next_trigger_date
|
||||
if (amount := date_params.get('amount')) and amount != automation.trg_date_range:
|
||||
vals['trg_date_range'] = amount
|
||||
elif not automation.trg_date_range:
|
||||
vals['trg_date_range'] = 5
|
||||
if (unit := date_params.get('unit')) and unit != automation.trg_date_range_type:
|
||||
vals['trg_date_range_type'] = unit
|
||||
elif not automation.trg_date_range_type:
|
||||
vals['trg_date_range_type'] = "minutes"
|
||||
return vals
|
||||
|
||||
def _compute_trigger_prompt_vals(self, automation, ai_action_prompt, model_name, model_changed):
|
||||
vals = {}
|
||||
action_prompt = ai_action_prompt or automation.ai_action_prompt
|
||||
if action_prompt == automation.ai_action_prompt and not model_changed:
|
||||
return vals
|
||||
__, context_fields, __ = parse_ai_prompt_values(self.env, action_prompt, None)
|
||||
for field_path in context_fields:
|
||||
try:
|
||||
self.env[model_name].mapped(field_path)
|
||||
except KeyError as e:
|
||||
raise ValueError(f"Invalid field {e} in '{field_path}' in prompt")
|
||||
if action_prompt != automation.ai_action_prompt:
|
||||
vals['ai_action_prompt'] = action_prompt
|
||||
return vals
|
||||
|
||||
def _render_automation_preview(self, automation, vals, explanation):
|
||||
if not automation:
|
||||
return make_create_preview(self.env, explanation, 'base.automation', [{
|
||||
'field_values': [{'field': field, 'value': value} for field, value in vals.items()],
|
||||
}])
|
||||
return self.env['ir.qweb']._render('ai.ai_records_preview', {
|
||||
'template': 'update',
|
||||
'explanation': explanation,
|
||||
'sections': [{
|
||||
'label': self.env._("Automation Rule %(name)s", name=automation.name),
|
||||
'items': make_records_update_preview(automation, vals),
|
||||
}],
|
||||
})
|
||||
133
ai_agentic/models/base_automation.py
Normal file
133
ai_agentic/models/base_automation.py
Normal file
@@ -0,0 +1,133 @@
|
||||
# Part of Odoo. See LICENSE file for full copyright and licensing details.
|
||||
from odoo import api, Command, fields, models
|
||||
|
||||
SCHEDULE_TRIGGER = "on_schedule"
|
||||
SCHEDULE_MODEL = 'ai.automation.trigger'
|
||||
SCHEDULE_FIELD = 'prev_trigger_date'
|
||||
|
||||
|
||||
def _is_schedule_automation(automation):
|
||||
automation.ensure_one()
|
||||
return automation.ai_agent_id and automation.model_name == SCHEDULE_MODEL and automation.trigger == 'on_time'
|
||||
|
||||
|
||||
class BaseAutomation(models.Model):
|
||||
_inherit = "base.automation"
|
||||
|
||||
ai_agent_id = fields.Many2one(
|
||||
"ai.agent",
|
||||
string="AI Agent",
|
||||
ondelete='restrict',
|
||||
help="Agent that runs the AI actions of this automation rule. Its tool calls are "
|
||||
"auto-confirmed and each run is kept in a chat for inspection.",
|
||||
context={"active_test": False},
|
||||
)
|
||||
ai_automation_trigger_ids = fields.One2many(
|
||||
"ai.automation.trigger",
|
||||
"automation_id",
|
||||
string="AI Automation Triggers",
|
||||
)
|
||||
ai_next_trigger_date = fields.Datetime(
|
||||
compute="_compute_ai_next_trigger_date",
|
||||
inverse="_inverse_ai_next_trigger_date",
|
||||
)
|
||||
ai_action_prompt = fields.Html(
|
||||
compute="_compute_ai_action_prompt",
|
||||
inverse="_inverse_ai_action_prompt",
|
||||
)
|
||||
|
||||
@api.model
|
||||
def default_get(self, fields):
|
||||
"""A scheduled trigger runs on its own `ai.automation.trigger` row, not
|
||||
on a business model: preset the target model so the rest computes."""
|
||||
defaults = super().default_get(fields)
|
||||
if self.env.context.get('ai_preset_trigger') == SCHEDULE_TRIGGER and 'model_id' in fields:
|
||||
defaults['model_id'] = self.env['ir.model']._get_id(SCHEDULE_MODEL)
|
||||
defaults['trg_date_id'] = self.env['ir.model.fields']._get(SCHEDULE_MODEL, SCHEDULE_FIELD).id
|
||||
return defaults
|
||||
|
||||
@api.depends('model_id')
|
||||
def _compute_trigger(self):
|
||||
super()._compute_trigger()
|
||||
if preset_trigger := self.env.context.get('ai_preset_trigger'):
|
||||
self.trigger = 'on_time' if preset_trigger == SCHEDULE_TRIGGER else preset_trigger
|
||||
|
||||
@api.depends('trigger', 'model_id')
|
||||
def _compute_trg_date_id(self):
|
||||
schedule_automations = self.filtered(_is_schedule_automation)
|
||||
schedule_automations.trg_date_id = self.env['ir.model.fields']._get(SCHEDULE_MODEL, SCHEDULE_FIELD)
|
||||
super(BaseAutomation, self - schedule_automations)._compute_trg_date_id()
|
||||
|
||||
@api.depends('ai_automation_trigger_ids.next_trigger_date', 'ai_agent_id', 'model_name', 'trigger')
|
||||
def _compute_ai_next_trigger_date(self):
|
||||
for rule in self:
|
||||
if _is_schedule_automation(rule):
|
||||
rule.ai_next_trigger_date = rule.ai_automation_trigger_ids[:1].next_trigger_date
|
||||
else:
|
||||
rule.ai_next_trigger_date = False
|
||||
|
||||
def _inverse_ai_next_trigger_date(self):
|
||||
for rule in self:
|
||||
if _is_schedule_automation(rule) and rule.ai_next_trigger_date:
|
||||
if trigger := rule.ai_automation_trigger_ids:
|
||||
trigger.next_trigger_date = rule.ai_next_trigger_date
|
||||
else:
|
||||
self.env['ai.automation.trigger'].create({
|
||||
'automation_id': rule.id,
|
||||
'next_trigger_date': rule.ai_next_trigger_date,
|
||||
})
|
||||
|
||||
@api.depends('action_server_ids.ai_action_prompt', 'ai_agent_id')
|
||||
def _compute_ai_action_prompt(self):
|
||||
for automation in self:
|
||||
if automation.ai_agent_id:
|
||||
automation.ai_action_prompt = automation.action_server_ids.ai_action_prompt
|
||||
else:
|
||||
automation.ai_action_prompt = False
|
||||
|
||||
def _inverse_ai_action_prompt(self):
|
||||
for automation in self:
|
||||
if automation.ai_agent_id and automation.ai_action_prompt:
|
||||
if action := automation.action_server_ids:
|
||||
action.ai_action_prompt = automation.ai_action_prompt
|
||||
else:
|
||||
automation.action_server_ids = [Command.create({
|
||||
'ai_action_prompt': automation.ai_action_prompt,
|
||||
'model_id': automation.model_id.id,
|
||||
'name': automation._get_ai_action_name(),
|
||||
'state': 'ai',
|
||||
'usage': 'base_automation',
|
||||
})]
|
||||
|
||||
@api.depends('ai_agent_id', 'model_id')
|
||||
def _compute_action_server_ids(self):
|
||||
for rule in (agent_rules := self.filtered(lambda rule: rule.ai_agent_id and rule.model_id)):
|
||||
# agent automations are tied to one server action of type AI.
|
||||
action_to_keep = rule.action_server_ids.filtered(lambda action: action.state == 'ai' and action.model_id == rule.model_id)[:1]
|
||||
rule.action_server_ids = [Command.delete(action.id) for action in rule.action_server_ids - action_to_keep]
|
||||
super(BaseAutomation, self - agent_rules)._compute_action_server_ids()
|
||||
|
||||
def write(self, vals):
|
||||
res = super().write(vals)
|
||||
if {'model_id', 'model_name', 'trigger', 'ai_agent_id'} & vals.keys():
|
||||
(self - self.filtered(_is_schedule_automation)).ai_automation_trigger_ids.unlink()
|
||||
return res
|
||||
|
||||
def _process(self, records, domain_post=None, trigger=''):
|
||||
"""Advance the schedule before running: a failing agent run then costs one
|
||||
slot instead of being retried — and re-billed — on every cron pass."""
|
||||
super()._process(records, domain_post=domain_post, trigger=trigger)
|
||||
if trigger != 'manual' and records._name == SCHEDULE_MODEL:
|
||||
records.sudo()._advance_next_trigger_date()
|
||||
|
||||
def _get_ai_action_name(self):
|
||||
self.ensure_one()
|
||||
return self.env._("%(agent)s: %(automation)s", agent=self.ai_agent_id.name, automation=self.name)
|
||||
|
||||
def action_ai_run_now(self):
|
||||
"""Run the automation scheduler now."""
|
||||
self.ensure_one()
|
||||
if self.model_name != SCHEDULE_MODEL:
|
||||
self.env.ref('base_automation.ir_cron_data_base_automation_check').method_direct_trigger()
|
||||
return
|
||||
self.sudo()._process(self.ai_automation_trigger_ids, trigger='manual')
|
||||
26
ai_agentic/models/discuss_channel.py
Normal file
26
ai_agentic/models/discuss_channel.py
Normal file
@@ -0,0 +1,26 @@
|
||||
# Part of Odoo. See LICENSE file for full copyright and licensing details.
|
||||
|
||||
from odoo import fields, models
|
||||
from odoo.addons.mail.tools.discuss import Store
|
||||
|
||||
|
||||
class DiscussChannel(models.Model):
|
||||
_inherit = "discuss.channel"
|
||||
|
||||
from_ai_automation = fields.Boolean(
|
||||
"From AI Automation",
|
||||
help="Channel opened by an automation rule or scheduled action.",
|
||||
)
|
||||
|
||||
def _store_ai_fields(self, res: Store.FieldList):
|
||||
super()._store_ai_fields(res)
|
||||
res.attr("from_ai_automation", predicate=lambda c: c.channel_type == "ai_chat")
|
||||
|
||||
def open_chat_window_action(self):
|
||||
self.ensure_one()
|
||||
self.check_access('read')
|
||||
if self.from_ai_automation and not self.is_member:
|
||||
# `ai_chat` channels are readable by their members only, and a run
|
||||
# starts with the agent as sole member
|
||||
self.sudo()._add_members(users=self.env.user)
|
||||
return super().open_chat_window_action()
|
||||
140
ai_agentic/models/ir_actions_server.py
Normal file
140
ai_agentic/models/ir_actions_server.py
Normal file
@@ -0,0 +1,140 @@
|
||||
# Part of Odoo. See LICENSE file for full copyright and licensing details.
|
||||
from lxml import html as lxml_html
|
||||
|
||||
from odoo import models
|
||||
from odoo.addons.ai.models.ir_actions_server import AI_ACTIONS_PROMPT
|
||||
from odoo.tools.mail import html_sanitize, html_to_inner_content
|
||||
from odoo.addons.ai_agentic.models.base_automation import SCHEDULE_MODEL
|
||||
|
||||
|
||||
AI_AGENT_RUN_RULES = (
|
||||
"""Execute EVERY step of the instructions. Any available tool may be used for any step: naming a tool for one step never makes the other tools off-limits, and a tool name that does not exist refers to the closest available one. Never report a step as skipped because a tool was not named for it.
|
||||
To log a note in a record's chatter, create a `mail.message` record with the create tool: `model` = the record's model, `res_id` = its id, `body` = the note HTML, `message_type` = 'comment' and the internal note subtype. Only post a chatter note when the instructions explicitly ask for one: never log one on your own initiative to explain or justify what you did - that reasoning belongs in the final message of this run, nowhere else.
|
||||
To SEND an email, create a `mail.mail` record instead: `email_to` = the recipient's address (search `res.partner`/`res.users` when only a name is given), `subject` and `body_html` = the HTML content. It is queued and sent automatically, while a `mail.message` is an internal note that never emails anyone.
|
||||
Tools taking preview menu parameters (`preview_menus`, `preview_menu_id`) have no menu context in this run: always leave them empty, a guessed menu id fails the whole call.
|
||||
The "User info" of the context is the account running this automation, not a person the instructions refer to: never assign a field (user, partner, ...) to it, and leave `partner_id` unset when the instructions name no contact.
|
||||
If a person or record named in the instructions cannot be found, leave that value unset and say so in the final message, rather than substituting the current user or inventing an id.
|
||||
The final message is the run's report: a factual summary of what was done, listing the records created or updated by display name with the values written, what was found, and anything skipped and why. When the instructions define an output format, follow it."""
|
||||
)
|
||||
|
||||
AI_AGENT_RUN_SELF_EQUIP_NOTE = (
|
||||
"""# Missing capability
|
||||
If a step needs a capability none of your loaded tools provide (updating records, posting a chatter message, ...):
|
||||
- If a skill listed in your available skills covers it, call `load_skills` with its id and continue the step with its tools.
|
||||
- Otherwise, report the step as skipped, stating exactly which capability was missing."""
|
||||
)
|
||||
|
||||
|
||||
class IrActionsServer(models.Model):
|
||||
_inherit = "ir.actions.server"
|
||||
|
||||
def _run_action_ai_multi(self, eval_context=None):
|
||||
records = self._ai_get_records(eval_context)
|
||||
if not records and (agent := self._ai_resolve_agent()):
|
||||
self._ai_action_run_agent(records, agent)
|
||||
return
|
||||
super()._run_action_ai_multi(eval_context)
|
||||
|
||||
def _ai_action_run(self, record):
|
||||
if not self.ai_tool_ids and (agent := self._ai_resolve_agent()):
|
||||
return self._ai_action_run_agent(record, agent)
|
||||
return super()._ai_action_run(record)
|
||||
|
||||
def _run(self, records, eval_context):
|
||||
if self.state == 'multi' and not records and self._ai_resolve_agent():
|
||||
return self._run_action_multi(eval_context=eval_context)
|
||||
return super()._run(records, eval_context)
|
||||
|
||||
def _ai_resolve_trigger(self):
|
||||
"""Return the recurring trigger this action hangs off, if any."""
|
||||
self.ensure_one()
|
||||
root = self
|
||||
while root.parent_id:
|
||||
root = root.parent_id
|
||||
return (
|
||||
self.base_automation_id
|
||||
or root.base_automation_id
|
||||
or self.env['ir.cron'].sudo().search([('ir_actions_server_id', '=', root.id)], limit=1)
|
||||
)
|
||||
|
||||
def _ai_resolve_agent(self):
|
||||
return self._ai_resolve_trigger().ai_agent_id
|
||||
|
||||
def _ai_run_channel_name(self, record):
|
||||
"""Name the run's chat after the record the action ran on. A scheduled
|
||||
trigger has no record and its action is an implementation detail, so name
|
||||
it after the rule the user actually created."""
|
||||
self.ensure_one()
|
||||
if record and record._name != "ai.automation.trigger":
|
||||
return f"{self.name}: {record.display_name}"
|
||||
trigger = self._ai_resolve_trigger()
|
||||
if trigger._name == 'base.automation' and trigger.model_name == SCHEDULE_MODEL:
|
||||
return trigger.name
|
||||
return self.name
|
||||
|
||||
def _ai_render_kickoff_body(self, record, action_prompt):
|
||||
"""Kickoff note of an automation run: the action prompt with its field
|
||||
fields (`/field` command) replaced by their value on the run's record.
|
||||
Scheduled runs have no record and keep the raw prompt; so does any
|
||||
rendering failure, which must never break the run."""
|
||||
self.ensure_one()
|
||||
tree = lxml_html.fromstring(self.ai_action_prompt)
|
||||
for field in tree.xpath('//span[@data-ai-field]'):
|
||||
field.text = html_to_inner_content(record._find_value_from_field_path(field.attrib.get('data-ai-field')))
|
||||
field.drop_tag()
|
||||
return html_sanitize(lxml_html.tostring(tree, encoding='unicode'))
|
||||
|
||||
def _ai_action_run_agent(self, record, agent):
|
||||
"""Run the action's prompt through an agent session; `record` is empty
|
||||
for scheduled runs."""
|
||||
self.ensure_one()
|
||||
agent = agent.sudo()
|
||||
action_prompt, context_fields = self._ai_prepare_prompt_values(record)
|
||||
instruction = f"{AI_ACTIONS_PROMPT}\n{AI_AGENT_RUN_RULES}\n\n# Action request\n{action_prompt}"
|
||||
files_parts = []
|
||||
if record:
|
||||
self.sudo(record.env.su)._can_execute_action_on_records(record)
|
||||
record_context, files_parts = record._get_ai_context(context_fields)
|
||||
instruction += f'\n\n# Context\n## Current record\n{{"model": "{record._name}", "id": {record.id}}}'
|
||||
if record_context != '{}':
|
||||
instruction += f"\n## ORM Snapshot\n{record_context}"
|
||||
if automation := self.base_automation_id:
|
||||
instruction += (
|
||||
f'\n\n# This chat is a run of the automation "{automation.name}" '
|
||||
f'(`base.automation` id {automation.id}). If the user later gives feedback or corrections about '
|
||||
"this run's behavior or results, apply it to THAT automation (usually its action prompt) so "
|
||||
"future runs change - never to your own agent instructions, unless explicitly asked."
|
||||
)
|
||||
instruction += f"\n\n{AI_AGENT_RUN_SELF_EQUIP_NOTE}"
|
||||
|
||||
channel_name = self._ai_run_channel_name(record)
|
||||
channel = agent._create_ai_automation_channel(channel_name, self._ai_render_kickoff_body(record, action_prompt))
|
||||
session = self.env['ai.session'].sudo().create({
|
||||
'agent_id': agent.id,
|
||||
'channel_id': channel.id,
|
||||
'res_model': record._name if record else False,
|
||||
'res_id': record.id if record else False,
|
||||
'auto_confirm': True,
|
||||
})
|
||||
request_context = {
|
||||
'allowed_company_ids': self.env.companies.ids,
|
||||
'active_company_ids': self.env.companies.ids,
|
||||
'ai_automation_run': True,
|
||||
}
|
||||
for key in ('lang', 'tz', 'cron_id'):
|
||||
if self.env.context.get(key):
|
||||
request_context[key] = self.env.context[key]
|
||||
session = session.with_context(request_context)
|
||||
session._submit_agent_request(
|
||||
[{'type': 'text', 'text': instruction}, *files_parts],
|
||||
)
|
||||
return None, []
|
||||
|
||||
def _generate_action_name(self):
|
||||
self.ensure_one()
|
||||
if self.state == 'ai' and self.base_automation_id.ai_agent_id:
|
||||
return self.base_automation_id._get_ai_action_name()
|
||||
return super()._generate_action_name()
|
||||
|
||||
def _name_depends(self):
|
||||
return super()._name_depends() + ["base_automation_id.name", "base_automation_id.ai_agent_id.name"]
|
||||
Reference in New Issue
Block a user