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 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from . import ai_agent
from . import ai_composer
from . import discuss_channel
from . import im_livechat_channel

View File

@@ -0,0 +1,58 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import logging
from odoo import fields, models
_logger = logging.getLogger(__name__)
class AiAgent(models.Model):
_inherit = "ai.agent"
ai_social_livechat_channel_ids = fields.One2many(
comodel_name='im_livechat.channel',
inverse_name='ai_social_livechat_agent_id',
)
def _is_user_access_allowed(self):
return super()._is_user_access_allowed() or bool(self.ai_social_livechat_channel_ids)
def _get_social_livechat_channel_from_context(self):
# Same context key as ai_livechat.models.ai_agent.AIAgent._get_instructions,
# where `discuss_channel` is used to detect the livechat conversation.
discuss_channel = self.env.context.get('discuss_channel')
if not discuss_channel or not isinstance(discuss_channel, self.pool['discuss.channel']):
return self.env['discuss.channel']
return discuss_channel
def _get_default_tools(self):
"""Always add the tool "ask human" for AI social channel."""
tools = super()._get_default_tools()
discuss_channel_sudo = self._get_social_livechat_channel_from_context().sudo()
if (
discuss_channel_sudo
and discuss_channel_sudo.channel_type == 'livechat'
and discuss_channel_sudo.livechat_social_account_id
):
# don't load skills like `ai_skill_information_retrieval_query`
tools = self.env.ref('ai_social.ir_actions_server_add_human')
return tools
def _ai_tool_social_livechat_add_human(self):
discuss_channel_sudo = self._get_social_livechat_channel_from_context().sudo()
if (
not discuss_channel_sudo
or discuss_channel_sudo.channel_type != 'livechat'
or not discuss_channel_sudo.livechat_social_account_id
):
_logger.warning("AI Social: human asked in non-social channel")
return self.env._("Error: Cannot use this tool in this conversation")
forward_result = discuss_channel_sudo._forward_human_operator()
if not forward_result['agent']:
_logger.info("AI Social: no human online")
discuss_channel_sudo.livechat_status = 'need_help'
return self.env._("Error: Failed to add a human, no human operator online.")
return self.env._("A human operator has been added to the conversation. Let the user know that a human will take over.")

View File

@@ -0,0 +1,32 @@
import json
from odoo import api, fields, models
class AIComposer(models.Model):
_name = "ai.composer"
_inherit = ["ai.composer"]
interface_key = fields.Selection(
selection_add=[("text_field_social", "Write a social post")],
ondelete={"text_field_social": "cascade"},
)
@api.depends("interface_key")
def _compute_hide_model_selection(self):
super()._compute_hide_model_selection()
for rule in self:
rule.hide_model_selection = (
rule.hide_model_selection or rule.interface_key == "text_field_social"
)
def _get_initial_context(self, res_model=None, res_id=None, text_selection=None, text_of_editable=None, reference_image_path=None):
"""Allow to add information about the social post, without saving the form."""
parts = super()._get_initial_context(res_model, res_id, text_selection, text_of_editable, reference_image_path)
if self.interface_key != "text_field_social":
return parts
if post_data := self.env.context.get('ai_social_post_values'):
parts.append({'type': 'text', 'text': json.dumps(post_data)})
return parts

View File

@@ -0,0 +1,35 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models
class DiscussChannel(models.Model):
_inherit = "discuss.channel"
def _social_should_send_message(self, **message_values):
return super()._social_should_send_message(**message_values) or (
self.livechat_social_account_id
and (author_id := message_values.get('author_id'))
and self.env['res.partner'].browse(author_id).agent_ids
)
def _add_members(self, **kwargs):
all_new_members = super()._add_members(**kwargs)
# when a human joins manually the channel, remove the AI bot
for channel in self.filtered('livechat_social_account_id'):
new_members = channel.channel_member_ids & all_new_members
if any(user._is_internal() for user in new_members.partner_id.user_ids):
channel._social_remove_ai_agent()
return all_new_members
def _social_on_self_sent_message(self):
"""Called when we reply from the social media website."""
super()._social_on_self_sent_message()
self._social_remove_ai_agent()
self.livechat_end_dt = False # we should not close the channel
def _social_remove_ai_agent(self):
self.ensure_one()
self.sudo().channel_member_ids.filtered(lambda m: m.livechat_member_type == "bot").unlink()
self.sudo().ai_agent_id = False

View File

@@ -0,0 +1,69 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models
class ImLivechatChannel(models.Model):
_inherit = "im_livechat.channel"
ai_social_livechat_agent_id = fields.Many2one(
"ai.agent",
string="AI Agent",
domain="[('is_system_agent', '=', False)]",
index="btree_not_null",
)
ai_social_livechat_enabled_condition = fields.Selection(
string="Enable ChatBot",
selection=[
("always", "Always"),
("only_if_no_operator", "Only when no operator is available"),
("only_if_operator", "Only when an operator is available"),
],
required=True,
default="always",
)
def _social_get_session_args(self, previous_operator_id=False):
session_args = super()._social_get_session_args(previous_operator_id)
session_args['ai_agent_id'] = False
if not self.ai_social_livechat_agent_id:
return session_args
add_ai_agent = self.ai_social_livechat_enabled_condition == "always"
if not add_ai_agent:
operator_available = self._get_operator(
country_id=False,
lang=False,
previous_operator_id=previous_operator_id,
)
if self.ai_social_livechat_enabled_condition == "only_if_operator":
add_ai_agent = operator_available
elif self.ai_social_livechat_enabled_condition == "only_if_no_operator":
add_ai_agent = not operator_available
if add_ai_agent:
session_args['ai_agent_id'] = self.ai_social_livechat_agent_id.id
return session_args
def _social_livechat_on_media_message(self, discuss_channel, message):
super()._social_livechat_on_media_message(discuss_channel, message)
ai_agent = discuss_channel.ai_agent_id
if not ai_agent:
return
ai_session_sudo = self.env['ai.session'].sudo().search(
[('channel_id', '=', discuss_channel.id), ('agent_id', '=', ai_agent.id)],
order='create_date DESC',
limit=1,
)
if not ai_session_sudo:
ai_session_sudo = self.env['ai.session'].sudo().create({
'agent_id': ai_agent.id,
'channel_id': discuss_channel.id,
})
# A new message supersedes any model request still awaiting its callback.
ai_session_sudo.with_context(discuss_channel=discuss_channel)._submit_agent_request(
message._convert_to_parts(),
)