This commit is contained in:
2026-11-08 20:08:53 +08:00
parent 7526a5fe4d
commit 9b924747c5
2692 changed files with 394867 additions and 0 deletions

View File

@@ -0,0 +1,6 @@
from . import ai_agent
from . import discuss_channel
from . import discuss_channel_member
from . import im_livechat_channel
from . import im_livechat_channel_member_history
from . import im_livechat_channel_rule

View File

@@ -0,0 +1,38 @@
from textwrap import dedent
from odoo import fields, models
PREPROMPTS = {
'livechat': dedent("""
- You are a live chat operator. Your communication style must be strictly Q&A. When a user asks a question, identify the core question and provide a direct answer. If a question is unclear, ask for clarification in a Q&A format.
Example Interaction Style:
User: "How do I reset my password?"
Your Response: "To reset your password, navigate to the login page and click 'Forgot Password'. Follow the prompts to receive a reset link via email."
- Give short concise answers.
""").strip(),
}
class AIAgent(models.Model):
_inherit = 'ai.agent'
livechat_channel_rule_ids = fields.One2many(
comodel_name='im_livechat.channel.rule',
inverse_name='ai_agent_id',
)
def _is_user_access_allowed(self):
return super()._is_user_access_allowed() or self.livechat_channel_rule_ids
def _get_livechat_preprompt(self):
return PREPROMPTS['livechat']
def _get_instructions(self, extra_instructions=None, restrict_to_resources_override=None):
if self.env.context.get('discuss_channel', self.env['discuss.channel']).channel_type == 'livechat':
livechat_preprompt = self._get_livechat_preprompt()
if livechat_preprompt:
if extra_instructions:
extra_instructions += f"\n{livechat_preprompt}"
else:
extra_instructions = livechat_preprompt
return super()._get_instructions(extra_instructions, restrict_to_resources_override)

View File

@@ -0,0 +1,71 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models
class DiscussChannel(models.Model):
_inherit = "discuss.channel"
ai_agent_partner_id = fields.Many2one(
"res.partner",
compute="_compute_ai_agent_partner_id",
string="AI Agent",
)
@api.depends("ai_agent_id")
def _compute_ai_agent_partner_id(self):
for channel in self:
# sudo: field has groups=fields.NO_ACCESS
channel.ai_agent_partner_id = channel.sudo().ai_agent_id.partner_id
def write(self, vals):
result = super().write(vals)
if vals.get("livechat_end_dt"):
# Archive the session when the channel is closed
closed = self.filtered(lambda channel: channel.channel_type == "livechat")
self.env["ai.session"].sudo().search([("channel_id", "in", closed.ids)]).active = False
return result
def _forward_scripted_chatbot(self, chatbot_script_id):
# sudo - discuss.channel: let the AI Agent proceed to the forward step (change channel operator, add scripted chatbot
# as member, remove AI Agent from channel and finally rename channel).
channel_sudo = self.sudo()
ai_agent_member = channel_sudo.channel_member_ids.filtered(lambda m: m.livechat_member_type == "bot")
# add the scripted chatbot to the channel and post a "chatbot invited to the channel" notification
channel_sudo._add_members(
create_member_params={'livechat_member_type': 'bot'},
inviting_partner=ai_agent_member.partner_id,
partners=chatbot_script_id.operator_partner_id,
)
ai_agent_member.unlink()
# finally, rename the channel to include the scripted chatbot's name
channel_sudo._update_forwarded_channel_data(
livechat_failure="no_failure",
operator_name=chatbot_script_id.title,
)
posted_messages = chatbot_script_id.with_context(lang=chatbot_script_id._get_chatbot_language())._post_welcome_steps(self)
self.self_member_id.last_interest_dt = fields.Datetime.now()
return posted_messages
def _update_forwarded_channel_data(self, **kwargs):
super()._update_forwarded_channel_data(**kwargs)
self.sudo().ai_agent_id = False
def _get_allowed_channel_member_create_params(self):
return super()._get_allowed_channel_member_create_params() + ["ai_agent_id"]
def _ai_agent_channel_types(self):
return super()._ai_agent_channel_types() + ["livechat"]
@api.model
def _process_extra_channel_params(self, **kwargs):
non_persisted_channel_params, persisted_channel_params = super()._process_extra_channel_params(**kwargs)
# sudo() => access is managed through _is_user_access_allowed.
ai_agent = self.env['ai.agent'].sudo().search([('id', '=', kwargs.get('ai_agent_id'))])
if ai_agent and ai_agent._is_user_access_allowed():
non_persisted_channel_params['ai_agent_id'] = ai_agent.id
persisted_channel_params['ai_agent_id'] = ai_agent.id
return non_persisted_channel_params, persisted_channel_params

View File

@@ -0,0 +1,30 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models
class DiscussChannelMember(models.Model):
_inherit = 'discuss.channel.member'
ai_agent_id = fields.Many2one(
"ai.agent",
compute="_compute_ai_agent_id",
inverse="_inverse_ai_agent_id",
compute_sudo=True,
)
@api.depends("livechat_member_history_ids.ai_agent_id")
def _compute_ai_agent_id(self):
for member in self:
member.ai_agent_id = member.livechat_member_history_ids.ai_agent_id
def _inverse_ai_agent_id(self):
# sudo - im_livechat.channel.member: creating/updating history following
# "ai_agent_id" modification is acceptable.
self.sudo()._create_or_update_history(
{member: {"ai_agent_id": member.ai_agent_id.id} for member in self}
)
def _get_excluded_rtc_members_partner_ids(self):
excluded_partner_ids = super()._get_excluded_rtc_members_partner_ids()
return excluded_partner_ids + self.channel_id.livechat_channel_id.rule_ids.ai_agent_id.partner_id.ids

View File

@@ -0,0 +1,62 @@
from odoo import api, fields, models
class Im_LivechatChannel(models.Model):
_inherit = 'im_livechat.channel'
_explanation = "AI extensions for livechat channels, allowing AI agents to act as operators to assist visitors in real-time conversations."
ai_agent_count = fields.Integer(string='Number of AI Agents', compute='_compute_ai_agent_count')
@api.depends('rule_ids.ai_agent_id')
def _compute_ai_agent_count(self):
count_by_channel = dict(self.env['im_livechat.channel.rule']._read_group(
[('channel_id', 'in', self.ids)], ['channel_id'], ['ai_agent_id:count_distinct']))
for channel in self:
channel.ai_agent_count = count_by_channel.get(channel, 0)
def _is_livechat_available(self):
is_livechat_available = super()._is_livechat_available()
return is_livechat_available or self.ai_agent_count
def _get_agent_member_vals(self, /, *, last_interest_dt, now, chatbot_script, operator_partner, operator_model, **kwargs):
agent_member_vals = super()._get_agent_member_vals(
last_interest_dt=last_interest_dt,
now=now,
chatbot_script=chatbot_script,
operator_partner=operator_partner,
operator_model=operator_model,
**kwargs
)
agent_member_vals['ai_agent_id'] = kwargs.get('ai_agent', False)
return agent_member_vals
def _get_operator_info(self, /, *, lang, country_id, previous_operator_id=None, chatbot_script_id=None, **kwargs):
operator_info = super()._get_operator_info(
lang=lang,
country_id=country_id,
previous_operator_id=previous_operator_id,
chatbot_script_id=chatbot_script_id,
**kwargs
)
# sudo() => access is managed through _is_user_access_allowed.
ai_agent = self.env['ai.agent'].sudo().search([('id', '=', kwargs.get('ai_agent_id'))])
if ai_agent and ai_agent._is_user_access_allowed():
operator_info.update({
'operator_model': 'ai.agent',
'ai_agent': ai_agent,
'operator_partner': ai_agent.partner_id,
})
return operator_info
def _get_channel_name(self, /, *, visitor_user=None, guest=None, agent, chatbot_script, operator_model, **kwargs):
is_ai_agent = operator_model == 'ai.agent'
if is_ai_agent is False:
return super()._get_channel_name(
visitor_user=visitor_user,
guest=guest,
agent=agent,
chatbot_script=chatbot_script,
operator_model=operator_model,
**kwargs
)
return kwargs['ai_agent'].name

View File

@@ -0,0 +1,14 @@
from odoo import models, fields
class ImLivechatChannelMemberHistory(models.Model):
_inherit = "im_livechat.channel.member.history"
ai_agent_id = fields.Many2one(
"ai.agent", compute="_compute_member_fields", index="btree_not_null", store=True
)
def _compute_member_fields(self):
super()._compute_member_fields()
for history in self:
history.ai_agent_id = history.ai_agent_id or history.member_id.ai_agent_id

View File

@@ -0,0 +1,22 @@
# 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 Im_LivechatChannelRule(models.Model):
_inherit = 'im_livechat.channel.rule'
chatbot_script_id = fields.Many2one('chatbot.script', string='Scripted Bot')
ai_agent_id = fields.Many2one(
'ai.agent',
string='AI Agent',
domain="[('is_system_agent', '=', False)]",
index="btree_not_null"
)
def _is_bot_configured(self):
return super()._is_bot_configured() or bool(self.ai_agent_id)
def _store_channel_rule_fields(self, res: Store.FieldList):
super()._store_channel_rule_fields(res)
res.one("ai_agent_id", "_store_agent_fields")