citu_app.py 108 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710
  1. # 给dataops 对话助手返回结果
  2. from vanna.flask import VannaFlaskApp
  3. from core.vanna_llm_factory import create_vanna_instance
  4. from flask import request, jsonify
  5. import pandas as pd
  6. import common.result as result
  7. from datetime import datetime, timedelta
  8. from common.session_aware_cache import WebSessionAwareMemoryCache
  9. from app_config import API_MAX_RETURN_ROWS, ENABLE_RESULT_SUMMARY
  10. import re
  11. import chainlit as cl
  12. import json
  13. from flask import session # 添加session导入
  14. import sqlparse # 用于SQL语法检查
  15. from common.redis_conversation_manager import RedisConversationManager # 添加Redis对话管理器导入
  16. from common.qa_feedback_manager import QAFeedbackManager
  17. from common.result import success_response, bad_request_response, not_found_response, internal_error_response
  18. from common.result import ( # 统一导入所有需要的响应函数
  19. bad_request_response, service_unavailable_response,
  20. agent_success_response, agent_error_response,
  21. internal_error_response, success_response,
  22. validation_failed_response
  23. )
  24. from app_config import ( # 添加Redis相关配置导入
  25. USER_MAX_CONVERSATIONS,
  26. CONVERSATION_CONTEXT_COUNT,
  27. DEFAULT_ANONYMOUS_USER,
  28. ENABLE_QUESTION_ANSWER_CACHE
  29. )
  30. # 设置默认的最大返回行数
  31. DEFAULT_MAX_RETURN_ROWS = 200
  32. MAX_RETURN_ROWS = API_MAX_RETURN_ROWS if API_MAX_RETURN_ROWS is not None else DEFAULT_MAX_RETURN_ROWS
  33. vn = create_vanna_instance()
  34. # 创建带时间戳的缓存
  35. timestamped_cache = WebSessionAwareMemoryCache()
  36. # 实例化 VannaFlaskApp,使用自定义缓存
  37. app = VannaFlaskApp(
  38. vn,
  39. cache=timestamped_cache, # 使用带时间戳的缓存
  40. title="辞图智能数据问答平台",
  41. logo = "https://www.citupro.com/img/logo-black-2.png",
  42. subtitle="让 AI 为你写 SQL",
  43. chart=False,
  44. allow_llm_to_see_data=True,
  45. ask_results_correct=True,
  46. followup_questions=True,
  47. debug=True
  48. )
  49. # 创建Redis对话管理器实例
  50. redis_conversation_manager = RedisConversationManager()
  51. # 修改ask接口,支持前端传递session_id
  52. @app.flask_app.route('/api/v0/ask', methods=['POST'])
  53. def ask_full():
  54. req = request.get_json(force=True)
  55. question = req.get("question", None)
  56. browser_session_id = req.get("session_id", None) # 前端传递的会话ID
  57. if not question:
  58. from common.result import bad_request_response
  59. return jsonify(bad_request_response(
  60. response_text="缺少必需参数:question",
  61. missing_params=["question"]
  62. )), 400
  63. # 如果使用WebSessionAwareMemoryCache
  64. if hasattr(app.cache, 'generate_id_with_browser_session') and browser_session_id:
  65. # 这里需要修改vanna的ask方法来支持传递session_id
  66. # 或者预先调用generate_id来建立会话关联
  67. conversation_id = app.cache.generate_id_with_browser_session(
  68. question=question,
  69. browser_session_id=browser_session_id
  70. )
  71. try:
  72. sql, df, _ = vn.ask(
  73. question=question,
  74. print_results=False,
  75. visualize=False,
  76. allow_llm_to_see_data=True
  77. )
  78. # 关键:检查是否有LLM解释性文本(无法生成SQL的情况)
  79. if sql is None and hasattr(vn, 'last_llm_explanation') and vn.last_llm_explanation:
  80. # 在解释性文本末尾添加提示语
  81. explanation_message = vn.last_llm_explanation + "请尝试提问其它问题。"
  82. # 使用标准化错误响应
  83. from common.result import validation_failed_response
  84. return jsonify(validation_failed_response(
  85. response_text=explanation_message
  86. )), 422 # 修改HTTP状态码为422
  87. # 如果sql为None但没有解释性文本,返回通用错误
  88. if sql is None:
  89. from common.result import validation_failed_response
  90. return jsonify(validation_failed_response(
  91. response_text="无法生成SQL查询,请检查问题描述或数据表结构"
  92. )), 422
  93. # 处理返回数据 - 使用新的query_result结构
  94. query_result = {
  95. "rows": [],
  96. "columns": [],
  97. "row_count": 0,
  98. "is_limited": False,
  99. "total_row_count": 0
  100. }
  101. summary = None
  102. if isinstance(df, pd.DataFrame):
  103. query_result["columns"] = list(df.columns)
  104. if not df.empty:
  105. total_rows = len(df)
  106. limited_df = df.head(MAX_RETURN_ROWS)
  107. query_result["rows"] = limited_df.to_dict(orient="records")
  108. query_result["row_count"] = len(limited_df)
  109. query_result["total_row_count"] = total_rows
  110. query_result["is_limited"] = total_rows > MAX_RETURN_ROWS
  111. # 生成数据摘要(可通过配置控制,仅在有数据时生成)
  112. if ENABLE_RESULT_SUMMARY:
  113. try:
  114. summary = vn.generate_summary(question=question, df=df)
  115. print(f"[INFO] 成功生成摘要: {summary}")
  116. except Exception as e:
  117. print(f"[WARNING] 生成摘要失败: {str(e)}")
  118. summary = None
  119. # 构建返回数据
  120. response_data = {
  121. "sql": sql,
  122. "query_result": query_result,
  123. "conversation_id": conversation_id if 'conversation_id' in locals() else None,
  124. "session_id": browser_session_id
  125. }
  126. # 添加摘要(如果启用且生成成功)
  127. if ENABLE_RESULT_SUMMARY and summary is not None:
  128. response_data["summary"] = summary
  129. response_data["response"] = summary # 同时添加response字段
  130. from common.result import success_response
  131. return jsonify(success_response(
  132. response_text="查询执行完成" if summary is None else None,
  133. data=response_data
  134. ))
  135. except Exception as e:
  136. print(f"[ERROR] ask_full执行失败: {str(e)}")
  137. # 即使发生异常,也检查是否有业务层面的解释
  138. if hasattr(vn, 'last_llm_explanation') and vn.last_llm_explanation:
  139. # 在解释性文本末尾添加提示语
  140. explanation_message = vn.last_llm_explanation + "请尝试提问其它问题。"
  141. from common.result import validation_failed_response
  142. return jsonify(validation_failed_response(
  143. response_text=explanation_message
  144. )), 422
  145. else:
  146. # 技术错误,使用500错误码
  147. from common.result import internal_error_response
  148. return jsonify(internal_error_response(
  149. response_text="查询处理失败,请稍后重试"
  150. )), 500
  151. @app.flask_app.route('/api/v0/citu_run_sql', methods=['POST'])
  152. def citu_run_sql():
  153. req = request.get_json(force=True)
  154. sql = req.get('sql')
  155. if not sql:
  156. from common.result import bad_request_response
  157. return jsonify(bad_request_response(
  158. response_text="缺少必需参数:sql",
  159. missing_params=["sql"]
  160. )), 400
  161. try:
  162. df = vn.run_sql(sql)
  163. # 处理返回数据 - 使用新的query_result结构
  164. query_result = {
  165. "rows": [],
  166. "columns": [],
  167. "row_count": 0,
  168. "is_limited": False,
  169. "total_row_count": 0
  170. }
  171. if isinstance(df, pd.DataFrame):
  172. query_result["columns"] = list(df.columns)
  173. if not df.empty:
  174. total_rows = len(df)
  175. limited_df = df.head(MAX_RETURN_ROWS)
  176. query_result["rows"] = limited_df.to_dict(orient="records")
  177. query_result["row_count"] = len(limited_df)
  178. query_result["total_row_count"] = total_rows
  179. query_result["is_limited"] = total_rows > MAX_RETURN_ROWS
  180. from common.result import success_response
  181. return jsonify(success_response(
  182. response_text=f"SQL执行完成,共返回 {query_result['total_row_count']} 条记录" +
  183. (f",已限制显示前 {MAX_RETURN_ROWS} 条" if query_result["is_limited"] else ""),
  184. data={
  185. "sql": sql,
  186. "query_result": query_result
  187. }
  188. ))
  189. except Exception as e:
  190. print(f"[ERROR] citu_run_sql执行失败: {str(e)}")
  191. from common.result import internal_error_response
  192. return jsonify(internal_error_response(
  193. response_text=f"SQL执行失败,请检查SQL语句是否正确"
  194. )), 500
  195. @app.flask_app.route('/api/v0/ask_cached', methods=['POST'])
  196. def ask_cached():
  197. """
  198. 带缓存功能的智能查询接口
  199. 支持会话管理和结果缓存,提高查询效率
  200. """
  201. req = request.get_json(force=True)
  202. question = req.get("question", None)
  203. browser_session_id = req.get("session_id", None)
  204. if not question:
  205. from common.result import bad_request_response
  206. return jsonify(bad_request_response(
  207. response_text="缺少必需参数:question",
  208. missing_params=["question"]
  209. )), 400
  210. try:
  211. # 生成conversation_id
  212. # 调试:查看generate_id的实际行为
  213. print(f"[DEBUG] 输入问题: '{question}'")
  214. conversation_id = app.cache.generate_id(question=question)
  215. print(f"[DEBUG] 生成的conversation_id: {conversation_id}")
  216. # 再次用相同问题测试
  217. conversation_id2 = app.cache.generate_id(question=question)
  218. print(f"[DEBUG] 再次生成的conversation_id: {conversation_id2}")
  219. print(f"[DEBUG] 两次ID是否相同: {conversation_id == conversation_id2}")
  220. # 检查缓存
  221. cached_sql = app.cache.get(id=conversation_id, field="sql")
  222. if cached_sql is not None:
  223. # 缓存命中
  224. print(f"[CACHE HIT] 使用缓存结果: {conversation_id}")
  225. sql = cached_sql
  226. df = app.cache.get(id=conversation_id, field="df")
  227. summary = app.cache.get(id=conversation_id, field="summary")
  228. else:
  229. # 缓存未命中,执行新查询
  230. print(f"[CACHE MISS] 执行新查询: {conversation_id}")
  231. sql, df, _ = vn.ask(
  232. question=question,
  233. print_results=False,
  234. visualize=False,
  235. allow_llm_to_see_data=True
  236. )
  237. # 检查是否有LLM解释性文本(无法生成SQL的情况)
  238. if sql is None and hasattr(vn, 'last_llm_explanation') and vn.last_llm_explanation:
  239. # 在解释性文本末尾添加提示语
  240. explanation_message = vn.last_llm_explanation + "请尝试用其它方式提问。"
  241. from common.result import validation_failed_response
  242. return jsonify(validation_failed_response(
  243. response_text=explanation_message
  244. )), 422
  245. # 如果sql为None但没有解释性文本,返回通用错误
  246. if sql is None:
  247. from common.result import validation_failed_response
  248. return jsonify(validation_failed_response(
  249. response_text="无法生成SQL查询,请检查问题描述或数据表结构"
  250. )), 422
  251. # 缓存结果
  252. app.cache.set(id=conversation_id, field="question", value=question)
  253. app.cache.set(id=conversation_id, field="sql", value=sql)
  254. app.cache.set(id=conversation_id, field="df", value=df)
  255. # 生成并缓存摘要(可通过配置控制,仅在有数据时生成)
  256. summary = None
  257. if ENABLE_RESULT_SUMMARY and isinstance(df, pd.DataFrame) and not df.empty:
  258. try:
  259. summary = vn.generate_summary(question=question, df=df)
  260. print(f"[INFO] 成功生成摘要: {summary}")
  261. except Exception as e:
  262. print(f"[WARNING] 生成摘要失败: {str(e)}")
  263. summary = None
  264. app.cache.set(id=conversation_id, field="summary", value=summary)
  265. # 处理返回数据 - 使用新的query_result结构
  266. query_result = {
  267. "rows": [],
  268. "columns": [],
  269. "row_count": 0,
  270. "is_limited": False,
  271. "total_row_count": 0
  272. }
  273. if isinstance(df, pd.DataFrame):
  274. query_result["columns"] = list(df.columns)
  275. if not df.empty:
  276. total_rows = len(df)
  277. limited_df = df.head(MAX_RETURN_ROWS)
  278. query_result["rows"] = limited_df.to_dict(orient="records")
  279. query_result["row_count"] = len(limited_df)
  280. query_result["total_row_count"] = total_rows
  281. query_result["is_limited"] = total_rows > MAX_RETURN_ROWS
  282. # 构建返回数据
  283. response_data = {
  284. "sql": sql,
  285. "query_result": query_result,
  286. "conversation_id": conversation_id,
  287. "session_id": browser_session_id,
  288. "cached": cached_sql is not None # 标识是否来自缓存
  289. }
  290. # 添加摘要(如果启用且生成成功)
  291. if ENABLE_RESULT_SUMMARY and summary is not None:
  292. response_data["summary"] = summary
  293. response_data["response"] = summary # 同时添加response字段
  294. from common.result import success_response
  295. return jsonify(success_response(
  296. response_text="查询执行完成" if summary is None else None,
  297. data=response_data
  298. ))
  299. except Exception as e:
  300. print(f"[ERROR] ask_cached执行失败: {str(e)}")
  301. from common.result import internal_error_response
  302. return jsonify(internal_error_response(
  303. response_text="查询处理失败,请稍后重试"
  304. )), 500
  305. @app.flask_app.route('/api/v0/citu_train_question_sql', methods=['POST'])
  306. def citu_train_question_sql():
  307. """
  308. 训练问题-SQL对接口
  309. 此API将接收的question/sql pair写入到training库中,用于训练和改进AI模型。
  310. 支持仅传入SQL或同时传入问题和SQL进行训练。
  311. Args:
  312. question (str, optional): 用户问题
  313. sql (str, required): 对应的SQL查询语句
  314. Returns:
  315. JSON: 包含训练ID和成功消息的响应
  316. """
  317. try:
  318. req = request.get_json(force=True)
  319. question = req.get('question')
  320. sql = req.get('sql')
  321. if not sql:
  322. from common.result import bad_request_response
  323. return jsonify(bad_request_response(
  324. response_text="缺少必需参数:sql",
  325. missing_params=["sql"]
  326. )), 400
  327. # 正确的调用方式:同时传递question和sql
  328. if question:
  329. training_id = vn.train(question=question, sql=sql)
  330. print(f"训练成功,训练ID为:{training_id},问题:{question},SQL:{sql}")
  331. else:
  332. training_id = vn.train(sql=sql)
  333. print(f"训练成功,训练ID为:{training_id},SQL:{sql}")
  334. from common.result import success_response
  335. return jsonify(success_response(
  336. response_text="问题-SQL对训练成功",
  337. data={
  338. "training_id": training_id,
  339. "message": "Question-SQL pair trained successfully"
  340. }
  341. ))
  342. except Exception as e:
  343. from common.result import internal_error_response
  344. return jsonify(internal_error_response(
  345. response_text="训练失败,请稍后重试"
  346. )), 500
  347. # ============ LangGraph Agent 集成 ============
  348. # 全局Agent实例(单例模式)
  349. citu_langraph_agent = None
  350. def get_citu_langraph_agent():
  351. """获取LangGraph Agent实例(懒加载)"""
  352. global citu_langraph_agent
  353. if citu_langraph_agent is None:
  354. try:
  355. from agent.citu_agent import CituLangGraphAgent
  356. print("[CITU_APP] 开始创建LangGraph Agent实例...")
  357. citu_langraph_agent = CituLangGraphAgent()
  358. print("[CITU_APP] LangGraph Agent实例创建成功")
  359. except ImportError as e:
  360. print(f"[CRITICAL] Agent模块导入失败: {str(e)}")
  361. print("[CRITICAL] 请检查agent模块是否存在以及依赖是否正确安装")
  362. raise Exception(f"Agent模块导入失败: {str(e)}")
  363. except Exception as e:
  364. print(f"[CRITICAL] LangGraph Agent实例创建失败: {str(e)}")
  365. print(f"[CRITICAL] 错误类型: {type(e).__name__}")
  366. # 提供更有用的错误信息
  367. if "config" in str(e).lower():
  368. print("[CRITICAL] 可能是配置文件问题,请检查配置")
  369. elif "llm" in str(e).lower():
  370. print("[CRITICAL] 可能是LLM连接问题,请检查LLM配置")
  371. elif "tool" in str(e).lower():
  372. print("[CRITICAL] 可能是工具加载问题,请检查工具模块")
  373. raise Exception(f"Agent初始化失败: {str(e)}")
  374. return citu_langraph_agent
  375. @app.flask_app.route('/api/v0/ask_agent', methods=['POST'])
  376. def ask_agent():
  377. """
  378. 支持对话上下文的ask_agent API - 修正版
  379. """
  380. req = request.get_json(force=True)
  381. question = req.get("question", None)
  382. browser_session_id = req.get("session_id", None)
  383. # 新增参数解析
  384. user_id_input = req.get("user_id", None)
  385. conversation_id_input = req.get("conversation_id", None)
  386. continue_conversation = req.get("continue_conversation", False)
  387. # 新增:路由模式参数解析和验证
  388. api_routing_mode = req.get("routing_mode", None)
  389. VALID_ROUTING_MODES = ["database_direct", "chat_direct", "hybrid", "llm_only"]
  390. if not question:
  391. return jsonify(bad_request_response(
  392. response_text="缺少必需参数:question",
  393. missing_params=["question"]
  394. )), 400
  395. # 验证routing_mode参数
  396. if api_routing_mode and api_routing_mode not in VALID_ROUTING_MODES:
  397. return jsonify(bad_request_response(
  398. response_text=f"无效的routing_mode参数值: {api_routing_mode},支持的值: {VALID_ROUTING_MODES}",
  399. invalid_params=["routing_mode"]
  400. )), 400
  401. try:
  402. # 1. 获取登录用户ID(修正:在函数中获取session信息)
  403. login_user_id = session.get('user_id') if 'user_id' in session else None
  404. # 2. 智能ID解析(修正:传入登录用户ID)
  405. user_id = redis_conversation_manager.resolve_user_id(
  406. user_id_input, browser_session_id, request.remote_addr, login_user_id
  407. )
  408. conversation_id, conversation_status = redis_conversation_manager.resolve_conversation_id(
  409. user_id, conversation_id_input, continue_conversation
  410. )
  411. # 3. 获取上下文和上下文类型(提前到缓存检查之前)
  412. context = redis_conversation_manager.get_context(conversation_id)
  413. # 获取上下文类型:从最后一条助手消息的metadata中获取类型
  414. context_type = None
  415. if context:
  416. try:
  417. # 获取最后一条助手消息的metadata
  418. messages = redis_conversation_manager.get_messages(conversation_id, limit=10)
  419. for message in reversed(messages): # 从最新的开始找
  420. if message.get("role") == "assistant":
  421. metadata = message.get("metadata", {})
  422. context_type = metadata.get("type")
  423. if context_type:
  424. print(f"[AGENT_API] 检测到上下文类型: {context_type}")
  425. break
  426. except Exception as e:
  427. print(f"[WARNING] 获取上下文类型失败: {str(e)}")
  428. # 4. 检查缓存(新逻辑:放宽使用条件,严控存储条件)
  429. cached_answer = redis_conversation_manager.get_cached_answer(question, context)
  430. if cached_answer:
  431. print(f"[AGENT_API] 使用缓存答案")
  432. # 确定缓存答案的助手回复内容(使用与非缓存相同的优先级逻辑)
  433. cached_response_type = cached_answer.get("type", "UNKNOWN")
  434. if cached_response_type == "DATABASE":
  435. # DATABASE类型:按优先级选择内容
  436. if cached_answer.get("response"):
  437. # 优先级1:错误或解释性回复(如SQL生成失败)
  438. assistant_response = cached_answer.get("response")
  439. elif cached_answer.get("summary"):
  440. # 优先级2:查询成功的摘要
  441. assistant_response = cached_answer.get("summary")
  442. elif cached_answer.get("query_result"):
  443. # 优先级3:构造简单描述
  444. query_result = cached_answer.get("query_result")
  445. row_count = query_result.get("row_count", 0)
  446. assistant_response = f"查询执行完成,共返回 {row_count} 条记录。"
  447. else:
  448. # 异常情况
  449. assistant_response = "数据库查询已处理。"
  450. else:
  451. # CHAT类型:直接使用response
  452. assistant_response = cached_answer.get("response", "")
  453. # 更新对话历史
  454. redis_conversation_manager.save_message(conversation_id, "user", question)
  455. redis_conversation_manager.save_message(
  456. conversation_id, "assistant",
  457. assistant_response,
  458. metadata={"from_cache": True}
  459. )
  460. # 添加对话信息到缓存结果
  461. cached_answer["conversation_id"] = conversation_id
  462. cached_answer["user_id"] = user_id
  463. cached_answer["from_cache"] = True
  464. cached_answer.update(conversation_status)
  465. # 使用agent_success_response返回标准格式
  466. return jsonify(agent_success_response(
  467. response_type=cached_answer.get("type", "UNKNOWN"),
  468. response=cached_answer.get("response", ""), # 修正:使用response而不是response_text
  469. sql=cached_answer.get("sql"),
  470. query_result=cached_answer.get("query_result"),
  471. summary=cached_answer.get("summary"),
  472. session_id=browser_session_id,
  473. execution_path=cached_answer.get("execution_path", []),
  474. classification_info=cached_answer.get("classification_info", {}),
  475. conversation_id=conversation_id,
  476. user_id=user_id,
  477. is_guest_user=(user_id == DEFAULT_ANONYMOUS_USER),
  478. context_used=bool(context),
  479. from_cache=True,
  480. conversation_status=conversation_status["status"],
  481. conversation_message=conversation_status["message"],
  482. requested_conversation_id=conversation_status.get("requested_id")
  483. ))
  484. # 5. 保存用户消息
  485. redis_conversation_manager.save_message(conversation_id, "user", question)
  486. # 6. 构建带上下文的问题
  487. if context:
  488. enhanced_question = f"\n[CONTEXT]\n{context}\n\n[CURRENT]\n{question}"
  489. print(f"[AGENT_API] 使用上下文,长度: {len(context)}字符")
  490. else:
  491. enhanced_question = question
  492. print(f"[AGENT_API] 新对话,无上下文")
  493. # 7. 确定最终使用的路由模式(优先级逻辑)
  494. if api_routing_mode:
  495. # API传了参数,优先使用
  496. effective_routing_mode = api_routing_mode
  497. print(f"[AGENT_API] 使用API指定的路由模式: {effective_routing_mode}")
  498. else:
  499. # API没传参数,使用配置文件
  500. try:
  501. from app_config import QUESTION_ROUTING_MODE
  502. effective_routing_mode = QUESTION_ROUTING_MODE
  503. print(f"[AGENT_API] 使用配置文件路由模式: {effective_routing_mode}")
  504. except ImportError:
  505. effective_routing_mode = "hybrid"
  506. print(f"[AGENT_API] 配置文件读取失败,使用默认路由模式: {effective_routing_mode}")
  507. # 8. 现有Agent处理逻辑(修改为传递路由模式)
  508. try:
  509. agent = get_citu_langraph_agent()
  510. except Exception as e:
  511. print(f"[CRITICAL] Agent初始化失败: {str(e)}")
  512. return jsonify(service_unavailable_response(
  513. response_text="AI服务暂时不可用,请稍后重试",
  514. can_retry=True
  515. )), 503
  516. agent_result = agent.process_question(
  517. question=enhanced_question, # 使用增强后的问题
  518. session_id=browser_session_id,
  519. context_type=context_type, # 传递上下文类型
  520. routing_mode=effective_routing_mode # 新增:传递路由模式
  521. )
  522. # 8. 处理Agent结果
  523. if agent_result.get("success", False):
  524. # 修正:直接从agent_result获取字段,因为它就是final_response
  525. response_type = agent_result.get("type", "UNKNOWN")
  526. response_text = agent_result.get("response", "")
  527. sql = agent_result.get("sql")
  528. query_result = agent_result.get("query_result")
  529. summary = agent_result.get("summary")
  530. execution_path = agent_result.get("execution_path", [])
  531. classification_info = agent_result.get("classification_info", {})
  532. # 确定助手回复内容的优先级
  533. if response_type == "DATABASE":
  534. # DATABASE类型:按优先级选择内容
  535. if response_text:
  536. # 优先级1:错误或解释性回复(如SQL生成失败)
  537. assistant_response = response_text
  538. elif summary:
  539. # 优先级2:查询成功的摘要
  540. assistant_response = summary
  541. elif query_result:
  542. # 优先级3:构造简单描述
  543. row_count = query_result.get("row_count", 0)
  544. assistant_response = f"查询执行完成,共返回 {row_count} 条记录。"
  545. else:
  546. # 异常情况
  547. assistant_response = "数据库查询已处理。"
  548. else:
  549. # CHAT类型:直接使用response
  550. assistant_response = response_text
  551. # 保存助手回复
  552. redis_conversation_manager.save_message(
  553. conversation_id, "assistant", assistant_response,
  554. metadata={
  555. "type": response_type,
  556. "sql": sql,
  557. "execution_path": execution_path
  558. }
  559. )
  560. # 缓存成功的答案(新逻辑:只缓存无上下文的问答)
  561. # 直接缓存agent_result,它已经包含所有需要的字段
  562. redis_conversation_manager.cache_answer(question, agent_result, context)
  563. # 使用agent_success_response的正确方式
  564. return jsonify(agent_success_response(
  565. response_type=response_type,
  566. response=response_text, # 修正:使用response而不是response_text
  567. sql=sql,
  568. query_result=query_result,
  569. summary=summary,
  570. session_id=browser_session_id,
  571. execution_path=execution_path,
  572. classification_info=classification_info,
  573. conversation_id=conversation_id,
  574. user_id=user_id,
  575. is_guest_user=(user_id == DEFAULT_ANONYMOUS_USER),
  576. context_used=bool(context),
  577. from_cache=False,
  578. conversation_status=conversation_status["status"],
  579. conversation_message=conversation_status["message"],
  580. requested_conversation_id=conversation_status.get("requested_id"),
  581. routing_mode_used=effective_routing_mode, # 新增:实际使用的路由模式
  582. routing_mode_source="api" if api_routing_mode else "config" # 新增:路由模式来源
  583. ))
  584. else:
  585. # 错误处理(修正:确保使用现有的错误响应格式)
  586. error_message = agent_result.get("error", "Agent处理失败")
  587. error_code = agent_result.get("error_code", 500)
  588. return jsonify(agent_error_response(
  589. response_text=error_message,
  590. error_type="agent_processing_failed",
  591. code=error_code,
  592. session_id=browser_session_id,
  593. conversation_id=conversation_id,
  594. user_id=user_id
  595. )), error_code
  596. except Exception as e:
  597. print(f"[ERROR] ask_agent执行失败: {str(e)}")
  598. return jsonify(internal_error_response(
  599. response_text="查询处理失败,请稍后重试"
  600. )), 500
  601. @app.flask_app.route('/api/v0/agent_health', methods=['GET'])
  602. def agent_health():
  603. """
  604. Agent健康检查接口
  605. 响应格式:
  606. {
  607. "success": true/false,
  608. "code": 200/503,
  609. "message": "healthy/degraded/unhealthy",
  610. "data": {
  611. "status": "healthy/degraded/unhealthy",
  612. "test_result": true/false,
  613. "workflow_compiled": true/false,
  614. "tools_count": 4,
  615. "message": "详细信息",
  616. "timestamp": "2024-01-01T12:00:00",
  617. "checks": {
  618. "agent_creation": true/false,
  619. "tools_import": true/false,
  620. "llm_connection": true/false,
  621. "classifier_ready": true/false
  622. }
  623. }
  624. }
  625. """
  626. try:
  627. # 基础健康检查
  628. health_data = {
  629. "status": "unknown",
  630. "test_result": False,
  631. "workflow_compiled": False,
  632. "tools_count": 0,
  633. "message": "",
  634. "timestamp": datetime.now().isoformat(),
  635. "checks": {
  636. "agent_creation": False,
  637. "tools_import": False,
  638. "llm_connection": False,
  639. "classifier_ready": False
  640. }
  641. }
  642. # 检查1: Agent创建
  643. try:
  644. agent = get_citu_langraph_agent()
  645. health_data["checks"]["agent_creation"] = True
  646. health_data["workflow_compiled"] = agent.workflow is not None
  647. health_data["tools_count"] = len(agent.tools) if hasattr(agent, 'tools') else 0
  648. except Exception as e:
  649. health_data["message"] = f"Agent创建失败: {str(e)}"
  650. from common.result import health_error_response
  651. return jsonify(health_error_response(
  652. status="unhealthy",
  653. **health_data
  654. )), 503
  655. # 检查2: 工具导入
  656. try:
  657. from agent.tools import TOOLS
  658. health_data["checks"]["tools_import"] = len(TOOLS) > 0
  659. except Exception as e:
  660. health_data["message"] = f"工具导入失败: {str(e)}"
  661. # 检查3: LLM连接(简单测试)
  662. try:
  663. from agent.utils import get_compatible_llm
  664. llm = get_compatible_llm()
  665. health_data["checks"]["llm_connection"] = llm is not None
  666. except Exception as e:
  667. health_data["message"] = f"LLM连接失败: {str(e)}"
  668. # 检查4: 分类器准备
  669. try:
  670. from agent.classifier import QuestionClassifier
  671. classifier = QuestionClassifier()
  672. health_data["checks"]["classifier_ready"] = True
  673. except Exception as e:
  674. health_data["message"] = f"分类器失败: {str(e)}"
  675. # 检查5: 完整流程测试(可选)
  676. try:
  677. if all(health_data["checks"].values()):
  678. test_result = agent.health_check()
  679. health_data["test_result"] = test_result.get("status") == "healthy"
  680. health_data["status"] = test_result.get("status", "unknown")
  681. health_data["message"] = test_result.get("message", "健康检查完成")
  682. else:
  683. health_data["status"] = "degraded"
  684. health_data["message"] = "部分组件异常"
  685. except Exception as e:
  686. health_data["status"] = "degraded"
  687. health_data["message"] = f"完整测试失败: {str(e)}"
  688. # 根据状态返回相应的HTTP代码 - 使用标准化健康检查响应
  689. from common.result import health_success_response, health_error_response
  690. if health_data["status"] == "healthy":
  691. return jsonify(health_success_response(**health_data))
  692. elif health_data["status"] == "degraded":
  693. return jsonify(health_error_response(status="degraded", **health_data)), 503
  694. else:
  695. return jsonify(health_error_response(status="unhealthy", **health_data)), 503
  696. except Exception as e:
  697. print(f"[ERROR] 健康检查异常: {str(e)}")
  698. from common.result import internal_error_response
  699. return jsonify(internal_error_response(
  700. response_text="健康检查失败,请稍后重试"
  701. )), 500
  702. # ==================== 日常管理API ====================
  703. @app.flask_app.route('/api/v0/cache_overview', methods=['GET'])
  704. def cache_overview():
  705. """日常管理:轻量概览 - 合并原cache_inspect的核心功能"""
  706. try:
  707. cache = app.cache
  708. result_data = {
  709. 'overview_summary': {
  710. 'total_conversations': 0,
  711. 'total_sessions': 0,
  712. 'query_time': datetime.now().isoformat()
  713. },
  714. 'recent_conversations': [], # 最近的对话
  715. 'session_summary': [] # 会话摘要
  716. }
  717. if hasattr(cache, 'cache') and isinstance(cache.cache, dict):
  718. result_data['overview_summary']['total_conversations'] = len(cache.cache)
  719. # 获取会话信息
  720. if hasattr(cache, 'get_all_sessions'):
  721. all_sessions = cache.get_all_sessions()
  722. result_data['overview_summary']['total_sessions'] = len(all_sessions)
  723. # 会话摘要(按最近活动排序)
  724. session_list = []
  725. for session_id, session_data in all_sessions.items():
  726. session_summary = {
  727. 'session_id': session_id,
  728. 'start_time': session_data['start_time'].isoformat(),
  729. 'conversation_count': session_data.get('conversation_count', 0),
  730. 'duration_seconds': session_data.get('session_duration_seconds', 0),
  731. 'last_activity': session_data.get('last_activity', session_data['start_time']).isoformat(),
  732. 'is_active': (datetime.now() - session_data.get('last_activity', session_data['start_time'])).total_seconds() < 1800 # 30分钟内活跃
  733. }
  734. session_list.append(session_summary)
  735. # 按最后活动时间排序
  736. session_list.sort(key=lambda x: x['last_activity'], reverse=True)
  737. result_data['session_summary'] = session_list
  738. # 最近的对话(最多显示10个)
  739. conversation_list = []
  740. for conversation_id, conversation_data in cache.cache.items():
  741. conversation_start_time = cache.conversation_start_times.get(conversation_id)
  742. conversation_info = {
  743. 'conversation_id': conversation_id,
  744. 'conversation_start_time': conversation_start_time.isoformat() if conversation_start_time else None,
  745. 'session_id': cache.conversation_to_session.get(conversation_id),
  746. 'has_question': 'question' in conversation_data,
  747. 'has_sql': 'sql' in conversation_data,
  748. 'has_data': 'df' in conversation_data and conversation_data['df'] is not None,
  749. 'question_preview': conversation_data.get('question', '')[:80] + '...' if len(conversation_data.get('question', '')) > 80 else conversation_data.get('question', ''),
  750. }
  751. # 计算对话持续时间
  752. if conversation_start_time:
  753. duration = datetime.now() - conversation_start_time
  754. conversation_info['conversation_duration_seconds'] = duration.total_seconds()
  755. conversation_list.append(conversation_info)
  756. # 按对话开始时间排序,显示最新的10个
  757. conversation_list.sort(key=lambda x: x['conversation_start_time'] or '', reverse=True)
  758. result_data['recent_conversations'] = conversation_list[:10]
  759. from common.result import success_response
  760. return jsonify(success_response(
  761. response_text="缓存概览查询完成",
  762. data=result_data
  763. ))
  764. except Exception as e:
  765. from common.result import internal_error_response
  766. return jsonify(internal_error_response(
  767. response_text="获取缓存概览失败,请稍后重试"
  768. )), 500
  769. @app.flask_app.route('/api/v0/cache_stats', methods=['GET'])
  770. def cache_stats():
  771. """日常管理:统计信息 - 合并原session_stats和cache_stats功能"""
  772. try:
  773. cache = app.cache
  774. current_time = datetime.now()
  775. stats = {
  776. 'basic_stats': {
  777. 'total_sessions': len(getattr(cache, 'session_info', {})),
  778. 'total_conversations': len(getattr(cache, 'cache', {})),
  779. 'active_sessions': 0, # 最近30分钟有活动
  780. 'average_conversations_per_session': 0
  781. },
  782. 'time_distribution': {
  783. 'sessions': {
  784. 'last_1_hour': 0,
  785. 'last_6_hours': 0,
  786. 'last_24_hours': 0,
  787. 'last_7_days': 0,
  788. 'older': 0
  789. },
  790. 'conversations': {
  791. 'last_1_hour': 0,
  792. 'last_6_hours': 0,
  793. 'last_24_hours': 0,
  794. 'last_7_days': 0,
  795. 'older': 0
  796. }
  797. },
  798. 'session_details': [],
  799. 'time_ranges': {
  800. 'oldest_session': None,
  801. 'newest_session': None,
  802. 'oldest_conversation': None,
  803. 'newest_conversation': None
  804. }
  805. }
  806. # 会话统计
  807. if hasattr(cache, 'session_info'):
  808. session_times = []
  809. total_conversations = 0
  810. for session_id, session_data in cache.session_info.items():
  811. start_time = session_data['start_time']
  812. session_times.append(start_time)
  813. conversation_count = len(session_data.get('conversations', []))
  814. total_conversations += conversation_count
  815. # 检查活跃状态
  816. last_activity = session_data.get('last_activity', session_data['start_time'])
  817. if (current_time - last_activity).total_seconds() < 1800:
  818. stats['basic_stats']['active_sessions'] += 1
  819. # 时间分布统计
  820. age_hours = (current_time - start_time).total_seconds() / 3600
  821. if age_hours <= 1:
  822. stats['time_distribution']['sessions']['last_1_hour'] += 1
  823. elif age_hours <= 6:
  824. stats['time_distribution']['sessions']['last_6_hours'] += 1
  825. elif age_hours <= 24:
  826. stats['time_distribution']['sessions']['last_24_hours'] += 1
  827. elif age_hours <= 168: # 7 days
  828. stats['time_distribution']['sessions']['last_7_days'] += 1
  829. else:
  830. stats['time_distribution']['sessions']['older'] += 1
  831. # 会话详细信息
  832. session_duration = current_time - start_time
  833. stats['session_details'].append({
  834. 'session_id': session_id,
  835. 'start_time': start_time.isoformat(),
  836. 'last_activity': last_activity.isoformat(),
  837. 'conversation_count': conversation_count,
  838. 'duration_seconds': session_duration.total_seconds(),
  839. 'duration_formatted': str(session_duration),
  840. 'is_active': (current_time - last_activity).total_seconds() < 1800,
  841. 'browser_session_id': session_data.get('browser_session_id')
  842. })
  843. # 计算平均值
  844. if len(cache.session_info) > 0:
  845. stats['basic_stats']['average_conversations_per_session'] = total_conversations / len(cache.session_info)
  846. # 时间范围
  847. if session_times:
  848. stats['time_ranges']['oldest_session'] = min(session_times).isoformat()
  849. stats['time_ranges']['newest_session'] = max(session_times).isoformat()
  850. # 对话统计
  851. if hasattr(cache, 'conversation_start_times'):
  852. conversation_times = []
  853. for conv_time in cache.conversation_start_times.values():
  854. conversation_times.append(conv_time)
  855. age_hours = (current_time - conv_time).total_seconds() / 3600
  856. if age_hours <= 1:
  857. stats['time_distribution']['conversations']['last_1_hour'] += 1
  858. elif age_hours <= 6:
  859. stats['time_distribution']['conversations']['last_6_hours'] += 1
  860. elif age_hours <= 24:
  861. stats['time_distribution']['conversations']['last_24_hours'] += 1
  862. elif age_hours <= 168:
  863. stats['time_distribution']['conversations']['last_7_days'] += 1
  864. else:
  865. stats['time_distribution']['conversations']['older'] += 1
  866. if conversation_times:
  867. stats['time_ranges']['oldest_conversation'] = min(conversation_times).isoformat()
  868. stats['time_ranges']['newest_conversation'] = max(conversation_times).isoformat()
  869. # 按最近活动排序会话详情
  870. stats['session_details'].sort(key=lambda x: x['last_activity'], reverse=True)
  871. from common.result import success_response
  872. return jsonify(success_response(
  873. response_text="缓存统计信息查询完成",
  874. data=stats
  875. ))
  876. except Exception as e:
  877. from common.result import internal_error_response
  878. return jsonify(internal_error_response(
  879. response_text="获取缓存统计失败,请稍后重试"
  880. )), 500
  881. # ==================== 高级功能API ====================
  882. @app.flask_app.route('/api/v0/cache_export', methods=['GET'])
  883. def cache_export():
  884. """高级功能:完整导出 - 保持原cache_raw_export的完整功能"""
  885. try:
  886. cache = app.cache
  887. # 验证缓存的实际结构
  888. if not hasattr(cache, 'cache'):
  889. from common.result import internal_error_response
  890. return jsonify(internal_error_response(
  891. response_text="缓存对象结构异常,请联系系统管理员"
  892. )), 500
  893. if not isinstance(cache.cache, dict):
  894. from common.result import internal_error_response
  895. return jsonify(internal_error_response(
  896. response_text="缓存数据类型异常,请联系系统管理员"
  897. )), 500
  898. # 定义JSON序列化辅助函数
  899. def make_json_serializable(obj):
  900. """将对象转换为JSON可序列化的格式"""
  901. if obj is None:
  902. return None
  903. elif isinstance(obj, (str, int, float, bool)):
  904. return obj
  905. elif isinstance(obj, (list, tuple)):
  906. return [make_json_serializable(item) for item in obj]
  907. elif isinstance(obj, dict):
  908. return {str(k): make_json_serializable(v) for k, v in obj.items()}
  909. elif hasattr(obj, 'isoformat'): # datetime objects
  910. return obj.isoformat()
  911. elif hasattr(obj, 'item'): # numpy scalars
  912. return obj.item()
  913. elif hasattr(obj, 'tolist'): # numpy arrays
  914. return obj.tolist()
  915. elif hasattr(obj, '__dict__'): # pandas dtypes and other objects
  916. return str(obj)
  917. else:
  918. return str(obj)
  919. # 获取完整的原始缓存数据
  920. raw_cache = cache.cache
  921. # 获取会话和对话时间信息
  922. conversation_times = getattr(cache, 'conversation_start_times', {})
  923. session_info = getattr(cache, 'session_info', {})
  924. conversation_to_session = getattr(cache, 'conversation_to_session', {})
  925. export_data = {
  926. 'export_metadata': {
  927. 'export_time': datetime.now().isoformat(),
  928. 'total_conversations': len(raw_cache),
  929. 'total_sessions': len(session_info),
  930. 'cache_type': type(cache).__name__,
  931. 'cache_object_info': str(cache),
  932. 'has_session_times': bool(session_info),
  933. 'has_conversation_times': bool(conversation_times)
  934. },
  935. 'session_info': {
  936. session_id: {
  937. 'start_time': session_data['start_time'].isoformat(),
  938. 'last_activity': session_data.get('last_activity', session_data['start_time']).isoformat(),
  939. 'conversations': session_data['conversations'],
  940. 'conversation_count': len(session_data['conversations']),
  941. 'browser_session_id': session_data.get('browser_session_id'),
  942. 'user_info': session_data.get('user_info', {})
  943. }
  944. for session_id, session_data in session_info.items()
  945. },
  946. 'conversation_times': {
  947. conversation_id: start_time.isoformat()
  948. for conversation_id, start_time in conversation_times.items()
  949. },
  950. 'conversation_to_session_mapping': conversation_to_session,
  951. 'conversations': {}
  952. }
  953. # 处理每个对话的完整数据
  954. for conversation_id, conversation_data in raw_cache.items():
  955. # 获取时间信息
  956. conversation_start_time = conversation_times.get(conversation_id)
  957. session_id = conversation_to_session.get(conversation_id)
  958. session_start_time = None
  959. if session_id and session_id in session_info:
  960. session_start_time = session_info[session_id]['start_time']
  961. processed_conversation = {
  962. 'conversation_id': conversation_id,
  963. 'conversation_start_time': conversation_start_time.isoformat() if conversation_start_time else None,
  964. 'session_id': session_id,
  965. 'session_start_time': session_start_time.isoformat() if session_start_time else None,
  966. 'field_count': len(conversation_data),
  967. 'fields': {}
  968. }
  969. # 添加时间计算
  970. if conversation_start_time:
  971. conversation_duration = datetime.now() - conversation_start_time
  972. processed_conversation['conversation_duration_seconds'] = conversation_duration.total_seconds()
  973. processed_conversation['conversation_duration_formatted'] = str(conversation_duration)
  974. if session_start_time:
  975. session_duration = datetime.now() - session_start_time
  976. processed_conversation['session_duration_seconds'] = session_duration.total_seconds()
  977. processed_conversation['session_duration_formatted'] = str(session_duration)
  978. # 处理每个字段,确保JSON序列化安全
  979. for field_name, field_value in conversation_data.items():
  980. field_info = {
  981. 'field_name': field_name,
  982. 'data_type': type(field_value).__name__,
  983. 'is_none': field_value is None
  984. }
  985. try:
  986. if field_value is None:
  987. field_info['value'] = None
  988. elif field_name in ['conversation_start_time', 'session_start_time']:
  989. # 处理时间字段
  990. field_info['content'] = make_json_serializable(field_value)
  991. elif field_name == 'df' and field_value is not None:
  992. # DataFrame的安全处理
  993. if hasattr(field_value, 'to_dict'):
  994. # 安全地处理dtypes
  995. try:
  996. dtypes_dict = {}
  997. for col, dtype in field_value.dtypes.items():
  998. dtypes_dict[col] = str(dtype)
  999. except Exception:
  1000. dtypes_dict = {"error": "无法序列化dtypes"}
  1001. # 安全地处理内存使用
  1002. try:
  1003. memory_usage = field_value.memory_usage(deep=True)
  1004. memory_dict = {}
  1005. for idx, usage in memory_usage.items():
  1006. memory_dict[str(idx)] = int(usage) if hasattr(usage, 'item') else int(usage)
  1007. except Exception:
  1008. memory_dict = {"error": "无法获取内存使用信息"}
  1009. field_info.update({
  1010. 'dataframe_info': {
  1011. 'shape': list(field_value.shape),
  1012. 'columns': list(field_value.columns),
  1013. 'dtypes': dtypes_dict,
  1014. 'index_info': {
  1015. 'type': type(field_value.index).__name__,
  1016. 'length': len(field_value.index)
  1017. }
  1018. },
  1019. 'data': make_json_serializable(field_value.to_dict('records')),
  1020. 'memory_usage': memory_dict
  1021. })
  1022. else:
  1023. field_info['value'] = str(field_value)
  1024. field_info['note'] = 'not_standard_dataframe'
  1025. elif field_name == 'fig_json':
  1026. # 图表JSON数据处理
  1027. if isinstance(field_value, str):
  1028. try:
  1029. import json
  1030. parsed_fig = json.loads(field_value)
  1031. field_info.update({
  1032. 'json_valid': True,
  1033. 'json_size_bytes': len(field_value),
  1034. 'plotly_structure': {
  1035. 'has_data': 'data' in parsed_fig,
  1036. 'has_layout': 'layout' in parsed_fig,
  1037. 'data_traces_count': len(parsed_fig.get('data', [])),
  1038. },
  1039. 'raw_json': field_value
  1040. })
  1041. except json.JSONDecodeError:
  1042. field_info.update({
  1043. 'json_valid': False,
  1044. 'raw_content': str(field_value)
  1045. })
  1046. else:
  1047. field_info['value'] = make_json_serializable(field_value)
  1048. elif field_name == 'followup_questions':
  1049. # 后续问题列表
  1050. field_info.update({
  1051. 'content': make_json_serializable(field_value)
  1052. })
  1053. elif field_name in ['question', 'sql', 'summary']:
  1054. # 文本字段
  1055. if isinstance(field_value, str):
  1056. field_info.update({
  1057. 'text_length': len(field_value),
  1058. 'content': field_value
  1059. })
  1060. else:
  1061. field_info['value'] = make_json_serializable(field_value)
  1062. else:
  1063. # 未知字段的安全处理
  1064. field_info['content'] = make_json_serializable(field_value)
  1065. except Exception as e:
  1066. field_info.update({
  1067. 'processing_error': str(e),
  1068. 'fallback_value': str(field_value)[:500] + '...' if len(str(field_value)) > 500 else str(field_value)
  1069. })
  1070. processed_conversation['fields'][field_name] = field_info
  1071. export_data['conversations'][conversation_id] = processed_conversation
  1072. # 添加缓存统计信息
  1073. field_frequency = {}
  1074. data_types_found = set()
  1075. total_dataframes = 0
  1076. total_questions = 0
  1077. for conv_data in export_data['conversations'].values():
  1078. for field_name, field_info in conv_data['fields'].items():
  1079. field_frequency[field_name] = field_frequency.get(field_name, 0) + 1
  1080. data_types_found.add(field_info['data_type'])
  1081. if field_name == 'df' and not field_info['is_none']:
  1082. total_dataframes += 1
  1083. if field_name == 'question' and not field_info['is_none']:
  1084. total_questions += 1
  1085. export_data['cache_statistics'] = {
  1086. 'field_frequency': field_frequency,
  1087. 'data_types_found': list(data_types_found),
  1088. 'total_dataframes': total_dataframes,
  1089. 'total_questions': total_questions,
  1090. 'has_session_timing': 'session_start_time' in field_frequency,
  1091. 'has_conversation_timing': 'conversation_start_time' in field_frequency
  1092. }
  1093. from common.result import success_response
  1094. return jsonify(success_response(
  1095. response_text="缓存数据导出完成",
  1096. data=export_data
  1097. ))
  1098. except Exception as e:
  1099. import traceback
  1100. error_details = {
  1101. 'error_message': str(e),
  1102. 'error_type': type(e).__name__,
  1103. 'traceback': traceback.format_exc()
  1104. }
  1105. from common.result import internal_error_response
  1106. return jsonify(internal_error_response(
  1107. response_text="导出缓存失败,请稍后重试"
  1108. )), 500
  1109. # ==================== 清理功能API ====================
  1110. @app.flask_app.route('/api/v0/cache_preview_cleanup', methods=['POST'])
  1111. def cache_preview_cleanup():
  1112. """清理功能:预览删除操作 - 保持原功能"""
  1113. try:
  1114. req = request.get_json(force=True)
  1115. # 时间条件 - 支持三种方式
  1116. older_than_hours = req.get('older_than_hours')
  1117. older_than_days = req.get('older_than_days')
  1118. before_timestamp = req.get('before_timestamp') # YYYY-MM-DD HH:MM:SS 格式
  1119. cache = app.cache
  1120. # 计算截止时间
  1121. cutoff_time = None
  1122. time_condition = None
  1123. if older_than_hours:
  1124. cutoff_time = datetime.now() - timedelta(hours=older_than_hours)
  1125. time_condition = f"older_than_hours: {older_than_hours}"
  1126. elif older_than_days:
  1127. cutoff_time = datetime.now() - timedelta(days=older_than_days)
  1128. time_condition = f"older_than_days: {older_than_days}"
  1129. elif before_timestamp:
  1130. try:
  1131. # 支持 YYYY-MM-DD HH:MM:SS 格式
  1132. cutoff_time = datetime.strptime(before_timestamp, '%Y-%m-%d %H:%M:%S')
  1133. time_condition = f"before_timestamp: {before_timestamp}"
  1134. except ValueError:
  1135. from common.result import validation_failed_response
  1136. return jsonify(validation_failed_response(
  1137. response_text="before_timestamp格式错误,请使用 YYYY-MM-DD HH:MM:SS 格式"
  1138. )), 422
  1139. else:
  1140. from common.result import bad_request_response
  1141. return jsonify(bad_request_response(
  1142. response_text="必须提供时间条件:older_than_hours, older_than_days 或 before_timestamp (YYYY-MM-DD HH:MM:SS)",
  1143. missing_params=["older_than_hours", "older_than_days", "before_timestamp"]
  1144. )), 400
  1145. preview = {
  1146. 'time_condition': time_condition,
  1147. 'cutoff_time': cutoff_time.isoformat(),
  1148. 'will_be_removed': {
  1149. 'sessions': []
  1150. },
  1151. 'will_be_kept': {
  1152. 'sessions_count': 0,
  1153. 'conversations_count': 0
  1154. },
  1155. 'summary': {
  1156. 'sessions_to_remove': 0,
  1157. 'conversations_to_remove': 0,
  1158. 'sessions_to_keep': 0,
  1159. 'conversations_to_keep': 0
  1160. }
  1161. }
  1162. # 预览按session删除
  1163. sessions_to_remove_count = 0
  1164. conversations_to_remove_count = 0
  1165. for session_id, session_data in cache.session_info.items():
  1166. session_preview = {
  1167. 'session_id': session_id,
  1168. 'start_time': session_data['start_time'].isoformat(),
  1169. 'conversation_count': len(session_data['conversations']),
  1170. 'conversations': []
  1171. }
  1172. # 添加conversation详情
  1173. for conv_id in session_data['conversations']:
  1174. if conv_id in cache.cache:
  1175. conv_data = cache.cache[conv_id]
  1176. session_preview['conversations'].append({
  1177. 'conversation_id': conv_id,
  1178. 'question': conv_data.get('question', '')[:50] + '...' if conv_data.get('question') else '',
  1179. 'start_time': cache.conversation_start_times.get(conv_id, '').isoformat() if cache.conversation_start_times.get(conv_id) else ''
  1180. })
  1181. if session_data['start_time'] < cutoff_time:
  1182. preview['will_be_removed']['sessions'].append(session_preview)
  1183. sessions_to_remove_count += 1
  1184. conversations_to_remove_count += len(session_data['conversations'])
  1185. else:
  1186. preview['will_be_kept']['sessions_count'] += 1
  1187. preview['will_be_kept']['conversations_count'] += len(session_data['conversations'])
  1188. # 更新摘要统计
  1189. preview['summary'] = {
  1190. 'sessions_to_remove': sessions_to_remove_count,
  1191. 'conversations_to_remove': conversations_to_remove_count,
  1192. 'sessions_to_keep': preview['will_be_kept']['sessions_count'],
  1193. 'conversations_to_keep': preview['will_be_kept']['conversations_count']
  1194. }
  1195. from common.result import success_response
  1196. return jsonify(success_response(
  1197. response_text=f"清理预览完成,将删除 {sessions_to_remove_count} 个会话和 {conversations_to_remove_count} 个对话",
  1198. data=preview
  1199. ))
  1200. except Exception as e:
  1201. from common.result import internal_error_response
  1202. return jsonify(internal_error_response(
  1203. response_text="预览清理操作失败,请稍后重试"
  1204. )), 500
  1205. @app.flask_app.route('/api/v0/cache_cleanup', methods=['POST'])
  1206. def cache_cleanup():
  1207. """清理功能:实际删除缓存 - 保持原功能"""
  1208. try:
  1209. req = request.get_json(force=True)
  1210. # 时间条件 - 支持三种方式
  1211. older_than_hours = req.get('older_than_hours')
  1212. older_than_days = req.get('older_than_days')
  1213. before_timestamp = req.get('before_timestamp') # YYYY-MM-DD HH:MM:SS 格式
  1214. cache = app.cache
  1215. if not hasattr(cache, 'session_info'):
  1216. from common.result import service_unavailable_response
  1217. return jsonify(service_unavailable_response(
  1218. response_text="缓存不支持会话功能"
  1219. )), 503
  1220. # 计算截止时间
  1221. cutoff_time = None
  1222. time_condition = None
  1223. if older_than_hours:
  1224. cutoff_time = datetime.now() - timedelta(hours=older_than_hours)
  1225. time_condition = f"older_than_hours: {older_than_hours}"
  1226. elif older_than_days:
  1227. cutoff_time = datetime.now() - timedelta(days=older_than_days)
  1228. time_condition = f"older_than_days: {older_than_days}"
  1229. elif before_timestamp:
  1230. try:
  1231. # 支持 YYYY-MM-DD HH:MM:SS 格式
  1232. cutoff_time = datetime.strptime(before_timestamp, '%Y-%m-%d %H:%M:%S')
  1233. time_condition = f"before_timestamp: {before_timestamp}"
  1234. except ValueError:
  1235. from common.result import validation_failed_response
  1236. return jsonify(validation_failed_response(
  1237. response_text="before_timestamp格式错误,请使用 YYYY-MM-DD HH:MM:SS 格式"
  1238. )), 422
  1239. else:
  1240. from common.result import bad_request_response
  1241. return jsonify(bad_request_response(
  1242. response_text="必须提供时间条件:older_than_hours, older_than_days 或 before_timestamp (YYYY-MM-DD HH:MM:SS)",
  1243. missing_params=["older_than_hours", "older_than_days", "before_timestamp"]
  1244. )), 400
  1245. cleanup_stats = {
  1246. 'time_condition': time_condition,
  1247. 'cutoff_time': cutoff_time.isoformat(),
  1248. 'sessions_removed': 0,
  1249. 'conversations_removed': 0,
  1250. 'sessions_kept': 0,
  1251. 'conversations_kept': 0,
  1252. 'removed_session_ids': [],
  1253. 'removed_conversation_ids': []
  1254. }
  1255. # 按session删除
  1256. sessions_to_remove = []
  1257. for session_id, session_data in cache.session_info.items():
  1258. if session_data['start_time'] < cutoff_time:
  1259. sessions_to_remove.append(session_id)
  1260. # 删除符合条件的sessions及其所有conversations
  1261. for session_id in sessions_to_remove:
  1262. session_data = cache.session_info[session_id]
  1263. conversations_in_session = session_data['conversations'].copy()
  1264. # 删除session中的所有conversations
  1265. for conv_id in conversations_in_session:
  1266. if conv_id in cache.cache:
  1267. del cache.cache[conv_id]
  1268. cleanup_stats['conversations_removed'] += 1
  1269. cleanup_stats['removed_conversation_ids'].append(conv_id)
  1270. # 清理conversation相关的时间记录
  1271. if hasattr(cache, 'conversation_start_times') and conv_id in cache.conversation_start_times:
  1272. del cache.conversation_start_times[conv_id]
  1273. if hasattr(cache, 'conversation_to_session') and conv_id in cache.conversation_to_session:
  1274. del cache.conversation_to_session[conv_id]
  1275. # 删除session记录
  1276. del cache.session_info[session_id]
  1277. cleanup_stats['sessions_removed'] += 1
  1278. cleanup_stats['removed_session_ids'].append(session_id)
  1279. # 统计保留的sessions和conversations
  1280. cleanup_stats['sessions_kept'] = len(cache.session_info)
  1281. cleanup_stats['conversations_kept'] = len(cache.cache)
  1282. from common.result import success_response
  1283. return jsonify(success_response(
  1284. response_text=f"缓存清理完成,删除了 {cleanup_stats['sessions_removed']} 个会话和 {cleanup_stats['conversations_removed']} 个对话",
  1285. data=cleanup_stats
  1286. ))
  1287. except Exception as e:
  1288. from common.result import internal_error_response
  1289. return jsonify(internal_error_response(
  1290. response_text="缓存清理失败,请稍后重试"
  1291. )), 500
  1292. @app.flask_app.route('/api/v0/training_error_question_sql', methods=['POST'])
  1293. def training_error_question_sql():
  1294. """
  1295. 存储错误的question-sql对到error_sql集合中
  1296. 此API将接收的错误question/sql pair写入到error_sql集合中,用于记录和分析错误的SQL查询。
  1297. Args:
  1298. question (str, required): 用户问题
  1299. sql (str, required): 对应的错误SQL查询语句
  1300. Returns:
  1301. JSON: 包含训练ID和成功消息的响应
  1302. """
  1303. try:
  1304. data = request.get_json()
  1305. question = data.get('question')
  1306. sql = data.get('sql')
  1307. print(f"[DEBUG] 接收到错误SQL训练请求: question={question}, sql={sql}")
  1308. if not question or not sql:
  1309. from common.result import bad_request_response
  1310. missing_params = []
  1311. if not question:
  1312. missing_params.append("question")
  1313. if not sql:
  1314. missing_params.append("sql")
  1315. return jsonify(bad_request_response(
  1316. response_text="question和sql参数都是必需的",
  1317. missing_params=missing_params
  1318. )), 400
  1319. # 使用vn实例的train_error_sql方法存储错误SQL
  1320. id = vn.train_error_sql(question=question, sql=sql)
  1321. print(f"[INFO] 成功存储错误SQL,ID: {id}")
  1322. from common.result import success_response
  1323. return jsonify(success_response(
  1324. response_text="错误SQL对已成功存储",
  1325. data={
  1326. "id": id,
  1327. "message": "错误SQL对已成功存储到error_sql集合"
  1328. }
  1329. ))
  1330. except Exception as e:
  1331. print(f"[ERROR] 存储错误SQL失败: {str(e)}")
  1332. from common.result import internal_error_response
  1333. return jsonify(internal_error_response(
  1334. response_text="存储错误SQL失败,请稍后重试"
  1335. )), 500
  1336. # ==================== Redis对话管理API ====================
  1337. @app.flask_app.route('/api/v0/user/<user_id>/conversations', methods=['GET'])
  1338. def get_user_conversations(user_id: str):
  1339. """获取用户的对话列表(按时间倒序)"""
  1340. try:
  1341. limit = request.args.get('limit', USER_MAX_CONVERSATIONS, type=int)
  1342. conversations = redis_conversation_manager.get_conversations(user_id, limit)
  1343. return jsonify(success_response(
  1344. response_text="获取用户对话列表成功",
  1345. data={
  1346. "user_id": user_id,
  1347. "conversations": conversations,
  1348. "total_count": len(conversations)
  1349. }
  1350. ))
  1351. except Exception as e:
  1352. return jsonify(internal_error_response(
  1353. response_text="获取对话列表失败,请稍后重试"
  1354. )), 500
  1355. @app.flask_app.route('/api/v0/conversation/<conversation_id>/messages', methods=['GET'])
  1356. def get_conversation_messages(conversation_id: str):
  1357. """获取特定对话的消息历史"""
  1358. try:
  1359. limit = request.args.get('limit', type=int) # 可选参数
  1360. messages = redis_conversation_manager.get_conversation_messages(conversation_id, limit)
  1361. meta = redis_conversation_manager.get_conversation_meta(conversation_id)
  1362. return jsonify(success_response(
  1363. response_text="获取对话消息成功",
  1364. data={
  1365. "conversation_id": conversation_id,
  1366. "conversation_meta": meta,
  1367. "messages": messages,
  1368. "message_count": len(messages)
  1369. }
  1370. ))
  1371. except Exception as e:
  1372. return jsonify(internal_error_response(
  1373. response_text="获取对话消息失败"
  1374. )), 500
  1375. @app.flask_app.route('/api/v0/conversation/<conversation_id>/context', methods=['GET'])
  1376. def get_conversation_context(conversation_id: str):
  1377. """获取对话上下文(格式化用于LLM)"""
  1378. try:
  1379. count = request.args.get('count', CONVERSATION_CONTEXT_COUNT, type=int)
  1380. context = redis_conversation_manager.get_context(conversation_id, count)
  1381. return jsonify(success_response(
  1382. response_text="获取对话上下文成功",
  1383. data={
  1384. "conversation_id": conversation_id,
  1385. "context": context,
  1386. "context_message_count": count
  1387. }
  1388. ))
  1389. except Exception as e:
  1390. return jsonify(internal_error_response(
  1391. response_text="获取对话上下文失败"
  1392. )), 500
  1393. @app.flask_app.route('/api/v0/conversation_stats', methods=['GET'])
  1394. def conversation_stats():
  1395. """获取对话系统统计信息"""
  1396. try:
  1397. stats = redis_conversation_manager.get_stats()
  1398. return jsonify(success_response(
  1399. response_text="获取统计信息成功",
  1400. data=stats
  1401. ))
  1402. except Exception as e:
  1403. return jsonify(internal_error_response(
  1404. response_text="获取统计信息失败,请稍后重试"
  1405. )), 500
  1406. @app.flask_app.route('/api/v0/conversation_cleanup', methods=['POST'])
  1407. def conversation_cleanup():
  1408. """手动清理过期对话"""
  1409. try:
  1410. redis_conversation_manager.cleanup_expired_conversations()
  1411. return jsonify(success_response(
  1412. response_text="对话清理完成"
  1413. ))
  1414. except Exception as e:
  1415. return jsonify(internal_error_response(
  1416. response_text="对话清理失败,请稍后重试"
  1417. )), 500
  1418. @app.flask_app.route('/api/v0/user/<user_id>/conversations/full', methods=['GET'])
  1419. def get_user_conversations_with_messages(user_id: str):
  1420. """
  1421. 获取用户的完整对话数据(包含所有消息)
  1422. 一次性返回用户的所有对话和每个对话下的消息历史
  1423. Args:
  1424. user_id: 用户ID(路径参数)
  1425. conversation_limit: 对话数量限制(查询参数,可选,不传则返回所有对话)
  1426. message_limit: 每个对话的消息数限制(查询参数,可选,不传则返回所有消息)
  1427. Returns:
  1428. 包含用户所有对话和消息的完整数据
  1429. """
  1430. try:
  1431. # 获取可选参数,不传递时使用None(返回所有记录)
  1432. conversation_limit = request.args.get('conversation_limit', type=int)
  1433. message_limit = request.args.get('message_limit', type=int)
  1434. # 获取用户的对话列表
  1435. conversations = redis_conversation_manager.get_conversations(user_id, conversation_limit)
  1436. # 为每个对话获取消息历史
  1437. full_conversations = []
  1438. total_messages = 0
  1439. for conversation in conversations:
  1440. conversation_id = conversation['conversation_id']
  1441. # 获取对话消息
  1442. messages = redis_conversation_manager.get_conversation_messages(
  1443. conversation_id, message_limit
  1444. )
  1445. # 获取对话元数据
  1446. meta = redis_conversation_manager.get_conversation_meta(conversation_id)
  1447. # 组合完整数据
  1448. full_conversation = {
  1449. **conversation, # 基础对话信息
  1450. 'meta': meta, # 对话元数据
  1451. 'messages': messages, # 消息列表
  1452. 'message_count': len(messages)
  1453. }
  1454. full_conversations.append(full_conversation)
  1455. total_messages += len(messages)
  1456. return jsonify(success_response(
  1457. response_text="获取用户完整对话数据成功",
  1458. data={
  1459. "user_id": user_id,
  1460. "conversations": full_conversations,
  1461. "total_conversations": len(full_conversations),
  1462. "total_messages": total_messages,
  1463. "conversation_limit_applied": conversation_limit,
  1464. "message_limit_applied": message_limit,
  1465. "query_time": datetime.now().isoformat()
  1466. }
  1467. ))
  1468. except Exception as e:
  1469. print(f"[ERROR] 获取用户完整对话数据失败: {str(e)}")
  1470. return jsonify(internal_error_response(
  1471. response_text="获取用户对话数据失败,请稍后重试"
  1472. )), 500
  1473. # ==================== Embedding缓存管理接口 ====================
  1474. @app.flask_app.route('/api/v0/embedding_cache_stats', methods=['GET'])
  1475. def embedding_cache_stats():
  1476. """获取embedding缓存统计信息"""
  1477. try:
  1478. from common.embedding_cache_manager import get_embedding_cache_manager
  1479. cache_manager = get_embedding_cache_manager()
  1480. stats = cache_manager.get_cache_stats()
  1481. return jsonify(success_response(
  1482. response_text="获取embedding缓存统计成功",
  1483. data=stats
  1484. ))
  1485. except Exception as e:
  1486. print(f"[ERROR] 获取embedding缓存统计失败: {str(e)}")
  1487. return jsonify(internal_error_response(
  1488. response_text="获取embedding缓存统计失败,请稍后重试"
  1489. )), 500
  1490. @app.flask_app.route('/api/v0/embedding_cache_cleanup', methods=['POST'])
  1491. def embedding_cache_cleanup():
  1492. """清空所有embedding缓存"""
  1493. try:
  1494. from common.embedding_cache_manager import get_embedding_cache_manager
  1495. cache_manager = get_embedding_cache_manager()
  1496. if not cache_manager.is_available():
  1497. return jsonify(internal_error_response(
  1498. response_text="Embedding缓存功能未启用或不可用"
  1499. )), 400
  1500. success = cache_manager.clear_all_cache()
  1501. if success:
  1502. return jsonify(success_response(
  1503. response_text="所有embedding缓存已清空",
  1504. data={"cleared": True}
  1505. ))
  1506. else:
  1507. return jsonify(internal_error_response(
  1508. response_text="清空embedding缓存失败"
  1509. )), 500
  1510. except Exception as e:
  1511. print(f"[ERROR] 清空embedding缓存失败: {str(e)}")
  1512. return jsonify(internal_error_response(
  1513. response_text="清空embedding缓存失败,请稍后重试"
  1514. )), 500
  1515. # ==================== QA反馈系统接口 ====================
  1516. # 全局反馈管理器实例
  1517. qa_feedback_manager = None
  1518. def get_qa_feedback_manager():
  1519. """获取QA反馈管理器实例(懒加载)- 复用Vanna连接版本"""
  1520. global qa_feedback_manager
  1521. if qa_feedback_manager is None:
  1522. try:
  1523. # 优先尝试复用vanna连接
  1524. vanna_instance = None
  1525. try:
  1526. # 尝试获取现有的vanna实例
  1527. if 'get_citu_langraph_agent' in globals():
  1528. agent = get_citu_langraph_agent()
  1529. if hasattr(agent, 'vn'):
  1530. vanna_instance = agent.vn
  1531. elif 'vn' in globals():
  1532. vanna_instance = vn
  1533. else:
  1534. print("[INFO] 未找到可用的vanna实例,将创建新的数据库连接")
  1535. except Exception as e:
  1536. print(f"[INFO] 获取vanna实例失败: {e},将创建新的数据库连接")
  1537. vanna_instance = None
  1538. qa_feedback_manager = QAFeedbackManager(vanna_instance=vanna_instance)
  1539. print("[CITU_APP] QA反馈管理器实例创建成功")
  1540. except Exception as e:
  1541. print(f"[CRITICAL] QA反馈管理器创建失败: {str(e)}")
  1542. raise Exception(f"QA反馈管理器初始化失败: {str(e)}")
  1543. return qa_feedback_manager
  1544. @app.flask_app.route('/api/v0/qa_feedback/query', methods=['POST'])
  1545. def qa_feedback_query():
  1546. """
  1547. 查询反馈记录API
  1548. 支持分页、筛选和排序功能
  1549. """
  1550. try:
  1551. req = request.get_json(force=True)
  1552. # 解析参数,设置默认值
  1553. page = req.get('page', 1)
  1554. page_size = req.get('page_size', 20)
  1555. is_thumb_up = req.get('is_thumb_up')
  1556. create_time_start = req.get('create_time_start')
  1557. create_time_end = req.get('create_time_end')
  1558. is_in_training_data = req.get('is_in_training_data')
  1559. sort_by = req.get('sort_by', 'create_time')
  1560. sort_order = req.get('sort_order', 'desc')
  1561. # 参数验证
  1562. if page < 1:
  1563. return jsonify(bad_request_response(
  1564. response_text="页码必须大于0",
  1565. invalid_params=["page"]
  1566. )), 400
  1567. if page_size < 1 or page_size > 100:
  1568. return jsonify(bad_request_response(
  1569. response_text="每页大小必须在1-100之间",
  1570. invalid_params=["page_size"]
  1571. )), 400
  1572. # 获取反馈管理器并查询
  1573. manager = get_qa_feedback_manager()
  1574. records, total = manager.query_feedback(
  1575. page=page,
  1576. page_size=page_size,
  1577. is_thumb_up=is_thumb_up,
  1578. create_time_start=create_time_start,
  1579. create_time_end=create_time_end,
  1580. is_in_training_data=is_in_training_data,
  1581. sort_by=sort_by,
  1582. sort_order=sort_order
  1583. )
  1584. # 计算分页信息
  1585. total_pages = (total + page_size - 1) // page_size
  1586. return jsonify(success_response(
  1587. response_text=f"查询成功,共找到 {total} 条记录",
  1588. data={
  1589. "records": records,
  1590. "pagination": {
  1591. "page": page,
  1592. "page_size": page_size,
  1593. "total": total,
  1594. "total_pages": total_pages,
  1595. "has_next": page < total_pages,
  1596. "has_prev": page > 1
  1597. }
  1598. }
  1599. ))
  1600. except Exception as e:
  1601. print(f"[ERROR] qa_feedback_query执行失败: {str(e)}")
  1602. return jsonify(internal_error_response(
  1603. response_text="查询反馈记录失败,请稍后重试"
  1604. )), 500
  1605. @app.flask_app.route('/api/v0/qa_feedback/delete/<int:feedback_id>', methods=['DELETE'])
  1606. def qa_feedback_delete(feedback_id):
  1607. """
  1608. 删除反馈记录API
  1609. """
  1610. try:
  1611. manager = get_qa_feedback_manager()
  1612. success = manager.delete_feedback(feedback_id)
  1613. if success:
  1614. return jsonify(success_response(
  1615. response_text=f"反馈记录删除成功",
  1616. data={"deleted_id": feedback_id}
  1617. ))
  1618. else:
  1619. return jsonify(not_found_response(
  1620. response_text=f"反馈记录不存在 (ID: {feedback_id})"
  1621. )), 404
  1622. except Exception as e:
  1623. print(f"[ERROR] qa_feedback_delete执行失败: {str(e)}")
  1624. return jsonify(internal_error_response(
  1625. response_text="删除反馈记录失败,请稍后重试"
  1626. )), 500
  1627. @app.flask_app.route('/api/v0/qa_feedback/update/<int:feedback_id>', methods=['PUT'])
  1628. def qa_feedback_update(feedback_id):
  1629. """
  1630. 更新反馈记录API
  1631. """
  1632. try:
  1633. req = request.get_json(force=True)
  1634. # 提取允许更新的字段
  1635. allowed_fields = ['question', 'sql', 'is_thumb_up', 'user_id', 'is_in_training_data']
  1636. update_data = {}
  1637. for field in allowed_fields:
  1638. if field in req:
  1639. update_data[field] = req[field]
  1640. if not update_data:
  1641. return jsonify(bad_request_response(
  1642. response_text="没有提供有效的更新字段",
  1643. missing_params=allowed_fields
  1644. )), 400
  1645. manager = get_qa_feedback_manager()
  1646. success = manager.update_feedback(feedback_id, **update_data)
  1647. if success:
  1648. return jsonify(success_response(
  1649. response_text="反馈记录更新成功",
  1650. data={
  1651. "updated_id": feedback_id,
  1652. "updated_fields": list(update_data.keys())
  1653. }
  1654. ))
  1655. else:
  1656. return jsonify(not_found_response(
  1657. response_text=f"反馈记录不存在或无变化 (ID: {feedback_id})"
  1658. )), 404
  1659. except Exception as e:
  1660. print(f"[ERROR] qa_feedback_update执行失败: {str(e)}")
  1661. return jsonify(internal_error_response(
  1662. response_text="更新反馈记录失败,请稍后重试"
  1663. )), 500
  1664. @app.flask_app.route('/api/v0/qa_feedback/add_to_training', methods=['POST'])
  1665. def qa_feedback_add_to_training():
  1666. """
  1667. 将反馈记录添加到训练数据集API
  1668. 支持混合批量处理:正向反馈加入SQL训练集,负向反馈加入error_sql训练集
  1669. """
  1670. try:
  1671. req = request.get_json(force=True)
  1672. feedback_ids = req.get('feedback_ids', [])
  1673. if not feedback_ids or not isinstance(feedback_ids, list):
  1674. return jsonify(bad_request_response(
  1675. response_text="缺少有效的反馈ID列表",
  1676. missing_params=["feedback_ids"]
  1677. )), 400
  1678. manager = get_qa_feedback_manager()
  1679. # 获取反馈记录
  1680. records = manager.get_feedback_by_ids(feedback_ids)
  1681. if not records:
  1682. return jsonify(not_found_response(
  1683. response_text="未找到任何有效的反馈记录"
  1684. )), 404
  1685. # 分别处理正向和负向反馈
  1686. positive_count = 0 # 正向训练计数
  1687. negative_count = 0 # 负向训练计数
  1688. already_trained_count = 0 # 已训练计数
  1689. error_count = 0 # 错误计数
  1690. successfully_trained_ids = [] # 成功训练的ID列表
  1691. for record in records:
  1692. try:
  1693. # 检查是否已经在训练数据中
  1694. if record['is_in_training_data']:
  1695. already_trained_count += 1
  1696. continue
  1697. if record['is_thumb_up']:
  1698. # 正向反馈 - 加入标准SQL训练集
  1699. training_id = vn.train(
  1700. question=record['question'],
  1701. sql=record['sql']
  1702. )
  1703. positive_count += 1
  1704. print(f"[TRAINING] 正向训练成功 - ID: {record['id']}, TrainingID: {training_id}")
  1705. else:
  1706. # 负向反馈 - 加入错误SQL训练集
  1707. training_id = vn.train_error_sql(
  1708. question=record['question'],
  1709. sql=record['sql']
  1710. )
  1711. negative_count += 1
  1712. print(f"[TRAINING] 负向训练成功 - ID: {record['id']}, TrainingID: {training_id}")
  1713. successfully_trained_ids.append(record['id'])
  1714. except Exception as e:
  1715. print(f"[ERROR] 训练失败 - 反馈ID: {record['id']}, 错误: {e}")
  1716. error_count += 1
  1717. # 更新训练状态
  1718. if successfully_trained_ids:
  1719. updated_count = manager.mark_training_status(successfully_trained_ids, True)
  1720. print(f"[TRAINING] 批量更新训练状态完成,影响 {updated_count} 条记录")
  1721. # 构建响应
  1722. total_processed = positive_count + negative_count + already_trained_count + error_count
  1723. return jsonify(success_response(
  1724. response_text=f"训练数据添加完成,成功处理 {positive_count + negative_count} 条记录",
  1725. data={
  1726. "summary": {
  1727. "total_requested": len(feedback_ids),
  1728. "total_processed": total_processed,
  1729. "positive_trained": positive_count,
  1730. "negative_trained": negative_count,
  1731. "already_trained": already_trained_count,
  1732. "errors": error_count
  1733. },
  1734. "successfully_trained_ids": successfully_trained_ids,
  1735. "training_details": {
  1736. "sql_training_count": positive_count,
  1737. "error_sql_training_count": negative_count
  1738. }
  1739. }
  1740. ))
  1741. except Exception as e:
  1742. print(f"[ERROR] qa_feedback_add_to_training执行失败: {str(e)}")
  1743. return jsonify(internal_error_response(
  1744. response_text="添加训练数据失败,请稍后重试"
  1745. )), 500
  1746. @app.flask_app.route('/api/v0/qa_feedback/add', methods=['POST'])
  1747. def qa_feedback_add():
  1748. """
  1749. 添加反馈记录API
  1750. 用于前端直接创建反馈记录
  1751. """
  1752. try:
  1753. req = request.get_json(force=True)
  1754. question = req.get('question')
  1755. sql = req.get('sql')
  1756. is_thumb_up = req.get('is_thumb_up')
  1757. user_id = req.get('user_id', 'guest')
  1758. # 参数验证
  1759. if not question:
  1760. return jsonify(bad_request_response(
  1761. response_text="缺少必需参数:question",
  1762. missing_params=["question"]
  1763. )), 400
  1764. if not sql:
  1765. return jsonify(bad_request_response(
  1766. response_text="缺少必需参数:sql",
  1767. missing_params=["sql"]
  1768. )), 400
  1769. if is_thumb_up is None:
  1770. return jsonify(bad_request_response(
  1771. response_text="缺少必需参数:is_thumb_up",
  1772. missing_params=["is_thumb_up"]
  1773. )), 400
  1774. manager = get_qa_feedback_manager()
  1775. feedback_id = manager.add_feedback(
  1776. question=question,
  1777. sql=sql,
  1778. is_thumb_up=bool(is_thumb_up),
  1779. user_id=user_id
  1780. )
  1781. return jsonify(success_response(
  1782. response_text="反馈记录创建成功",
  1783. data={
  1784. "feedback_id": feedback_id
  1785. }
  1786. ))
  1787. except Exception as e:
  1788. print(f"[ERROR] qa_feedback_add执行失败: {str(e)}")
  1789. return jsonify(internal_error_response(
  1790. response_text="创建反馈记录失败,请稍后重试"
  1791. )), 500
  1792. @app.flask_app.route('/api/v0/qa_feedback/stats', methods=['GET'])
  1793. def qa_feedback_stats():
  1794. """
  1795. 反馈统计API
  1796. 返回反馈数据的统计信息
  1797. """
  1798. try:
  1799. manager = get_qa_feedback_manager()
  1800. # 查询各种统计数据
  1801. all_records, total_count = manager.query_feedback(page=1, page_size=1)
  1802. positive_records, positive_count = manager.query_feedback(page=1, page_size=1, is_thumb_up=True)
  1803. negative_records, negative_count = manager.query_feedback(page=1, page_size=1, is_thumb_up=False)
  1804. trained_records, trained_count = manager.query_feedback(page=1, page_size=1, is_in_training_data=True)
  1805. untrained_records, untrained_count = manager.query_feedback(page=1, page_size=1, is_in_training_data=False)
  1806. return jsonify(success_response(
  1807. response_text="统计信息获取成功",
  1808. data={
  1809. "total_feedback": total_count,
  1810. "positive_feedback": positive_count,
  1811. "negative_feedback": negative_count,
  1812. "trained_feedback": trained_count,
  1813. "untrained_feedback": untrained_count,
  1814. "positive_rate": round(positive_count / max(total_count, 1) * 100, 2),
  1815. "training_rate": round(trained_count / max(total_count, 1) * 100, 2)
  1816. }
  1817. ))
  1818. except Exception as e:
  1819. print(f"[ERROR] qa_feedback_stats执行失败: {str(e)}")
  1820. return jsonify(internal_error_response(
  1821. response_text="获取统计信息失败,请稍后重试"
  1822. )), 500
  1823. # ==================== 问答缓存管理接口 ====================
  1824. @app.flask_app.route('/api/v0/qa_cache_stats', methods=['GET'])
  1825. def qa_cache_stats():
  1826. """获取问答缓存统计信息"""
  1827. try:
  1828. stats = redis_conversation_manager.get_qa_cache_stats()
  1829. return jsonify(success_response(
  1830. response_text="获取问答缓存统计成功",
  1831. data=stats
  1832. ))
  1833. except Exception as e:
  1834. print(f"[ERROR] 获取问答缓存统计失败: {str(e)}")
  1835. return jsonify(internal_error_response(
  1836. response_text="获取问答缓存统计失败,请稍后重试"
  1837. )), 500
  1838. @app.flask_app.route('/api/v0/qa_cache_list', methods=['GET'])
  1839. def qa_cache_list():
  1840. """获取问答缓存列表(支持分页)"""
  1841. try:
  1842. # 获取分页参数,默认限制50条
  1843. limit = request.args.get('limit', 50, type=int)
  1844. # 限制最大返回数量,防止一次性返回过多数据
  1845. if limit > 500:
  1846. limit = 500
  1847. elif limit <= 0:
  1848. limit = 50
  1849. cache_list = redis_conversation_manager.get_qa_cache_list(limit)
  1850. return jsonify(success_response(
  1851. response_text="获取问答缓存列表成功",
  1852. data={
  1853. "cache_list": cache_list,
  1854. "total_returned": len(cache_list),
  1855. "limit_applied": limit,
  1856. "note": "按缓存时间倒序排列,最新的在前面"
  1857. }
  1858. ))
  1859. except Exception as e:
  1860. print(f"[ERROR] 获取问答缓存列表失败: {str(e)}")
  1861. return jsonify(internal_error_response(
  1862. response_text="获取问答缓存列表失败,请稍后重试"
  1863. )), 500
  1864. @app.flask_app.route('/api/v0/qa_cache_cleanup', methods=['POST'])
  1865. def qa_cache_cleanup():
  1866. """清空所有问答缓存"""
  1867. try:
  1868. if not redis_conversation_manager.is_available():
  1869. return jsonify(internal_error_response(
  1870. response_text="Redis连接不可用,无法执行清理操作"
  1871. )), 500
  1872. deleted_count = redis_conversation_manager.clear_all_qa_cache()
  1873. return jsonify(success_response(
  1874. response_text="问答缓存清理完成",
  1875. data={
  1876. "deleted_count": deleted_count,
  1877. "cleared": deleted_count > 0,
  1878. "cleanup_time": datetime.now().isoformat()
  1879. }
  1880. ))
  1881. except Exception as e:
  1882. print(f"[ERROR] 清空问答缓存失败: {str(e)}")
  1883. return jsonify(internal_error_response(
  1884. response_text="清空问答缓存失败,请稍后重试"
  1885. )), 500
  1886. # ==================== 训练数据管理接口 ====================
  1887. def validate_sql_syntax(sql: str) -> tuple[bool, str]:
  1888. """SQL语法检查(仅对sql类型)"""
  1889. try:
  1890. parsed = sqlparse.parse(sql.strip())
  1891. if not parsed or not parsed[0].tokens:
  1892. return False, "SQL语法错误:空语句"
  1893. # 基本语法检查
  1894. sql_upper = sql.strip().upper()
  1895. if not any(sql_upper.startswith(keyword) for keyword in
  1896. ['SELECT', 'INSERT', 'UPDATE', 'DELETE', 'CREATE', 'ALTER', 'DROP']):
  1897. return False, "SQL语法错误:不是有效的SQL语句"
  1898. # 安全检查:禁止危险的SQL操作
  1899. dangerous_operations = ['UPDATE', 'DELETE', 'ALERT', 'DROP']
  1900. for operation in dangerous_operations:
  1901. if sql_upper.startswith(operation):
  1902. return False, f'在训练集中禁止使用"{",".join(dangerous_operations)}"'
  1903. return True, ""
  1904. except Exception as e:
  1905. return False, f"SQL语法错误:{str(e)}"
  1906. def paginate_data(data_list: list, page: int, page_size: int):
  1907. """分页处理算法"""
  1908. total = len(data_list)
  1909. start_idx = (page - 1) * page_size
  1910. end_idx = start_idx + page_size
  1911. page_data = data_list[start_idx:end_idx]
  1912. return {
  1913. "data": page_data,
  1914. "pagination": {
  1915. "page": page,
  1916. "page_size": page_size,
  1917. "total": total,
  1918. "total_pages": (total + page_size - 1) // page_size,
  1919. "has_next": end_idx < total,
  1920. "has_prev": page > 1
  1921. }
  1922. }
  1923. def filter_by_type(data_list: list, training_data_type: str):
  1924. """按类型筛选算法"""
  1925. if not training_data_type:
  1926. return data_list
  1927. return [
  1928. record for record in data_list
  1929. if record.get('training_data_type') == training_data_type
  1930. ]
  1931. def search_in_data(data_list: list, search_keyword: str):
  1932. """在数据中搜索关键词"""
  1933. if not search_keyword:
  1934. return data_list
  1935. keyword_lower = search_keyword.lower()
  1936. return [
  1937. record for record in data_list
  1938. if (record.get('question') and keyword_lower in record['question'].lower()) or
  1939. (record.get('content') and keyword_lower in record['content'].lower())
  1940. ]
  1941. def process_single_training_item(item: dict, index: int) -> dict:
  1942. """处理单个训练数据项"""
  1943. training_type = item.get('training_data_type')
  1944. if training_type == 'sql':
  1945. sql = item.get('sql')
  1946. if not sql:
  1947. raise ValueError("SQL字段是必需的")
  1948. # SQL语法检查
  1949. is_valid, error_msg = validate_sql_syntax(sql)
  1950. if not is_valid:
  1951. raise ValueError(error_msg)
  1952. question = item.get('question')
  1953. if question:
  1954. training_id = vn.train(question=question, sql=sql)
  1955. else:
  1956. training_id = vn.train(sql=sql)
  1957. elif training_type == 'error_sql':
  1958. # error_sql不需要语法检查
  1959. question = item.get('question')
  1960. sql = item.get('sql')
  1961. if not question or not sql:
  1962. raise ValueError("question和sql字段都是必需的")
  1963. training_id = vn.train_error_sql(question=question, sql=sql)
  1964. elif training_type == 'documentation':
  1965. content = item.get('content')
  1966. if not content:
  1967. raise ValueError("content字段是必需的")
  1968. training_id = vn.train(documentation=content)
  1969. elif training_type == 'ddl':
  1970. ddl = item.get('ddl')
  1971. if not ddl:
  1972. raise ValueError("ddl字段是必需的")
  1973. training_id = vn.train(ddl=ddl)
  1974. else:
  1975. raise ValueError(f"不支持的训练数据类型: {training_type}")
  1976. return {
  1977. "index": index,
  1978. "success": True,
  1979. "training_id": training_id,
  1980. "type": training_type,
  1981. "message": f"{training_type}训练数据创建成功"
  1982. }
  1983. def get_total_training_count():
  1984. """获取当前训练数据总数"""
  1985. try:
  1986. training_data = vn.get_training_data()
  1987. if training_data is not None and not training_data.empty:
  1988. return len(training_data)
  1989. return 0
  1990. except Exception as e:
  1991. print(f"[WARNING] 获取训练数据总数失败: {e}")
  1992. return 0
  1993. @app.flask_app.route('/api/v0/training_data/query', methods=['POST'])
  1994. def training_data_query():
  1995. """
  1996. 分页查询训练数据API
  1997. 支持类型筛选、搜索和排序功能
  1998. """
  1999. try:
  2000. req = request.get_json(force=True)
  2001. # 解析参数,设置默认值
  2002. page = req.get('page', 1)
  2003. page_size = req.get('page_size', 20)
  2004. training_data_type = req.get('training_data_type')
  2005. sort_by = req.get('sort_by', 'id')
  2006. sort_order = req.get('sort_order', 'desc')
  2007. search_keyword = req.get('search_keyword')
  2008. # 参数验证
  2009. if page < 1:
  2010. return jsonify(bad_request_response(
  2011. response_text="页码必须大于0",
  2012. missing_params=["page"]
  2013. )), 400
  2014. if page_size < 1 or page_size > 100:
  2015. return jsonify(bad_request_response(
  2016. response_text="每页大小必须在1-100之间",
  2017. missing_params=["page_size"]
  2018. )), 400
  2019. if search_keyword and len(search_keyword) > 100:
  2020. return jsonify(bad_request_response(
  2021. response_text="搜索关键词最大长度为100字符",
  2022. missing_params=["search_keyword"]
  2023. )), 400
  2024. # 获取训练数据
  2025. training_data = vn.get_training_data()
  2026. if training_data is None or training_data.empty:
  2027. return jsonify(success_response(
  2028. response_text="查询成功,暂无训练数据",
  2029. data={
  2030. "records": [],
  2031. "pagination": {
  2032. "page": page,
  2033. "page_size": page_size,
  2034. "total": 0,
  2035. "total_pages": 0,
  2036. "has_next": False,
  2037. "has_prev": False
  2038. },
  2039. "filters_applied": {
  2040. "training_data_type": training_data_type,
  2041. "search_keyword": search_keyword
  2042. }
  2043. }
  2044. ))
  2045. # 转换为列表格式
  2046. records = training_data.to_dict(orient="records")
  2047. # 应用筛选条件
  2048. if training_data_type:
  2049. records = filter_by_type(records, training_data_type)
  2050. if search_keyword:
  2051. records = search_in_data(records, search_keyword)
  2052. # 排序
  2053. if sort_by in ['id', 'training_data_type']:
  2054. reverse = (sort_order.lower() == 'desc')
  2055. records.sort(key=lambda x: x.get(sort_by, ''), reverse=reverse)
  2056. # 分页
  2057. paginated_result = paginate_data(records, page, page_size)
  2058. return jsonify(success_response(
  2059. response_text=f"查询成功,共找到 {paginated_result['pagination']['total']} 条记录",
  2060. data={
  2061. "records": paginated_result["data"],
  2062. "pagination": paginated_result["pagination"],
  2063. "filters_applied": {
  2064. "training_data_type": training_data_type,
  2065. "search_keyword": search_keyword
  2066. }
  2067. }
  2068. ))
  2069. except Exception as e:
  2070. print(f"[ERROR] training_data_query执行失败: {str(e)}")
  2071. return jsonify(internal_error_response(
  2072. response_text="查询训练数据失败,请稍后重试"
  2073. )), 500
  2074. @app.flask_app.route('/api/v0/training_data/create', methods=['POST'])
  2075. def training_data_create():
  2076. """
  2077. 创建训练数据API
  2078. 支持单条和批量创建,支持四种数据类型
  2079. """
  2080. try:
  2081. req = request.get_json(force=True)
  2082. data = req.get('data')
  2083. if not data:
  2084. return jsonify(bad_request_response(
  2085. response_text="缺少必需参数:data",
  2086. missing_params=["data"]
  2087. )), 400
  2088. # 统一处理为列表格式
  2089. if isinstance(data, dict):
  2090. data_list = [data]
  2091. elif isinstance(data, list):
  2092. data_list = data
  2093. else:
  2094. return jsonify(bad_request_response(
  2095. response_text="data字段格式错误,应为对象或数组"
  2096. )), 400
  2097. # 批量操作限制
  2098. if len(data_list) > 50:
  2099. return jsonify(bad_request_response(
  2100. response_text="批量操作最大支持50条记录"
  2101. )), 400
  2102. results = []
  2103. successful_count = 0
  2104. type_summary = {"sql": 0, "documentation": 0, "ddl": 0, "error_sql": 0}
  2105. for index, item in enumerate(data_list):
  2106. try:
  2107. result = process_single_training_item(item, index)
  2108. results.append(result)
  2109. if result['success']:
  2110. successful_count += 1
  2111. type_summary[result['type']] += 1
  2112. except Exception as e:
  2113. results.append({
  2114. "index": index,
  2115. "success": False,
  2116. "type": item.get('training_data_type', 'unknown'),
  2117. "error": str(e),
  2118. "message": "创建失败"
  2119. })
  2120. # 获取创建后的总记录数
  2121. current_total = get_total_training_count()
  2122. return jsonify(success_response(
  2123. response_text="训练数据创建完成",
  2124. data={
  2125. "total_requested": len(data_list),
  2126. "successfully_created": successful_count,
  2127. "failed_count": len(data_list) - successful_count,
  2128. "results": results,
  2129. "summary": type_summary,
  2130. "current_total_count": current_total
  2131. }
  2132. ))
  2133. except Exception as e:
  2134. print(f"[ERROR] training_data_create执行失败: {str(e)}")
  2135. return jsonify(internal_error_response(
  2136. response_text="创建训练数据失败,请稍后重试"
  2137. )), 500
  2138. @app.flask_app.route('/api/v0/training_data/delete', methods=['POST'])
  2139. def training_data_delete():
  2140. """
  2141. 删除训练数据API
  2142. 支持批量删除
  2143. """
  2144. try:
  2145. req = request.get_json(force=True)
  2146. ids = req.get('ids', [])
  2147. confirm = req.get('confirm', False)
  2148. if not ids or not isinstance(ids, list):
  2149. return jsonify(bad_request_response(
  2150. response_text="缺少有效的ID列表",
  2151. missing_params=["ids"]
  2152. )), 400
  2153. if not confirm:
  2154. return jsonify(bad_request_response(
  2155. response_text="删除操作需要确认,请设置confirm为true"
  2156. )), 400
  2157. # 批量操作限制
  2158. if len(ids) > 50:
  2159. return jsonify(bad_request_response(
  2160. response_text="批量删除最大支持50条记录"
  2161. )), 400
  2162. deleted_ids = []
  2163. failed_ids = []
  2164. failed_details = []
  2165. for training_id in ids:
  2166. try:
  2167. success = vn.remove_training_data(training_id)
  2168. if success:
  2169. deleted_ids.append(training_id)
  2170. else:
  2171. failed_ids.append(training_id)
  2172. failed_details.append({
  2173. "id": training_id,
  2174. "error": "记录不存在或删除失败"
  2175. })
  2176. except Exception as e:
  2177. failed_ids.append(training_id)
  2178. failed_details.append({
  2179. "id": training_id,
  2180. "error": str(e)
  2181. })
  2182. # 获取删除后的总记录数
  2183. current_total = get_total_training_count()
  2184. return jsonify(success_response(
  2185. response_text="训练数据删除完成",
  2186. data={
  2187. "total_requested": len(ids),
  2188. "successfully_deleted": len(deleted_ids),
  2189. "failed_count": len(failed_ids),
  2190. "deleted_ids": deleted_ids,
  2191. "failed_ids": failed_ids,
  2192. "failed_details": failed_details,
  2193. "current_total_count": current_total
  2194. }
  2195. ))
  2196. except Exception as e:
  2197. print(f"[ERROR] training_data_delete执行失败: {str(e)}")
  2198. return jsonify(internal_error_response(
  2199. response_text="删除训练数据失败,请稍后重试"
  2200. )), 500
  2201. @app.flask_app.route('/api/v0/training_data/stats', methods=['GET'])
  2202. def training_data_stats():
  2203. """
  2204. 获取训练数据统计信息API
  2205. """
  2206. try:
  2207. training_data = vn.get_training_data()
  2208. if training_data is None or training_data.empty:
  2209. return jsonify(success_response(
  2210. response_text="统计信息获取成功",
  2211. data={
  2212. "total_count": 0,
  2213. "type_breakdown": {
  2214. "sql": 0,
  2215. "documentation": 0,
  2216. "ddl": 0,
  2217. "error_sql": 0
  2218. },
  2219. "type_percentages": {
  2220. "sql": 0.0,
  2221. "documentation": 0.0,
  2222. "ddl": 0.0,
  2223. "error_sql": 0.0
  2224. },
  2225. "last_updated": datetime.now().isoformat()
  2226. }
  2227. ))
  2228. total_count = len(training_data)
  2229. # 统计各类型数量
  2230. type_breakdown = {"sql": 0, "documentation": 0, "ddl": 0, "error_sql": 0}
  2231. if 'training_data_type' in training_data.columns:
  2232. type_counts = training_data['training_data_type'].value_counts()
  2233. for data_type, count in type_counts.items():
  2234. if data_type in type_breakdown:
  2235. type_breakdown[data_type] = int(count)
  2236. # 计算百分比
  2237. type_percentages = {}
  2238. for data_type, count in type_breakdown.items():
  2239. type_percentages[data_type] = round(count / max(total_count, 1) * 100, 2)
  2240. return jsonify(success_response(
  2241. response_text="统计信息获取成功",
  2242. data={
  2243. "total_count": total_count,
  2244. "type_breakdown": type_breakdown,
  2245. "type_percentages": type_percentages,
  2246. "last_updated": datetime.now().isoformat()
  2247. }
  2248. ))
  2249. except Exception as e:
  2250. print(f"[ERROR] training_data_stats执行失败: {str(e)}")
  2251. return jsonify(internal_error_response(
  2252. response_text="获取统计信息失败,请稍后重试"
  2253. )), 500
  2254. @app.flask_app.route('/api/v0/cache_overview_full', methods=['GET'])
  2255. def cache_overview_full():
  2256. """获取所有缓存系统的综合概览"""
  2257. try:
  2258. from common.embedding_cache_manager import get_embedding_cache_manager
  2259. from common.vanna_instance import get_vanna_instance
  2260. # 获取现有的缓存统计
  2261. vanna_cache = get_vanna_instance()
  2262. # 直接使用应用中的缓存实例
  2263. cache = app.cache
  2264. cache_overview = {
  2265. "conversation_aware_cache": {
  2266. "enabled": True,
  2267. "total_items": len(cache.cache) if hasattr(cache, 'cache') else 0,
  2268. "sessions": list(cache.cache.keys()) if hasattr(cache, 'cache') else [],
  2269. "cache_type": type(cache).__name__
  2270. },
  2271. "question_answer_cache": redis_conversation_manager.get_qa_cache_stats() if redis_conversation_manager.is_available() else {"available": False},
  2272. "embedding_cache": get_embedding_cache_manager().get_cache_stats(),
  2273. "redis_conversation_stats": redis_conversation_manager.get_stats() if redis_conversation_manager.is_available() else None
  2274. }
  2275. return jsonify(success_response(
  2276. response_text="获取综合缓存概览成功",
  2277. data=cache_overview
  2278. ))
  2279. except Exception as e:
  2280. print(f"[ERROR] 获取综合缓存概览失败: {str(e)}")
  2281. return jsonify(internal_error_response(
  2282. response_text="获取缓存概览失败,请稍后重试"
  2283. )), 500
  2284. # 前端JavaScript示例 - 如何维持会话
  2285. """
  2286. // 前端需要维护一个会话ID
  2287. class ChatSession {
  2288. constructor() {
  2289. // 从localStorage获取或创建新的会话ID
  2290. this.sessionId = localStorage.getItem('chat_session_id') || this.generateSessionId();
  2291. localStorage.setItem('chat_session_id', this.sessionId);
  2292. }
  2293. generateSessionId() {
  2294. return 'session_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
  2295. }
  2296. async askQuestion(question) {
  2297. const response = await fetch('/api/v0/ask', {
  2298. method: 'POST',
  2299. headers: {
  2300. 'Content-Type': 'application/json',
  2301. },
  2302. body: JSON.stringify({
  2303. question: question,
  2304. session_id: this.sessionId // 关键:传递会话ID
  2305. })
  2306. });
  2307. return await response.json();
  2308. }
  2309. // 开始新会话
  2310. startNewSession() {
  2311. this.sessionId = this.generateSessionId();
  2312. localStorage.setItem('chat_session_id', this.sessionId);
  2313. }
  2314. }
  2315. // 使用示例
  2316. const chatSession = new ChatSession();
  2317. chatSession.askQuestion("各年龄段客户的流失率如何?");
  2318. """
  2319. print("正在启动Flask应用: http://localhost:8084")
  2320. app.run(host="0.0.0.0", port=8084, debug=True)