unified_api.py 186 KB

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