unified_api.py 166 KB

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