api_server.py 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. #! /usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # vim:fenc=utf-8
  4. from calendar import prmonth
  5. import werkzeug.exceptions
  6. from flask import Flask, request, jsonify
  7. from datetime import datetime, timedelta
  8. from argparse import ArgumentParser
  9. from openai import OpenAI
  10. import chat_service
  11. import configs
  12. import json
  13. import logging_service
  14. import prompt_templates
  15. from dialogue_manager import DialogueManager
  16. from history_dialogue_service import HistoryDialogueService
  17. from user_manager import MySQLUserManager, MySQLUserRelationManager
  18. from user_profile_extractor import UserProfileExtractor
  19. app = Flask('agent_api_server')
  20. def wrap_response(code, msg=None, data=None):
  21. resp = {
  22. 'code': code,
  23. 'msg': msg
  24. }
  25. if code == 200 and not msg:
  26. resp['msg'] = 'success'
  27. if data:
  28. resp['data'] = data
  29. return jsonify(resp)
  30. @app.route('/api/listStaffs', methods=['GET'])
  31. def list_staffs():
  32. staff_data = app.user_relation_manager.list_staffs()
  33. return wrap_response(200, data=staff_data)
  34. @app.route('/api/getStaffProfile', methods=['GET'])
  35. def get_staff_profile():
  36. staff_id = request.args['staff_id']
  37. profile = app.user_manager.get_staff_profile(staff_id)
  38. if not profile:
  39. return wrap_response(404, msg='staff not found')
  40. else:
  41. return wrap_response(200, data=profile)
  42. @app.route('/api/getUserProfile', methods=['GET'])
  43. def get_user_profile():
  44. user_id = request.args['user_id']
  45. profile = app.user_manager.get_user_profile(user_id)
  46. if not profile:
  47. resp = {
  48. 'code': 404,
  49. 'msg': 'user not found'
  50. }
  51. else:
  52. resp = {
  53. 'code': 200,
  54. 'msg': 'success',
  55. 'data': profile
  56. }
  57. return jsonify(resp)
  58. @app.route('/api/listUsers', methods=['GET'])
  59. def list_users():
  60. user_name = request.args.get('user_name', None)
  61. user_union_id = request.args.get('user_union_id', None)
  62. if not user_name and not user_union_id:
  63. resp = {
  64. 'code': 400,
  65. 'msg': 'user_name or user_union_id is required'
  66. }
  67. return jsonify(resp)
  68. data = app.user_manager.list_users(user_name=user_name, user_union_id=user_union_id)
  69. return jsonify({'code': 200, 'data': data})
  70. @app.route('/api/getDialogueHistory', methods=['GET'])
  71. def get_dialogue_history():
  72. staff_id = request.args['staff_id']
  73. user_id = request.args['user_id']
  74. recent_minutes = int(request.args.get('recent_minutes', 1440))
  75. dialogue_history = app.history_dialogue_service.get_dialogue_history(staff_id, user_id, recent_minutes)
  76. return jsonify({'code': 200, 'data': dialogue_history})
  77. @app.route('/api/listModels', methods=['GET'])
  78. def list_models():
  79. models = [
  80. {
  81. 'model_type': 'openai_compatible',
  82. 'model_name': chat_service.VOLCENGINE_MODEL_DEEPSEEK_V3,
  83. 'display_name': 'DeepSeek V3 on 火山'
  84. },
  85. {
  86. 'model_type': 'openai_compatible',
  87. 'model_name': chat_service.VOLCENGINE_MODEL_DOUBAO_PRO_32K,
  88. 'display_name': '豆包Pro 32K'
  89. },
  90. {
  91. 'model_type': 'openai_compatible',
  92. 'model_name': chat_service.VOLCENGINE_MODEL_DOUBAO_PRO_1_5,
  93. 'display_name': '豆包Pro 1.5'
  94. },
  95. ]
  96. return wrap_response(200, data=models)
  97. @app.route('/api/listScenes', methods=['GET'])
  98. def list_scenes():
  99. scenes = [
  100. {'scene': 'greeting', 'display_name': '问候'},
  101. {'scene': 'chitchat', 'display_name': '闲聊'},
  102. {'scene': 'profile_extractor', 'display_name': '画像提取'}
  103. ]
  104. return wrap_response(200, data=scenes)
  105. @app.route('/api/getBasePrompt', methods=['GET'])
  106. def get_base_prompt():
  107. scene = request.args['scene']
  108. prompt_map = {
  109. 'greeting': prompt_templates.GENERAL_GREETING_PROMPT,
  110. 'chitchat': prompt_templates.CHITCHAT_PROMPT_COZE,
  111. 'profile_extractor': prompt_templates.USER_PROFILE_EXTRACT_PROMPT
  112. }
  113. model_map = {
  114. 'greeting': chat_service.VOLCENGINE_MODEL_DOUBAO_PRO_32K,
  115. 'chitchat': chat_service.VOLCENGINE_MODEL_DOUBAO_PRO_32K,
  116. 'profile_extractor': chat_service.VOLCENGINE_MODEL_DOUBAO_PRO_1_5
  117. }
  118. if scene not in prompt_map:
  119. return wrap_response(404, msg='scene not found')
  120. data = {
  121. 'model_name': model_map[scene],
  122. 'content': prompt_map[scene]
  123. }
  124. return wrap_response(200, data=data)
  125. def run_openai_chat(messages, model_name, **kwargs):
  126. volcengine_models = [
  127. chat_service.VOLCENGINE_MODEL_DOUBAO_PRO_32K,
  128. chat_service.VOLCENGINE_MODEL_DOUBAO_PRO_1_5,
  129. chat_service.VOLCENGINE_MODEL_DEEPSEEK_V3
  130. ]
  131. deepseek_models = [
  132. chat_service.DEEPSEEK_CHAT_MODEL,
  133. ]
  134. if model_name in volcengine_models:
  135. llm_client = OpenAI(api_key=chat_service.VOLCENGINE_API_TOKEN, base_url=chat_service.VOLCENGINE_BASE_URL)
  136. response = llm_client.chat.completions.create(
  137. messages=messages, model=model_name, **kwargs)
  138. return response
  139. elif model_name in deepseek_models:
  140. llm_client = OpenAI(api_key=chat_service.DEEPSEEK_API_TOKEN, base_url=chat_service.DEEPSEEK_BASE_URL)
  141. response = llm_client.chat.completions.create(
  142. messages=messages, model=model_name, temperature=1, top_p=0.7, max_tokens=1024)
  143. return response
  144. else:
  145. raise Exception('model not supported')
  146. def run_extractor_prompt(req_data):
  147. prompt = req_data['prompt']
  148. user_profile = req_data['user_profile']
  149. staff_profile = req_data['staff_profile']
  150. dialogue_history = req_data['dialogue_history']
  151. model_name = req_data['model_name']
  152. prompt_context = {**staff_profile,
  153. **user_profile,
  154. 'dialogue_history': UserProfileExtractor.compose_dialogue(dialogue_history)}
  155. prompt = prompt.format(**prompt_context)
  156. messages = [
  157. {"role": "system", "content": '你是一个专业的用户画像分析助手。'},
  158. {"role": "user", "content": prompt}
  159. ]
  160. tools = [UserProfileExtractor.get_extraction_function()]
  161. response = run_openai_chat(messages, model_name, tools=tools, temperature=0)
  162. tool_calls = response.choices[0].message.tool_calls
  163. if tool_calls:
  164. function_call = tool_calls[0]
  165. if function_call.function.name == 'update_user_profile':
  166. profile_info = json.loads(function_call.function.arguments)
  167. return {k: v for k, v in profile_info.items() if v}
  168. else:
  169. raise Exception("llm does not return tool_calls")
  170. def run_chat_prompt(req_data):
  171. prompt = req_data['prompt']
  172. staff_profile = req_data['staff_profile']
  173. user_profile = req_data['user_profile']
  174. dialogue_history = req_data['dialogue_history']
  175. model_name = req_data['model_name']
  176. current_timestamp = req_data['current_timestamp'] / 1000
  177. prompt_context = {**staff_profile, **user_profile}
  178. current_hour = datetime.fromtimestamp(current_timestamp).hour
  179. prompt_context['last_interaction_interval'] = 0
  180. prompt_context['current_time_period'] = DialogueManager.get_time_context(current_hour)
  181. prompt_context['current_hour'] = current_hour
  182. prompt_context['if_first_interaction'] = False if dialogue_history else True
  183. current_time_str = datetime.fromtimestamp(current_timestamp).strftime('%Y-%m-%d %H:%M:%S')
  184. system_prompt = {
  185. 'role': 'system',
  186. 'content': prompt.format(**prompt_context)
  187. }
  188. messages = [system_prompt]
  189. messages.extend(DialogueManager.compose_chat_messages_openai_compatible(dialogue_history, current_time_str))
  190. return run_openai_chat(messages, model_name, temperature=1, top_p=0.7, max_tokens=1024)
  191. @app.route('/api/runPrompt', methods=['POST'])
  192. def run_prompt():
  193. try:
  194. req_data = request.json
  195. scene = req_data['scene']
  196. if scene == 'profile_extractor':
  197. response = run_extractor_prompt(req_data)
  198. return wrap_response(200, data=response)
  199. else:
  200. response = run_chat_prompt(req_data)
  201. return wrap_response(200, data=response.choices[0].message.content)
  202. except Exception as e:
  203. return wrap_response(500, msg='Error: {}'.format(e))
  204. @app.errorhandler(werkzeug.exceptions.BadRequest)
  205. def handle_bad_request(e):
  206. return wrap_response(400, msg='Bad Request: {}'.format(e.description))
  207. if __name__ == '__main__':
  208. parser = ArgumentParser()
  209. parser.add_argument('--prod', action='store_true')
  210. parser.add_argument('--host', default='127.0.0.1')
  211. parser.add_argument('--port', type=int, default=8083)
  212. args = parser.parse_args()
  213. config = configs.get()
  214. logging_service.setup_root_logger(logfile_name='agent_api_server.log')
  215. user_db_config = config['storage']['user']
  216. staff_db_config = config['storage']['staff']
  217. user_manager = MySQLUserManager(user_db_config['mysql'], user_db_config['table'], staff_db_config['table'])
  218. app.user_manager = user_manager
  219. wecom_db_config = config['storage']['user_relation']
  220. user_relation_manager = MySQLUserRelationManager(
  221. user_db_config['mysql'], wecom_db_config['mysql'],
  222. config['storage']['staff']['table'],
  223. user_db_config['table'],
  224. wecom_db_config['table']['staff'],
  225. wecom_db_config['table']['relation'],
  226. wecom_db_config['table']['user']
  227. )
  228. app.user_relation_manager = user_relation_manager
  229. app.history_dialogue_service = HistoryDialogueService(
  230. config['storage']['history_dialogue']['api_base_url']
  231. )
  232. app.run(debug=not args.prod, host=args.host, port=args.port)