mirror of
https://github.com/guohuadeng/app-odoo.git
synced 2025-02-23 04:11:36 +02:00
prepare #I6SC9C 处理azure私聊,app_chatgpt优化,指定用户时增加使用情况 置顶
处理azure 私聊
This commit is contained in:
@@ -13,41 +13,42 @@ _logger = logging.getLogger(__name__)
|
||||
|
||||
class Channel(models.Model):
|
||||
_inherit = 'mail.channel'
|
||||
|
||||
@api.model
|
||||
def get_openai_context(self, channel_id, partner_chatgpt, current_prompt, seconds=600):
|
||||
afterTime = fields.Datetime.now() - datetime.timedelta(seconds=seconds)
|
||||
|
||||
def get_openai_context(self, channel_id, author_id, answer_id, minutes=30):
|
||||
# 上下文处理,要处理群的方式,以及独聊的方式
|
||||
# azure新api 处理
|
||||
context_history = []
|
||||
afterTime = fields.Datetime.now() - datetime.timedelta(minutes=minutes)
|
||||
message_model = self.env['mail.message'].sudo()
|
||||
prompt = [f"Human:{current_prompt}\nAI:", ]
|
||||
# 处理消息: 取最新问题 + 上2次的交互,将之前的交互按时间顺序拼接
|
||||
# 注意: ai 每一次回复都有 parent_id 来处理连续性
|
||||
# 私聊处理
|
||||
domain = [('res_id', '=', channel_id),
|
||||
('model', '=', 'mail.channel'),
|
||||
('message_type', '!=', 'user_notification'),
|
||||
('parent_id', '=', False),
|
||||
('date', '>=', afterTime),
|
||||
('author_id', '=', self.env.user.partner_id.id)]
|
||||
messages = message_model.with_context(tz='UTC').search(domain, order="id desc", limit=15)
|
||||
# print('domain:',domain)
|
||||
# print('messages:',messages)
|
||||
for msg in messages:
|
||||
ai_msg = message_model.search([("res_id", "=", channel_id),
|
||||
('model', '=', msg.model),
|
||||
('parent_id', '=', msg.id),
|
||||
('author_id', '=', partner_chatgpt),
|
||||
('body', '!=', '<p>获取结果超时,请重新跟我聊聊。</p>')])
|
||||
if ai_msg:
|
||||
prompt.append("Human:%s\nAI:%s" % (
|
||||
msg.body.replace("<p>", "").replace("</p>", ""), ai_msg.body.replace("<p>", "").replace("</p>", "")))
|
||||
# print(msg.body.replace("<p>", "").replace("</p>", ""))
|
||||
# print(ai_msg.body.replace("<p>", "").replace("</p>", ""))
|
||||
else:
|
||||
_logger.error(f"not find for id:{str(msg.id)}")
|
||||
('model', '=', 'mail.channel'),
|
||||
('message_type', '!=', 'user_notification'),
|
||||
('parent_id', '!=', False),
|
||||
('author_id', '=', answer_id.id),
|
||||
('body', '!=', '<p>%s</p>' % _('Response Timeout, please speak again.'))]
|
||||
if self.channel_type in ['group', 'channel']:
|
||||
# 群聊增加时间限制,当前找所有人,不限制 author_id
|
||||
domain += [('date', '>=', afterTime)]
|
||||
ai_msg_list = message_model.with_context(tz='UTC').search(domain, order="id desc", limit=2)
|
||||
for ai_msg in ai_msg_list.sorted(key='id'):
|
||||
user_content = ai_msg.parent_id.body.replace("<p>", "").replace("</p>", "")
|
||||
ai_content = ai_msg.body.replace("<p>", "").replace("</p>", "")
|
||||
context_history.append({
|
||||
'role': 'user',
|
||||
'content': user_content,
|
||||
}, {
|
||||
'role': 'assistant',
|
||||
'content': ai_content,
|
||||
})
|
||||
return context_history
|
||||
|
||||
return '\n'.join(prompt[::-1])
|
||||
|
||||
def get_ai(self, ai, prompt, partner_name, channel, user_id, message):
|
||||
sender_id = message.create_uid.partner_id
|
||||
def get_ai_response(self, ai, messages, channel, user_id, message):
|
||||
author_id = message.create_uid.partner_id
|
||||
answer_id = user_id.partner_id
|
||||
res = ai.get_ai(prompt, sender_id, answer_id)
|
||||
res = ai.get_ai(messages, author_id, answer_id)
|
||||
if res:
|
||||
res = res.replace('\n', '<br/>')
|
||||
channel.with_user(user_id).message_post(body=res, message_type='comment', subtype_xmlid='mail.mt_comment', parent_id=message.id)
|
||||
@@ -55,21 +56,21 @@ class Channel(models.Model):
|
||||
def _notify_thread(self, message, msg_vals=False, **kwargs):
|
||||
rdata = super(Channel, self)._notify_thread(message, msg_vals=msg_vals, **kwargs)
|
||||
# print(f'rdata:{rdata}')
|
||||
to_partner_id = self.env['res.partner']
|
||||
answer_id = self.env['res.partner']
|
||||
user_id = self.env['res.users']
|
||||
author_id = msg_vals.get('author_id')
|
||||
ai = self.env['ai.robot']
|
||||
channel_type = self.channel_type
|
||||
if channel_type == 'chat':
|
||||
channel_partner_ids = self.channel_partner_ids
|
||||
to_partner_id = channel_partner_ids - message.author_id
|
||||
user_id = to_partner_id.mapped('user_ids').filtered(lambda r: r.gpt_id)[:1]
|
||||
if user_id and to_partner_id.gpt_id:
|
||||
answer_id = channel_partner_ids - message.author_id
|
||||
user_id = answer_id.mapped('user_ids').filtered(lambda r: r.gpt_id)[:1]
|
||||
if user_id and answer_id.gpt_id:
|
||||
gpt_policy = user_id.gpt_policy
|
||||
gpt_wl_users = user_id.gpt_wl_users
|
||||
is_allow = message.create_uid.id in gpt_wl_users.ids
|
||||
if gpt_policy == 'all' or (gpt_policy == 'limit' and is_allow):
|
||||
ai = to_partner_id.gpt_id
|
||||
ai = answer_id.gpt_id
|
||||
|
||||
elif channel_type in ['group', 'channel']:
|
||||
# partner_ids = @ ids
|
||||
@@ -82,16 +83,16 @@ class Channel(models.Model):
|
||||
gpt_policy = user_id.gpt_policy
|
||||
gpt_wl_users = user_id.gpt_wl_users
|
||||
is_allow = message.create_uid.id in gpt_wl_users.ids
|
||||
to_partner_id = user_id.partner_id
|
||||
answer_id = user_id.partner_id
|
||||
if gpt_policy == 'all' or (gpt_policy == 'limit' and is_allow):
|
||||
ai = user_id.gpt_id
|
||||
|
||||
chatgpt_channel_id = self.env.ref('app_chatgpt.channel_chatgpt')
|
||||
|
||||
prompt = msg_vals.get('body')
|
||||
msg = msg_vals.get('body')
|
||||
# print('prompt:', prompt)
|
||||
# print('-----')
|
||||
if not prompt:
|
||||
if not msg:
|
||||
return rdata
|
||||
# api_key = self.env['ir.config_parameter'].sudo().get_param('app_chatgpt.openapi_api_key')
|
||||
api_key = ''
|
||||
@@ -106,48 +107,36 @@ class Channel(models.Model):
|
||||
openapi_context_timeout = 600
|
||||
sync_config = self.env['ir.config_parameter'].sudo().get_param('app_chatgpt.openai_sync_config')
|
||||
openai.api_key = api_key
|
||||
partner_name = ''
|
||||
# print(msg_vals)
|
||||
# print(msg_vals.get('record_name', ''))
|
||||
# print('self.channel_type :',self.channel_type)
|
||||
if ai:
|
||||
if author_id != to_partner_id.id and self.channel_type == 'chat':
|
||||
_logger.info(f'私聊:author_id:{author_id},partner_chatgpt.id:{to_partner_id.id}')
|
||||
if author_id != answer_id.id and self.channel_type == 'chat':
|
||||
_logger.info(f'私聊:author_id:{author_id},partner_chatgpt.id:{answer_id.id}')
|
||||
try:
|
||||
channel = self.env[msg_vals.get('model')].browse(msg_vals.get('res_id'))
|
||||
# if ai_model not in ['gpt-3.5-turbo', 'gpt-3.5-turbo-0301']:
|
||||
prompt = self.get_openai_context(channel.id, to_partner_id.id, prompt, openapi_context_timeout)
|
||||
print(prompt)
|
||||
messages = [{"role": "user", "content": msg}]
|
||||
c_history = self.get_openai_context(channel.id, author_id, answer_id, openapi_context_timeout)
|
||||
if c_history:
|
||||
messages.insert(0, c_history)
|
||||
if sync_config == 'sync':
|
||||
self.get_ai(ai, prompt, partner_name, channel, user_id, message)
|
||||
self.get_ai_response(ai, messages, channel, user_id, message)
|
||||
else:
|
||||
self.with_delay().get_ai(ai, prompt, partner_name, channel, user_id, message)
|
||||
# res = ai.get_ai(prompt, partner_name)
|
||||
# res = res.replace('\n', '<br/>')
|
||||
# print('res:',res)
|
||||
# print('channel:',channel)
|
||||
# channel.with_user(user_id).message_post(body=res, message_type='comment',subtype_xmlid='mail.mt_comment', parent_id=message.id)
|
||||
# channel.with_user(user_chatgpt).message_post(body=res, message_type='notification', subtype_xmlid='mail.mt_comment')
|
||||
# channel.sudo().message_post(
|
||||
# body=res,
|
||||
# author_id=partner_chatgpt.id,
|
||||
# message_type="comment",
|
||||
# subtype_xmlid="mail.mt_comment",
|
||||
# )
|
||||
# self.with_user(user_chatgpt).message_post(body=res, message_type='comment', subtype_xmlid='mail.mt_comment')
|
||||
self.with_delay().get_ai_response(ai, messages, channel, user_id, message)
|
||||
except Exception as e:
|
||||
raise UserError(_(e))
|
||||
elif author_id != to_partner_id.id and msg_vals.get('model', '') == 'mail.channel' and msg_vals.get('res_id', 0) == chatgpt_channel_id.id:
|
||||
_logger.info(f'频道群聊:author_id:{author_id},partner_chatgpt.id:{to_partner_id.id}')
|
||||
elif author_id != answer_id.id and msg_vals.get('model', '') == 'mail.channel' and msg_vals.get('res_id', 0) == chatgpt_channel_id.id:
|
||||
_logger.info(f'频道群聊:author_id:{author_id},partner_chatgpt.id:{answer_id.id}')
|
||||
try:
|
||||
prompt = self.get_openai_context(chatgpt_channel_id.id, to_partner_id.id, prompt, openapi_context_timeout)
|
||||
messages = [{"role": "user", "content": msg}]
|
||||
c_history = self.get_openai_context(chatgpt_channel_id.id, author_id, answer_id, openapi_context_timeout)
|
||||
if c_history:
|
||||
messages.insert(0, c_history)
|
||||
if sync_config == 'sync':
|
||||
self.get_ai(ai, prompt, 'odoo', chatgpt_channel_id, user_id, message)
|
||||
self.get_ai_response(ai, messages, chatgpt_channel_id, user_id, message)
|
||||
else:
|
||||
self.with_delay().get_ai(ai, prompt, 'odoo', chatgpt_channel_id, user_id, message)
|
||||
# res = ai.get_ai(prompt, 'odoo')
|
||||
# res = res.replace('\n', '<br/>')
|
||||
# chatgpt_channel_id.with_user(user_id).message_post(body=res, message_type='comment', subtype_xmlid='mail.mt_comment', parent_id=message.id)
|
||||
self.with_delay().get_ai(ai, messages, chatgpt_channel_id, user_id, message)
|
||||
except Exception as e:
|
||||
raise UserError(_(e))
|
||||
|
||||
|
||||
Reference in New Issue
Block a user