unified_api.py 165 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266
  1. """
  2. 统一 API 服务
  3. 集成 citu_app.py 指定API 和 react_agent/api.py 的所有功能
  4. 提供数据库问答、Redis对话管理、QA反馈、训练数据管理、React Agent等功能
  5. 使用普通 Flask 应用 + ASGI 包装实现异步支持
  6. """
  7. import asyncio
  8. import logging
  9. import atexit
  10. import os
  11. import sys
  12. from datetime import datetime, timedelta
  13. from typing import Optional, Dict, Any, TYPE_CHECKING, Union
  14. import signal
  15. from threading import Thread
  16. if TYPE_CHECKING:
  17. from react_agent.agent import CustomReactAgent
  18. # 初始化日志系统 - 必须在最前面
  19. from core.logging import initialize_logging, get_app_logger
  20. initialize_logging()
  21. # 标准 Flask 导入
  22. from flask import Flask, request, jsonify, session, send_file
  23. import redis.asyncio as redis
  24. from werkzeug.utils import secure_filename
  25. # 基础依赖
  26. import pandas as pd
  27. import json
  28. import sqlparse
  29. import tempfile
  30. import os
  31. import psycopg2
  32. import re
  33. # 项目模块导入
  34. from core.vanna_llm_factory import create_vanna_instance
  35. from common.redis_conversation_manager import RedisConversationManager
  36. from common.qa_feedback_manager import QAFeedbackManager
  37. # Data Pipeline 相关导入 - 从 citu_app.py 迁移
  38. from data_pipeline.api.simple_workflow import SimpleWorkflowManager, SimpleWorkflowExecutor
  39. from data_pipeline.api.simple_file_manager import SimpleFileManager
  40. from data_pipeline.api.table_inspector_api import TableInspectorAPI
  41. from common.result import (
  42. success_response, bad_request_response, not_found_response, internal_error_response,
  43. error_response, service_unavailable_response,
  44. agent_success_response, agent_error_response,
  45. validation_failed_response
  46. )
  47. from app_config import (
  48. USER_MAX_CONVERSATIONS, CONVERSATION_CONTEXT_COUNT,
  49. DEFAULT_ANONYMOUS_USER, ENABLE_QUESTION_ANSWER_CACHE
  50. )
  51. # 创建标准 Flask 应用
  52. app = Flask(__name__)
  53. # 创建日志记录器
  54. logger = get_app_logger("UnifiedApp")
  55. # React Agent 导入
  56. try:
  57. from react_agent.agent import CustomReactAgent
  58. from react_agent.enhanced_redis_api import get_conversation_detail_from_redis
  59. except ImportError:
  60. try:
  61. from test.custom_react_agent.agent import CustomReactAgent
  62. from test.custom_react_agent.enhanced_redis_api import get_conversation_detail_from_redis
  63. except ImportError:
  64. logger.warning("无法导入 CustomReactAgent,React Agent功能将不可用")
  65. CustomReactAgent = None
  66. get_conversation_detail_from_redis = None
  67. # 初始化核心组件
  68. vn = create_vanna_instance()
  69. redis_conversation_manager = RedisConversationManager()
  70. # ==================== React Agent 全局实例管理 ====================
  71. _react_agent_instance: Optional[Any] = None
  72. _redis_client: Optional[redis.Redis] = None
  73. def validate_request_data(data: Dict[str, Any]) -> Dict[str, Any]:
  74. """验证请求数据,并支持从thread_id中推断user_id"""
  75. errors = []
  76. # 验证 question(必填)
  77. question = data.get('question', '')
  78. if not question or not question.strip():
  79. errors.append('问题不能为空')
  80. elif len(question) > 2000:
  81. errors.append('问题长度不能超过2000字符')
  82. # 优先获取 thread_id
  83. thread_id = data.get('thread_id') or data.get('conversation_id')
  84. # 获取 user_id,但暂不设置默认值
  85. user_id = data.get('user_id')
  86. # 如果没有传递 user_id,则尝试从 thread_id 中推断
  87. if not user_id:
  88. if thread_id and ':' in thread_id:
  89. inferred_user_id = thread_id.split(':', 1)[0]
  90. if inferred_user_id:
  91. user_id = inferred_user_id
  92. logger.info(f"👤 未提供user_id,从 thread_id '{thread_id}' 中推断出: '{user_id}'")
  93. else:
  94. user_id = 'guest'
  95. else:
  96. user_id = 'guest'
  97. # 验证 user_id 长度
  98. if user_id and len(user_id) > 50:
  99. errors.append('用户ID长度不能超过50字符')
  100. # 用户ID与会话ID一致性校验
  101. if thread_id:
  102. if ':' not in thread_id:
  103. errors.append('会话ID格式无效,期望格式为 user_id:timestamp')
  104. else:
  105. thread_user_id = thread_id.split(':', 1)[0]
  106. if thread_user_id != user_id:
  107. errors.append(f'会话归属验证失败:会话ID [{thread_id}] 不属于当前用户 [{user_id}]')
  108. if errors:
  109. raise ValueError('; '.join(errors))
  110. return {
  111. 'question': question.strip(),
  112. 'user_id': user_id,
  113. 'thread_id': thread_id # 可选,不传则自动生成新会话
  114. }
  115. async def get_react_agent() -> Any:
  116. """获取 React Agent 实例(懒加载)"""
  117. global _react_agent_instance, _redis_client
  118. if _react_agent_instance is None:
  119. if CustomReactAgent is None:
  120. logger.error("❌ CustomReactAgent 未能导入,无法初始化")
  121. raise ImportError("CustomReactAgent 未能导入")
  122. logger.info("🚀 正在异步初始化 Custom React Agent...")
  123. try:
  124. # 设置环境变量
  125. os.environ['REDIS_URL'] = 'redis://localhost:6379'
  126. # 初始化共享的Redis客户端
  127. _redis_client = redis.from_url('redis://localhost:6379', decode_responses=True)
  128. await _redis_client.ping()
  129. logger.info("✅ Redis客户端连接成功")
  130. _react_agent_instance = await CustomReactAgent.create()
  131. logger.info("✅ React Agent 异步初始化完成")
  132. except Exception as e:
  133. logger.error(f"❌ React Agent 异步初始化失败: {e}")
  134. raise
  135. return _react_agent_instance
  136. async def ensure_agent_ready() -> bool:
  137. """异步确保Agent实例可用"""
  138. global _react_agent_instance
  139. if _react_agent_instance is None:
  140. await get_react_agent()
  141. # 测试Agent是否还可用
  142. try:
  143. test_result = await _react_agent_instance.get_user_recent_conversations("__test__", 1)
  144. return True
  145. except Exception as e:
  146. logger.warning(f"⚠️ Agent实例不可用: {e}")
  147. _react_agent_instance = None
  148. await get_react_agent()
  149. return True
  150. def get_user_conversations_simple_sync(user_id: str, limit: int = 10):
  151. """直接从Redis获取用户对话,测试版本"""
  152. import redis
  153. import json
  154. try:
  155. # 创建Redis连接
  156. redis_client = redis.Redis(host='localhost', port=6379, decode_responses=True)
  157. redis_client.ping()
  158. # 扫描用户的checkpoint keys
  159. pattern = f"checkpoint:{user_id}:*"
  160. logger.info(f"🔍 扫描模式: {pattern}")
  161. keys = []
  162. cursor = 0
  163. while True:
  164. cursor, batch = redis_client.scan(cursor=cursor, match=pattern, count=1000)
  165. keys.extend(batch)
  166. if cursor == 0:
  167. break
  168. logger.info(f"📋 找到 {len(keys)} 个keys")
  169. # 解析thread信息
  170. thread_data = {}
  171. for key in keys:
  172. try:
  173. parts = key.split(':')
  174. if len(parts) >= 4:
  175. thread_id = f"{parts[1]}:{parts[2]}" # user_id:timestamp
  176. timestamp = parts[2]
  177. if thread_id not in thread_data:
  178. thread_data[thread_id] = {
  179. "thread_id": thread_id,
  180. "timestamp": timestamp,
  181. "keys": []
  182. }
  183. thread_data[thread_id]["keys"].append(key)
  184. except Exception as e:
  185. logger.warning(f"解析key失败 {key}: {e}")
  186. continue
  187. logger.info(f"📊 找到 {len(thread_data)} 个thread")
  188. # 按时间戳排序
  189. sorted_threads = sorted(
  190. thread_data.values(),
  191. key=lambda x: x["timestamp"],
  192. reverse=True
  193. )[:limit]
  194. # 获取每个thread的详细信息
  195. conversations = []
  196. for thread_info in sorted_threads:
  197. try:
  198. thread_id = thread_info["thread_id"]
  199. # 获取最新的checkpoint数据
  200. latest_key = max(thread_info["keys"])
  201. # 先检查key的数据类型
  202. key_type = redis_client.type(latest_key)
  203. logger.info(f"🔍 Key {latest_key} 的类型: {key_type}")
  204. data = None
  205. if key_type == 'string':
  206. data = redis_client.get(latest_key)
  207. elif key_type == 'hash':
  208. # 如果是hash类型,获取所有字段
  209. hash_data = redis_client.hgetall(latest_key)
  210. logger.info(f"🔍 Hash字段: {list(hash_data.keys())}")
  211. # 尝试获取可能的数据字段
  212. for field in ['data', 'state', 'value', 'checkpoint']:
  213. if field in hash_data:
  214. data = hash_data[field]
  215. break
  216. if not data and hash_data:
  217. # 如果没找到预期字段,取第一个值试试
  218. data = list(hash_data.values())[0]
  219. elif key_type == 'list':
  220. # 如果是list类型,获取最后一个元素
  221. data = redis_client.lindex(latest_key, -1)
  222. elif key_type == 'ReJSON-RL':
  223. # 这是RedisJSON类型,使用JSON.GET命令
  224. logger.info(f"🔍 使用JSON.GET获取RedisJSON数据")
  225. try:
  226. # 使用JSON.GET命令获取整个JSON对象
  227. json_data = redis_client.execute_command('JSON.GET', latest_key)
  228. if json_data:
  229. data = json_data # JSON.GET返回的就是JSON字符串
  230. logger.info(f"🔍 JSON数据长度: {len(data)} 字符")
  231. else:
  232. logger.warning(f"⚠️ JSON.GET 返回空数据")
  233. continue
  234. except Exception as json_error:
  235. logger.error(f"❌ JSON.GET 失败: {json_error}")
  236. continue
  237. else:
  238. logger.warning(f"⚠️ 未知的key类型: {key_type}")
  239. continue
  240. if data:
  241. try:
  242. checkpoint_data = json.loads(data)
  243. # 调试:查看JSON数据结构
  244. logger.info(f"🔍 JSON顶级keys: {list(checkpoint_data.keys())}")
  245. # 根据您提供的JSON结构,消息在 checkpoint.channel_values.messages
  246. messages = []
  247. # 首先检查是否有checkpoint字段
  248. if 'checkpoint' in checkpoint_data:
  249. checkpoint = checkpoint_data['checkpoint']
  250. if isinstance(checkpoint, dict) and 'channel_values' in checkpoint:
  251. channel_values = checkpoint['channel_values']
  252. if isinstance(channel_values, dict) and 'messages' in channel_values:
  253. messages = channel_values['messages']
  254. logger.info(f"🔍 找到messages: {len(messages)} 条消息")
  255. # 如果没有checkpoint字段,尝试直接在channel_values
  256. if not messages and 'channel_values' in checkpoint_data:
  257. channel_values = checkpoint_data['channel_values']
  258. if isinstance(channel_values, dict) and 'messages' in channel_values:
  259. messages = channel_values['messages']
  260. logger.info(f"🔍 找到messages(直接路径): {len(messages)} 条消息")
  261. # 生成对话预览
  262. preview = "空对话"
  263. if messages:
  264. for msg in messages:
  265. # 处理LangChain消息格式:{"lc": 1, "type": "constructor", "id": ["langchain", "schema", "messages", "HumanMessage"], "kwargs": {"content": "...", "type": "human"}}
  266. if isinstance(msg, dict):
  267. # 检查是否是LangChain格式的HumanMessage
  268. if (msg.get('lc') == 1 and
  269. msg.get('type') == 'constructor' and
  270. 'id' in msg and
  271. isinstance(msg['id'], list) and
  272. len(msg['id']) >= 4 and
  273. msg['id'][3] == 'HumanMessage' and
  274. 'kwargs' in msg):
  275. kwargs = msg['kwargs']
  276. if kwargs.get('type') == 'human' and 'content' in kwargs:
  277. content = str(kwargs['content'])
  278. preview = content[:50] + "..." if len(content) > 50 else content
  279. break
  280. # 兼容其他格式
  281. elif msg.get('type') == 'human' and 'content' in msg:
  282. content = str(msg['content'])
  283. preview = content[:50] + "..." if len(content) > 50 else content
  284. break
  285. conversations.append({
  286. "thread_id": thread_id,
  287. "user_id": user_id,
  288. "timestamp": thread_info["timestamp"],
  289. "message_count": len(messages),
  290. "conversation_preview": preview
  291. })
  292. except json.JSONDecodeError:
  293. logger.error(f"❌ JSON解析失败,数据类型: {type(data)}, 长度: {len(str(data))}")
  294. logger.error(f"❌ 数据开头: {str(data)[:200]}...")
  295. continue
  296. except Exception as e:
  297. logger.error(f"处理thread {thread_info['thread_id']} 失败: {e}")
  298. continue
  299. redis_client.close()
  300. logger.info(f"✅ 返回 {len(conversations)} 个对话")
  301. return conversations
  302. except Exception as e:
  303. logger.error(f"❌ Redis查询失败: {e}")
  304. return []
  305. def cleanup_resources():
  306. """清理资源"""
  307. global _react_agent_instance, _redis_client
  308. async def async_cleanup():
  309. if _react_agent_instance:
  310. await _react_agent_instance.close()
  311. logger.info("✅ React Agent 资源已清理")
  312. if _redis_client:
  313. await _redis_client.aclose()
  314. logger.info("✅ Redis客户端已关闭")
  315. try:
  316. asyncio.run(async_cleanup())
  317. except Exception as e:
  318. logger.error(f"清理资源失败: {e}")
  319. atexit.register(cleanup_resources)
  320. # ==================== 基础路由 ====================
  321. @app.route("/")
  322. def index():
  323. """根路径健康检查"""
  324. return jsonify({"message": "统一API服务正在运行", "version": "1.0.0"})
  325. @app.route('/health', methods=['GET'])
  326. def health_check():
  327. """健康检查端点"""
  328. try:
  329. health_status = {
  330. "status": "healthy",
  331. "react_agent_initialized": _react_agent_instance is not None,
  332. "timestamp": datetime.now().isoformat(),
  333. "services": {
  334. "redis": redis_conversation_manager.is_available(),
  335. "vanna": vn is not None
  336. }
  337. }
  338. return jsonify(health_status), 200
  339. except Exception as e:
  340. logger.error(f"健康检查失败: {e}")
  341. return jsonify({"status": "unhealthy", "error": str(e)}), 500
  342. # ==================== React Agent API ====================
  343. @app.route("/api/v0/ask_react_agent", methods=["POST"])
  344. async def ask_react_agent():
  345. """异步React Agent智能问答接口(从 custom_react_agent 迁移,原路由:/api/chat)"""
  346. global _react_agent_instance
  347. # 确保Agent已初始化
  348. if not await ensure_agent_ready():
  349. return jsonify({
  350. "code": 503,
  351. "message": "服务未就绪",
  352. "success": False,
  353. "error": "React Agent 初始化失败"
  354. }), 503
  355. try:
  356. # 获取请求数据
  357. try:
  358. data = request.get_json(force=True)
  359. except Exception as json_error:
  360. logger.warning(f"⚠️ JSON解析失败: {json_error}")
  361. return jsonify({
  362. "code": 400,
  363. "message": "请求格式错误",
  364. "success": False,
  365. "error": "无效的JSON格式,请检查请求体中是否存在语法错误(如多余的逗号、引号不匹配等)",
  366. "details": str(json_error)
  367. }), 400
  368. if not data:
  369. return jsonify({
  370. "code": 400,
  371. "message": "请求参数错误",
  372. "success": False,
  373. "error": "请求体不能为空"
  374. }), 400
  375. # 验证请求数据
  376. validated_data = validate_request_data(data)
  377. logger.info(f"📨 收到React Agent请求 - User: {validated_data['user_id']}, Question: {validated_data['question'][:50]}...")
  378. # 异步调用处理
  379. agent_result = await _react_agent_instance.chat(
  380. message=validated_data['question'],
  381. user_id=validated_data['user_id'],
  382. thread_id=validated_data['thread_id']
  383. )
  384. if not agent_result.get("success", False):
  385. # Agent处理失败
  386. error_msg = agent_result.get("error", "React Agent处理失败")
  387. logger.error(f"❌ React Agent处理失败: {error_msg}")
  388. # 检查是否建议重试
  389. retry_suggested = agent_result.get("retry_suggested", False)
  390. error_code = 503 if retry_suggested else 500
  391. message = "服务暂时不可用,请稍后重试" if retry_suggested else "处理失败"
  392. return jsonify({
  393. "code": error_code,
  394. "message": message,
  395. "success": False,
  396. "error": error_msg,
  397. "retry_suggested": retry_suggested,
  398. "data": {
  399. "conversation_id": agent_result.get("thread_id"),
  400. "user_id": validated_data['user_id'],
  401. "timestamp": datetime.now().isoformat()
  402. }
  403. }), error_code
  404. # Agent处理成功
  405. api_data = agent_result.get("api_data", {})
  406. # 构建响应数据(按照 react_agent/api.py 的正确格式)
  407. response_data = {
  408. "response": api_data.get("response", ""),
  409. "conversation_id": agent_result.get("thread_id"),
  410. "user_id": validated_data['user_id'],
  411. "react_agent_meta": api_data.get("react_agent_meta", {
  412. "thread_id": agent_result.get("thread_id"),
  413. "agent_version": "custom_react_v1_async"
  414. }),
  415. "timestamp": datetime.now().isoformat()
  416. }
  417. # 可选字段:SQL(仅当执行SQL时存在)
  418. if "sql" in api_data:
  419. response_data["sql"] = api_data["sql"]
  420. # 可选字段:records(仅当有查询结果时存在)
  421. if "records" in api_data:
  422. response_data["records"] = api_data["records"]
  423. return jsonify({
  424. "code": 200,
  425. "message": "处理成功",
  426. "success": True,
  427. "data": response_data
  428. }), 200
  429. except ValueError as ve:
  430. # 参数验证错误
  431. logger.warning(f"⚠️ 参数验证失败: {ve}")
  432. return jsonify({
  433. "code": 400,
  434. "message": "参数验证失败",
  435. "success": False,
  436. "error": str(ve)
  437. }), 400
  438. except Exception as e:
  439. logger.error(f"❌ React Agent API 异常: {e}")
  440. return jsonify({
  441. "code": 500,
  442. "message": "内部服务错误",
  443. "success": False,
  444. "error": "服务暂时不可用,请稍后重试"
  445. }), 500
  446. # ==================== LangGraph Agent API ====================
  447. # 全局Agent实例(单例模式)
  448. citu_langraph_agent = None
  449. def get_citu_langraph_agent():
  450. """获取LangGraph Agent实例(懒加载)"""
  451. global citu_langraph_agent
  452. if citu_langraph_agent is None:
  453. try:
  454. from agent.citu_agent import CituLangGraphAgent
  455. logger.info("开始创建LangGraph Agent实例...")
  456. citu_langraph_agent = CituLangGraphAgent()
  457. logger.info("LangGraph Agent实例创建成功")
  458. except ImportError as e:
  459. logger.critical(f"Agent模块导入失败: {str(e)}")
  460. raise Exception(f"Agent模块导入失败: {str(e)}")
  461. except Exception as e:
  462. logger.critical(f"LangGraph Agent实例创建失败: {str(e)}")
  463. raise Exception(f"Agent初始化失败: {str(e)}")
  464. return citu_langraph_agent
  465. @app.route('/api/v0/ask_agent', methods=['POST'])
  466. def ask_agent():
  467. """支持对话上下文的ask_agent API"""
  468. req = request.get_json(force=True)
  469. question = req.get("question", None)
  470. browser_session_id = req.get("session_id", None)
  471. user_id_input = req.get("user_id", None)
  472. conversation_id_input = req.get("conversation_id", None)
  473. continue_conversation = req.get("continue_conversation", False)
  474. api_routing_mode = req.get("routing_mode", None)
  475. VALID_ROUTING_MODES = ["database_direct", "chat_direct", "hybrid", "llm_only"]
  476. if not question:
  477. return jsonify(bad_request_response(
  478. response_text="缺少必需参数:question",
  479. missing_params=["question"]
  480. )), 400
  481. if api_routing_mode and api_routing_mode not in VALID_ROUTING_MODES:
  482. return jsonify(bad_request_response(
  483. response_text=f"无效的routing_mode参数值: {api_routing_mode},支持的值: {VALID_ROUTING_MODES}",
  484. invalid_params=["routing_mode"]
  485. )), 400
  486. try:
  487. # 获取登录用户ID
  488. login_user_id = session.get('user_id') if 'user_id' in session else None
  489. # 智能ID解析
  490. user_id = redis_conversation_manager.resolve_user_id(
  491. user_id_input, browser_session_id, request.remote_addr, login_user_id
  492. )
  493. conversation_id, conversation_status = redis_conversation_manager.resolve_conversation_id(
  494. user_id, conversation_id_input, continue_conversation
  495. )
  496. # 获取上下文和上下文类型(提前到缓存检查之前)
  497. context = redis_conversation_manager.get_context(conversation_id)
  498. # 获取上下文类型:从最后一条助手消息的metadata中获取类型
  499. context_type = None
  500. if context:
  501. try:
  502. # 获取最后一条助手消息的metadata
  503. messages = redis_conversation_manager.get_messages(conversation_id, limit=10)
  504. for message in reversed(messages): # 从最新的开始找
  505. if message.get("role") == "assistant":
  506. metadata = message.get("metadata", {})
  507. context_type = metadata.get("type")
  508. if context_type:
  509. logger.info(f"[AGENT_API] 检测到上下文类型: {context_type}")
  510. break
  511. except Exception as e:
  512. logger.warning(f"获取上下文类型失败: {str(e)}")
  513. # 检查缓存(新逻辑:放宽使用条件,严控存储条件)
  514. cached_answer = redis_conversation_manager.get_cached_answer(question, context)
  515. if cached_answer:
  516. logger.info(f"[AGENT_API] 使用缓存答案")
  517. # 确定缓存答案的助手回复内容(使用与非缓存相同的优先级逻辑)
  518. cached_response_type = cached_answer.get("type", "UNKNOWN")
  519. if cached_response_type == "DATABASE":
  520. # DATABASE类型:按优先级选择内容
  521. if cached_answer.get("response"):
  522. # 优先级1:错误或解释性回复(如SQL生成失败)
  523. assistant_response = cached_answer.get("response")
  524. elif cached_answer.get("summary"):
  525. # 优先级2:查询成功的摘要
  526. assistant_response = cached_answer.get("summary")
  527. elif cached_answer.get("query_result"):
  528. # 优先级3:构造简单描述
  529. query_result = cached_answer.get("query_result")
  530. row_count = query_result.get("row_count", 0)
  531. assistant_response = f"查询执行完成,共返回 {row_count} 条记录。"
  532. else:
  533. # 异常情况
  534. assistant_response = "数据库查询已处理。"
  535. else:
  536. # CHAT类型:直接使用response
  537. assistant_response = cached_answer.get("response", "")
  538. # 更新对话历史
  539. redis_conversation_manager.save_message(conversation_id, "user", question)
  540. redis_conversation_manager.save_message(
  541. conversation_id, "assistant",
  542. assistant_response,
  543. metadata={"from_cache": True}
  544. )
  545. # 添加对话信息到缓存结果
  546. cached_answer["conversation_id"] = conversation_id
  547. cached_answer["user_id"] = user_id
  548. cached_answer["from_cache"] = True
  549. cached_answer.update(conversation_status)
  550. # 使用agent_success_response返回标准格式
  551. return jsonify(agent_success_response(
  552. response_type=cached_answer.get("type", "UNKNOWN"),
  553. response=cached_answer.get("response", ""),
  554. sql=cached_answer.get("sql"),
  555. records=cached_answer.get("query_result"),
  556. summary=cached_answer.get("summary"),
  557. session_id=browser_session_id,
  558. execution_path=cached_answer.get("execution_path", []),
  559. classification_info=cached_answer.get("classification_info", {}),
  560. conversation_id=conversation_id,
  561. user_id=user_id,
  562. is_guest_user=(user_id == DEFAULT_ANONYMOUS_USER),
  563. context_used=bool(context),
  564. from_cache=True,
  565. conversation_status=conversation_status["status"],
  566. conversation_message=conversation_status["message"],
  567. requested_conversation_id=conversation_status.get("requested_id")
  568. ))
  569. # 保存用户消息
  570. redis_conversation_manager.save_message(conversation_id, "user", question)
  571. # 构建带上下文的问题
  572. if context:
  573. enhanced_question = f"\n[CONTEXT]\n{context}\n\n[CURRENT]\n{question}"
  574. logger.info(f"[AGENT_API] 使用上下文,长度: {len(context)}字符")
  575. else:
  576. enhanced_question = question
  577. logger.info(f"[AGENT_API] 新对话,无上下文")
  578. # 确定最终使用的路由模式(优先级逻辑)
  579. if api_routing_mode:
  580. # API传了参数,优先使用
  581. effective_routing_mode = api_routing_mode
  582. logger.info(f"[AGENT_API] 使用API指定的路由模式: {effective_routing_mode}")
  583. else:
  584. # API没传参数,使用配置文件
  585. try:
  586. from app_config import QUESTION_ROUTING_MODE
  587. effective_routing_mode = QUESTION_ROUTING_MODE
  588. logger.info(f"[AGENT_API] 使用配置文件路由模式: {effective_routing_mode}")
  589. except ImportError:
  590. effective_routing_mode = "hybrid"
  591. logger.info(f"[AGENT_API] 配置文件读取失败,使用默认路由模式: {effective_routing_mode}")
  592. # Agent处理
  593. try:
  594. agent = get_citu_langraph_agent()
  595. except Exception as e:
  596. logger.critical(f"Agent初始化失败: {str(e)}")
  597. return jsonify(service_unavailable_response(
  598. response_text="AI服务暂时不可用,请稍后重试",
  599. can_retry=True
  600. )), 503
  601. # 异步调用Agent处理问题
  602. import asyncio
  603. agent_result = asyncio.run(agent.process_question(
  604. question=enhanced_question, # 使用增强后的问题
  605. session_id=browser_session_id,
  606. context_type=context_type, # 传递上下文类型
  607. routing_mode=effective_routing_mode # 新增:传递路由模式
  608. ))
  609. # 处理Agent结果
  610. if agent_result.get("success", False):
  611. response_type = agent_result.get("type", "UNKNOWN")
  612. response_text = agent_result.get("response", "")
  613. sql = agent_result.get("sql")
  614. query_result = agent_result.get("query_result")
  615. summary = agent_result.get("summary")
  616. execution_path = agent_result.get("execution_path", [])
  617. classification_info = agent_result.get("classification_info", {})
  618. # 确定助手回复内容的优先级
  619. if response_type == "DATABASE":
  620. if response_text:
  621. assistant_response = response_text
  622. elif summary:
  623. assistant_response = summary
  624. elif query_result:
  625. row_count = query_result.get("row_count", 0)
  626. assistant_response = f"查询执行完成,共返回 {row_count} 条记录。"
  627. else:
  628. assistant_response = "数据库查询已处理。"
  629. else:
  630. assistant_response = response_text
  631. # 保存助手回复
  632. redis_conversation_manager.save_message(
  633. conversation_id, "assistant", assistant_response,
  634. metadata={
  635. "type": response_type,
  636. "sql": sql,
  637. "execution_path": execution_path
  638. }
  639. )
  640. # 缓存成功的答案(新逻辑:只缓存无上下文的问答)
  641. # 直接缓存agent_result,它已经包含所有需要的字段
  642. redis_conversation_manager.cache_answer(question, agent_result, context)
  643. # 使用agent_success_response的正确方式
  644. return jsonify(agent_success_response(
  645. response_type=response_type,
  646. response=response_text,
  647. sql=sql,
  648. records=query_result,
  649. summary=summary,
  650. session_id=browser_session_id,
  651. execution_path=execution_path,
  652. classification_info=classification_info,
  653. conversation_id=conversation_id,
  654. user_id=user_id,
  655. is_guest_user=(user_id == DEFAULT_ANONYMOUS_USER),
  656. context_used=bool(context),
  657. from_cache=False,
  658. conversation_status=conversation_status["status"],
  659. conversation_message=conversation_status["message"],
  660. requested_conversation_id=conversation_status.get("requested_id"),
  661. routing_mode_used=effective_routing_mode, # 新增:实际使用的路由模式
  662. routing_mode_source="api" if api_routing_mode else "config" # 新增:路由模式来源
  663. ))
  664. else:
  665. # 错误处理
  666. error_message = agent_result.get("error", "Agent处理失败")
  667. error_code = agent_result.get("error_code", 500)
  668. return jsonify(agent_error_response(
  669. response_text=error_message,
  670. error_type="agent_processing_failed",
  671. code=error_code,
  672. session_id=browser_session_id,
  673. conversation_id=conversation_id,
  674. user_id=user_id
  675. )), error_code
  676. except Exception as e:
  677. logger.error(f"ask_agent执行失败: {str(e)}")
  678. return jsonify(internal_error_response(
  679. response_text="查询处理失败,请稍后重试"
  680. )), 500
  681. # ==================== QA反馈系统API ====================
  682. qa_feedback_manager = None
  683. def get_qa_feedback_manager():
  684. """获取QA反馈管理器实例(懒加载)"""
  685. global qa_feedback_manager
  686. if qa_feedback_manager is None:
  687. try:
  688. qa_feedback_manager = QAFeedbackManager(vanna_instance=vn)
  689. logger.info("QA反馈管理器实例创建成功")
  690. except Exception as e:
  691. logger.critical(f"QA反馈管理器创建失败: {str(e)}")
  692. raise Exception(f"QA反馈管理器初始化失败: {str(e)}")
  693. return qa_feedback_manager
  694. @app.route('/api/v0/qa_feedback/query', methods=['POST'])
  695. def qa_feedback_query():
  696. """
  697. 查询反馈记录API
  698. 支持分页、筛选和排序功能
  699. """
  700. try:
  701. req = request.get_json(force=True)
  702. # 解析参数,设置默认值
  703. page = req.get('page', 1)
  704. page_size = req.get('page_size', 20)
  705. is_thumb_up = req.get('is_thumb_up')
  706. create_time_start = req.get('create_time_start')
  707. create_time_end = req.get('create_time_end')
  708. is_in_training_data = req.get('is_in_training_data')
  709. sort_by = req.get('sort_by', 'create_time')
  710. sort_order = req.get('sort_order', 'desc')
  711. # 参数验证
  712. if page < 1:
  713. return jsonify(bad_request_response(
  714. response_text="页码必须大于0",
  715. invalid_params=["page"]
  716. )), 400
  717. if page_size < 1 or page_size > 100:
  718. return jsonify(bad_request_response(
  719. response_text="每页大小必须在1-100之间",
  720. invalid_params=["page_size"]
  721. )), 400
  722. # 获取反馈管理器并查询
  723. manager = get_qa_feedback_manager()
  724. records, total = manager.query_feedback(
  725. page=page,
  726. page_size=page_size,
  727. is_thumb_up=is_thumb_up,
  728. create_time_start=create_time_start,
  729. create_time_end=create_time_end,
  730. is_in_training_data=is_in_training_data,
  731. sort_by=sort_by,
  732. sort_order=sort_order
  733. )
  734. total_pages = (total + page_size - 1) // page_size
  735. return jsonify(success_response(
  736. response_text=f"查询成功,共找到 {total} 条记录",
  737. data={
  738. "records": records,
  739. "pagination": {
  740. "page": page,
  741. "page_size": page_size,
  742. "total": total,
  743. "total_pages": total_pages,
  744. "has_next": page < total_pages,
  745. "has_prev": page > 1
  746. }
  747. }
  748. ))
  749. except Exception as e:
  750. logger.error(f"qa_feedback_query执行失败: {str(e)}")
  751. return jsonify(internal_error_response(
  752. response_text="查询反馈记录失败,请稍后重试"
  753. )), 500
  754. @app.route('/api/v0/qa_feedback/delete/<int:feedback_id>', methods=['DELETE'])
  755. def qa_feedback_delete(feedback_id):
  756. """删除反馈记录API"""
  757. try:
  758. manager = get_qa_feedback_manager()
  759. success = manager.delete_feedback(feedback_id)
  760. if success:
  761. return jsonify(success_response(
  762. response_text=f"反馈记录删除成功",
  763. data={"deleted_id": feedback_id}
  764. ))
  765. else:
  766. return jsonify(not_found_response(
  767. response_text=f"反馈记录不存在 (ID: {feedback_id})"
  768. )), 404
  769. except Exception as e:
  770. logger.error(f"qa_feedback_delete执行失败: {str(e)}")
  771. return jsonify(internal_error_response(
  772. response_text="删除反馈记录失败,请稍后重试"
  773. )), 500
  774. @app.route('/api/v0/qa_feedback/update/<int:feedback_id>', methods=['PUT'])
  775. def qa_feedback_update(feedback_id):
  776. """更新反馈记录API"""
  777. try:
  778. req = request.get_json(force=True)
  779. allowed_fields = ['question', 'sql', 'is_thumb_up', 'user_id', 'is_in_training_data']
  780. update_data = {}
  781. for field in allowed_fields:
  782. if field in req:
  783. update_data[field] = req[field]
  784. if not update_data:
  785. return jsonify(bad_request_response(
  786. response_text="没有提供有效的更新字段"
  787. )), 400
  788. manager = get_qa_feedback_manager()
  789. success = manager.update_feedback(feedback_id, **update_data)
  790. if success:
  791. return jsonify(success_response(
  792. response_text="反馈记录更新成功",
  793. data={
  794. "updated_id": feedback_id,
  795. "updated_fields": list(update_data.keys())
  796. }
  797. ))
  798. else:
  799. return jsonify(not_found_response(
  800. response_text=f"反馈记录不存在或无变化 (ID: {feedback_id})"
  801. )), 404
  802. except Exception as e:
  803. logger.error(f"qa_feedback_update执行失败: {str(e)}")
  804. return jsonify(internal_error_response(
  805. response_text="更新反馈记录失败,请稍后重试"
  806. )), 500
  807. @app.route('/api/v0/qa_feedback/add_to_training', methods=['POST'])
  808. def qa_feedback_add_to_training():
  809. """将反馈记录添加到训练数据集API"""
  810. try:
  811. req = request.get_json(force=True)
  812. feedback_ids = req.get('feedback_ids', [])
  813. if not feedback_ids or not isinstance(feedback_ids, list):
  814. return jsonify(bad_request_response(
  815. response_text="缺少有效的反馈ID列表"
  816. )), 400
  817. manager = get_qa_feedback_manager()
  818. records = manager.get_feedback_by_ids(feedback_ids)
  819. if not records:
  820. return jsonify(not_found_response(
  821. response_text="未找到任何有效的反馈记录"
  822. )), 404
  823. positive_count = 0
  824. negative_count = 0
  825. successfully_trained_ids = []
  826. for record in records:
  827. try:
  828. if record['is_in_training_data']:
  829. continue
  830. if record['is_thumb_up']:
  831. training_id = vn.train(
  832. question=record['question'],
  833. sql=record['sql']
  834. )
  835. positive_count += 1
  836. else:
  837. training_id = vn.train_error_sql(
  838. question=record['question'],
  839. sql=record['sql']
  840. )
  841. negative_count += 1
  842. successfully_trained_ids.append(record['id'])
  843. except Exception as e:
  844. logger.error(f"训练失败 - 反馈ID: {record['id']}, 错误: {e}")
  845. if successfully_trained_ids:
  846. manager.mark_training_status(successfully_trained_ids, True)
  847. return jsonify(success_response(
  848. response_text=f"训练数据添加完成,成功处理 {positive_count + negative_count} 条记录",
  849. data={
  850. "positive_trained": positive_count,
  851. "negative_trained": negative_count,
  852. "successfully_trained_ids": successfully_trained_ids
  853. }
  854. ))
  855. except Exception as e:
  856. logger.error(f"qa_feedback_add_to_training执行失败: {str(e)}")
  857. return jsonify(internal_error_response(
  858. response_text="添加训练数据失败,请稍后重试"
  859. )), 500
  860. @app.route('/api/v0/qa_feedback/add', methods=['POST'])
  861. def qa_feedback_add():
  862. """添加反馈记录API"""
  863. try:
  864. req = request.get_json(force=True)
  865. question = req.get('question')
  866. sql = req.get('sql')
  867. is_thumb_up = req.get('is_thumb_up')
  868. user_id = req.get('user_id', 'guest')
  869. if not question or not sql or is_thumb_up is None:
  870. return jsonify(bad_request_response(
  871. response_text="缺少必需参数"
  872. )), 400
  873. manager = get_qa_feedback_manager()
  874. feedback_id = manager.add_feedback(
  875. question=question,
  876. sql=sql,
  877. is_thumb_up=bool(is_thumb_up),
  878. user_id=user_id
  879. )
  880. return jsonify(success_response(
  881. response_text="反馈记录创建成功",
  882. data={"feedback_id": feedback_id}
  883. ))
  884. except Exception as e:
  885. logger.error(f"qa_feedback_add执行失败: {str(e)}")
  886. return jsonify(internal_error_response(
  887. response_text="创建反馈记录失败,请稍后重试"
  888. )), 500
  889. @app.route('/api/v0/qa_feedback/stats', methods=['GET'])
  890. def qa_feedback_stats():
  891. """反馈统计API"""
  892. try:
  893. manager = get_qa_feedback_manager()
  894. all_records, total_count = manager.query_feedback(page=1, page_size=1)
  895. positive_records, positive_count = manager.query_feedback(page=1, page_size=1, is_thumb_up=True)
  896. negative_records, negative_count = manager.query_feedback(page=1, page_size=1, is_thumb_up=False)
  897. return jsonify(success_response(
  898. response_text="统计信息获取成功",
  899. data={
  900. "total_feedback": total_count,
  901. "positive_feedback": positive_count,
  902. "negative_feedback": negative_count,
  903. "positive_rate": round(positive_count / max(total_count, 1) * 100, 2)
  904. }
  905. ))
  906. except Exception as e:
  907. logger.error(f"qa_feedback_stats执行失败: {str(e)}")
  908. return jsonify(internal_error_response(
  909. response_text="获取统计信息失败,请稍后重试"
  910. )), 500
  911. # ==================== Redis对话管理API ====================
  912. @app.route('/api/v0/user/<user_id>/conversations', methods=['GET'])
  913. def get_user_conversations_redis(user_id: str):
  914. """获取用户的对话列表"""
  915. try:
  916. limit = request.args.get('limit', USER_MAX_CONVERSATIONS, type=int)
  917. conversations = redis_conversation_manager.get_conversations(user_id, limit)
  918. return jsonify(success_response(
  919. response_text="获取用户对话列表成功",
  920. data={
  921. "user_id": user_id,
  922. "conversations": conversations,
  923. "total_count": len(conversations)
  924. }
  925. ))
  926. except Exception as e:
  927. return jsonify(internal_error_response(
  928. response_text="获取对话列表失败,请稍后重试"
  929. )), 500
  930. @app.route('/api/v0/conversation/<conversation_id>/messages', methods=['GET'])
  931. def get_conversation_messages_redis(conversation_id: str):
  932. """获取特定对话的消息历史"""
  933. try:
  934. limit = request.args.get('limit', type=int)
  935. messages = redis_conversation_manager.get_conversation_messages(conversation_id, limit)
  936. meta = redis_conversation_manager.get_conversation_meta(conversation_id)
  937. return jsonify(success_response(
  938. response_text="获取对话消息成功",
  939. data={
  940. "conversation_id": conversation_id,
  941. "conversation_meta": meta,
  942. "messages": messages,
  943. "message_count": len(messages)
  944. }
  945. ))
  946. except Exception as e:
  947. return jsonify(internal_error_response(
  948. response_text="获取对话消息失败"
  949. )), 500
  950. @app.route('/api/v0/conversation_stats', methods=['GET'])
  951. def conversation_stats():
  952. """获取对话系统统计信息"""
  953. try:
  954. stats = redis_conversation_manager.get_stats()
  955. return jsonify(success_response(
  956. response_text="获取统计信息成功",
  957. data=stats
  958. ))
  959. except Exception as e:
  960. return jsonify(internal_error_response(
  961. response_text="获取统计信息失败,请稍后重试"
  962. )), 500
  963. @app.route('/api/v0/conversation_cleanup', methods=['POST'])
  964. def conversation_cleanup():
  965. """手动清理过期对话"""
  966. try:
  967. redis_conversation_manager.cleanup_expired_conversations()
  968. return jsonify(success_response(
  969. response_text="对话清理完成"
  970. ))
  971. except Exception as e:
  972. return jsonify(internal_error_response(
  973. response_text="对话清理失败,请稍后重试"
  974. )), 500
  975. @app.route('/api/v0/embedding_cache_stats', methods=['GET'])
  976. def embedding_cache_stats():
  977. """获取embedding缓存统计信息"""
  978. try:
  979. from common.embedding_cache_manager import get_embedding_cache_manager
  980. cache_manager = get_embedding_cache_manager()
  981. stats = cache_manager.get_cache_stats()
  982. return jsonify(success_response(
  983. response_text="获取embedding缓存统计成功",
  984. data=stats
  985. ))
  986. except Exception as e:
  987. logger.error(f"获取embedding缓存统计失败: {str(e)}")
  988. return jsonify(internal_error_response(
  989. response_text="获取embedding缓存统计失败,请稍后重试"
  990. )), 500
  991. @app.route('/api/v0/embedding_cache_cleanup', methods=['POST'])
  992. def embedding_cache_cleanup():
  993. """清空所有embedding缓存"""
  994. try:
  995. from common.embedding_cache_manager import get_embedding_cache_manager
  996. cache_manager = get_embedding_cache_manager()
  997. if not cache_manager.is_available():
  998. return jsonify(internal_error_response(
  999. response_text="Embedding缓存功能未启用或不可用"
  1000. )), 400
  1001. success = cache_manager.clear_all_cache()
  1002. if success:
  1003. return jsonify(success_response(
  1004. response_text="所有embedding缓存已清空",
  1005. data={"cleared": True}
  1006. ))
  1007. else:
  1008. return jsonify(internal_error_response(
  1009. response_text="清空embedding缓存失败"
  1010. )), 500
  1011. except Exception as e:
  1012. logger.error(f"清空embedding缓存失败: {str(e)}")
  1013. return jsonify(internal_error_response(
  1014. response_text="清空embedding缓存失败,请稍后重试"
  1015. )), 500
  1016. # ==================== 训练数据管理API ====================
  1017. def validate_sql_syntax(sql: str) -> tuple[bool, str]:
  1018. """SQL语法检查"""
  1019. try:
  1020. parsed = sqlparse.parse(sql.strip())
  1021. if not parsed or not parsed[0].tokens:
  1022. return False, "SQL语法错误:空语句"
  1023. sql_upper = sql.strip().upper()
  1024. if not any(sql_upper.startswith(keyword) for keyword in
  1025. ['SELECT', 'INSERT', 'UPDATE', 'DELETE', 'CREATE', 'ALTER', 'DROP']):
  1026. return False, "SQL语法错误:不是有效的SQL语句"
  1027. return True, ""
  1028. except Exception as e:
  1029. return False, f"SQL语法错误:{str(e)}"
  1030. def paginate_data(data_list: list, page: int, page_size: int):
  1031. """分页算法"""
  1032. total = len(data_list)
  1033. start_idx = (page - 1) * page_size
  1034. end_idx = start_idx + page_size
  1035. page_data = data_list[start_idx:end_idx]
  1036. total_pages = (total + page_size - 1) // page_size
  1037. return {
  1038. "data": page_data,
  1039. "pagination": {
  1040. "page": page,
  1041. "page_size": page_size,
  1042. "total": total,
  1043. "total_pages": total_pages,
  1044. "has_next": end_idx < total,
  1045. "has_prev": page > 1
  1046. }
  1047. }
  1048. def filter_by_type(data_list: list, training_data_type: str):
  1049. """按类型筛选算法"""
  1050. if not training_data_type:
  1051. return data_list
  1052. return [
  1053. record for record in data_list
  1054. if record.get('training_data_type') == training_data_type
  1055. ]
  1056. def search_in_data(data_list: list, search_keyword: str):
  1057. """在数据中搜索关键词"""
  1058. if not search_keyword:
  1059. return data_list
  1060. keyword_lower = search_keyword.lower()
  1061. return [
  1062. record for record in data_list
  1063. if (record.get('question') and keyword_lower in record['question'].lower()) or
  1064. (record.get('content') and keyword_lower in record['content'].lower())
  1065. ]
  1066. def get_total_training_count():
  1067. """获取当前训练数据总数"""
  1068. try:
  1069. training_data = vn.get_training_data()
  1070. if training_data is not None and not training_data.empty:
  1071. return len(training_data)
  1072. return 0
  1073. except Exception as e:
  1074. logger.warning(f"获取训练数据总数失败: {e}")
  1075. return 0
  1076. def process_single_training_item(item: dict, index: int) -> dict:
  1077. """处理单个训练数据项"""
  1078. training_type = item.get('training_data_type')
  1079. if training_type == 'sql':
  1080. sql = item.get('sql')
  1081. if not sql:
  1082. raise ValueError("SQL字段是必需的")
  1083. # SQL语法检查
  1084. is_valid, error_msg = validate_sql_syntax(sql)
  1085. if not is_valid:
  1086. raise ValueError(error_msg)
  1087. question = item.get('question')
  1088. if question:
  1089. training_id = vn.train(question=question, sql=sql)
  1090. else:
  1091. training_id = vn.train(sql=sql)
  1092. elif training_type == 'error_sql':
  1093. # error_sql不需要语法检查
  1094. question = item.get('question')
  1095. sql = item.get('sql')
  1096. if not question or not sql:
  1097. raise ValueError("question和sql字段都是必需的")
  1098. training_id = vn.train_error_sql(question=question, sql=sql)
  1099. elif training_type == 'documentation':
  1100. content = item.get('content')
  1101. if not content:
  1102. raise ValueError("content字段是必需的")
  1103. training_id = vn.train(documentation=content)
  1104. elif training_type == 'ddl':
  1105. ddl = item.get('ddl')
  1106. if not ddl:
  1107. raise ValueError("ddl字段是必需的")
  1108. training_id = vn.train(ddl=ddl)
  1109. else:
  1110. raise ValueError(f"不支持的训练数据类型: {training_type}")
  1111. return {
  1112. "index": index,
  1113. "success": True,
  1114. "training_id": training_id,
  1115. "type": training_type,
  1116. "message": f"{training_type}训练数据创建成功"
  1117. }
  1118. @app.route('/api/v0/training_data/stats', methods=['GET'])
  1119. def training_data_stats():
  1120. """获取训练数据统计信息API"""
  1121. try:
  1122. training_data = vn.get_training_data()
  1123. if training_data is None or training_data.empty:
  1124. return jsonify(success_response(
  1125. response_text="统计信息获取成功",
  1126. data={
  1127. "total_count": 0,
  1128. "type_breakdown": {
  1129. "sql": 0,
  1130. "documentation": 0,
  1131. "ddl": 0,
  1132. "error_sql": 0
  1133. },
  1134. "type_percentages": {
  1135. "sql": 0.0,
  1136. "documentation": 0.0,
  1137. "ddl": 0.0,
  1138. "error_sql": 0.0
  1139. },
  1140. "last_updated": datetime.now().isoformat()
  1141. }
  1142. ))
  1143. total_count = len(training_data)
  1144. # 统计各类型数量
  1145. type_breakdown = {"sql": 0, "documentation": 0, "ddl": 0, "error_sql": 0}
  1146. if 'training_data_type' in training_data.columns:
  1147. type_counts = training_data['training_data_type'].value_counts()
  1148. for data_type, count in type_counts.items():
  1149. if data_type in type_breakdown:
  1150. type_breakdown[data_type] = int(count)
  1151. # 计算百分比
  1152. type_percentages = {}
  1153. for data_type, count in type_breakdown.items():
  1154. type_percentages[data_type] = round(count / max(total_count, 1) * 100, 2)
  1155. return jsonify(success_response(
  1156. response_text="统计信息获取成功",
  1157. data={
  1158. "total_count": total_count,
  1159. "type_breakdown": type_breakdown,
  1160. "type_percentages": type_percentages,
  1161. "last_updated": datetime.now().isoformat()
  1162. }
  1163. ))
  1164. except Exception as e:
  1165. logger.error(f"training_data_stats执行失败: {str(e)}")
  1166. return jsonify(internal_error_response(
  1167. response_text="获取统计信息失败,请稍后重试"
  1168. )), 500
  1169. @app.route('/api/v0/training_data/query', methods=['POST'])
  1170. def training_data_query():
  1171. """分页查询训练数据API - 支持类型筛选、搜索和排序功能"""
  1172. try:
  1173. req = request.get_json(force=True)
  1174. # 解析参数,设置默认值
  1175. page = req.get('page', 1)
  1176. page_size = req.get('page_size', 20)
  1177. training_data_type = req.get('training_data_type')
  1178. sort_by = req.get('sort_by', 'id')
  1179. sort_order = req.get('sort_order', 'desc')
  1180. search_keyword = req.get('search_keyword')
  1181. # 参数验证
  1182. if page < 1:
  1183. return jsonify(bad_request_response(
  1184. response_text="页码必须大于0",
  1185. missing_params=["page"]
  1186. )), 400
  1187. if page_size < 1 or page_size > 100:
  1188. return jsonify(bad_request_response(
  1189. response_text="每页大小必须在1-100之间",
  1190. missing_params=["page_size"]
  1191. )), 400
  1192. if search_keyword and len(search_keyword) > 100:
  1193. return jsonify(bad_request_response(
  1194. response_text="搜索关键词最大长度为100字符",
  1195. missing_params=["search_keyword"]
  1196. )), 400
  1197. # 获取训练数据
  1198. training_data = vn.get_training_data()
  1199. if training_data is None or training_data.empty:
  1200. return jsonify(success_response(
  1201. response_text="查询成功,暂无训练数据",
  1202. data={
  1203. "records": [],
  1204. "pagination": {
  1205. "page": page,
  1206. "page_size": page_size,
  1207. "total": 0,
  1208. "total_pages": 0,
  1209. "has_next": False,
  1210. "has_prev": False
  1211. },
  1212. "filters_applied": {
  1213. "training_data_type": training_data_type,
  1214. "search_keyword": search_keyword
  1215. }
  1216. }
  1217. ))
  1218. # 转换为列表格式
  1219. records = training_data.to_dict(orient="records")
  1220. # 应用筛选条件
  1221. if training_data_type:
  1222. records = filter_by_type(records, training_data_type)
  1223. if search_keyword:
  1224. records = search_in_data(records, search_keyword)
  1225. # 排序
  1226. if sort_by in ['id', 'training_data_type']:
  1227. reverse = (sort_order.lower() == 'desc')
  1228. records.sort(key=lambda x: x.get(sort_by, ''), reverse=reverse)
  1229. # 分页
  1230. paginated_result = paginate_data(records, page, page_size)
  1231. return jsonify(success_response(
  1232. response_text=f"查询成功,共找到 {paginated_result['pagination']['total']} 条记录",
  1233. data={
  1234. "records": paginated_result["data"],
  1235. "pagination": paginated_result["pagination"],
  1236. "filters_applied": {
  1237. "training_data_type": training_data_type,
  1238. "search_keyword": search_keyword
  1239. }
  1240. }
  1241. ))
  1242. except Exception as e:
  1243. logger.error(f"training_data_query执行失败: {str(e)}")
  1244. return jsonify(internal_error_response(
  1245. response_text="查询训练数据失败,请稍后重试"
  1246. )), 500
  1247. @app.route('/api/v0/training_data/create', methods=['POST'])
  1248. def training_data_create():
  1249. """创建训练数据API - 支持单条和批量创建,支持四种数据类型"""
  1250. try:
  1251. req = request.get_json(force=True)
  1252. data = req.get('data')
  1253. if not data:
  1254. return jsonify(bad_request_response(
  1255. response_text="缺少必需参数:data",
  1256. missing_params=["data"]
  1257. )), 400
  1258. # 统一处理为列表格式
  1259. if isinstance(data, dict):
  1260. data_list = [data]
  1261. elif isinstance(data, list):
  1262. data_list = data
  1263. else:
  1264. return jsonify(bad_request_response(
  1265. response_text="data字段格式错误,应为对象或数组"
  1266. )), 400
  1267. # 批量操作限制
  1268. if len(data_list) > 50:
  1269. return jsonify(bad_request_response(
  1270. response_text="批量操作最大支持50条记录"
  1271. )), 400
  1272. results = []
  1273. successful_count = 0
  1274. type_summary = {"sql": 0, "documentation": 0, "ddl": 0, "error_sql": 0}
  1275. for index, item in enumerate(data_list):
  1276. try:
  1277. result = process_single_training_item(item, index)
  1278. results.append(result)
  1279. if result['success']:
  1280. successful_count += 1
  1281. type_summary[result['type']] += 1
  1282. except Exception as e:
  1283. results.append({
  1284. "index": index,
  1285. "success": False,
  1286. "type": item.get('training_data_type', 'unknown'),
  1287. "error": str(e),
  1288. "message": "创建失败"
  1289. })
  1290. # 获取创建后的总记录数
  1291. current_total = get_total_training_count()
  1292. # 根据实际执行结果决定响应状态
  1293. failed_count = len(data_list) - successful_count
  1294. if failed_count == 0:
  1295. # 全部成功
  1296. return jsonify(success_response(
  1297. response_text="训练数据创建完成",
  1298. data={
  1299. "total_requested": len(data_list),
  1300. "successfully_created": successful_count,
  1301. "failed_count": failed_count,
  1302. "results": results,
  1303. "summary": type_summary,
  1304. "current_total_count": current_total
  1305. }
  1306. ))
  1307. elif successful_count == 0:
  1308. # 全部失败
  1309. return jsonify(error_response(
  1310. response_text="训练数据创建失败",
  1311. data={
  1312. "total_requested": len(data_list),
  1313. "successfully_created": successful_count,
  1314. "failed_count": failed_count,
  1315. "results": results,
  1316. "summary": type_summary,
  1317. "current_total_count": current_total
  1318. }
  1319. )), 400
  1320. else:
  1321. # 部分成功,部分失败
  1322. return jsonify(error_response(
  1323. response_text=f"训练数据创建部分成功,成功{successful_count}条,失败{failed_count}条",
  1324. data={
  1325. "total_requested": len(data_list),
  1326. "successfully_created": successful_count,
  1327. "failed_count": failed_count,
  1328. "results": results,
  1329. "summary": type_summary,
  1330. "current_total_count": current_total
  1331. }
  1332. )), 207
  1333. except Exception as e:
  1334. logger.error(f"training_data_create执行失败: {str(e)}")
  1335. return jsonify(internal_error_response(
  1336. response_text="创建训练数据失败,请稍后重试"
  1337. )), 500
  1338. @app.route('/api/v0/training_data/delete', methods=['POST'])
  1339. def training_data_delete():
  1340. """删除训练数据API - 支持批量删除"""
  1341. try:
  1342. req = request.get_json(force=True)
  1343. ids = req.get('ids', [])
  1344. confirm = req.get('confirm', False)
  1345. if not ids or not isinstance(ids, list):
  1346. return jsonify(bad_request_response(
  1347. response_text="缺少有效的ID列表",
  1348. missing_params=["ids"]
  1349. )), 400
  1350. if not confirm:
  1351. return jsonify(bad_request_response(
  1352. response_text="删除操作需要确认,请设置confirm为true"
  1353. )), 400
  1354. # 批量操作限制
  1355. if len(ids) > 50:
  1356. return jsonify(bad_request_response(
  1357. response_text="批量删除最大支持50条记录"
  1358. )), 400
  1359. deleted_ids = []
  1360. failed_ids = []
  1361. failed_details = []
  1362. for training_id in ids:
  1363. try:
  1364. success = vn.remove_training_data(training_id)
  1365. if success:
  1366. deleted_ids.append(training_id)
  1367. else:
  1368. failed_ids.append(training_id)
  1369. failed_details.append({
  1370. "id": training_id,
  1371. "error": "记录不存在或删除失败"
  1372. })
  1373. except Exception as e:
  1374. failed_ids.append(training_id)
  1375. failed_details.append({
  1376. "id": training_id,
  1377. "error": str(e)
  1378. })
  1379. # 获取删除后的总记录数
  1380. current_total = get_total_training_count()
  1381. # 根据实际执行结果决定响应状态
  1382. failed_count = len(failed_ids)
  1383. if failed_count == 0:
  1384. # 全部成功
  1385. return jsonify(success_response(
  1386. response_text="训练数据删除完成",
  1387. data={
  1388. "total_requested": len(ids),
  1389. "successfully_deleted": len(deleted_ids),
  1390. "failed_count": failed_count,
  1391. "deleted_ids": deleted_ids,
  1392. "failed_ids": failed_ids,
  1393. "failed_details": failed_details,
  1394. "current_total_count": current_total
  1395. }
  1396. ))
  1397. elif len(deleted_ids) == 0:
  1398. # 全部失败
  1399. return jsonify(error_response(
  1400. response_text="训练数据删除失败",
  1401. data={
  1402. "total_requested": len(ids),
  1403. "successfully_deleted": len(deleted_ids),
  1404. "failed_count": failed_count,
  1405. "deleted_ids": deleted_ids,
  1406. "failed_ids": failed_ids,
  1407. "failed_details": failed_details,
  1408. "current_total_count": current_total
  1409. }
  1410. )), 400
  1411. else:
  1412. # 部分成功,部分失败
  1413. return jsonify(error_response(
  1414. response_text=f"训练数据删除部分成功,成功{len(deleted_ids)}条,失败{failed_count}条",
  1415. data={
  1416. "total_requested": len(ids),
  1417. "successfully_deleted": len(deleted_ids),
  1418. "failed_count": failed_count,
  1419. "deleted_ids": deleted_ids,
  1420. "failed_ids": failed_ids,
  1421. "failed_details": failed_details,
  1422. "current_total_count": current_total
  1423. }
  1424. )), 207
  1425. except Exception as e:
  1426. logger.error(f"training_data_delete执行失败: {str(e)}")
  1427. return jsonify(internal_error_response(
  1428. response_text="删除训练数据失败,请稍后重试"
  1429. )), 500
  1430. @app.route('/api/v0/training_data/update', methods=['POST'])
  1431. def training_data_update():
  1432. """更新训练数据API - 支持单条更新,采用先删除后插入策略"""
  1433. try:
  1434. req = request.get_json(force=True)
  1435. # 1. 参数验证
  1436. original_id = req.get('id')
  1437. if not original_id:
  1438. return jsonify(bad_request_response(
  1439. response_text="缺少必需参数:id",
  1440. missing_params=["id"]
  1441. )), 400
  1442. training_type = req.get('training_data_type')
  1443. if not training_type:
  1444. return jsonify(bad_request_response(
  1445. response_text="缺少必需参数:training_data_type",
  1446. missing_params=["training_data_type"]
  1447. )), 400
  1448. # 2. 先删除原始记录
  1449. try:
  1450. success = vn.remove_training_data(original_id)
  1451. if not success:
  1452. return jsonify(bad_request_response(
  1453. response_text=f"原始记录 {original_id} 不存在或删除失败"
  1454. )), 400
  1455. except Exception as e:
  1456. return jsonify(internal_error_response(
  1457. response_text=f"删除原始记录失败: {str(e)}"
  1458. )), 500
  1459. # 3. 根据类型验证和准备新数据
  1460. try:
  1461. if training_type == 'sql':
  1462. sql = req.get('sql')
  1463. if not sql:
  1464. return jsonify(bad_request_response(
  1465. response_text="SQL字段是必需的",
  1466. missing_params=["sql"]
  1467. )), 400
  1468. # SQL语法检查
  1469. is_valid, error_msg = validate_sql_syntax(sql)
  1470. if not is_valid:
  1471. return jsonify(bad_request_response(
  1472. response_text=f"SQL语法错误: {error_msg}"
  1473. )), 400
  1474. question = req.get('question')
  1475. if question:
  1476. training_id = vn.train(question=question, sql=sql)
  1477. else:
  1478. training_id = vn.train(sql=sql)
  1479. elif training_type == 'error_sql':
  1480. question = req.get('question')
  1481. sql = req.get('sql')
  1482. if not question or not sql:
  1483. return jsonify(bad_request_response(
  1484. response_text="question和sql字段都是必需的",
  1485. missing_params=["question", "sql"]
  1486. )), 400
  1487. training_id = vn.train_error_sql(question=question, sql=sql)
  1488. elif training_type == 'documentation':
  1489. content = req.get('content')
  1490. if not content:
  1491. return jsonify(bad_request_response(
  1492. response_text="content字段是必需的",
  1493. missing_params=["content"]
  1494. )), 400
  1495. training_id = vn.train(documentation=content)
  1496. elif training_type == 'ddl':
  1497. ddl = req.get('ddl')
  1498. if not ddl:
  1499. return jsonify(bad_request_response(
  1500. response_text="ddl字段是必需的",
  1501. missing_params=["ddl"]
  1502. )), 400
  1503. training_id = vn.train(ddl=ddl)
  1504. else:
  1505. return jsonify(bad_request_response(
  1506. response_text=f"不支持的训练数据类型: {training_type}"
  1507. )), 400
  1508. except Exception as e:
  1509. return jsonify(internal_error_response(
  1510. response_text=f"创建新训练数据失败: {str(e)}"
  1511. )), 500
  1512. # 4. 获取更新后的总记录数
  1513. current_total = get_total_training_count()
  1514. return jsonify(success_response(
  1515. response_text="训练数据更新成功",
  1516. data={
  1517. "original_id": original_id,
  1518. "new_training_id": training_id,
  1519. "type": training_type,
  1520. "current_total_count": current_total
  1521. }
  1522. ))
  1523. except Exception as e:
  1524. logger.error(f"training_data_update执行失败: {str(e)}")
  1525. return jsonify(internal_error_response(
  1526. response_text="更新训练数据失败,请稍后重试"
  1527. )), 500
  1528. # 导入现有的专业训练函数
  1529. from data_pipeline.trainer.run_training import (
  1530. train_ddl_statements,
  1531. train_documentation_blocks,
  1532. train_json_question_sql_pairs,
  1533. train_formatted_question_sql_pairs,
  1534. train_sql_examples
  1535. )
  1536. def get_allowed_extensions(file_type: str) -> list:
  1537. """根据文件类型返回允许的扩展名"""
  1538. type_specific_extensions = {
  1539. 'ddl': ['ddl', 'sql', 'txt', ''], # 支持无扩展名
  1540. 'markdown': ['md', 'markdown'], # 不支持无扩展名
  1541. 'sql_pair_json': ['json', 'txt', ''], # 支持无扩展名
  1542. 'sql_pair': ['sql', 'txt', ''], # 支持无扩展名
  1543. 'sql': ['sql', 'txt', ''] # 支持无扩展名
  1544. }
  1545. return type_specific_extensions.get(file_type, [])
  1546. def validate_file_content(content: str, file_type: str) -> dict:
  1547. """验证文件内容格式"""
  1548. try:
  1549. if file_type == 'ddl':
  1550. # 检查是否包含CREATE语句
  1551. if not re.search(r'\bCREATE\b', content, re.IGNORECASE):
  1552. return {'valid': False, 'error': '文件内容不符合DDL格式,必须包含CREATE语句'}
  1553. elif file_type == 'markdown':
  1554. # 检查是否包含##标题
  1555. if '##' not in content:
  1556. return {'valid': False, 'error': '文件内容不符合Markdown格式,必须包含##标题'}
  1557. elif file_type == 'sql_pair_json':
  1558. # 检查是否为有效JSON
  1559. try:
  1560. data = json.loads(content)
  1561. if not isinstance(data, list) or not data:
  1562. return {'valid': False, 'error': '文件内容不符合JSON问答对格式,必须是非空数组'}
  1563. # 检查是否包含question和sql字段
  1564. for item in data:
  1565. if not isinstance(item, dict):
  1566. return {'valid': False, 'error': '文件内容不符合JSON问答对格式,数组元素必须是对象'}
  1567. has_question = any(key.lower() == 'question' for key in item.keys())
  1568. has_sql = any(key.lower() == 'sql' for key in item.keys())
  1569. if not has_question or not has_sql:
  1570. return {'valid': False, 'error': '文件内容不符合JSON问答对格式,必须包含question和sql字段'}
  1571. except json.JSONDecodeError:
  1572. return {'valid': False, 'error': '文件内容不符合JSON问答对格式,JSON格式错误'}
  1573. elif file_type == 'sql_pair':
  1574. # 检查是否包含Question:和SQL:
  1575. if not re.search(r'\bQuestion\s*:', content, re.IGNORECASE):
  1576. return {'valid': False, 'error': '文件内容不符合问答对格式,必须包含Question:'}
  1577. if not re.search(r'\bSQL\s*:', content, re.IGNORECASE):
  1578. return {'valid': False, 'error': '文件内容不符合问答对格式,必须包含SQL:'}
  1579. elif file_type == 'sql':
  1580. # 检查是否包含;分隔符
  1581. if ';' not in content:
  1582. return {'valid': False, 'error': '文件内容不符合SQL格式,必须包含;分隔符'}
  1583. return {'valid': True}
  1584. except Exception as e:
  1585. return {'valid': False, 'error': f'文件内容验证失败: {str(e)}'}
  1586. @app.route('/api/v0/training_data/upload', methods=['POST'])
  1587. def upload_training_data():
  1588. """上传训练数据文件API - 支持多种文件格式的自动解析和导入"""
  1589. try:
  1590. # 1. 参数验证
  1591. if 'file' not in request.files:
  1592. return jsonify(bad_request_response("未提供文件"))
  1593. file = request.files['file']
  1594. if file.filename == '':
  1595. return jsonify(bad_request_response("未选择文件"))
  1596. # 获取file_type参数
  1597. file_type = request.form.get('file_type')
  1598. if not file_type:
  1599. return jsonify(bad_request_response("缺少必需参数:file_type"))
  1600. # 验证file_type参数
  1601. valid_file_types = ['ddl', 'markdown', 'sql_pair_json', 'sql_pair', 'sql']
  1602. if file_type not in valid_file_types:
  1603. return jsonify(bad_request_response(f"不支持的文件类型:{file_type},支持的类型:{', '.join(valid_file_types)}"))
  1604. # 2. 文件大小验证 (500KB)
  1605. file.seek(0, 2)
  1606. file_size = file.tell()
  1607. file.seek(0)
  1608. if file_size > 500 * 1024: # 500KB
  1609. return jsonify(bad_request_response("文件大小不能超过500KB"))
  1610. # 3. 验证文件扩展名(基于file_type)
  1611. filename = secure_filename(file.filename)
  1612. allowed_extensions = get_allowed_extensions(file_type)
  1613. file_ext = filename.split('.')[-1].lower() if '.' in filename else ''
  1614. if file_ext not in allowed_extensions:
  1615. # 构建友好的错误信息
  1616. non_empty_extensions = [ext for ext in allowed_extensions if ext]
  1617. if '' in allowed_extensions:
  1618. ext_message = f"{', '.join(non_empty_extensions)} 或无扩展名"
  1619. else:
  1620. ext_message = ', '.join(non_empty_extensions)
  1621. return jsonify(bad_request_response(f"文件类型 {file_type} 不支持的文件扩展名:{file_ext},支持的扩展名:{ext_message}"))
  1622. # 4. 读取文件内容并验证格式
  1623. file.seek(0)
  1624. content = file.read().decode('utf-8')
  1625. # 格式验证
  1626. validation_result = validate_file_content(content, file_type)
  1627. if not validation_result['valid']:
  1628. return jsonify(bad_request_response(validation_result['error']))
  1629. # 5. 创建临时文件(复用现有函数需要文件路径)
  1630. temp_file_path = None
  1631. try:
  1632. with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix='.tmp', encoding='utf-8') as tmp_file:
  1633. tmp_file.write(content)
  1634. temp_file_path = tmp_file.name
  1635. # 6. 根据文件类型调用现有的训练函数
  1636. if file_type == 'ddl':
  1637. train_ddl_statements(temp_file_path)
  1638. elif file_type == 'markdown':
  1639. train_documentation_blocks(temp_file_path)
  1640. elif file_type == 'sql_pair_json':
  1641. train_json_question_sql_pairs(temp_file_path)
  1642. elif file_type == 'sql_pair':
  1643. train_formatted_question_sql_pairs(temp_file_path)
  1644. elif file_type == 'sql':
  1645. train_sql_examples(temp_file_path)
  1646. return jsonify(success_response(
  1647. response_text=f"文件上传并训练成功:{filename}",
  1648. data={
  1649. "filename": filename,
  1650. "file_type": file_type,
  1651. "file_size": file_size,
  1652. "status": "completed"
  1653. }
  1654. ))
  1655. except Exception as e:
  1656. logger.error(f"训练失败: {str(e)}")
  1657. return jsonify(internal_error_response(f"训练失败: {str(e)}"))
  1658. finally:
  1659. # 清理临时文件
  1660. if temp_file_path and os.path.exists(temp_file_path):
  1661. try:
  1662. os.unlink(temp_file_path)
  1663. except Exception as e:
  1664. logger.warning(f"清理临时文件失败: {str(e)}")
  1665. except Exception as e:
  1666. logger.error(f"文件上传失败: {str(e)}")
  1667. return jsonify(internal_error_response(f"文件上传失败: {str(e)}"))
  1668. def get_db_connection():
  1669. """获取数据库连接"""
  1670. try:
  1671. from app_config import PGVECTOR_CONFIG
  1672. return psycopg2.connect(**PGVECTOR_CONFIG)
  1673. except Exception as e:
  1674. logger.error(f"数据库连接失败: {str(e)}")
  1675. raise
  1676. def get_db_connection_for_transaction():
  1677. """获取用于事务操作的数据库连接(非自动提交模式)"""
  1678. try:
  1679. from app_config import PGVECTOR_CONFIG
  1680. conn = psycopg2.connect(**PGVECTOR_CONFIG)
  1681. conn.autocommit = False # 设置为非自动提交模式,允许手动控制事务
  1682. return conn
  1683. except Exception as e:
  1684. logger.error(f"数据库连接失败: {str(e)}")
  1685. raise
  1686. @app.route('/api/v0/training_data/combine', methods=['POST'])
  1687. def combine_training_data():
  1688. """合并训练数据API - 支持合并重复记录"""
  1689. try:
  1690. # 1. 参数验证
  1691. data = request.get_json()
  1692. if not data:
  1693. return jsonify(bad_request_response("请求体不能为空"))
  1694. collection_names = data.get('collection_names', [])
  1695. if not collection_names or not isinstance(collection_names, list):
  1696. return jsonify(bad_request_response("collection_names 参数必须是非空数组"))
  1697. # 验证集合名称
  1698. valid_collections = ['sql', 'ddl', 'documentation', 'error_sql']
  1699. invalid_collections = [name for name in collection_names if name not in valid_collections]
  1700. if invalid_collections:
  1701. return jsonify(bad_request_response(f"不支持的集合名称: {invalid_collections}"))
  1702. dry_run = data.get('dry_run', True)
  1703. keep_strategy = data.get('keep_strategy', 'first')
  1704. if keep_strategy not in ['first', 'last', 'by_metadata_time']:
  1705. return jsonify(bad_request_response("keep_strategy 必须是 'first', 'last' 或 'by_metadata_time'"))
  1706. # 2. 获取数据库连接(用于事务操作)
  1707. conn = get_db_connection_for_transaction()
  1708. cursor = conn.cursor()
  1709. # 3. 查找重复记录
  1710. duplicate_groups = []
  1711. total_before = 0
  1712. total_duplicates = 0
  1713. collections_stats = {}
  1714. for collection_name in collection_names:
  1715. # 获取集合ID
  1716. cursor.execute(
  1717. "SELECT uuid FROM langchain_pg_collection WHERE name = %s",
  1718. (collection_name,)
  1719. )
  1720. collection_result = cursor.fetchone()
  1721. if not collection_result:
  1722. continue
  1723. collection_id = collection_result[0]
  1724. # 统计该集合的记录数
  1725. cursor.execute(
  1726. "SELECT COUNT(*) FROM langchain_pg_embedding WHERE collection_id = %s",
  1727. (collection_id,)
  1728. )
  1729. collection_before = cursor.fetchone()[0]
  1730. total_before += collection_before
  1731. # 查找重复记录
  1732. if keep_strategy in ['first', 'last']:
  1733. order_by = "id"
  1734. else:
  1735. order_by = "COALESCE((cmetadata->>'createdat')::timestamp, '1970-01-01'::timestamp) DESC, id"
  1736. cursor.execute(f"""
  1737. SELECT document, COUNT(*) as duplicate_count,
  1738. array_agg(id ORDER BY {order_by}) as record_ids
  1739. FROM langchain_pg_embedding
  1740. WHERE collection_id = %s
  1741. GROUP BY document
  1742. HAVING COUNT(*) > 1
  1743. """, (collection_id,))
  1744. collection_duplicates = 0
  1745. for row in cursor.fetchall():
  1746. document_content, duplicate_count, record_ids = row
  1747. collection_duplicates += duplicate_count - 1 # 减去要保留的一条
  1748. # 根据保留策略选择要保留的记录
  1749. if keep_strategy == 'first':
  1750. keep_id = record_ids[0]
  1751. remove_ids = record_ids[1:]
  1752. elif keep_strategy == 'last':
  1753. keep_id = record_ids[-1]
  1754. remove_ids = record_ids[:-1]
  1755. else: # by_metadata_time
  1756. keep_id = record_ids[0] # 已经按时间排序
  1757. remove_ids = record_ids[1:]
  1758. duplicate_groups.append({
  1759. "collection_name": collection_name,
  1760. "document_content": document_content[:100] + "..." if len(document_content) > 100 else document_content,
  1761. "duplicate_count": duplicate_count,
  1762. "kept_record_id" if not dry_run else "records_to_keep": keep_id,
  1763. "removed_record_ids" if not dry_run else "records_to_remove": remove_ids
  1764. })
  1765. total_duplicates += collection_duplicates
  1766. collections_stats[collection_name] = {
  1767. "before": collection_before,
  1768. "after": collection_before - collection_duplicates,
  1769. "duplicates_removed" if not dry_run else "duplicates_to_remove": collection_duplicates
  1770. }
  1771. # 4. 执行合并操作(如果不是dry_run)
  1772. if not dry_run:
  1773. try:
  1774. # 连接已经设置为非自动提交模式,直接开始事务
  1775. for group in duplicate_groups:
  1776. remove_ids = group["removed_record_ids"]
  1777. if remove_ids:
  1778. cursor.execute(
  1779. "DELETE FROM langchain_pg_embedding WHERE id = ANY(%s)",
  1780. (remove_ids,)
  1781. )
  1782. conn.commit()
  1783. except Exception as e:
  1784. conn.rollback()
  1785. return jsonify(internal_error_response(f"合并操作失败: {str(e)}"))
  1786. # 5. 构建响应
  1787. total_after = total_before - total_duplicates
  1788. summary = {
  1789. "total_records_before": total_before,
  1790. "total_records_after": total_after,
  1791. "duplicates_removed" if not dry_run else "duplicates_to_remove": total_duplicates,
  1792. "collections_stats": collections_stats
  1793. }
  1794. if dry_run:
  1795. response_text = f"发现 {total_duplicates} 条重复记录,预计删除后将从 {total_before} 条减少到 {total_after} 条记录"
  1796. data_key = "duplicate_groups"
  1797. else:
  1798. response_text = f"成功合并重复记录,删除了 {total_duplicates} 条重复记录,从 {total_before} 条减少到 {total_after} 条记录"
  1799. data_key = "merged_groups"
  1800. return jsonify(success_response(
  1801. response_text=response_text,
  1802. data={
  1803. "dry_run": dry_run,
  1804. "collections_processed": collection_names,
  1805. "summary": summary,
  1806. data_key: duplicate_groups
  1807. }
  1808. ))
  1809. except Exception as e:
  1810. return jsonify(internal_error_response(f"合并操作失败: {str(e)}"))
  1811. finally:
  1812. if 'cursor' in locals():
  1813. cursor.close()
  1814. if 'conn' in locals():
  1815. conn.close()
  1816. # ==================== React Agent 扩展API ====================
  1817. @app.route('/api/v0/react/users/<user_id>/conversations', methods=['GET'])
  1818. async def get_user_conversations_react(user_id: str):
  1819. """异步获取用户的聊天记录列表(从 custom_react_agent 迁移)"""
  1820. global _react_agent_instance
  1821. try:
  1822. # 获取查询参数
  1823. limit = request.args.get('limit', 10, type=int)
  1824. # 限制limit的范围
  1825. limit = max(1, min(limit, 50)) # 限制在1-50之间
  1826. logger.info(f"📋 异步获取用户 {user_id} 的对话列表,限制 {limit} 条")
  1827. # 确保Agent可用
  1828. if not await ensure_agent_ready():
  1829. return jsonify({
  1830. "success": False,
  1831. "error": "Agent 未就绪",
  1832. "timestamp": datetime.now().isoformat()
  1833. }), 503
  1834. # 直接调用异步方法
  1835. conversations = await _react_agent_instance.get_user_recent_conversations(user_id, limit)
  1836. return jsonify({
  1837. "success": True,
  1838. "data": {
  1839. "user_id": user_id,
  1840. "conversations": conversations,
  1841. "total_count": len(conversations),
  1842. "limit": limit
  1843. },
  1844. "timestamp": datetime.now().isoformat()
  1845. }), 200
  1846. except Exception as e:
  1847. logger.error(f"❌ 异步获取用户 {user_id} 对话列表失败: {e}")
  1848. return jsonify({
  1849. "success": False,
  1850. "error": str(e),
  1851. "timestamp": datetime.now().isoformat()
  1852. }), 500
  1853. @app.route('/api/v0/react/users/<user_id>/conversations/<thread_id>', methods=['GET'])
  1854. async def get_user_conversation_detail_react(user_id: str, thread_id: str):
  1855. """异步获取特定对话的详细历史(从 custom_react_agent 迁移)"""
  1856. global _react_agent_instance
  1857. try:
  1858. # 验证thread_id格式是否匹配user_id
  1859. if not thread_id.startswith(f"{user_id}:"):
  1860. return jsonify({
  1861. "success": False,
  1862. "error": f"Thread ID {thread_id} 不属于用户 {user_id}",
  1863. "timestamp": datetime.now().isoformat()
  1864. }), 400
  1865. logger.info(f"📖 异步获取用户 {user_id} 的对话 {thread_id} 详情")
  1866. # 确保Agent可用
  1867. if not await ensure_agent_ready():
  1868. return jsonify({
  1869. "success": False,
  1870. "error": "Agent 未就绪",
  1871. "timestamp": datetime.now().isoformat()
  1872. }), 503
  1873. # 直接调用异步方法
  1874. history = await _react_agent_instance.get_conversation_history(thread_id)
  1875. logger.info(f"✅ 异步成功获取对话历史,消息数量: {len(history)}")
  1876. if not history:
  1877. return jsonify({
  1878. "success": False,
  1879. "error": f"未找到对话 {thread_id}",
  1880. "timestamp": datetime.now().isoformat()
  1881. }), 404
  1882. return jsonify({
  1883. "success": True,
  1884. "data": {
  1885. "user_id": user_id,
  1886. "thread_id": thread_id,
  1887. "message_count": len(history),
  1888. "messages": history
  1889. },
  1890. "timestamp": datetime.now().isoformat()
  1891. }), 200
  1892. except Exception as e:
  1893. import traceback
  1894. logger.error(f"❌ 异步获取对话 {thread_id} 详情失败: {e}")
  1895. logger.error(f"❌ 详细错误信息: {traceback.format_exc()}")
  1896. return jsonify({
  1897. "success": False,
  1898. "error": str(e),
  1899. "timestamp": datetime.now().isoformat()
  1900. }), 500
  1901. @app.route('/api/test/redis', methods=['GET'])
  1902. def test_redis_connection():
  1903. """测试Redis连接和基本查询(从 custom_react_agent 迁移)"""
  1904. try:
  1905. import redis
  1906. # 创建Redis连接
  1907. r = redis.Redis(host='localhost', port=6379, decode_responses=True)
  1908. r.ping()
  1909. # 扫描checkpoint keys
  1910. pattern = "checkpoint:*"
  1911. keys = []
  1912. cursor = 0
  1913. count = 0
  1914. while True:
  1915. cursor, batch = r.scan(cursor=cursor, match=pattern, count=100)
  1916. keys.extend(batch)
  1917. count += len(batch)
  1918. if cursor == 0 or count > 500: # 限制扫描数量
  1919. break
  1920. # 统计用户
  1921. users = {}
  1922. for key in keys:
  1923. try:
  1924. parts = key.split(':')
  1925. if len(parts) >= 2:
  1926. user_id = parts[1]
  1927. users[user_id] = users.get(user_id, 0) + 1
  1928. except:
  1929. continue
  1930. r.close()
  1931. return jsonify({
  1932. "success": True,
  1933. "data": {
  1934. "redis_connected": True,
  1935. "total_checkpoint_keys": len(keys),
  1936. "users_found": list(users.keys()),
  1937. "user_key_counts": users,
  1938. "sample_keys": keys[:5] if keys else []
  1939. },
  1940. "timestamp": datetime.now().isoformat()
  1941. }), 200
  1942. except Exception as e:
  1943. logger.error(f"❌ Redis测试失败: {e}")
  1944. return jsonify({
  1945. "success": False,
  1946. "error": str(e),
  1947. "timestamp": datetime.now().isoformat()
  1948. }), 500
  1949. @app.route('/api/v0/react/direct/users/<user_id>/conversations', methods=['GET'])
  1950. def test_get_user_conversations_simple(user_id: str):
  1951. """测试简单Redis查询获取用户对话列表(从 custom_react_agent 迁移)"""
  1952. try:
  1953. limit = request.args.get('limit', 10, type=int)
  1954. limit = max(1, min(limit, 50))
  1955. logger.info(f"🧪 测试获取用户 {user_id} 的对话列表(简单Redis方式)")
  1956. # 使用简单Redis查询
  1957. conversations = get_user_conversations_simple_sync(user_id, limit)
  1958. return jsonify({
  1959. "success": True,
  1960. "method": "simple_redis_query",
  1961. "data": {
  1962. "user_id": user_id,
  1963. "conversations": conversations,
  1964. "total_count": len(conversations),
  1965. "limit": limit
  1966. },
  1967. "timestamp": datetime.now().isoformat()
  1968. }), 200
  1969. except Exception as e:
  1970. logger.error(f"❌ 测试简单Redis查询失败: {e}")
  1971. return jsonify({
  1972. "success": False,
  1973. "error": str(e),
  1974. "timestamp": datetime.now().isoformat()
  1975. }), 500
  1976. @app.route('/api/v0/react/direct/conversations/<thread_id>', methods=['GET'])
  1977. def get_conversation_detail_api(thread_id: str):
  1978. """
  1979. 获取特定对话的详细信息 - 支持include_tools开关参数(从 custom_react_agent 迁移)
  1980. Query Parameters:
  1981. - include_tools: bool, 是否包含工具调用信息,默认false
  1982. true: 返回完整对话(human/ai/tool/system)
  1983. false: 只返回human/ai消息,清理工具调用信息
  1984. - user_id: str, 可选的用户ID验证
  1985. Examples:
  1986. GET /api/conversations/wang:20250709195048728?include_tools=true # 完整模式
  1987. GET /api/conversations/wang:20250709195048728?include_tools=false # 简化模式(默认)
  1988. GET /api/conversations/wang:20250709195048728 # 简化模式(默认)
  1989. """
  1990. try:
  1991. # 获取查询参数
  1992. include_tools = request.args.get('include_tools', 'false').lower() == 'true'
  1993. user_id = request.args.get('user_id')
  1994. # 验证thread_id格式
  1995. if ':' not in thread_id:
  1996. return jsonify({
  1997. "success": False,
  1998. "error": "Invalid thread_id format. Expected format: user_id:timestamp",
  1999. "timestamp": datetime.now().isoformat()
  2000. }), 400
  2001. # 如果提供了user_id,验证thread_id是否属于该用户
  2002. thread_user_id = thread_id.split(':')[0]
  2003. if user_id and thread_user_id != user_id:
  2004. return jsonify({
  2005. "success": False,
  2006. "error": f"Thread ID {thread_id} does not belong to user {user_id}",
  2007. "timestamp": datetime.now().isoformat()
  2008. }), 400
  2009. logger.info(f"📖 获取对话详情 - Thread: {thread_id}, Include Tools: {include_tools}")
  2010. # 检查enhanced_redis_api是否可用
  2011. if get_conversation_detail_from_redis is None:
  2012. return jsonify({
  2013. "success": False,
  2014. "error": "enhanced_redis_api 模块不可用",
  2015. "timestamp": datetime.now().isoformat()
  2016. }), 503
  2017. # 从Redis获取对话详情(使用我们的新函数)
  2018. result = get_conversation_detail_from_redis(thread_id, include_tools)
  2019. if not result['success']:
  2020. logger.warning(f"⚠️ 获取对话详情失败: {result['error']}")
  2021. return jsonify({
  2022. "success": False,
  2023. "error": result['error'],
  2024. "timestamp": datetime.now().isoformat()
  2025. }), 404
  2026. # 添加API元数据
  2027. result['data']['api_metadata'] = {
  2028. "timestamp": datetime.now().isoformat(),
  2029. "api_version": "v1",
  2030. "endpoint": "get_conversation_detail",
  2031. "query_params": {
  2032. "include_tools": include_tools,
  2033. "user_id": user_id
  2034. }
  2035. }
  2036. mode_desc = "完整模式" if include_tools else "简化模式"
  2037. logger.info(f"✅ 成功获取对话详情 - Messages: {result['data']['message_count']}, Mode: {mode_desc}")
  2038. return jsonify({
  2039. "success": True,
  2040. "data": result['data'],
  2041. "timestamp": datetime.now().isoformat()
  2042. }), 200
  2043. except Exception as e:
  2044. import traceback
  2045. logger.error(f"❌ 获取对话详情异常: {e}")
  2046. logger.error(f"❌ 详细错误信息: {traceback.format_exc()}")
  2047. return jsonify({
  2048. "success": False,
  2049. "error": str(e),
  2050. "timestamp": datetime.now().isoformat()
  2051. }), 500
  2052. @app.route('/api/v0/react/direct/conversations/<thread_id>/compare', methods=['GET'])
  2053. def compare_conversation_modes_api(thread_id: str):
  2054. """
  2055. 比较完整模式和简化模式的对话内容
  2056. 用于调试和理解两种模式的差异(从 custom_react_agent 迁移)
  2057. Examples:
  2058. GET /api/conversations/wang:20250709195048728/compare
  2059. """
  2060. try:
  2061. logger.info(f"🔍 比较对话模式 - Thread: {thread_id}")
  2062. # 检查enhanced_redis_api是否可用
  2063. if get_conversation_detail_from_redis is None:
  2064. return jsonify({
  2065. "success": False,
  2066. "error": "enhanced_redis_api 模块不可用",
  2067. "timestamp": datetime.now().isoformat()
  2068. }), 503
  2069. # 获取完整模式
  2070. full_result = get_conversation_detail_from_redis(thread_id, include_tools=True)
  2071. # 获取简化模式
  2072. simple_result = get_conversation_detail_from_redis(thread_id, include_tools=False)
  2073. if not (full_result['success'] and simple_result['success']):
  2074. return jsonify({
  2075. "success": False,
  2076. "error": "无法获取对话数据进行比较",
  2077. "timestamp": datetime.now().isoformat()
  2078. }), 404
  2079. # 构建比较结果
  2080. comparison = {
  2081. "thread_id": thread_id,
  2082. "full_mode": {
  2083. "message_count": full_result['data']['message_count'],
  2084. "stats": full_result['data']['stats'],
  2085. "sample_messages": full_result['data']['messages'][:3] # 只显示前3条作为示例
  2086. },
  2087. "simple_mode": {
  2088. "message_count": simple_result['data']['message_count'],
  2089. "stats": simple_result['data']['stats'],
  2090. "sample_messages": simple_result['data']['messages'][:3] # 只显示前3条作为示例
  2091. },
  2092. "comparison_summary": {
  2093. "message_count_difference": full_result['data']['message_count'] - simple_result['data']['message_count'],
  2094. "tools_filtered_out": full_result['data']['stats'].get('tool_messages', 0),
  2095. "ai_messages_with_tools": full_result['data']['stats'].get('messages_with_tools', 0),
  2096. "filtering_effectiveness": "有效" if (full_result['data']['message_count'] - simple_result['data']['message_count']) > 0 else "无差异"
  2097. },
  2098. "metadata": {
  2099. "timestamp": datetime.now().isoformat(),
  2100. "note": "sample_messages 只显示前3条消息作为示例,完整消息请使用相应的详情API"
  2101. }
  2102. }
  2103. logger.info(f"✅ 模式比较完成 - 完整: {comparison['full_mode']['message_count']}, 简化: {comparison['simple_mode']['message_count']}")
  2104. return jsonify({
  2105. "success": True,
  2106. "data": comparison,
  2107. "timestamp": datetime.now().isoformat()
  2108. }), 200
  2109. except Exception as e:
  2110. logger.error(f"❌ 对话模式比较失败: {e}")
  2111. return jsonify({
  2112. "success": False,
  2113. "error": str(e),
  2114. "timestamp": datetime.now().isoformat()
  2115. }), 500
  2116. @app.route('/api/v0/react/direct/conversations/<thread_id>/summary', methods=['GET'])
  2117. def get_conversation_summary_api(thread_id: str):
  2118. """
  2119. 获取对话摘要信息(只包含基本统计,不返回具体消息)(从 custom_react_agent 迁移)
  2120. Query Parameters:
  2121. - include_tools: bool, 影响统计信息的计算方式
  2122. Examples:
  2123. GET /api/conversations/wang:20250709195048728/summary?include_tools=true
  2124. """
  2125. try:
  2126. include_tools = request.args.get('include_tools', 'false').lower() == 'true'
  2127. # 验证thread_id格式
  2128. if ':' not in thread_id:
  2129. return jsonify({
  2130. "success": False,
  2131. "error": "Invalid thread_id format. Expected format: user_id:timestamp",
  2132. "timestamp": datetime.now().isoformat()
  2133. }), 400
  2134. logger.info(f"📊 获取对话摘要 - Thread: {thread_id}, Include Tools: {include_tools}")
  2135. # 检查enhanced_redis_api是否可用
  2136. if get_conversation_detail_from_redis is None:
  2137. return jsonify({
  2138. "success": False,
  2139. "error": "enhanced_redis_api 模块不可用",
  2140. "timestamp": datetime.now().isoformat()
  2141. }), 503
  2142. # 获取完整对话信息
  2143. result = get_conversation_detail_from_redis(thread_id, include_tools)
  2144. if not result['success']:
  2145. return jsonify({
  2146. "success": False,
  2147. "error": result['error'],
  2148. "timestamp": datetime.now().isoformat()
  2149. }), 404
  2150. # 只返回摘要信息,不包含具体消息
  2151. data = result['data']
  2152. summary = {
  2153. "thread_id": data['thread_id'],
  2154. "user_id": data['user_id'],
  2155. "include_tools": data['include_tools'],
  2156. "message_count": data['message_count'],
  2157. "stats": data['stats'],
  2158. "metadata": data['metadata'],
  2159. "first_message_preview": None,
  2160. "last_message_preview": None,
  2161. "conversation_preview": None
  2162. }
  2163. # 添加消息预览
  2164. messages = data.get('messages', [])
  2165. if messages:
  2166. # 第一条human消息预览
  2167. for msg in messages:
  2168. if msg['type'] == 'human':
  2169. content = str(msg['content'])
  2170. summary['first_message_preview'] = content[:100] + "..." if len(content) > 100 else content
  2171. break
  2172. # 最后一条ai消息预览
  2173. for msg in reversed(messages):
  2174. if msg['type'] == 'ai' and msg.get('content', '').strip():
  2175. content = str(msg['content'])
  2176. summary['last_message_preview'] = content[:100] + "..." if len(content) > 100 else content
  2177. break
  2178. # 生成对话预览(第一条human消息)
  2179. summary['conversation_preview'] = summary['first_message_preview']
  2180. # 添加API元数据
  2181. summary['api_metadata'] = {
  2182. "timestamp": datetime.now().isoformat(),
  2183. "api_version": "v1",
  2184. "endpoint": "get_conversation_summary"
  2185. }
  2186. logger.info(f"✅ 成功获取对话摘要")
  2187. return jsonify({
  2188. "success": True,
  2189. "data": summary,
  2190. "timestamp": datetime.now().isoformat()
  2191. }), 200
  2192. except Exception as e:
  2193. logger.error(f"❌ 获取对话摘要失败: {e}")
  2194. return jsonify({
  2195. "success": False,
  2196. "error": str(e),
  2197. "timestamp": datetime.now().isoformat()
  2198. }), 500
  2199. # ==================== 启动逻辑 ====================
  2200. def signal_handler(signum, frame):
  2201. """信号处理器,优雅退出"""
  2202. logger.info(f"接收到信号 {signum},准备退出...")
  2203. cleanup_resources()
  2204. sys.exit(0)
  2205. if __name__ == '__main__':
  2206. # 注册信号处理器
  2207. signal.signal(signal.SIGINT, signal_handler)
  2208. signal.signal(signal.SIGTERM, signal_handler)
  2209. logger.info("🚀 启动统一API服务...")
  2210. logger.info("📍 服务地址: http://localhost:8084")
  2211. logger.info("🔗 健康检查: http://localhost:8084/health")
  2212. logger.info("📘 React Agent API: http://localhost:8084/api/v0/ask_react_agent")
  2213. logger.info("📘 LangGraph Agent API: http://localhost:8084/api/v0/ask_agent")
  2214. try:
  2215. # 尝试使用ASGI模式启动(推荐)
  2216. import uvicorn
  2217. from asgiref.wsgi import WsgiToAsgi
  2218. logger.info("🚀 使用ASGI模式启动异步Flask应用...")
  2219. logger.info(" 这将解决事件循环冲突问题,支持LangGraph异步checkpoint保存")
  2220. # 将Flask WSGI应用转换为ASGI应用
  2221. asgi_app = WsgiToAsgi(app)
  2222. # 使用uvicorn启动ASGI应用
  2223. uvicorn.run(
  2224. asgi_app,
  2225. host="0.0.0.0",
  2226. port=8084,
  2227. log_level="info",
  2228. access_log=True
  2229. )
  2230. except ImportError as e:
  2231. # 如果缺少ASGI依赖,fallback到传统Flask模式
  2232. logger.warning("⚠️ ASGI依赖缺失,使用传统Flask模式启动")
  2233. logger.warning(" 建议安装: pip install uvicorn asgiref")
  2234. logger.warning(" 传统模式可能存在异步事件循环冲突问题")
  2235. # 启动标准Flask应用(支持异步路由)
  2236. app.run(host="0.0.0.0", port=8084, debug=False, threaded=True)
  2237. # Data Pipeline 全局变量 - 从 citu_app.py 迁移
  2238. data_pipeline_manager = None
  2239. data_pipeline_file_manager = None
  2240. def get_data_pipeline_manager():
  2241. """获取Data Pipeline管理器单例(从 citu_app.py 迁移)"""
  2242. global data_pipeline_manager
  2243. if data_pipeline_manager is None:
  2244. data_pipeline_manager = SimpleWorkflowManager()
  2245. return data_pipeline_manager
  2246. def get_data_pipeline_file_manager():
  2247. """获取Data Pipeline文件管理器单例(从 citu_app.py 迁移)"""
  2248. global data_pipeline_file_manager
  2249. if data_pipeline_file_manager is None:
  2250. data_pipeline_file_manager = SimpleFileManager()
  2251. return data_pipeline_file_manager
  2252. # ==================== QA缓存管理API (从 citu_app.py 迁移) ====================
  2253. @app.route('/api/v0/qa_cache_stats', methods=['GET'])
  2254. def qa_cache_stats():
  2255. """获取问答缓存统计信息(从 citu_app.py 迁移)"""
  2256. try:
  2257. stats = redis_conversation_manager.get_qa_cache_stats()
  2258. return jsonify(success_response(
  2259. response_text="获取问答缓存统计成功",
  2260. data=stats
  2261. ))
  2262. except Exception as e:
  2263. logger.error(f"获取问答缓存统计失败: {str(e)}")
  2264. return jsonify(internal_error_response(
  2265. response_text="获取问答缓存统计失败,请稍后重试"
  2266. )), 500
  2267. @app.route('/api/v0/qa_cache_cleanup', methods=['POST'])
  2268. def qa_cache_cleanup():
  2269. """清空所有问答缓存(从 citu_app.py 迁移)"""
  2270. try:
  2271. if not redis_conversation_manager.is_available():
  2272. return jsonify(internal_error_response(
  2273. response_text="Redis连接不可用,无法执行清理操作"
  2274. )), 500
  2275. deleted_count = redis_conversation_manager.clear_all_qa_cache()
  2276. return jsonify(success_response(
  2277. response_text="问答缓存清理完成",
  2278. data={
  2279. "deleted_count": deleted_count,
  2280. "cleared": deleted_count > 0,
  2281. "cleanup_time": datetime.now().isoformat()
  2282. }
  2283. ))
  2284. except Exception as e:
  2285. logger.error(f"清空问答缓存失败: {str(e)}")
  2286. return jsonify(internal_error_response(
  2287. response_text="清空问答缓存失败,请稍后重试"
  2288. )), 500
  2289. # ==================== Database API (从 citu_app.py 迁移) ====================
  2290. @app.route('/api/v0/database/tables', methods=['POST'])
  2291. def get_database_tables():
  2292. """
  2293. 获取数据库表列表(从 citu_app.py 迁移)
  2294. 请求体:
  2295. {
  2296. "db_connection": "postgresql://postgres:postgres@192.168.67.1:5432/highway_db", // 可选,不传则使用默认配置
  2297. "schema": "public,ods", // 可选,支持多个schema用逗号分隔,默认为public
  2298. "table_name_pattern": "ods_*" // 可选,表名模式匹配,支持通配符:ods_*、*_dim、*fact*、ods_%
  2299. }
  2300. 响应:
  2301. {
  2302. "success": true,
  2303. "code": 200,
  2304. "message": "获取表列表成功",
  2305. "data": {
  2306. "tables": ["public.table1", "public.table2", "ods.table3"],
  2307. "total": 3,
  2308. "schemas": ["public", "ods"],
  2309. "table_name_pattern": "ods_*"
  2310. }
  2311. }
  2312. """
  2313. try:
  2314. req = request.get_json(force=True)
  2315. # 处理数据库连接参数(可选)
  2316. db_connection = req.get('db_connection')
  2317. if not db_connection:
  2318. # 使用app_config的默认数据库配置
  2319. import app_config
  2320. db_params = app_config.APP_DB_CONFIG
  2321. db_connection = f"postgresql://{db_params['user']}:{db_params['password']}@{db_params['host']}:{db_params['port']}/{db_params['dbname']}"
  2322. logger.info("使用默认数据库配置获取表列表")
  2323. else:
  2324. logger.info("使用用户指定的数据库配置获取表列表")
  2325. # 可选参数
  2326. schema = req.get('schema', '')
  2327. table_name_pattern = req.get('table_name_pattern')
  2328. # 创建表检查API实例
  2329. table_inspector = TableInspectorAPI()
  2330. # 使用asyncio运行异步方法
  2331. async def get_tables():
  2332. return await table_inspector.get_tables_list(db_connection, schema, table_name_pattern)
  2333. # 在新的事件循环中运行异步方法
  2334. try:
  2335. loop = asyncio.new_event_loop()
  2336. asyncio.set_event_loop(loop)
  2337. tables = loop.run_until_complete(get_tables())
  2338. finally:
  2339. loop.close()
  2340. # 解析schema信息
  2341. parsed_schemas = table_inspector._parse_schemas(schema)
  2342. response_data = {
  2343. "tables": tables,
  2344. "total": len(tables),
  2345. "schemas": parsed_schemas,
  2346. "db_connection_info": {
  2347. "database": db_connection.split('/')[-1].split('?')[0] if '/' in db_connection else "unknown"
  2348. }
  2349. }
  2350. # 如果使用了表名模式,添加到响应中
  2351. if table_name_pattern:
  2352. response_data["table_name_pattern"] = table_name_pattern
  2353. return jsonify(success_response(
  2354. response_text="获取表列表成功",
  2355. data=response_data
  2356. )), 200
  2357. except Exception as e:
  2358. logger.error(f"获取数据库表列表失败: {str(e)}")
  2359. return jsonify(internal_error_response(
  2360. response_text=f"获取表列表失败: {str(e)}"
  2361. )), 500
  2362. @app.route('/api/v0/database/table/ddl', methods=['POST'])
  2363. def get_table_ddl():
  2364. """
  2365. 获取表的DDL语句或MD文档(从 citu_app.py 迁移)
  2366. 请求体:
  2367. {
  2368. "db_connection": "postgresql://postgres:postgres@192.168.67.1:5432/highway_db", // 可选,不传则使用默认配置
  2369. "table": "public.test",
  2370. "business_context": "这是高速公路服务区的相关数据", // 可选
  2371. "type": "ddl" // 可选,支持ddl/md/both,默认为ddl
  2372. }
  2373. 响应:
  2374. {
  2375. "success": true,
  2376. "code": 200,
  2377. "message": "获取表DDL成功",
  2378. "data": {
  2379. "ddl": "create table public.test (...);",
  2380. "md": "## test表...", // 仅当type为md或both时返回
  2381. "table_info": {
  2382. "table_name": "test",
  2383. "schema_name": "public",
  2384. "full_name": "public.test",
  2385. "comment": "测试表",
  2386. "field_count": 10,
  2387. "row_count": 1000
  2388. },
  2389. "fields": [...]
  2390. }
  2391. }
  2392. """
  2393. try:
  2394. req = request.get_json(force=True)
  2395. # 处理参数(table仍为必需,db_connection可选)
  2396. table = req.get('table')
  2397. db_connection = req.get('db_connection')
  2398. if not table:
  2399. return jsonify(bad_request_response(
  2400. response_text="缺少必需参数:table",
  2401. missing_params=['table']
  2402. )), 400
  2403. if not db_connection:
  2404. # 使用app_config的默认数据库配置
  2405. import app_config
  2406. db_params = app_config.APP_DB_CONFIG
  2407. db_connection = f"postgresql://{db_params['user']}:{db_params['password']}@{db_params['host']}:{db_params['port']}/{db_params['dbname']}"
  2408. logger.info("使用默认数据库配置获取表DDL")
  2409. else:
  2410. logger.info("使用用户指定的数据库配置获取表DDL")
  2411. # 可选参数
  2412. business_context = req.get('business_context', '')
  2413. output_type = req.get('type', 'ddl')
  2414. # 验证type参数
  2415. valid_types = ['ddl', 'md', 'both']
  2416. if output_type not in valid_types:
  2417. return jsonify(bad_request_response(
  2418. response_text=f"无效的type参数: {output_type},支持的值: {valid_types}",
  2419. invalid_params=['type']
  2420. )), 400
  2421. # 创建表检查API实例
  2422. table_inspector = TableInspectorAPI()
  2423. # 使用asyncio运行异步方法
  2424. async def get_ddl():
  2425. return await table_inspector.get_table_ddl(
  2426. db_connection=db_connection,
  2427. table=table,
  2428. business_context=business_context,
  2429. output_type=output_type
  2430. )
  2431. # 在新的事件循环中运行异步方法
  2432. try:
  2433. loop = asyncio.new_event_loop()
  2434. asyncio.set_event_loop(loop)
  2435. result = loop.run_until_complete(get_ddl())
  2436. finally:
  2437. loop.close()
  2438. response_data = {
  2439. **result,
  2440. "generation_info": {
  2441. "business_context": business_context,
  2442. "output_type": output_type,
  2443. "has_llm_comments": bool(business_context),
  2444. "database": db_connection.split('/')[-1].split('?')[0] if '/' in db_connection else "unknown"
  2445. }
  2446. }
  2447. return jsonify(success_response(
  2448. response_text=f"获取表{output_type.upper()}成功",
  2449. data=response_data
  2450. )), 200
  2451. except Exception as e:
  2452. logger.error(f"获取表DDL失败: {str(e)}")
  2453. return jsonify(internal_error_response(
  2454. response_text=f"获取表{output_type.upper() if 'output_type' in locals() else 'DDL'}失败: {str(e)}"
  2455. )), 500
  2456. # ==================== Data Pipeline API (从 citu_app.py 迁移) ====================
  2457. @app.route('/api/v0/data_pipeline/tasks', methods=['POST'])
  2458. def create_data_pipeline_task():
  2459. """创建数据管道任务(从 citu_app.py 迁移)"""
  2460. try:
  2461. req = request.get_json(force=True)
  2462. # table_list_file和business_context现在都是可选参数
  2463. # 如果未提供table_list_file,将使用文件上传模式
  2464. # 创建任务(支持可选的db_connection参数)
  2465. manager = get_data_pipeline_manager()
  2466. task_id = manager.create_task(
  2467. table_list_file=req.get('table_list_file'),
  2468. business_context=req.get('business_context'),
  2469. db_name=req.get('db_name'), # 可选参数,用于指定特定数据库名称
  2470. db_connection=req.get('db_connection'), # 可选参数,用于指定数据库连接字符串
  2471. task_name=req.get('task_name'), # 可选参数,用于指定任务名称
  2472. enable_sql_validation=req.get('enable_sql_validation', True),
  2473. enable_llm_repair=req.get('enable_llm_repair', True),
  2474. modify_original_file=req.get('modify_original_file', True),
  2475. enable_training_data_load=req.get('enable_training_data_load', True)
  2476. )
  2477. # 获取任务信息
  2478. task_info = manager.get_task_status(task_id)
  2479. response_data = {
  2480. "task_id": task_id,
  2481. "task_name": task_info.get('task_name'),
  2482. "status": task_info.get('status'),
  2483. "created_at": task_info.get('created_at').isoformat() if task_info.get('created_at') else None
  2484. }
  2485. # 检查是否为文件上传模式
  2486. file_upload_mode = not req.get('table_list_file')
  2487. response_message = "任务创建成功"
  2488. if file_upload_mode:
  2489. response_data["file_upload_mode"] = True
  2490. response_data["next_step"] = f"POST /api/v0/data_pipeline/tasks/{task_id}/upload-table-list"
  2491. response_message += ",请上传表清单文件后再执行任务"
  2492. return jsonify(success_response(
  2493. response_text=response_message,
  2494. data=response_data
  2495. )), 201
  2496. except Exception as e:
  2497. logger.error(f"创建数据管道任务失败: {str(e)}")
  2498. return jsonify(internal_error_response(
  2499. response_text="创建任务失败,请稍后重试"
  2500. )), 500
  2501. @app.route('/api/v0/data_pipeline/tasks/<task_id>/execute', methods=['POST'])
  2502. def execute_data_pipeline_task(task_id):
  2503. """执行数据管道任务(从 citu_app.py 迁移)"""
  2504. try:
  2505. req = request.get_json(force=True) if request.is_json else {}
  2506. execution_mode = req.get('execution_mode', 'complete')
  2507. step_name = req.get('step_name')
  2508. # 验证执行模式
  2509. if execution_mode not in ['complete', 'step']:
  2510. return jsonify(bad_request_response(
  2511. response_text="无效的执行模式,必须是 'complete' 或 'step'",
  2512. invalid_params=['execution_mode']
  2513. )), 400
  2514. # 如果是步骤执行模式,验证步骤名称
  2515. if execution_mode == 'step':
  2516. if not step_name:
  2517. return jsonify(bad_request_response(
  2518. response_text="步骤执行模式需要指定step_name",
  2519. missing_params=['step_name']
  2520. )), 400
  2521. valid_steps = ['ddl_generation', 'qa_generation', 'sql_validation', 'training_load']
  2522. if step_name not in valid_steps:
  2523. return jsonify(bad_request_response(
  2524. response_text=f"无效的步骤名称,支持的步骤: {', '.join(valid_steps)}",
  2525. invalid_params=['step_name']
  2526. )), 400
  2527. # 检查任务是否存在
  2528. manager = get_data_pipeline_manager()
  2529. task_info = manager.get_task_status(task_id)
  2530. if not task_info:
  2531. return jsonify(not_found_response(
  2532. response_text=f"任务不存在: {task_id}"
  2533. )), 404
  2534. # 使用subprocess启动独立进程执行任务
  2535. def run_task_subprocess():
  2536. try:
  2537. import subprocess
  2538. import sys
  2539. from pathlib import Path
  2540. # 构建执行命令
  2541. python_executable = sys.executable
  2542. script_path = Path(__file__).parent / "data_pipeline" / "task_executor.py"
  2543. cmd = [
  2544. python_executable,
  2545. str(script_path),
  2546. "--task-id", task_id,
  2547. "--execution-mode", execution_mode
  2548. ]
  2549. if step_name:
  2550. cmd.extend(["--step-name", step_name])
  2551. logger.info(f"启动任务进程: {' '.join(cmd)}")
  2552. # 启动后台进程(不等待完成)
  2553. process = subprocess.Popen(
  2554. cmd,
  2555. stdout=subprocess.PIPE,
  2556. stderr=subprocess.PIPE,
  2557. text=True,
  2558. cwd=Path(__file__).parent
  2559. )
  2560. logger.info(f"任务进程已启动: PID={process.pid}, task_id={task_id}")
  2561. except Exception as e:
  2562. logger.error(f"启动任务进程失败: {task_id}, 错误: {str(e)}")
  2563. # 在新线程中启动subprocess(避免阻塞API响应)
  2564. thread = Thread(target=run_task_subprocess, daemon=True)
  2565. thread.start()
  2566. response_data = {
  2567. "task_id": task_id,
  2568. "execution_mode": execution_mode,
  2569. "step_name": step_name if execution_mode == 'step' else None,
  2570. "message": "任务正在后台执行,请通过状态接口查询进度"
  2571. }
  2572. return jsonify(success_response(
  2573. response_text="任务执行已启动",
  2574. data=response_data
  2575. )), 202
  2576. except Exception as e:
  2577. logger.error(f"启动数据管道任务执行失败: {str(e)}")
  2578. return jsonify(internal_error_response(
  2579. response_text="启动任务执行失败,请稍后重试"
  2580. )), 500
  2581. @app.route('/api/v0/data_pipeline/tasks/<task_id>', methods=['GET'])
  2582. def get_data_pipeline_task_status(task_id):
  2583. """
  2584. 获取数据管道任务状态(从 citu_app.py 迁移)
  2585. 响应:
  2586. {
  2587. "success": true,
  2588. "code": 200,
  2589. "message": "获取任务状态成功",
  2590. "data": {
  2591. "task_id": "task_20250627_143052",
  2592. "status": "in_progress",
  2593. "step_status": {
  2594. "ddl_generation": "completed",
  2595. "qa_generation": "running",
  2596. "sql_validation": "pending",
  2597. "training_load": "pending"
  2598. },
  2599. "created_at": "2025-06-27T14:30:52",
  2600. "started_at": "2025-06-27T14:31:00",
  2601. "parameters": {...},
  2602. "current_execution": {...},
  2603. "total_executions": 2
  2604. }
  2605. }
  2606. """
  2607. try:
  2608. manager = get_data_pipeline_manager()
  2609. task_info = manager.get_task_status(task_id)
  2610. if not task_info:
  2611. return jsonify(not_found_response(
  2612. response_text=f"任务不存在: {task_id}"
  2613. )), 404
  2614. # 获取步骤状态
  2615. steps = manager.get_task_steps(task_id)
  2616. current_step = None
  2617. for step in steps:
  2618. if step['step_status'] == 'running':
  2619. current_step = step
  2620. break
  2621. # 构建步骤状态摘要
  2622. step_status_summary = {}
  2623. for step in steps:
  2624. step_status_summary[step['step_name']] = step['step_status']
  2625. response_data = {
  2626. "task_id": task_info['task_id'],
  2627. "task_name": task_info.get('task_name'),
  2628. "status": task_info['status'],
  2629. "step_status": step_status_summary,
  2630. "created_at": task_info['created_at'].isoformat() if task_info.get('created_at') else None,
  2631. "started_at": task_info['started_at'].isoformat() if task_info.get('started_at') else None,
  2632. "completed_at": task_info['completed_at'].isoformat() if task_info.get('completed_at') else None,
  2633. "parameters": task_info.get('parameters', {}),
  2634. "result": task_info.get('result'),
  2635. "error_message": task_info.get('error_message'),
  2636. "current_step": {
  2637. "execution_id": current_step['execution_id'],
  2638. "step": current_step['step_name'],
  2639. "status": current_step['step_status'],
  2640. "started_at": current_step['started_at'].isoformat() if current_step and current_step.get('started_at') else None
  2641. } if current_step else None,
  2642. "total_steps": len(steps),
  2643. "steps": [{
  2644. "step_name": step['step_name'],
  2645. "step_status": step['step_status'],
  2646. "started_at": step['started_at'].isoformat() if step.get('started_at') else None,
  2647. "completed_at": step['completed_at'].isoformat() if step.get('completed_at') else None,
  2648. "error_message": step.get('error_message')
  2649. } for step in steps]
  2650. }
  2651. return jsonify(success_response(
  2652. response_text="获取任务状态成功",
  2653. data=response_data
  2654. ))
  2655. except Exception as e:
  2656. logger.error(f"获取数据管道任务状态失败: {str(e)}")
  2657. return jsonify(internal_error_response(
  2658. response_text="获取任务状态失败,请稍后重试"
  2659. )), 500
  2660. @app.route('/api/v0/data_pipeline/tasks/<task_id>/logs', methods=['GET'])
  2661. def get_data_pipeline_task_logs(task_id):
  2662. """
  2663. 获取数据管道任务日志(从任务目录文件读取)(从 citu_app.py 迁移)
  2664. 查询参数:
  2665. - limit: 日志行数限制,默认100
  2666. - level: 日志级别过滤,可选
  2667. 响应:
  2668. {
  2669. "success": true,
  2670. "code": 200,
  2671. "message": "获取任务日志成功",
  2672. "data": {
  2673. "task_id": "task_20250627_143052",
  2674. "logs": [
  2675. {
  2676. "timestamp": "2025-06-27 14:30:52",
  2677. "level": "INFO",
  2678. "message": "任务开始执行"
  2679. }
  2680. ],
  2681. "total": 15,
  2682. "source": "file"
  2683. }
  2684. }
  2685. """
  2686. try:
  2687. limit = request.args.get('limit', 100, type=int)
  2688. level = request.args.get('level')
  2689. # 限制最大查询数量
  2690. limit = min(limit, 1000)
  2691. manager = get_data_pipeline_manager()
  2692. # 验证任务是否存在
  2693. task_info = manager.get_task_status(task_id)
  2694. if not task_info:
  2695. return jsonify(not_found_response(
  2696. response_text=f"任务不存在: {task_id}"
  2697. )), 404
  2698. # 获取任务目录下的日志文件
  2699. import os
  2700. from pathlib import Path
  2701. # 获取项目根目录的绝对路径
  2702. project_root = Path(__file__).parent.absolute()
  2703. task_dir = project_root / "data_pipeline" / "training_data" / task_id
  2704. log_file = task_dir / "data_pipeline.log"
  2705. logs = []
  2706. if log_file.exists():
  2707. try:
  2708. # 读取日志文件的最后N行
  2709. with open(log_file, 'r', encoding='utf-8') as f:
  2710. lines = f.readlines()
  2711. # 取最后limit行
  2712. recent_lines = lines[-limit:] if len(lines) > limit else lines
  2713. # 解析日志行
  2714. import re
  2715. log_pattern = r'^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}) \[(\w+)\] (.+?): (.+)$'
  2716. for line in recent_lines:
  2717. line = line.strip()
  2718. if not line:
  2719. continue
  2720. match = re.match(log_pattern, line)
  2721. if match:
  2722. timestamp, log_level, logger_name, message = match.groups()
  2723. # 级别过滤
  2724. if level and log_level != level.upper():
  2725. continue
  2726. logs.append({
  2727. "timestamp": timestamp,
  2728. "level": log_level,
  2729. "logger": logger_name,
  2730. "message": message
  2731. })
  2732. else:
  2733. # 处理多行日志(如异常堆栈)
  2734. if logs:
  2735. logs[-1]["message"] += f"\n{line}"
  2736. except Exception as e:
  2737. logger.error(f"读取日志文件失败: {e}")
  2738. response_data = {
  2739. "task_id": task_id,
  2740. "logs": logs,
  2741. "total": len(logs),
  2742. "source": "file",
  2743. "log_file": str(log_file) if log_file.exists() else None
  2744. }
  2745. return jsonify(success_response(
  2746. response_text="获取任务日志成功",
  2747. data=response_data
  2748. ))
  2749. except Exception as e:
  2750. logger.error(f"获取数据管道任务日志失败: {str(e)}")
  2751. return jsonify(internal_error_response(
  2752. response_text="获取任务日志失败,请稍后重试"
  2753. )), 500
  2754. @app.route('/api/v0/data_pipeline/tasks', methods=['GET'])
  2755. def list_data_pipeline_tasks():
  2756. """获取数据管道任务列表(从 citu_app.py 迁移)"""
  2757. try:
  2758. limit = request.args.get('limit', 50, type=int)
  2759. offset = request.args.get('offset', 0, type=int)
  2760. status_filter = request.args.get('status')
  2761. # 限制查询数量
  2762. limit = min(limit, 100)
  2763. manager = get_data_pipeline_manager()
  2764. tasks = manager.get_tasks_list(
  2765. limit=limit,
  2766. offset=offset,
  2767. status_filter=status_filter
  2768. )
  2769. # 格式化任务列表
  2770. formatted_tasks = []
  2771. for task in tasks:
  2772. formatted_tasks.append({
  2773. "task_id": task.get('task_id'),
  2774. "task_name": task.get('task_name'),
  2775. "status": task.get('status'),
  2776. "step_status": task.get('step_status'),
  2777. "created_at": task['created_at'].isoformat() if task.get('created_at') else None,
  2778. "started_at": task['started_at'].isoformat() if task.get('started_at') else None,
  2779. "completed_at": task['completed_at'].isoformat() if task.get('completed_at') else None,
  2780. "created_by": task.get('by_user'),
  2781. "db_name": task.get('db_name'),
  2782. "business_context": task.get('parameters', {}).get('business_context') if task.get('parameters') else None,
  2783. # 新增字段
  2784. "directory_exists": task.get('directory_exists', True), # 默认为True,兼容旧数据
  2785. "updated_at": task['updated_at'].isoformat() if task.get('updated_at') else None
  2786. })
  2787. response_data = {
  2788. "tasks": formatted_tasks,
  2789. "total": len(formatted_tasks),
  2790. "limit": limit,
  2791. "offset": offset
  2792. }
  2793. return jsonify(success_response(
  2794. response_text="获取任务列表成功",
  2795. data=response_data
  2796. ))
  2797. except Exception as e:
  2798. logger.error(f"获取数据管道任务列表失败: {str(e)}")
  2799. return jsonify(internal_error_response(
  2800. response_text="获取任务列表失败,请稍后重试"
  2801. )), 500
  2802. @app.route('/api/v0/data_pipeline/tasks/query', methods=['POST'])
  2803. def query_data_pipeline_tasks():
  2804. """
  2805. 高级查询数据管道任务列表(从 citu_app.py 迁移)
  2806. 支持复杂筛选、排序、分页功能
  2807. 请求体:
  2808. {
  2809. "page": 1, // 页码,必须大于0,默认1
  2810. "page_size": 20, // 每页大小,1-100之间,默认20
  2811. "status": "completed", // 可选,任务状态筛选:"pending"|"running"|"completed"|"failed"|"cancelled"
  2812. "task_name": "highway", // 可选,任务名称模糊搜索,最大100字符
  2813. "created_by": "user123", // 可选,创建者精确匹配
  2814. "db_name": "highway_db", // 可选,数据库名称精确匹配
  2815. "created_time_start": "2025-01-01T00:00:00", // 可选,创建时间范围开始
  2816. "created_time_end": "2025-12-31T23:59:59", // 可选,创建时间范围结束
  2817. "started_time_start": "2025-01-01T00:00:00", // 可选,开始时间范围开始
  2818. "started_time_end": "2025-12-31T23:59:59", // 可选,开始时间范围结束
  2819. "completed_time_start": "2025-01-01T00:00:00", // 可选,完成时间范围开始
  2820. "completed_time_end": "2025-12-31T23:59:59", // 可选,完成时间范围结束
  2821. "sort_by": "created_at", // 可选,排序字段:"created_at"|"started_at"|"completed_at"|"task_name"|"status",默认"created_at"
  2822. "sort_order": "desc" // 可选,排序方向:"asc"|"desc",默认"desc"
  2823. }
  2824. """
  2825. try:
  2826. # 获取请求数据
  2827. req = request.get_json(force=True) if request.is_json else {}
  2828. # 解析参数,设置默认值
  2829. page = req.get('page', 1)
  2830. page_size = req.get('page_size', 20)
  2831. status = req.get('status')
  2832. task_name = req.get('task_name')
  2833. created_by = req.get('created_by')
  2834. db_name = req.get('db_name')
  2835. created_time_start = req.get('created_time_start')
  2836. created_time_end = req.get('created_time_end')
  2837. started_time_start = req.get('started_time_start')
  2838. started_time_end = req.get('started_time_end')
  2839. completed_time_start = req.get('completed_time_start')
  2840. completed_time_end = req.get('completed_time_end')
  2841. sort_by = req.get('sort_by', 'created_at')
  2842. sort_order = req.get('sort_order', 'desc')
  2843. # 参数验证
  2844. # 验证分页参数
  2845. if page < 1:
  2846. return jsonify(bad_request_response(
  2847. response_text="页码必须大于0",
  2848. invalid_params=['page']
  2849. )), 400
  2850. if page_size < 1 or page_size > 100:
  2851. return jsonify(bad_request_response(
  2852. response_text="每页大小必须在1-100之间",
  2853. invalid_params=['page_size']
  2854. )), 400
  2855. # 验证任务名称长度
  2856. if task_name and len(task_name) > 100:
  2857. return jsonify(bad_request_response(
  2858. response_text="任务名称搜索关键词最大长度为100字符",
  2859. invalid_params=['task_name']
  2860. )), 400
  2861. # 验证排序参数
  2862. allowed_sort_fields = ['created_at', 'started_at', 'completed_at', 'task_name', 'status']
  2863. if sort_by not in allowed_sort_fields:
  2864. return jsonify(bad_request_response(
  2865. response_text=f"不支持的排序字段: {sort_by},支持的字段: {', '.join(allowed_sort_fields)}",
  2866. invalid_params=['sort_by']
  2867. )), 400
  2868. if sort_order.lower() not in ['asc', 'desc']:
  2869. return jsonify(bad_request_response(
  2870. response_text="排序方向必须是 'asc' 或 'desc'",
  2871. invalid_params=['sort_order']
  2872. )), 400
  2873. # 验证状态筛选
  2874. if status:
  2875. allowed_statuses = ['pending', 'running', 'completed', 'failed', 'cancelled']
  2876. if status not in allowed_statuses:
  2877. return jsonify(bad_request_response(
  2878. response_text=f"不支持的状态值: {status},支持的状态: {', '.join(allowed_statuses)}",
  2879. invalid_params=['status']
  2880. )), 400
  2881. # 调用管理器执行查询
  2882. manager = get_data_pipeline_manager()
  2883. result = manager.query_tasks_advanced(
  2884. page=page,
  2885. page_size=page_size,
  2886. status=status,
  2887. task_name=task_name,
  2888. created_by=created_by,
  2889. db_name=db_name,
  2890. created_time_start=created_time_start,
  2891. created_time_end=created_time_end,
  2892. started_time_start=started_time_start,
  2893. started_time_end=started_time_end,
  2894. completed_time_start=completed_time_start,
  2895. completed_time_end=completed_time_end,
  2896. sort_by=sort_by,
  2897. sort_order=sort_order
  2898. )
  2899. # 格式化任务列表
  2900. formatted_tasks = []
  2901. for task in result['tasks']:
  2902. formatted_tasks.append({
  2903. "task_id": task.get('task_id'),
  2904. "task_name": task.get('task_name'),
  2905. "status": task.get('status'),
  2906. "step_status": task.get('step_status'),
  2907. "created_at": task['created_at'].isoformat() if task.get('created_at') else None,
  2908. "started_at": task['started_at'].isoformat() if task.get('started_at') else None,
  2909. "completed_at": task['completed_at'].isoformat() if task.get('completed_at') else None,
  2910. "created_by": task.get('by_user'),
  2911. "db_name": task.get('db_name'),
  2912. "business_context": task.get('parameters', {}).get('business_context') if task.get('parameters') else None,
  2913. "directory_exists": task.get('directory_exists', True),
  2914. "updated_at": task['updated_at'].isoformat() if task.get('updated_at') else None
  2915. })
  2916. # 构建响应数据
  2917. response_data = {
  2918. "tasks": formatted_tasks,
  2919. "pagination": result['pagination'],
  2920. "filters_applied": {
  2921. k: v for k, v in {
  2922. "status": status,
  2923. "task_name": task_name,
  2924. "created_by": created_by,
  2925. "db_name": db_name,
  2926. "created_time_start": created_time_start,
  2927. "created_time_end": created_time_end,
  2928. "started_time_start": started_time_start,
  2929. "started_time_end": started_time_end,
  2930. "completed_time_start": completed_time_start,
  2931. "completed_time_end": completed_time_end
  2932. }.items() if v
  2933. },
  2934. "sort_applied": {
  2935. "sort_by": sort_by,
  2936. "sort_order": sort_order
  2937. },
  2938. "query_time": result.get('query_time', '0.000s')
  2939. }
  2940. return jsonify(success_response(
  2941. response_text="查询任务列表成功",
  2942. data=response_data
  2943. ))
  2944. except Exception as e:
  2945. logger.error(f"查询数据管道任务列表失败: {str(e)}")
  2946. return jsonify(internal_error_response(
  2947. response_text="查询任务列表失败,请稍后重试"
  2948. )), 500
  2949. @app.route('/api/v0/data_pipeline/tasks/<task_id>/files', methods=['GET'])
  2950. def get_data_pipeline_task_files(task_id):
  2951. """获取任务文件列表(从 citu_app.py 迁移)"""
  2952. try:
  2953. file_manager = get_data_pipeline_file_manager()
  2954. # 获取任务文件
  2955. files = file_manager.get_task_files(task_id)
  2956. directory_info = file_manager.get_directory_info(task_id)
  2957. # 格式化文件信息
  2958. formatted_files = []
  2959. for file_info in files:
  2960. formatted_files.append({
  2961. "file_name": file_info['file_name'],
  2962. "file_type": file_info['file_type'],
  2963. "file_size": file_info['file_size'],
  2964. "file_size_formatted": file_info['file_size_formatted'],
  2965. "created_at": file_info['created_at'].isoformat() if file_info.get('created_at') else None,
  2966. "modified_at": file_info['modified_at'].isoformat() if file_info.get('modified_at') else None,
  2967. "is_readable": file_info['is_readable']
  2968. })
  2969. response_data = {
  2970. "task_id": task_id,
  2971. "files": formatted_files,
  2972. "directory_info": directory_info
  2973. }
  2974. return jsonify(success_response(
  2975. response_text="获取任务文件列表成功",
  2976. data=response_data
  2977. ))
  2978. except Exception as e:
  2979. logger.error(f"获取任务文件列表失败: {str(e)}")
  2980. return jsonify(internal_error_response(
  2981. response_text="获取任务文件列表失败,请稍后重试"
  2982. )), 500
  2983. @app.route('/api/v0/data_pipeline/tasks/<task_id>/files/<file_name>', methods=['GET'])
  2984. def download_data_pipeline_task_file(task_id, file_name):
  2985. """下载任务文件(从 citu_app.py 迁移)"""
  2986. try:
  2987. logger.info(f"开始下载文件: task_id={task_id}, file_name={file_name}")
  2988. # 直接构建文件路径,避免依赖数据库
  2989. from pathlib import Path
  2990. import os
  2991. # 获取项目根目录的绝对路径
  2992. project_root = Path(__file__).parent.absolute()
  2993. task_dir = project_root / "data_pipeline" / "training_data" / task_id
  2994. file_path = task_dir / file_name
  2995. logger.info(f"文件路径: {file_path}")
  2996. # 检查文件是否存在
  2997. if not file_path.exists():
  2998. logger.warning(f"文件不存在: {file_path}")
  2999. return jsonify(not_found_response(
  3000. response_text=f"文件不存在: {file_name}"
  3001. )), 404
  3002. # 检查是否为文件(而不是目录)
  3003. if not file_path.is_file():
  3004. logger.warning(f"路径不是文件: {file_path}")
  3005. return jsonify(bad_request_response(
  3006. response_text=f"路径不是有效文件: {file_name}"
  3007. )), 400
  3008. # 安全检查:确保文件在允许的目录内
  3009. try:
  3010. file_path.resolve().relative_to(task_dir.resolve())
  3011. except ValueError:
  3012. logger.warning(f"文件路径不安全: {file_path}")
  3013. return jsonify(bad_request_response(
  3014. response_text="非法的文件路径"
  3015. )), 400
  3016. # 检查文件是否可读
  3017. if not os.access(file_path, os.R_OK):
  3018. logger.warning(f"文件不可读: {file_path}")
  3019. return jsonify(bad_request_response(
  3020. response_text="文件不可读"
  3021. )), 400
  3022. logger.info(f"开始发送文件: {file_path}")
  3023. return send_file(
  3024. file_path,
  3025. as_attachment=True,
  3026. download_name=file_name
  3027. )
  3028. except Exception as e:
  3029. logger.error(f"下载任务文件失败: task_id={task_id}, file_name={file_name}, 错误: {str(e)}", exc_info=True)
  3030. return jsonify(internal_error_response(
  3031. response_text="下载文件失败,请稍后重试"
  3032. )), 500
  3033. @app.route('/api/v0/data_pipeline/tasks/<task_id>/upload-table-list', methods=['POST'])
  3034. def upload_table_list_file(task_id):
  3035. """
  3036. 上传表清单文件(从 citu_app.py 迁移)
  3037. 表单参数:
  3038. - file: 要上传的表清单文件(multipart/form-data)
  3039. 响应:
  3040. {
  3041. "success": true,
  3042. "code": 200,
  3043. "message": "表清单文件上传成功",
  3044. "data": {
  3045. "task_id": "task_20250701_123456",
  3046. "filename": "table_list.txt",
  3047. "file_size": 1024,
  3048. "file_size_formatted": "1.0 KB"
  3049. }
  3050. }
  3051. """
  3052. try:
  3053. # 验证任务是否存在
  3054. manager = get_data_pipeline_manager()
  3055. task_info = manager.get_task_status(task_id)
  3056. if not task_info:
  3057. return jsonify(not_found_response(
  3058. response_text=f"任务不存在: {task_id}"
  3059. )), 404
  3060. # 检查是否有文件上传
  3061. if 'file' not in request.files:
  3062. return jsonify(bad_request_response(
  3063. response_text="请选择要上传的表清单文件",
  3064. missing_params=['file']
  3065. )), 400
  3066. file = request.files['file']
  3067. # 验证文件名
  3068. if file.filename == '':
  3069. return jsonify(bad_request_response(
  3070. response_text="请选择有效的文件"
  3071. )), 400
  3072. try:
  3073. # 使用文件管理器上传文件
  3074. file_manager = get_data_pipeline_file_manager()
  3075. result = file_manager.upload_table_list_file(task_id, file)
  3076. response_data = {
  3077. "task_id": task_id,
  3078. "filename": result["filename"],
  3079. "file_size": result["file_size"],
  3080. "file_size_formatted": result["file_size_formatted"],
  3081. "upload_time": result["upload_time"].isoformat() if result.get("upload_time") else None
  3082. }
  3083. return jsonify(success_response(
  3084. response_text="表清单文件上传成功",
  3085. data=response_data
  3086. )), 200
  3087. except ValueError as e:
  3088. # 文件验证错误(如文件太大、空文件等)
  3089. return jsonify(bad_request_response(
  3090. response_text=str(e)
  3091. )), 400
  3092. except Exception as e:
  3093. logger.error(f"上传表清单文件失败: {str(e)}")
  3094. return jsonify(internal_error_response(
  3095. response_text="文件上传失败,请稍后重试"
  3096. )), 500
  3097. except Exception as e:
  3098. logger.error(f"处理表清单文件上传请求失败: {str(e)}")
  3099. return jsonify(internal_error_response(
  3100. response_text="处理上传请求失败,请稍后重试"
  3101. )), 500
  3102. @app.route('/api/v0/data_pipeline/tasks/<task_id>/table-list-info', methods=['GET'])
  3103. def get_table_list_info(task_id):
  3104. """
  3105. 获取任务的表清单文件信息(从 citu_app.py 迁移)
  3106. 响应:
  3107. {
  3108. "success": true,
  3109. "code": 200,
  3110. "message": "获取表清单文件信息成功",
  3111. "data": {
  3112. "task_id": "task_20250701_123456",
  3113. "has_file": true,
  3114. "filename": "table_list.txt",
  3115. "file_path": "./data_pipeline/training_data/task_20250701_123456/table_list.txt",
  3116. "file_size": 1024,
  3117. "file_size_formatted": "1.0 KB",
  3118. "uploaded_at": "2025-07-01T12:34:56",
  3119. "table_count": 5,
  3120. "is_readable": true
  3121. }
  3122. }
  3123. """
  3124. try:
  3125. file_manager = get_data_pipeline_file_manager()
  3126. # 获取表清单文件信息
  3127. table_list_info = file_manager.get_table_list_file_info(task_id)
  3128. response_data = {
  3129. "task_id": task_id,
  3130. "has_file": table_list_info.get("exists", False),
  3131. **table_list_info
  3132. }
  3133. return jsonify(success_response(
  3134. response_text="获取表清单文件信息成功",
  3135. data=response_data
  3136. ))
  3137. except Exception as e:
  3138. logger.error(f"获取表清单文件信息失败: {str(e)}")
  3139. return jsonify(internal_error_response(
  3140. response_text="获取表清单文件信息失败,请稍后重试"
  3141. )), 500
  3142. @app.route('/api/v0/data_pipeline/tasks/<task_id>/table-list', methods=['POST'])
  3143. def create_table_list_from_names(task_id):
  3144. """
  3145. 通过POST方式提交表名列表并创建table_list.txt文件(从 citu_app.py 迁移)
  3146. 请求体:
  3147. {
  3148. "tables": ["table1", "schema.table2", "table3"]
  3149. }
  3150. 或者:
  3151. {
  3152. "tables": "table1,schema.table2,table3"
  3153. }
  3154. 响应:
  3155. {
  3156. "success": true,
  3157. "code": 200,
  3158. "message": "表清单已成功创建",
  3159. "data": {
  3160. "task_id": "task_20250701_123456",
  3161. "filename": "table_list.txt",
  3162. "table_count": 3,
  3163. "file_size": 45,
  3164. "file_size_formatted": "45 B",
  3165. "created_time": "2025-07-01T12:34:56"
  3166. }
  3167. }
  3168. """
  3169. try:
  3170. # 验证任务是否存在
  3171. manager = get_data_pipeline_manager()
  3172. task_info = manager.get_task_status(task_id)
  3173. if not task_info:
  3174. return jsonify(not_found_response(
  3175. response_text=f"任务不存在: {task_id}"
  3176. )), 404
  3177. # 获取请求数据
  3178. req = request.get_json(force=True)
  3179. tables_param = req.get('tables')
  3180. if not tables_param:
  3181. return jsonify(bad_request_response(
  3182. response_text="缺少必需参数:tables",
  3183. missing_params=['tables']
  3184. )), 400
  3185. # 处理不同格式的表名参数
  3186. try:
  3187. if isinstance(tables_param, str):
  3188. # 逗号分隔的字符串格式
  3189. table_names = [name.strip() for name in tables_param.split(',') if name.strip()]
  3190. elif isinstance(tables_param, list):
  3191. # 数组格式
  3192. table_names = [str(name).strip() for name in tables_param if str(name).strip()]
  3193. else:
  3194. return jsonify(bad_request_response(
  3195. response_text="tables参数格式错误,应为字符串(逗号分隔)或数组"
  3196. )), 400
  3197. if not table_names:
  3198. return jsonify(bad_request_response(
  3199. response_text="表名列表不能为空"
  3200. )), 400
  3201. except Exception as e:
  3202. return jsonify(bad_request_response(
  3203. response_text=f"解析tables参数失败: {str(e)}"
  3204. )), 400
  3205. try:
  3206. # 使用文件管理器创建表清单文件
  3207. file_manager = get_data_pipeline_file_manager()
  3208. result = file_manager.create_table_list_from_names(task_id, table_names)
  3209. response_data = {
  3210. "task_id": task_id,
  3211. "filename": result["filename"],
  3212. "table_count": result["table_count"],
  3213. "unique_table_count": result["unique_table_count"],
  3214. "file_size": result["file_size"],
  3215. "file_size_formatted": result["file_size_formatted"],
  3216. "created_time": result["created_time"].isoformat() if result.get("created_time") else None,
  3217. "original_count": len(table_names) if isinstance(table_names, list) else len(tables_param.split(','))
  3218. }
  3219. return jsonify(success_response(
  3220. response_text=f"表清单已成功创建,包含 {result['table_count']} 个表",
  3221. data=response_data
  3222. )), 200
  3223. except ValueError as e:
  3224. # 表名验证错误(如格式错误、数量限制等)
  3225. return jsonify(bad_request_response(
  3226. response_text=str(e)
  3227. )), 400
  3228. except Exception as e:
  3229. logger.error(f"创建表清单文件失败: {str(e)}")
  3230. return jsonify(internal_error_response(
  3231. response_text="创建表清单文件失败,请稍后重试"
  3232. )), 500
  3233. except Exception as e:
  3234. logger.error(f"处理表清单创建请求失败: {str(e)}")
  3235. return jsonify(internal_error_response(
  3236. response_text="处理请求失败,请稍后重试"
  3237. )), 500
  3238. @app.route('/api/v0/data_pipeline/tasks/<task_id>/files', methods=['POST'])
  3239. def upload_file_to_task(task_id):
  3240. """
  3241. 上传文件到指定任务目录(从 citu_app.py 迁移)
  3242. 表单参数:
  3243. - file: 要上传的文件(multipart/form-data)
  3244. - overwrite_mode: 重名处理模式 (backup, replace, skip),默认为backup
  3245. 支持的文件类型:
  3246. - .ddl: DDL文件
  3247. - .md: Markdown文档
  3248. - .txt: 文本文件
  3249. - .json: JSON文件
  3250. - .sql: SQL文件
  3251. - .csv: CSV文件
  3252. 重名处理模式:
  3253. - backup: 备份原文件(默认)
  3254. - replace: 直接覆盖
  3255. - skip: 跳过上传
  3256. """
  3257. try:
  3258. # 验证任务是否存在
  3259. manager = get_data_pipeline_manager()
  3260. task_info = manager.get_task_status(task_id)
  3261. if not task_info:
  3262. return jsonify(not_found_response(
  3263. response_text=f"任务不存在: {task_id}"
  3264. )), 404
  3265. # 检查是否有文件上传
  3266. if 'file' not in request.files:
  3267. return jsonify(bad_request_response(
  3268. response_text="请选择要上传的文件",
  3269. missing_params=['file']
  3270. )), 400
  3271. file = request.files['file']
  3272. # 验证文件名
  3273. if file.filename == '':
  3274. return jsonify(bad_request_response(
  3275. response_text="请选择有效的文件"
  3276. )), 400
  3277. # 获取重名处理模式
  3278. overwrite_mode = request.form.get('overwrite_mode', 'backup')
  3279. # 验证重名处理模式
  3280. valid_modes = ['backup', 'replace', 'skip']
  3281. if overwrite_mode not in valid_modes:
  3282. return jsonify(bad_request_response(
  3283. response_text=f"无效的overwrite_mode参数: {overwrite_mode},支持的值: {valid_modes}",
  3284. invalid_params=['overwrite_mode']
  3285. )), 400
  3286. try:
  3287. # 使用文件管理器上传文件
  3288. file_manager = get_data_pipeline_file_manager()
  3289. result = file_manager.upload_file_to_task(task_id, file, file.filename, overwrite_mode)
  3290. # 检查是否跳过上传
  3291. if result.get('skipped'):
  3292. return jsonify(success_response(
  3293. response_text=result.get('message', '文件已存在,跳过上传'),
  3294. data=result
  3295. )), 200
  3296. return jsonify(success_response(
  3297. response_text="文件上传成功",
  3298. data=result
  3299. )), 200
  3300. except ValueError as e:
  3301. # 文件验证错误(如文件太大、空文件、不支持的类型等)
  3302. return jsonify(bad_request_response(
  3303. response_text=str(e)
  3304. )), 400
  3305. except Exception as e:
  3306. logger.error(f"上传文件失败: {str(e)}")
  3307. return jsonify(internal_error_response(
  3308. response_text="文件上传失败,请稍后重试"
  3309. )), 500
  3310. except Exception as e:
  3311. logger.error(f"处理文件上传请求失败: {str(e)}")
  3312. return jsonify(internal_error_response(
  3313. response_text="处理上传请求失败,请稍后重试"
  3314. )), 500
  3315. # 任务目录删除功能(从 citu_app.py 迁移)
  3316. import shutil
  3317. from pathlib import Path
  3318. import psycopg2
  3319. from app_config import PGVECTOR_CONFIG
  3320. def delete_task_directory_simple(task_id, delete_database_records=False):
  3321. """
  3322. 简单的任务目录删除功能(从 citu_app.py 迁移)
  3323. - 删除 data_pipeline/training_data/{task_id} 目录
  3324. - 更新数据库中的 directory_exists 字段
  3325. - 可选:删除数据库记录
  3326. """
  3327. try:
  3328. # 1. 删除目录
  3329. project_root = Path(__file__).parent.absolute()
  3330. task_dir = project_root / "data_pipeline" / "training_data" / task_id
  3331. deleted_files_count = 0
  3332. deleted_size = 0
  3333. if task_dir.exists():
  3334. # 计算删除前的统计信息
  3335. for file_path in task_dir.rglob('*'):
  3336. if file_path.is_file():
  3337. deleted_files_count += 1
  3338. deleted_size += file_path.stat().st_size
  3339. # 删除目录
  3340. shutil.rmtree(task_dir)
  3341. directory_deleted = True
  3342. operation_message = "目录删除成功"
  3343. else:
  3344. directory_deleted = False
  3345. operation_message = "目录不存在,无需删除"
  3346. # 2. 更新数据库
  3347. database_records_deleted = False
  3348. try:
  3349. conn = psycopg2.connect(**PGVECTOR_CONFIG)
  3350. cur = conn.cursor()
  3351. if delete_database_records:
  3352. # 删除任务步骤记录
  3353. cur.execute("DELETE FROM data_pipeline_task_steps WHERE task_id = %s", (task_id,))
  3354. # 删除任务主记录
  3355. cur.execute("DELETE FROM data_pipeline_tasks WHERE task_id = %s", (task_id,))
  3356. database_records_deleted = True
  3357. else:
  3358. # 只更新目录状态
  3359. cur.execute("""
  3360. UPDATE data_pipeline_tasks
  3361. SET directory_exists = FALSE, updated_at = CURRENT_TIMESTAMP
  3362. WHERE task_id = %s
  3363. """, (task_id,))
  3364. conn.commit()
  3365. cur.close()
  3366. conn.close()
  3367. except Exception as db_error:
  3368. logger.error(f"数据库操作失败: {db_error}")
  3369. # 数据库失败不影响文件删除的结果
  3370. # 3. 格式化文件大小
  3371. def format_size(size_bytes):
  3372. if size_bytes < 1024:
  3373. return f"{size_bytes} B"
  3374. elif size_bytes < 1024**2:
  3375. return f"{size_bytes/1024:.1f} KB"
  3376. elif size_bytes < 1024**3:
  3377. return f"{size_bytes/(1024**2):.1f} MB"
  3378. else:
  3379. return f"{size_bytes/(1024**3):.1f} GB"
  3380. return {
  3381. "success": True,
  3382. "task_id": task_id,
  3383. "directory_deleted": directory_deleted,
  3384. "database_records_deleted": database_records_deleted,
  3385. "deleted_files_count": deleted_files_count,
  3386. "deleted_size": format_size(deleted_size),
  3387. "deleted_at": datetime.now().isoformat(),
  3388. "operation_message": operation_message # 新增:具体的操作消息
  3389. }
  3390. except Exception as e:
  3391. logger.error(f"删除任务目录失败: {task_id}, 错误: {str(e)}")
  3392. return {
  3393. "success": False,
  3394. "task_id": task_id,
  3395. "error": str(e),
  3396. "error_code": "DELETE_FAILED",
  3397. "operation_message": f"删除操作失败: {str(e)}" # 新增:失败消息
  3398. }
  3399. @app.route('/api/v0/data_pipeline/tasks', methods=['DELETE'])
  3400. def delete_tasks():
  3401. """删除任务目录(支持单个和批量)(从 citu_app.py 迁移)"""
  3402. try:
  3403. # 智能获取参数:支持JSON body和URL查询参数两种方式
  3404. def get_request_parameter(param_name, array_param_name=None):
  3405. """从JSON body或URL查询参数中获取参数值"""
  3406. # 1. 优先从JSON body获取
  3407. if request.is_json:
  3408. try:
  3409. json_data = request.get_json()
  3410. if json_data and param_name in json_data:
  3411. return json_data[param_name]
  3412. except:
  3413. pass
  3414. # 2. 从URL查询参数获取
  3415. if param_name in request.args:
  3416. value = request.args.get(param_name)
  3417. # 处理布尔值
  3418. if value.lower() in ('true', '1', 'yes'):
  3419. return True
  3420. elif value.lower() in ('false', '0', 'no'):
  3421. return False
  3422. return value
  3423. # 3. 处理数组参数(如 task_ids[])
  3424. if array_param_name and array_param_name in request.args:
  3425. return request.args.getlist(array_param_name)
  3426. return None
  3427. # 获取参数
  3428. task_ids = get_request_parameter('task_ids', 'task_ids[]')
  3429. confirm = get_request_parameter('confirm')
  3430. if not task_ids:
  3431. return jsonify(bad_request_response(
  3432. response_text="缺少必需参数: task_ids",
  3433. missing_params=['task_ids']
  3434. )), 400
  3435. if not confirm:
  3436. return jsonify(bad_request_response(
  3437. response_text="缺少必需参数: confirm",
  3438. missing_params=['confirm']
  3439. )), 400
  3440. if confirm != True:
  3441. return jsonify(bad_request_response(
  3442. response_text="confirm参数必须为true以确认删除操作"
  3443. )), 400
  3444. if not isinstance(task_ids, list) or len(task_ids) == 0:
  3445. return jsonify(bad_request_response(
  3446. response_text="task_ids必须是非空的任务ID列表"
  3447. )), 400
  3448. # 获取可选参数
  3449. delete_database_records = get_request_parameter('delete_database_records') or False
  3450. continue_on_error = get_request_parameter('continue_on_error')
  3451. if continue_on_error is None:
  3452. continue_on_error = True
  3453. # 执行批量删除操作
  3454. deleted_tasks = []
  3455. failed_tasks = []
  3456. total_size_freed = 0
  3457. for task_id in task_ids:
  3458. result = delete_task_directory_simple(task_id, delete_database_records)
  3459. if result["success"]:
  3460. deleted_tasks.append(result)
  3461. # 累计释放的空间大小(这里简化处理,实际应该解析size字符串)
  3462. else:
  3463. failed_tasks.append({
  3464. "task_id": task_id,
  3465. "error": result["error"],
  3466. "error_code": result.get("error_code", "UNKNOWN")
  3467. })
  3468. if not continue_on_error:
  3469. break
  3470. # 构建响应
  3471. summary = {
  3472. "total_requested": len(task_ids),
  3473. "successfully_deleted": len(deleted_tasks),
  3474. "failed": len(failed_tasks)
  3475. }
  3476. batch_result = {
  3477. "deleted_tasks": deleted_tasks,
  3478. "failed_tasks": failed_tasks,
  3479. "summary": summary,
  3480. "deleted_at": datetime.now().isoformat()
  3481. }
  3482. # 构建智能响应消息
  3483. if len(task_ids) == 1:
  3484. # 单个删除:使用具体的操作消息
  3485. if summary["failed"] == 0:
  3486. # 从deleted_tasks中获取具体的操作消息
  3487. operation_msg = deleted_tasks[0].get('operation_message', '任务处理完成')
  3488. message = operation_msg
  3489. else:
  3490. # 从failed_tasks中获取错误消息
  3491. error_msg = failed_tasks[0].get('error', '删除失败')
  3492. message = f"任务删除失败: {error_msg}"
  3493. else:
  3494. # 批量删除:统计各种操作结果
  3495. directory_deleted_count = sum(1 for task in deleted_tasks if task.get('directory_deleted', False))
  3496. directory_not_exist_count = sum(1 for task in deleted_tasks if not task.get('directory_deleted', False))
  3497. if summary["failed"] == 0:
  3498. # 全部成功
  3499. if directory_deleted_count > 0 and directory_not_exist_count > 0:
  3500. message = f"批量操作完成:{directory_deleted_count}个目录已删除,{directory_not_exist_count}个目录不存在"
  3501. elif directory_deleted_count > 0:
  3502. message = f"批量删除完成:成功删除{directory_deleted_count}个目录"
  3503. elif directory_not_exist_count > 0:
  3504. message = f"批量操作完成:{directory_not_exist_count}个目录不存在,无需删除"
  3505. else:
  3506. message = "批量操作完成"
  3507. elif summary["successfully_deleted"] == 0:
  3508. message = f"批量删除失败:{summary['failed']}个任务处理失败"
  3509. else:
  3510. message = f"批量删除部分完成:成功{summary['successfully_deleted']}个,失败{summary['failed']}个"
  3511. return jsonify(success_response(
  3512. response_text=message,
  3513. data=batch_result
  3514. )), 200
  3515. except Exception as e:
  3516. logger.error(f"删除任务失败: 错误: {str(e)}")
  3517. return jsonify(internal_error_response(
  3518. response_text="删除任务失败,请稍后重试"
  3519. )), 500
  3520. @app.route('/api/v0/data_pipeline/tasks/<task_id>/logs/query', methods=['POST'])
  3521. def query_data_pipeline_task_logs(task_id):
  3522. """
  3523. 高级查询数据管道任务日志(从 citu_app.py 迁移)
  3524. 支持复杂筛选、排序、分页功能
  3525. 请求体:
  3526. {
  3527. "page": 1, // 页码,必须大于0,默认1
  3528. "page_size": 50, // 每页大小,1-500之间,默认50
  3529. "level": "ERROR", // 可选,日志级别筛选:"DEBUG"|"INFO"|"WARNING"|"ERROR"|"CRITICAL"
  3530. "start_time": "2025-01-01 00:00:00", // 可选,开始时间范围 (YYYY-MM-DD HH:MM:SS)
  3531. "end_time": "2025-01-02 23:59:59", // 可选,结束时间范围 (YYYY-MM-DD HH:MM:SS)
  3532. "keyword": "failed", // 可选,关键字搜索(消息内容模糊匹配)
  3533. "logger_name": "DDLGenerator", // 可选,日志记录器名称精确匹配
  3534. "step_name": "ddl_generation", // 可选,执行步骤名称精确匹配
  3535. "sort_by": "timestamp", // 可选,排序字段:"timestamp"|"level"|"logger"|"step"|"line_number",默认"timestamp"
  3536. "sort_order": "desc" // 可选,排序方向:"asc"|"desc",默认"desc"
  3537. }
  3538. """
  3539. try:
  3540. # 验证任务是否存在
  3541. manager = get_data_pipeline_manager()
  3542. task_info = manager.get_task_status(task_id)
  3543. if not task_info:
  3544. return jsonify(not_found_response(
  3545. response_text=f"任务不存在: {task_id}"
  3546. )), 404
  3547. # 解析请求数据
  3548. request_data = request.get_json() or {}
  3549. # 参数验证
  3550. def _is_valid_time_format(time_str):
  3551. """验证时间格式是否有效"""
  3552. if not time_str:
  3553. return True
  3554. # 支持的时间格式
  3555. time_formats = [
  3556. '%Y-%m-%d %H:%M:%S', # 2025-01-01 00:00:00
  3557. '%Y-%m-%d', # 2025-01-01
  3558. '%Y-%m-%dT%H:%M:%S', # 2025-01-01T00:00:00
  3559. '%Y-%m-%dT%H:%M:%S.%f', # 2025-01-01T00:00:00.123456
  3560. ]
  3561. for fmt in time_formats:
  3562. try:
  3563. from datetime import datetime
  3564. datetime.strptime(time_str, fmt)
  3565. return True
  3566. except ValueError:
  3567. continue
  3568. return False
  3569. # 提取和验证参数
  3570. page = request_data.get('page', 1)
  3571. page_size = request_data.get('page_size', 50)
  3572. level = request_data.get('level')
  3573. start_time = request_data.get('start_time')
  3574. end_time = request_data.get('end_time')
  3575. keyword = request_data.get('keyword')
  3576. logger_name = request_data.get('logger_name')
  3577. step_name = request_data.get('step_name')
  3578. sort_by = request_data.get('sort_by', 'timestamp')
  3579. sort_order = request_data.get('sort_order', 'desc')
  3580. # 参数验证
  3581. if not isinstance(page, int) or page < 1:
  3582. return jsonify(bad_request_response(
  3583. response_text="页码必须是大于0的整数"
  3584. )), 400
  3585. if not isinstance(page_size, int) or page_size < 1 or page_size > 500:
  3586. return jsonify(bad_request_response(
  3587. response_text="每页大小必须是1-500之间的整数"
  3588. )), 400
  3589. # 验证日志级别
  3590. if level and level.upper() not in ['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL']:
  3591. return jsonify(bad_request_response(
  3592. response_text="日志级别必须是DEBUG、INFO、WARNING、ERROR、CRITICAL之一"
  3593. )), 400
  3594. # 验证时间格式
  3595. if not _is_valid_time_format(start_time):
  3596. return jsonify(bad_request_response(
  3597. response_text="开始时间格式无效,支持格式:YYYY-MM-DD HH:MM:SS 或 YYYY-MM-DD"
  3598. )), 400
  3599. if not _is_valid_time_format(end_time):
  3600. return jsonify(bad_request_response(
  3601. response_text="结束时间格式无效,支持格式:YYYY-MM-DD HH:MM:SS 或 YYYY-MM-DD"
  3602. )), 400
  3603. # 验证关键字长度
  3604. if keyword and len(keyword) > 200:
  3605. return jsonify(bad_request_response(
  3606. response_text="关键字长度不能超过200个字符"
  3607. )), 400
  3608. # 验证排序字段
  3609. allowed_sort_fields = ['timestamp', 'level', 'logger', 'step', 'line_number']
  3610. if sort_by not in allowed_sort_fields:
  3611. return jsonify(bad_request_response(
  3612. response_text=f"排序字段必须是以下之一: {', '.join(allowed_sort_fields)}"
  3613. )), 400
  3614. # 验证排序方向
  3615. if sort_order.lower() not in ['asc', 'desc']:
  3616. return jsonify(bad_request_response(
  3617. response_text="排序方向必须是asc或desc"
  3618. )), 400
  3619. # 创建工作流执行器并查询日志
  3620. from data_pipeline.api.simple_workflow import SimpleWorkflowExecutor
  3621. executor = SimpleWorkflowExecutor(task_id)
  3622. try:
  3623. result = executor.query_logs_advanced(
  3624. page=page,
  3625. page_size=page_size,
  3626. level=level,
  3627. start_time=start_time,
  3628. end_time=end_time,
  3629. keyword=keyword,
  3630. logger_name=logger_name,
  3631. step_name=step_name,
  3632. sort_by=sort_by,
  3633. sort_order=sort_order
  3634. )
  3635. return jsonify(success_response(
  3636. response_text="查询任务日志成功",
  3637. data=result
  3638. ))
  3639. finally:
  3640. executor.cleanup()
  3641. except Exception as e:
  3642. logger.error(f"查询数据管道任务日志失败: {str(e)}")
  3643. return jsonify(internal_error_response(
  3644. response_text="查询任务日志失败,请稍后重试"
  3645. )), 500