unified_api.py 186 KB

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