user_profile_extractor.py 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  1. #! /usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # vim:fenc=utf-8
  4. import json
  5. from typing import Dict, Any, Optional, List
  6. import chat_service
  7. import configs
  8. from prompt_templates import USER_PROFILE_EXTRACT_PROMPT
  9. from openai import OpenAI
  10. from logging_service import logger
  11. class UserProfileExtractor:
  12. def __init__(self):
  13. self.llm_client = OpenAI(
  14. api_key=chat_service.VOLCENGINE_API_TOKEN,
  15. base_url=chat_service.VOLCENGINE_BASE_URL
  16. )
  17. self.model_name = chat_service.VOLCENGINE_MODEL_DEEPSEEK_V3
  18. def get_extraction_function(self) -> Dict:
  19. """
  20. 定义用于用户画像信息提取的Function Calling函数
  21. """
  22. return {
  23. "type": "function",
  24. "function": {
  25. "name": "update_user_profile",
  26. "description": "从用户对话中提取并更新用户的个人信息",
  27. "parameters": {
  28. "type": "object",
  29. "properties": {
  30. "name": {
  31. "type": "string",
  32. "description": "用户的姓名,如果能够准确识别"
  33. },
  34. "preferred_nickname": {
  35. "type": "string",
  36. "description": "用户希望对其的称呼,如果用户明确提到"
  37. },
  38. "gender": {
  39. "type": "string",
  40. "description": "用户的性别,男或女,如果不能准确识别则为未知"
  41. },
  42. "age": {
  43. "type": "integer",
  44. "description": "用户的年龄,如果能够准确识别"
  45. },
  46. "region": {
  47. "type": "string",
  48. "description": "用户常驻的地区,不是用户临时所在地"
  49. },
  50. "interests": {
  51. "type": "array",
  52. "items": {"type": "string"},
  53. "description": "用户提到的自己的兴趣爱好"
  54. },
  55. "health_conditions": {
  56. "type": "array",
  57. "items": {"type": "string"},
  58. "description": "用户提及的健康状况"
  59. },
  60. "interaction_frequency": {
  61. "type": "string",
  62. "description": "用户期望的交互频率。每2天联系小于1次为low,每天联系1次为medium,不再联系为stopped"
  63. }
  64. },
  65. "required": []
  66. }
  67. }
  68. }
  69. def generate_extraction_prompt(self, user_profile: Dict, dialogue_history: List[Dict]) -> str:
  70. """
  71. 生成用于信息提取的系统提示词
  72. """
  73. context = user_profile.copy()
  74. context['dialogue_history'] = self.compose_dialogue(dialogue_history)
  75. return USER_PROFILE_EXTRACT_PROMPT.format(**context)
  76. @staticmethod
  77. def compose_dialogue(dialogue: List[Dict]) -> str:
  78. role_map = {'user': '用户', 'assistant': '客服'}
  79. messages = []
  80. for msg in dialogue:
  81. if not msg['content']:
  82. continue
  83. if msg['role'] not in role_map:
  84. continue
  85. messages.append('[{}] {}'.format(role_map[msg['role']], msg['content']))
  86. return '\n'.join(messages)
  87. def extract_profile_info(self, user_profile, dialogue_history: List[Dict]) -> Optional[Dict]:
  88. """
  89. 使用Function Calling提取用户画像信息
  90. """
  91. if configs.get().get('debug_flags', {}).get('disable_llm_api_call', False):
  92. return None
  93. try:
  94. logger.debug("try to extract profile from message: {}".format(dialogue_history))
  95. prompt = self.generate_extraction_prompt(user_profile, dialogue_history)
  96. response = self.llm_client.chat.completions.create(
  97. model=self.model_name,
  98. messages=[
  99. {"role": "system", "content": '你是一个专业的用户画像分析助手。'},
  100. {"role": "user", "content": prompt}
  101. ],
  102. tools=[self.get_extraction_function()],
  103. temperature=0
  104. )
  105. # 解析Function Call的参数
  106. tool_calls = response.choices[0].message.tool_calls
  107. logger.debug(response)
  108. if tool_calls:
  109. function_call = tool_calls[0]
  110. if function_call.function.name == 'update_user_profile':
  111. try:
  112. profile_info = json.loads(function_call.function.arguments)
  113. return {k: v for k, v in profile_info.items() if v}
  114. except json.JSONDecodeError:
  115. logger.error("无法解析提取的用户信息")
  116. return None
  117. except Exception as e:
  118. logger.error(f"用户画像提取出错: {e}")
  119. return None
  120. def merge_profile_info(self, existing_profile: Dict, new_info: Dict) -> Dict:
  121. """
  122. 合并新提取的用户信息到现有资料
  123. """
  124. merged_profile = existing_profile.copy()
  125. merged_profile.update(new_info)
  126. return merged_profile
  127. if __name__ == '__main__':
  128. extractor = UserProfileExtractor()
  129. current_profile = {
  130. 'name': '',
  131. 'preferred_nickname': '李叔',
  132. "gender": "男",
  133. 'age': 0,
  134. 'region': '北京',
  135. 'health_conditions': [],
  136. 'medications': [],
  137. 'interests': [],
  138. 'interaction_frequency': 'medium'
  139. }
  140. message = "没有任何问题放心,不会骚扰你了,再见"
  141. resp = extractor.extract_profile_info(current_profile, message)
  142. print(resp)
  143. message = "好的,孩子,我是老李头,今年68啦,住在北京海淀区。平时喜欢在微信上跟老伙伴们聊聊养生、下下象棋,偶尔也跟年轻人学学新鲜事儿。\n" \
  144. "你叫我李叔就行,有啥事儿咱们慢慢聊啊\n" \
  145. "哎,今儿个天气不错啊,我刚才还去楼下小公园溜达了一圈儿。碰到几个老伙计在打太极,我也跟着比划了两下,这老胳膊老腿的,原来老不舒服,活动活动舒坦多了!\n" \
  146. "你吃饭了没?我们这儿中午吃的打卤面,老伴儿做的,香得很!这人老了就爱念叨些家长里短的,你可别嫌我啰嗦啊。\n" \
  147. "对了,最近我孙子教我发语音,比打字方便多啦!就是有时候一激动,说话声音太大,把手机都给震得嗡嗡响\n"
  148. resp = extractor.extract_profile_info(current_profile, message)
  149. print(resp)
  150. print(extractor.merge_profile_info(current_profile, resp))
  151. current_profile = {
  152. 'name': '李老头',
  153. 'preferred_nickname': '李叔',
  154. "gender": "男",
  155. 'age': 68,
  156. 'region': '北京市海淀区',
  157. 'health_conditions': [],
  158. 'medications': [],
  159. 'interests': ['养生', '下象棋']
  160. }
  161. resp = extractor.extract_profile_info(current_profile, message)
  162. print(resp)
  163. print(extractor.merge_profile_info(current_profile, resp))