message_push_agent.py 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127
  1. from typing import Optional, List, Dict
  2. from pqai_agent.agents.simple_chat_agent import SimpleOpenAICompatibleChatAgent
  3. from pqai_agent.chat_service import VOLCENGINE_MODEL_DEEPSEEK_V3
  4. from pqai_agent.logging_service import logger
  5. from pqai_agent.toolkit.function_tool import FunctionTool
  6. from pqai_agent.toolkit.image_describer import ImageDescriber
  7. from pqai_agent.toolkit.message_notifier import MessageNotifier
  8. DEFAULT_SYSTEM_PROMPT = '''
  9. <基本设定>
  10. 你是一位熟悉中老年用户交流习惯的微信客服Agent。
  11. 你擅长以下事项:
  12. * 倾听、引导和共情,在对话中自然促进用户互动
  13. * 理解中老年人的典型情感需求、对话习惯
  14. * 分析用户的微信名、头像,以适合的话术与用户建立联系
  15. 你的工作方法论:
  16. * 分析用户请求以确定核心需求
  17. * 为完成任务制定结构化的计划
  18. </基本设定>
  19. <语言设定>
  20. * 默认的工作语言:中文
  21. * 如果用户指定使用其它语言,则将其作为工作语言
  22. * 所有的思考和回答都要用工作语言
  23. </语言设定>
  24. <通用话术>
  25. * 时间锚点:"早上好!今天阳光这么好,您打算做点什么让自己开心的事呀?"
  26. * 轻量求助:"听说最近好多长辈在学手机拍照技巧,您有没有什么实用小窍门能教教我呀?"
  27. * 正向引导:"这个季节最适合喝养生茶啦,您平时喜欢枸杞红枣茶还是菊花茶呀?"
  28. </通用话术>
  29. <心理学技巧>
  30. * 怀旧效应:可以用"当年/以前"触发美好回忆
  31. * 具象化提问:避免抽象问题
  32. * 正向反馈圈:在后续对话中重复用户的关键词
  33. </心理学技巧>
  34. <风险规避原则>
  35. * 避免过度打扰和重复:注意分析历史对话
  36. * 避免过度解读
  37. * 文化适配:注意不同地域的用户文化差异
  38. * 准确性要求:不要使用虚构的信息
  39. </风险规避原则>
  40. <agent_loop>
  41. You are operating in an agent loop, iteratively completing tasks through these steps:
  42. 1. Analyze Events: Understand user needs and current state through event stream, focusing on latest user messages and execution results
  43. 2. Select Tools: Choose next tool call based on current state, task planning, relevant knowledge and available data APIs
  44. 3. Wait for Execution: Selected tool action will be executed by sandbox environment with new observations added to event stream
  45. 4. Iterate: Choose only one tool call per iteration, patiently repeat above steps until task completion
  46. 5. Submit Results: Send results to user via message tools, providing deliverables and related files as message attachments
  47. 6. Enter Standby: Enter idle state when all tasks are completed or user explicitly requests to stop, and wait for new tasks
  48. </agent_loop>
  49. '''
  50. QUERY_PROMPT_TEMPLATE = """现在,请通过多步思考,选择合适的方法向一位用户发起问候。
  51. # 已知用户的信息
  52. 用户信息:
  53. - 姓名:{name}
  54. - 头像:{avatar}
  55. - 偏好的称呼:{preferred_nickname}
  56. - 年龄:{age}
  57. - 地区:{region}
  58. - 健康状况:{health_conditions}
  59. - 用药信息:{medications}
  60. - 兴趣爱好:{interests}
  61. # 已知过去的对话
  62. {dialogue_history}
  63. # 当前上下文信息
  64. 时间:{current_datetime}
  65. 注意对话信息的格式为: [角色][时间]对话内容
  66. 注意一定要分析对话信息中的时间,避免和当前时间段不符的内容!注意一定要结合历史的对话情况进行分析和问候方式的选择!
  67. 可以使用analyse_image分析用户头像。
  68. 必须使用message_notify_user发送最终的问候内容,调用message_notify_user时不要传入除了问候内容外的其它任何信息。
  69. Please think step by step.
  70. """
  71. class MessagePushAgent(SimpleOpenAICompatibleChatAgent):
  72. """A specialized agent for message push tasks."""
  73. def __init__(self, model: Optional[str] = VOLCENGINE_MODEL_DEEPSEEK_V3, system_prompt: Optional[str] = None,
  74. tools: Optional[List[FunctionTool]] = None,
  75. generate_cfg: Optional[dict] = None, max_run_step: Optional[int] = None):
  76. system_prompt = system_prompt or DEFAULT_SYSTEM_PROMPT
  77. tools = tools or []
  78. tools = tools.copy()
  79. tools.extend([
  80. *ImageDescriber().get_tools(),
  81. *MessageNotifier().get_tools()
  82. ])
  83. super().__init__(model, system_prompt, tools, generate_cfg, max_run_step)
  84. def generate_message(self, user_profile: Dict, context: Dict, dialogue_history: List[Dict]) -> str:
  85. query = QUERY_PROMPT_TEMPLATE.format(**user_profile, **context, dialogue_history=dialogue_history)
  86. self.run(query)
  87. for tool_call in reversed(self.tool_call_records):
  88. if tool_call['name'] == MessageNotifier.message_notify_user.__name__:
  89. return tool_call['arguments']['message']
  90. return ''
  91. if __name__ == '__main__':
  92. import pqai_agent.logging_service
  93. pqai_agent.logging_service.setup_root_logger()
  94. agent = MessagePushAgent()
  95. test_user_profile = {
  96. 'name': '薛岱月',
  97. 'avatar': 'http://wx.qlogo.cn/mmhead/Q3auHgzwzM5glpnBtDUianJErYf9AQsptLM3N78xP3sOR8SSibsG35HQ/0',
  98. 'preferred_nickname': '月哥',
  99. 'age': 65,
  100. 'region': '北京',
  101. 'health_conditions': '高血压',
  102. 'medications': ['降压药'],
  103. 'interests': ['钓鱼', '旅游']
  104. }
  105. test_context = {
  106. "current_datetime": "2025-05-13 08:00:00",
  107. }
  108. response = agent.generate_message(test_user_profile, test_context, [])
  109. print(response)