unified_api.py 170 KB

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