unified_api.py 234 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882
  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. @app.route('/api/v0/react/status/<thread_id>', methods=['GET'])
  580. async def get_react_agent_status(thread_id: str):
  581. """获取React Agent执行状态,使用LangGraph API"""
  582. try:
  583. global _react_agent_instance
  584. if not _react_agent_instance:
  585. from common.result import failed
  586. return jsonify(failed(message="Agent实例未初始化", code=500)), 500
  587. # 工具状态映射
  588. TOOL_STATUS_MAPPING = {
  589. "generate_sql": {"name": "生成SQL中", "icon": "🔍"},
  590. "valid_sql": {"name": "验证SQL中", "icon": "✅"},
  591. "run_sql": {"name": "执行查询中", "icon": "⚡"},
  592. }
  593. # 使用LangGraph API获取checkpoint
  594. read_config = {"configurable": {"thread_id": thread_id}}
  595. checkpoint_tuple = await _react_agent_instance.checkpointer.aget_tuple(read_config)
  596. if not checkpoint_tuple or not checkpoint_tuple.checkpoint:
  597. from common.result import failed
  598. return jsonify(failed(message="未找到执行线程", code=404)), 404
  599. # 获取checkpoint数据
  600. checkpoint = checkpoint_tuple.checkpoint
  601. channel_values = checkpoint.get("channel_values", {})
  602. messages = channel_values.get("messages", [])
  603. if not messages:
  604. from common.result import success
  605. return jsonify(success(data={
  606. "status": "running",
  607. "name": "初始化中",
  608. "icon": "🚀",
  609. "timestamp": datetime.now().isoformat()
  610. }, message="获取状态成功"))
  611. # 分析最后一条消息确定状态
  612. last_message = messages[-1]
  613. last_msg_type = last_message.get("type", "") if hasattr(last_message, 'get') else getattr(last_message, 'type', "")
  614. # 如果last_message是对象,需要转换为字典格式
  615. if hasattr(last_message, '__dict__'):
  616. last_message_dict = {
  617. 'type': getattr(last_message, 'type', ''),
  618. 'content': getattr(last_message, 'content', ''),
  619. 'tool_calls': getattr(last_message, 'tool_calls', []) if hasattr(last_message, 'tool_calls') else [],
  620. }
  621. # 如果有additional_kwargs,也包含进来
  622. if hasattr(last_message, 'additional_kwargs'):
  623. last_message_dict.update(last_message.additional_kwargs)
  624. else:
  625. last_message_dict = last_message
  626. # 判断执行状态
  627. if (last_msg_type == "ai" and
  628. not last_message_dict.get("tool_calls", []) and
  629. last_message_dict.get("content", "").strip()):
  630. from common.result import success
  631. return jsonify(success(data={
  632. "status": "completed",
  633. "name": "完成",
  634. "icon": "✅",
  635. "timestamp": datetime.now().isoformat()
  636. }, message="获取状态成功"))
  637. elif (last_msg_type == "ai" and
  638. last_message_dict.get("tool_calls", [])):
  639. tool_calls = last_message_dict.get("tool_calls", [])
  640. tool_name = tool_calls[0].get("name", "") if tool_calls else ""
  641. tool_info = TOOL_STATUS_MAPPING.get(tool_name, {
  642. "name": f"调用{tool_name}中" if tool_name else "调用工具中",
  643. "icon": "🔧"
  644. })
  645. from common.result import success
  646. return jsonify(success(data={
  647. "status": "running",
  648. "name": tool_info["name"],
  649. "icon": tool_info["icon"],
  650. "timestamp": datetime.now().isoformat()
  651. }, message="获取状态成功"))
  652. elif last_msg_type == "tool":
  653. tool_name = last_message_dict.get("name", "")
  654. tool_status = last_message_dict.get("status", "")
  655. if tool_status == "success":
  656. tool_info = TOOL_STATUS_MAPPING.get(tool_name, {"name": "处理中", "icon": "🔄"})
  657. from common.result import success
  658. return jsonify(success(data={
  659. "status": "running",
  660. "name": f"{tool_info['name'].replace('中', '')}完成,AI处理中",
  661. "icon": "🤖",
  662. "timestamp": datetime.now().isoformat()
  663. }, message="获取状态成功"))
  664. else:
  665. tool_info = TOOL_STATUS_MAPPING.get(tool_name, {
  666. "name": f"执行{tool_name}中",
  667. "icon": "⚙️"
  668. })
  669. from common.result import success
  670. return jsonify(success(data={
  671. "status": "running",
  672. "name": tool_info["name"],
  673. "icon": tool_info["icon"],
  674. "timestamp": datetime.now().isoformat()
  675. }, message="获取状态成功"))
  676. else:
  677. from common.result import success
  678. return jsonify(success(data={
  679. "status": "running",
  680. "name": "执行中",
  681. "icon": "⚙️",
  682. "timestamp": datetime.now().isoformat()
  683. }, message="获取状态成功"))
  684. except Exception as e:
  685. from common.result import failed
  686. logger.error(f"获取React Agent状态失败: {e}")
  687. return jsonify(failed(message=f"获取状态失败: {str(e)}", code=500)), 500
  688. @app.route('/api/v0/react/direct/status/<thread_id>', methods=['GET'])
  689. async def get_react_agent_status_direct(thread_id: str):
  690. """直接访问Redis获取React Agent执行状态,绕过Agent实例资源竞争"""
  691. try:
  692. # 工具状态映射
  693. TOOL_STATUS_MAPPING = {
  694. "generate_sql": {"name": "生成SQL中", "icon": "🔍"},
  695. "valid_sql": {"name": "验证SQL中", "icon": "✅"},
  696. "run_sql": {"name": "执行查询中", "icon": "⚡"},
  697. }
  698. # 创建独立的Redis连接,不使用Agent的连接
  699. redis_client = redis.from_url("redis://localhost:6379", decode_responses=True)
  700. try:
  701. # 1. 查找该thread_id的所有checkpoint键
  702. pattern = f"checkpoint:{thread_id}:*"
  703. keys = await redis_client.keys(pattern)
  704. if not keys:
  705. from common.result import failed
  706. return jsonify(failed(message="未找到执行线程", code=404)), 404
  707. # 2. 获取最新的checkpoint键
  708. latest_key = sorted(keys)[-1]
  709. # 3. 检查Redis key的数据类型
  710. key_type = await redis_client.type(latest_key)
  711. logger.info(f"🔍 Redis key类型: {key_type}, key: {latest_key}")
  712. # 4. 根据数据类型获取checkpoint数据
  713. if key_type == "string":
  714. # 字符串类型,直接使用GET
  715. raw_checkpoint_data = await redis_client.get(latest_key)
  716. if raw_checkpoint_data:
  717. checkpoint = json.loads(raw_checkpoint_data)
  718. else:
  719. from common.result import failed
  720. return jsonify(failed(message="无法读取checkpoint数据", code=500)), 500
  721. elif key_type == "ReJSON-RL":
  722. # RedisJSON类型,使用JSON.GET命令
  723. try:
  724. # 使用execute_command执行JSON.GET
  725. checkpoint = await redis_client.execute_command("JSON.GET", latest_key)
  726. if checkpoint:
  727. # JSON.GET返回的是JSON字符串,需要解析
  728. if isinstance(checkpoint, str):
  729. checkpoint = json.loads(checkpoint)
  730. logger.info(f"✅ 成功从RedisJSON获取checkpoint数据")
  731. else:
  732. from common.result import failed
  733. return jsonify(failed(message="无法读取RedisJSON数据", code=500)), 500
  734. except Exception as json_error:
  735. logger.error(f"❌ RedisJSON操作失败: {json_error}")
  736. from common.result import failed
  737. return jsonify(failed(message=f"RedisJSON操作失败: {str(json_error)}", code=500)), 500
  738. elif key_type == "hash":
  739. # Hash类型,使用HGETALL
  740. hash_data = await redis_client.hgetall(latest_key)
  741. logger.info(f"🔍 Hash数据字段: {list(hash_data.keys())}")
  742. # 尝试不同的字段名获取checkpoint
  743. checkpoint_fields = ['checkpoint', 'data', 'value']
  744. checkpoint_data = None
  745. for field in checkpoint_fields:
  746. if field in hash_data:
  747. checkpoint_data = hash_data[field]
  748. break
  749. if not checkpoint_data:
  750. # 如果没有找到标准字段,返回整个hash结构
  751. checkpoint = {"hash_data": hash_data}
  752. else:
  753. try:
  754. checkpoint = json.loads(checkpoint_data)
  755. except json.JSONDecodeError:
  756. # 如果不是JSON,可能是其他格式
  757. checkpoint = {"raw_data": checkpoint_data}
  758. elif key_type == "list":
  759. # List类型,获取所有元素
  760. list_data = await redis_client.lrange(latest_key, 0, -1)
  761. logger.info(f"🔍 List数据长度: {len(list_data)}")
  762. checkpoint = {"list_data": list_data}
  763. else:
  764. from common.result import failed
  765. return jsonify(failed(message=f"不支持的Redis数据类型: {key_type}", code=500)), 500
  766. # 5. 提取messages
  767. messages = []
  768. # 根据不同的checkpoint结构提取messages
  769. if "checkpoint" in checkpoint and "channel_values" in checkpoint["checkpoint"]:
  770. # 标准checkpoint结构(与您的数据匹配)
  771. messages = checkpoint["checkpoint"]["channel_values"].get("messages", [])
  772. logger.info(f"✅ 从标准checkpoint结构提取到 {len(messages)} 条messages")
  773. elif "channel_values" in checkpoint:
  774. # 直接的channel_values结构
  775. messages = checkpoint["channel_values"].get("messages", [])
  776. logger.info(f"✅ 从直接channel_values结构提取到 {len(messages)} 条messages")
  777. elif "hash_data" in checkpoint:
  778. # Hash数据结构,尝试从不同字段提取
  779. hash_data = checkpoint["hash_data"]
  780. logger.info(f"🔍 Hash字段详情: {list(hash_data.keys())}")
  781. # 尝试解析可能包含messages的字段
  782. for key, value in hash_data.items():
  783. try:
  784. parsed_data = json.loads(value)
  785. if isinstance(parsed_data, dict):
  786. if "channel_values" in parsed_data and "messages" in parsed_data["channel_values"]:
  787. messages = parsed_data["channel_values"]["messages"]
  788. logger.info(f"✅ 从Hash字段 {key} 提取到 {len(messages)} 条messages")
  789. break
  790. elif "messages" in parsed_data:
  791. messages = parsed_data["messages"]
  792. logger.info(f"✅ 从Hash字段 {key} 直接提取到 {len(messages)} 条messages")
  793. break
  794. except (json.JSONDecodeError, TypeError):
  795. continue
  796. elif "list_data" in checkpoint:
  797. # List数据结构
  798. logger.info(f"🔍 List数据: {len(checkpoint['list_data'])} 个元素")
  799. # 如果无法提取messages或为空,返回初始化状态
  800. if not messages:
  801. logger.warning(f"⚠️ 无法从checkpoint中提取messages,checkpoint结构: {list(checkpoint.keys())}")
  802. status_data = {
  803. "status": "running",
  804. "name": "初始化中",
  805. "icon": "🚀",
  806. "timestamp": datetime.now().isoformat(),
  807. "debug_info": {
  808. "key_type": key_type,
  809. "checkpoint_keys": list(checkpoint.keys()),
  810. "has_checkpoint": "checkpoint" in checkpoint,
  811. "has_channel_values": "channel_values" in checkpoint.get("checkpoint", {})
  812. }
  813. }
  814. from common.result import success
  815. return jsonify(success(data=status_data, message="获取状态成功")), 200
  816. # 6. 分析最后一条消息
  817. last_message = messages[-1]
  818. last_msg_type = last_message.get("kwargs", {}).get("type", "")
  819. # 7. 判断执行状态
  820. if (last_msg_type == "ai" and
  821. not last_message.get("kwargs", {}).get("tool_calls", []) and
  822. last_message.get("kwargs", {}).get("content", "").strip()):
  823. # 完成状态:AIMessage有完整回答且无tool_calls
  824. status_data = {
  825. "status": "completed",
  826. "name": "完成",
  827. "icon": "✅",
  828. "timestamp": datetime.now().isoformat()
  829. }
  830. elif (last_msg_type == "ai" and
  831. last_message.get("kwargs", {}).get("tool_calls", [])):
  832. # AI正在调用工具
  833. tool_calls = last_message.get("kwargs", {}).get("tool_calls", [])
  834. tool_name = tool_calls[0].get("name", "") if tool_calls else ""
  835. tool_info = TOOL_STATUS_MAPPING.get(tool_name, {
  836. "name": f"调用{tool_name}中" if tool_name else "调用工具中",
  837. "icon": "🔧"
  838. })
  839. status_data = {
  840. "status": "running",
  841. "name": tool_info["name"],
  842. "icon": tool_info["icon"],
  843. "timestamp": datetime.now().isoformat()
  844. }
  845. elif last_msg_type == "tool":
  846. # 工具执行完成,等待AI处理
  847. tool_name = last_message.get("kwargs", {}).get("name", "")
  848. tool_status = last_message.get("kwargs", {}).get("status", "")
  849. if tool_status == "success":
  850. tool_info = TOOL_STATUS_MAPPING.get(tool_name, {"name": "处理中", "icon": "🔄"})
  851. status_data = {
  852. "status": "running",
  853. "name": f"{tool_info['name'].replace('中', '')}完成,AI处理中",
  854. "icon": "🤖",
  855. "timestamp": datetime.now().isoformat()
  856. }
  857. else:
  858. tool_info = TOOL_STATUS_MAPPING.get(tool_name, {
  859. "name": f"执行{tool_name}中",
  860. "icon": "⚙️"
  861. })
  862. status_data = {
  863. "status": "running",
  864. "name": tool_info["name"],
  865. "icon": tool_info["icon"],
  866. "timestamp": datetime.now().isoformat()
  867. }
  868. elif last_msg_type == "human":
  869. # 用户刚提问,AI开始思考
  870. status_data = {
  871. "status": "running",
  872. "name": "AI思考中",
  873. "icon": "🤖",
  874. "timestamp": datetime.now().isoformat()
  875. }
  876. else:
  877. # 默认执行中状态
  878. status_data = {
  879. "status": "running",
  880. "name": "执行中",
  881. "icon": "⚙️",
  882. "timestamp": datetime.now().isoformat()
  883. }
  884. from common.result import success
  885. return jsonify(success(data=status_data, message="获取状态成功")), 200
  886. finally:
  887. await redis_client.aclose()
  888. except Exception as e:
  889. logger.error(f"获取React Agent状态失败: {e}")
  890. from common.result import failed
  891. return jsonify(failed(message=f"获取状态失败: {str(e)}", code=500)), 500
  892. # ==================== LangGraph Agent API ====================
  893. # 全局Agent实例(单例模式)
  894. citu_langraph_agent = None
  895. def get_citu_langraph_agent():
  896. """获取LangGraph Agent实例(懒加载)"""
  897. global citu_langraph_agent
  898. if citu_langraph_agent is None:
  899. try:
  900. from agent.citu_agent import CituLangGraphAgent
  901. logger.info("开始创建LangGraph Agent实例...")
  902. citu_langraph_agent = CituLangGraphAgent()
  903. logger.info("LangGraph Agent实例创建成功")
  904. except ImportError as e:
  905. logger.critical(f"Agent模块导入失败: {str(e)}")
  906. raise Exception(f"Agent模块导入失败: {str(e)}")
  907. except Exception as e:
  908. logger.critical(f"LangGraph Agent实例创建失败: {str(e)}")
  909. raise Exception(f"Agent初始化失败: {str(e)}")
  910. return citu_langraph_agent
  911. @app.route('/api/v0/ask_agent', methods=['POST'])
  912. def ask_agent():
  913. """支持对话上下文的ask_agent API"""
  914. req = request.get_json(force=True)
  915. question = req.get("question", None)
  916. user_id_input = req.get("user_id", None)
  917. conversation_id_input = req.get("conversation_id", None)
  918. continue_conversation = req.get("continue_conversation", False)
  919. api_routing_mode = req.get("routing_mode", None)
  920. VALID_ROUTING_MODES = ["database_direct", "chat_direct", "hybrid", "llm_only"]
  921. if not question:
  922. return jsonify(bad_request_response(
  923. response_text="缺少必需参数:question",
  924. missing_params=["question"]
  925. )), 400
  926. if api_routing_mode and api_routing_mode not in VALID_ROUTING_MODES:
  927. return jsonify(bad_request_response(
  928. response_text=f"无效的routing_mode参数值: {api_routing_mode},支持的值: {VALID_ROUTING_MODES}",
  929. invalid_params=["routing_mode"]
  930. )), 400
  931. try:
  932. # 获取登录用户ID
  933. login_user_id = session.get('user_id') if 'user_id' in session else None
  934. # 用户ID和对话ID一致性校验
  935. from common.session_aware_cache import ConversationAwareMemoryCache
  936. # 如果传递了conversation_id,从中解析user_id
  937. extracted_user_id = None
  938. if conversation_id_input:
  939. extracted_user_id = ConversationAwareMemoryCache.extract_user_id(conversation_id_input)
  940. # 如果同时传递了user_id和conversation_id,进行一致性校验
  941. if user_id_input:
  942. is_valid, error_msg = ConversationAwareMemoryCache.validate_user_id_consistency(
  943. conversation_id_input, user_id_input
  944. )
  945. if not is_valid:
  946. return jsonify(bad_request_response(
  947. response_text=error_msg,
  948. invalid_params=["user_id", "conversation_id"]
  949. )), 400
  950. # 如果没有传递user_id,但有conversation_id,则从conversation_id中解析
  951. elif not user_id_input and extracted_user_id:
  952. user_id_input = extracted_user_id
  953. logger.info(f"从conversation_id解析出user_id: {user_id_input}")
  954. # 如果没有传递user_id,使用默认值guest
  955. if not user_id_input:
  956. user_id_input = "guest"
  957. logger.info("未传递user_id,使用默认值: guest")
  958. # 智能ID解析
  959. user_id = redis_conversation_manager.resolve_user_id(
  960. user_id_input, None, request.remote_addr, login_user_id
  961. )
  962. conversation_id, conversation_status = redis_conversation_manager.resolve_conversation_id(
  963. user_id, conversation_id_input, continue_conversation
  964. )
  965. # 获取上下文和上下文类型(提前到缓存检查之前)
  966. context = redis_conversation_manager.get_context(conversation_id)
  967. # 获取上下文类型:从最后一条助手消息的metadata中获取类型
  968. context_type = None
  969. if context:
  970. try:
  971. # 获取最后一条助手消息的metadata
  972. messages = redis_conversation_manager.get_conversation_messages(conversation_id, limit=10)
  973. for message in reversed(messages): # 从最新的开始找
  974. if message.get("role") == "assistant":
  975. metadata = message.get("metadata", {})
  976. context_type = metadata.get("type")
  977. if context_type:
  978. logger.info(f"[AGENT_API] 检测到上下文类型: {context_type}")
  979. break
  980. except Exception as e:
  981. logger.warning(f"获取上下文类型失败: {str(e)}")
  982. # 检查缓存(新逻辑:放宽使用条件,严控存储条件)
  983. cached_answer = redis_conversation_manager.get_cached_answer(question, context)
  984. if cached_answer:
  985. logger.info(f"[AGENT_API] 使用缓存答案")
  986. # 确定缓存答案的助手回复内容(使用与非缓存相同的优先级逻辑)
  987. cached_response_type = cached_answer.get("type", "UNKNOWN")
  988. if cached_response_type == "DATABASE":
  989. # DATABASE类型:按优先级选择内容
  990. if cached_answer.get("response"):
  991. # 优先级1:错误或解释性回复(如SQL生成失败)
  992. assistant_response = cached_answer.get("response")
  993. elif cached_answer.get("summary"):
  994. # 优先级2:查询成功的摘要
  995. assistant_response = cached_answer.get("summary")
  996. elif cached_answer.get("query_result"):
  997. # 优先级3:构造简单描述
  998. query_result = cached_answer.get("query_result")
  999. row_count = query_result.get("row_count", 0)
  1000. assistant_response = f"查询执行完成,共返回 {row_count} 条记录。"
  1001. else:
  1002. # 异常情况
  1003. assistant_response = "数据库查询已处理。"
  1004. else:
  1005. # CHAT类型:直接使用response
  1006. assistant_response = cached_answer.get("response", "")
  1007. # 更新对话历史
  1008. redis_conversation_manager.save_message(conversation_id, "user", question)
  1009. redis_conversation_manager.save_message(
  1010. conversation_id, "assistant",
  1011. assistant_response,
  1012. metadata={"from_cache": True}
  1013. )
  1014. # 添加对话信息到缓存结果
  1015. cached_answer["conversation_id"] = conversation_id
  1016. cached_answer["user_id"] = user_id
  1017. cached_answer["from_cache"] = True
  1018. cached_answer.update(conversation_status)
  1019. # 使用agent_success_response返回标准格式
  1020. return jsonify(agent_success_response(
  1021. response_type=cached_answer.get("type", "UNKNOWN"),
  1022. response=cached_answer.get("response", ""),
  1023. sql=cached_answer.get("sql"),
  1024. records=cached_answer.get("query_result"),
  1025. summary=cached_answer.get("summary"),
  1026. conversation_id=conversation_id,
  1027. execution_path=cached_answer.get("execution_path", []),
  1028. classification_info=cached_answer.get("classification_info", {}),
  1029. user_id=user_id,
  1030. context_used=bool(context),
  1031. from_cache=True,
  1032. conversation_status=conversation_status["status"],
  1033. requested_conversation_id=conversation_status.get("requested_id")
  1034. ))
  1035. # 保存用户消息
  1036. redis_conversation_manager.save_message(conversation_id, "user", question)
  1037. # 构建带上下文的问题
  1038. if context:
  1039. enhanced_question = f"\n[CONTEXT]\n{context}\n\n[CURRENT]\n{question}"
  1040. logger.info(f"[AGENT_API] 使用上下文,长度: {len(context)}字符")
  1041. else:
  1042. enhanced_question = question
  1043. logger.info(f"[AGENT_API] 新对话,无上下文")
  1044. # 确定最终使用的路由模式(优先级逻辑)
  1045. if api_routing_mode:
  1046. # API传了参数,优先使用
  1047. effective_routing_mode = api_routing_mode
  1048. logger.info(f"[AGENT_API] 使用API指定的路由模式: {effective_routing_mode}")
  1049. else:
  1050. # API没传参数,使用配置文件
  1051. try:
  1052. from app_config import QUESTION_ROUTING_MODE
  1053. effective_routing_mode = QUESTION_ROUTING_MODE
  1054. logger.info(f"[AGENT_API] 使用配置文件路由模式: {effective_routing_mode}")
  1055. except ImportError:
  1056. effective_routing_mode = "hybrid"
  1057. logger.info(f"[AGENT_API] 配置文件读取失败,使用默认路由模式: {effective_routing_mode}")
  1058. # Agent处理
  1059. try:
  1060. agent = get_citu_langraph_agent()
  1061. except Exception as e:
  1062. logger.critical(f"Agent初始化失败: {str(e)}")
  1063. return jsonify(service_unavailable_response(
  1064. response_text="AI服务暂时不可用,请稍后重试",
  1065. can_retry=True
  1066. )), 503
  1067. # 异步调用Agent处理问题
  1068. import asyncio
  1069. agent_result = asyncio.run(agent.process_question(
  1070. question=enhanced_question, # 使用增强后的问题
  1071. conversation_id=conversation_id,
  1072. context_type=context_type, # 传递上下文类型
  1073. routing_mode=effective_routing_mode # 新增:传递路由模式
  1074. ))
  1075. # 处理Agent结果
  1076. if agent_result.get("success", False):
  1077. response_type = agent_result.get("type", "UNKNOWN")
  1078. response_text = agent_result.get("response", "")
  1079. sql = agent_result.get("sql")
  1080. query_result = agent_result.get("query_result")
  1081. summary = agent_result.get("summary")
  1082. execution_path = agent_result.get("execution_path", [])
  1083. classification_info = agent_result.get("classification_info", {})
  1084. # 确定助手回复内容的优先级
  1085. if response_type == "DATABASE":
  1086. if response_text:
  1087. assistant_response = response_text
  1088. elif summary:
  1089. assistant_response = summary
  1090. elif query_result:
  1091. row_count = query_result.get("row_count", 0)
  1092. assistant_response = f"查询执行完成,共返回 {row_count} 条记录。"
  1093. else:
  1094. assistant_response = "数据库查询已处理。"
  1095. else:
  1096. assistant_response = response_text
  1097. # 保存助手回复
  1098. redis_conversation_manager.save_message(
  1099. conversation_id, "assistant", assistant_response,
  1100. metadata={
  1101. "type": response_type,
  1102. "sql": sql,
  1103. "execution_path": execution_path
  1104. }
  1105. )
  1106. # 缓存成功的答案(新逻辑:只缓存无上下文的问答)
  1107. # 直接缓存agent_result,它已经包含所有需要的字段
  1108. redis_conversation_manager.cache_answer(question, agent_result, context)
  1109. # 使用agent_success_response的正确方式
  1110. return jsonify(agent_success_response(
  1111. response_type=response_type,
  1112. response=response_text,
  1113. sql=sql,
  1114. records=query_result,
  1115. summary=summary,
  1116. conversation_id=conversation_id,
  1117. execution_path=execution_path,
  1118. classification_info=classification_info,
  1119. user_id=user_id,
  1120. context_used=bool(context),
  1121. from_cache=False,
  1122. conversation_status=conversation_status["status"],
  1123. requested_conversation_id=conversation_status.get("requested_id"),
  1124. routing_mode_used=effective_routing_mode, # 新增:实际使用的路由模式
  1125. routing_mode_source="api" if api_routing_mode else "config" # 新增:路由模式来源
  1126. ))
  1127. else:
  1128. # 错误处理
  1129. error_message = agent_result.get("error", "Agent处理失败")
  1130. error_code = agent_result.get("error_code", 500)
  1131. return jsonify(agent_error_response(
  1132. response_text=error_message,
  1133. error_type="agent_processing_failed",
  1134. code=error_code,
  1135. conversation_id=conversation_id,
  1136. user_id=user_id
  1137. )), error_code
  1138. except Exception as e:
  1139. logger.error(f"ask_agent执行失败: {str(e)}")
  1140. return jsonify(internal_error_response(
  1141. response_text="查询处理失败,请稍后重试"
  1142. )), 500
  1143. @app.route('/api/v0/ask_agent_stream', methods=['GET'])
  1144. def ask_agent_stream():
  1145. """Citu Agent 流式API - 支持实时进度显示(EventSource只支持GET请求)
  1146. 功能与ask_agent完全相同,除了采用流式输出"""
  1147. def generate():
  1148. try:
  1149. # 从URL参数获取数据(EventSource只支持GET请求)
  1150. question = request.args.get('question')
  1151. user_id_input = request.args.get('user_id')
  1152. conversation_id_input = request.args.get('conversation_id')
  1153. continue_conversation = request.args.get('continue_conversation', 'false').lower() == 'true'
  1154. api_routing_mode = request.args.get('routing_mode')
  1155. VALID_ROUTING_MODES = ["database_direct", "chat_direct", "hybrid", "llm_only"]
  1156. # 参数验证
  1157. if not question:
  1158. yield format_sse_error("缺少必需参数:question")
  1159. return
  1160. if api_routing_mode and api_routing_mode not in VALID_ROUTING_MODES:
  1161. yield format_sse_error(f"无效的routing_mode参数值: {api_routing_mode}")
  1162. return
  1163. # 🆕 用户ID和对话ID一致性校验(与ask_agent相同)
  1164. try:
  1165. # 获取登录用户ID
  1166. login_user_id = session.get('user_id') if 'user_id' in session else None
  1167. # 用户ID和对话ID一致性校验
  1168. from common.session_aware_cache import ConversationAwareMemoryCache
  1169. # 如果传递了conversation_id,从中解析user_id
  1170. extracted_user_id = None
  1171. if conversation_id_input:
  1172. extracted_user_id = ConversationAwareMemoryCache.extract_user_id(conversation_id_input)
  1173. # 如果同时传递了user_id和conversation_id,进行一致性校验
  1174. if user_id_input:
  1175. is_valid, error_msg = ConversationAwareMemoryCache.validate_user_id_consistency(
  1176. conversation_id_input, user_id_input
  1177. )
  1178. if not is_valid:
  1179. yield format_sse_error(error_msg)
  1180. return
  1181. # 如果没有传递user_id,但有conversation_id,则从conversation_id中解析
  1182. elif not user_id_input and extracted_user_id:
  1183. user_id_input = extracted_user_id
  1184. logger.info(f"从conversation_id解析出user_id: {user_id_input}")
  1185. # 如果没有传递user_id,使用默认值guest
  1186. if not user_id_input:
  1187. user_id_input = "guest"
  1188. logger.info("未传递user_id,使用默认值: guest")
  1189. # 🆕 智能ID解析(与ask_agent相同)
  1190. user_id = redis_conversation_manager.resolve_user_id(
  1191. user_id_input, None, request.remote_addr, login_user_id
  1192. )
  1193. conversation_id, conversation_status = redis_conversation_manager.resolve_conversation_id(
  1194. user_id, conversation_id_input, continue_conversation
  1195. )
  1196. except Exception as e:
  1197. logger.error(f"用户ID和对话ID解析失败: {str(e)}")
  1198. yield format_sse_error(f"参数解析失败: {str(e)}")
  1199. return
  1200. logger.info(f"[STREAM_API] 收到请求 - 问题: {question[:50]}..., 用户: {user_id}, 对话: {conversation_id}")
  1201. # 🆕 获取上下文和上下文类型(与ask_agent相同)
  1202. context = redis_conversation_manager.get_context(conversation_id)
  1203. # 获取上下文类型:从最后一条助手消息的metadata中获取类型
  1204. context_type = None
  1205. if context:
  1206. try:
  1207. # 获取最后一条助手消息的metadata
  1208. messages = redis_conversation_manager.get_conversation_messages(conversation_id, limit=10)
  1209. for message in reversed(messages): # 从最新的开始找
  1210. if message.get("role") == "assistant":
  1211. metadata = message.get("metadata", {})
  1212. context_type = metadata.get("type")
  1213. if context_type:
  1214. logger.info(f"[STREAM_API] 检测到上下文类型: {context_type}")
  1215. break
  1216. except Exception as e:
  1217. logger.warning(f"获取上下文类型失败: {str(e)}")
  1218. # 🆕 检查缓存(与ask_agent相同)
  1219. cached_answer = redis_conversation_manager.get_cached_answer(question, context)
  1220. if cached_answer:
  1221. logger.info(f"[STREAM_API] 使用缓存答案")
  1222. # 确定缓存答案的助手回复内容(使用与非缓存相同的优先级逻辑)
  1223. cached_response_type = cached_answer.get("type", "UNKNOWN")
  1224. if cached_response_type == "DATABASE":
  1225. # DATABASE类型:按优先级选择内容
  1226. if cached_answer.get("response"):
  1227. assistant_response = cached_answer.get("response")
  1228. elif cached_answer.get("summary"):
  1229. assistant_response = cached_answer.get("summary")
  1230. elif cached_answer.get("query_result"):
  1231. query_result = cached_answer.get("query_result")
  1232. row_count = query_result.get("row_count", 0)
  1233. assistant_response = f"查询执行完成,共返回 {row_count} 条记录。"
  1234. else:
  1235. assistant_response = "查询处理完成"
  1236. else:
  1237. assistant_response = cached_answer.get("response", "处理完成")
  1238. # 返回缓存结果的SSE格式
  1239. yield format_sse_completed({
  1240. "type": "completed",
  1241. "result": {
  1242. "success": True,
  1243. "type": cached_response_type,
  1244. "response": assistant_response,
  1245. "sql": cached_answer.get("sql"),
  1246. "query_result": cached_answer.get("query_result"),
  1247. "summary": cached_answer.get("summary"),
  1248. "conversation_id": conversation_id,
  1249. "execution_path": cached_answer.get("execution_path", []),
  1250. "classification_info": cached_answer.get("classification_info", {}),
  1251. "user_id": user_id,
  1252. "context_used": bool(context),
  1253. "from_cache": True,
  1254. "conversation_status": conversation_status["status"],
  1255. "requested_conversation_id": conversation_status.get("requested_id")
  1256. }
  1257. })
  1258. return
  1259. # 🆕 保存用户消息(与ask_agent相同)
  1260. redis_conversation_manager.save_message(conversation_id, "user", question)
  1261. # 🆕 构建带上下文的问题(与ask_agent相同)
  1262. if context:
  1263. enhanced_question = f"\n[CONTEXT]\n{context}\n\n[CURRENT]\n{question}"
  1264. logger.info(f"[STREAM_API] 使用上下文,长度: {len(context)}字符")
  1265. else:
  1266. enhanced_question = question
  1267. logger.info(f"[STREAM_API] 新对话,无上下文")
  1268. # 获取Agent实例
  1269. try:
  1270. agent = get_citu_langraph_agent()
  1271. if not agent:
  1272. yield format_sse_error("Agent实例获取失败")
  1273. return
  1274. # 检查是否有process_question_stream方法
  1275. if not hasattr(agent, 'process_question_stream'):
  1276. yield format_sse_error("Agent不支持流式处理")
  1277. return
  1278. except Exception as e:
  1279. logger.error(f"Agent初始化失败: {str(e)}")
  1280. yield format_sse_error("AI服务暂时不可用,请稍后重试")
  1281. return
  1282. # 🆕 确定最终使用的路由模式(与ask_agent相同)
  1283. if api_routing_mode:
  1284. # API传了参数,优先使用
  1285. effective_routing_mode = api_routing_mode
  1286. logger.info(f"[STREAM_API] 使用API指定的路由模式: {effective_routing_mode}")
  1287. else:
  1288. # API没传参数,使用配置文件
  1289. try:
  1290. from app_config import QUESTION_ROUTING_MODE
  1291. effective_routing_mode = QUESTION_ROUTING_MODE
  1292. logger.info(f"[STREAM_API] 使用配置文件路由模式: {effective_routing_mode}")
  1293. except ImportError:
  1294. effective_routing_mode = "hybrid"
  1295. logger.info(f"[STREAM_API] 配置文件读取失败,使用默认路由模式: {effective_routing_mode}")
  1296. # 流式处理 - 实时转发
  1297. try:
  1298. import asyncio
  1299. # 获取当前事件循环,如果没有则创建新的
  1300. try:
  1301. loop = asyncio.get_event_loop()
  1302. except RuntimeError:
  1303. loop = asyncio.new_event_loop()
  1304. asyncio.set_event_loop(loop)
  1305. # 用于收集最终结果,以便保存到Redis
  1306. final_result = None
  1307. # 异步生成器,实时yield数据
  1308. async def stream_generator():
  1309. nonlocal final_result
  1310. try:
  1311. async for chunk in agent.process_question_stream(
  1312. question=enhanced_question, # 🆕 使用增强后的问题
  1313. user_id=user_id,
  1314. conversation_id=conversation_id,
  1315. context_type=context_type, # 🆕 传递上下文类型
  1316. routing_mode=effective_routing_mode
  1317. ):
  1318. # 如果是完成的chunk,保存最终结果
  1319. if chunk.get("type") == "completed":
  1320. final_result = chunk.get("result")
  1321. yield chunk
  1322. except Exception as e:
  1323. logger.error(f"流式处理异常: {str(e)}")
  1324. yield {"type": "error", "error": str(e)}
  1325. # 同步包装器,实时转发数据
  1326. def sync_stream_wrapper():
  1327. # 创建异步任务
  1328. async_gen = stream_generator()
  1329. while True:
  1330. try:
  1331. # 获取下一个chunk
  1332. chunk = loop.run_until_complete(async_gen.__anext__())
  1333. if chunk["type"] == "progress":
  1334. yield format_sse_progress(chunk)
  1335. elif chunk["type"] == "completed":
  1336. yield format_sse_completed(chunk)
  1337. break # 完成后退出循环
  1338. elif chunk["type"] == "error":
  1339. yield format_sse_error(chunk.get("error", "未知错误"))
  1340. break # 错误后退出循环
  1341. except StopAsyncIteration:
  1342. # 异步生成器结束
  1343. break
  1344. except Exception as e:
  1345. logger.error(f"流式转发异常: {str(e)}")
  1346. yield format_sse_error(f"流式处理异常: {str(e)}")
  1347. break
  1348. # 返回同步生成器
  1349. yield from sync_stream_wrapper()
  1350. # 🆕 保存助手消息和缓存结果(与ask_agent相同)
  1351. if final_result and final_result.get("success", False):
  1352. try:
  1353. response_type = final_result.get("type", "UNKNOWN")
  1354. response_text = final_result.get("response", "")
  1355. sql = final_result.get("sql")
  1356. query_result = final_result.get("query_result")
  1357. summary = final_result.get("summary")
  1358. execution_path = final_result.get("execution_path", [])
  1359. classification_info = final_result.get("classification_info", {})
  1360. # 确定助手回复内容的优先级
  1361. if response_type == "DATABASE":
  1362. if response_text:
  1363. assistant_response = response_text
  1364. elif summary:
  1365. assistant_response = summary
  1366. elif query_result:
  1367. row_count = query_result.get("row_count", 0)
  1368. assistant_response = f"查询执行完成,共返回 {row_count} 条记录。"
  1369. else:
  1370. assistant_response = "查询处理完成"
  1371. else:
  1372. assistant_response = response_text or "处理完成"
  1373. # 保存助手消息
  1374. metadata = {
  1375. "type": response_type,
  1376. "sql": sql,
  1377. "execution_path": execution_path,
  1378. "classification_info": classification_info
  1379. }
  1380. redis_conversation_manager.save_message(
  1381. conversation_id, "assistant", assistant_response, metadata
  1382. )
  1383. # 缓存结果(仅缓存成功的结果)- 与ask_agent相同的调用方式
  1384. redis_conversation_manager.cache_answer(question, final_result, context)
  1385. logger.info(f"[STREAM_API] 结果已缓存")
  1386. except Exception as e:
  1387. logger.error(f"保存结果和缓存失败: {str(e)}")
  1388. except Exception as e:
  1389. logger.error(f"流式处理异常: {str(e)}")
  1390. import traceback
  1391. traceback.print_exc()
  1392. yield format_sse_error(f"处理异常: {str(e)}")
  1393. except Exception as e:
  1394. logger.error(f"流式API异常: {str(e)}")
  1395. yield format_sse_error(f"服务异常: {str(e)}")
  1396. return Response(stream_with_context(generate()), mimetype='text/event-stream')
  1397. def format_sse_progress(chunk: dict) -> str:
  1398. """格式化进度事件为SSE格式"""
  1399. progress = chunk.get("progress", {})
  1400. node = chunk.get("node")
  1401. # 🆕 特殊处理:格式化响应节点的显示内容
  1402. if node == "format_response":
  1403. display_name = "格式化响应结果"
  1404. message = "正在执行:格式化响应结果"
  1405. else:
  1406. display_name = progress.get("display_name")
  1407. message = f"正在执行: {progress.get('display_name', '处理中')}"
  1408. data = {
  1409. "code": 200,
  1410. "success": True,
  1411. "message": message,
  1412. "data": {
  1413. "type": "progress",
  1414. "node": node,
  1415. "display_name": display_name,
  1416. # 🆕 删除icon字段
  1417. "details": progress.get("details"),
  1418. "sub_status": progress.get("sub_status"),
  1419. "conversation_id": chunk.get("conversation_id"),
  1420. "timestamp": datetime.now().isoformat()
  1421. }
  1422. }
  1423. import json
  1424. return f"data: {json.dumps(data, ensure_ascii=False)}\n\n"
  1425. def format_sse_completed(chunk: dict) -> str:
  1426. """格式化完成事件为SSE格式"""
  1427. result = chunk.get("result", {})
  1428. data = {
  1429. "code": 200,
  1430. "success": True,
  1431. "message": "处理完成",
  1432. "data": {
  1433. "type": "completed",
  1434. "response": result.get("response", ""),
  1435. "response_type": result.get("type", "UNKNOWN"),
  1436. "sql": result.get("sql"),
  1437. "query_result": result.get("query_result"),
  1438. "summary": result.get("summary"),
  1439. "conversation_id": chunk.get("conversation_id"),
  1440. "execution_path": result.get("execution_path", []),
  1441. "classification_info": result.get("classification_info", {}),
  1442. "timestamp": datetime.now().isoformat()
  1443. }
  1444. }
  1445. import json
  1446. return f"data: {json.dumps(data, ensure_ascii=False)}\n\n"
  1447. def format_sse_error(error_message: str) -> str:
  1448. """格式化错误事件为SSE格式"""
  1449. data = {
  1450. "code": 500,
  1451. "success": False,
  1452. "message": "处理失败",
  1453. "data": {
  1454. "type": "error",
  1455. "error": error_message,
  1456. "timestamp": datetime.now().isoformat()
  1457. }
  1458. }
  1459. import json
  1460. return f"data: {json.dumps(data, ensure_ascii=False)}\n\n"
  1461. # ==================== QA反馈系统API ====================
  1462. qa_feedback_manager = None
  1463. def get_qa_feedback_manager():
  1464. """获取QA反馈管理器实例(懒加载)"""
  1465. global qa_feedback_manager
  1466. if qa_feedback_manager is None:
  1467. try:
  1468. qa_feedback_manager = QAFeedbackManager(vanna_instance=vn)
  1469. logger.info("QA反馈管理器实例创建成功")
  1470. except Exception as e:
  1471. logger.critical(f"QA反馈管理器创建失败: {str(e)}")
  1472. raise Exception(f"QA反馈管理器初始化失败: {str(e)}")
  1473. return qa_feedback_manager
  1474. @app.route('/api/v0/qa_feedback/query', methods=['POST'])
  1475. def qa_feedback_query():
  1476. """
  1477. 查询反馈记录API
  1478. 支持分页、筛选和排序功能
  1479. """
  1480. try:
  1481. req = request.get_json(force=True)
  1482. # 解析参数,设置默认值
  1483. page = req.get('page', 1)
  1484. page_size = req.get('page_size', 20)
  1485. is_thumb_up = req.get('is_thumb_up')
  1486. create_time_start = req.get('create_time_start')
  1487. create_time_end = req.get('create_time_end')
  1488. is_in_training_data = req.get('is_in_training_data')
  1489. sort_by = req.get('sort_by', 'create_time')
  1490. sort_order = req.get('sort_order', 'desc')
  1491. # 参数验证
  1492. if page < 1:
  1493. return jsonify(bad_request_response(
  1494. response_text="页码必须大于0",
  1495. invalid_params=["page"]
  1496. )), 400
  1497. if page_size < 1 or page_size > 100:
  1498. return jsonify(bad_request_response(
  1499. response_text="每页大小必须在1-100之间",
  1500. invalid_params=["page_size"]
  1501. )), 400
  1502. # 获取反馈管理器并查询
  1503. manager = get_qa_feedback_manager()
  1504. records, total = manager.query_feedback(
  1505. page=page,
  1506. page_size=page_size,
  1507. is_thumb_up=is_thumb_up,
  1508. create_time_start=create_time_start,
  1509. create_time_end=create_time_end,
  1510. is_in_training_data=is_in_training_data,
  1511. sort_by=sort_by,
  1512. sort_order=sort_order
  1513. )
  1514. total_pages = (total + page_size - 1) // page_size
  1515. return jsonify(success_response(
  1516. response_text=f"查询成功,共找到 {total} 条记录",
  1517. data={
  1518. "records": records,
  1519. "pagination": {
  1520. "page": page,
  1521. "page_size": page_size,
  1522. "total": total,
  1523. "total_pages": total_pages,
  1524. "has_next": page < total_pages,
  1525. "has_prev": page > 1
  1526. }
  1527. }
  1528. ))
  1529. except Exception as e:
  1530. logger.error(f"qa_feedback_query执行失败: {str(e)}")
  1531. return jsonify(internal_error_response(
  1532. response_text="查询反馈记录失败,请稍后重试"
  1533. )), 500
  1534. @app.route('/api/v0/qa_feedback/delete/<int:feedback_id>', methods=['DELETE'])
  1535. def qa_feedback_delete(feedback_id):
  1536. """删除反馈记录API"""
  1537. try:
  1538. manager = get_qa_feedback_manager()
  1539. success = manager.delete_feedback(feedback_id)
  1540. if success:
  1541. return jsonify(success_response(
  1542. response_text=f"反馈记录删除成功",
  1543. data={"deleted_id": feedback_id}
  1544. ))
  1545. else:
  1546. return jsonify(not_found_response(
  1547. response_text=f"反馈记录不存在 (ID: {feedback_id})"
  1548. )), 404
  1549. except Exception as e:
  1550. logger.error(f"qa_feedback_delete执行失败: {str(e)}")
  1551. return jsonify(internal_error_response(
  1552. response_text="删除反馈记录失败,请稍后重试"
  1553. )), 500
  1554. @app.route('/api/v0/qa_feedback/update/<int:feedback_id>', methods=['PUT'])
  1555. def qa_feedback_update(feedback_id):
  1556. """更新反馈记录API"""
  1557. try:
  1558. req = request.get_json(force=True)
  1559. allowed_fields = ['question', 'sql', 'is_thumb_up', 'user_id', 'is_in_training_data']
  1560. update_data = {}
  1561. for field in allowed_fields:
  1562. if field in req:
  1563. update_data[field] = req[field]
  1564. if not update_data:
  1565. return jsonify(bad_request_response(
  1566. response_text="没有提供有效的更新字段",
  1567. missing_params=allowed_fields
  1568. )), 400
  1569. manager = get_qa_feedback_manager()
  1570. success = manager.update_feedback(feedback_id, **update_data)
  1571. if success:
  1572. return jsonify(success_response(
  1573. response_text="反馈记录更新成功",
  1574. data={
  1575. "updated_id": feedback_id,
  1576. "updated_fields": list(update_data.keys())
  1577. }
  1578. ))
  1579. else:
  1580. return jsonify(not_found_response(
  1581. response_text=f"反馈记录不存在或无变化 (ID: {feedback_id})"
  1582. )), 404
  1583. except Exception as e:
  1584. logger.error(f"qa_feedback_update执行失败: {str(e)}")
  1585. return jsonify(internal_error_response(
  1586. response_text="更新反馈记录失败,请稍后重试"
  1587. )), 500
  1588. @app.route('/api/v0/qa_feedback/add_to_training', methods=['POST'])
  1589. def qa_feedback_add_to_training():
  1590. """
  1591. 将反馈记录添加到训练数据集API
  1592. 支持混合批量处理:正向反馈加入SQL训练集,负向反馈加入error_sql训练集
  1593. """
  1594. try:
  1595. req = request.get_json(force=True)
  1596. feedback_ids = req.get('feedback_ids', [])
  1597. if not feedback_ids or not isinstance(feedback_ids, list):
  1598. return jsonify(bad_request_response(
  1599. response_text="缺少有效的反馈ID列表",
  1600. missing_params=["feedback_ids"]
  1601. )), 400
  1602. manager = get_qa_feedback_manager()
  1603. # 获取反馈记录
  1604. records = manager.get_feedback_by_ids(feedback_ids)
  1605. if not records:
  1606. return jsonify(not_found_response(
  1607. response_text="未找到任何有效的反馈记录"
  1608. )), 404
  1609. # 分别处理正向和负向反馈
  1610. positive_count = 0 # 正向训练计数
  1611. negative_count = 0 # 负向训练计数
  1612. already_trained_count = 0 # 已训练计数
  1613. error_count = 0 # 错误计数
  1614. successfully_trained_ids = [] # 成功训练的ID列表
  1615. for record in records:
  1616. try:
  1617. # 检查是否已经在训练数据中
  1618. if record['is_in_training_data']:
  1619. already_trained_count += 1
  1620. continue
  1621. if record['is_thumb_up']:
  1622. # 正向反馈 - 加入标准SQL训练集
  1623. training_id = vn.train(
  1624. question=record['question'],
  1625. sql=record['sql']
  1626. )
  1627. positive_count += 1
  1628. logger.info(f"正向训练成功 - ID: {record['id']}, TrainingID: {training_id}")
  1629. else:
  1630. # 负向反馈 - 加入错误SQL训练集
  1631. training_id = vn.train_error_sql(
  1632. question=record['question'],
  1633. sql=record['sql']
  1634. )
  1635. negative_count += 1
  1636. logger.info(f"负向训练成功 - ID: {record['id']}, TrainingID: {training_id}")
  1637. successfully_trained_ids.append(record['id'])
  1638. except Exception as e:
  1639. logger.error(f"训练失败 - 反馈ID: {record['id']}, 错误: {e}")
  1640. error_count += 1
  1641. # 更新训练状态
  1642. if successfully_trained_ids:
  1643. updated_count = manager.mark_training_status(successfully_trained_ids, True)
  1644. logger.info(f"批量更新训练状态完成,影响 {updated_count} 条记录")
  1645. # 构建响应
  1646. total_processed = positive_count + negative_count + already_trained_count + error_count
  1647. return jsonify(success_response(
  1648. response_text=f"训练数据添加完成,成功处理 {positive_count + negative_count} 条记录",
  1649. data={
  1650. "summary": {
  1651. "total_requested": len(feedback_ids),
  1652. "total_processed": total_processed,
  1653. "positive_trained": positive_count,
  1654. "negative_trained": negative_count,
  1655. "already_trained": already_trained_count,
  1656. "errors": error_count
  1657. },
  1658. "successfully_trained_ids": successfully_trained_ids,
  1659. "training_details": {
  1660. "sql_training_count": positive_count,
  1661. "error_sql_training_count": negative_count
  1662. }
  1663. }
  1664. ))
  1665. except Exception as e:
  1666. logger.error(f"qa_feedback_add_to_training执行失败: {str(e)}")
  1667. return jsonify(internal_error_response(
  1668. response_text="添加训练数据失败,请稍后重试"
  1669. )), 500
  1670. @app.route('/api/v0/qa_feedback/add', methods=['POST'])
  1671. def qa_feedback_add():
  1672. """
  1673. 添加反馈记录API
  1674. 用于前端直接创建反馈记录
  1675. """
  1676. try:
  1677. req = request.get_json(force=True)
  1678. question = req.get('question')
  1679. sql = req.get('sql')
  1680. is_thumb_up = req.get('is_thumb_up')
  1681. user_id = req.get('user_id', 'guest')
  1682. # 参数验证
  1683. if not question:
  1684. return jsonify(bad_request_response(
  1685. response_text="缺少必需参数:question",
  1686. missing_params=["question"]
  1687. )), 400
  1688. if not sql:
  1689. return jsonify(bad_request_response(
  1690. response_text="缺少必需参数:sql",
  1691. missing_params=["sql"]
  1692. )), 400
  1693. if is_thumb_up is None:
  1694. return jsonify(bad_request_response(
  1695. response_text="缺少必需参数:is_thumb_up",
  1696. missing_params=["is_thumb_up"]
  1697. )), 400
  1698. manager = get_qa_feedback_manager()
  1699. feedback_id = manager.add_feedback(
  1700. question=question,
  1701. sql=sql,
  1702. is_thumb_up=bool(is_thumb_up),
  1703. user_id=user_id
  1704. )
  1705. return jsonify(success_response(
  1706. response_text="反馈记录创建成功",
  1707. data={
  1708. "feedback_id": feedback_id
  1709. }
  1710. ))
  1711. except Exception as e:
  1712. logger.error(f"qa_feedback_add执行失败: {str(e)}")
  1713. return jsonify(internal_error_response(
  1714. response_text="创建反馈记录失败,请稍后重试"
  1715. )), 500
  1716. @app.route('/api/v0/qa_feedback/stats', methods=['GET'])
  1717. def qa_feedback_stats():
  1718. """
  1719. 反馈统计API
  1720. 返回反馈数据的统计信息
  1721. """
  1722. try:
  1723. manager = get_qa_feedback_manager()
  1724. # 查询各种统计数据
  1725. all_records, total_count = manager.query_feedback(page=1, page_size=1)
  1726. positive_records, positive_count = manager.query_feedback(page=1, page_size=1, is_thumb_up=True)
  1727. negative_records, negative_count = manager.query_feedback(page=1, page_size=1, is_thumb_up=False)
  1728. trained_records, trained_count = manager.query_feedback(page=1, page_size=1, is_in_training_data=True)
  1729. untrained_records, untrained_count = manager.query_feedback(page=1, page_size=1, is_in_training_data=False)
  1730. return jsonify(success_response(
  1731. response_text="统计信息获取成功",
  1732. data={
  1733. "total_feedback": total_count,
  1734. "positive_feedback": positive_count,
  1735. "negative_feedback": negative_count,
  1736. "trained_feedback": trained_count,
  1737. "untrained_feedback": untrained_count,
  1738. "positive_rate": round(positive_count / max(total_count, 1) * 100, 2),
  1739. "training_rate": round(trained_count / max(total_count, 1) * 100, 2)
  1740. }
  1741. ))
  1742. except Exception as e:
  1743. logger.error(f"qa_feedback_stats执行失败: {str(e)}")
  1744. return jsonify(internal_error_response(
  1745. response_text="获取统计信息失败,请稍后重试"
  1746. )), 500
  1747. # ==================== Redis对话管理API ====================
  1748. @app.route('/api/v0/user/<user_id>/conversations', methods=['GET'])
  1749. def get_user_conversations_redis(user_id: str):
  1750. """获取用户的对话列表"""
  1751. try:
  1752. limit = request.args.get('limit', USER_MAX_CONVERSATIONS, type=int)
  1753. conversations = redis_conversation_manager.get_conversations(user_id, limit)
  1754. # 为每个对话动态获取标题(第一条用户消息)
  1755. for conversation in conversations:
  1756. conversation_id = conversation['conversation_id']
  1757. try:
  1758. # 获取所有消息,然后取第一条用户消息作为标题
  1759. messages = redis_conversation_manager.get_conversation_messages(conversation_id)
  1760. if messages and len(messages) > 0:
  1761. # 找到第一条用户消息(按时间顺序)
  1762. first_user_message = None
  1763. for message in messages:
  1764. if message.get('role') == 'user':
  1765. first_user_message = message
  1766. break
  1767. if first_user_message:
  1768. title = first_user_message.get('content', '对话').strip()
  1769. # 限制标题长度,保持整洁
  1770. if len(title) > 50:
  1771. conversation['conversation_title'] = title[:47] + "..."
  1772. else:
  1773. conversation['conversation_title'] = title
  1774. else:
  1775. conversation['conversation_title'] = "对话"
  1776. else:
  1777. conversation['conversation_title'] = "空对话"
  1778. except Exception as e:
  1779. logger.warning(f"获取对话标题失败 {conversation_id}: {str(e)}")
  1780. conversation['conversation_title'] = "对话"
  1781. return jsonify(success_response(
  1782. response_text="获取用户对话列表成功",
  1783. data={
  1784. "user_id": user_id,
  1785. "conversations": conversations,
  1786. "total_count": len(conversations)
  1787. }
  1788. ))
  1789. except Exception as e:
  1790. return jsonify(internal_error_response(
  1791. response_text="获取对话列表失败,请稍后重试"
  1792. )), 500
  1793. @app.route('/api/v0/conversation/<conversation_id>/messages', methods=['GET'])
  1794. def get_conversation_messages_redis(conversation_id: str):
  1795. """获取特定对话的消息历史"""
  1796. try:
  1797. limit = request.args.get('limit', type=int)
  1798. messages = redis_conversation_manager.get_conversation_messages(conversation_id, limit)
  1799. meta = redis_conversation_manager.get_conversation_meta(conversation_id)
  1800. return jsonify(success_response(
  1801. response_text="获取对话消息成功",
  1802. data={
  1803. "conversation_id": conversation_id,
  1804. "conversation_meta": meta,
  1805. "messages": messages,
  1806. "message_count": len(messages)
  1807. }
  1808. ))
  1809. except Exception as e:
  1810. return jsonify(internal_error_response(
  1811. response_text="获取对话消息失败"
  1812. )), 500
  1813. @app.route('/api/v0/conversation_stats', methods=['GET'])
  1814. def conversation_stats():
  1815. """获取对话系统统计信息"""
  1816. try:
  1817. stats = redis_conversation_manager.get_stats()
  1818. return jsonify(success_response(
  1819. response_text="获取统计信息成功",
  1820. data=stats
  1821. ))
  1822. except Exception as e:
  1823. return jsonify(internal_error_response(
  1824. response_text="获取统计信息失败,请稍后重试"
  1825. )), 500
  1826. @app.route('/api/v0/conversation_cleanup', methods=['POST'])
  1827. def conversation_cleanup():
  1828. """手动清理过期对话"""
  1829. try:
  1830. redis_conversation_manager.cleanup_expired_conversations()
  1831. return jsonify(success_response(
  1832. response_text="对话清理完成"
  1833. ))
  1834. except Exception as e:
  1835. return jsonify(internal_error_response(
  1836. response_text="对话清理失败,请稍后重试"
  1837. )), 500
  1838. @app.route('/api/v0/embedding_cache_stats', methods=['GET'])
  1839. def embedding_cache_stats():
  1840. """获取embedding缓存统计信息"""
  1841. try:
  1842. from common.embedding_cache_manager import get_embedding_cache_manager
  1843. cache_manager = get_embedding_cache_manager()
  1844. stats = cache_manager.get_cache_stats()
  1845. return jsonify(success_response(
  1846. response_text="获取embedding缓存统计成功",
  1847. data=stats
  1848. ))
  1849. except Exception as e:
  1850. logger.error(f"获取embedding缓存统计失败: {str(e)}")
  1851. return jsonify(internal_error_response(
  1852. response_text="获取embedding缓存统计失败,请稍后重试"
  1853. )), 500
  1854. @app.route('/api/v0/embedding_cache_cleanup', methods=['POST'])
  1855. def embedding_cache_cleanup():
  1856. """清空所有embedding缓存"""
  1857. try:
  1858. from common.embedding_cache_manager import get_embedding_cache_manager
  1859. cache_manager = get_embedding_cache_manager()
  1860. if not cache_manager.is_available():
  1861. return jsonify(internal_error_response(
  1862. response_text="Embedding缓存功能未启用或不可用"
  1863. )), 400
  1864. success = cache_manager.clear_all_cache()
  1865. if success:
  1866. return jsonify(success_response(
  1867. response_text="所有embedding缓存已清空",
  1868. data={"cleared": True}
  1869. ))
  1870. else:
  1871. return jsonify(internal_error_response(
  1872. response_text="清空embedding缓存失败"
  1873. )), 500
  1874. except Exception as e:
  1875. logger.error(f"清空embedding缓存失败: {str(e)}")
  1876. return jsonify(internal_error_response(
  1877. response_text="清空embedding缓存失败,请稍后重试"
  1878. )), 500
  1879. # ==================== 训练数据管理API ====================
  1880. def validate_sql_syntax(sql: str) -> tuple[bool, str]:
  1881. """SQL语法检查"""
  1882. try:
  1883. parsed = sqlparse.parse(sql.strip())
  1884. if not parsed or not parsed[0].tokens:
  1885. return False, "SQL语法错误:空语句"
  1886. sql_upper = sql.strip().upper()
  1887. if not any(sql_upper.startswith(keyword) for keyword in
  1888. ['SELECT', 'INSERT', 'UPDATE', 'DELETE', 'CREATE', 'ALTER', 'DROP']):
  1889. return False, "SQL语法错误:不是有效的SQL语句"
  1890. return True, ""
  1891. except Exception as e:
  1892. return False, f"SQL语法错误:{str(e)}"
  1893. def paginate_data(data_list: list, page: int, page_size: int):
  1894. """分页算法"""
  1895. total = len(data_list)
  1896. start_idx = (page - 1) * page_size
  1897. end_idx = start_idx + page_size
  1898. page_data = data_list[start_idx:end_idx]
  1899. total_pages = (total + page_size - 1) // page_size
  1900. return {
  1901. "data": page_data,
  1902. "pagination": {
  1903. "page": page,
  1904. "page_size": page_size,
  1905. "total": total,
  1906. "total_pages": total_pages,
  1907. "has_next": end_idx < total,
  1908. "has_prev": page > 1
  1909. }
  1910. }
  1911. def filter_by_type(data_list: list, training_data_type: str):
  1912. """按类型筛选算法"""
  1913. if not training_data_type:
  1914. return data_list
  1915. return [
  1916. record for record in data_list
  1917. if record.get('training_data_type') == training_data_type
  1918. ]
  1919. def search_in_data(data_list: list, search_keyword: str):
  1920. """在数据中搜索关键词"""
  1921. if not search_keyword:
  1922. return data_list
  1923. keyword_lower = search_keyword.lower()
  1924. return [
  1925. record for record in data_list
  1926. if (record.get('question') and keyword_lower in record['question'].lower()) or
  1927. (record.get('content') and keyword_lower in record['content'].lower())
  1928. ]
  1929. def get_total_training_count():
  1930. """获取当前训练数据总数"""
  1931. try:
  1932. training_data = vn.get_training_data()
  1933. if training_data is not None and not training_data.empty:
  1934. return len(training_data)
  1935. return 0
  1936. except Exception as e:
  1937. logger.warning(f"获取训练数据总数失败: {e}")
  1938. return 0
  1939. def process_single_training_item(item: dict, index: int) -> dict:
  1940. """处理单个训练数据项"""
  1941. training_type = item.get('training_data_type')
  1942. if training_type == 'sql':
  1943. sql = item.get('sql')
  1944. if not sql:
  1945. raise ValueError("SQL字段是必需的")
  1946. # SQL语法检查
  1947. is_valid, error_msg = validate_sql_syntax(sql)
  1948. if not is_valid:
  1949. raise ValueError(error_msg)
  1950. question = item.get('question')
  1951. if question:
  1952. training_id = vn.train(question=question, sql=sql)
  1953. else:
  1954. training_id = vn.train(sql=sql)
  1955. elif training_type == 'error_sql':
  1956. # error_sql不需要语法检查
  1957. question = item.get('question')
  1958. sql = item.get('sql')
  1959. if not question or not sql:
  1960. raise ValueError("question和sql字段都是必需的")
  1961. training_id = vn.train_error_sql(question=question, sql=sql)
  1962. elif training_type == 'documentation':
  1963. content = item.get('content')
  1964. if not content:
  1965. raise ValueError("content字段是必需的")
  1966. training_id = vn.train(documentation=content)
  1967. elif training_type == 'ddl':
  1968. ddl = item.get('ddl')
  1969. if not ddl:
  1970. raise ValueError("ddl字段是必需的")
  1971. training_id = vn.train(ddl=ddl)
  1972. else:
  1973. raise ValueError(f"不支持的训练数据类型: {training_type}")
  1974. return {
  1975. "index": index,
  1976. "success": True,
  1977. "training_id": training_id,
  1978. "type": training_type,
  1979. "message": f"{training_type}训练数据创建成功"
  1980. }
  1981. @app.route('/api/v0/training_data/stats', methods=['GET'])
  1982. def training_data_stats():
  1983. """获取训练数据统计信息API"""
  1984. try:
  1985. training_data = vn.get_training_data()
  1986. if training_data is None or training_data.empty:
  1987. return jsonify(success_response(
  1988. response_text="统计信息获取成功",
  1989. data={
  1990. "total_count": 0,
  1991. "type_breakdown": {
  1992. "sql": 0,
  1993. "documentation": 0,
  1994. "ddl": 0,
  1995. "error_sql": 0
  1996. },
  1997. "type_percentages": {
  1998. "sql": 0.0,
  1999. "documentation": 0.0,
  2000. "ddl": 0.0,
  2001. "error_sql": 0.0
  2002. },
  2003. "last_updated": datetime.now().isoformat()
  2004. }
  2005. ))
  2006. total_count = len(training_data)
  2007. # 统计各类型数量
  2008. type_breakdown = {"sql": 0, "documentation": 0, "ddl": 0, "error_sql": 0}
  2009. if 'training_data_type' in training_data.columns:
  2010. type_counts = training_data['training_data_type'].value_counts()
  2011. for data_type, count in type_counts.items():
  2012. if data_type in type_breakdown:
  2013. type_breakdown[data_type] = int(count)
  2014. # 计算百分比
  2015. type_percentages = {}
  2016. for data_type, count in type_breakdown.items():
  2017. type_percentages[data_type] = round(count / max(total_count, 1) * 100, 2)
  2018. return jsonify(success_response(
  2019. response_text="统计信息获取成功",
  2020. data={
  2021. "total_count": total_count,
  2022. "type_breakdown": type_breakdown,
  2023. "type_percentages": type_percentages,
  2024. "last_updated": datetime.now().isoformat()
  2025. }
  2026. ))
  2027. except Exception as e:
  2028. logger.error(f"training_data_stats执行失败: {str(e)}")
  2029. return jsonify(internal_error_response(
  2030. response_text="获取统计信息失败,请稍后重试"
  2031. )), 500
  2032. @app.route('/api/v0/training_data/query', methods=['POST'])
  2033. def training_data_query():
  2034. """分页查询训练数据API - 支持类型筛选、搜索和排序功能"""
  2035. try:
  2036. req = request.get_json(force=True)
  2037. # 解析参数,设置默认值
  2038. page = req.get('page', 1)
  2039. page_size = req.get('page_size', 20)
  2040. training_data_type = req.get('training_data_type')
  2041. sort_by = req.get('sort_by', 'id')
  2042. sort_order = req.get('sort_order', 'desc')
  2043. search_keyword = req.get('search_keyword')
  2044. # 参数验证
  2045. if page < 1:
  2046. return jsonify(bad_request_response(
  2047. response_text="页码必须大于0",
  2048. missing_params=["page"]
  2049. )), 400
  2050. if page_size < 1 or page_size > 100:
  2051. return jsonify(bad_request_response(
  2052. response_text="每页大小必须在1-100之间",
  2053. missing_params=["page_size"]
  2054. )), 400
  2055. if search_keyword and len(search_keyword) > 100:
  2056. return jsonify(bad_request_response(
  2057. response_text="搜索关键词最大长度为100字符",
  2058. missing_params=["search_keyword"]
  2059. )), 400
  2060. # 获取训练数据
  2061. training_data = vn.get_training_data()
  2062. if training_data is None or training_data.empty:
  2063. return jsonify(success_response(
  2064. response_text="查询成功,暂无训练数据",
  2065. data={
  2066. "records": [],
  2067. "pagination": {
  2068. "page": page,
  2069. "page_size": page_size,
  2070. "total": 0,
  2071. "total_pages": 0,
  2072. "has_next": False,
  2073. "has_prev": False
  2074. },
  2075. "filters_applied": {
  2076. "training_data_type": training_data_type,
  2077. "search_keyword": search_keyword
  2078. }
  2079. }
  2080. ))
  2081. # 转换为列表格式
  2082. records = training_data.to_dict(orient="records")
  2083. # 应用筛选条件
  2084. if training_data_type:
  2085. records = filter_by_type(records, training_data_type)
  2086. if search_keyword:
  2087. records = search_in_data(records, search_keyword)
  2088. # 排序
  2089. if sort_by in ['id', 'training_data_type']:
  2090. reverse = (sort_order.lower() == 'desc')
  2091. records.sort(key=lambda x: x.get(sort_by, ''), reverse=reverse)
  2092. # 分页
  2093. paginated_result = paginate_data(records, page, page_size)
  2094. return jsonify(success_response(
  2095. response_text=f"查询成功,共找到 {paginated_result['pagination']['total']} 条记录",
  2096. data={
  2097. "records": paginated_result["data"],
  2098. "pagination": paginated_result["pagination"],
  2099. "filters_applied": {
  2100. "training_data_type": training_data_type,
  2101. "search_keyword": search_keyword
  2102. }
  2103. }
  2104. ))
  2105. except Exception as e:
  2106. logger.error(f"training_data_query执行失败: {str(e)}")
  2107. return jsonify(internal_error_response(
  2108. response_text="查询训练数据失败,请稍后重试"
  2109. )), 500
  2110. @app.route('/api/v0/training_data/create', methods=['POST'])
  2111. def training_data_create():
  2112. """创建训练数据API - 支持单条和批量创建,支持四种数据类型"""
  2113. try:
  2114. req = request.get_json(force=True)
  2115. data = req.get('data')
  2116. if not data:
  2117. return jsonify(bad_request_response(
  2118. response_text="缺少必需参数:data",
  2119. missing_params=["data"]
  2120. )), 400
  2121. # 统一处理为列表格式
  2122. if isinstance(data, dict):
  2123. data_list = [data]
  2124. elif isinstance(data, list):
  2125. data_list = data
  2126. else:
  2127. return jsonify(bad_request_response(
  2128. response_text="data字段格式错误,应为对象或数组"
  2129. )), 400
  2130. # 批量操作限制
  2131. if len(data_list) > 50:
  2132. return jsonify(bad_request_response(
  2133. response_text="批量操作最大支持50条记录"
  2134. )), 400
  2135. results = []
  2136. successful_count = 0
  2137. type_summary = {"sql": 0, "documentation": 0, "ddl": 0, "error_sql": 0}
  2138. for index, item in enumerate(data_list):
  2139. try:
  2140. result = process_single_training_item(item, index)
  2141. results.append(result)
  2142. if result['success']:
  2143. successful_count += 1
  2144. type_summary[result['type']] += 1
  2145. except Exception as e:
  2146. results.append({
  2147. "index": index,
  2148. "success": False,
  2149. "type": item.get('training_data_type', 'unknown'),
  2150. "error": str(e),
  2151. "message": "创建失败"
  2152. })
  2153. # 获取创建后的总记录数
  2154. current_total = get_total_training_count()
  2155. # 根据实际执行结果决定响应状态
  2156. failed_count = len(data_list) - successful_count
  2157. if failed_count == 0:
  2158. # 全部成功
  2159. return jsonify(success_response(
  2160. response_text="训练数据创建完成",
  2161. data={
  2162. "total_requested": len(data_list),
  2163. "successfully_created": successful_count,
  2164. "failed_count": failed_count,
  2165. "results": results,
  2166. "summary": type_summary,
  2167. "current_total_count": current_total
  2168. }
  2169. ))
  2170. elif successful_count == 0:
  2171. # 全部失败
  2172. return jsonify(error_response(
  2173. response_text="训练数据创建失败",
  2174. data={
  2175. "total_requested": len(data_list),
  2176. "successfully_created": successful_count,
  2177. "failed_count": failed_count,
  2178. "results": results,
  2179. "summary": type_summary,
  2180. "current_total_count": current_total
  2181. }
  2182. )), 400
  2183. else:
  2184. # 部分成功,部分失败
  2185. return jsonify(error_response(
  2186. response_text=f"训练数据创建部分成功,成功{successful_count}条,失败{failed_count}条",
  2187. data={
  2188. "total_requested": len(data_list),
  2189. "successfully_created": successful_count,
  2190. "failed_count": failed_count,
  2191. "results": results,
  2192. "summary": type_summary,
  2193. "current_total_count": current_total
  2194. }
  2195. )), 207
  2196. except Exception as e:
  2197. logger.error(f"training_data_create执行失败: {str(e)}")
  2198. return jsonify(internal_error_response(
  2199. response_text="创建训练数据失败,请稍后重试"
  2200. )), 500
  2201. @app.route('/api/v0/training_data/delete', methods=['POST'])
  2202. def training_data_delete():
  2203. """删除训练数据API - 支持批量删除"""
  2204. try:
  2205. req = request.get_json(force=True)
  2206. ids = req.get('ids', [])
  2207. confirm = req.get('confirm', False)
  2208. if not ids or not isinstance(ids, list):
  2209. return jsonify(bad_request_response(
  2210. response_text="缺少有效的ID列表",
  2211. missing_params=["ids"]
  2212. )), 400
  2213. if not confirm:
  2214. return jsonify(bad_request_response(
  2215. response_text="删除操作需要确认,请设置confirm为true"
  2216. )), 400
  2217. # 批量操作限制
  2218. if len(ids) > 50:
  2219. return jsonify(bad_request_response(
  2220. response_text="批量删除最大支持50条记录"
  2221. )), 400
  2222. deleted_ids = []
  2223. failed_ids = []
  2224. failed_details = []
  2225. for training_id in ids:
  2226. try:
  2227. success = vn.remove_training_data(training_id)
  2228. if success:
  2229. deleted_ids.append(training_id)
  2230. else:
  2231. failed_ids.append(training_id)
  2232. failed_details.append({
  2233. "id": training_id,
  2234. "error": "记录不存在或删除失败"
  2235. })
  2236. except Exception as e:
  2237. failed_ids.append(training_id)
  2238. failed_details.append({
  2239. "id": training_id,
  2240. "error": str(e)
  2241. })
  2242. # 获取删除后的总记录数
  2243. current_total = get_total_training_count()
  2244. # 根据实际执行结果决定响应状态
  2245. failed_count = len(failed_ids)
  2246. if failed_count == 0:
  2247. # 全部成功
  2248. return jsonify(success_response(
  2249. response_text="训练数据删除完成",
  2250. data={
  2251. "total_requested": len(ids),
  2252. "successfully_deleted": len(deleted_ids),
  2253. "failed_count": failed_count,
  2254. "deleted_ids": deleted_ids,
  2255. "failed_ids": failed_ids,
  2256. "failed_details": failed_details,
  2257. "current_total_count": current_total
  2258. }
  2259. ))
  2260. elif len(deleted_ids) == 0:
  2261. # 全部失败
  2262. return jsonify(error_response(
  2263. response_text="训练数据删除失败",
  2264. data={
  2265. "total_requested": len(ids),
  2266. "successfully_deleted": len(deleted_ids),
  2267. "failed_count": failed_count,
  2268. "deleted_ids": deleted_ids,
  2269. "failed_ids": failed_ids,
  2270. "failed_details": failed_details,
  2271. "current_total_count": current_total
  2272. }
  2273. )), 400
  2274. else:
  2275. # 部分成功,部分失败
  2276. return jsonify(error_response(
  2277. response_text=f"训练数据删除部分成功,成功{len(deleted_ids)}条,失败{failed_count}条",
  2278. data={
  2279. "total_requested": len(ids),
  2280. "successfully_deleted": len(deleted_ids),
  2281. "failed_count": failed_count,
  2282. "deleted_ids": deleted_ids,
  2283. "failed_ids": failed_ids,
  2284. "failed_details": failed_details,
  2285. "current_total_count": current_total
  2286. }
  2287. )), 207
  2288. except Exception as e:
  2289. logger.error(f"training_data_delete执行失败: {str(e)}")
  2290. return jsonify(internal_error_response(
  2291. response_text="删除训练数据失败,请稍后重试"
  2292. )), 500
  2293. @app.route('/api/v0/training_data/update', methods=['POST'])
  2294. def training_data_update():
  2295. """更新训练数据API - 支持单条更新,采用先删除后插入策略"""
  2296. try:
  2297. req = request.get_json(force=True)
  2298. # 1. 参数验证
  2299. original_id = req.get('id')
  2300. if not original_id:
  2301. return jsonify(bad_request_response(
  2302. response_text="缺少必需参数:id",
  2303. missing_params=["id"]
  2304. )), 400
  2305. training_type = req.get('training_data_type')
  2306. if not training_type:
  2307. return jsonify(bad_request_response(
  2308. response_text="缺少必需参数:training_data_type",
  2309. missing_params=["training_data_type"]
  2310. )), 400
  2311. # 2. 先删除原始记录
  2312. try:
  2313. success = vn.remove_training_data(original_id)
  2314. if not success:
  2315. return jsonify(bad_request_response(
  2316. response_text=f"原始记录 {original_id} 不存在或删除失败"
  2317. )), 400
  2318. except Exception as e:
  2319. return jsonify(internal_error_response(
  2320. response_text=f"删除原始记录失败: {str(e)}"
  2321. )), 500
  2322. # 3. 根据类型验证和准备新数据
  2323. try:
  2324. if training_type == 'sql':
  2325. sql = req.get('sql')
  2326. if not sql:
  2327. return jsonify(bad_request_response(
  2328. response_text="SQL字段是必需的",
  2329. missing_params=["sql"]
  2330. )), 400
  2331. # SQL语法检查
  2332. is_valid, error_msg = validate_sql_syntax(sql)
  2333. if not is_valid:
  2334. return jsonify(bad_request_response(
  2335. response_text=f"SQL语法错误: {error_msg}"
  2336. )), 400
  2337. question = req.get('question')
  2338. if question:
  2339. training_id = vn.train(question=question, sql=sql)
  2340. else:
  2341. training_id = vn.train(sql=sql)
  2342. elif training_type == 'error_sql':
  2343. question = req.get('question')
  2344. sql = req.get('sql')
  2345. if not question or not sql:
  2346. return jsonify(bad_request_response(
  2347. response_text="question和sql字段都是必需的",
  2348. missing_params=["question", "sql"]
  2349. )), 400
  2350. training_id = vn.train_error_sql(question=question, sql=sql)
  2351. elif training_type == 'documentation':
  2352. content = req.get('content')
  2353. if not content:
  2354. return jsonify(bad_request_response(
  2355. response_text="content字段是必需的",
  2356. missing_params=["content"]
  2357. )), 400
  2358. training_id = vn.train(documentation=content)
  2359. elif training_type == 'ddl':
  2360. ddl = req.get('ddl')
  2361. if not ddl:
  2362. return jsonify(bad_request_response(
  2363. response_text="ddl字段是必需的",
  2364. missing_params=["ddl"]
  2365. )), 400
  2366. training_id = vn.train(ddl=ddl)
  2367. else:
  2368. return jsonify(bad_request_response(
  2369. response_text=f"不支持的训练数据类型: {training_type}"
  2370. )), 400
  2371. except Exception as e:
  2372. return jsonify(internal_error_response(
  2373. response_text=f"创建新训练数据失败: {str(e)}"
  2374. )), 500
  2375. # 4. 获取更新后的总记录数
  2376. current_total = get_total_training_count()
  2377. return jsonify(success_response(
  2378. response_text="训练数据更新成功",
  2379. data={
  2380. "original_id": original_id,
  2381. "new_training_id": training_id,
  2382. "type": training_type,
  2383. "current_total_count": current_total
  2384. }
  2385. ))
  2386. except Exception as e:
  2387. logger.error(f"training_data_update执行失败: {str(e)}")
  2388. return jsonify(internal_error_response(
  2389. response_text="更新训练数据失败,请稍后重试"
  2390. )), 500
  2391. # 导入现有的专业训练函数
  2392. from data_pipeline.trainer.run_training import (
  2393. train_ddl_statements,
  2394. train_documentation_blocks,
  2395. train_json_question_sql_pairs,
  2396. train_formatted_question_sql_pairs,
  2397. train_sql_examples
  2398. )
  2399. def get_allowed_extensions(file_type: str) -> list:
  2400. """根据文件类型返回允许的扩展名"""
  2401. type_specific_extensions = {
  2402. 'ddl': ['ddl', 'sql', 'txt', ''], # 支持无扩展名
  2403. 'markdown': ['md', 'markdown'], # 不支持无扩展名
  2404. 'sql_pair_json': ['json', 'txt', ''], # 支持无扩展名
  2405. 'sql_pair': ['sql', 'txt', ''], # 支持无扩展名
  2406. 'sql': ['sql', 'txt', ''] # 支持无扩展名
  2407. }
  2408. return type_specific_extensions.get(file_type, [])
  2409. def validate_file_content(content: str, file_type: str) -> dict:
  2410. """验证文件内容格式"""
  2411. try:
  2412. if file_type == 'ddl':
  2413. # 检查是否包含CREATE语句
  2414. if not re.search(r'\bCREATE\b', content, re.IGNORECASE):
  2415. return {'valid': False, 'error': '文件内容不符合DDL格式,必须包含CREATE语句'}
  2416. elif file_type == 'markdown':
  2417. # 检查是否包含##标题
  2418. if '##' not in content:
  2419. return {'valid': False, 'error': '文件内容不符合Markdown格式,必须包含##标题'}
  2420. elif file_type == 'sql_pair_json':
  2421. # 检查是否为有效JSON
  2422. try:
  2423. data = json.loads(content)
  2424. if not isinstance(data, list) or not data:
  2425. return {'valid': False, 'error': '文件内容不符合JSON问答对格式,必须是非空数组'}
  2426. # 检查是否包含question和sql字段
  2427. for item in data:
  2428. if not isinstance(item, dict):
  2429. return {'valid': False, 'error': '文件内容不符合JSON问答对格式,数组元素必须是对象'}
  2430. has_question = any(key.lower() == 'question' for key in item.keys())
  2431. has_sql = any(key.lower() == 'sql' for key in item.keys())
  2432. if not has_question or not has_sql:
  2433. return {'valid': False, 'error': '文件内容不符合JSON问答对格式,必须包含question和sql字段'}
  2434. except json.JSONDecodeError:
  2435. return {'valid': False, 'error': '文件内容不符合JSON问答对格式,JSON格式错误'}
  2436. elif file_type == 'sql_pair':
  2437. # 检查是否包含Question:和SQL:
  2438. if not re.search(r'\bQuestion\s*:', content, re.IGNORECASE):
  2439. return {'valid': False, 'error': '文件内容不符合问答对格式,必须包含Question:'}
  2440. if not re.search(r'\bSQL\s*:', content, re.IGNORECASE):
  2441. return {'valid': False, 'error': '文件内容不符合问答对格式,必须包含SQL:'}
  2442. elif file_type == 'sql':
  2443. # 检查是否包含;分隔符
  2444. if ';' not in content:
  2445. return {'valid': False, 'error': '文件内容不符合SQL格式,必须包含;分隔符'}
  2446. return {'valid': True}
  2447. except Exception as e:
  2448. return {'valid': False, 'error': f'文件内容验证失败: {str(e)}'}
  2449. @app.route('/api/v0/training_data/upload', methods=['POST'])
  2450. def upload_training_data():
  2451. """上传训练数据文件API - 支持多种文件格式的自动解析和导入"""
  2452. try:
  2453. # 1. 参数验证
  2454. if 'file' not in request.files:
  2455. return jsonify(bad_request_response("未提供文件"))
  2456. file = request.files['file']
  2457. if file.filename == '':
  2458. return jsonify(bad_request_response("未选择文件"))
  2459. # 获取file_type参数
  2460. file_type = request.form.get('file_type')
  2461. if not file_type:
  2462. return jsonify(bad_request_response("缺少必需参数:file_type"))
  2463. # 验证file_type参数
  2464. valid_file_types = ['ddl', 'markdown', 'sql_pair_json', 'sql_pair', 'sql']
  2465. if file_type not in valid_file_types:
  2466. return jsonify(bad_request_response(f"不支持的文件类型:{file_type},支持的类型:{', '.join(valid_file_types)}"))
  2467. # 2. 文件大小验证 (500KB)
  2468. file.seek(0, 2)
  2469. file_size = file.tell()
  2470. file.seek(0)
  2471. if file_size > 500 * 1024: # 500KB
  2472. return jsonify(bad_request_response("文件大小不能超过500KB"))
  2473. # 3. 验证文件扩展名(基于file_type)
  2474. filename = secure_filename(file.filename)
  2475. allowed_extensions = get_allowed_extensions(file_type)
  2476. file_ext = filename.split('.')[-1].lower() if '.' in filename else ''
  2477. if file_ext not in allowed_extensions:
  2478. # 构建友好的错误信息
  2479. non_empty_extensions = [ext for ext in allowed_extensions if ext]
  2480. if '' in allowed_extensions:
  2481. ext_message = f"{', '.join(non_empty_extensions)} 或无扩展名"
  2482. else:
  2483. ext_message = ', '.join(non_empty_extensions)
  2484. return jsonify(bad_request_response(f"文件类型 {file_type} 不支持的文件扩展名:{file_ext},支持的扩展名:{ext_message}"))
  2485. # 4. 读取文件内容并验证格式
  2486. file.seek(0)
  2487. content = file.read().decode('utf-8')
  2488. # 格式验证
  2489. validation_result = validate_file_content(content, file_type)
  2490. if not validation_result['valid']:
  2491. return jsonify(bad_request_response(validation_result['error']))
  2492. # 5. 创建临时文件(复用现有函数需要文件路径)
  2493. temp_file_path = None
  2494. try:
  2495. with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix='.tmp', encoding='utf-8') as tmp_file:
  2496. tmp_file.write(content)
  2497. temp_file_path = tmp_file.name
  2498. # 6. 根据文件类型调用现有的训练函数
  2499. if file_type == 'ddl':
  2500. train_ddl_statements(temp_file_path)
  2501. elif file_type == 'markdown':
  2502. train_documentation_blocks(temp_file_path)
  2503. elif file_type == 'sql_pair_json':
  2504. train_json_question_sql_pairs(temp_file_path)
  2505. elif file_type == 'sql_pair':
  2506. train_formatted_question_sql_pairs(temp_file_path)
  2507. elif file_type == 'sql':
  2508. train_sql_examples(temp_file_path)
  2509. return jsonify(success_response(
  2510. response_text=f"文件上传并训练成功:{filename}",
  2511. data={
  2512. "filename": filename,
  2513. "file_type": file_type,
  2514. "file_size": file_size,
  2515. "status": "completed"
  2516. }
  2517. ))
  2518. except Exception as e:
  2519. logger.error(f"训练失败: {str(e)}")
  2520. return jsonify(internal_error_response(f"训练失败: {str(e)}"))
  2521. finally:
  2522. # 清理临时文件
  2523. if temp_file_path and os.path.exists(temp_file_path):
  2524. try:
  2525. os.unlink(temp_file_path)
  2526. except Exception as e:
  2527. logger.warning(f"清理临时文件失败: {str(e)}")
  2528. except Exception as e:
  2529. logger.error(f"文件上传失败: {str(e)}")
  2530. return jsonify(internal_error_response(f"文件上传失败: {str(e)}"))
  2531. def get_db_connection():
  2532. """获取数据库连接"""
  2533. try:
  2534. from app_config import PGVECTOR_CONFIG
  2535. return psycopg2.connect(**PGVECTOR_CONFIG)
  2536. except Exception as e:
  2537. logger.error(f"数据库连接失败: {str(e)}")
  2538. raise
  2539. def get_db_connection_for_transaction():
  2540. """获取用于事务操作的数据库连接(非自动提交模式)"""
  2541. try:
  2542. from app_config import PGVECTOR_CONFIG
  2543. conn = psycopg2.connect(**PGVECTOR_CONFIG)
  2544. conn.autocommit = False # 设置为非自动提交模式,允许手动控制事务
  2545. return conn
  2546. except Exception as e:
  2547. logger.error(f"数据库连接失败: {str(e)}")
  2548. raise
  2549. @app.route('/api/v0/training_data/combine', methods=['POST'])
  2550. def combine_training_data():
  2551. """合并训练数据API - 支持合并重复记录"""
  2552. try:
  2553. # 1. 参数验证
  2554. data = request.get_json()
  2555. if not data:
  2556. return jsonify(bad_request_response("请求体不能为空"))
  2557. collection_names = data.get('collection_names', [])
  2558. if not collection_names or not isinstance(collection_names, list):
  2559. return jsonify(bad_request_response("collection_names 参数必须是非空数组"))
  2560. # 验证集合名称
  2561. valid_collections = ['sql', 'ddl', 'documentation', 'error_sql']
  2562. invalid_collections = [name for name in collection_names if name not in valid_collections]
  2563. if invalid_collections:
  2564. return jsonify(bad_request_response(f"不支持的集合名称: {invalid_collections}"))
  2565. dry_run = data.get('dry_run', True)
  2566. keep_strategy = data.get('keep_strategy', 'first')
  2567. if keep_strategy not in ['first', 'last', 'by_metadata_time']:
  2568. return jsonify(bad_request_response("keep_strategy 必须是 'first', 'last' 或 'by_metadata_time'"))
  2569. # 2. 获取数据库连接(用于事务操作)
  2570. conn = get_db_connection_for_transaction()
  2571. cursor = conn.cursor()
  2572. # 3. 查找重复记录
  2573. duplicate_groups = []
  2574. total_before = 0
  2575. total_duplicates = 0
  2576. collections_stats = {}
  2577. for collection_name in collection_names:
  2578. # 获取集合ID
  2579. cursor.execute(
  2580. "SELECT uuid FROM langchain_pg_collection WHERE name = %s",
  2581. (collection_name,)
  2582. )
  2583. collection_result = cursor.fetchone()
  2584. if not collection_result:
  2585. continue
  2586. collection_id = collection_result[0]
  2587. # 统计该集合的记录数
  2588. cursor.execute(
  2589. "SELECT COUNT(*) FROM langchain_pg_embedding WHERE collection_id = %s",
  2590. (collection_id,)
  2591. )
  2592. collection_before = cursor.fetchone()[0]
  2593. total_before += collection_before
  2594. # 查找重复记录
  2595. if keep_strategy in ['first', 'last']:
  2596. order_by = "id"
  2597. else:
  2598. order_by = "COALESCE((cmetadata->>'createdat')::timestamp, '1970-01-01'::timestamp) DESC, id"
  2599. cursor.execute(f"""
  2600. SELECT document, COUNT(*) as duplicate_count,
  2601. array_agg(id ORDER BY {order_by}) as record_ids
  2602. FROM langchain_pg_embedding
  2603. WHERE collection_id = %s
  2604. GROUP BY document
  2605. HAVING COUNT(*) > 1
  2606. """, (collection_id,))
  2607. collection_duplicates = 0
  2608. for row in cursor.fetchall():
  2609. document_content, duplicate_count, record_ids = row
  2610. collection_duplicates += duplicate_count - 1 # 减去要保留的一条
  2611. # 根据保留策略选择要保留的记录
  2612. if keep_strategy == 'first':
  2613. keep_id = record_ids[0]
  2614. remove_ids = record_ids[1:]
  2615. elif keep_strategy == 'last':
  2616. keep_id = record_ids[-1]
  2617. remove_ids = record_ids[:-1]
  2618. else: # by_metadata_time
  2619. keep_id = record_ids[0] # 已经按时间排序
  2620. remove_ids = record_ids[1:]
  2621. duplicate_groups.append({
  2622. "collection_name": collection_name,
  2623. "document_content": document_content[:100] + "..." if len(document_content) > 100 else document_content,
  2624. "duplicate_count": duplicate_count,
  2625. "kept_record_id" if not dry_run else "records_to_keep": keep_id,
  2626. "removed_record_ids" if not dry_run else "records_to_remove": remove_ids
  2627. })
  2628. total_duplicates += collection_duplicates
  2629. collections_stats[collection_name] = {
  2630. "before": collection_before,
  2631. "after": collection_before - collection_duplicates,
  2632. "duplicates_removed" if not dry_run else "duplicates_to_remove": collection_duplicates
  2633. }
  2634. # 4. 执行合并操作(如果不是dry_run)
  2635. if not dry_run:
  2636. try:
  2637. # 连接已经设置为非自动提交模式,直接开始事务
  2638. for group in duplicate_groups:
  2639. remove_ids = group["removed_record_ids"]
  2640. if remove_ids:
  2641. cursor.execute(
  2642. "DELETE FROM langchain_pg_embedding WHERE id = ANY(%s)",
  2643. (remove_ids,)
  2644. )
  2645. conn.commit()
  2646. except Exception as e:
  2647. conn.rollback()
  2648. return jsonify(internal_error_response(f"合并操作失败: {str(e)}"))
  2649. # 5. 构建响应
  2650. total_after = total_before - total_duplicates
  2651. summary = {
  2652. "total_records_before": total_before,
  2653. "total_records_after": total_after,
  2654. "duplicates_removed" if not dry_run else "duplicates_to_remove": total_duplicates,
  2655. "collections_stats": collections_stats
  2656. }
  2657. if dry_run:
  2658. response_text = f"发现 {total_duplicates} 条重复记录,预计删除后将从 {total_before} 条减少到 {total_after} 条记录"
  2659. data_key = "duplicate_groups"
  2660. else:
  2661. response_text = f"成功合并重复记录,删除了 {total_duplicates} 条重复记录,从 {total_before} 条减少到 {total_after} 条记录"
  2662. data_key = "merged_groups"
  2663. return jsonify(success_response(
  2664. response_text=response_text,
  2665. data={
  2666. "dry_run": dry_run,
  2667. "collections_processed": collection_names,
  2668. "summary": summary,
  2669. data_key: duplicate_groups
  2670. }
  2671. ))
  2672. except Exception as e:
  2673. return jsonify(internal_error_response(f"合并操作失败: {str(e)}"))
  2674. finally:
  2675. if 'cursor' in locals():
  2676. cursor.close()
  2677. if 'conn' in locals():
  2678. conn.close()
  2679. # ==================== React Agent 扩展API ====================
  2680. @app.route('/api/v0/react/users/<user_id>/conversations', methods=['GET'])
  2681. async def get_user_conversations_react(user_id: str):
  2682. """异步获取用户的聊天记录列表(从 custom_react_agent 迁移)"""
  2683. global _react_agent_instance
  2684. try:
  2685. # 获取查询参数
  2686. limit = request.args.get('limit', 10, type=int)
  2687. # 限制limit的范围
  2688. limit = max(1, min(limit, 50)) # 限制在1-50之间
  2689. logger.info(f"📋 异步获取用户 {user_id} 的对话列表,限制 {limit} 条")
  2690. # 确保Agent可用
  2691. if not await ensure_agent_ready():
  2692. return jsonify(service_unavailable_response(
  2693. response_text="Agent 未就绪"
  2694. )), 503
  2695. # 直接调用异步方法
  2696. conversations = await _react_agent_instance.get_user_recent_conversations(user_id, limit)
  2697. return jsonify(success_response(
  2698. response_text="获取用户对话列表成功",
  2699. data={
  2700. "user_id": user_id,
  2701. "conversations": conversations,
  2702. "total_count": len(conversations),
  2703. "limit": limit
  2704. }
  2705. )), 200
  2706. except Exception as e:
  2707. logger.error(f"❌ 异步获取用户 {user_id} 对话列表失败: {e}")
  2708. return jsonify(internal_error_response(
  2709. response_text=f"获取用户对话列表失败: {str(e)}"
  2710. )), 500
  2711. @app.route('/api/v0/react/conversations/<thread_id>', methods=['GET'])
  2712. async def get_user_conversation_detail_react(thread_id: str):
  2713. """异步获取特定对话的详细历史(从 custom_react_agent 迁移)"""
  2714. global _react_agent_instance
  2715. try:
  2716. # 从thread_id中提取user_id
  2717. user_id = thread_id.split(':')[0] if ':' in thread_id else 'unknown'
  2718. logger.info(f"📖 异步获取用户 {user_id} 的对话 {thread_id} 详情")
  2719. # 确保Agent可用
  2720. if not await ensure_agent_ready():
  2721. return jsonify(service_unavailable_response(
  2722. response_text="Agent 未就绪"
  2723. )), 503
  2724. # 获取查询参数
  2725. include_tools = request.args.get('include_tools', 'false').lower() == 'true'
  2726. # 直接调用异步方法
  2727. conversation_data = await _react_agent_instance.get_conversation_history(thread_id, include_tools=include_tools)
  2728. messages = conversation_data.get("messages", [])
  2729. logger.info(f"✅ 异步成功获取对话历史,消息数量: {len(messages)}")
  2730. if not messages:
  2731. return jsonify(not_found_response(
  2732. response_text=f"未找到对话 {thread_id}"
  2733. )), 404
  2734. # 格式化消息
  2735. formatted_messages = []
  2736. for msg in messages:
  2737. formatted_msg = {
  2738. "message_id": msg["id"], # id -> message_id
  2739. "role": msg["type"], # type -> role
  2740. "content": msg["content"],
  2741. "timestamp": _format_timestamp_to_china_time(msg["timestamp"]) # 转换为中国时区
  2742. }
  2743. formatted_messages.append(formatted_msg)
  2744. return jsonify(success_response(
  2745. response_text="获取对话详情成功",
  2746. data={
  2747. "user_id": user_id,
  2748. "thread_id": thread_id,
  2749. "conversation_id": thread_id, # 新增conversation_id字段
  2750. "message_count": len(formatted_messages),
  2751. "messages": formatted_messages,
  2752. "created_at": conversation_data.get("thread_created_at"), # 已经包含毫秒
  2753. "total_checkpoints": conversation_data.get("total_checkpoints", 0)
  2754. }
  2755. )), 200
  2756. except Exception as e:
  2757. import traceback
  2758. logger.error(f"❌ 异步获取对话 {thread_id} 详情失败: {e}")
  2759. logger.error(f"❌ 详细错误信息: {traceback.format_exc()}")
  2760. return jsonify(internal_error_response(
  2761. response_text=f"获取对话详情失败: {str(e)}"
  2762. )), 500
  2763. @app.route('/api/test/redis', methods=['GET'])
  2764. def test_redis_connection():
  2765. """测试Redis连接和基本查询(从 custom_react_agent 迁移)"""
  2766. try:
  2767. import redis
  2768. # 创建Redis连接
  2769. if react_agent_config:
  2770. r = redis.Redis(
  2771. host=react_agent_config.REDIS_HOST,
  2772. port=react_agent_config.REDIS_PORT,
  2773. db=react_agent_config.REDIS_DB,
  2774. password=react_agent_config.REDIS_PASSWORD,
  2775. decode_responses=True
  2776. )
  2777. else:
  2778. r = redis.Redis(host='localhost', port=6379, decode_responses=True)
  2779. r.ping()
  2780. # 扫描checkpoint keys
  2781. pattern = "checkpoint:*"
  2782. keys = []
  2783. cursor = 0
  2784. count = 0
  2785. while True:
  2786. cursor, batch = r.scan(cursor=cursor, match=pattern, count=100)
  2787. keys.extend(batch)
  2788. count += len(batch)
  2789. if cursor == 0 or count > 500: # 限制扫描数量
  2790. break
  2791. # 统计用户
  2792. users = {}
  2793. for key in keys:
  2794. try:
  2795. parts = key.split(':')
  2796. if len(parts) >= 2:
  2797. user_id = parts[1]
  2798. users[user_id] = users.get(user_id, 0) + 1
  2799. except:
  2800. continue
  2801. r.close()
  2802. return jsonify({
  2803. "success": True,
  2804. "data": {
  2805. "redis_connected": True,
  2806. "total_checkpoint_keys": len(keys),
  2807. "users_found": list(users.keys()),
  2808. "user_key_counts": users,
  2809. "sample_keys": keys[:5] if keys else []
  2810. },
  2811. "timestamp": datetime.now().isoformat()
  2812. }), 200
  2813. except Exception as e:
  2814. logger.error(f"❌ Redis测试失败: {e}")
  2815. return jsonify({
  2816. "success": False,
  2817. "error": str(e),
  2818. "timestamp": datetime.now().isoformat()
  2819. }), 500
  2820. @app.route('/api/v0/react/direct/users/<user_id>/conversations', methods=['GET'])
  2821. def test_get_user_conversations_simple(user_id: str):
  2822. """直接从Redis获取用户对话列表"""
  2823. try:
  2824. limit = request.args.get('limit', 10, type=int)
  2825. limit = max(1, min(limit, 50))
  2826. logger.info(f"📋 获取用户 {user_id} 的对话列表(直接Redis方式)")
  2827. # 使用简单Redis查询
  2828. conversations = get_user_conversations_simple_sync(user_id, limit)
  2829. return jsonify(success_response(
  2830. response_text="获取用户对话列表成功",
  2831. data={
  2832. "user_id": user_id,
  2833. "conversations": conversations,
  2834. "total_count": len(conversations),
  2835. "limit": limit
  2836. }
  2837. )), 200
  2838. except Exception as e:
  2839. logger.error(f"❌ 获取用户对话列表失败: {e}")
  2840. return jsonify(internal_error_response(
  2841. response_text=f"获取用户对话列表失败: {str(e)}"
  2842. )), 500
  2843. @app.route('/api/v0/react/direct/conversations/<thread_id>', methods=['GET'])
  2844. def get_conversation_detail_api(thread_id: str):
  2845. """
  2846. 获取特定对话的详细信息 - 支持include_tools开关参数(从 custom_react_agent 迁移)
  2847. Query Parameters:
  2848. - include_tools: bool, 是否包含工具调用信息,默认false
  2849. true: 返回完整对话(human/ai/tool/system)
  2850. false: 只返回human/ai消息,清理工具调用信息
  2851. - user_id: str, 可选的用户ID验证
  2852. Examples:
  2853. GET /api/conversations/wang:20250709195048728?include_tools=true # 完整模式
  2854. GET /api/conversations/wang:20250709195048728?include_tools=false # 简化模式(默认)
  2855. GET /api/conversations/wang:20250709195048728 # 简化模式(默认)
  2856. """
  2857. try:
  2858. # 获取查询参数
  2859. include_tools = request.args.get('include_tools', 'false').lower() == 'true'
  2860. user_id = request.args.get('user_id')
  2861. # 验证thread_id格式
  2862. if ':' not in thread_id:
  2863. return jsonify({
  2864. "success": False,
  2865. "error": "Invalid thread_id format. Expected format: user_id:timestamp",
  2866. "timestamp": datetime.now().isoformat()
  2867. }), 400
  2868. # 如果提供了user_id,验证thread_id是否属于该用户
  2869. thread_user_id = thread_id.split(':')[0]
  2870. if user_id and thread_user_id != user_id:
  2871. return jsonify(bad_request_response(
  2872. response_text=f"Thread ID {thread_id} does not belong to user {user_id}"
  2873. )), 400
  2874. logger.info(f"📖 获取对话详情 - Thread: {thread_id}, Include Tools: {include_tools}")
  2875. # 检查enhanced_redis_api是否可用
  2876. if get_conversation_detail_from_redis is None:
  2877. return jsonify(service_unavailable_response(
  2878. response_text="enhanced_redis_api 模块不可用"
  2879. )), 503
  2880. # 从Redis获取对话详情(使用我们的新函数)
  2881. result = get_conversation_detail_from_redis(thread_id, include_tools)
  2882. if not result['success']:
  2883. logger.warning(f"⚠️ 获取对话详情失败: {result['error']}")
  2884. return jsonify(internal_error_response(
  2885. response_text=result['error']
  2886. )), 404
  2887. # 添加API元数据
  2888. result['data']['api_metadata'] = {
  2889. "timestamp": datetime.now().isoformat(),
  2890. "api_version": "v1",
  2891. "endpoint": "get_conversation_detail",
  2892. "query_params": {
  2893. "include_tools": include_tools,
  2894. "user_id": user_id
  2895. }
  2896. }
  2897. mode_desc = "完整模式" if include_tools else "简化模式"
  2898. logger.info(f"✅ 成功获取对话详情 - Messages: {result['data']['message_count']}, Mode: {mode_desc}")
  2899. return jsonify(success_response(
  2900. response_text=f"获取对话详情成功 ({mode_desc})",
  2901. data=result['data']
  2902. )), 200
  2903. except Exception as e:
  2904. import traceback
  2905. logger.error(f"❌ 获取对话详情异常: {e}")
  2906. logger.error(f"❌ 详细错误信息: {traceback.format_exc()}")
  2907. return jsonify(internal_error_response(
  2908. response_text=f"获取对话详情失败: {str(e)}"
  2909. )), 500
  2910. @app.route('/api/v0/react/direct/conversations/<thread_id>/compare', methods=['GET'])
  2911. def compare_conversation_modes_api(thread_id: str):
  2912. """
  2913. 比较完整模式和简化模式的对话内容
  2914. 用于调试和理解两种模式的差异(从 custom_react_agent 迁移)
  2915. Examples:
  2916. GET /api/conversations/wang:20250709195048728/compare
  2917. """
  2918. try:
  2919. logger.info(f"🔍 比较对话模式 - Thread: {thread_id}")
  2920. # 检查enhanced_redis_api是否可用
  2921. if get_conversation_detail_from_redis is None:
  2922. return jsonify({
  2923. "success": False,
  2924. "error": "enhanced_redis_api 模块不可用",
  2925. "timestamp": datetime.now().isoformat()
  2926. }), 503
  2927. # 获取完整模式
  2928. full_result = get_conversation_detail_from_redis(thread_id, include_tools=True)
  2929. # 获取简化模式
  2930. simple_result = get_conversation_detail_from_redis(thread_id, include_tools=False)
  2931. if not (full_result['success'] and simple_result['success']):
  2932. return jsonify({
  2933. "success": False,
  2934. "error": "无法获取对话数据进行比较",
  2935. "timestamp": datetime.now().isoformat()
  2936. }), 404
  2937. # 构建比较结果
  2938. comparison = {
  2939. "thread_id": thread_id,
  2940. "full_mode": {
  2941. "message_count": full_result['data']['message_count'],
  2942. "stats": full_result['data']['stats'],
  2943. "sample_messages": full_result['data']['messages'][:3] # 只显示前3条作为示例
  2944. },
  2945. "simple_mode": {
  2946. "message_count": simple_result['data']['message_count'],
  2947. "stats": simple_result['data']['stats'],
  2948. "sample_messages": simple_result['data']['messages'][:3] # 只显示前3条作为示例
  2949. },
  2950. "comparison_summary": {
  2951. "message_count_difference": full_result['data']['message_count'] - simple_result['data']['message_count'],
  2952. "tools_filtered_out": full_result['data']['stats'].get('tool_messages', 0),
  2953. "ai_messages_with_tools": full_result['data']['stats'].get('messages_with_tools', 0),
  2954. "filtering_effectiveness": "有效" if (full_result['data']['message_count'] - simple_result['data']['message_count']) > 0 else "无差异"
  2955. },
  2956. "metadata": {
  2957. "timestamp": datetime.now().isoformat(),
  2958. "note": "sample_messages 只显示前3条消息作为示例,完整消息请使用相应的详情API"
  2959. }
  2960. }
  2961. logger.info(f"✅ 模式比较完成 - 完整: {comparison['full_mode']['message_count']}, 简化: {comparison['simple_mode']['message_count']}")
  2962. return jsonify({
  2963. "success": True,
  2964. "data": comparison,
  2965. "timestamp": datetime.now().isoformat()
  2966. }), 200
  2967. except Exception as e:
  2968. logger.error(f"❌ 对话模式比较失败: {e}")
  2969. return jsonify({
  2970. "success": False,
  2971. "error": str(e),
  2972. "timestamp": datetime.now().isoformat()
  2973. }), 500
  2974. @app.route('/api/v0/react/direct/conversations/<thread_id>/summary', methods=['GET'])
  2975. def get_conversation_summary_api(thread_id: str):
  2976. """
  2977. 获取对话摘要信息(只包含基本统计,不返回具体消息)(从 custom_react_agent 迁移)
  2978. Query Parameters:
  2979. - include_tools: bool, 影响统计信息的计算方式
  2980. Examples:
  2981. GET /api/conversations/wang:20250709195048728/summary?include_tools=true
  2982. """
  2983. try:
  2984. include_tools = request.args.get('include_tools', 'false').lower() == 'true'
  2985. # 验证thread_id格式
  2986. if ':' not in thread_id:
  2987. return jsonify(bad_request_response(
  2988. response_text="Invalid thread_id format. Expected format: user_id:timestamp"
  2989. )), 400
  2990. logger.info(f"📊 获取对话摘要 - Thread: {thread_id}, Include Tools: {include_tools}")
  2991. # 检查enhanced_redis_api是否可用
  2992. if get_conversation_detail_from_redis is None:
  2993. return jsonify(service_unavailable_response(
  2994. response_text="enhanced_redis_api 模块不可用"
  2995. )), 503
  2996. # 获取完整对话信息
  2997. result = get_conversation_detail_from_redis(thread_id, include_tools)
  2998. if not result['success']:
  2999. return jsonify(internal_error_response(
  3000. response_text=result['error']
  3001. )), 404
  3002. # 只返回摘要信息,不包含具体消息
  3003. data = result['data']
  3004. summary = {
  3005. "thread_id": data['thread_id'],
  3006. "user_id": data['user_id'],
  3007. "include_tools": data['include_tools'],
  3008. "message_count": data['message_count'],
  3009. "stats": data['stats'],
  3010. "metadata": data['metadata'],
  3011. "first_message_preview": None,
  3012. "last_message_preview": None,
  3013. "conversation_preview": None
  3014. }
  3015. # 添加消息预览
  3016. messages = data.get('messages', [])
  3017. if messages:
  3018. # 第一条human消息预览
  3019. for msg in messages:
  3020. if msg['role'] == 'human':
  3021. content = str(msg['content'])
  3022. summary['first_message_preview'] = content[:100] + "..." if len(content) > 100 else content
  3023. break
  3024. # 最后一条ai消息预览
  3025. for msg in reversed(messages):
  3026. if msg['role'] == 'ai' and msg.get('content', '').strip():
  3027. content = str(msg['content'])
  3028. summary['last_message_preview'] = content[:100] + "..." if len(content) > 100 else content
  3029. break
  3030. # 生成对话预览(第一条human消息)
  3031. summary['conversation_preview'] = summary['first_message_preview']
  3032. # 添加API元数据
  3033. summary['api_metadata'] = {
  3034. "timestamp": datetime.now().isoformat(),
  3035. "api_version": "v1",
  3036. "endpoint": "get_conversation_summary"
  3037. }
  3038. logger.info(f"✅ 成功获取对话摘要")
  3039. return jsonify(success_response(
  3040. response_text="获取对话摘要成功",
  3041. data=summary
  3042. )), 200
  3043. except Exception as e:
  3044. logger.error(f"❌ 获取对话摘要失败: {e}")
  3045. return jsonify(internal_error_response(
  3046. response_text=f"获取对话摘要失败: {str(e)}"
  3047. )), 500
  3048. # ================== Checkpoint 管理 API ==================
  3049. @app.route('/api/v0/checkpoint/direct/cleanup', methods=['POST'])
  3050. async def cleanup_checkpoints():
  3051. """
  3052. 清理checkpoint,保留最近N个
  3053. 请求参数:
  3054. - keep_count: 可选,保留数量,默认使用配置值
  3055. - user_id: 可选,指定用户ID
  3056. - thread_id: 可选,指定线程ID
  3057. 参数逻辑:
  3058. - 无任何参数:清理所有thread_id的checkpoint
  3059. - 只有user_id:清理指定用户的所有thread
  3060. - 只有thread_id:清理指定的thread
  3061. - user_id和thread_id同时存在:以thread_id为准
  3062. """
  3063. try:
  3064. # 获取请求参数
  3065. data = request.get_json() or {}
  3066. keep_count = data.get('keep_count', react_agent_config.CHECKPOINT_KEEP_COUNT)
  3067. user_id = data.get('user_id')
  3068. thread_id = data.get('thread_id')
  3069. logger.info(f"🧹 开始checkpoint清理 - keep_count: {keep_count}, user_id: {user_id}, thread_id: {thread_id}")
  3070. # 参数验证
  3071. if keep_count <= 0:
  3072. return jsonify(bad_request_response(
  3073. response_text="keep_count必须大于0"
  3074. )), 400
  3075. # 验证thread_id格式
  3076. if thread_id and ':' not in thread_id:
  3077. return jsonify(bad_request_response(
  3078. response_text="thread_id格式错误,期望格式: user_id:timestamp"
  3079. )), 400
  3080. # 创建Redis连接(异步版本)
  3081. redis_client = redis.Redis(
  3082. host=react_agent_config.REDIS_HOST,
  3083. port=react_agent_config.REDIS_PORT,
  3084. db=react_agent_config.REDIS_DB,
  3085. password=react_agent_config.REDIS_PASSWORD,
  3086. decode_responses=True
  3087. )
  3088. await redis_client.ping()
  3089. # 确定扫描模式和操作类型
  3090. if thread_id:
  3091. # 清理指定thread
  3092. pattern = f"checkpoint:{thread_id}:*"
  3093. operation_type = "cleanup_thread"
  3094. target = thread_id
  3095. elif user_id:
  3096. # 清理指定用户的所有thread
  3097. pattern = f"checkpoint:{user_id}:*"
  3098. operation_type = "cleanup_user"
  3099. target = user_id
  3100. else:
  3101. # 清理所有thread
  3102. pattern = "checkpoint:*"
  3103. operation_type = "cleanup_all"
  3104. target = "all"
  3105. logger.info(f" 扫描模式: {pattern}")
  3106. # 扫描匹配的keys
  3107. keys = []
  3108. cursor = 0
  3109. while True:
  3110. cursor, batch = await redis_client.scan(cursor=cursor, match=pattern, count=1000)
  3111. keys.extend(batch)
  3112. if cursor == 0:
  3113. break
  3114. logger.info(f" 找到 {len(keys)} 个checkpoint keys")
  3115. if not keys:
  3116. await redis_client.close()
  3117. return jsonify(success_response(
  3118. response_text="未找到需要清理的checkpoint",
  3119. data={
  3120. "operation_type": operation_type,
  3121. "target": target,
  3122. "keep_count": keep_count,
  3123. "total_processed": 0,
  3124. "total_deleted": 0,
  3125. "details": {}
  3126. }
  3127. )), 200
  3128. # 按thread_id分组
  3129. thread_groups = {}
  3130. for key in keys:
  3131. parts = key.split(':')
  3132. if len(parts) >= 3:
  3133. key_user_id = parts[1]
  3134. timestamp = parts[2]
  3135. key_thread_id = f"{key_user_id}:{timestamp}"
  3136. if key_thread_id not in thread_groups:
  3137. thread_groups[key_thread_id] = []
  3138. thread_groups[key_thread_id].append(key)
  3139. logger.info(f" 分组结果: {len(thread_groups)} 个threads")
  3140. # 清理每个thread的checkpoint
  3141. details = {}
  3142. total_deleted = 0
  3143. total_processed = 0
  3144. for tid, tid_keys in thread_groups.items():
  3145. original_count = len(tid_keys)
  3146. if original_count <= keep_count:
  3147. # 无需清理
  3148. details[tid] = {
  3149. "original_count": original_count,
  3150. "deleted_count": 0,
  3151. "remaining_count": original_count,
  3152. "status": "no_cleanup_needed"
  3153. }
  3154. total_processed += 1
  3155. continue
  3156. # 按key排序(key包含timestamp,天然有序)
  3157. tid_keys.sort()
  3158. keys_to_delete = tid_keys[:-keep_count]
  3159. # 使用Redis Pipeline批量删除
  3160. deleted_count = 0
  3161. if keys_to_delete:
  3162. try:
  3163. pipeline = redis_client.pipeline()
  3164. for key in keys_to_delete:
  3165. pipeline.delete(key)
  3166. await pipeline.execute()
  3167. deleted_count = len(keys_to_delete)
  3168. logger.info(f" Thread {tid}: 删除了 {deleted_count} 个checkpoint")
  3169. except Exception as e:
  3170. logger.error(f" Thread {tid}: 批量删除失败: {e}")
  3171. # 尝试逐个删除
  3172. for key in keys_to_delete:
  3173. try:
  3174. await redis_client.delete(key)
  3175. deleted_count += 1
  3176. except Exception as del_error:
  3177. logger.error(f" 删除key失败: {key}, 错误: {del_error}")
  3178. details[tid] = {
  3179. "original_count": original_count,
  3180. "deleted_count": deleted_count,
  3181. "remaining_count": original_count - deleted_count,
  3182. "status": "success" if deleted_count > 0 else "failed"
  3183. }
  3184. total_deleted += deleted_count
  3185. total_processed += 1
  3186. await redis_client.aclose()
  3187. logger.info(f"✅ Checkpoint清理完成 - 处理{total_processed}个threads,删除{total_deleted}个checkpoints")
  3188. return jsonify(success_response(
  3189. response_text=f"Checkpoint清理完成,删除了{total_deleted}个checkpoint",
  3190. data={
  3191. "operation_type": operation_type,
  3192. "target": target,
  3193. "keep_count": keep_count,
  3194. "total_processed": total_processed,
  3195. "total_deleted": total_deleted,
  3196. "details": details
  3197. }
  3198. )), 200
  3199. except redis.ConnectionError as e:
  3200. logger.error(f"❌ Redis连接失败: {e}")
  3201. return jsonify(internal_error_response(
  3202. response_text="Redis连接失败,请检查Redis服务状态"
  3203. )), 500
  3204. except Exception as e:
  3205. logger.error(f"❌ Checkpoint清理失败: {e}")
  3206. return jsonify(internal_error_response(
  3207. response_text=f"Checkpoint清理失败: {str(e)}"
  3208. )), 500
  3209. @app.route('/api/v0/checkpoint/direct/stats', methods=['GET'])
  3210. async def get_checkpoint_stats():
  3211. """
  3212. 获取checkpoint统计信息
  3213. 查询参数:
  3214. - user_id: 可选,指定用户ID
  3215. 调用方式:
  3216. GET /api/v0/checkpoint/direct/stats # 获取全部统计信息
  3217. GET /api/v0/checkpoint/direct/stats?user_id=wang1 # 获取指定用户统计信息
  3218. """
  3219. try:
  3220. user_id = request.args.get('user_id')
  3221. logger.info(f"📊 获取checkpoint统计 - user_id: {user_id}")
  3222. # 创建Redis连接(异步版本)
  3223. redis_client = redis.Redis(
  3224. host=react_agent_config.REDIS_HOST,
  3225. port=react_agent_config.REDIS_PORT,
  3226. db=react_agent_config.REDIS_DB,
  3227. password=react_agent_config.REDIS_PASSWORD,
  3228. decode_responses=True
  3229. )
  3230. await redis_client.ping()
  3231. # 确定扫描模式
  3232. if user_id:
  3233. pattern = f"checkpoint:{user_id}:*"
  3234. operation_type = "user_stats"
  3235. else:
  3236. pattern = "checkpoint:*"
  3237. operation_type = "system_stats"
  3238. logger.info(f" 扫描模式: {pattern}")
  3239. # 扫描匹配的keys
  3240. keys = []
  3241. cursor = 0
  3242. while True:
  3243. cursor, batch = await redis_client.scan(cursor=cursor, match=pattern, count=1000)
  3244. keys.extend(batch)
  3245. if cursor == 0:
  3246. break
  3247. logger.info(f" 找到 {len(keys)} 个checkpoint keys")
  3248. await redis_client.aclose()
  3249. if not keys:
  3250. if user_id:
  3251. return jsonify(not_found_response(
  3252. response_text=f"用户 {user_id} 没有任何checkpoint"
  3253. )), 404
  3254. else:
  3255. return jsonify(success_response(
  3256. response_text="系统中暂无checkpoint数据",
  3257. data={
  3258. "operation_type": operation_type,
  3259. "total_users": 0,
  3260. "total_threads": 0,
  3261. "total_checkpoints": 0,
  3262. "users": []
  3263. }
  3264. )), 200
  3265. # 按用户和thread分组统计
  3266. user_stats = {}
  3267. for key in keys:
  3268. parts = key.split(':')
  3269. if len(parts) >= 3:
  3270. key_user_id = parts[1]
  3271. timestamp = parts[2]
  3272. thread_id = f"{key_user_id}:{timestamp}"
  3273. if key_user_id not in user_stats:
  3274. user_stats[key_user_id] = {}
  3275. if thread_id not in user_stats[key_user_id]:
  3276. user_stats[key_user_id][thread_id] = 0
  3277. user_stats[key_user_id][thread_id] += 1
  3278. # 构建响应数据
  3279. if user_id:
  3280. # 返回指定用户的统计信息
  3281. if user_id not in user_stats:
  3282. return jsonify(not_found_response(
  3283. response_text=f"用户 {user_id} 没有任何checkpoint"
  3284. )), 404
  3285. threads = []
  3286. total_checkpoints = 0
  3287. for thread_id, count in user_stats[user_id].items():
  3288. threads.append({
  3289. "thread_id": thread_id,
  3290. "checkpoint_count": count
  3291. })
  3292. total_checkpoints += count
  3293. # 按checkpoint数量排序
  3294. threads.sort(key=lambda x: x["checkpoint_count"], reverse=True)
  3295. result_data = {
  3296. "operation_type": operation_type,
  3297. "user_id": user_id,
  3298. "thread_count": len(threads),
  3299. "total_checkpoints": total_checkpoints,
  3300. "threads": threads
  3301. }
  3302. logger.info(f"✅ 获取用户 {user_id} 统计完成 - {len(threads)} threads, {total_checkpoints} checkpoints")
  3303. return jsonify(success_response(
  3304. response_text=f"获取用户{user_id}统计成功",
  3305. data=result_data
  3306. )), 200
  3307. else:
  3308. # 返回系统全部统计信息
  3309. users = []
  3310. total_threads = 0
  3311. total_checkpoints = 0
  3312. for uid, threads_data in user_stats.items():
  3313. user_threads = []
  3314. user_total_checkpoints = 0
  3315. for thread_id, count in threads_data.items():
  3316. user_threads.append({
  3317. "thread_id": thread_id,
  3318. "checkpoint_count": count
  3319. })
  3320. user_total_checkpoints += count
  3321. # 按checkpoint数量排序
  3322. user_threads.sort(key=lambda x: x["checkpoint_count"], reverse=True)
  3323. users.append({
  3324. "user_id": uid,
  3325. "thread_count": len(user_threads),
  3326. "total_checkpoints": user_total_checkpoints,
  3327. "threads": user_threads
  3328. })
  3329. total_threads += len(user_threads)
  3330. total_checkpoints += user_total_checkpoints
  3331. # 按用户的checkpoint数量排序
  3332. users.sort(key=lambda x: x["total_checkpoints"], reverse=True)
  3333. result_data = {
  3334. "operation_type": operation_type,
  3335. "total_users": len(users),
  3336. "total_threads": total_threads,
  3337. "total_checkpoints": total_checkpoints,
  3338. "users": users
  3339. }
  3340. logger.info(f"✅ 获取系统统计完成 - {len(users)} users, {total_threads} threads, {total_checkpoints} checkpoints")
  3341. return jsonify(success_response(
  3342. response_text="获取系统checkpoint统计成功",
  3343. data=result_data
  3344. )), 200
  3345. except redis.ConnectionError as e:
  3346. logger.error(f"❌ Redis连接失败: {e}")
  3347. return jsonify(internal_error_response(
  3348. response_text="Redis连接失败,请检查Redis服务状态"
  3349. )), 500
  3350. except Exception as e:
  3351. logger.error(f"❌ 获取checkpoint统计失败: {e}")
  3352. return jsonify(internal_error_response(
  3353. response_text=f"获取checkpoint统计失败: {str(e)}"
  3354. )), 500
  3355. # Data Pipeline 全局变量 - 从 citu_app.py 迁移
  3356. data_pipeline_manager = None
  3357. data_pipeline_file_manager = None
  3358. def get_data_pipeline_manager():
  3359. """获取Data Pipeline管理器单例(从 citu_app.py 迁移)"""
  3360. global data_pipeline_manager
  3361. if data_pipeline_manager is None:
  3362. data_pipeline_manager = SimpleWorkflowManager()
  3363. return data_pipeline_manager
  3364. def get_data_pipeline_file_manager():
  3365. """获取Data Pipeline文件管理器单例(从 citu_app.py 迁移)"""
  3366. global data_pipeline_file_manager
  3367. if data_pipeline_file_manager is None:
  3368. data_pipeline_file_manager = SimpleFileManager()
  3369. return data_pipeline_file_manager
  3370. # ==================== QA缓存管理API (从 citu_app.py 迁移) ====================
  3371. @app.route('/api/v0/qa_cache_stats', methods=['GET'])
  3372. def qa_cache_stats():
  3373. """获取问答缓存统计信息(从 citu_app.py 迁移)"""
  3374. try:
  3375. stats = redis_conversation_manager.get_qa_cache_stats()
  3376. return jsonify(success_response(
  3377. response_text="获取问答缓存统计成功",
  3378. data=stats
  3379. ))
  3380. except Exception as e:
  3381. logger.error(f"获取问答缓存统计失败: {str(e)}")
  3382. return jsonify(internal_error_response(
  3383. response_text="获取问答缓存统计失败,请稍后重试"
  3384. )), 500
  3385. @app.route('/api/v0/qa_cache_cleanup', methods=['POST'])
  3386. def qa_cache_cleanup():
  3387. """清空所有问答缓存(从 citu_app.py 迁移)"""
  3388. try:
  3389. if not redis_conversation_manager.is_available():
  3390. return jsonify(internal_error_response(
  3391. response_text="Redis连接不可用,无法执行清理操作"
  3392. )), 500
  3393. deleted_count = redis_conversation_manager.clear_all_qa_cache()
  3394. return jsonify(success_response(
  3395. response_text="问答缓存清理完成",
  3396. data={
  3397. "deleted_count": deleted_count,
  3398. "cleared": deleted_count > 0,
  3399. "cleanup_time": datetime.now().isoformat()
  3400. }
  3401. ))
  3402. except Exception as e:
  3403. logger.error(f"清空问答缓存失败: {str(e)}")
  3404. return jsonify(internal_error_response(
  3405. response_text="清空问答缓存失败,请稍后重试"
  3406. )), 500
  3407. # ==================== Database API (从 citu_app.py 迁移) ====================
  3408. @app.route('/api/v0/database/tables', methods=['POST'])
  3409. def get_database_tables():
  3410. """
  3411. 获取数据库表列表(从 citu_app.py 迁移)
  3412. 请求体:
  3413. {
  3414. "db_connection": "postgresql://postgres:postgres@192.168.67.1:5432/highway_db", // 可选,不传则使用默认配置
  3415. "schema": "public,ods", // 可选,支持多个schema用逗号分隔,默认为public
  3416. "table_name_pattern": "ods_*" // 可选,表名模式匹配,支持通配符:ods_*、*_dim、*fact*、ods_%
  3417. }
  3418. 响应:
  3419. {
  3420. "success": true,
  3421. "code": 200,
  3422. "message": "获取表列表成功",
  3423. "data": {
  3424. "tables": ["public.table1", "public.table2", "ods.table3"],
  3425. "total": 3,
  3426. "schemas": ["public", "ods"],
  3427. "table_name_pattern": "ods_*"
  3428. }
  3429. }
  3430. """
  3431. try:
  3432. req = request.get_json(force=True)
  3433. # 处理数据库连接参数(可选)
  3434. db_connection = req.get('db_connection')
  3435. if not db_connection:
  3436. # 使用app_config的默认数据库配置
  3437. import app_config
  3438. db_params = app_config.APP_DB_CONFIG
  3439. db_connection = f"postgresql://{db_params['user']}:{db_params['password']}@{db_params['host']}:{db_params['port']}/{db_params['dbname']}"
  3440. logger.info("使用默认数据库配置获取表列表")
  3441. else:
  3442. logger.info("使用用户指定的数据库配置获取表列表")
  3443. # 可选参数
  3444. schema = req.get('schema', '')
  3445. table_name_pattern = req.get('table_name_pattern')
  3446. # 创建表检查API实例
  3447. table_inspector = TableInspectorAPI()
  3448. # 使用asyncio运行异步方法
  3449. async def get_tables():
  3450. return await table_inspector.get_tables_list(db_connection, schema, table_name_pattern)
  3451. # 在新的事件循环中运行异步方法
  3452. try:
  3453. loop = asyncio.new_event_loop()
  3454. asyncio.set_event_loop(loop)
  3455. tables = loop.run_until_complete(get_tables())
  3456. finally:
  3457. loop.close()
  3458. # 解析schema信息
  3459. parsed_schemas = table_inspector._parse_schemas(schema)
  3460. response_data = {
  3461. "tables": tables,
  3462. "total": len(tables),
  3463. "schemas": parsed_schemas,
  3464. "db_connection_info": {
  3465. "database": db_connection.split('/')[-1].split('?')[0] if '/' in db_connection else "unknown"
  3466. }
  3467. }
  3468. # 如果使用了表名模式,添加到响应中
  3469. if table_name_pattern:
  3470. response_data["table_name_pattern"] = table_name_pattern
  3471. return jsonify(success_response(
  3472. response_text="获取表列表成功",
  3473. data=response_data
  3474. )), 200
  3475. except Exception as e:
  3476. logger.error(f"获取数据库表列表失败: {str(e)}")
  3477. return jsonify(internal_error_response(
  3478. response_text=f"获取表列表失败: {str(e)}"
  3479. )), 500
  3480. @app.route('/api/v0/database/table/ddl', methods=['POST'])
  3481. def get_table_ddl():
  3482. """
  3483. 获取表的DDL语句或MD文档(从 citu_app.py 迁移)
  3484. 请求体:
  3485. {
  3486. "db_connection": "postgresql://postgres:postgres@192.168.67.1:5432/highway_db", // 可选,不传则使用默认配置
  3487. "table": "public.test",
  3488. "business_context": "这是高速公路服务区的相关数据", // 可选
  3489. "type": "ddl" // 可选,支持ddl/md/both,默认为ddl
  3490. }
  3491. 响应:
  3492. {
  3493. "success": true,
  3494. "code": 200,
  3495. "message": "获取表DDL成功",
  3496. "data": {
  3497. "ddl": "create table public.test (...);",
  3498. "md": "## test表...", // 仅当type为md或both时返回
  3499. "table_info": {
  3500. "table_name": "test",
  3501. "schema_name": "public",
  3502. "full_name": "public.test",
  3503. "comment": "测试表",
  3504. "field_count": 10,
  3505. "row_count": 1000
  3506. },
  3507. "fields": [...]
  3508. }
  3509. }
  3510. """
  3511. try:
  3512. req = request.get_json(force=True)
  3513. # 处理参数(table仍为必需,db_connection可选)
  3514. table = req.get('table')
  3515. db_connection = req.get('db_connection')
  3516. if not table:
  3517. return jsonify(bad_request_response(
  3518. response_text="缺少必需参数:table",
  3519. missing_params=['table']
  3520. )), 400
  3521. if not db_connection:
  3522. # 使用app_config的默认数据库配置
  3523. import app_config
  3524. db_params = app_config.APP_DB_CONFIG
  3525. db_connection = f"postgresql://{db_params['user']}:{db_params['password']}@{db_params['host']}:{db_params['port']}/{db_params['dbname']}"
  3526. logger.info("使用默认数据库配置获取表DDL")
  3527. else:
  3528. logger.info("使用用户指定的数据库配置获取表DDL")
  3529. # 可选参数
  3530. business_context = req.get('business_context', '')
  3531. output_type = req.get('type', 'ddl')
  3532. # 验证type参数
  3533. valid_types = ['ddl', 'md', 'both']
  3534. if output_type not in valid_types:
  3535. return jsonify(bad_request_response(
  3536. response_text=f"无效的type参数: {output_type},支持的值: {valid_types}",
  3537. invalid_params=['type']
  3538. )), 400
  3539. # 创建表检查API实例
  3540. table_inspector = TableInspectorAPI()
  3541. # 使用asyncio运行异步方法
  3542. async def get_ddl():
  3543. return await table_inspector.get_table_ddl(
  3544. db_connection=db_connection,
  3545. table=table,
  3546. business_context=business_context,
  3547. output_type=output_type
  3548. )
  3549. # 在新的事件循环中运行异步方法
  3550. try:
  3551. loop = asyncio.new_event_loop()
  3552. asyncio.set_event_loop(loop)
  3553. result = loop.run_until_complete(get_ddl())
  3554. finally:
  3555. loop.close()
  3556. response_data = {
  3557. **result,
  3558. "generation_info": {
  3559. "business_context": business_context,
  3560. "output_type": output_type,
  3561. "has_llm_comments": bool(business_context),
  3562. "database": db_connection.split('/')[-1].split('?')[0] if '/' in db_connection else "unknown"
  3563. }
  3564. }
  3565. return jsonify(success_response(
  3566. response_text=f"获取表{output_type.upper()}成功",
  3567. data=response_data
  3568. )), 200
  3569. except Exception as e:
  3570. logger.error(f"获取表DDL失败: {str(e)}")
  3571. return jsonify(internal_error_response(
  3572. response_text=f"获取表{output_type.upper() if 'output_type' in locals() else 'DDL'}失败: {str(e)}"
  3573. )), 500
  3574. # ==================== Data Pipeline API (从 citu_app.py 迁移) ====================
  3575. @app.route('/api/v0/data_pipeline/tasks', methods=['POST'])
  3576. def create_data_pipeline_task():
  3577. """创建数据管道任务(从 citu_app.py 迁移)"""
  3578. try:
  3579. req = request.get_json(force=True)
  3580. # table_list_file和business_context现在都是可选参数
  3581. # 如果未提供table_list_file,将使用文件上传模式
  3582. # 创建任务(支持可选的db_connection参数)
  3583. manager = get_data_pipeline_manager()
  3584. task_id = manager.create_task(
  3585. table_list_file=req.get('table_list_file'),
  3586. business_context=req.get('business_context'),
  3587. db_name=req.get('db_name'), # 可选参数,用于指定特定数据库名称
  3588. db_connection=req.get('db_connection'), # 可选参数,用于指定数据库连接字符串
  3589. task_name=req.get('task_name'), # 可选参数,用于指定任务名称
  3590. enable_sql_validation=req.get('enable_sql_validation', True),
  3591. enable_llm_repair=req.get('enable_llm_repair', True),
  3592. modify_original_file=req.get('modify_original_file', True),
  3593. enable_training_data_load=req.get('enable_training_data_load', True)
  3594. )
  3595. # 获取任务信息
  3596. task_info = manager.get_task_status(task_id)
  3597. response_data = {
  3598. "task_id": task_id,
  3599. "task_name": task_info.get('task_name'),
  3600. "status": task_info.get('status'),
  3601. "created_at": task_info.get('created_at').isoformat() if task_info.get('created_at') else None
  3602. }
  3603. # 检查是否为文件上传模式
  3604. file_upload_mode = not req.get('table_list_file')
  3605. response_message = "任务创建成功"
  3606. if file_upload_mode:
  3607. response_data["file_upload_mode"] = True
  3608. response_data["next_step"] = f"POST /api/v0/data_pipeline/tasks/{task_id}/upload-table-list"
  3609. response_message += ",请上传表清单文件后再执行任务"
  3610. return jsonify(success_response(
  3611. response_text=response_message,
  3612. data=response_data
  3613. )), 201
  3614. except Exception as e:
  3615. logger.error(f"创建数据管道任务失败: {str(e)}")
  3616. return jsonify(internal_error_response(
  3617. response_text="创建任务失败,请稍后重试"
  3618. )), 500
  3619. @app.route('/api/v0/data_pipeline/tasks/<task_id>/execute', methods=['POST'])
  3620. def execute_data_pipeline_task(task_id):
  3621. """执行数据管道任务(从 citu_app.py 迁移)"""
  3622. try:
  3623. req = request.get_json(force=True) if request.is_json else {}
  3624. execution_mode = req.get('execution_mode', 'complete')
  3625. step_name = req.get('step_name')
  3626. # 新增:Vector表管理参数
  3627. backup_vector_tables = req.get('backup_vector_tables', False)
  3628. truncate_vector_tables = req.get('truncate_vector_tables', False)
  3629. skip_training = req.get('skip_training', False)
  3630. # 验证执行模式
  3631. if execution_mode not in ['complete', 'step']:
  3632. return jsonify(bad_request_response(
  3633. response_text="无效的执行模式,必须是 'complete' 或 'step'",
  3634. invalid_params=['execution_mode']
  3635. )), 400
  3636. # 如果是步骤执行模式,验证步骤名称
  3637. if execution_mode == 'step':
  3638. if not step_name:
  3639. return jsonify(bad_request_response(
  3640. response_text="步骤执行模式需要指定step_name",
  3641. missing_params=['step_name']
  3642. )), 400
  3643. valid_steps = ['ddl_generation', 'qa_generation', 'sql_validation', 'training_load']
  3644. if step_name not in valid_steps:
  3645. return jsonify(bad_request_response(
  3646. response_text=f"无效的步骤名称,支持的步骤: {', '.join(valid_steps)}",
  3647. invalid_params=['step_name']
  3648. )), 400
  3649. # 新增:Vector表管理参数验证和警告
  3650. if execution_mode == 'step' and step_name != 'training_load':
  3651. if backup_vector_tables or truncate_vector_tables or skip_training:
  3652. logger.warning(
  3653. f"⚠️ Vector表管理参数仅在training_load步骤有效,当前步骤: {step_name},忽略参数"
  3654. )
  3655. backup_vector_tables = False
  3656. truncate_vector_tables = False
  3657. skip_training = False
  3658. # 检查任务是否存在
  3659. manager = get_data_pipeline_manager()
  3660. task_info = manager.get_task_status(task_id)
  3661. if not task_info:
  3662. return jsonify(not_found_response(
  3663. response_text=f"任务不存在: {task_id}"
  3664. )), 404
  3665. # 使用subprocess启动独立进程执行任务
  3666. def run_task_subprocess():
  3667. try:
  3668. import subprocess
  3669. import sys
  3670. from pathlib import Path
  3671. # 构建执行命令
  3672. python_executable = sys.executable
  3673. script_path = Path(__file__).parent / "data_pipeline" / "task_executor.py"
  3674. cmd = [
  3675. python_executable,
  3676. str(script_path),
  3677. "--task-id", task_id,
  3678. "--execution-mode", execution_mode
  3679. ]
  3680. if step_name:
  3681. cmd.extend(["--step-name", step_name])
  3682. # 新增:Vector表管理参数传递
  3683. if backup_vector_tables:
  3684. cmd.append("--backup-vector-tables")
  3685. if truncate_vector_tables:
  3686. cmd.append("--truncate-vector-tables")
  3687. if skip_training:
  3688. cmd.append("--skip-training")
  3689. logger.info(f"启动任务进程: {' '.join(cmd)}")
  3690. # 启动后台进程(不等待完成)
  3691. process = subprocess.Popen(
  3692. cmd,
  3693. stdout=subprocess.PIPE,
  3694. stderr=subprocess.PIPE,
  3695. text=True,
  3696. cwd=Path(__file__).parent
  3697. )
  3698. logger.info(f"任务进程已启动: PID={process.pid}, task_id={task_id}")
  3699. except Exception as e:
  3700. logger.error(f"启动任务进程失败: {task_id}, 错误: {str(e)}")
  3701. # 在新线程中启动subprocess(避免阻塞API响应)
  3702. thread = Thread(target=run_task_subprocess, daemon=True)
  3703. thread.start()
  3704. # 新增:记录Vector表管理参数到日志
  3705. if backup_vector_tables or truncate_vector_tables:
  3706. logger.info(f"📋 API请求包含Vector表管理参数: backup={backup_vector_tables}, truncate={truncate_vector_tables}")
  3707. response_data = {
  3708. "task_id": task_id,
  3709. "execution_mode": execution_mode,
  3710. "step_name": step_name if execution_mode == 'step' else None,
  3711. "message": "任务正在后台执行,请通过状态接口查询进度"
  3712. }
  3713. return jsonify(success_response(
  3714. response_text="任务执行已启动",
  3715. data=response_data
  3716. )), 202
  3717. except Exception as e:
  3718. logger.error(f"启动数据管道任务执行失败: {str(e)}")
  3719. return jsonify(internal_error_response(
  3720. response_text="启动任务执行失败,请稍后重试"
  3721. )), 500
  3722. @app.route('/api/v0/data_pipeline/tasks/<task_id>', methods=['GET'])
  3723. def get_data_pipeline_task_status(task_id):
  3724. """
  3725. 获取数据管道任务状态(从 citu_app.py 迁移)
  3726. 响应:
  3727. {
  3728. "success": true,
  3729. "code": 200,
  3730. "message": "获取任务状态成功",
  3731. "data": {
  3732. "task_id": "task_20250627_143052",
  3733. "status": "in_progress",
  3734. "step_status": {
  3735. "ddl_generation": "completed",
  3736. "qa_generation": "running",
  3737. "sql_validation": "pending",
  3738. "training_load": "pending"
  3739. },
  3740. "created_at": "2025-06-27T14:30:52",
  3741. "started_at": "2025-06-27T14:31:00",
  3742. "parameters": {...},
  3743. "current_execution": {...},
  3744. "total_executions": 2
  3745. }
  3746. }
  3747. """
  3748. try:
  3749. manager = get_data_pipeline_manager()
  3750. task_info = manager.get_task_status(task_id)
  3751. if not task_info:
  3752. return jsonify(not_found_response(
  3753. response_text=f"任务不存在: {task_id}"
  3754. )), 404
  3755. # 获取步骤状态
  3756. steps = manager.get_task_steps(task_id)
  3757. current_step = None
  3758. for step in steps:
  3759. if step['step_status'] == 'running':
  3760. current_step = step
  3761. break
  3762. # 构建步骤状态摘要
  3763. step_status_summary = {}
  3764. for step in steps:
  3765. step_status_summary[step['step_name']] = step['step_status']
  3766. response_data = {
  3767. "task_id": task_info['task_id'],
  3768. "task_name": task_info.get('task_name'),
  3769. "status": task_info['status'],
  3770. "step_status": step_status_summary,
  3771. "created_at": task_info['created_at'].isoformat() if task_info.get('created_at') else None,
  3772. "started_at": task_info['started_at'].isoformat() if task_info.get('started_at') else None,
  3773. "completed_at": task_info['completed_at'].isoformat() if task_info.get('completed_at') else None,
  3774. "parameters": task_info.get('parameters', {}),
  3775. "result": task_info.get('result'),
  3776. "error_message": task_info.get('error_message'),
  3777. "current_step": {
  3778. "execution_id": current_step['execution_id'],
  3779. "step": current_step['step_name'],
  3780. "status": current_step['step_status'],
  3781. "started_at": current_step['started_at'].isoformat() if current_step and current_step.get('started_at') else None
  3782. } if current_step else None,
  3783. "total_steps": len(steps),
  3784. "steps": [{
  3785. "step_name": step['step_name'],
  3786. "step_status": step['step_status'],
  3787. "started_at": step['started_at'].isoformat() if step.get('started_at') else None,
  3788. "completed_at": step['completed_at'].isoformat() if step.get('completed_at') else None,
  3789. "error_message": step.get('error_message')
  3790. } for step in steps]
  3791. }
  3792. return jsonify(success_response(
  3793. response_text="获取任务状态成功",
  3794. data=response_data
  3795. ))
  3796. except Exception as e:
  3797. logger.error(f"获取数据管道任务状态失败: {str(e)}")
  3798. return jsonify(internal_error_response(
  3799. response_text="获取任务状态失败,请稍后重试"
  3800. )), 500
  3801. @app.route('/api/v0/data_pipeline/tasks/<task_id>/logs', methods=['GET'])
  3802. def get_data_pipeline_task_logs(task_id):
  3803. """
  3804. 获取数据管道任务日志(从任务目录文件读取)(从 citu_app.py 迁移)
  3805. 查询参数:
  3806. - limit: 日志行数限制,默认100
  3807. - level: 日志级别过滤,可选
  3808. 响应:
  3809. {
  3810. "success": true,
  3811. "code": 200,
  3812. "message": "获取任务日志成功",
  3813. "data": {
  3814. "task_id": "task_20250627_143052",
  3815. "logs": [
  3816. {
  3817. "timestamp": "2025-06-27 14:30:52",
  3818. "level": "INFO",
  3819. "message": "任务开始执行"
  3820. }
  3821. ],
  3822. "total": 15,
  3823. "source": "file"
  3824. }
  3825. }
  3826. """
  3827. try:
  3828. limit = request.args.get('limit', 100, type=int)
  3829. level = request.args.get('level')
  3830. # 限制最大查询数量
  3831. limit = min(limit, 1000)
  3832. manager = get_data_pipeline_manager()
  3833. # 验证任务是否存在
  3834. task_info = manager.get_task_status(task_id)
  3835. if not task_info:
  3836. return jsonify(not_found_response(
  3837. response_text=f"任务不存在: {task_id}"
  3838. )), 404
  3839. # 获取任务目录下的日志文件
  3840. import os
  3841. from pathlib import Path
  3842. # 获取项目根目录的绝对路径
  3843. project_root = Path(__file__).parent.absolute()
  3844. task_dir = project_root / "data_pipeline" / "training_data" / task_id
  3845. log_file = task_dir / "data_pipeline.log"
  3846. logs = []
  3847. if log_file.exists():
  3848. try:
  3849. # 读取日志文件的最后N行
  3850. with open(log_file, 'r', encoding='utf-8') as f:
  3851. lines = f.readlines()
  3852. # 取最后limit行
  3853. recent_lines = lines[-limit:] if len(lines) > limit else lines
  3854. # 解析日志行
  3855. import re
  3856. log_pattern = r'^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}) \[(\w+)\] (.+?): (.+)$'
  3857. for line in recent_lines:
  3858. line = line.strip()
  3859. if not line:
  3860. continue
  3861. match = re.match(log_pattern, line)
  3862. if match:
  3863. timestamp, log_level, logger_name, message = match.groups()
  3864. # 级别过滤
  3865. if level and log_level != level.upper():
  3866. continue
  3867. logs.append({
  3868. "timestamp": timestamp,
  3869. "level": log_level,
  3870. "logger": logger_name,
  3871. "message": message
  3872. })
  3873. else:
  3874. # 处理多行日志(如异常堆栈)
  3875. if logs:
  3876. logs[-1]["message"] += f"\n{line}"
  3877. except Exception as e:
  3878. logger.error(f"读取日志文件失败: {e}")
  3879. response_data = {
  3880. "task_id": task_id,
  3881. "logs": logs,
  3882. "total": len(logs),
  3883. "source": "file",
  3884. "log_file": str(log_file) if log_file.exists() else None
  3885. }
  3886. return jsonify(success_response(
  3887. response_text="获取任务日志成功",
  3888. data=response_data
  3889. ))
  3890. except Exception as e:
  3891. logger.error(f"获取数据管道任务日志失败: {str(e)}")
  3892. return jsonify(internal_error_response(
  3893. response_text="获取任务日志失败,请稍后重试"
  3894. )), 500
  3895. @app.route('/api/v0/data_pipeline/tasks', methods=['GET'])
  3896. def list_data_pipeline_tasks():
  3897. """获取数据管道任务列表(从 citu_app.py 迁移)"""
  3898. try:
  3899. limit = request.args.get('limit', 50, type=int)
  3900. offset = request.args.get('offset', 0, type=int)
  3901. status_filter = request.args.get('status')
  3902. # 限制查询数量
  3903. limit = min(limit, 100)
  3904. manager = get_data_pipeline_manager()
  3905. tasks = manager.get_tasks_list(
  3906. limit=limit,
  3907. offset=offset,
  3908. status_filter=status_filter
  3909. )
  3910. # 格式化任务列表
  3911. formatted_tasks = []
  3912. for task in tasks:
  3913. formatted_tasks.append({
  3914. "task_id": task.get('task_id'),
  3915. "task_name": task.get('task_name'),
  3916. "status": task.get('status'),
  3917. "step_status": task.get('step_status'),
  3918. "created_at": task['created_at'].isoformat() if task.get('created_at') else None,
  3919. "started_at": task['started_at'].isoformat() if task.get('started_at') else None,
  3920. "completed_at": task['completed_at'].isoformat() if task.get('completed_at') else None,
  3921. "created_by": task.get('by_user'),
  3922. "db_name": task.get('db_name'),
  3923. "business_context": task.get('parameters', {}).get('business_context') if task.get('parameters') else None,
  3924. # 新增字段
  3925. "directory_exists": task.get('directory_exists', True), # 默认为True,兼容旧数据
  3926. "updated_at": task['updated_at'].isoformat() if task.get('updated_at') else None
  3927. })
  3928. response_data = {
  3929. "tasks": formatted_tasks,
  3930. "total": len(formatted_tasks),
  3931. "limit": limit,
  3932. "offset": offset
  3933. }
  3934. return jsonify(success_response(
  3935. response_text="获取任务列表成功",
  3936. data=response_data
  3937. ))
  3938. except Exception as e:
  3939. logger.error(f"获取数据管道任务列表失败: {str(e)}")
  3940. return jsonify(internal_error_response(
  3941. response_text="获取任务列表失败,请稍后重试"
  3942. )), 500
  3943. @app.route('/api/v0/data_pipeline/tasks/query', methods=['POST'])
  3944. def query_data_pipeline_tasks():
  3945. """
  3946. 高级查询数据管道任务列表(从 citu_app.py 迁移)
  3947. 支持复杂筛选、排序、分页功能
  3948. 请求体:
  3949. {
  3950. "page": 1, // 页码,必须大于0,默认1
  3951. "page_size": 20, // 每页大小,1-100之间,默认20
  3952. "status": "completed", // 可选,任务状态筛选:"pending"|"running"|"completed"|"failed"|"cancelled"
  3953. "task_name": "highway", // 可选,任务名称模糊搜索,最大100字符
  3954. "created_by": "user123", // 可选,创建者精确匹配
  3955. "db_name": "highway_db", // 可选,数据库名称精确匹配
  3956. "created_time_start": "2025-01-01T00:00:00", // 可选,创建时间范围开始
  3957. "created_time_end": "2025-12-31T23:59:59", // 可选,创建时间范围结束
  3958. "started_time_start": "2025-01-01T00:00:00", // 可选,开始时间范围开始
  3959. "started_time_end": "2025-12-31T23:59:59", // 可选,开始时间范围结束
  3960. "completed_time_start": "2025-01-01T00:00:00", // 可选,完成时间范围开始
  3961. "completed_time_end": "2025-12-31T23:59:59", // 可选,完成时间范围结束
  3962. "sort_by": "created_at", // 可选,排序字段:"created_at"|"started_at"|"completed_at"|"task_name"|"status",默认"created_at"
  3963. "sort_order": "desc" // 可选,排序方向:"asc"|"desc",默认"desc"
  3964. }
  3965. """
  3966. try:
  3967. # 获取请求数据
  3968. req = request.get_json(force=True) if request.is_json else {}
  3969. # 解析参数,设置默认值
  3970. page = req.get('page', 1)
  3971. page_size = req.get('page_size', 20)
  3972. status = req.get('status')
  3973. task_name = req.get('task_name')
  3974. created_by = req.get('created_by')
  3975. db_name = req.get('db_name')
  3976. created_time_start = req.get('created_time_start')
  3977. created_time_end = req.get('created_time_end')
  3978. started_time_start = req.get('started_time_start')
  3979. started_time_end = req.get('started_time_end')
  3980. completed_time_start = req.get('completed_time_start')
  3981. completed_time_end = req.get('completed_time_end')
  3982. sort_by = req.get('sort_by', 'created_at')
  3983. sort_order = req.get('sort_order', 'desc')
  3984. # 参数验证
  3985. # 验证分页参数
  3986. if page < 1:
  3987. return jsonify(bad_request_response(
  3988. response_text="页码必须大于0",
  3989. invalid_params=['page']
  3990. )), 400
  3991. if page_size < 1 or page_size > 100:
  3992. return jsonify(bad_request_response(
  3993. response_text="每页大小必须在1-100之间",
  3994. invalid_params=['page_size']
  3995. )), 400
  3996. # 验证任务名称长度
  3997. if task_name and len(task_name) > 100:
  3998. return jsonify(bad_request_response(
  3999. response_text="任务名称搜索关键词最大长度为100字符",
  4000. invalid_params=['task_name']
  4001. )), 400
  4002. # 验证排序参数
  4003. allowed_sort_fields = ['created_at', 'started_at', 'completed_at', 'task_name', 'status']
  4004. if sort_by not in allowed_sort_fields:
  4005. return jsonify(bad_request_response(
  4006. response_text=f"不支持的排序字段: {sort_by},支持的字段: {', '.join(allowed_sort_fields)}",
  4007. invalid_params=['sort_by']
  4008. )), 400
  4009. if sort_order.lower() not in ['asc', 'desc']:
  4010. return jsonify(bad_request_response(
  4011. response_text="排序方向必须是 'asc' 或 'desc'",
  4012. invalid_params=['sort_order']
  4013. )), 400
  4014. # 验证状态筛选
  4015. if status:
  4016. allowed_statuses = ['pending', 'running', 'completed', 'failed', 'cancelled']
  4017. if status not in allowed_statuses:
  4018. return jsonify(bad_request_response(
  4019. response_text=f"不支持的状态值: {status},支持的状态: {', '.join(allowed_statuses)}",
  4020. invalid_params=['status']
  4021. )), 400
  4022. # 调用管理器执行查询
  4023. manager = get_data_pipeline_manager()
  4024. result = manager.query_tasks_advanced(
  4025. page=page,
  4026. page_size=page_size,
  4027. status=status,
  4028. task_name=task_name,
  4029. created_by=created_by,
  4030. db_name=db_name,
  4031. created_time_start=created_time_start,
  4032. created_time_end=created_time_end,
  4033. started_time_start=started_time_start,
  4034. started_time_end=started_time_end,
  4035. completed_time_start=completed_time_start,
  4036. completed_time_end=completed_time_end,
  4037. sort_by=sort_by,
  4038. sort_order=sort_order
  4039. )
  4040. # 格式化任务列表
  4041. formatted_tasks = []
  4042. for task in result['tasks']:
  4043. formatted_tasks.append({
  4044. "task_id": task.get('task_id'),
  4045. "task_name": task.get('task_name'),
  4046. "status": task.get('status'),
  4047. "step_status": task.get('step_status'),
  4048. "created_at": task['created_at'].isoformat() if task.get('created_at') else None,
  4049. "started_at": task['started_at'].isoformat() if task.get('started_at') else None,
  4050. "completed_at": task['completed_at'].isoformat() if task.get('completed_at') else None,
  4051. "created_by": task.get('by_user'),
  4052. "db_name": task.get('db_name'),
  4053. "business_context": task.get('parameters', {}).get('business_context') if task.get('parameters') else None,
  4054. "directory_exists": task.get('directory_exists', True),
  4055. "updated_at": task['updated_at'].isoformat() if task.get('updated_at') else None
  4056. })
  4057. # 构建响应数据
  4058. response_data = {
  4059. "tasks": formatted_tasks,
  4060. "pagination": result['pagination'],
  4061. "filters_applied": {
  4062. k: v for k, v in {
  4063. "status": status,
  4064. "task_name": task_name,
  4065. "created_by": created_by,
  4066. "db_name": db_name,
  4067. "created_time_start": created_time_start,
  4068. "created_time_end": created_time_end,
  4069. "started_time_start": started_time_start,
  4070. "started_time_end": started_time_end,
  4071. "completed_time_start": completed_time_start,
  4072. "completed_time_end": completed_time_end
  4073. }.items() if v
  4074. },
  4075. "sort_applied": {
  4076. "sort_by": sort_by,
  4077. "sort_order": sort_order
  4078. },
  4079. "query_time": result.get('query_time', '0.000s')
  4080. }
  4081. return jsonify(success_response(
  4082. response_text="查询任务列表成功",
  4083. data=response_data
  4084. ))
  4085. except Exception as e:
  4086. logger.error(f"查询数据管道任务列表失败: {str(e)}")
  4087. return jsonify(internal_error_response(
  4088. response_text="查询任务列表失败,请稍后重试"
  4089. )), 500
  4090. @app.route('/api/v0/data_pipeline/tasks/<task_id>/files', methods=['GET'])
  4091. def get_data_pipeline_task_files(task_id):
  4092. """获取任务文件列表(从 citu_app.py 迁移)"""
  4093. try:
  4094. file_manager = get_data_pipeline_file_manager()
  4095. # 获取任务文件
  4096. files = file_manager.get_task_files(task_id)
  4097. directory_info = file_manager.get_directory_info(task_id)
  4098. # 格式化文件信息
  4099. formatted_files = []
  4100. for file_info in files:
  4101. formatted_files.append({
  4102. "file_name": file_info['file_name'],
  4103. "file_type": file_info['file_type'],
  4104. "file_size": file_info['file_size'],
  4105. "file_size_formatted": file_info['file_size_formatted'],
  4106. "created_at": file_info['created_at'].isoformat() if file_info.get('created_at') else None,
  4107. "modified_at": file_info['modified_at'].isoformat() if file_info.get('modified_at') else None,
  4108. "is_readable": file_info['is_readable']
  4109. })
  4110. response_data = {
  4111. "task_id": task_id,
  4112. "files": formatted_files,
  4113. "directory_info": directory_info
  4114. }
  4115. return jsonify(success_response(
  4116. response_text="获取任务文件列表成功",
  4117. data=response_data
  4118. ))
  4119. except Exception as e:
  4120. logger.error(f"获取任务文件列表失败: {str(e)}")
  4121. return jsonify(internal_error_response(
  4122. response_text="获取任务文件列表失败,请稍后重试"
  4123. )), 500
  4124. @app.route('/api/v0/data_pipeline/tasks/<task_id>/files/<file_name>', methods=['GET'])
  4125. def download_data_pipeline_task_file(task_id, file_name):
  4126. """下载任务文件(从 citu_app.py 迁移)"""
  4127. try:
  4128. logger.info(f"开始下载文件: task_id={task_id}, file_name={file_name}")
  4129. # 直接构建文件路径,避免依赖数据库
  4130. from pathlib import Path
  4131. import os
  4132. # 获取项目根目录的绝对路径
  4133. project_root = Path(__file__).parent.absolute()
  4134. task_dir = project_root / "data_pipeline" / "training_data" / task_id
  4135. file_path = task_dir / file_name
  4136. logger.info(f"文件路径: {file_path}")
  4137. # 检查文件是否存在
  4138. if not file_path.exists():
  4139. logger.warning(f"文件不存在: {file_path}")
  4140. return jsonify(not_found_response(
  4141. response_text=f"文件不存在: {file_name}"
  4142. )), 404
  4143. # 检查是否为文件(而不是目录)
  4144. if not file_path.is_file():
  4145. logger.warning(f"路径不是文件: {file_path}")
  4146. return jsonify(bad_request_response(
  4147. response_text=f"路径不是有效文件: {file_name}"
  4148. )), 400
  4149. # 安全检查:确保文件在允许的目录内
  4150. try:
  4151. file_path.resolve().relative_to(task_dir.resolve())
  4152. except ValueError:
  4153. logger.warning(f"文件路径不安全: {file_path}")
  4154. return jsonify(bad_request_response(
  4155. response_text="非法的文件路径"
  4156. )), 400
  4157. # 检查文件是否可读
  4158. if not os.access(file_path, os.R_OK):
  4159. logger.warning(f"文件不可读: {file_path}")
  4160. return jsonify(bad_request_response(
  4161. response_text="文件不可读"
  4162. )), 400
  4163. logger.info(f"开始发送文件: {file_path}")
  4164. return send_file(
  4165. file_path,
  4166. as_attachment=True,
  4167. download_name=file_name
  4168. )
  4169. except Exception as e:
  4170. logger.error(f"下载任务文件失败: task_id={task_id}, file_name={file_name}, 错误: {str(e)}", exc_info=True)
  4171. return jsonify(internal_error_response(
  4172. response_text="下载文件失败,请稍后重试"
  4173. )), 500
  4174. @app.route('/api/v0/data_pipeline/tasks/<task_id>/upload-table-list', methods=['POST'])
  4175. def upload_table_list_file(task_id):
  4176. """
  4177. 上传表清单文件(从 citu_app.py 迁移)
  4178. 表单参数:
  4179. - file: 要上传的表清单文件(multipart/form-data)
  4180. 响应:
  4181. {
  4182. "success": true,
  4183. "code": 200,
  4184. "message": "表清单文件上传成功",
  4185. "data": {
  4186. "task_id": "task_20250701_123456",
  4187. "filename": "table_list.txt",
  4188. "file_size": 1024,
  4189. "file_size_formatted": "1.0 KB"
  4190. }
  4191. }
  4192. """
  4193. try:
  4194. # 验证任务是否存在
  4195. manager = get_data_pipeline_manager()
  4196. task_info = manager.get_task_status(task_id)
  4197. if not task_info:
  4198. return jsonify(not_found_response(
  4199. response_text=f"任务不存在: {task_id}"
  4200. )), 404
  4201. # 检查是否有文件上传
  4202. if 'file' not in request.files:
  4203. return jsonify(bad_request_response(
  4204. response_text="请选择要上传的表清单文件",
  4205. missing_params=['file']
  4206. )), 400
  4207. file = request.files['file']
  4208. # 验证文件名
  4209. if file.filename == '':
  4210. return jsonify(bad_request_response(
  4211. response_text="请选择有效的文件"
  4212. )), 400
  4213. try:
  4214. # 使用文件管理器上传文件
  4215. file_manager = get_data_pipeline_file_manager()
  4216. result = file_manager.upload_table_list_file(task_id, file)
  4217. response_data = {
  4218. "task_id": task_id,
  4219. "filename": result["filename"],
  4220. "file_size": result["file_size"],
  4221. "file_size_formatted": result["file_size_formatted"],
  4222. "upload_time": result["upload_time"].isoformat() if result.get("upload_time") else None
  4223. }
  4224. return jsonify(success_response(
  4225. response_text="表清单文件上传成功",
  4226. data=response_data
  4227. )), 200
  4228. except ValueError as e:
  4229. # 文件验证错误(如文件太大、空文件等)
  4230. return jsonify(bad_request_response(
  4231. response_text=str(e)
  4232. )), 400
  4233. except Exception as e:
  4234. logger.error(f"上传表清单文件失败: {str(e)}")
  4235. return jsonify(internal_error_response(
  4236. response_text="文件上传失败,请稍后重试"
  4237. )), 500
  4238. except Exception as e:
  4239. logger.error(f"处理表清单文件上传请求失败: {str(e)}")
  4240. return jsonify(internal_error_response(
  4241. response_text="处理上传请求失败,请稍后重试"
  4242. )), 500
  4243. @app.route('/api/v0/data_pipeline/tasks/<task_id>/table-list-info', methods=['GET'])
  4244. def get_table_list_info(task_id):
  4245. """
  4246. 获取任务的表清单文件信息(从 citu_app.py 迁移)
  4247. 响应:
  4248. {
  4249. "success": true,
  4250. "code": 200,
  4251. "message": "获取表清单文件信息成功",
  4252. "data": {
  4253. "task_id": "task_20250701_123456",
  4254. "has_file": true,
  4255. "filename": "table_list.txt",
  4256. "file_path": "./data_pipeline/training_data/task_20250701_123456/table_list.txt",
  4257. "file_size": 1024,
  4258. "file_size_formatted": "1.0 KB",
  4259. "uploaded_at": "2025-07-01T12:34:56",
  4260. "table_count": 5,
  4261. "table_names": ["table_name_1", "table_name_2", "table_name_3", "table_name_4", "table_name_5"],
  4262. "is_readable": true
  4263. }
  4264. }
  4265. """
  4266. try:
  4267. file_manager = get_data_pipeline_file_manager()
  4268. # 获取表清单文件信息
  4269. table_list_info = file_manager.get_table_list_file_info(task_id)
  4270. response_data = {
  4271. "task_id": task_id,
  4272. "has_file": table_list_info.get("exists", False),
  4273. **table_list_info
  4274. }
  4275. return jsonify(success_response(
  4276. response_text="获取表清单文件信息成功",
  4277. data=response_data
  4278. ))
  4279. except Exception as e:
  4280. logger.error(f"获取表清单文件信息失败: {str(e)}")
  4281. return jsonify(internal_error_response(
  4282. response_text="获取表清单文件信息失败,请稍后重试"
  4283. )), 500
  4284. @app.route('/api/v0/data_pipeline/tasks/<task_id>/table-list', methods=['POST'])
  4285. def create_table_list_from_names(task_id):
  4286. """
  4287. 通过POST方式提交表名列表并创建table_list.txt文件(从 citu_app.py 迁移)
  4288. 请求体:
  4289. {
  4290. "tables": ["table1", "schema.table2", "table3"]
  4291. }
  4292. 或者:
  4293. {
  4294. "tables": "table1,schema.table2,table3"
  4295. }
  4296. 响应:
  4297. {
  4298. "success": true,
  4299. "code": 200,
  4300. "message": "表清单已成功创建",
  4301. "data": {
  4302. "task_id": "task_20250701_123456",
  4303. "filename": "table_list.txt",
  4304. "table_count": 3,
  4305. "file_size": 45,
  4306. "file_size_formatted": "45 B",
  4307. "created_time": "2025-07-01T12:34:56"
  4308. }
  4309. }
  4310. """
  4311. try:
  4312. # 验证任务是否存在
  4313. manager = get_data_pipeline_manager()
  4314. task_info = manager.get_task_status(task_id)
  4315. if not task_info:
  4316. return jsonify(not_found_response(
  4317. response_text=f"任务不存在: {task_id}"
  4318. )), 404
  4319. # 获取请求数据
  4320. req = request.get_json(force=True)
  4321. tables_param = req.get('tables')
  4322. if not tables_param:
  4323. return jsonify(bad_request_response(
  4324. response_text="缺少必需参数:tables",
  4325. missing_params=['tables']
  4326. )), 400
  4327. # 处理不同格式的表名参数
  4328. try:
  4329. if isinstance(tables_param, str):
  4330. # 逗号分隔的字符串格式
  4331. table_names = [name.strip() for name in tables_param.split(',') if name.strip()]
  4332. elif isinstance(tables_param, list):
  4333. # 数组格式
  4334. table_names = [str(name).strip() for name in tables_param if str(name).strip()]
  4335. else:
  4336. return jsonify(bad_request_response(
  4337. response_text="tables参数格式错误,应为字符串(逗号分隔)或数组"
  4338. )), 400
  4339. if not table_names:
  4340. return jsonify(bad_request_response(
  4341. response_text="表名列表不能为空"
  4342. )), 400
  4343. except Exception as e:
  4344. return jsonify(bad_request_response(
  4345. response_text=f"解析tables参数失败: {str(e)}"
  4346. )), 400
  4347. try:
  4348. # 使用文件管理器创建表清单文件
  4349. file_manager = get_data_pipeline_file_manager()
  4350. result = file_manager.create_table_list_from_names(task_id, table_names)
  4351. response_data = {
  4352. "task_id": task_id,
  4353. "filename": result["filename"],
  4354. "table_count": result["table_count"],
  4355. "unique_table_count": result["unique_table_count"],
  4356. "file_size": result["file_size"],
  4357. "file_size_formatted": result["file_size_formatted"],
  4358. "created_time": result["created_time"].isoformat() if result.get("created_time") else None,
  4359. "original_count": len(table_names) if isinstance(table_names, list) else len(tables_param.split(','))
  4360. }
  4361. return jsonify(success_response(
  4362. response_text=f"表清单已成功创建,包含 {result['table_count']} 个表",
  4363. data=response_data
  4364. )), 200
  4365. except ValueError as e:
  4366. # 表名验证错误(如格式错误、数量限制等)
  4367. return jsonify(bad_request_response(
  4368. response_text=str(e)
  4369. )), 400
  4370. except Exception as e:
  4371. logger.error(f"创建表清单文件失败: {str(e)}")
  4372. return jsonify(internal_error_response(
  4373. response_text="创建表清单文件失败,请稍后重试"
  4374. )), 500
  4375. except Exception as e:
  4376. logger.error(f"处理表清单创建请求失败: {str(e)}")
  4377. return jsonify(internal_error_response(
  4378. response_text="处理请求失败,请稍后重试"
  4379. )), 500
  4380. @app.route('/api/v0/data_pipeline/tasks/<task_id>/files', methods=['POST'])
  4381. def upload_file_to_task(task_id):
  4382. """
  4383. 上传文件到指定任务目录(从 citu_app.py 迁移)
  4384. 表单参数:
  4385. - file: 要上传的文件(multipart/form-data)
  4386. - overwrite_mode: 重名处理模式 (backup, replace, skip),默认为backup
  4387. 支持的文件类型:
  4388. - .ddl: DDL文件
  4389. - .md: Markdown文档
  4390. - .txt: 文本文件
  4391. - .json: JSON文件
  4392. - .sql: SQL文件
  4393. - .csv: CSV文件
  4394. 重名处理模式:
  4395. - backup: 备份原文件(默认)
  4396. - replace: 直接覆盖
  4397. - skip: 跳过上传
  4398. """
  4399. try:
  4400. # 验证任务是否存在
  4401. manager = get_data_pipeline_manager()
  4402. task_info = manager.get_task_status(task_id)
  4403. if not task_info:
  4404. return jsonify(not_found_response(
  4405. response_text=f"任务不存在: {task_id}"
  4406. )), 404
  4407. # 检查是否有文件上传
  4408. if 'file' not in request.files:
  4409. return jsonify(bad_request_response(
  4410. response_text="请选择要上传的文件",
  4411. missing_params=['file']
  4412. )), 400
  4413. file = request.files['file']
  4414. # 验证文件名
  4415. if file.filename == '':
  4416. return jsonify(bad_request_response(
  4417. response_text="请选择有效的文件"
  4418. )), 400
  4419. # 获取重名处理模式
  4420. overwrite_mode = request.form.get('overwrite_mode', 'backup')
  4421. # 验证重名处理模式
  4422. valid_modes = ['backup', 'replace', 'skip']
  4423. if overwrite_mode not in valid_modes:
  4424. return jsonify(bad_request_response(
  4425. response_text=f"无效的overwrite_mode参数: {overwrite_mode},支持的值: {valid_modes}",
  4426. invalid_params=['overwrite_mode']
  4427. )), 400
  4428. try:
  4429. # 使用文件管理器上传文件
  4430. file_manager = get_data_pipeline_file_manager()
  4431. result = file_manager.upload_file_to_task(task_id, file, file.filename, overwrite_mode)
  4432. # 检查是否跳过上传
  4433. if result.get('skipped'):
  4434. return jsonify(success_response(
  4435. response_text=result.get('message', '文件已存在,跳过上传'),
  4436. data=result
  4437. )), 200
  4438. return jsonify(success_response(
  4439. response_text="文件上传成功",
  4440. data=result
  4441. )), 200
  4442. except ValueError as e:
  4443. # 文件验证错误(如文件太大、空文件、不支持的类型等)
  4444. return jsonify(bad_request_response(
  4445. response_text=str(e)
  4446. )), 400
  4447. except Exception as e:
  4448. logger.error(f"上传文件失败: {str(e)}")
  4449. return jsonify(internal_error_response(
  4450. response_text="文件上传失败,请稍后重试"
  4451. )), 500
  4452. except Exception as e:
  4453. logger.error(f"处理文件上传请求失败: {str(e)}")
  4454. return jsonify(internal_error_response(
  4455. response_text="处理上传请求失败,请稍后重试"
  4456. )), 500
  4457. # 任务目录删除功能(从 citu_app.py 迁移)
  4458. import shutil
  4459. from pathlib import Path
  4460. import psycopg2
  4461. from app_config import PGVECTOR_CONFIG
  4462. def delete_task_directory_simple(task_id, delete_database_records=False):
  4463. """
  4464. 简单的任务目录删除功能(从 citu_app.py 迁移)
  4465. - 删除 data_pipeline/training_data/{task_id} 目录
  4466. - 更新数据库中的 directory_exists 字段
  4467. - 可选:删除数据库记录
  4468. """
  4469. try:
  4470. # 1. 删除目录
  4471. project_root = Path(__file__).parent.absolute()
  4472. task_dir = project_root / "data_pipeline" / "training_data" / task_id
  4473. deleted_files_count = 0
  4474. deleted_size = 0
  4475. if task_dir.exists():
  4476. # 计算删除前的统计信息
  4477. for file_path in task_dir.rglob('*'):
  4478. if file_path.is_file():
  4479. deleted_files_count += 1
  4480. deleted_size += file_path.stat().st_size
  4481. # 删除目录
  4482. shutil.rmtree(task_dir)
  4483. directory_deleted = True
  4484. operation_message = "目录删除成功"
  4485. else:
  4486. directory_deleted = False
  4487. operation_message = "目录不存在,无需删除"
  4488. # 2. 更新数据库
  4489. database_records_deleted = False
  4490. try:
  4491. conn = psycopg2.connect(**PGVECTOR_CONFIG)
  4492. cur = conn.cursor()
  4493. if delete_database_records:
  4494. # 删除任务步骤记录
  4495. cur.execute("DELETE FROM data_pipeline_task_steps WHERE task_id = %s", (task_id,))
  4496. # 删除任务主记录
  4497. cur.execute("DELETE FROM data_pipeline_tasks WHERE task_id = %s", (task_id,))
  4498. database_records_deleted = True
  4499. else:
  4500. # 只更新目录状态
  4501. cur.execute("""
  4502. UPDATE data_pipeline_tasks
  4503. SET directory_exists = FALSE, updated_at = CURRENT_TIMESTAMP
  4504. WHERE task_id = %s
  4505. """, (task_id,))
  4506. conn.commit()
  4507. cur.close()
  4508. conn.close()
  4509. except Exception as db_error:
  4510. logger.error(f"数据库操作失败: {db_error}")
  4511. # 数据库失败不影响文件删除的结果
  4512. # 3. 格式化文件大小
  4513. def format_size(size_bytes):
  4514. if size_bytes < 1024:
  4515. return f"{size_bytes} B"
  4516. elif size_bytes < 1024**2:
  4517. return f"{size_bytes/1024:.1f} KB"
  4518. elif size_bytes < 1024**3:
  4519. return f"{size_bytes/(1024**2):.1f} MB"
  4520. else:
  4521. return f"{size_bytes/(1024**3):.1f} GB"
  4522. return {
  4523. "success": True,
  4524. "task_id": task_id,
  4525. "directory_deleted": directory_deleted,
  4526. "database_records_deleted": database_records_deleted,
  4527. "deleted_files_count": deleted_files_count,
  4528. "deleted_size": format_size(deleted_size),
  4529. "deleted_at": datetime.now().isoformat(),
  4530. "operation_message": operation_message # 新增:具体的操作消息
  4531. }
  4532. except Exception as e:
  4533. logger.error(f"删除任务目录失败: {task_id}, 错误: {str(e)}")
  4534. return {
  4535. "success": False,
  4536. "task_id": task_id,
  4537. "error": str(e),
  4538. "error_code": "DELETE_FAILED",
  4539. "operation_message": f"删除操作失败: {str(e)}" # 新增:失败消息
  4540. }
  4541. @app.route('/api/v0/data_pipeline/tasks', methods=['DELETE'])
  4542. def delete_tasks():
  4543. """删除任务目录(支持单个和批量)(从 citu_app.py 迁移)"""
  4544. try:
  4545. # 智能获取参数:支持JSON body和URL查询参数两种方式
  4546. def get_request_parameter(param_name, array_param_name=None):
  4547. """从JSON body或URL查询参数中获取参数值"""
  4548. # 1. 优先从JSON body获取
  4549. if request.is_json:
  4550. try:
  4551. json_data = request.get_json()
  4552. if json_data and param_name in json_data:
  4553. return json_data[param_name]
  4554. except:
  4555. pass
  4556. # 2. 从URL查询参数获取
  4557. if param_name in request.args:
  4558. value = request.args.get(param_name)
  4559. # 处理布尔值
  4560. if value.lower() in ('true', '1', 'yes'):
  4561. return True
  4562. elif value.lower() in ('false', '0', 'no'):
  4563. return False
  4564. return value
  4565. # 3. 处理数组参数(如 task_ids[])
  4566. if array_param_name and array_param_name in request.args:
  4567. return request.args.getlist(array_param_name)
  4568. return None
  4569. # 获取参数
  4570. task_ids = get_request_parameter('task_ids', 'task_ids[]')
  4571. confirm = get_request_parameter('confirm')
  4572. if not task_ids:
  4573. return jsonify(bad_request_response(
  4574. response_text="缺少必需参数: task_ids",
  4575. missing_params=['task_ids']
  4576. )), 400
  4577. if not confirm:
  4578. return jsonify(bad_request_response(
  4579. response_text="缺少必需参数: confirm",
  4580. missing_params=['confirm']
  4581. )), 400
  4582. if confirm != True:
  4583. return jsonify(bad_request_response(
  4584. response_text="confirm参数必须为true以确认删除操作"
  4585. )), 400
  4586. if not isinstance(task_ids, list) or len(task_ids) == 0:
  4587. return jsonify(bad_request_response(
  4588. response_text="task_ids必须是非空的任务ID列表"
  4589. )), 400
  4590. # 获取可选参数
  4591. delete_database_records = get_request_parameter('delete_database_records') or False
  4592. continue_on_error = get_request_parameter('continue_on_error')
  4593. if continue_on_error is None:
  4594. continue_on_error = True
  4595. # 执行批量删除操作
  4596. deleted_tasks = []
  4597. failed_tasks = []
  4598. total_size_freed = 0
  4599. for task_id in task_ids:
  4600. result = delete_task_directory_simple(task_id, delete_database_records)
  4601. if result["success"]:
  4602. deleted_tasks.append(result)
  4603. # 累计释放的空间大小(这里简化处理,实际应该解析size字符串)
  4604. else:
  4605. failed_tasks.append({
  4606. "task_id": task_id,
  4607. "error": result["error"],
  4608. "error_code": result.get("error_code", "UNKNOWN")
  4609. })
  4610. if not continue_on_error:
  4611. break
  4612. # 构建响应
  4613. summary = {
  4614. "total_requested": len(task_ids),
  4615. "successfully_deleted": len(deleted_tasks),
  4616. "failed": len(failed_tasks)
  4617. }
  4618. batch_result = {
  4619. "deleted_tasks": deleted_tasks,
  4620. "failed_tasks": failed_tasks,
  4621. "summary": summary,
  4622. "deleted_at": datetime.now().isoformat()
  4623. }
  4624. # 构建智能响应消息
  4625. if len(task_ids) == 1:
  4626. # 单个删除:使用具体的操作消息
  4627. if summary["failed"] == 0:
  4628. # 从deleted_tasks中获取具体的操作消息
  4629. operation_msg = deleted_tasks[0].get('operation_message', '任务处理完成')
  4630. message = operation_msg
  4631. else:
  4632. # 从failed_tasks中获取错误消息
  4633. error_msg = failed_tasks[0].get('error', '删除失败')
  4634. message = f"任务删除失败: {error_msg}"
  4635. else:
  4636. # 批量删除:统计各种操作结果
  4637. directory_deleted_count = sum(1 for task in deleted_tasks if task.get('directory_deleted', False))
  4638. directory_not_exist_count = sum(1 for task in deleted_tasks if not task.get('directory_deleted', False))
  4639. if summary["failed"] == 0:
  4640. # 全部成功
  4641. if directory_deleted_count > 0 and directory_not_exist_count > 0:
  4642. message = f"批量操作完成:{directory_deleted_count}个目录已删除,{directory_not_exist_count}个目录不存在"
  4643. elif directory_deleted_count > 0:
  4644. message = f"批量删除完成:成功删除{directory_deleted_count}个目录"
  4645. elif directory_not_exist_count > 0:
  4646. message = f"批量操作完成:{directory_not_exist_count}个目录不存在,无需删除"
  4647. else:
  4648. message = "批量操作完成"
  4649. elif summary["successfully_deleted"] == 0:
  4650. message = f"批量删除失败:{summary['failed']}个任务处理失败"
  4651. else:
  4652. message = f"批量删除部分完成:成功{summary['successfully_deleted']}个,失败{summary['failed']}个"
  4653. return jsonify(success_response(
  4654. response_text=message,
  4655. data=batch_result
  4656. )), 200
  4657. except Exception as e:
  4658. logger.error(f"删除任务失败: 错误: {str(e)}")
  4659. return jsonify(internal_error_response(
  4660. response_text="删除任务失败,请稍后重试"
  4661. )), 500
  4662. @app.route('/api/v0/data_pipeline/tasks/<task_id>/logs/query', methods=['POST'])
  4663. def query_data_pipeline_task_logs(task_id):
  4664. """
  4665. 高级查询数据管道任务日志(从 citu_app.py 迁移)
  4666. 支持复杂筛选、排序、分页功能
  4667. 请求体:
  4668. {
  4669. "page": 1, // 页码,必须大于0,默认1
  4670. "page_size": 50, // 每页大小,1-500之间,默认50
  4671. "level": "ERROR", // 可选,日志级别筛选:"DEBUG"|"INFO"|"WARNING"|"ERROR"|"CRITICAL"
  4672. "start_time": "2025-01-01 00:00:00", // 可选,开始时间范围 (YYYY-MM-DD HH:MM:SS)
  4673. "end_time": "2025-01-02 23:59:59", // 可选,结束时间范围 (YYYY-MM-DD HH:MM:SS)
  4674. "keyword": "failed", // 可选,关键字搜索(消息内容模糊匹配)
  4675. "logger_name": "DDLGenerator", // 可选,日志记录器名称精确匹配
  4676. "step_name": "ddl_generation", // 可选,执行步骤名称精确匹配
  4677. "sort_by": "timestamp", // 可选,排序字段:"timestamp"|"level"|"logger"|"step"|"line_number",默认"timestamp"
  4678. "sort_order": "desc" // 可选,排序方向:"asc"|"desc",默认"desc"
  4679. }
  4680. """
  4681. try:
  4682. # 验证任务是否存在
  4683. manager = get_data_pipeline_manager()
  4684. task_info = manager.get_task_status(task_id)
  4685. if not task_info:
  4686. return jsonify(not_found_response(
  4687. response_text=f"任务不存在: {task_id}"
  4688. )), 404
  4689. # 解析请求数据
  4690. request_data = request.get_json() or {}
  4691. # 参数验证
  4692. def _is_valid_time_format(time_str):
  4693. """验证时间格式是否有效"""
  4694. if not time_str:
  4695. return True
  4696. # 支持的时间格式
  4697. time_formats = [
  4698. '%Y-%m-%d %H:%M:%S', # 2025-01-01 00:00:00
  4699. '%Y-%m-%d', # 2025-01-01
  4700. '%Y-%m-%dT%H:%M:%S', # 2025-01-01T00:00:00
  4701. '%Y-%m-%dT%H:%M:%S.%f', # 2025-01-01T00:00:00.123456
  4702. ]
  4703. for fmt in time_formats:
  4704. try:
  4705. from datetime import datetime
  4706. datetime.strptime(time_str, fmt)
  4707. return True
  4708. except ValueError:
  4709. continue
  4710. return False
  4711. # 提取和验证参数
  4712. page = request_data.get('page', 1)
  4713. page_size = request_data.get('page_size', 50)
  4714. level = request_data.get('level')
  4715. start_time = request_data.get('start_time')
  4716. end_time = request_data.get('end_time')
  4717. keyword = request_data.get('keyword')
  4718. logger_name = request_data.get('logger_name')
  4719. step_name = request_data.get('step_name')
  4720. sort_by = request_data.get('sort_by', 'timestamp')
  4721. sort_order = request_data.get('sort_order', 'desc')
  4722. # 参数验证
  4723. if not isinstance(page, int) or page < 1:
  4724. return jsonify(bad_request_response(
  4725. response_text="页码必须是大于0的整数"
  4726. )), 400
  4727. if not isinstance(page_size, int) or page_size < 1 or page_size > 500:
  4728. return jsonify(bad_request_response(
  4729. response_text="每页大小必须是1-500之间的整数"
  4730. )), 400
  4731. # 验证日志级别
  4732. if level and level.upper() not in ['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL']:
  4733. return jsonify(bad_request_response(
  4734. response_text="日志级别必须是DEBUG、INFO、WARNING、ERROR、CRITICAL之一"
  4735. )), 400
  4736. # 验证时间格式
  4737. if not _is_valid_time_format(start_time):
  4738. return jsonify(bad_request_response(
  4739. response_text="开始时间格式无效,支持格式:YYYY-MM-DD HH:MM:SS 或 YYYY-MM-DD"
  4740. )), 400
  4741. if not _is_valid_time_format(end_time):
  4742. return jsonify(bad_request_response(
  4743. response_text="结束时间格式无效,支持格式:YYYY-MM-DD HH:MM:SS 或 YYYY-MM-DD"
  4744. )), 400
  4745. # 验证关键字长度
  4746. if keyword and len(keyword) > 200:
  4747. return jsonify(bad_request_response(
  4748. response_text="关键字长度不能超过200个字符"
  4749. )), 400
  4750. # 验证排序字段
  4751. allowed_sort_fields = ['timestamp', 'level', 'logger', 'step', 'line_number']
  4752. if sort_by not in allowed_sort_fields:
  4753. return jsonify(bad_request_response(
  4754. response_text=f"排序字段必须是以下之一: {', '.join(allowed_sort_fields)}"
  4755. )), 400
  4756. # 验证排序方向
  4757. if sort_order.lower() not in ['asc', 'desc']:
  4758. return jsonify(bad_request_response(
  4759. response_text="排序方向必须是asc或desc"
  4760. )), 400
  4761. # 创建工作流执行器并查询日志
  4762. from data_pipeline.api.simple_workflow import SimpleWorkflowExecutor
  4763. executor = SimpleWorkflowExecutor(task_id)
  4764. try:
  4765. result = executor.query_logs_advanced(
  4766. page=page,
  4767. page_size=page_size,
  4768. level=level,
  4769. start_time=start_time,
  4770. end_time=end_time,
  4771. keyword=keyword,
  4772. logger_name=logger_name,
  4773. step_name=step_name,
  4774. sort_by=sort_by,
  4775. sort_order=sort_order
  4776. )
  4777. return jsonify(success_response(
  4778. response_text="查询任务日志成功",
  4779. data=result
  4780. ))
  4781. finally:
  4782. executor.cleanup()
  4783. except Exception as e:
  4784. logger.error(f"查询数据管道任务日志失败: {str(e)}")
  4785. return jsonify(internal_error_response(
  4786. response_text="查询任务日志失败,请稍后重试"
  4787. )), 500
  4788. # ==================== 启动逻辑 ====================
  4789. def signal_handler(signum, frame):
  4790. """信号处理器,优雅退出"""
  4791. logger.info(f"接收到信号 {signum},准备退出...")
  4792. cleanup_resources()
  4793. sys.exit(0)
  4794. @app.route('/api/v0/data_pipeline/vector/backup', methods=['POST'])
  4795. def backup_pgvector_tables():
  4796. """专用的pgvector表备份API - 纯备份功能,不执行truncate操作
  4797. 注意:truncate功能已移除,如需清空表请使用 /api/v0/data_pipeline/vector/restore 的 truncate_before_restore 参数
  4798. """
  4799. try:
  4800. # 支持空参数调用 {}
  4801. req = request.get_json(force=True) if request.is_json else {}
  4802. # 解析参数(全部可选)
  4803. task_id = req.get('task_id')
  4804. db_connection = req.get('db_connection')
  4805. # truncate_vector_tables = req.get('truncate_vector_tables', False) # 已注释:备份API不应执行truncate操作
  4806. backup_vector_tables = req.get('backup_vector_tables', True)
  4807. # 参数验证
  4808. if task_id and not re.match(r'^[a-zA-Z0-9_]+$', task_id):
  4809. return jsonify(bad_request_response(
  4810. "无效的task_id格式,只能包含字母、数字和下划线"
  4811. )), 400
  4812. # 确定备份目录
  4813. if task_id:
  4814. # 验证task_id目录是否存在
  4815. task_dir = Path(f"data_pipeline/training_data/{task_id}")
  4816. if not task_dir.exists():
  4817. return jsonify(not_found_response(
  4818. f"指定的任务目录不存在: {task_id}"
  4819. )), 404
  4820. backup_base_dir = str(task_dir)
  4821. else:
  4822. # 使用training_data根目录(支持空参数调用)
  4823. backup_base_dir = "data_pipeline/training_data"
  4824. # 直接使用现有的VectorTableManager
  4825. from data_pipeline.trainer.vector_table_manager import VectorTableManager
  4826. # 临时修改数据库连接配置(如果提供了自定义连接)
  4827. original_config = None
  4828. if db_connection:
  4829. from data_pipeline.config import SCHEMA_TOOLS_CONFIG
  4830. original_config = SCHEMA_TOOLS_CONFIG.get("default_db_connection")
  4831. SCHEMA_TOOLS_CONFIG["default_db_connection"] = db_connection
  4832. try:
  4833. # 使用现有的成熟管理器
  4834. vector_manager = VectorTableManager(
  4835. task_output_dir=backup_base_dir,
  4836. task_id=task_id or "vector_bak"
  4837. )
  4838. # 执行备份(纯备份操作,不执行truncate)
  4839. result = vector_manager.execute_vector_management(
  4840. backup=backup_vector_tables,
  4841. truncate=False # 强制设为False,备份API不执行truncate操作
  4842. )
  4843. # 使用 common/result.py 的标准格式
  4844. return jsonify(success_response(
  4845. response_text="Vector表备份完成",
  4846. data=result
  4847. )), 200
  4848. finally:
  4849. # 恢复原始配置
  4850. if original_config is not None:
  4851. SCHEMA_TOOLS_CONFIG["default_db_connection"] = original_config
  4852. except Exception as e:
  4853. logger.error(f"Vector表备份失败: {str(e)}")
  4854. return jsonify(internal_error_response(
  4855. "Vector表备份失败,请稍后重试"
  4856. )), 500
  4857. # ====================================================================
  4858. # Vector表恢复备份API
  4859. # ====================================================================
  4860. @app.route('/api/v0/data_pipeline/vector/restore/list', methods=['GET'])
  4861. def list_vector_backups():
  4862. """列出可用的vector表备份文件"""
  4863. try:
  4864. # 解析查询参数
  4865. global_only = request.args.get('global_only', 'false').lower() == 'true'
  4866. task_id = request.args.get('task_id')
  4867. # 参数验证
  4868. if task_id and not re.match(r'^[a-zA-Z0-9_]+$', task_id):
  4869. return jsonify(bad_request_response(
  4870. "无效的task_id格式,只能包含字母、数字和下划线"
  4871. )), 400
  4872. # 使用VectorRestoreManager扫描
  4873. from data_pipeline.api.vector_restore_manager import VectorRestoreManager
  4874. restore_manager = VectorRestoreManager()
  4875. result = restore_manager.scan_backup_files(global_only, task_id)
  4876. # 构建响应文本
  4877. total_locations = result['summary']['total_locations']
  4878. total_backup_sets = result['summary']['total_backup_sets']
  4879. if total_backup_sets == 0:
  4880. response_text = "未找到任何可用的备份文件"
  4881. else:
  4882. response_text = f"成功扫描到 {total_locations} 个备份位置,共 {total_backup_sets} 个备份集"
  4883. # 返回标准格式
  4884. return jsonify(success_response(
  4885. response_text=response_text,
  4886. data=result
  4887. )), 200
  4888. except Exception as e:
  4889. logger.error(f"扫描备份文件失败: {str(e)}")
  4890. return jsonify(internal_error_response(
  4891. "扫描备份文件失败,请稍后重试"
  4892. )), 500
  4893. @app.route('/api/v0/data_pipeline/vector/restore', methods=['POST'])
  4894. def restore_vector_tables():
  4895. """恢复vector表数据"""
  4896. try:
  4897. # 解析请求参数
  4898. req = request.get_json(force=True) if request.is_json else {}
  4899. # 必需参数验证
  4900. backup_path = req.get('backup_path')
  4901. timestamp = req.get('timestamp')
  4902. if not backup_path or not timestamp:
  4903. missing_params = []
  4904. if not backup_path:
  4905. missing_params.append('backup_path')
  4906. if not timestamp:
  4907. missing_params.append('timestamp')
  4908. return jsonify(bad_request_response(
  4909. f"缺少必需参数: {', '.join(missing_params)}",
  4910. missing_params
  4911. )), 400
  4912. # 可选参数
  4913. tables = req.get('tables')
  4914. db_connection = req.get('db_connection')
  4915. truncate_before_restore = req.get('truncate_before_restore', False)
  4916. # 参数验证
  4917. if tables is not None and not isinstance(tables, list):
  4918. return jsonify(bad_request_response(
  4919. "tables参数必须是数组格式"
  4920. )), 400
  4921. # 验证时间戳格式
  4922. if not re.match(r'^\d{8}_\d{6}$', timestamp):
  4923. return jsonify(bad_request_response(
  4924. "无效的timestamp格式,应为YYYYMMDD_HHMMSS"
  4925. )), 400
  4926. # 执行恢复
  4927. from data_pipeline.api.vector_restore_manager import VectorRestoreManager
  4928. restore_manager = VectorRestoreManager()
  4929. result = restore_manager.restore_from_backup(
  4930. backup_path=backup_path,
  4931. timestamp=timestamp,
  4932. tables=tables,
  4933. db_connection=db_connection,
  4934. truncate_before_restore=truncate_before_restore
  4935. )
  4936. # 构建响应文本
  4937. if result.get("errors"):
  4938. response_text = "Vector表恢复部分完成,部分表恢复失败"
  4939. else:
  4940. response_text = "Vector表恢复完成"
  4941. # 返回结果
  4942. return jsonify(success_response(
  4943. response_text=response_text,
  4944. data=result
  4945. )), 200
  4946. except FileNotFoundError as e:
  4947. return jsonify(not_found_response(str(e))), 404
  4948. except ValueError as e:
  4949. return jsonify(bad_request_response(str(e))), 400
  4950. except Exception as e:
  4951. logger.error(f"Vector表恢复失败: {str(e)}")
  4952. return jsonify(internal_error_response(
  4953. "Vector表恢复失败,请稍后重试"
  4954. )), 500
  4955. if __name__ == '__main__':
  4956. # 注册信号处理器
  4957. signal.signal(signal.SIGINT, signal_handler)
  4958. signal.signal(signal.SIGTERM, signal_handler)
  4959. logger.info("🚀 启动统一API服务...")
  4960. logger.info("📍 服务地址: http://localhost:8084")
  4961. logger.info("🔗 健康检查: http://localhost:8084/health")
  4962. logger.info("📘 React Agent API: http://localhost:8084/api/v0/ask_react_agent")
  4963. logger.info("📘 LangGraph Agent API: http://localhost:8084/api/v0/ask_agent")
  4964. logger.info("💾 Vector备份API: http://localhost:8084/api/v0/data_pipeline/vector/backup")
  4965. logger.info("📥 Vector恢复API: http://localhost:8084/api/v0/data_pipeline/vector/restore")
  4966. logger.info("📋 备份列表API: http://localhost:8084/api/v0/data_pipeline/vector/restore/list")
  4967. # 并发问题解决方案:已确认WsgiToAsgi导致阻塞,使用原生Flask解决
  4968. USE_WSGI_TO_ASGI = False # 使用原生Flask并发,解决状态API阻塞问题
  4969. if USE_WSGI_TO_ASGI:
  4970. try:
  4971. # 方案A:使用ASGI模式启动(可能有并发限制)
  4972. import uvicorn
  4973. from asgiref.wsgi import WsgiToAsgi
  4974. logger.info("🚀 使用ASGI模式启动异步Flask应用...")
  4975. logger.info(" 这将解决事件循环冲突问题,支持LangGraph异步checkpoint保存")
  4976. # 将Flask WSGI应用转换为ASGI应用
  4977. asgi_app = WsgiToAsgi(app)
  4978. # 使用uvicorn启动ASGI应用,增加并发配置
  4979. uvicorn.run(
  4980. asgi_app,
  4981. host="0.0.0.0",
  4982. port=8084,
  4983. log_level="info",
  4984. access_log=True,
  4985. workers=1, # 单进程多协程
  4986. loop="asyncio", # 使用asyncio事件循环
  4987. limit_concurrency=100, # 增加并发限制
  4988. limit_max_requests=1000 # 增加请求限制
  4989. )
  4990. except ImportError as e:
  4991. # 如果缺少ASGI依赖,fallback到传统Flask模式
  4992. logger.warning("⚠️ ASGI依赖缺失,使用传统Flask模式启动")
  4993. logger.warning(" 建议安装: pip install uvicorn asgiref")
  4994. logger.warning(" 传统模式可能存在异步事件循环冲突问题")
  4995. # 启动标准Flask应用(支持异步路由)
  4996. app.run(host="0.0.0.0", port=8084, debug=False, threaded=True)
  4997. else:
  4998. # 方案B:使用原生Flask并发(可能解决WsgiToAsgi并发问题)
  4999. logger.info("🚀 使用原生Flask并发模式启动...")
  5000. logger.info(" 绕过WsgiToAsgi,测试是否解决并发阻塞问题")
  5001. logger.info(" 使用Flask内置多线程并发支持")
  5002. # 启动标准Flask应用(支持异步路由)
  5003. app.run(host="0.0.0.0", port=8084, debug=False, threaded=True)