Forráskód Böngészése

Add response_type_detector

StrayWarrior 6 napja
szülő
commit
1c2db5e796
2 módosított fájl, 88 hozzáadás és 0 törlés
  1. 35 0
      prompt_templates.py
  2. 53 0
      response_type_detector.py

+ 35 - 0
prompt_templates.py

@@ -207,3 +207,38 @@ USER_PROFILE_EXTRACT_PROMPT = """
 
 请使用update_user_profile函数返回需要更新的信息,注意不要返回不需要更新的信息!
 """
+
+RESPONSE_TYPE_DETECT_PROMPT = """
+# 角色设定
+* 你是一位熟悉中老年用户交流习惯的智能客服,能够精准理解用户需求,提供专业、实用且有温度的建议。
+* 你擅长倾听、引导和共情,在对话中自然促进用户互动。
+* 你正在向用户发送一条聊天消息。
+
+# 任务目标
+* 根据历史对话判断,当前消息是否需要以语音的形式发送
+
+# 规则和注意事项
+* 只有用户明确希望使用语音形式回复时才应该选择语音
+* 注意对话中包含的时间!注意时间流逝和情境切换!判断合适的回复方式!
+
+# 输入格式
+## 历史对话格式
+[用户] [时间] 内容...
+[客服] [时间] 内容...
+[用户] [时间] 内容...
+
+## 即将发送的消息格式
+[时间] 内容...
+
+# 输出格式要求
+直接返回需要发送的消息形式,从以下选项中选择一个:
+* 文本
+* 语音
+不要输出任何其它内容!不要输出任何符号!
+
+# 历史对话
+{dialogue_history}
+
+# 即将发送的消息
+{message}
+"""

+ 53 - 0
response_type_detector.py

@@ -0,0 +1,53 @@
+#! /usr/bin/env python
+# -*- coding: utf-8 -*-
+# vim:fenc=utf-8
+
+from openai import OpenAI
+from datetime import datetime
+import chat_service
+import prompt_templates
+from dialogue_manager import DialogueManager
+from logging_service import logger
+from message import MessageType
+
+
+class ResponseTypeDetector:
+    @staticmethod
+    def compose_dialogue(dialogue):
+        role_map = {'user': '用户', 'assistant': '客服'}
+        messages = []
+        for msg in dialogue:
+            if not msg['content']:
+                continue
+            if msg['role'] not in role_map:
+                continue
+            fmt_time = datetime.fromtimestamp(msg['timestamp'] / 1000).strftime('%Y-%m-%d %H:%M:%S')
+            messages.append('[{}] [{}] {}'.format(role_map[msg['role']], fmt_time, msg['content']))
+        return '\n'.join(messages)
+
+    def __init__(self):
+        self.llm_client = OpenAI(
+            api_key=chat_service.VOLCENGINE_API_TOKEN,
+            base_url=chat_service.VOLCENGINE_BASE_URL
+        )
+        self.model_name = chat_service.VOLCENGINE_MODEL_DOUBAO_PRO_1_5
+
+    def detect_type(self, dialogue_history, next_message):
+        composed_dialogue = self.compose_dialogue(dialogue_history)
+        next_message = DialogueManager.format_dialogue_content(next_message)
+        prompt = prompt_templates.RESPONSE_TYPE_DETECT_PROMPT.format(
+            dialogue_history=composed_dialogue,
+            message=next_message
+        )
+        # logger.debug(prompt)
+        messages = [
+            {'role': 'system', 'content': '你是一个专业的智能助手'},
+            {'role': 'user', 'content': prompt}
+        ]
+        response = self.llm_client.chat.completions.create(messages=messages, model=self.model_name,
+                                                           temperature=0.2, max_tokens=128)
+        response = response.choices[0].message.content.strip()
+        if response == '语音':
+            return MessageType.VOICE
+        else:
+            return MessageType.TEXT