unified_api.py 139 KB

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