operate.py 224 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793
  1. from __future__ import annotations
  2. from functools import partial
  3. from pathlib import Path
  4. import asyncio
  5. import json
  6. import re
  7. import json_repair
  8. from typing import Any, AsyncIterator, overload, Literal
  9. from collections import Counter, defaultdict
  10. from lightrag.exceptions import (
  11. PipelineCancelledException,
  12. )
  13. from lightrag.utils import (
  14. logger,
  15. compute_mdhash_id,
  16. Tokenizer,
  17. is_float_regex,
  18. sanitize_and_normalize_extracted_text,
  19. pack_user_ass_to_openai_messages,
  20. split_string_by_multi_markers,
  21. truncate_list_by_token_size,
  22. compute_args_hash,
  23. handle_cache,
  24. save_to_cache,
  25. CacheData,
  26. use_llm_func_with_cache,
  27. get_env_value,
  28. get_llm_cache_identity,
  29. serialize_llm_cache_identity,
  30. update_chunk_cache_list,
  31. remove_think_tags,
  32. pick_by_weighted_polling,
  33. pick_by_vector_similarity,
  34. process_chunks_unified,
  35. safe_vdb_operation_with_exception,
  36. create_prefixed_exception,
  37. fix_tuple_delimiter_corruption,
  38. convert_to_user_format,
  39. generate_reference_list_from_chunks,
  40. apply_source_ids_limit,
  41. merge_source_ids,
  42. make_relation_chunk_key,
  43. _cooperative_yield,
  44. performance_timing_log,
  45. )
  46. from lightrag.base import (
  47. BaseGraphStorage,
  48. BaseKVStorage,
  49. BaseVectorStorage,
  50. TextChunkSchema,
  51. QueryParam,
  52. QueryResult,
  53. QueryContextResult,
  54. )
  55. from lightrag.chunk_schema import strip_internal_multimodal_markup_for_extraction
  56. from lightrag.prompt import PROMPTS, resolve_entity_extraction_prompt_profile
  57. from lightrag.constants import (
  58. GRAPH_FIELD_SEP,
  59. DEFAULT_MAX_ENTITY_TOKENS,
  60. DEFAULT_MAX_EXTRACT_INPUT_TOKENS,
  61. DEFAULT_MAX_RELATION_TOKENS,
  62. DEFAULT_MAX_TOTAL_TOKENS,
  63. DEFAULT_RELATED_CHUNK_NUMBER,
  64. DEFAULT_KG_CHUNK_PICK_METHOD,
  65. DEFAULT_SUMMARY_LANGUAGE,
  66. SOURCE_IDS_LIMIT_METHOD_KEEP,
  67. SOURCE_IDS_LIMIT_METHOD_FIFO,
  68. DEFAULT_FILE_PATH_MORE_PLACEHOLDER,
  69. DEFAULT_MAX_FILE_PATHS,
  70. DEFAULT_ENTITY_NAME_MAX_LENGTH,
  71. )
  72. from lightrag.kg.shared_storage import get_storage_keyed_lock
  73. import time
  74. from dotenv import load_dotenv
  75. # use the .env that is inside the current folder
  76. # allows to use different .env file for each lightrag instance
  77. # the OS environment variables take precedence over the .env file
  78. load_dotenv(dotenv_path=Path(__file__).resolve().parent / ".env", override=False)
  79. def _get_relationship_vdb_timeout_seconds(global_config: dict[str, Any]) -> float:
  80. """Derive a defensive timeout for relation VDB upserts.
  81. Rationale:
  82. - `knowledge_graph_inst.upsert_edge()` for the default NetworkX storage is in-memory and fast.
  83. - `relationships_vdb.upsert()` performs embedding calls and remote I/O, which is the more likely
  84. point of silent stalls during relation merge.
  85. """
  86. configured = global_config.get("default_embedding_timeout")
  87. try:
  88. base_timeout = float(configured)
  89. except (TypeError, ValueError):
  90. base_timeout = 30.0
  91. # Keep a fixed lower bound high enough to avoid false positives on slow providers.
  92. return max(base_timeout * 3, 120.0)
  93. def _format_relation_edge_label(edge_key: tuple[str, str] | list[str]) -> str:
  94. if isinstance(edge_key, tuple):
  95. left, right = edge_key
  96. else:
  97. left, right = edge_key[0], edge_key[1]
  98. return f"{left}->{right}"
  99. def _truncate_entity_identifier(
  100. identifier: str, limit: int, chunk_key: str, identifier_role: str
  101. ) -> str:
  102. """Truncate entity identifiers that exceed the configured length limit."""
  103. if len(identifier) <= limit:
  104. return identifier
  105. display_value = identifier[:limit]
  106. preview = identifier[:20] # Show first 20 characters as preview
  107. logger.warning(
  108. "%s: %s len %d > %d chars (Name: '%s...')",
  109. chunk_key,
  110. identifier_role,
  111. len(identifier),
  112. limit,
  113. preview,
  114. )
  115. return display_value
  116. def _truncate_vdb_content(content: str, global_config: dict, content_label: str) -> str:
  117. """Clamp vector-store payload size to stay under embedding limits."""
  118. if not content:
  119. return content
  120. embedding_token_limit = global_config.get("embedding_token_limit")
  121. tokenizer: Tokenizer | None = global_config.get("tokenizer")
  122. if embedding_token_limit is None or tokenizer is None:
  123. return content
  124. threshold = int(embedding_token_limit)
  125. if threshold <= 0:
  126. return content
  127. tokens = tokenizer.encode(content)
  128. if len(tokens) <= threshold:
  129. return content
  130. # Leave headroom because tokenizer behavior can differ slightly from the provider.
  131. effective_limit = max(threshold - min(256, max(32, threshold // 16)), 1)
  132. truncated_content = tokenizer.decode(tokens[:effective_limit])
  133. logger.warning(
  134. "%s VDB content truncated from %d to %d tokens (embedding limit: %d)",
  135. content_label,
  136. len(tokens),
  137. effective_limit,
  138. threshold,
  139. )
  140. return truncated_content
  141. _MM_DISPLAY_NAME_PATTERN = re.compile(
  142. r"^\[(?:Image|Table|Equation) Name\](.+)$",
  143. flags=re.MULTILINE,
  144. )
  145. def _parse_mm_display_name(content: str, fallback: str) -> str:
  146. """Return the friendly name embedded in a multimodal chunk.
  147. Matches the leading ``[Image Name]…`` / ``[Table Name]…`` /
  148. ``[Equation Name]…`` segment produced by
  149. ``LightRAG._build_mm_chunks_from_sidecars`` — the producer-side
  150. contract is documented in that function's ``_render`` helper. Falls
  151. back to the sidecar id when the segment is missing or empty so
  152. callers never end up with a blank label.
  153. """
  154. if content:
  155. match = _MM_DISPLAY_NAME_PATTERN.search(content)
  156. if match:
  157. candidate = match.group(1).strip()
  158. if candidate:
  159. return candidate
  160. return fallback
  161. async def _handle_entity_relation_summary(
  162. description_type: str,
  163. entity_or_relation_name: str,
  164. description_list: list[str],
  165. separator: str,
  166. global_config: dict,
  167. llm_response_cache: BaseKVStorage | None = None,
  168. ) -> tuple[str, bool]:
  169. """Handle entity relation description summary using map-reduce approach.
  170. This function summarizes a list of descriptions using a map-reduce strategy:
  171. 1. If total tokens < summary_context_size and len(description_list) < force_llm_summary_on_merge, no need to summarize
  172. 2. If total tokens < summary_max_tokens, summarize with LLM directly
  173. 3. Otherwise, split descriptions into chunks that fit within token limits
  174. 4. Summarize each chunk, then recursively process the summaries
  175. 5. Continue until we get a final summary within token limits or num of descriptions is less than force_llm_summary_on_merge
  176. Args:
  177. entity_or_relation_name: Name of the entity or relation being summarized
  178. description_list: List of description strings to summarize
  179. global_config: Global configuration containing tokenizer and limits
  180. llm_response_cache: Optional cache for LLM responses
  181. Returns:
  182. Tuple of (final_summarized_description_string, llm_was_used_boolean)
  183. """
  184. # Handle empty input
  185. if not description_list:
  186. return "", False
  187. # If only one description, return it directly (no need for LLM call)
  188. if len(description_list) == 1:
  189. return description_list[0], False
  190. # Get configuration
  191. tokenizer: Tokenizer = global_config["tokenizer"]
  192. summary_context_size = global_config["summary_context_size"]
  193. summary_max_tokens = global_config["summary_max_tokens"]
  194. force_llm_summary_on_merge = global_config["force_llm_summary_on_merge"]
  195. current_list = description_list[:] # Copy the list to avoid modifying original
  196. llm_was_used = False # Track whether LLM was used during the entire process
  197. # Iterative map-reduce process
  198. while True:
  199. # Calculate total tokens in current list while periodically yielding so
  200. # a large merge does not monopolize the event loop in single-worker mode.
  201. total_tokens = 0
  202. for i, desc in enumerate(current_list, start=1):
  203. total_tokens += len(tokenizer.encode(desc))
  204. await _cooperative_yield(i, every=32)
  205. # If total length is within limits, perform final summarization
  206. if total_tokens <= summary_context_size or len(current_list) <= 2:
  207. if (
  208. len(current_list) < force_llm_summary_on_merge
  209. and total_tokens < summary_max_tokens
  210. ):
  211. # no LLM needed, just join the descriptions
  212. final_description = separator.join(current_list)
  213. return final_description if final_description else "", llm_was_used
  214. else:
  215. if total_tokens > summary_context_size and len(current_list) <= 2:
  216. logger.warning(
  217. f"Summarizing {entity_or_relation_name}: Oversize description found"
  218. )
  219. # Final summarization of remaining descriptions - LLM will be used
  220. final_summary = await _summarize_descriptions(
  221. description_type,
  222. entity_or_relation_name,
  223. current_list,
  224. global_config,
  225. llm_response_cache,
  226. )
  227. return final_summary, True # LLM was used for final summarization
  228. # Need to split into chunks - Map phase
  229. # Ensure each chunk has minimum 2 descriptions to guarantee progress
  230. chunks = []
  231. current_chunk = []
  232. current_tokens = 0
  233. # Currently least 3 descriptions in current_list
  234. for i, desc in enumerate(current_list, start=1):
  235. desc_tokens = len(tokenizer.encode(desc))
  236. await _cooperative_yield(i, every=32)
  237. # If adding current description would exceed limit, finalize current chunk
  238. if current_tokens + desc_tokens > summary_context_size and current_chunk:
  239. # Ensure we have at least 2 descriptions in the chunk (when possible)
  240. if len(current_chunk) == 1:
  241. # Force add one more description to ensure minimum 2 per chunk
  242. current_chunk.append(desc)
  243. chunks.append(current_chunk)
  244. logger.warning(
  245. f"Summarizing {entity_or_relation_name}: Oversize description found"
  246. )
  247. current_chunk = [] # next group is empty
  248. current_tokens = 0
  249. else: # curren_chunk is ready for summary in reduce phase
  250. chunks.append(current_chunk)
  251. current_chunk = [desc] # leave it for next group
  252. current_tokens = desc_tokens
  253. else:
  254. current_chunk.append(desc)
  255. current_tokens += desc_tokens
  256. # Add the last chunk if it exists
  257. if current_chunk:
  258. chunks.append(current_chunk)
  259. logger.info(
  260. f" Summarizing {entity_or_relation_name}: Map {len(current_list)} descriptions into {len(chunks)} groups"
  261. )
  262. # Reduce phase: summarize each group from chunks
  263. new_summaries = []
  264. for i, chunk in enumerate(chunks, start=1):
  265. if len(chunk) == 1:
  266. # Optimization: single description chunks don't need LLM summarization
  267. new_summaries.append(chunk[0])
  268. else:
  269. # Multiple descriptions need LLM summarization
  270. summary = await _summarize_descriptions(
  271. description_type,
  272. entity_or_relation_name,
  273. chunk,
  274. global_config,
  275. llm_response_cache,
  276. )
  277. new_summaries.append(summary)
  278. llm_was_used = True # Mark that LLM was used in reduce phase
  279. # Update current list with new summaries for next iteration
  280. current_list = new_summaries
  281. async def _summarize_descriptions(
  282. description_type: str,
  283. description_name: str,
  284. description_list: list[str],
  285. global_config: dict,
  286. llm_response_cache: BaseKVStorage | None = None,
  287. ) -> str:
  288. """Helper function to summarize a list of descriptions using LLM.
  289. Args:
  290. entity_or_relation_name: Name of the entity or relation being summarized
  291. descriptions: List of description strings to summarize
  292. global_config: Global configuration containing LLM function and settings
  293. llm_response_cache: Optional cache for LLM responses
  294. Returns:
  295. Summarized description string
  296. """
  297. use_llm_func: callable = global_config["role_llm_funcs"]["extract"]
  298. # Apply higher priority (8) to entity/relation summary tasks
  299. use_llm_func = partial(use_llm_func, _priority=8)
  300. addon_params = global_config.get("addon_params") or {}
  301. language = global_config.get("_resolved_summary_language")
  302. if language is None:
  303. language = addon_params.get("language", DEFAULT_SUMMARY_LANGUAGE)
  304. summary_length_recommended = global_config["summary_length_recommended"]
  305. prompt_template = PROMPTS["summarize_entity_descriptions"]
  306. # Convert descriptions to JSONL format and apply token-based truncation
  307. tokenizer = global_config["tokenizer"]
  308. summary_context_size = global_config["summary_context_size"]
  309. # Create list of JSON objects with "Description" field
  310. json_descriptions = [{"Description": desc} for desc in description_list]
  311. # Use truncate_list_by_token_size for length truncation
  312. truncated_json_descriptions = truncate_list_by_token_size(
  313. json_descriptions,
  314. key=lambda x: json.dumps(x, ensure_ascii=False),
  315. max_token_size=summary_context_size,
  316. tokenizer=tokenizer,
  317. )
  318. # Convert to JSONL format (one JSON object per line)
  319. joined_descriptions = "\n".join(
  320. json.dumps(desc, ensure_ascii=False) for desc in truncated_json_descriptions
  321. )
  322. # Prepare context for the prompt
  323. context_base = dict(
  324. description_type=description_type,
  325. description_name=description_name,
  326. description_list=joined_descriptions,
  327. summary_length=summary_length_recommended,
  328. language=language,
  329. )
  330. use_prompt = prompt_template.format(**context_base)
  331. # Use LLM function with cache (higher priority for summary generation)
  332. summary, _ = await use_llm_func_with_cache(
  333. use_prompt,
  334. use_llm_func,
  335. llm_response_cache=llm_response_cache,
  336. cache_type="summary",
  337. llm_cache_identity=get_llm_cache_identity(global_config, "extract"),
  338. )
  339. # Check summary token length against embedding limit
  340. embedding_token_limit = global_config.get("embedding_token_limit")
  341. if embedding_token_limit is not None and summary:
  342. tokenizer = global_config["tokenizer"]
  343. summary_token_count = len(tokenizer.encode(summary))
  344. threshold = int(embedding_token_limit)
  345. if summary_token_count > threshold:
  346. logger.warning(
  347. f"Summary tokens({summary_token_count}) exceeds embedding_token_limit({embedding_token_limit}) "
  348. f" for {description_type}: {description_name}"
  349. )
  350. return summary
  351. def _handle_single_entity_extraction(
  352. record_attributes: list[str],
  353. chunk_key: str,
  354. timestamp: int,
  355. file_path: str = "unknown_source",
  356. ):
  357. if len(record_attributes) != 4 or "entity" not in record_attributes[0]:
  358. if len(record_attributes) > 1 and "entity" in record_attributes[0]:
  359. logger.warning(
  360. f"{chunk_key}: LLM output format error; found {len(record_attributes)}/4 fields on ENTITY `{record_attributes[1]}` @ `{record_attributes[2] if len(record_attributes) > 2 else 'N/A'}`"
  361. )
  362. logger.debug(record_attributes)
  363. return None
  364. try:
  365. entity_name = sanitize_and_normalize_extracted_text(
  366. record_attributes[1], remove_inner_quotes=True
  367. )
  368. # Validate entity name after all cleaning steps
  369. if not entity_name or not entity_name.strip():
  370. logger.info(
  371. f"Empty entity name found after sanitization. Original: '{record_attributes[1]}'"
  372. )
  373. return None
  374. # Process entity type with same cleaning pipeline
  375. entity_type = sanitize_and_normalize_extracted_text(
  376. record_attributes[2], remove_inner_quotes=True
  377. )
  378. if not entity_type.strip() or any(
  379. char in entity_type for char in ["'", "(", ")", "<", ">", "|", "/", "\\"]
  380. ):
  381. logger.warning(
  382. f"Entity extraction error: invalid entity type in: {record_attributes}"
  383. )
  384. return None
  385. # Handle comma-separated entity types by finding the first non-empty token
  386. if "," in entity_type:
  387. original = entity_type
  388. tokens = [t.strip() for t in entity_type.split(",")]
  389. non_empty = [t for t in tokens if t]
  390. if not non_empty:
  391. logger.warning(
  392. f"Entity extraction error: all tokens empty after comma-split: '{original}'"
  393. )
  394. return None
  395. entity_type = non_empty[0]
  396. logger.warning(
  397. f"Entity type contains comma, taking first non-empty token: '{original}' -> '{entity_type}'"
  398. )
  399. # Remove spaces and convert to lowercase
  400. entity_type = entity_type.replace(" ", "").lower()
  401. # Process entity description with same cleaning pipeline
  402. entity_description = sanitize_and_normalize_extracted_text(record_attributes[3])
  403. if not entity_description.strip():
  404. logger.warning(
  405. f"Entity extraction error: empty description for entity '{entity_name}' of type '{entity_type}'"
  406. )
  407. return None
  408. return dict(
  409. entity_name=entity_name,
  410. entity_type=entity_type,
  411. description=entity_description,
  412. source_id=chunk_key,
  413. file_path=file_path,
  414. timestamp=timestamp,
  415. )
  416. except ValueError as e:
  417. logger.error(
  418. f"Entity extraction failed due to encoding issues in chunk {chunk_key}: {e}"
  419. )
  420. return None
  421. except Exception as e:
  422. logger.error(
  423. f"Entity extraction failed with unexpected error in chunk {chunk_key}: {e}"
  424. )
  425. return None
  426. def _handle_single_relationship_extraction(
  427. record_attributes: list[str],
  428. chunk_key: str,
  429. timestamp: int,
  430. file_path: str = "unknown_source",
  431. ):
  432. if (
  433. len(record_attributes) != 5 or "relation" not in record_attributes[0]
  434. ): # treat "relationship" and "relation" interchangeable
  435. if len(record_attributes) > 1 and "relation" in record_attributes[0]:
  436. logger.warning(
  437. f"{chunk_key}: LLM output format error; found {len(record_attributes)}/5 fields on RELATION `{record_attributes[1]}`~`{record_attributes[2] if len(record_attributes) > 2 else 'N/A'}`"
  438. )
  439. logger.debug(record_attributes)
  440. return None
  441. try:
  442. source = sanitize_and_normalize_extracted_text(
  443. record_attributes[1], remove_inner_quotes=True
  444. )
  445. target = sanitize_and_normalize_extracted_text(
  446. record_attributes[2], remove_inner_quotes=True
  447. )
  448. # Validate entity names after all cleaning steps
  449. if not source:
  450. logger.info(
  451. f"Empty source entity found after sanitization. Original: '{record_attributes[1]}'"
  452. )
  453. return None
  454. if not target:
  455. logger.info(
  456. f"Empty target entity found after sanitization. Original: '{record_attributes[2]}'"
  457. )
  458. return None
  459. if source == target:
  460. logger.debug(
  461. f"Relationship source and target are the same in: {record_attributes}"
  462. )
  463. return None
  464. # Process keywords with same cleaning pipeline
  465. edge_keywords = sanitize_and_normalize_extracted_text(
  466. record_attributes[3], remove_inner_quotes=True
  467. )
  468. edge_keywords = edge_keywords.replace(",", ",")
  469. # Process relationship description with same cleaning pipeline
  470. edge_description = sanitize_and_normalize_extracted_text(record_attributes[4])
  471. if not edge_description.strip():
  472. logger.warning(
  473. f"Relationship extraction error: empty description for relation '{source}'~'{target}' in chunk '{chunk_key}'"
  474. )
  475. return None
  476. edge_source_id = chunk_key
  477. weight = (
  478. float(record_attributes[-1].strip('"').strip("'"))
  479. if is_float_regex(record_attributes[-1].strip('"').strip("'"))
  480. else 1.0
  481. )
  482. return dict(
  483. src_id=source,
  484. tgt_id=target,
  485. weight=weight,
  486. description=edge_description,
  487. keywords=edge_keywords,
  488. source_id=edge_source_id,
  489. file_path=file_path,
  490. timestamp=timestamp,
  491. )
  492. except ValueError as e:
  493. logger.warning(
  494. f"Relationship extraction failed due to encoding issues in chunk {chunk_key}: {e}"
  495. )
  496. return None
  497. except Exception as e:
  498. logger.warning(
  499. f"Relationship extraction failed with unexpected error in chunk {chunk_key}: {e}"
  500. )
  501. return None
  502. def _normalize_text_extraction_record_attributes(
  503. record_attributes: list[str], chunk_key: str
  504. ) -> list[str]:
  505. """Recover the known text-mode failure where relation rows use the entity prefix."""
  506. if len(record_attributes) != 5:
  507. return record_attributes
  508. prefix = record_attributes[0].strip().lower()
  509. if "entity" not in prefix or "relation" in prefix:
  510. return record_attributes
  511. logger.warning(
  512. "Recovering mis-prefixed relation: `%s` ~ `%s`",
  513. record_attributes[1],
  514. record_attributes[2],
  515. )
  516. normalized = list(record_attributes)
  517. normalized[0] = "relation"
  518. return normalized
  519. def _looks_like_json_extraction_result(result: str) -> bool:
  520. """Return True for raw or fenced JSON extraction responses."""
  521. stripped = result.strip()
  522. if not stripped:
  523. return False
  524. if stripped.startswith(("{", "[")):
  525. return True
  526. if stripped.startswith("```"):
  527. return _strip_markdown_code_fence(stripped).strip().startswith(("{", "["))
  528. return False
  529. async def _process_json_extraction_result(
  530. result: str,
  531. chunk_key: str,
  532. timestamp: int,
  533. file_path: str = "unknown_source",
  534. ) -> tuple[dict, dict]:
  535. """Process a JSON-formatted extraction result from LLM.
  536. This function parses the LLM response as JSON and extracts entities and relationships.
  537. It uses json_repair to handle slightly malformed JSON from weaker models.
  538. Args:
  539. result: The JSON extraction result from LLM
  540. chunk_key: The chunk key for source tracking
  541. timestamp: The timestamp for the extraction
  542. file_path: The file path for citation
  543. Returns:
  544. tuple: (nodes_dict, edges_dict) containing the extracted entities and relationships
  545. """
  546. maybe_nodes = defaultdict(list)
  547. maybe_edges = defaultdict(list)
  548. try:
  549. # Parse the JSON response using json_repair for robustness
  550. parsed = json_repair.loads(_strip_markdown_code_fence(result).strip())
  551. except Exception as e:
  552. logger.warning(f"{chunk_key}: Failed to parse JSON extraction result: {e}")
  553. return dict(maybe_nodes), dict(maybe_edges)
  554. if not isinstance(parsed, dict):
  555. logger.warning(
  556. f"{chunk_key}: JSON extraction result is not a dict, got {type(parsed).__name__}"
  557. )
  558. return dict(maybe_nodes), dict(maybe_edges)
  559. # Process entities
  560. entities_list = parsed.get("entities", [])
  561. if not isinstance(entities_list, list):
  562. logger.warning(
  563. f"{chunk_key}: 'entities' field is not a list in JSON extraction result"
  564. )
  565. entities_list = []
  566. for entity_data in entities_list:
  567. if not isinstance(entity_data, dict):
  568. continue
  569. try:
  570. entity_name = sanitize_and_normalize_extracted_text(
  571. str(entity_data.get("name", "")), remove_inner_quotes=True
  572. )
  573. if not entity_name or not entity_name.strip():
  574. logger.info(
  575. f"{chunk_key}: Empty entity name found after sanitization in JSON result"
  576. )
  577. continue
  578. entity_type = sanitize_and_normalize_extracted_text(
  579. str(entity_data.get("type", "")), remove_inner_quotes=True
  580. )
  581. if not entity_type.strip() or any(
  582. char in entity_type
  583. for char in ["'", "(", ")", "<", ">", "|", "/", "\\"]
  584. ):
  585. logger.warning(
  586. f"{chunk_key}: Invalid entity type '{entity_type}' for entity '{entity_name}'"
  587. )
  588. continue
  589. entity_type = entity_type.replace(" ", "").lower()
  590. entity_description = sanitize_and_normalize_extracted_text(
  591. str(entity_data.get("description", ""))
  592. )
  593. if not entity_description.strip():
  594. logger.warning(
  595. f"{chunk_key}: Empty description for entity '{entity_name}'"
  596. )
  597. continue
  598. truncated_name = _truncate_entity_identifier(
  599. entity_name,
  600. DEFAULT_ENTITY_NAME_MAX_LENGTH,
  601. chunk_key,
  602. "Entity name",
  603. )
  604. node_data = dict(
  605. entity_name=truncated_name,
  606. entity_type=entity_type,
  607. description=entity_description,
  608. source_id=chunk_key,
  609. file_path=file_path,
  610. timestamp=timestamp,
  611. )
  612. maybe_nodes[truncated_name].append(node_data)
  613. except Exception as e:
  614. logger.warning(
  615. f"{chunk_key}: Failed to process entity from JSON result: {e}"
  616. )
  617. continue
  618. # Process relationships
  619. relationships_list = parsed.get("relationships", [])
  620. if not isinstance(relationships_list, list):
  621. logger.warning(
  622. f"{chunk_key}: 'relationships' field is not a list in JSON extraction result"
  623. )
  624. relationships_list = []
  625. for rel_data in relationships_list:
  626. if not isinstance(rel_data, dict):
  627. continue
  628. try:
  629. source = sanitize_and_normalize_extracted_text(
  630. str(rel_data.get("source", "")), remove_inner_quotes=True
  631. )
  632. target = sanitize_and_normalize_extracted_text(
  633. str(rel_data.get("target", "")), remove_inner_quotes=True
  634. )
  635. if not source:
  636. logger.info(
  637. f"{chunk_key}: Empty source entity in JSON relationship result"
  638. )
  639. continue
  640. if not target:
  641. logger.info(
  642. f"{chunk_key}: Empty target entity in JSON relationship result"
  643. )
  644. continue
  645. if source == target:
  646. logger.debug(f"{chunk_key}: Source and target are the same: '{source}'")
  647. continue
  648. edge_keywords = sanitize_and_normalize_extracted_text(
  649. str(rel_data.get("keywords", "")), remove_inner_quotes=True
  650. )
  651. edge_keywords = edge_keywords.replace(",", ",")
  652. edge_description = sanitize_and_normalize_extracted_text(
  653. str(rel_data.get("description", ""))
  654. )
  655. if not edge_description.strip():
  656. logger.warning(
  657. f"{chunk_key}: Empty description for relationship '{source}' ~ '{target}', skipping"
  658. )
  659. continue
  660. truncated_source = _truncate_entity_identifier(
  661. source,
  662. DEFAULT_ENTITY_NAME_MAX_LENGTH,
  663. chunk_key,
  664. "Relation entity",
  665. )
  666. truncated_target = _truncate_entity_identifier(
  667. target,
  668. DEFAULT_ENTITY_NAME_MAX_LENGTH,
  669. chunk_key,
  670. "Relation entity",
  671. )
  672. edge_data = dict(
  673. src_id=truncated_source,
  674. tgt_id=truncated_target,
  675. weight=1.0,
  676. description=edge_description,
  677. keywords=edge_keywords,
  678. source_id=chunk_key,
  679. file_path=file_path,
  680. timestamp=timestamp,
  681. )
  682. maybe_edges[(truncated_source, truncated_target)].append(edge_data)
  683. except Exception as e:
  684. logger.warning(
  685. f"{chunk_key}: Failed to process relationship from JSON result: {e}"
  686. )
  687. continue
  688. return dict(maybe_nodes), dict(maybe_edges)
  689. async def rebuild_knowledge_from_chunks(
  690. entities_to_rebuild: dict[str, list[str]],
  691. relationships_to_rebuild: dict[tuple[str, str], list[str]],
  692. knowledge_graph_inst: BaseGraphStorage,
  693. entities_vdb: BaseVectorStorage,
  694. relationships_vdb: BaseVectorStorage,
  695. text_chunks_storage: BaseKVStorage,
  696. llm_response_cache: BaseKVStorage,
  697. global_config: dict[str, str],
  698. pipeline_status: dict | None = None,
  699. pipeline_status_lock=None,
  700. entity_chunks_storage: BaseKVStorage | None = None,
  701. relation_chunks_storage: BaseKVStorage | None = None,
  702. ) -> None:
  703. """Rebuild entity and relationship descriptions from cached extraction results with parallel processing
  704. This method uses cached LLM extraction results instead of calling LLM again,
  705. following the same approach as the insert process. Now with parallel processing
  706. controlled by llm_model_max_async and using get_storage_keyed_lock for data consistency.
  707. Args:
  708. entities_to_rebuild: Dict mapping entity_name -> list of remaining chunk_ids
  709. relationships_to_rebuild: Dict mapping (src, tgt) -> list of remaining chunk_ids
  710. knowledge_graph_inst: Knowledge graph storage
  711. entities_vdb: Entity vector database
  712. relationships_vdb: Relationship vector database
  713. text_chunks_storage: Text chunks storage
  714. llm_response_cache: LLM response cache
  715. global_config: Global configuration containing llm_model_max_async
  716. pipeline_status: Pipeline status dictionary
  717. pipeline_status_lock: Lock for pipeline status
  718. entity_chunks_storage: KV storage maintaining full chunk IDs per entity
  719. relation_chunks_storage: KV storage maintaining full chunk IDs per relation
  720. """
  721. if not entities_to_rebuild and not relationships_to_rebuild:
  722. return
  723. # Get all referenced chunk IDs
  724. all_referenced_chunk_ids = set()
  725. for chunk_ids in entities_to_rebuild.values():
  726. all_referenced_chunk_ids.update(chunk_ids)
  727. for chunk_ids in relationships_to_rebuild.values():
  728. all_referenced_chunk_ids.update(chunk_ids)
  729. status_message = f"Rebuilding knowledge from {len(all_referenced_chunk_ids)} cached chunk extractions (parallel processing)"
  730. logger.info(status_message)
  731. if pipeline_status is not None and pipeline_status_lock is not None:
  732. async with pipeline_status_lock:
  733. pipeline_status["latest_message"] = status_message
  734. pipeline_status["history_messages"].append(status_message)
  735. # Get cached extraction results for these chunks using storage
  736. # cached_results: chunk_id -> [list of (extraction_result, create_time) from LLM cache sorted by create_time of the first extraction_result]
  737. cached_results = await _get_cached_extraction_results(
  738. llm_response_cache,
  739. all_referenced_chunk_ids,
  740. text_chunks_storage=text_chunks_storage,
  741. )
  742. if not cached_results:
  743. status_message = "No cached extraction results found, cannot rebuild"
  744. logger.warning(status_message)
  745. if pipeline_status is not None and pipeline_status_lock is not None:
  746. async with pipeline_status_lock:
  747. pipeline_status["latest_message"] = status_message
  748. pipeline_status["history_messages"].append(status_message)
  749. return
  750. # Process cached results to get entities and relationships for each chunk
  751. chunk_entities = {} # chunk_id -> {entity_name: [entity_data]}
  752. chunk_relationships = {} # chunk_id -> {(src, tgt): [relationship_data]}
  753. for chunk_id, results in cached_results.items():
  754. try:
  755. # Handle multiple extraction results per chunk
  756. chunk_entities[chunk_id] = defaultdict(list)
  757. chunk_relationships[chunk_id] = defaultdict(list)
  758. # process multiple LLM extraction results for a single chunk_id
  759. for result in results:
  760. entities, relationships = await _rebuild_from_extraction_result(
  761. text_chunks_storage=text_chunks_storage,
  762. chunk_id=chunk_id,
  763. extraction_result=result[0],
  764. timestamp=result[1],
  765. )
  766. # Merge entities and relationships from this extraction result
  767. # Compare description lengths and keep the better version for the same chunk_id
  768. for entity_name, entity_list in entities.items():
  769. if entity_name not in chunk_entities[chunk_id]:
  770. # New entity for this chunk_id
  771. chunk_entities[chunk_id][entity_name].extend(entity_list)
  772. elif len(chunk_entities[chunk_id][entity_name]) == 0:
  773. # Empty list, add the new entities
  774. chunk_entities[chunk_id][entity_name].extend(entity_list)
  775. else:
  776. # Compare description lengths and keep the better one
  777. existing_desc_len = len(
  778. chunk_entities[chunk_id][entity_name][0].get(
  779. "description", ""
  780. )
  781. or ""
  782. )
  783. new_desc_len = len(entity_list[0].get("description", "") or "")
  784. if new_desc_len > existing_desc_len:
  785. # Replace with the new entity that has longer description
  786. chunk_entities[chunk_id][entity_name] = list(entity_list)
  787. # Otherwise keep existing version
  788. # Compare description lengths and keep the better version for the same chunk_id
  789. for rel_key, rel_list in relationships.items():
  790. if rel_key not in chunk_relationships[chunk_id]:
  791. # New relationship for this chunk_id
  792. chunk_relationships[chunk_id][rel_key].extend(rel_list)
  793. elif len(chunk_relationships[chunk_id][rel_key]) == 0:
  794. # Empty list, add the new relationships
  795. chunk_relationships[chunk_id][rel_key].extend(rel_list)
  796. else:
  797. # Compare description lengths and keep the better one
  798. existing_desc_len = len(
  799. chunk_relationships[chunk_id][rel_key][0].get(
  800. "description", ""
  801. )
  802. or ""
  803. )
  804. new_desc_len = len(rel_list[0].get("description", "") or "")
  805. if new_desc_len > existing_desc_len:
  806. # Replace with the new relationship that has longer description
  807. chunk_relationships[chunk_id][rel_key] = list(rel_list)
  808. # Otherwise keep existing version
  809. except Exception as e:
  810. status_message = (
  811. f"Failed to parse cached extraction result for chunk {chunk_id}: {e}"
  812. )
  813. logger.info(status_message) # Per requirement, change to info
  814. if pipeline_status is not None and pipeline_status_lock is not None:
  815. async with pipeline_status_lock:
  816. pipeline_status["latest_message"] = status_message
  817. pipeline_status["history_messages"].append(status_message)
  818. continue
  819. # Get max async tasks limit from global_config for semaphore control
  820. graph_max_async = global_config.get("llm_model_max_async", 4) * 2
  821. semaphore = asyncio.Semaphore(graph_max_async)
  822. # Counters for tracking progress
  823. rebuilt_entities_count = 0
  824. rebuilt_relationships_count = 0
  825. failed_entities_count = 0
  826. failed_relationships_count = 0
  827. async def _locked_rebuild_entity(entity_name, chunk_ids):
  828. nonlocal rebuilt_entities_count, failed_entities_count
  829. async with semaphore:
  830. workspace = global_config.get("workspace", "")
  831. namespace = f"{workspace}:GraphDB" if workspace else "GraphDB"
  832. async with get_storage_keyed_lock(
  833. [entity_name], namespace=namespace, enable_logging=False
  834. ):
  835. try:
  836. await _rebuild_single_entity(
  837. knowledge_graph_inst=knowledge_graph_inst,
  838. entities_vdb=entities_vdb,
  839. entity_name=entity_name,
  840. chunk_ids=chunk_ids,
  841. chunk_entities=chunk_entities,
  842. llm_response_cache=llm_response_cache,
  843. global_config=global_config,
  844. entity_chunks_storage=entity_chunks_storage,
  845. )
  846. rebuilt_entities_count += 1
  847. except Exception as e:
  848. failed_entities_count += 1
  849. status_message = f"Failed to rebuild `{entity_name}`: {e}"
  850. logger.info(status_message) # Per requirement, change to info
  851. if pipeline_status is not None and pipeline_status_lock is not None:
  852. async with pipeline_status_lock:
  853. pipeline_status["latest_message"] = status_message
  854. pipeline_status["history_messages"].append(status_message)
  855. async def _locked_rebuild_relationship(src, tgt, chunk_ids):
  856. nonlocal rebuilt_relationships_count, failed_relationships_count
  857. async with semaphore:
  858. workspace = global_config.get("workspace", "")
  859. namespace = f"{workspace}:GraphDB" if workspace else "GraphDB"
  860. # Sort src and tgt to ensure order-independent lock key generation
  861. sorted_key_parts = sorted([src, tgt])
  862. async with get_storage_keyed_lock(
  863. sorted_key_parts,
  864. namespace=namespace,
  865. enable_logging=False,
  866. ):
  867. try:
  868. await _rebuild_single_relationship(
  869. knowledge_graph_inst=knowledge_graph_inst,
  870. relationships_vdb=relationships_vdb,
  871. entities_vdb=entities_vdb,
  872. src=src,
  873. tgt=tgt,
  874. chunk_ids=chunk_ids,
  875. chunk_relationships=chunk_relationships,
  876. llm_response_cache=llm_response_cache,
  877. global_config=global_config,
  878. relation_chunks_storage=relation_chunks_storage,
  879. entity_chunks_storage=entity_chunks_storage,
  880. pipeline_status=pipeline_status,
  881. pipeline_status_lock=pipeline_status_lock,
  882. )
  883. rebuilt_relationships_count += 1
  884. except Exception as e:
  885. failed_relationships_count += 1
  886. status_message = f"Failed to rebuild `{src}`~`{tgt}`: {e}"
  887. logger.info(status_message) # Per requirement, change to info
  888. if pipeline_status is not None and pipeline_status_lock is not None:
  889. async with pipeline_status_lock:
  890. pipeline_status["latest_message"] = status_message
  891. pipeline_status["history_messages"].append(status_message)
  892. # Create tasks for parallel processing
  893. tasks = []
  894. # Add entity rebuilding tasks
  895. for entity_name, chunk_ids in entities_to_rebuild.items():
  896. task = asyncio.create_task(_locked_rebuild_entity(entity_name, chunk_ids))
  897. tasks.append(task)
  898. # Add relationship rebuilding tasks
  899. for (src, tgt), chunk_ids in relationships_to_rebuild.items():
  900. task = asyncio.create_task(_locked_rebuild_relationship(src, tgt, chunk_ids))
  901. tasks.append(task)
  902. # Log parallel processing start
  903. status_message = f"Starting parallel rebuild of {len(entities_to_rebuild)} entities and {len(relationships_to_rebuild)} relationships (async: {graph_max_async})"
  904. logger.info(status_message)
  905. if pipeline_status is not None and pipeline_status_lock is not None:
  906. async with pipeline_status_lock:
  907. pipeline_status["latest_message"] = status_message
  908. pipeline_status["history_messages"].append(status_message)
  909. # Execute all tasks in parallel with semaphore control and early failure detection
  910. done, pending = await asyncio.wait(tasks, return_when=asyncio.FIRST_EXCEPTION)
  911. # Check if any task raised an exception and ensure all exceptions are retrieved
  912. first_exception = None
  913. for task in done:
  914. try:
  915. exception = task.exception()
  916. if exception is not None:
  917. if first_exception is None:
  918. first_exception = exception
  919. else:
  920. # Task completed successfully, retrieve result to mark as processed
  921. task.result()
  922. except Exception as e:
  923. if first_exception is None:
  924. first_exception = e
  925. # If any task failed, cancel all pending tasks and raise the first exception
  926. if first_exception is not None:
  927. # Cancel all pending tasks
  928. for pending_task in pending:
  929. pending_task.cancel()
  930. # Wait for cancellation to complete
  931. if pending:
  932. await asyncio.wait(pending)
  933. # Re-raise the first exception to notify the caller
  934. raise first_exception
  935. # Final status report
  936. status_message = f"KG rebuild completed: {rebuilt_entities_count} entities and {rebuilt_relationships_count} relationships rebuilt successfully."
  937. if failed_entities_count > 0 or failed_relationships_count > 0:
  938. status_message += f" Failed: {failed_entities_count} entities, {failed_relationships_count} relationships."
  939. logger.info(status_message)
  940. if pipeline_status is not None and pipeline_status_lock is not None:
  941. async with pipeline_status_lock:
  942. pipeline_status["latest_message"] = status_message
  943. pipeline_status["history_messages"].append(status_message)
  944. async def _get_cached_extraction_results(
  945. llm_response_cache: BaseKVStorage,
  946. chunk_ids: set[str],
  947. text_chunks_storage: BaseKVStorage,
  948. ) -> dict[str, list[str]]:
  949. """Get cached extraction results for specific chunk IDs
  950. This function retrieves cached LLM extraction results for the given chunk IDs and returns
  951. them sorted by creation time. The results are sorted at two levels:
  952. 1. Individual extraction results within each chunk are sorted by create_time (earliest first)
  953. 2. Chunks themselves are sorted by the create_time of their earliest extraction result
  954. Args:
  955. llm_response_cache: LLM response cache storage
  956. chunk_ids: Set of chunk IDs to get cached results for
  957. text_chunks_storage: Text chunks storage for retrieving chunk data and LLM cache references
  958. Returns:
  959. Dict mapping chunk_id -> list of extraction_result_text, where:
  960. - Keys (chunk_ids) are ordered by the create_time of their first extraction result
  961. - Values (extraction results) are ordered by create_time within each chunk
  962. """
  963. cached_results = {}
  964. # Collect all LLM cache IDs from chunks
  965. all_cache_ids = set()
  966. # Read from storage
  967. chunk_data_list = await text_chunks_storage.get_by_ids(list(chunk_ids))
  968. for chunk_data in chunk_data_list:
  969. if chunk_data and isinstance(chunk_data, dict):
  970. llm_cache_list = chunk_data.get("llm_cache_list", [])
  971. if llm_cache_list:
  972. all_cache_ids.update(llm_cache_list)
  973. else:
  974. logger.warning(f"Chunk data is invalid or None: {chunk_data}")
  975. if not all_cache_ids:
  976. logger.warning(f"No LLM cache IDs found for {len(chunk_ids)} chunk IDs")
  977. return cached_results
  978. # Batch get LLM cache entries
  979. cache_data_list = await llm_response_cache.get_by_ids(list(all_cache_ids))
  980. # Process cache entries and group by chunk_id
  981. valid_entries = 0
  982. for cache_entry in cache_data_list:
  983. if (
  984. cache_entry is not None
  985. and isinstance(cache_entry, dict)
  986. and cache_entry.get("cache_type") == "extract"
  987. and cache_entry.get("chunk_id") in chunk_ids
  988. ):
  989. chunk_id = cache_entry["chunk_id"]
  990. extraction_result = cache_entry["return"]
  991. create_time = cache_entry.get(
  992. "create_time", 0
  993. ) # Get creation time, default to 0
  994. valid_entries += 1
  995. # Support multiple LLM caches per chunk
  996. if chunk_id not in cached_results:
  997. cached_results[chunk_id] = []
  998. # Store tuple with extraction result and creation time for sorting
  999. cached_results[chunk_id].append((extraction_result, create_time))
  1000. # Sort extraction results by create_time for each chunk and collect earliest times
  1001. chunk_earliest_times = {}
  1002. for chunk_id in cached_results:
  1003. # Sort by create_time (x[1]), then extract only extraction_result (x[0])
  1004. cached_results[chunk_id].sort(key=lambda x: x[1])
  1005. # Store the earliest create_time for this chunk (first item after sorting)
  1006. chunk_earliest_times[chunk_id] = cached_results[chunk_id][0][1]
  1007. # Sort cached_results by the earliest create_time of each chunk
  1008. sorted_chunk_ids = sorted(
  1009. chunk_earliest_times.keys(), key=lambda chunk_id: chunk_earliest_times[chunk_id]
  1010. )
  1011. # Rebuild cached_results in sorted order
  1012. sorted_cached_results = {}
  1013. for chunk_id in sorted_chunk_ids:
  1014. sorted_cached_results[chunk_id] = cached_results[chunk_id]
  1015. logger.info(
  1016. f"Found {valid_entries} valid cache entries, {len(sorted_cached_results)} chunks with results"
  1017. )
  1018. return sorted_cached_results # each item: list(extraction_result, create_time)
  1019. async def _process_extraction_result(
  1020. result: str,
  1021. chunk_key: str,
  1022. timestamp: int,
  1023. file_path: str = "unknown_source",
  1024. tuple_delimiter: str = "<|#|>",
  1025. completion_delimiter: str = "<|COMPLETE|>",
  1026. ) -> tuple[dict, dict]:
  1027. """Process a single extraction result (either initial or gleaning)
  1028. Args:
  1029. result (str): The extraction result to process
  1030. chunk_key (str): The chunk key for source tracking
  1031. file_path (str): The file path for citation
  1032. tuple_delimiter (str): Delimiter for tuple fields
  1033. record_delimiter (str): Delimiter for records
  1034. completion_delimiter (str): Delimiter for completion
  1035. Returns:
  1036. tuple: (nodes_dict, edges_dict) containing the extracted entities and relationships
  1037. """
  1038. maybe_nodes = defaultdict(list)
  1039. maybe_edges = defaultdict(list)
  1040. if completion_delimiter not in result:
  1041. logger.warning(
  1042. f"{chunk_key}: Complete delimiter can not be found in extraction result"
  1043. )
  1044. # Split LLL output result to records by "\n"
  1045. records = split_string_by_multi_markers(
  1046. result,
  1047. ["\n", completion_delimiter, completion_delimiter.lower()],
  1048. )
  1049. # Fix LLM output format error which use tuple_delimiter to separate record instead of "\n"
  1050. fixed_records = []
  1051. for i, record in enumerate(records, start=1):
  1052. record = record.strip()
  1053. if record is None:
  1054. continue
  1055. entity_records = split_string_by_multi_markers(
  1056. record, [f"{tuple_delimiter}entity{tuple_delimiter}"]
  1057. )
  1058. for entity_record in entity_records:
  1059. if not entity_record.startswith("entity") and not entity_record.startswith(
  1060. "relation"
  1061. ):
  1062. entity_record = f"entity<|{entity_record}"
  1063. entity_relation_records = split_string_by_multi_markers(
  1064. # treat "relationship" and "relation" interchangeable
  1065. entity_record,
  1066. [
  1067. f"{tuple_delimiter}relationship{tuple_delimiter}",
  1068. f"{tuple_delimiter}relation{tuple_delimiter}",
  1069. ],
  1070. )
  1071. for entity_relation_record in entity_relation_records:
  1072. if not entity_relation_record.startswith(
  1073. "entity"
  1074. ) and not entity_relation_record.startswith("relation"):
  1075. entity_relation_record = (
  1076. f"relation{tuple_delimiter}{entity_relation_record}"
  1077. )
  1078. fixed_records.append(entity_relation_record)
  1079. await _cooperative_yield(i, every=8)
  1080. if len(fixed_records) != len(records):
  1081. logger.warning(
  1082. f"{chunk_key}: LLM output format error; find LLM use {tuple_delimiter} as record separators instead new-line"
  1083. )
  1084. delimiter_core = tuple_delimiter[2:-2] # Extract "#" from "<|#|>"
  1085. delimiter_core_lower = delimiter_core.lower()
  1086. for i, record in enumerate(fixed_records, start=1):
  1087. record = record.strip()
  1088. if record is None:
  1089. continue
  1090. # Fix various forms of tuple_delimiter corruption from the LLM output using the dedicated function
  1091. record = fix_tuple_delimiter_corruption(record, delimiter_core, tuple_delimiter)
  1092. if delimiter_core != delimiter_core_lower:
  1093. # change delimiter_core to lower case, and fix again
  1094. record = fix_tuple_delimiter_corruption(
  1095. record, delimiter_core_lower, tuple_delimiter
  1096. )
  1097. record_attributes = split_string_by_multi_markers(record, [tuple_delimiter])
  1098. record_attributes = _normalize_text_extraction_record_attributes(
  1099. record_attributes, chunk_key
  1100. )
  1101. # Try to parse as entity
  1102. entity_data = _handle_single_entity_extraction(
  1103. record_attributes, chunk_key, timestamp, file_path
  1104. )
  1105. if entity_data is not None:
  1106. truncated_name = _truncate_entity_identifier(
  1107. entity_data["entity_name"],
  1108. DEFAULT_ENTITY_NAME_MAX_LENGTH,
  1109. chunk_key,
  1110. "Entity name",
  1111. )
  1112. entity_data["entity_name"] = truncated_name
  1113. maybe_nodes[truncated_name].append(entity_data)
  1114. await _cooperative_yield(i, every=8)
  1115. continue
  1116. # Try to parse as relationship
  1117. relationship_data = _handle_single_relationship_extraction(
  1118. record_attributes, chunk_key, timestamp, file_path
  1119. )
  1120. if relationship_data is not None:
  1121. truncated_source = _truncate_entity_identifier(
  1122. relationship_data["src_id"],
  1123. DEFAULT_ENTITY_NAME_MAX_LENGTH,
  1124. chunk_key,
  1125. "Relation entity",
  1126. )
  1127. truncated_target = _truncate_entity_identifier(
  1128. relationship_data["tgt_id"],
  1129. DEFAULT_ENTITY_NAME_MAX_LENGTH,
  1130. chunk_key,
  1131. "Relation entity",
  1132. )
  1133. relationship_data["src_id"] = truncated_source
  1134. relationship_data["tgt_id"] = truncated_target
  1135. maybe_edges[(truncated_source, truncated_target)].append(relationship_data)
  1136. await _cooperative_yield(i, every=8)
  1137. return dict(maybe_nodes), dict(maybe_edges)
  1138. async def _rebuild_from_extraction_result(
  1139. text_chunks_storage: BaseKVStorage,
  1140. extraction_result: str,
  1141. chunk_id: str,
  1142. timestamp: int,
  1143. ) -> tuple[dict, dict]:
  1144. """Parse cached extraction result using the same logic as extract_entities.
  1145. Supports both JSON and delimiter-based formats for backward compatibility.
  1146. Attempts JSON parsing first; if the cached result looks like JSON (starts with '{'),
  1147. uses the JSON parser. Otherwise, falls back to the traditional delimiter-based parser.
  1148. Args:
  1149. text_chunks_storage: Text chunks storage to get chunk data
  1150. extraction_result: The cached LLM extraction result
  1151. chunk_id: The chunk ID for source tracking
  1152. Returns:
  1153. Tuple of (entities_dict, relationships_dict)
  1154. """
  1155. # Get chunk data for file_path from storage
  1156. chunk_data = await text_chunks_storage.get_by_id(chunk_id)
  1157. file_path = (
  1158. chunk_data.get("file_path", "unknown_source")
  1159. if chunk_data
  1160. else "unknown_source"
  1161. )
  1162. # Auto-detect format: try JSON first if the result looks like JSON
  1163. if _looks_like_json_extraction_result(extraction_result):
  1164. # Likely JSON format (from entity_extraction_use_json mode)
  1165. nodes, edges = await _process_json_extraction_result(
  1166. extraction_result,
  1167. chunk_id,
  1168. timestamp,
  1169. file_path,
  1170. )
  1171. # If JSON parsing yielded results, use them
  1172. if nodes or edges:
  1173. return nodes, edges
  1174. # Otherwise fall through to text-based parsing
  1175. # Fall back to traditional delimiter-based parsing
  1176. return await _process_extraction_result(
  1177. extraction_result,
  1178. chunk_id,
  1179. timestamp,
  1180. file_path,
  1181. tuple_delimiter=PROMPTS["DEFAULT_TUPLE_DELIMITER"],
  1182. completion_delimiter=PROMPTS["DEFAULT_COMPLETION_DELIMITER"],
  1183. )
  1184. async def _rebuild_single_entity(
  1185. knowledge_graph_inst: BaseGraphStorage,
  1186. entities_vdb: BaseVectorStorage,
  1187. entity_name: str,
  1188. chunk_ids: list[str],
  1189. chunk_entities: dict,
  1190. llm_response_cache: BaseKVStorage,
  1191. global_config: dict[str, str],
  1192. entity_chunks_storage: BaseKVStorage | None = None,
  1193. pipeline_status: dict | None = None,
  1194. pipeline_status_lock=None,
  1195. ) -> None:
  1196. """Rebuild a single entity from cached extraction results"""
  1197. # Get current entity data
  1198. current_entity = await knowledge_graph_inst.get_node(entity_name)
  1199. if not current_entity:
  1200. return
  1201. # Helper function to update entity in both graph and vector storage
  1202. async def _update_entity_storage(
  1203. final_description: str,
  1204. entity_type: str,
  1205. file_paths: list[str],
  1206. source_chunk_ids: list[str],
  1207. truncation_info: str = "",
  1208. ):
  1209. try:
  1210. # Update entity in graph storage (critical path)
  1211. updated_entity_data = {
  1212. **current_entity,
  1213. "description": final_description,
  1214. "entity_type": entity_type,
  1215. "source_id": GRAPH_FIELD_SEP.join(source_chunk_ids),
  1216. "file_path": GRAPH_FIELD_SEP.join(file_paths)
  1217. if file_paths
  1218. else current_entity.get("file_path", "unknown_source"),
  1219. "created_at": int(time.time()),
  1220. "truncate": truncation_info,
  1221. }
  1222. await knowledge_graph_inst.upsert_node(entity_name, updated_entity_data)
  1223. # Update entity in vector database (equally critical)
  1224. entity_vdb_id = compute_mdhash_id(entity_name, prefix="ent-")
  1225. entity_content = _truncate_vdb_content(
  1226. f"{entity_name}\n{final_description}",
  1227. global_config,
  1228. f"entity:{entity_name}",
  1229. )
  1230. vdb_data = {
  1231. entity_vdb_id: {
  1232. "content": entity_content,
  1233. "entity_name": entity_name,
  1234. "source_id": updated_entity_data["source_id"],
  1235. "description": final_description,
  1236. "entity_type": entity_type,
  1237. "file_path": updated_entity_data["file_path"],
  1238. }
  1239. }
  1240. # Use safe operation wrapper - VDB failure must throw exception
  1241. await safe_vdb_operation_with_exception(
  1242. operation=lambda: entities_vdb.upsert(vdb_data),
  1243. operation_name="rebuild_entity_upsert",
  1244. entity_name=entity_name,
  1245. max_retries=3,
  1246. retry_delay=0.1,
  1247. )
  1248. except Exception as e:
  1249. error_msg = f"Failed to update entity storage for `{entity_name}`: {e}"
  1250. logger.error(error_msg)
  1251. raise # Re-raise exception
  1252. # normalized_chunk_ids = merge_source_ids([], chunk_ids)
  1253. normalized_chunk_ids = chunk_ids
  1254. if entity_chunks_storage is not None and normalized_chunk_ids:
  1255. await entity_chunks_storage.upsert(
  1256. {
  1257. entity_name: {
  1258. "chunk_ids": normalized_chunk_ids,
  1259. "count": len(normalized_chunk_ids),
  1260. }
  1261. }
  1262. )
  1263. limit_method = (
  1264. global_config.get("source_ids_limit_method") or SOURCE_IDS_LIMIT_METHOD_KEEP
  1265. )
  1266. limited_chunk_ids = apply_source_ids_limit(
  1267. normalized_chunk_ids,
  1268. global_config["max_source_ids_per_entity"],
  1269. limit_method,
  1270. identifier=f"`{entity_name}`",
  1271. )
  1272. # Collect all entity data from relevant (limited) chunks
  1273. all_entity_data = []
  1274. for chunk_id in limited_chunk_ids:
  1275. if chunk_id in chunk_entities and entity_name in chunk_entities[chunk_id]:
  1276. all_entity_data.extend(chunk_entities[chunk_id][entity_name])
  1277. if not all_entity_data:
  1278. logger.warning(
  1279. f"No entity data found for `{entity_name}`, trying to rebuild from relationships"
  1280. )
  1281. # Get all edges connected to this entity
  1282. edges = await knowledge_graph_inst.get_node_edges(entity_name)
  1283. if not edges:
  1284. logger.warning(f"No relations attached to entity `{entity_name}`")
  1285. return
  1286. # Collect relationship data to extract entity information
  1287. relationship_descriptions = []
  1288. file_paths = set()
  1289. # Get edge data for all connected relationships
  1290. for src_id, tgt_id in edges:
  1291. edge_data = await knowledge_graph_inst.get_edge(src_id, tgt_id)
  1292. if edge_data:
  1293. if edge_data.get("description"):
  1294. relationship_descriptions.append(edge_data["description"])
  1295. if edge_data.get("file_path"):
  1296. edge_file_paths = edge_data["file_path"].split(GRAPH_FIELD_SEP)
  1297. file_paths.update(edge_file_paths)
  1298. # deduplicate descriptions
  1299. description_list = list(dict.fromkeys(relationship_descriptions))
  1300. # Generate final description from relationships or fallback to current
  1301. if description_list:
  1302. final_description, _ = await _handle_entity_relation_summary(
  1303. "Entity",
  1304. entity_name,
  1305. description_list,
  1306. GRAPH_FIELD_SEP,
  1307. global_config,
  1308. llm_response_cache=llm_response_cache,
  1309. )
  1310. else:
  1311. final_description = current_entity.get("description", "")
  1312. entity_type = current_entity.get("entity_type", "UNKNOWN")
  1313. await _update_entity_storage(
  1314. final_description,
  1315. entity_type,
  1316. file_paths,
  1317. limited_chunk_ids,
  1318. )
  1319. return
  1320. # Process cached entity data
  1321. descriptions = []
  1322. entity_types = []
  1323. file_paths_list = []
  1324. seen_paths = set()
  1325. for entity_data in all_entity_data:
  1326. if entity_data.get("description"):
  1327. descriptions.append(entity_data["description"])
  1328. if entity_data.get("entity_type"):
  1329. entity_types.append(entity_data["entity_type"])
  1330. if entity_data.get("file_path"):
  1331. file_path = entity_data["file_path"]
  1332. if file_path and file_path not in seen_paths:
  1333. file_paths_list.append(file_path)
  1334. seen_paths.add(file_path)
  1335. # Apply MAX_FILE_PATHS limit
  1336. max_file_paths = global_config.get("max_file_paths", DEFAULT_MAX_FILE_PATHS)
  1337. file_path_placeholder = global_config.get(
  1338. "file_path_more_placeholder", DEFAULT_FILE_PATH_MORE_PLACEHOLDER
  1339. )
  1340. limit_method = global_config.get("source_ids_limit_method")
  1341. original_count = len(file_paths_list)
  1342. if original_count > max_file_paths:
  1343. if limit_method == SOURCE_IDS_LIMIT_METHOD_FIFO:
  1344. # FIFO: keep tail (newest), discard head
  1345. file_paths_list = file_paths_list[-max_file_paths:]
  1346. else:
  1347. # KEEP: keep head (earliest), discard tail
  1348. file_paths_list = file_paths_list[:max_file_paths]
  1349. file_paths_list.append(
  1350. f"...{file_path_placeholder}...({limit_method} {max_file_paths}/{original_count})"
  1351. )
  1352. logger.info(
  1353. f"Limited `{entity_name}`: file_path {original_count} -> {max_file_paths} ({limit_method})"
  1354. )
  1355. # Remove duplicates while preserving order
  1356. description_list = list(dict.fromkeys(descriptions))
  1357. entity_types = list(dict.fromkeys(entity_types))
  1358. # Get most common entity type
  1359. entity_type = (
  1360. max(set(entity_types), key=entity_types.count)
  1361. if entity_types
  1362. else current_entity.get("entity_type", "UNKNOWN")
  1363. )
  1364. # Generate final description from entities or fallback to current
  1365. if description_list:
  1366. final_description, _ = await _handle_entity_relation_summary(
  1367. "Entity",
  1368. entity_name,
  1369. description_list,
  1370. GRAPH_FIELD_SEP,
  1371. global_config,
  1372. llm_response_cache=llm_response_cache,
  1373. )
  1374. else:
  1375. final_description = current_entity.get("description", "")
  1376. if len(limited_chunk_ids) < len(normalized_chunk_ids):
  1377. truncation_info = (
  1378. f"{limit_method} {len(limited_chunk_ids)}/{len(normalized_chunk_ids)}"
  1379. )
  1380. else:
  1381. truncation_info = ""
  1382. await _update_entity_storage(
  1383. final_description,
  1384. entity_type,
  1385. file_paths_list,
  1386. limited_chunk_ids,
  1387. truncation_info,
  1388. )
  1389. # Log rebuild completion with truncation info
  1390. status_message = f"Rebuild `{entity_name}` from {len(chunk_ids)} chunks"
  1391. if truncation_info:
  1392. status_message += f" ({truncation_info})"
  1393. logger.info(status_message)
  1394. # Update pipeline status
  1395. if pipeline_status is not None and pipeline_status_lock is not None:
  1396. async with pipeline_status_lock:
  1397. pipeline_status["latest_message"] = status_message
  1398. pipeline_status["history_messages"].append(status_message)
  1399. async def _rebuild_single_relationship(
  1400. knowledge_graph_inst: BaseGraphStorage,
  1401. relationships_vdb: BaseVectorStorage,
  1402. entities_vdb: BaseVectorStorage,
  1403. src: str,
  1404. tgt: str,
  1405. chunk_ids: list[str],
  1406. chunk_relationships: dict,
  1407. llm_response_cache: BaseKVStorage,
  1408. global_config: dict[str, str],
  1409. relation_chunks_storage: BaseKVStorage | None = None,
  1410. entity_chunks_storage: BaseKVStorage | None = None,
  1411. pipeline_status: dict | None = None,
  1412. pipeline_status_lock=None,
  1413. ) -> None:
  1414. """Rebuild a single relationship from cached extraction results
  1415. Note: This function assumes the caller has already acquired the appropriate
  1416. keyed lock for the relationship pair to ensure thread safety.
  1417. """
  1418. # Get current relationship data
  1419. current_relationship = await knowledge_graph_inst.get_edge(src, tgt)
  1420. if not current_relationship:
  1421. return
  1422. # normalized_chunk_ids = merge_source_ids([], chunk_ids)
  1423. normalized_chunk_ids = chunk_ids
  1424. if relation_chunks_storage is not None and normalized_chunk_ids:
  1425. storage_key = make_relation_chunk_key(src, tgt)
  1426. await relation_chunks_storage.upsert(
  1427. {
  1428. storage_key: {
  1429. "chunk_ids": normalized_chunk_ids,
  1430. "count": len(normalized_chunk_ids),
  1431. }
  1432. }
  1433. )
  1434. limit_method = (
  1435. global_config.get("source_ids_limit_method") or SOURCE_IDS_LIMIT_METHOD_KEEP
  1436. )
  1437. limited_chunk_ids = apply_source_ids_limit(
  1438. normalized_chunk_ids,
  1439. global_config["max_source_ids_per_relation"],
  1440. limit_method,
  1441. identifier=f"`{src}`~`{tgt}`",
  1442. )
  1443. # Collect all relationship data from relevant chunks
  1444. all_relationship_data = []
  1445. for chunk_id in limited_chunk_ids:
  1446. if chunk_id in chunk_relationships:
  1447. # Check both (src, tgt) and (tgt, src) since relationships can be bidirectional
  1448. for edge_key in [(src, tgt), (tgt, src)]:
  1449. if edge_key in chunk_relationships[chunk_id]:
  1450. all_relationship_data.extend(
  1451. chunk_relationships[chunk_id][edge_key]
  1452. )
  1453. if not all_relationship_data:
  1454. logger.warning(f"No relation data found for `{src}-{tgt}`")
  1455. return
  1456. # Merge descriptions and keywords
  1457. descriptions = []
  1458. keywords = []
  1459. weights = []
  1460. file_paths_list = []
  1461. seen_paths = set()
  1462. for rel_data in all_relationship_data:
  1463. if rel_data.get("description"):
  1464. descriptions.append(rel_data["description"])
  1465. if rel_data.get("keywords"):
  1466. keywords.append(rel_data["keywords"])
  1467. if rel_data.get("weight"):
  1468. weights.append(rel_data["weight"])
  1469. if rel_data.get("file_path"):
  1470. file_path = rel_data["file_path"]
  1471. if file_path and file_path not in seen_paths:
  1472. file_paths_list.append(file_path)
  1473. seen_paths.add(file_path)
  1474. # Apply count limit
  1475. max_file_paths = global_config.get("max_file_paths", DEFAULT_MAX_FILE_PATHS)
  1476. file_path_placeholder = global_config.get(
  1477. "file_path_more_placeholder", DEFAULT_FILE_PATH_MORE_PLACEHOLDER
  1478. )
  1479. limit_method = global_config.get("source_ids_limit_method")
  1480. original_count = len(file_paths_list)
  1481. if original_count > max_file_paths:
  1482. if limit_method == SOURCE_IDS_LIMIT_METHOD_FIFO:
  1483. # FIFO: keep tail (newest), discard head
  1484. file_paths_list = file_paths_list[-max_file_paths:]
  1485. else:
  1486. # KEEP: keep head (earliest), discard tail
  1487. file_paths_list = file_paths_list[:max_file_paths]
  1488. file_paths_list.append(
  1489. f"...{file_path_placeholder}...({limit_method} {max_file_paths}/{original_count})"
  1490. )
  1491. logger.info(
  1492. f"Limited `{src}`~`{tgt}`: file_path {original_count} -> {max_file_paths} ({limit_method})"
  1493. )
  1494. # Remove duplicates while preserving order
  1495. description_list = list(dict.fromkeys(descriptions))
  1496. keywords = list(dict.fromkeys(keywords))
  1497. combined_keywords = (
  1498. ", ".join(set(keywords))
  1499. if keywords
  1500. else current_relationship.get("keywords", "")
  1501. )
  1502. weight = sum(weights) if weights else current_relationship.get("weight", 1.0)
  1503. # Generate final description from relations or fallback to current
  1504. if description_list:
  1505. final_description, _ = await _handle_entity_relation_summary(
  1506. "Relation",
  1507. f"{src}-{tgt}",
  1508. description_list,
  1509. GRAPH_FIELD_SEP,
  1510. global_config,
  1511. llm_response_cache=llm_response_cache,
  1512. )
  1513. else:
  1514. # fallback to keep current(unchanged)
  1515. final_description = current_relationship.get("description", "")
  1516. if len(limited_chunk_ids) < len(normalized_chunk_ids):
  1517. truncation_info = (
  1518. f"{limit_method} {len(limited_chunk_ids)}/{len(normalized_chunk_ids)}"
  1519. )
  1520. else:
  1521. truncation_info = ""
  1522. # Update relationship in graph storage
  1523. updated_relationship_data = {
  1524. **current_relationship,
  1525. "description": final_description
  1526. if final_description
  1527. else current_relationship.get("description", ""),
  1528. "keywords": combined_keywords,
  1529. "weight": weight,
  1530. "source_id": GRAPH_FIELD_SEP.join(limited_chunk_ids),
  1531. "file_path": GRAPH_FIELD_SEP.join([fp for fp in file_paths_list if fp])
  1532. if file_paths_list
  1533. else current_relationship.get("file_path", "unknown_source"),
  1534. "truncate": truncation_info,
  1535. }
  1536. # Ensure both endpoint nodes exist before writing the edge back
  1537. # (certain storage backends require pre-existing nodes).
  1538. node_description = (
  1539. updated_relationship_data["description"]
  1540. if updated_relationship_data.get("description")
  1541. else current_relationship.get("description", "")
  1542. )
  1543. node_source_id = updated_relationship_data.get("source_id", "")
  1544. node_file_path = updated_relationship_data.get("file_path", "unknown_source")
  1545. for node_id in {src, tgt}:
  1546. if not (await knowledge_graph_inst.has_node(node_id)):
  1547. node_created_at = int(time.time())
  1548. node_data = {
  1549. "entity_id": node_id,
  1550. "source_id": node_source_id,
  1551. "description": node_description,
  1552. "entity_type": "UNKNOWN",
  1553. "file_path": node_file_path,
  1554. "created_at": node_created_at,
  1555. "truncate": "",
  1556. }
  1557. await knowledge_graph_inst.upsert_node(node_id, node_data=node_data)
  1558. # Update entity_chunks_storage for the newly created entity
  1559. if entity_chunks_storage is not None and limited_chunk_ids:
  1560. await entity_chunks_storage.upsert(
  1561. {
  1562. node_id: {
  1563. "chunk_ids": limited_chunk_ids,
  1564. "count": len(limited_chunk_ids),
  1565. }
  1566. }
  1567. )
  1568. # Update entity_vdb for the newly created entity
  1569. if entities_vdb is not None:
  1570. entity_vdb_id = compute_mdhash_id(node_id, prefix="ent-")
  1571. entity_content = _truncate_vdb_content(
  1572. f"{node_id}\n{node_description}",
  1573. global_config,
  1574. f"entity:{node_id}",
  1575. )
  1576. vdb_data = {
  1577. entity_vdb_id: {
  1578. "content": entity_content,
  1579. "entity_name": node_id,
  1580. "source_id": node_source_id,
  1581. "entity_type": "UNKNOWN",
  1582. "file_path": node_file_path,
  1583. }
  1584. }
  1585. await safe_vdb_operation_with_exception(
  1586. operation=lambda payload=vdb_data: entities_vdb.upsert(payload),
  1587. operation_name="rebuild_added_entity_upsert",
  1588. entity_name=node_id,
  1589. max_retries=3,
  1590. retry_delay=0.1,
  1591. )
  1592. await knowledge_graph_inst.upsert_edge(src, tgt, updated_relationship_data)
  1593. # Update relationship in vector database
  1594. # Sort src and tgt to ensure consistent ordering (smaller string first)
  1595. if src > tgt:
  1596. src, tgt = tgt, src
  1597. try:
  1598. rel_vdb_id = compute_mdhash_id(src + tgt, prefix="rel-")
  1599. rel_vdb_id_reverse = compute_mdhash_id(tgt + src, prefix="rel-")
  1600. # Delete old vector records first (both directions to be safe)
  1601. try:
  1602. await relationships_vdb.delete([rel_vdb_id, rel_vdb_id_reverse])
  1603. except Exception as e:
  1604. logger.debug(
  1605. f"Could not delete old relationship vector records {rel_vdb_id}, {rel_vdb_id_reverse}: {e}"
  1606. )
  1607. # Insert new vector record
  1608. rel_content = f"{combined_keywords}\t{src}\n{tgt}\n{final_description}"
  1609. vdb_data = {
  1610. rel_vdb_id: {
  1611. "src_id": src,
  1612. "tgt_id": tgt,
  1613. "source_id": updated_relationship_data["source_id"],
  1614. "content": rel_content,
  1615. "keywords": combined_keywords,
  1616. "description": final_description,
  1617. "weight": weight,
  1618. "file_path": updated_relationship_data["file_path"],
  1619. }
  1620. }
  1621. # Use safe operation wrapper - VDB failure must throw exception
  1622. await safe_vdb_operation_with_exception(
  1623. operation=lambda: relationships_vdb.upsert(vdb_data),
  1624. operation_name="rebuild_relationship_upsert",
  1625. entity_name=f"{src}-{tgt}",
  1626. max_retries=3,
  1627. retry_delay=0.2,
  1628. )
  1629. except Exception as e:
  1630. error_msg = f"Failed to rebuild relationship storage for `{src}-{tgt}`: {e}"
  1631. logger.error(error_msg)
  1632. raise # Re-raise exception
  1633. # Log rebuild completion with truncation info
  1634. status_message = f"Rebuild `{src}`~`{tgt}` from {len(chunk_ids)} chunks"
  1635. if truncation_info:
  1636. status_message += f" ({truncation_info})"
  1637. # Add truncation info from apply_source_ids_limit if truncation occurred
  1638. if len(limited_chunk_ids) < len(normalized_chunk_ids):
  1639. truncation_info = (
  1640. f" ({limit_method}:{len(limited_chunk_ids)}/{len(normalized_chunk_ids)})"
  1641. )
  1642. status_message += truncation_info
  1643. logger.info(status_message)
  1644. # Update pipeline status
  1645. if pipeline_status is not None and pipeline_status_lock is not None:
  1646. async with pipeline_status_lock:
  1647. pipeline_status["latest_message"] = status_message
  1648. pipeline_status["history_messages"].append(status_message)
  1649. async def _merge_nodes_then_upsert(
  1650. entity_name: str,
  1651. nodes_data: list[dict],
  1652. knowledge_graph_inst: BaseGraphStorage,
  1653. entity_vdb: BaseVectorStorage | None,
  1654. global_config: dict,
  1655. pipeline_status: dict = None,
  1656. pipeline_status_lock=None,
  1657. llm_response_cache: BaseKVStorage | None = None,
  1658. entity_chunks_storage: BaseKVStorage | None = None,
  1659. ):
  1660. """Get existing nodes from knowledge graph use name,if exists, merge data, else create, then upsert."""
  1661. timing_start = time.perf_counter()
  1662. try:
  1663. already_entity_types = []
  1664. already_source_ids = []
  1665. already_description = []
  1666. already_file_paths = []
  1667. # 1. Get existing node data from knowledge graph
  1668. already_node = await knowledge_graph_inst.get_node(entity_name)
  1669. if already_node:
  1670. existing_entity_type = already_node.get("entity_type")
  1671. # Coerce to str before any string operations: non-string values from
  1672. # API/custom graph paths would otherwise raise TypeError on the comma check.
  1673. if (
  1674. not isinstance(existing_entity_type, str)
  1675. or not existing_entity_type.strip()
  1676. ):
  1677. existing_entity_type = "UNKNOWN"
  1678. # Sanitize entity_type read back from DB to prevent dirty data from propagating
  1679. if "," in existing_entity_type:
  1680. original = existing_entity_type
  1681. tokens = [t.strip() for t in existing_entity_type.split(",")]
  1682. non_empty = [t for t in tokens if t]
  1683. existing_entity_type = non_empty[0] if non_empty else "UNKNOWN"
  1684. logger.warning(
  1685. f"Entity type read from DB contains comma, taking first non-empty token: '{original}' -> '{existing_entity_type}'"
  1686. )
  1687. already_entity_types.append(existing_entity_type)
  1688. existing_source_id = already_node.get("source_id") or ""
  1689. already_source_ids.extend(existing_source_id.split(GRAPH_FIELD_SEP))
  1690. existing_file_path = already_node.get("file_path") or "unknown_source"
  1691. already_file_paths.extend(existing_file_path.split(GRAPH_FIELD_SEP))
  1692. existing_desc = (already_node.get("description") or "").strip()
  1693. if existing_desc:
  1694. already_description.extend(existing_desc.split(GRAPH_FIELD_SEP))
  1695. new_source_ids = [dp["source_id"] for dp in nodes_data if dp.get("source_id")]
  1696. existing_full_source_ids = []
  1697. if entity_chunks_storage is not None:
  1698. stored_chunks = await entity_chunks_storage.get_by_id(entity_name)
  1699. if stored_chunks and isinstance(stored_chunks, dict):
  1700. existing_full_source_ids = [
  1701. chunk_id
  1702. for chunk_id in stored_chunks.get("chunk_ids", [])
  1703. if chunk_id
  1704. ]
  1705. if not existing_full_source_ids:
  1706. existing_full_source_ids = [
  1707. chunk_id for chunk_id in already_source_ids if chunk_id
  1708. ]
  1709. # 2. Merging new source ids with existing ones
  1710. full_source_ids = merge_source_ids(existing_full_source_ids, new_source_ids)
  1711. if entity_chunks_storage is not None and full_source_ids:
  1712. await entity_chunks_storage.upsert(
  1713. {
  1714. entity_name: {
  1715. "chunk_ids": full_source_ids,
  1716. "count": len(full_source_ids),
  1717. }
  1718. }
  1719. )
  1720. # 3. Finalize source_id by applying source ids limit
  1721. limit_method = global_config.get("source_ids_limit_method")
  1722. max_source_limit = global_config.get("max_source_ids_per_entity")
  1723. source_ids = apply_source_ids_limit(
  1724. full_source_ids,
  1725. max_source_limit,
  1726. limit_method,
  1727. identifier=f"`{entity_name}`",
  1728. )
  1729. # 4. Only keep nodes not filter by apply_source_ids_limit if limit_method is KEEP
  1730. if limit_method == SOURCE_IDS_LIMIT_METHOD_KEEP:
  1731. allowed_source_ids = set(source_ids)
  1732. filtered_nodes = []
  1733. for dp in nodes_data:
  1734. source_id = dp.get("source_id")
  1735. # Skip descriptions sourced from chunks dropped by the limitation cap
  1736. if (
  1737. source_id
  1738. and source_id not in allowed_source_ids
  1739. and source_id not in existing_full_source_ids
  1740. ):
  1741. continue
  1742. filtered_nodes.append(dp)
  1743. nodes_data = filtered_nodes
  1744. else: # In FIFO mode, keep all nodes - truncation happens at source_ids level only
  1745. nodes_data = list(nodes_data)
  1746. # 5. Check if we need to skip summary due to source_ids limit
  1747. if (
  1748. limit_method == SOURCE_IDS_LIMIT_METHOD_KEEP
  1749. and len(existing_full_source_ids) >= max_source_limit
  1750. and not nodes_data
  1751. ):
  1752. if already_node:
  1753. logger.info(
  1754. f"Skipped `{entity_name}`: KEEP old chunks {already_source_ids}/{len(full_source_ids)}"
  1755. )
  1756. existing_node_data = dict(already_node)
  1757. return existing_node_data
  1758. else:
  1759. logger.error(
  1760. f"Internal Error: already_node missing for `{entity_name}`"
  1761. )
  1762. raise ValueError(
  1763. f"Internal Error: already_node missing for `{entity_name}`"
  1764. )
  1765. # 6.1 Finalize source_id
  1766. source_id = GRAPH_FIELD_SEP.join(source_ids)
  1767. # 6.2 Finalize entity type by highest count
  1768. entity_type = sorted(
  1769. Counter(
  1770. [dp["entity_type"] for dp in nodes_data] + already_entity_types
  1771. ).items(),
  1772. key=lambda x: x[1],
  1773. reverse=True,
  1774. )[0][0]
  1775. # 7. Deduplicate nodes by description, keeping first occurrence in the same document
  1776. unique_nodes = {}
  1777. for i, dp in enumerate(nodes_data, start=1):
  1778. desc = dp.get("description")
  1779. if not desc:
  1780. continue
  1781. if desc not in unique_nodes:
  1782. unique_nodes[desc] = dp
  1783. await _cooperative_yield(i, every=32)
  1784. # Sort description by timestamp, then by description length when timestamps are the same
  1785. sorted_nodes = sorted(
  1786. unique_nodes.values(),
  1787. key=lambda x: (x.get("timestamp", 0), -len(x.get("description", ""))),
  1788. )
  1789. sorted_descriptions = [dp["description"] for dp in sorted_nodes]
  1790. # Combine already_description with sorted new sorted descriptions
  1791. description_list = already_description + sorted_descriptions
  1792. if not description_list:
  1793. fallback_description = f"Entity {entity_name}"
  1794. logger.warning(
  1795. f"Entity `{entity_name}` has no description; fallback to `{fallback_description}`"
  1796. )
  1797. description_list = [fallback_description]
  1798. # Check for cancellation before LLM summary
  1799. if pipeline_status is not None and pipeline_status_lock is not None:
  1800. async with pipeline_status_lock:
  1801. if pipeline_status.get("cancellation_requested", False):
  1802. raise PipelineCancelledException(
  1803. "User cancelled during entity summary"
  1804. )
  1805. # 8. Get summary description an LLM usage status
  1806. description, llm_was_used = await _handle_entity_relation_summary(
  1807. "Entity",
  1808. entity_name,
  1809. description_list,
  1810. GRAPH_FIELD_SEP,
  1811. global_config,
  1812. llm_response_cache,
  1813. )
  1814. # 9. Build file_path within MAX_FILE_PATHS
  1815. file_paths_list = []
  1816. seen_paths = set()
  1817. has_placeholder = False # Indicating file_path has been truncated before
  1818. max_file_paths = global_config.get("max_file_paths", DEFAULT_MAX_FILE_PATHS)
  1819. file_path_placeholder = global_config.get(
  1820. "file_path_more_placeholder", DEFAULT_FILE_PATH_MORE_PLACEHOLDER
  1821. )
  1822. # Collect from already_file_paths, excluding placeholder
  1823. for fp in already_file_paths:
  1824. if fp and fp.startswith(f"...{file_path_placeholder}"): # Skip placeholders
  1825. has_placeholder = True
  1826. continue
  1827. if fp and fp not in seen_paths:
  1828. file_paths_list.append(fp)
  1829. seen_paths.add(fp)
  1830. # Collect from new data
  1831. for i, dp in enumerate(nodes_data, start=1):
  1832. file_path_item = dp.get("file_path")
  1833. if file_path_item and file_path_item not in seen_paths:
  1834. file_paths_list.append(file_path_item)
  1835. seen_paths.add(file_path_item)
  1836. await _cooperative_yield(i, every=32)
  1837. # Apply count limit
  1838. if len(file_paths_list) > max_file_paths:
  1839. limit_method = global_config.get(
  1840. "source_ids_limit_method", SOURCE_IDS_LIMIT_METHOD_KEEP
  1841. )
  1842. file_path_placeholder = global_config.get(
  1843. "file_path_more_placeholder", DEFAULT_FILE_PATH_MORE_PLACEHOLDER
  1844. )
  1845. # Add + sign to indicate actual file count is higher
  1846. original_count_str = (
  1847. f"{len(file_paths_list)}+"
  1848. if has_placeholder
  1849. else str(len(file_paths_list))
  1850. )
  1851. if limit_method == SOURCE_IDS_LIMIT_METHOD_FIFO:
  1852. # FIFO: keep tail (newest), discard head
  1853. file_paths_list = file_paths_list[-max_file_paths:]
  1854. file_paths_list.append(f"...{file_path_placeholder}...(FIFO)")
  1855. else:
  1856. # KEEP: keep head (earliest), discard tail
  1857. file_paths_list = file_paths_list[:max_file_paths]
  1858. file_paths_list.append(f"...{file_path_placeholder}...(KEEP Old)")
  1859. logger.info(
  1860. f"Limited `{entity_name}`: file_path {original_count_str} -> {max_file_paths} ({limit_method})"
  1861. )
  1862. # Finalize file_path
  1863. file_path = GRAPH_FIELD_SEP.join(file_paths_list)
  1864. # 10.Log based on actual LLM usage
  1865. num_fragment = len(description_list)
  1866. already_fragment = len(already_description)
  1867. if llm_was_used:
  1868. status_message = f"LLMmrg: `{entity_name}` | {already_fragment}+{num_fragment - already_fragment}"
  1869. else:
  1870. status_message = f"Merged: `{entity_name}` | {already_fragment}+{num_fragment - already_fragment}"
  1871. truncation_info = truncation_info_log = ""
  1872. if len(source_ids) < len(full_source_ids):
  1873. # Add truncation info from apply_source_ids_limit if truncation occurred
  1874. truncation_info_log = (
  1875. f"{limit_method} {len(source_ids)}/{len(full_source_ids)}"
  1876. )
  1877. if limit_method == SOURCE_IDS_LIMIT_METHOD_FIFO:
  1878. truncation_info = truncation_info_log
  1879. else:
  1880. truncation_info = "KEEP Old"
  1881. deduplicated_num = already_fragment + len(nodes_data) - num_fragment
  1882. dd_message = ""
  1883. if deduplicated_num > 0:
  1884. # Duplicated description detected across multiple trucks for the same entity
  1885. dd_message = f"dd {deduplicated_num}"
  1886. if dd_message or truncation_info_log:
  1887. status_message += (
  1888. f" ({', '.join(filter(None, [truncation_info_log, dd_message]))})"
  1889. )
  1890. # Add message to pipeline satus when merge happens
  1891. if already_fragment > 0 or llm_was_used:
  1892. logger.info(status_message)
  1893. if pipeline_status is not None and pipeline_status_lock is not None:
  1894. async with pipeline_status_lock:
  1895. pipeline_status["latest_message"] = status_message
  1896. pipeline_status["history_messages"].append(status_message)
  1897. else:
  1898. logger.debug(status_message)
  1899. # 11. Update both graph and vector db
  1900. node_data = dict(
  1901. entity_id=entity_name,
  1902. entity_type=entity_type,
  1903. description=description,
  1904. source_id=source_id,
  1905. file_path=file_path,
  1906. created_at=int(time.time()),
  1907. truncate=truncation_info,
  1908. )
  1909. await knowledge_graph_inst.upsert_node(
  1910. entity_name,
  1911. node_data=node_data,
  1912. )
  1913. node_data["entity_name"] = entity_name
  1914. if entity_vdb is not None:
  1915. entity_vdb_id = compute_mdhash_id(str(entity_name), prefix="ent-")
  1916. entity_content = _truncate_vdb_content(
  1917. f"{entity_name}\n{description}",
  1918. global_config,
  1919. f"entity:{entity_name}",
  1920. )
  1921. data_for_vdb = {
  1922. entity_vdb_id: {
  1923. "entity_name": entity_name,
  1924. "entity_type": entity_type,
  1925. "content": entity_content,
  1926. "source_id": source_id,
  1927. "file_path": file_path,
  1928. }
  1929. }
  1930. await safe_vdb_operation_with_exception(
  1931. operation=lambda payload=data_for_vdb: entity_vdb.upsert(payload),
  1932. operation_name="entity_upsert",
  1933. entity_name=entity_name,
  1934. max_retries=3,
  1935. retry_delay=0.1,
  1936. )
  1937. return node_data
  1938. finally:
  1939. performance_timing_log(
  1940. "[_merge_nodes_then_upsert] `%s` completed in %.4fs",
  1941. entity_name,
  1942. time.perf_counter() - timing_start,
  1943. )
  1944. async def _merge_edges_then_upsert(
  1945. src_id: str,
  1946. tgt_id: str,
  1947. edges_data: list[dict],
  1948. knowledge_graph_inst: BaseGraphStorage,
  1949. relationships_vdb: BaseVectorStorage | None,
  1950. entity_vdb: BaseVectorStorage | None,
  1951. global_config: dict,
  1952. pipeline_status: dict = None,
  1953. pipeline_status_lock=None,
  1954. llm_response_cache: BaseKVStorage | None = None,
  1955. added_entities: list = None, # New parameter to track entities added during edge processing
  1956. relation_chunks_storage: BaseKVStorage | None = None,
  1957. entity_chunks_storage: BaseKVStorage | None = None,
  1958. ):
  1959. timing_start = time.perf_counter()
  1960. timing_relation = f"`{src_id}`~`{tgt_id}`"
  1961. try:
  1962. if src_id == tgt_id:
  1963. return None
  1964. relation_key = f"{src_id}->{tgt_id}"
  1965. already_edge = None
  1966. already_weights = []
  1967. already_source_ids = []
  1968. already_description = []
  1969. already_keywords = []
  1970. already_file_paths = []
  1971. # 1. Get existing edge data from graph storage
  1972. if await knowledge_graph_inst.has_edge(src_id, tgt_id):
  1973. already_edge = await knowledge_graph_inst.get_edge(src_id, tgt_id)
  1974. # Handle the case where get_edge returns None or missing fields
  1975. if already_edge:
  1976. # Get weight with default 1.0 if missing
  1977. already_weights.append(already_edge.get("weight", 1.0))
  1978. # Get source_id with empty string default if missing or None
  1979. if already_edge.get("source_id") is not None:
  1980. already_source_ids.extend(
  1981. already_edge["source_id"].split(GRAPH_FIELD_SEP)
  1982. )
  1983. # Get file_path with empty string default if missing or None
  1984. if already_edge.get("file_path") is not None:
  1985. already_file_paths.extend(
  1986. already_edge["file_path"].split(GRAPH_FIELD_SEP)
  1987. )
  1988. # Get description with empty string default if missing or None
  1989. if already_edge.get("description") is not None:
  1990. already_description.extend(
  1991. already_edge["description"].split(GRAPH_FIELD_SEP)
  1992. )
  1993. # Get keywords with empty string default if missing or None
  1994. if already_edge.get("keywords") is not None:
  1995. already_keywords.extend(
  1996. split_string_by_multi_markers(
  1997. already_edge["keywords"], [GRAPH_FIELD_SEP]
  1998. )
  1999. )
  2000. new_source_ids = [dp["source_id"] for dp in edges_data if dp.get("source_id")]
  2001. storage_key = make_relation_chunk_key(src_id, tgt_id)
  2002. existing_full_source_ids = []
  2003. if relation_chunks_storage is not None:
  2004. stored_chunks = await relation_chunks_storage.get_by_id(storage_key)
  2005. if stored_chunks and isinstance(stored_chunks, dict):
  2006. existing_full_source_ids = [
  2007. chunk_id
  2008. for chunk_id in stored_chunks.get("chunk_ids", [])
  2009. if chunk_id
  2010. ]
  2011. if not existing_full_source_ids:
  2012. existing_full_source_ids = [
  2013. chunk_id for chunk_id in already_source_ids if chunk_id
  2014. ]
  2015. # 2. Merge new source ids with existing ones
  2016. full_source_ids = merge_source_ids(existing_full_source_ids, new_source_ids)
  2017. if relation_chunks_storage is not None and full_source_ids:
  2018. await relation_chunks_storage.upsert(
  2019. {
  2020. storage_key: {
  2021. "chunk_ids": full_source_ids,
  2022. "count": len(full_source_ids),
  2023. }
  2024. }
  2025. )
  2026. # 3. Finalize source_id by applying source ids limit
  2027. limit_method = global_config.get("source_ids_limit_method")
  2028. max_source_limit = global_config.get("max_source_ids_per_relation")
  2029. source_ids = apply_source_ids_limit(
  2030. full_source_ids,
  2031. max_source_limit,
  2032. limit_method,
  2033. identifier=f"`{src_id}`~`{tgt_id}`",
  2034. )
  2035. limit_method = (
  2036. global_config.get("source_ids_limit_method") or SOURCE_IDS_LIMIT_METHOD_KEEP
  2037. )
  2038. # 4. Only keep edges with source_id in the final source_ids list if in KEEP mode
  2039. if limit_method == SOURCE_IDS_LIMIT_METHOD_KEEP:
  2040. allowed_source_ids = set(source_ids)
  2041. filtered_edges = []
  2042. for dp in edges_data:
  2043. source_id = dp.get("source_id")
  2044. # Skip relationship fragments sourced from chunks dropped by keep oldest cap
  2045. if (
  2046. source_id
  2047. and source_id not in allowed_source_ids
  2048. and source_id not in existing_full_source_ids
  2049. ):
  2050. continue
  2051. filtered_edges.append(dp)
  2052. edges_data = filtered_edges
  2053. else: # In FIFO mode, keep all edges - truncation happens at source_ids level only
  2054. edges_data = list(edges_data)
  2055. # 5. Check if we need to skip summary due to source_ids limit
  2056. if (
  2057. limit_method == SOURCE_IDS_LIMIT_METHOD_KEEP
  2058. and len(existing_full_source_ids) >= max_source_limit
  2059. and not edges_data
  2060. ):
  2061. if already_edge:
  2062. logger.info(
  2063. f"Skipped `{src_id}`~`{tgt_id}`: KEEP old chunks {already_source_ids}/{len(full_source_ids)}"
  2064. )
  2065. existing_edge_data = dict(already_edge)
  2066. return existing_edge_data
  2067. else:
  2068. logger.error(
  2069. f"Internal Error: already_node missing for `{src_id}`~`{tgt_id}`"
  2070. )
  2071. raise ValueError(
  2072. f"Internal Error: already_node missing for `{src_id}`~`{tgt_id}`"
  2073. )
  2074. # 6.1 Finalize source_id
  2075. source_id = GRAPH_FIELD_SEP.join(source_ids)
  2076. # 6.2 Finalize weight by summing new edges and existing weights
  2077. weight = sum([dp["weight"] for dp in edges_data] + already_weights)
  2078. # 6.2 Finalize keywords by merging existing and new keywords
  2079. all_keywords = set()
  2080. # Process already_keywords (which are comma-separated)
  2081. for i, keyword_str in enumerate(already_keywords, start=1):
  2082. if keyword_str: # Skip empty strings
  2083. all_keywords.update(
  2084. k.strip() for k in keyword_str.split(",") if k.strip()
  2085. )
  2086. await _cooperative_yield(i, every=32)
  2087. # Process new keywords from edges_data
  2088. for i, edge in enumerate(edges_data, start=1):
  2089. if edge.get("keywords"):
  2090. all_keywords.update(
  2091. k.strip() for k in edge["keywords"].split(",") if k.strip()
  2092. )
  2093. await _cooperative_yield(i, every=32)
  2094. # Join all unique keywords with commas
  2095. keywords = ",".join(sorted(all_keywords))
  2096. # 7. Deduplicate by description, keeping first occurrence in the same document
  2097. unique_edges = {}
  2098. for i, dp in enumerate(edges_data, start=1):
  2099. description_value = dp.get("description")
  2100. if not description_value:
  2101. continue
  2102. if description_value not in unique_edges:
  2103. unique_edges[description_value] = dp
  2104. await _cooperative_yield(i, every=32)
  2105. # Sort description by timestamp, then by description length (largest to smallest) when timestamps are the same
  2106. sorted_edges = sorted(
  2107. unique_edges.values(),
  2108. key=lambda x: (x.get("timestamp", 0), -len(x.get("description", ""))),
  2109. )
  2110. sorted_descriptions = [dp["description"] for dp in sorted_edges]
  2111. # Combine already_description with sorted new descriptions
  2112. description_list = already_description + sorted_descriptions
  2113. if not description_list:
  2114. logger.error(f"Relation {src_id}~{tgt_id} has no description")
  2115. raise ValueError(f"Relation {src_id}~{tgt_id} has no description")
  2116. # Check for cancellation before LLM summary
  2117. if pipeline_status is not None and pipeline_status_lock is not None:
  2118. async with pipeline_status_lock:
  2119. if pipeline_status.get("cancellation_requested", False):
  2120. raise PipelineCancelledException(
  2121. "User cancelled during relation summary"
  2122. )
  2123. # 8. Get summary description an LLM usage status
  2124. description, llm_was_used = await _handle_entity_relation_summary(
  2125. "Relation",
  2126. f"({src_id}, {tgt_id})",
  2127. description_list,
  2128. GRAPH_FIELD_SEP,
  2129. global_config,
  2130. llm_response_cache,
  2131. )
  2132. # 9. Build file_path within MAX_FILE_PATHS limit
  2133. file_paths_list = []
  2134. seen_paths = set()
  2135. has_placeholder = False # Track if already_file_paths contains placeholder
  2136. max_file_paths = global_config.get("max_file_paths", DEFAULT_MAX_FILE_PATHS)
  2137. file_path_placeholder = global_config.get(
  2138. "file_path_more_placeholder", DEFAULT_FILE_PATH_MORE_PLACEHOLDER
  2139. )
  2140. # Collect from already_file_paths, excluding placeholder
  2141. for fp in already_file_paths:
  2142. # Check if this is a placeholder record
  2143. if fp and fp.startswith(f"...{file_path_placeholder}"): # Skip placeholders
  2144. has_placeholder = True
  2145. continue
  2146. if fp and fp not in seen_paths:
  2147. file_paths_list.append(fp)
  2148. seen_paths.add(fp)
  2149. # Collect from new data
  2150. for i, dp in enumerate(edges_data, start=1):
  2151. file_path_item = dp.get("file_path")
  2152. if file_path_item and file_path_item not in seen_paths:
  2153. file_paths_list.append(file_path_item)
  2154. seen_paths.add(file_path_item)
  2155. await _cooperative_yield(i, every=32)
  2156. # Apply count limit
  2157. if len(file_paths_list) > max_file_paths:
  2158. limit_method = global_config.get(
  2159. "source_ids_limit_method", SOURCE_IDS_LIMIT_METHOD_KEEP
  2160. )
  2161. # Add + sign to indicate actual file count is higher
  2162. original_count_str = (
  2163. f"{len(file_paths_list)}+"
  2164. if has_placeholder
  2165. else str(len(file_paths_list))
  2166. )
  2167. if limit_method == SOURCE_IDS_LIMIT_METHOD_FIFO:
  2168. # FIFO: keep tail (newest), discard head
  2169. file_paths_list = file_paths_list[-max_file_paths:]
  2170. file_paths_list.append(f"...{file_path_placeholder}...(FIFO)")
  2171. else:
  2172. # KEEP: keep head (earliest), discard tail
  2173. file_paths_list = file_paths_list[:max_file_paths]
  2174. file_paths_list.append(f"...{file_path_placeholder}...(KEEP Old)")
  2175. logger.info(
  2176. f"Limited `{src_id}`~`{tgt_id}`: file_path {original_count_str} -> {max_file_paths} ({limit_method})"
  2177. )
  2178. # Finalize file_path
  2179. file_path = GRAPH_FIELD_SEP.join(file_paths_list)
  2180. # 10. Log based on actual LLM usage
  2181. num_fragment = len(description_list)
  2182. already_fragment = len(already_description)
  2183. if llm_was_used:
  2184. status_message = f"LLMmrg: `{src_id}`~`{tgt_id}` | {already_fragment}+{num_fragment - already_fragment}"
  2185. else:
  2186. status_message = f"Merged: `{src_id}`~`{tgt_id}` | {already_fragment}+{num_fragment - already_fragment}"
  2187. truncation_info = truncation_info_log = ""
  2188. if len(source_ids) < len(full_source_ids):
  2189. # Add truncation info from apply_source_ids_limit if truncation occurred
  2190. truncation_info_log = (
  2191. f"{limit_method} {len(source_ids)}/{len(full_source_ids)}"
  2192. )
  2193. if limit_method == SOURCE_IDS_LIMIT_METHOD_FIFO:
  2194. truncation_info = truncation_info_log
  2195. else:
  2196. truncation_info = "KEEP Old"
  2197. deduplicated_num = already_fragment + len(edges_data) - num_fragment
  2198. dd_message = ""
  2199. if deduplicated_num > 0:
  2200. # Duplicated description detected across multiple trucks for the same entity
  2201. dd_message = f"dd {deduplicated_num}"
  2202. if dd_message or truncation_info_log:
  2203. status_message += (
  2204. f" ({', '.join(filter(None, [truncation_info_log, dd_message]))})"
  2205. )
  2206. # Add message to pipeline satus when merge happens
  2207. if already_fragment > 0 or llm_was_used:
  2208. logger.info(status_message)
  2209. if pipeline_status is not None and pipeline_status_lock is not None:
  2210. async with pipeline_status_lock:
  2211. pipeline_status["latest_message"] = status_message
  2212. pipeline_status["history_messages"].append(status_message)
  2213. else:
  2214. logger.debug(status_message)
  2215. # 11. Update both graph and vector db
  2216. for need_insert_id in [src_id, tgt_id]:
  2217. # Optimization: Use get_node instead of has_node + get_node
  2218. existing_node = await knowledge_graph_inst.get_node(need_insert_id)
  2219. if existing_node is None:
  2220. # Node doesn't exist - create new node
  2221. node_created_at = int(time.time())
  2222. node_data = {
  2223. "entity_id": need_insert_id,
  2224. "source_id": source_id,
  2225. "description": description,
  2226. "entity_type": "UNKNOWN",
  2227. "file_path": file_path,
  2228. "created_at": node_created_at,
  2229. "truncate": "",
  2230. }
  2231. await knowledge_graph_inst.upsert_node(
  2232. need_insert_id, node_data=node_data
  2233. )
  2234. # Update entity_chunks_storage for the newly created entity
  2235. if entity_chunks_storage is not None:
  2236. chunk_ids = [chunk_id for chunk_id in full_source_ids if chunk_id]
  2237. if chunk_ids:
  2238. await entity_chunks_storage.upsert(
  2239. {
  2240. need_insert_id: {
  2241. "chunk_ids": chunk_ids,
  2242. "count": len(chunk_ids),
  2243. }
  2244. }
  2245. )
  2246. if entity_vdb is not None:
  2247. entity_vdb_id = compute_mdhash_id(need_insert_id, prefix="ent-")
  2248. entity_content = _truncate_vdb_content(
  2249. f"{need_insert_id}\n{description}",
  2250. global_config,
  2251. f"entity:{need_insert_id}",
  2252. )
  2253. vdb_data = {
  2254. entity_vdb_id: {
  2255. "content": entity_content,
  2256. "entity_name": need_insert_id,
  2257. "source_id": source_id,
  2258. "entity_type": "UNKNOWN",
  2259. "file_path": file_path,
  2260. }
  2261. }
  2262. await safe_vdb_operation_with_exception(
  2263. operation=lambda payload=vdb_data: entity_vdb.upsert(payload),
  2264. operation_name="added_entity_upsert",
  2265. entity_name=f"{need_insert_id} [relation:{relation_key}]",
  2266. max_retries=3,
  2267. retry_delay=0.1,
  2268. timeout_seconds=_get_relationship_vdb_timeout_seconds(
  2269. global_config
  2270. ),
  2271. log_start=False,
  2272. success_log_threshold_seconds=5.0,
  2273. )
  2274. # Track entities added during edge processing
  2275. if added_entities is not None:
  2276. entity_data = {
  2277. "entity_name": need_insert_id,
  2278. "entity_type": "UNKNOWN",
  2279. "description": description,
  2280. "source_id": source_id,
  2281. "file_path": file_path,
  2282. "created_at": node_created_at,
  2283. }
  2284. added_entities.append(entity_data)
  2285. else:
  2286. # Node exists - update its source_ids by merging with new source_ids
  2287. updated = False # Track if any update occurred
  2288. # 1. Get existing full source_ids from entity_chunks_storage
  2289. existing_full_source_ids = []
  2290. if entity_chunks_storage is not None:
  2291. stored_chunks = await entity_chunks_storage.get_by_id(
  2292. need_insert_id
  2293. )
  2294. if stored_chunks and isinstance(stored_chunks, dict):
  2295. existing_full_source_ids = [
  2296. chunk_id
  2297. for chunk_id in stored_chunks.get("chunk_ids", [])
  2298. if chunk_id
  2299. ]
  2300. # If not in entity_chunks_storage, get from graph database
  2301. if not existing_full_source_ids:
  2302. if existing_node.get("source_id"):
  2303. existing_full_source_ids = existing_node["source_id"].split(
  2304. GRAPH_FIELD_SEP
  2305. )
  2306. # 2. Merge with new source_ids from this relationship
  2307. new_source_ids_from_relation = [
  2308. chunk_id for chunk_id in source_ids if chunk_id
  2309. ]
  2310. merged_full_source_ids = merge_source_ids(
  2311. existing_full_source_ids, new_source_ids_from_relation
  2312. )
  2313. # 3. Save merged full list to entity_chunks_storage (conditional)
  2314. if (
  2315. entity_chunks_storage is not None
  2316. and merged_full_source_ids != existing_full_source_ids
  2317. ):
  2318. updated = True
  2319. await entity_chunks_storage.upsert(
  2320. {
  2321. need_insert_id: {
  2322. "chunk_ids": merged_full_source_ids,
  2323. "count": len(merged_full_source_ids),
  2324. }
  2325. }
  2326. )
  2327. # 4. Apply source_ids limit for graph and vector db
  2328. limit_method = global_config.get(
  2329. "source_ids_limit_method", SOURCE_IDS_LIMIT_METHOD_KEEP
  2330. )
  2331. max_source_limit = global_config.get("max_source_ids_per_entity")
  2332. limited_source_ids = apply_source_ids_limit(
  2333. merged_full_source_ids,
  2334. max_source_limit,
  2335. limit_method,
  2336. identifier=f"`{need_insert_id}`",
  2337. )
  2338. # 5. Update graph database and vector database with limited source_ids (conditional)
  2339. limited_source_id_str = GRAPH_FIELD_SEP.join(limited_source_ids)
  2340. if limited_source_id_str != existing_node.get("source_id", ""):
  2341. updated = True
  2342. updated_node_data = {
  2343. **existing_node,
  2344. "source_id": limited_source_id_str,
  2345. }
  2346. await knowledge_graph_inst.upsert_node(
  2347. need_insert_id, node_data=updated_node_data
  2348. )
  2349. # Update vector database
  2350. if entity_vdb is not None:
  2351. entity_vdb_id = compute_mdhash_id(need_insert_id, prefix="ent-")
  2352. entity_content = (
  2353. f"{need_insert_id}\n{existing_node.get('description', '')}"
  2354. )
  2355. vdb_data = {
  2356. entity_vdb_id: {
  2357. "content": entity_content,
  2358. "entity_name": need_insert_id,
  2359. "source_id": limited_source_id_str,
  2360. "entity_type": existing_node.get(
  2361. "entity_type", "UNKNOWN"
  2362. ),
  2363. "file_path": existing_node.get(
  2364. "file_path", "unknown_source"
  2365. ),
  2366. }
  2367. }
  2368. await safe_vdb_operation_with_exception(
  2369. operation=lambda payload=vdb_data: entity_vdb.upsert(payload),
  2370. operation_name="existing_entity_update",
  2371. entity_name=f"{need_insert_id} [relation:{relation_key}]",
  2372. max_retries=3,
  2373. retry_delay=0.1,
  2374. timeout_seconds=_get_relationship_vdb_timeout_seconds(
  2375. global_config
  2376. ),
  2377. log_start=False,
  2378. success_log_threshold_seconds=5.0,
  2379. )
  2380. # 6. Log once at the end if any update occurred
  2381. if updated:
  2382. status_message = (
  2383. f"Chunks appended from relation: `{need_insert_id}`"
  2384. )
  2385. logger.info(status_message)
  2386. if pipeline_status is not None and pipeline_status_lock is not None:
  2387. async with pipeline_status_lock:
  2388. pipeline_status["latest_message"] = status_message
  2389. pipeline_status["history_messages"].append(status_message)
  2390. edge_created_at = int(time.time())
  2391. edge_upsert_started = time.perf_counter()
  2392. await knowledge_graph_inst.upsert_edge(
  2393. src_id,
  2394. tgt_id,
  2395. edge_data=dict(
  2396. weight=weight,
  2397. description=description,
  2398. keywords=keywords,
  2399. source_id=source_id,
  2400. file_path=file_path,
  2401. created_at=edge_created_at,
  2402. truncate=truncation_info,
  2403. ),
  2404. )
  2405. edge_upsert_elapsed = time.perf_counter() - edge_upsert_started
  2406. if edge_upsert_elapsed >= 5.0:
  2407. logger.info(
  2408. "Graph edge upsert slow for `%s` in %.2fs",
  2409. relation_key,
  2410. edge_upsert_elapsed,
  2411. )
  2412. edge_data = dict(
  2413. src_id=src_id,
  2414. tgt_id=tgt_id,
  2415. description=description,
  2416. keywords=keywords,
  2417. source_id=source_id,
  2418. file_path=file_path,
  2419. created_at=edge_created_at,
  2420. truncate=truncation_info,
  2421. weight=weight,
  2422. )
  2423. # Sort src_id and tgt_id to ensure consistent ordering (smaller string first)
  2424. if src_id > tgt_id:
  2425. src_id, tgt_id = tgt_id, src_id
  2426. if relationships_vdb is not None:
  2427. rel_vdb_id = compute_mdhash_id(src_id + tgt_id, prefix="rel-")
  2428. rel_vdb_id_reverse = compute_mdhash_id(tgt_id + src_id, prefix="rel-")
  2429. try:
  2430. await relationships_vdb.delete([rel_vdb_id, rel_vdb_id_reverse])
  2431. except Exception as e:
  2432. logger.debug(
  2433. f"Could not delete old relationship vector records {rel_vdb_id}, {rel_vdb_id_reverse}: {e}"
  2434. )
  2435. rel_content = _truncate_vdb_content(
  2436. f"{keywords}\t{src_id}\n{tgt_id}\n{description}",
  2437. global_config,
  2438. f"relationship:{src_id}-{tgt_id}",
  2439. )
  2440. vdb_data = {
  2441. rel_vdb_id: {
  2442. "src_id": src_id,
  2443. "tgt_id": tgt_id,
  2444. "source_id": source_id,
  2445. "content": rel_content,
  2446. "keywords": keywords,
  2447. "description": description,
  2448. "weight": weight,
  2449. "file_path": file_path,
  2450. }
  2451. }
  2452. relation_status_message = f"Upserting relation VDB: `{relation_key}`"
  2453. logger.info(relation_status_message)
  2454. if pipeline_status is not None and pipeline_status_lock is not None:
  2455. async with pipeline_status_lock:
  2456. pipeline_status["latest_message"] = relation_status_message
  2457. await safe_vdb_operation_with_exception(
  2458. operation=lambda payload=vdb_data: relationships_vdb.upsert(payload),
  2459. operation_name="relationship_upsert",
  2460. entity_name=relation_key,
  2461. max_retries=3,
  2462. retry_delay=0.2,
  2463. timeout_seconds=_get_relationship_vdb_timeout_seconds(global_config),
  2464. log_start=False,
  2465. success_log_threshold_seconds=5.0,
  2466. )
  2467. return edge_data
  2468. finally:
  2469. performance_timing_log(
  2470. "[_merge_edges_then_upsert] %s completed in %.4fs",
  2471. timing_relation,
  2472. time.perf_counter() - timing_start,
  2473. )
  2474. async def merge_nodes_and_edges(
  2475. chunk_results: list,
  2476. knowledge_graph_inst: BaseGraphStorage,
  2477. entity_vdb: BaseVectorStorage,
  2478. relationships_vdb: BaseVectorStorage,
  2479. global_config: dict[str, str],
  2480. full_entities_storage: BaseKVStorage = None,
  2481. full_relations_storage: BaseKVStorage = None,
  2482. doc_id: str = None,
  2483. pipeline_status: dict = None,
  2484. pipeline_status_lock=None,
  2485. llm_response_cache: BaseKVStorage | None = None,
  2486. entity_chunks_storage: BaseKVStorage | None = None,
  2487. relation_chunks_storage: BaseKVStorage | None = None,
  2488. current_file_number: int = 0,
  2489. total_files: int = 0,
  2490. file_path: str = "unknown_source",
  2491. ) -> None:
  2492. """Two-phase merge: process all entities first, then all relationships
  2493. This approach ensures data consistency by:
  2494. 1. Phase 1: Process all entities concurrently
  2495. 2. Phase 2: Process all relationships concurrently (may add missing entities)
  2496. 3. Phase 3: Update full_entities and full_relations storage with final results
  2497. Args:
  2498. chunk_results: List of tuples (maybe_nodes, maybe_edges) containing extracted entities and relationships
  2499. knowledge_graph_inst: Knowledge graph storage
  2500. entity_vdb: Entity vector database
  2501. relationships_vdb: Relationship vector database
  2502. global_config: Global configuration
  2503. full_entities_storage: Storage for document entity lists
  2504. full_relations_storage: Storage for document relation lists
  2505. doc_id: Document ID for storage indexing
  2506. pipeline_status: Pipeline status dictionary
  2507. pipeline_status_lock: Lock for pipeline status
  2508. llm_response_cache: LLM response cache
  2509. entity_chunks_storage: Storage tracking full chunk lists per entity
  2510. relation_chunks_storage: Storage tracking full chunk lists per relation
  2511. current_file_number: Current file number for logging
  2512. total_files: Total files for logging
  2513. file_path: File path for logging
  2514. """
  2515. # Check for cancellation at the start of merge
  2516. if pipeline_status is not None and pipeline_status_lock is not None:
  2517. async with pipeline_status_lock:
  2518. if pipeline_status.get("cancellation_requested", False):
  2519. raise PipelineCancelledException("User cancelled during merge phase")
  2520. # Collect all nodes and edges from all chunks
  2521. all_nodes = defaultdict(list)
  2522. all_edges = defaultdict(list)
  2523. for i, (maybe_nodes, maybe_edges) in enumerate(chunk_results, start=1):
  2524. # Collect nodes
  2525. for entity_name, entities in maybe_nodes.items():
  2526. all_nodes[entity_name].extend(entities)
  2527. # Collect edges with sorted keys for undirected graph
  2528. for edge_key, edges in maybe_edges.items():
  2529. sorted_edge_key = tuple(sorted(edge_key))
  2530. all_edges[sorted_edge_key].extend(edges)
  2531. await _cooperative_yield(i, every=32)
  2532. total_entities_count = len(all_nodes)
  2533. total_relations_count = len(all_edges)
  2534. log_message = f"Merging stage {current_file_number}/{total_files}: {file_path}"
  2535. logger.info(log_message)
  2536. async with pipeline_status_lock:
  2537. pipeline_status["latest_message"] = log_message
  2538. pipeline_status["history_messages"].append(log_message)
  2539. # Get max async tasks limit from global_config for semaphore control
  2540. graph_max_async = global_config.get("llm_model_max_async", 4) * 2
  2541. semaphore = asyncio.Semaphore(graph_max_async)
  2542. # ===== Phase 1: Process all entities concurrently =====
  2543. log_message = f"Phase 1: Processing {total_entities_count} entities from {doc_id} (async: {graph_max_async})"
  2544. logger.info(log_message)
  2545. async with pipeline_status_lock:
  2546. pipeline_status["latest_message"] = log_message
  2547. pipeline_status["history_messages"].append(log_message)
  2548. async def _locked_process_entity_name(entity_name, entities):
  2549. async with semaphore:
  2550. # Check for cancellation before processing entity
  2551. if pipeline_status is not None and pipeline_status_lock is not None:
  2552. async with pipeline_status_lock:
  2553. if pipeline_status.get("cancellation_requested", False):
  2554. raise PipelineCancelledException(
  2555. "User cancelled during entity merge"
  2556. )
  2557. workspace = global_config.get("workspace", "")
  2558. namespace = f"{workspace}:GraphDB" if workspace else "GraphDB"
  2559. async with get_storage_keyed_lock(
  2560. [entity_name], namespace=namespace, enable_logging=False
  2561. ):
  2562. try:
  2563. logger.debug(f"Processing entity {entity_name}")
  2564. entity_data = await _merge_nodes_then_upsert(
  2565. entity_name,
  2566. entities,
  2567. knowledge_graph_inst,
  2568. entity_vdb,
  2569. global_config,
  2570. pipeline_status,
  2571. pipeline_status_lock,
  2572. llm_response_cache,
  2573. entity_chunks_storage,
  2574. )
  2575. return entity_data
  2576. except Exception as e:
  2577. error_msg = f"Error processing entity `{entity_name}`: {e}"
  2578. logger.error(error_msg)
  2579. # Try to update pipeline status, but don't let status update failure affect main exception
  2580. try:
  2581. if (
  2582. pipeline_status is not None
  2583. and pipeline_status_lock is not None
  2584. ):
  2585. async with pipeline_status_lock:
  2586. pipeline_status["latest_message"] = error_msg
  2587. pipeline_status["history_messages"].append(error_msg)
  2588. except Exception as status_error:
  2589. logger.error(
  2590. f"Failed to update pipeline status: {status_error}"
  2591. )
  2592. # Re-raise the original exception with a prefix
  2593. prefixed_exception = create_prefixed_exception(
  2594. e, f"`{entity_name}`"
  2595. )
  2596. raise prefixed_exception from e
  2597. # Create entity processing tasks
  2598. entity_tasks = []
  2599. for i, (entity_name, entities) in enumerate(all_nodes.items(), start=1):
  2600. task = asyncio.create_task(_locked_process_entity_name(entity_name, entities))
  2601. entity_tasks.append(task)
  2602. await _cooperative_yield(i, every=16)
  2603. # Execute entity tasks with error handling
  2604. processed_entities = []
  2605. if entity_tasks:
  2606. done, pending = await asyncio.wait(
  2607. entity_tasks, return_when=asyncio.FIRST_EXCEPTION
  2608. )
  2609. first_exception = None
  2610. processed_entities = []
  2611. for i, task in enumerate(done, start=1):
  2612. try:
  2613. result = task.result()
  2614. except BaseException as e:
  2615. if first_exception is None:
  2616. first_exception = e
  2617. else:
  2618. processed_entities.append(result)
  2619. await _cooperative_yield(i, every=32)
  2620. if pending:
  2621. for task in pending:
  2622. task.cancel()
  2623. pending_results = await asyncio.gather(*pending, return_exceptions=True)
  2624. for result in pending_results:
  2625. if isinstance(result, BaseException):
  2626. if first_exception is None:
  2627. first_exception = result
  2628. else:
  2629. processed_entities.append(result)
  2630. if first_exception is not None:
  2631. raise first_exception
  2632. await asyncio.sleep(0)
  2633. # ===== Phase 2: Process all relationships concurrently =====
  2634. log_message = f"Phase 2: Processing {total_relations_count} relations from {doc_id} (async: {graph_max_async})"
  2635. logger.info(log_message)
  2636. async with pipeline_status_lock:
  2637. pipeline_status["latest_message"] = log_message
  2638. pipeline_status["history_messages"].append(log_message)
  2639. async def _locked_process_edges(edge_key, edges):
  2640. async with semaphore:
  2641. # Check for cancellation before processing edges
  2642. if pipeline_status is not None and pipeline_status_lock is not None:
  2643. async with pipeline_status_lock:
  2644. if pipeline_status.get("cancellation_requested", False):
  2645. raise PipelineCancelledException(
  2646. "User cancelled during relation merge"
  2647. )
  2648. workspace = global_config.get("workspace", "")
  2649. namespace = f"{workspace}:GraphDB" if workspace else "GraphDB"
  2650. sorted_edge_key = sorted([edge_key[0], edge_key[1]])
  2651. edge_label = _format_relation_edge_label(edge_key)
  2652. async with get_storage_keyed_lock(
  2653. sorted_edge_key,
  2654. namespace=namespace,
  2655. enable_logging=False,
  2656. ):
  2657. try:
  2658. added_entities = [] # Track entities added during edge processing
  2659. edge_data = await _merge_edges_then_upsert(
  2660. edge_key[0],
  2661. edge_key[1],
  2662. edges,
  2663. knowledge_graph_inst,
  2664. relationships_vdb,
  2665. entity_vdb,
  2666. global_config,
  2667. pipeline_status,
  2668. pipeline_status_lock,
  2669. llm_response_cache,
  2670. added_entities, # Pass list to collect added entities
  2671. relation_chunks_storage,
  2672. entity_chunks_storage, # Add entity_chunks_storage parameter
  2673. )
  2674. if edge_data is None:
  2675. return None, []
  2676. return edge_data, added_entities
  2677. except Exception as e:
  2678. error_msg = f"Error processing relation `{edge_label}`: {e}"
  2679. logger.error(error_msg)
  2680. # Try to update pipeline status, but don't let status update failure affect main exception
  2681. try:
  2682. if (
  2683. pipeline_status is not None
  2684. and pipeline_status_lock is not None
  2685. ):
  2686. async with pipeline_status_lock:
  2687. pipeline_status["latest_message"] = error_msg
  2688. pipeline_status["history_messages"].append(error_msg)
  2689. except Exception as status_error:
  2690. logger.error(
  2691. f"Failed to update pipeline status: {status_error}"
  2692. )
  2693. # Re-raise the original exception with a prefix
  2694. prefixed_exception = create_prefixed_exception(e, f"{edge_label}")
  2695. raise prefixed_exception from e
  2696. # Create relationship processing tasks
  2697. edge_tasks = []
  2698. edge_task_labels: dict[asyncio.Task, str] = {}
  2699. for i, (edge_key, edges) in enumerate(all_edges.items(), start=1):
  2700. task = asyncio.create_task(_locked_process_edges(edge_key, edges))
  2701. edge_tasks.append(task)
  2702. edge_task_labels[task] = _format_relation_edge_label(edge_key)
  2703. await _cooperative_yield(i, every=32)
  2704. # Execute relationship tasks with error handling
  2705. processed_edges = []
  2706. all_added_entities = []
  2707. if edge_tasks:
  2708. done, pending = await asyncio.wait(
  2709. edge_tasks, return_when=asyncio.FIRST_EXCEPTION
  2710. )
  2711. first_exception = None
  2712. for i, task in enumerate(done, start=1):
  2713. try:
  2714. edge_data, added_entities = task.result()
  2715. except BaseException as e:
  2716. if first_exception is None:
  2717. first_exception = e
  2718. else:
  2719. if edge_data is not None:
  2720. processed_edges.append(edge_data)
  2721. all_added_entities.extend(added_entities)
  2722. await _cooperative_yield(i, every=32)
  2723. if pending:
  2724. pending_labels = [
  2725. edge_task_labels.get(task, "<unknown>") for task in pending
  2726. ]
  2727. preview = ", ".join(pending_labels[:10])
  2728. if len(pending_labels) > 10:
  2729. preview += f", ... (+{len(pending_labels) - 10} more)"
  2730. logger.warning(
  2731. "Phase 2 pending relation tasks for %s: %s",
  2732. doc_id,
  2733. preview or "<none>",
  2734. )
  2735. for task in pending:
  2736. task.cancel()
  2737. pending_results = await asyncio.gather(*pending, return_exceptions=True)
  2738. for result in pending_results:
  2739. if isinstance(result, BaseException):
  2740. if first_exception is None:
  2741. first_exception = result
  2742. else:
  2743. edge_data, added_entities = result
  2744. if edge_data is not None:
  2745. processed_edges.append(edge_data)
  2746. all_added_entities.extend(added_entities)
  2747. logger.info(
  2748. "Phase 2 pending relation tasks drained for %s: collected_edges=%d collected_added_entities=%d",
  2749. doc_id,
  2750. len(processed_edges),
  2751. len(all_added_entities),
  2752. )
  2753. if first_exception is not None:
  2754. raise first_exception
  2755. logger.info(
  2756. "Phase 2 relation processing completed for %s: edges=%d added_entities=%d",
  2757. doc_id,
  2758. len(processed_edges),
  2759. len(all_added_entities),
  2760. )
  2761. await asyncio.sleep(0)
  2762. # ===== Phase 3: Update full_entities and full_relations storage =====
  2763. if full_entities_storage and full_relations_storage and doc_id:
  2764. try:
  2765. # Merge all entities: original entities + entities added during edge processing
  2766. final_entity_names = set()
  2767. # Add original processed entities
  2768. for i, entity_data in enumerate(processed_entities, start=1):
  2769. if entity_data and entity_data.get("entity_name"):
  2770. final_entity_names.add(entity_data["entity_name"])
  2771. await _cooperative_yield(i, every=32)
  2772. # Add entities that were added during relationship processing
  2773. for i, added_entity in enumerate(all_added_entities, start=1):
  2774. if added_entity and added_entity.get("entity_name"):
  2775. final_entity_names.add(added_entity["entity_name"])
  2776. await _cooperative_yield(i, every=32)
  2777. # Collect all relation pairs
  2778. final_relation_pairs = set()
  2779. for i, edge_data in enumerate(processed_edges, start=1):
  2780. if edge_data:
  2781. src_id = edge_data.get("src_id")
  2782. tgt_id = edge_data.get("tgt_id")
  2783. if src_id and tgt_id:
  2784. relation_pair = tuple(sorted([src_id, tgt_id]))
  2785. final_relation_pairs.add(relation_pair)
  2786. await _cooperative_yield(i, every=32)
  2787. log_message = f"Phase 3: Updating final {len(final_entity_names)}({len(processed_entities)}+{len(all_added_entities)}) entities and {len(final_relation_pairs)} relations from {doc_id}"
  2788. logger.info(log_message)
  2789. async with pipeline_status_lock:
  2790. pipeline_status["latest_message"] = log_message
  2791. pipeline_status["history_messages"].append(log_message)
  2792. # Update storage
  2793. if final_entity_names:
  2794. await full_entities_storage.upsert(
  2795. {
  2796. doc_id: {
  2797. "entity_names": list(final_entity_names),
  2798. "count": len(final_entity_names),
  2799. }
  2800. }
  2801. )
  2802. if final_relation_pairs:
  2803. await full_relations_storage.upsert(
  2804. {
  2805. doc_id: {
  2806. "relation_pairs": [
  2807. list(pair) for pair in final_relation_pairs
  2808. ],
  2809. "count": len(final_relation_pairs),
  2810. }
  2811. }
  2812. )
  2813. logger.debug(
  2814. f"Updated entity-relation index for document {doc_id}: {len(final_entity_names)} entities (original: {len(processed_entities)}, added: {len(all_added_entities)}), {len(final_relation_pairs)} relations"
  2815. )
  2816. except Exception as e:
  2817. logger.error(
  2818. f"Failed to update entity-relation index for document {doc_id}: {e}"
  2819. )
  2820. # Don't raise exception to avoid affecting main flow
  2821. log_message = f"Completed merging: {len(processed_entities)} entities, {len(all_added_entities)} extra entities, {len(processed_edges)} relations"
  2822. logger.info(log_message)
  2823. async with pipeline_status_lock:
  2824. pipeline_status["latest_message"] = log_message
  2825. pipeline_status["history_messages"].append(log_message)
  2826. async def extract_entities(
  2827. chunks: dict[str, TextChunkSchema],
  2828. global_config: dict[str, str],
  2829. pipeline_status: dict = None,
  2830. pipeline_status_lock=None,
  2831. llm_response_cache: BaseKVStorage | None = None,
  2832. text_chunks_storage: BaseKVStorage | None = None,
  2833. ) -> list:
  2834. # Check for cancellation at the start of entity extraction
  2835. if pipeline_status is not None and pipeline_status_lock is not None:
  2836. async with pipeline_status_lock:
  2837. if pipeline_status.get("cancellation_requested", False):
  2838. raise PipelineCancelledException(
  2839. "User cancelled during entity extraction"
  2840. )
  2841. use_llm_func: callable = global_config["role_llm_funcs"]["extract"]
  2842. entity_extract_max_gleaning = global_config["entity_extract_max_gleaning"]
  2843. # Cap on the gleaning LLM call's combined input (system + history user
  2844. # prompt + history assistant response + continue prompt). Pulled from
  2845. # the same env knob that gates ``analyze_multimodal``'s sidecar trimming
  2846. # so both EXTRACT-role consumers share one source of truth. ``0``
  2847. # disables the gleaning guard (gleaning always runs regardless of size).
  2848. max_extract_input_tokens = get_env_value(
  2849. "MAX_EXTRACT_INPUT_TOKENS",
  2850. DEFAULT_MAX_EXTRACT_INPUT_TOKENS,
  2851. int,
  2852. )
  2853. extract_tokenizer: Tokenizer | None = global_config.get("tokenizer")
  2854. # Check if JSON structured output mode is enabled
  2855. use_json_extraction = global_config.get("entity_extraction_use_json", False)
  2856. ordered_chunks = list(chunks.items())
  2857. # add language and example number params to prompt
  2858. addon_params = global_config.get("addon_params") or {}
  2859. language = global_config.get("_resolved_summary_language")
  2860. if language is None:
  2861. language = addon_params.get("language", DEFAULT_SUMMARY_LANGUAGE)
  2862. prompt_profile = global_config.get("_entity_extraction_prompt_profile")
  2863. if prompt_profile is None:
  2864. # Fallback for callers that construct global_config directly (e.g. tests
  2865. # or custom wiring). Re-run the resolver so behavior matches the cached
  2866. # path that LightRAG.__post_init__ populates, instead of duplicating
  2867. # guidance/override logic here.
  2868. prompt_profile = resolve_entity_extraction_prompt_profile(
  2869. addon_params, use_json_extraction
  2870. )
  2871. entity_types_guidance = prompt_profile["entity_types_guidance"]
  2872. max_total_records = global_config["entity_extract_max_records"]
  2873. max_entity_records = global_config["entity_extract_max_entities"]
  2874. if use_json_extraction:
  2875. # JSON mode: use JSON-specific prompts without delimiters
  2876. examples = "\n".join(prompt_profile["entity_extraction_json_examples"])
  2877. context_base = dict(
  2878. entity_types_guidance=entity_types_guidance,
  2879. examples=examples,
  2880. language=language,
  2881. max_total_records=max_total_records,
  2882. max_entity_records=max_entity_records,
  2883. )
  2884. else:
  2885. # Text mode: use traditional delimiter-based prompts
  2886. examples = "\n".join(prompt_profile["entity_extraction_examples"])
  2887. example_context_base = dict(
  2888. tuple_delimiter=PROMPTS["DEFAULT_TUPLE_DELIMITER"],
  2889. completion_delimiter=PROMPTS["DEFAULT_COMPLETION_DELIMITER"],
  2890. entity_types_guidance=entity_types_guidance,
  2891. language=language,
  2892. )
  2893. # add example's format
  2894. examples = examples.format(**example_context_base)
  2895. context_base = dict(
  2896. tuple_delimiter=PROMPTS["DEFAULT_TUPLE_DELIMITER"],
  2897. completion_delimiter=PROMPTS["DEFAULT_COMPLETION_DELIMITER"],
  2898. entity_types_guidance=entity_types_guidance,
  2899. examples=examples,
  2900. language=language,
  2901. max_total_records=max_total_records,
  2902. max_entity_records=max_entity_records,
  2903. )
  2904. processed_chunks = 0
  2905. total_chunks = len(ordered_chunks)
  2906. async def _process_single_content(chunk_key_dp: tuple[str, TextChunkSchema]):
  2907. """Process a single chunk
  2908. Args:
  2909. chunk_key_dp (tuple[str, TextChunkSchema]):
  2910. ("chunk-xxxxxx", {"tokens": int, "content": str, "full_doc_id": str, "chunk_order_index": int})
  2911. Returns:
  2912. tuple: (maybe_nodes, maybe_edges) containing extracted entities and relationships
  2913. """
  2914. nonlocal processed_chunks
  2915. chunk_key = chunk_key_dp[0]
  2916. chunk_dp = chunk_key_dp[1]
  2917. # Strip parser-internal markup (<cite refid>, <drawing id/path/src>,
  2918. # <equation id>) before building the extraction prompt. The stored
  2919. # chunk content is left intact so query-time citations still resolve.
  2920. content = strip_internal_multimodal_markup_for_extraction(chunk_dp["content"])
  2921. # Get file path from chunk data or use default
  2922. file_path = chunk_dp.get("file_path", "unknown_source")
  2923. # Create cache keys collector for batch processing
  2924. cache_keys_collector = []
  2925. if use_json_extraction:
  2926. # JSON mode: use JSON prompts and pass entity_extraction flag to LLM provider
  2927. entity_extraction_system_prompt = PROMPTS[
  2928. "entity_extraction_json_system_prompt"
  2929. ].format(**context_base)
  2930. entity_extraction_user_prompt = PROMPTS[
  2931. "entity_extraction_json_user_prompt"
  2932. ].format(**{**context_base, "input_text": content})
  2933. entity_continue_extraction_user_prompt = PROMPTS[
  2934. "entity_continue_extraction_json_user_prompt"
  2935. ].format(**context_base)
  2936. else:
  2937. # Text mode: use traditional delimiter-based prompts
  2938. entity_extraction_system_prompt = PROMPTS[
  2939. "entity_extraction_system_prompt"
  2940. ].format(**context_base)
  2941. entity_extraction_user_prompt = PROMPTS[
  2942. "entity_extraction_user_prompt"
  2943. ].format(**{**context_base, "input_text": content})
  2944. entity_continue_extraction_user_prompt = PROMPTS[
  2945. "entity_continue_extraction_user_prompt"
  2946. ].format(**{**context_base, "input_text": content})
  2947. final_result, timestamp = await use_llm_func_with_cache(
  2948. entity_extraction_user_prompt,
  2949. use_llm_func,
  2950. system_prompt=entity_extraction_system_prompt,
  2951. llm_response_cache=llm_response_cache,
  2952. cache_type="extract",
  2953. chunk_id=chunk_key,
  2954. cache_keys_collector=cache_keys_collector,
  2955. response_format=({"type": "json_object"} if use_json_extraction else None),
  2956. llm_cache_identity=get_llm_cache_identity(global_config, "extract"),
  2957. )
  2958. history = pack_user_ass_to_openai_messages(
  2959. entity_extraction_user_prompt, final_result
  2960. )
  2961. # Process initial extraction with appropriate parser
  2962. if use_json_extraction:
  2963. maybe_nodes, maybe_edges = await _process_json_extraction_result(
  2964. final_result,
  2965. chunk_key,
  2966. timestamp,
  2967. file_path,
  2968. )
  2969. else:
  2970. maybe_nodes, maybe_edges = await _process_extraction_result(
  2971. final_result,
  2972. chunk_key,
  2973. timestamp,
  2974. file_path,
  2975. tuple_delimiter=context_base["tuple_delimiter"],
  2976. completion_delimiter=context_base["completion_delimiter"],
  2977. )
  2978. # Process additional gleaning results only 1 time when entity_extract_max_gleaning is greater than zero.
  2979. run_gleaning = entity_extract_max_gleaning > 0
  2980. if (
  2981. run_gleaning
  2982. and extract_tokenizer is not None
  2983. and max_extract_input_tokens > 0
  2984. ):
  2985. # Gleaning replays the initial extraction's user/assistant pair
  2986. # via ``history_messages`` and appends a "continue" instruction.
  2987. # When the initial response was large (many entities/edges) or
  2988. # the chunk content is itself near the budget, that combined
  2989. # payload can blow past MAX_EXTRACT_INPUT_TOKENS and yield a
  2990. # provider ``context_length_exceeded`` error. Pre-check here
  2991. # and skip rather than fail.
  2992. gleaning_token_count = (
  2993. len(extract_tokenizer.encode(entity_extraction_system_prompt))
  2994. + sum(
  2995. len(extract_tokenizer.encode(msg.get("content", "") or ""))
  2996. for msg in history
  2997. )
  2998. + len(extract_tokenizer.encode(entity_continue_extraction_user_prompt))
  2999. )
  3000. if gleaning_token_count > max_extract_input_tokens:
  3001. logger.warning(
  3002. f"Gleaning stopped for chunk {chunk_key}: "
  3003. f"Input tokens ({gleaning_token_count}) exceeded limit "
  3004. f"({max_extract_input_tokens})."
  3005. )
  3006. run_gleaning = False
  3007. if run_gleaning:
  3008. glean_result, timestamp = await use_llm_func_with_cache(
  3009. entity_continue_extraction_user_prompt,
  3010. use_llm_func,
  3011. system_prompt=entity_extraction_system_prompt,
  3012. llm_response_cache=llm_response_cache,
  3013. history_messages=history,
  3014. cache_type="extract",
  3015. chunk_id=chunk_key,
  3016. cache_keys_collector=cache_keys_collector,
  3017. response_format=(
  3018. {"type": "json_object"} if use_json_extraction else None
  3019. ),
  3020. llm_cache_identity=get_llm_cache_identity(global_config, "extract"),
  3021. )
  3022. # Process gleaning result with appropriate parser
  3023. if use_json_extraction:
  3024. glean_nodes, glean_edges = await _process_json_extraction_result(
  3025. glean_result,
  3026. chunk_key,
  3027. timestamp,
  3028. file_path,
  3029. )
  3030. else:
  3031. glean_nodes, glean_edges = await _process_extraction_result(
  3032. glean_result,
  3033. chunk_key,
  3034. timestamp,
  3035. file_path,
  3036. tuple_delimiter=context_base["tuple_delimiter"],
  3037. completion_delimiter=context_base["completion_delimiter"],
  3038. )
  3039. # Merge results - compare description lengths to choose better version
  3040. for i, (entity_name, glean_entities) in enumerate(
  3041. glean_nodes.items(), start=1
  3042. ):
  3043. if entity_name in maybe_nodes:
  3044. # Compare description lengths and keep the better one
  3045. original_desc_len = len(
  3046. maybe_nodes[entity_name][0].get("description", "") or ""
  3047. )
  3048. glean_desc_len = len(glean_entities[0].get("description", "") or "")
  3049. if glean_desc_len > original_desc_len:
  3050. maybe_nodes[entity_name] = list(glean_entities)
  3051. # Otherwise keep original version
  3052. else:
  3053. # New entity from gleaning stage
  3054. maybe_nodes[entity_name] = list(glean_entities)
  3055. await _cooperative_yield(i, every=8)
  3056. for i, (edge_key, glean_edge_list) in enumerate(
  3057. glean_edges.items(), start=1
  3058. ):
  3059. if edge_key in maybe_edges:
  3060. # Compare description lengths and keep the better one
  3061. original_desc_len = len(
  3062. maybe_edges[edge_key][0].get("description", "") or ""
  3063. )
  3064. glean_desc_len = len(
  3065. glean_edge_list[0].get("description", "") or ""
  3066. )
  3067. if glean_desc_len > original_desc_len:
  3068. maybe_edges[edge_key] = list(glean_edge_list)
  3069. # Otherwise keep original version
  3070. else:
  3071. # New edge from gleaning stage
  3072. maybe_edges[edge_key] = list(glean_edge_list)
  3073. await _cooperative_yield(i, every=8)
  3074. # Inject multimodal entity + associations for drawing/table/equation
  3075. # chunks. Placed before update_chunk_cache_list so the per-chunk
  3076. # cache write still happens after; placed inside the chunk's
  3077. # concurrency slot (rather than the centralized post-pass that used
  3078. # to live in utils_pipeline.augment_chunk_results_with_mm_entities)
  3079. # so each multimodal chunk benefits from the chunk-level concurrency
  3080. # already enforced by extract_entities.
  3081. sidecar_block = chunk_dp.get("sidecar")
  3082. if isinstance(sidecar_block, dict):
  3083. sidecar_type = sidecar_block.get("type")
  3084. sidecar_id = sidecar_block.get("id")
  3085. if (
  3086. sidecar_type in {"drawing", "table", "equation"}
  3087. and isinstance(sidecar_id, str)
  3088. and sidecar_id
  3089. ):
  3090. mm_entity_name = sidecar_id
  3091. now_ts = int(time.time())
  3092. mm_nodes_list = maybe_nodes.setdefault(mm_entity_name, [])
  3093. mm_nodes_list.append(
  3094. {
  3095. "entity_name": mm_entity_name,
  3096. "entity_type": sidecar_type,
  3097. # description == the full multimodal chunk content so
  3098. # the extracted entity carries the same grounding
  3099. # surface the prompt produced; analyze_multimodal's
  3100. # description/name field is already inlined there.
  3101. "description": chunk_dp.get("content", "") or "",
  3102. "source_id": chunk_key,
  3103. "file_path": file_path,
  3104. "timestamp": now_ts,
  3105. }
  3106. )
  3107. heading_block = chunk_dp.get("heading")
  3108. heading_label = "unknown"
  3109. if isinstance(heading_block, dict):
  3110. heading_label = (
  3111. str(heading_block.get("heading") or "").strip() or "unknown"
  3112. )
  3113. mm_display_name = _parse_mm_display_name(
  3114. chunk_dp.get("content", "") or "", sidecar_id
  3115. )
  3116. for tgt in list(maybe_nodes.keys()):
  3117. if tgt == mm_entity_name:
  3118. continue
  3119. edge_key = (mm_entity_name, tgt)
  3120. edge_list = maybe_edges.setdefault(edge_key, [])
  3121. edge_list.append(
  3122. {
  3123. "src_id": mm_entity_name,
  3124. "tgt_id": tgt,
  3125. "weight": 1.0,
  3126. "description": (
  3127. f"{tgt} is associated with {sidecar_type} "
  3128. f"{mm_display_name} in section {heading_label} "
  3129. f'of document "{file_path}"'
  3130. ),
  3131. "keywords": "associated with, contained in",
  3132. "source_id": chunk_key,
  3133. "file_path": file_path,
  3134. "timestamp": now_ts,
  3135. }
  3136. )
  3137. # Batch update chunk's llm_cache_list with all collected cache keys
  3138. if cache_keys_collector and text_chunks_storage:
  3139. await update_chunk_cache_list(
  3140. chunk_key,
  3141. text_chunks_storage,
  3142. cache_keys_collector,
  3143. "entity_extraction",
  3144. )
  3145. processed_chunks += 1
  3146. entities_count = len(maybe_nodes)
  3147. relations_count = len(maybe_edges)
  3148. log_message = f"Chunk {processed_chunks} of {total_chunks} extracted {entities_count} Ent + {relations_count} Rel {chunk_key}"
  3149. logger.info(log_message)
  3150. if pipeline_status is not None:
  3151. async with pipeline_status_lock:
  3152. pipeline_status["latest_message"] = log_message
  3153. pipeline_status["history_messages"].append(log_message)
  3154. # Return the extracted nodes and edges for centralized processing
  3155. return maybe_nodes, maybe_edges
  3156. # Get max async tasks limit from global_config
  3157. chunk_max_async = global_config.get("llm_model_max_async", 4)
  3158. semaphore = asyncio.Semaphore(chunk_max_async)
  3159. async def _process_with_semaphore(chunk):
  3160. async with semaphore:
  3161. # Check for cancellation before processing chunk
  3162. if pipeline_status is not None and pipeline_status_lock is not None:
  3163. async with pipeline_status_lock:
  3164. if pipeline_status.get("cancellation_requested", False):
  3165. raise PipelineCancelledException(
  3166. "User cancelled during chunk processing"
  3167. )
  3168. try:
  3169. result = await _process_single_content(chunk)
  3170. # Yield once between chunk completions so API coroutines can resume
  3171. # even when many chunk tasks are hitting cache and finishing quickly.
  3172. await asyncio.sleep(0)
  3173. return result
  3174. except Exception as e:
  3175. chunk_id = chunk[0] # Extract chunk_id from chunk[0]
  3176. prefixed_exception = create_prefixed_exception(e, chunk_id)
  3177. raise prefixed_exception from e
  3178. tasks = []
  3179. for c in ordered_chunks:
  3180. task = asyncio.create_task(_process_with_semaphore(c))
  3181. tasks.append(task)
  3182. # Wait for tasks to complete or for the first exception to occur
  3183. # This allows us to cancel remaining tasks if any task fails
  3184. done, pending = await asyncio.wait(tasks, return_when=asyncio.FIRST_EXCEPTION)
  3185. # Check if any task raised an exception and ensure all exceptions are retrieved
  3186. first_exception = None
  3187. chunk_results = []
  3188. for task in done:
  3189. try:
  3190. exception = task.exception()
  3191. if exception is not None:
  3192. if first_exception is None:
  3193. first_exception = exception
  3194. else:
  3195. chunk_results.append(task.result())
  3196. except Exception as e:
  3197. if first_exception is None:
  3198. first_exception = e
  3199. # If any task failed, cancel all pending tasks and raise the first exception
  3200. if first_exception is not None:
  3201. # Cancel all pending tasks
  3202. for pending_task in pending:
  3203. pending_task.cancel()
  3204. # Wait for cancellation to complete
  3205. if pending:
  3206. await asyncio.wait(pending)
  3207. # Add progress prefix to the exception message
  3208. progress_prefix = f"C[{processed_chunks + 1}/{total_chunks}]"
  3209. # Re-raise the original exception with a prefix
  3210. prefixed_exception = create_prefixed_exception(first_exception, progress_prefix)
  3211. raise prefixed_exception from first_exception
  3212. # If all tasks completed successfully, chunk_results already contains the results
  3213. # Return the chunk_results for later processing in merge_nodes_and_edges
  3214. return chunk_results
  3215. async def kg_query(
  3216. query: str,
  3217. knowledge_graph_inst: BaseGraphStorage,
  3218. entities_vdb: BaseVectorStorage,
  3219. relationships_vdb: BaseVectorStorage,
  3220. text_chunks_db: BaseKVStorage,
  3221. query_param: QueryParam,
  3222. global_config: dict[str, str],
  3223. hashing_kv: BaseKVStorage | None = None,
  3224. system_prompt: str | None = None,
  3225. chunks_vdb: BaseVectorStorage = None,
  3226. ) -> QueryResult | None:
  3227. """
  3228. Execute knowledge graph query and return unified QueryResult object.
  3229. Args:
  3230. query: Query string
  3231. knowledge_graph_inst: Knowledge graph storage instance
  3232. entities_vdb: Entity vector database
  3233. relationships_vdb: Relationship vector database
  3234. text_chunks_db: Text chunks storage
  3235. query_param: Query parameters
  3236. global_config: Global configuration
  3237. hashing_kv: Cache storage
  3238. system_prompt: System prompt
  3239. chunks_vdb: Document chunks vector database
  3240. Returns:
  3241. QueryResult | None: Unified query result object containing:
  3242. - content: Non-streaming response text content
  3243. - response_iterator: Streaming response iterator
  3244. - raw_data: Complete structured data (including references and metadata)
  3245. - is_streaming: Whether this is a streaming result
  3246. Based on different query_param settings, different fields will be populated:
  3247. - only_need_context=True: content contains context string
  3248. - only_need_prompt=True: content contains complete prompt
  3249. - stream=True: response_iterator contains streaming response, raw_data contains complete data
  3250. - default: content contains LLM response text, raw_data contains complete data
  3251. Returns None when no relevant context could be constructed for the query.
  3252. """
  3253. if not query:
  3254. return QueryResult(content=PROMPTS["fail_response"])
  3255. # Apply higher priority (5) to query relation LLM function
  3256. use_model_func = partial(global_config["role_llm_funcs"]["query"], _priority=5)
  3257. llm_cache_identity = get_llm_cache_identity(global_config, "query")
  3258. hl_keywords, ll_keywords = await get_keywords_from_query(
  3259. query, query_param, global_config, hashing_kv
  3260. )
  3261. logger.debug(f"High-level keywords: {hl_keywords}")
  3262. logger.debug(f"Low-level keywords: {ll_keywords}")
  3263. # Handle empty keywords
  3264. if ll_keywords == [] and query_param.mode in ["local", "hybrid", "mix"]:
  3265. logger.warning("low_level_keywords is empty")
  3266. if hl_keywords == [] and query_param.mode in ["global", "hybrid", "mix"]:
  3267. logger.warning("high_level_keywords is empty")
  3268. if hl_keywords == [] and ll_keywords == []:
  3269. if len(query) < 50:
  3270. logger.warning(f"Forced low_level_keywords to origin query: {query}")
  3271. ll_keywords = [query]
  3272. else:
  3273. return QueryResult(content=PROMPTS["fail_response"])
  3274. ll_keywords_str = ", ".join(ll_keywords) if ll_keywords else ""
  3275. hl_keywords_str = ", ".join(hl_keywords) if hl_keywords else ""
  3276. # Build query context (unified interface)
  3277. context_result = await _build_query_context(
  3278. query,
  3279. ll_keywords_str,
  3280. hl_keywords_str,
  3281. knowledge_graph_inst,
  3282. entities_vdb,
  3283. relationships_vdb,
  3284. text_chunks_db,
  3285. query_param,
  3286. chunks_vdb,
  3287. )
  3288. if context_result is None:
  3289. logger.info("[kg_query] No query context could be built; returning no-result.")
  3290. return None
  3291. # Return different content based on query parameters
  3292. if query_param.only_need_context and not query_param.only_need_prompt:
  3293. return QueryResult(
  3294. content=context_result.context, raw_data=context_result.raw_data
  3295. )
  3296. user_prompt = f"\n\n{query_param.user_prompt}" if query_param.user_prompt else "n/a"
  3297. response_type = (
  3298. query_param.response_type
  3299. if query_param.response_type
  3300. else "Multiple Paragraphs"
  3301. )
  3302. # Build system prompt
  3303. sys_prompt_temp = system_prompt if system_prompt else PROMPTS["rag_response"]
  3304. sys_prompt = sys_prompt_temp.format(
  3305. response_type=response_type,
  3306. user_prompt=user_prompt,
  3307. context_data=context_result.context,
  3308. )
  3309. user_query = query
  3310. if query_param.only_need_prompt:
  3311. prompt_content = "\n\n".join([sys_prompt, "---User Query---", user_query])
  3312. return QueryResult(content=prompt_content, raw_data=context_result.raw_data)
  3313. # Call LLM
  3314. tokenizer: Tokenizer = global_config["tokenizer"]
  3315. len_of_prompts = len(tokenizer.encode(query + sys_prompt))
  3316. logger.debug(
  3317. f"[kg_query] Sending to LLM: {len_of_prompts:,} tokens (Query: {len(tokenizer.encode(query))}, System: {len(tokenizer.encode(sys_prompt))})"
  3318. )
  3319. # Handle cache
  3320. args_hash = compute_args_hash(
  3321. query_param.mode,
  3322. query,
  3323. query_param.response_type,
  3324. query_param.top_k,
  3325. query_param.chunk_top_k,
  3326. query_param.max_entity_tokens,
  3327. query_param.max_relation_tokens,
  3328. query_param.max_total_tokens,
  3329. hl_keywords_str,
  3330. ll_keywords_str,
  3331. query_param.user_prompt or "",
  3332. query_param.enable_rerank,
  3333. "\n<llm_identity>\n",
  3334. serialize_llm_cache_identity(llm_cache_identity),
  3335. )
  3336. cached_result = await handle_cache(
  3337. hashing_kv, args_hash, user_query, query_param.mode, cache_type="query"
  3338. )
  3339. if cached_result is not None:
  3340. cached_response, _ = cached_result # Extract content, ignore timestamp
  3341. logger.info(
  3342. " == LLM cache == Query cache hit, using cached response as query result"
  3343. )
  3344. response = cached_response
  3345. else:
  3346. response = await use_model_func(
  3347. user_query,
  3348. system_prompt=sys_prompt,
  3349. history_messages=query_param.conversation_history,
  3350. enable_cot=True,
  3351. stream=query_param.stream,
  3352. )
  3353. if hashing_kv and hashing_kv.global_config.get("enable_llm_cache"):
  3354. queryparam_dict = {
  3355. "mode": query_param.mode,
  3356. "response_type": query_param.response_type,
  3357. "top_k": query_param.top_k,
  3358. "chunk_top_k": query_param.chunk_top_k,
  3359. "max_entity_tokens": query_param.max_entity_tokens,
  3360. "max_relation_tokens": query_param.max_relation_tokens,
  3361. "max_total_tokens": query_param.max_total_tokens,
  3362. "hl_keywords": hl_keywords_str,
  3363. "ll_keywords": ll_keywords_str,
  3364. "user_prompt": query_param.user_prompt or "",
  3365. "enable_rerank": query_param.enable_rerank,
  3366. }
  3367. await save_to_cache(
  3368. hashing_kv,
  3369. CacheData(
  3370. args_hash=args_hash,
  3371. content=response,
  3372. prompt=query,
  3373. mode=query_param.mode,
  3374. cache_type="query",
  3375. queryparam=queryparam_dict,
  3376. ),
  3377. )
  3378. # Return unified result based on actual response type
  3379. if isinstance(response, str):
  3380. # Non-streaming response (string)
  3381. if len(response) > len(sys_prompt):
  3382. response = (
  3383. response.replace(sys_prompt, "")
  3384. .replace("user", "")
  3385. .replace("model", "")
  3386. .replace(query, "")
  3387. .replace("<system>", "")
  3388. .replace("</system>", "")
  3389. .strip()
  3390. )
  3391. return QueryResult(content=response, raw_data=context_result.raw_data)
  3392. else:
  3393. # Streaming response (AsyncIterator)
  3394. return QueryResult(
  3395. response_iterator=response,
  3396. raw_data=context_result.raw_data,
  3397. is_streaming=True,
  3398. )
  3399. async def get_keywords_from_query(
  3400. query: str,
  3401. query_param: QueryParam,
  3402. global_config: dict[str, str],
  3403. hashing_kv: BaseKVStorage | None = None,
  3404. ) -> tuple[list[str], list[str]]:
  3405. """
  3406. Retrieves high-level and low-level keywords for RAG operations.
  3407. This function checks if keywords are already provided in query parameters,
  3408. and if not, extracts them from the query text using LLM.
  3409. Args:
  3410. query: The user's query text
  3411. query_param: Query parameters that may contain pre-defined keywords
  3412. global_config: Global configuration dictionary
  3413. hashing_kv: Optional key-value storage for caching results
  3414. Returns:
  3415. A tuple containing (high_level_keywords, low_level_keywords)
  3416. """
  3417. # Check if pre-defined keywords are already provided
  3418. if query_param.hl_keywords or query_param.ll_keywords:
  3419. return query_param.hl_keywords, query_param.ll_keywords
  3420. # Extract keywords directly from the current query text.
  3421. hl_keywords, ll_keywords = await extract_keywords_only(
  3422. query, query_param, global_config, hashing_kv
  3423. )
  3424. return hl_keywords, ll_keywords
  3425. def _normalize_keyword_list(raw_values: Any, field_name: str) -> list[str]:
  3426. """Normalize keyword payloads into a clean list of strings.
  3427. When the field is a plain string (e.g. LLM returned CSV), split on
  3428. newlines/commas/semicolons. List-shaped payloads are preserved per-item so
  3429. multi-word phrases that legitimately contain commas are not broken apart.
  3430. """
  3431. if raw_values is None:
  3432. return []
  3433. if isinstance(raw_values, str):
  3434. raw_values = [
  3435. part.strip()
  3436. for part in re.split(r"[\n,;]+", raw_values)
  3437. if part and part.strip()
  3438. ]
  3439. if not isinstance(raw_values, list):
  3440. logger.warning(
  3441. "Keyword extraction field '%s' is not a list: %r",
  3442. field_name,
  3443. raw_values,
  3444. )
  3445. return []
  3446. normalized: list[str] = []
  3447. for idx, value in enumerate(raw_values):
  3448. if isinstance(value, str):
  3449. cleaned = value.strip()
  3450. if cleaned:
  3451. normalized.append(cleaned)
  3452. continue
  3453. logger.warning(
  3454. "Keyword extraction field '%s' contains non-string element at index %d: %r",
  3455. field_name,
  3456. idx,
  3457. value,
  3458. )
  3459. return normalized
  3460. _CODE_FENCE_PATTERN = re.compile(
  3461. r"^\s*```(?:json|JSON)?\s*\n?(.*?)\n?\s*```\s*$", re.DOTALL
  3462. )
  3463. def _strip_markdown_code_fence(text: str) -> str:
  3464. """Strip a surrounding markdown code fence (```json ... ``` or ``` ... ```).
  3465. Why: LLM training priors strongly associate "JSON output" with fenced code
  3466. blocks, so providers routinely wrap responses despite explicit instructions
  3467. to the contrary. Stripping here avoids relying on ``json_repair`` and the
  3468. noisy warning it emits.
  3469. """
  3470. match = _CODE_FENCE_PATTERN.match(text)
  3471. return match.group(1) if match else text
  3472. def _parse_keywords_payload(result: Any) -> tuple[bool, list[str], list[str]]:
  3473. """Parse keyword extraction responses from heterogeneous provider outputs."""
  3474. payload: Any
  3475. if result is None:
  3476. return False, [], []
  3477. if hasattr(result, "model_dump") and callable(result.model_dump):
  3478. payload = result.model_dump()
  3479. elif isinstance(result, dict):
  3480. payload = result
  3481. elif isinstance(result, str):
  3482. cleaned_result = remove_think_tags(result)
  3483. unfenced_result = _strip_markdown_code_fence(cleaned_result)
  3484. if unfenced_result is not cleaned_result:
  3485. logger.debug(
  3486. "Stripped markdown code fence from keyword extraction response"
  3487. )
  3488. cleaned_result = unfenced_result
  3489. try:
  3490. payload = json.loads(cleaned_result)
  3491. except json.JSONDecodeError as strict_error:
  3492. try:
  3493. payload = json_repair.loads(cleaned_result)
  3494. logger.warning(
  3495. "Keyword extraction response required JSON repair: %s; response: %r",
  3496. strict_error,
  3497. cleaned_result[:500],
  3498. )
  3499. except Exception as repair_error:
  3500. logger.error(
  3501. "JSON parsing error: %s; repair failed: %s; response: %r",
  3502. strict_error,
  3503. repair_error,
  3504. cleaned_result[:500],
  3505. )
  3506. return False, [], []
  3507. else:
  3508. logger.error(
  3509. "Unsupported keyword extraction response type: %s",
  3510. type(result).__name__,
  3511. )
  3512. return False, [], []
  3513. if not isinstance(payload, dict):
  3514. logger.error(
  3515. "Keyword extraction payload is not a JSON object: %s",
  3516. type(payload).__name__,
  3517. )
  3518. return False, [], []
  3519. hl_keywords = _normalize_keyword_list(
  3520. payload.get("high_level_keywords"), "high_level_keywords"
  3521. )
  3522. ll_keywords = _normalize_keyword_list(
  3523. payload.get("low_level_keywords"), "low_level_keywords"
  3524. )
  3525. return True, hl_keywords, ll_keywords
  3526. async def extract_keywords_only(
  3527. text: str,
  3528. param: QueryParam,
  3529. global_config: dict[str, str],
  3530. hashing_kv: BaseKVStorage | None = None,
  3531. ) -> tuple[list[str], list[str]]:
  3532. """
  3533. Extract high-level and low-level keywords from the given 'text' using the LLM.
  3534. This method does NOT build the final RAG context or provide a final answer.
  3535. It ONLY extracts keywords (hl_keywords, ll_keywords).
  3536. """
  3537. # 1. Build the examples
  3538. examples = "\n".join(PROMPTS["keywords_extraction_examples"])
  3539. addon_params = global_config.get("addon_params") or {}
  3540. language = global_config.get("_resolved_summary_language")
  3541. if language is None:
  3542. language = addon_params.get("language", DEFAULT_SUMMARY_LANGUAGE)
  3543. # 2. Handle cache if needed - add cache type for keywords
  3544. llm_cache_identity = get_llm_cache_identity(global_config, "keyword")
  3545. args_hash = compute_args_hash(
  3546. param.mode,
  3547. text,
  3548. language,
  3549. "\n<llm_identity>\n",
  3550. serialize_llm_cache_identity(llm_cache_identity),
  3551. )
  3552. cached_result = await handle_cache(
  3553. hashing_kv, args_hash, text, param.mode, cache_type="keywords"
  3554. )
  3555. if cached_result is not None:
  3556. cached_response, _ = cached_result # Extract content, ignore timestamp
  3557. is_valid_payload, hl_keywords, ll_keywords = _parse_keywords_payload(
  3558. cached_response
  3559. )
  3560. if is_valid_payload:
  3561. return hl_keywords, ll_keywords
  3562. else:
  3563. logger.warning(
  3564. "Invalid cache format for keywords, proceeding with extraction"
  3565. )
  3566. # 3. Build the keyword-extraction prompt
  3567. kw_prompt = PROMPTS["keywords_extraction"].format(
  3568. query=text,
  3569. examples=examples,
  3570. language=language,
  3571. )
  3572. tokenizer: Tokenizer = global_config["tokenizer"]
  3573. len_of_prompts = len(tokenizer.encode(kw_prompt))
  3574. logger.debug(
  3575. f"[extract_keywords] Sending to LLM: {len_of_prompts:,} tokens (Prompt: {len_of_prompts})"
  3576. )
  3577. # 4. Call the LLM for keyword extraction
  3578. # Apply higher priority (5) to query relation LLM function
  3579. use_model_func = partial(global_config["role_llm_funcs"]["keyword"], _priority=5)
  3580. result = await use_model_func(kw_prompt, response_format={"type": "json_object"})
  3581. # 5. Parse out JSON from the LLM response with tolerant provider normalization
  3582. _, hl_keywords, ll_keywords = _parse_keywords_payload(result)
  3583. # 6. Cache only the processed keywords with cache type
  3584. if hl_keywords or ll_keywords:
  3585. cache_data = {
  3586. "high_level_keywords": hl_keywords,
  3587. "low_level_keywords": ll_keywords,
  3588. }
  3589. if hashing_kv and hashing_kv.global_config.get("enable_llm_cache"):
  3590. # Save to cache with query parameters
  3591. queryparam_dict = {
  3592. "mode": param.mode,
  3593. "response_type": param.response_type,
  3594. "top_k": param.top_k,
  3595. "chunk_top_k": param.chunk_top_k,
  3596. "max_entity_tokens": param.max_entity_tokens,
  3597. "max_relation_tokens": param.max_relation_tokens,
  3598. "max_total_tokens": param.max_total_tokens,
  3599. "user_prompt": param.user_prompt or "",
  3600. "enable_rerank": param.enable_rerank,
  3601. }
  3602. await save_to_cache(
  3603. hashing_kv,
  3604. CacheData(
  3605. args_hash=args_hash,
  3606. content=json.dumps(cache_data),
  3607. prompt=text,
  3608. mode=param.mode,
  3609. cache_type="keywords",
  3610. queryparam=queryparam_dict,
  3611. ),
  3612. )
  3613. return hl_keywords, ll_keywords
  3614. async def _get_vector_context(
  3615. query: str,
  3616. chunks_vdb: BaseVectorStorage,
  3617. query_param: QueryParam,
  3618. query_embedding: list[float] = None,
  3619. ) -> list[dict]:
  3620. """
  3621. Retrieve text chunks from the vector database without reranking or truncation.
  3622. This function performs vector search to find relevant text chunks for a query.
  3623. Reranking and truncation will be handled later in the unified processing.
  3624. Args:
  3625. query: The query string to search for
  3626. chunks_vdb: Vector database containing document chunks
  3627. query_param: Query parameters including chunk_top_k and ids
  3628. query_embedding: Optional pre-computed query embedding to avoid redundant embedding calls
  3629. Returns:
  3630. List of text chunks with metadata
  3631. """
  3632. try:
  3633. # Use chunk_top_k if specified, otherwise fall back to top_k
  3634. search_top_k = query_param.chunk_top_k or query_param.top_k
  3635. cosine_threshold = chunks_vdb.cosine_better_than_threshold
  3636. results = await chunks_vdb.query(
  3637. query, top_k=search_top_k, query_embedding=query_embedding
  3638. )
  3639. if not results:
  3640. logger.info(
  3641. f"Naive query: 0 chunks (chunk_top_k:{search_top_k} cosine:{cosine_threshold})"
  3642. )
  3643. return []
  3644. valid_chunks = []
  3645. for result in results:
  3646. if "content" in result:
  3647. chunk_with_metadata = {
  3648. "content": result["content"],
  3649. "created_at": result.get("created_at", None),
  3650. "file_path": result.get("file_path", "unknown_source"),
  3651. "source_type": "vector", # Mark the source type
  3652. "chunk_id": result.get("id"), # Add chunk_id for deduplication
  3653. }
  3654. valid_chunks.append(chunk_with_metadata)
  3655. logger.info(
  3656. f"Naive query: {len(valid_chunks)} chunks (chunk_top_k:{search_top_k} cosine:{cosine_threshold})"
  3657. )
  3658. return valid_chunks
  3659. except Exception as e:
  3660. logger.error(f"Error in _get_vector_context: {e}")
  3661. return []
  3662. async def _perform_kg_search(
  3663. query: str,
  3664. ll_keywords: str,
  3665. hl_keywords: str,
  3666. knowledge_graph_inst: BaseGraphStorage,
  3667. entities_vdb: BaseVectorStorage,
  3668. relationships_vdb: BaseVectorStorage,
  3669. text_chunks_db: BaseKVStorage,
  3670. query_param: QueryParam,
  3671. chunks_vdb: BaseVectorStorage = None,
  3672. ) -> dict[str, Any]:
  3673. """
  3674. Pure search logic that retrieves raw entities, relations, and vector chunks.
  3675. No token truncation or formatting - just raw search results.
  3676. """
  3677. # Initialize result containers
  3678. local_entities = []
  3679. local_relations = []
  3680. global_entities = []
  3681. global_relations = []
  3682. vector_chunks = []
  3683. chunk_tracking = {}
  3684. # Handle different query modes
  3685. # Track chunk sources and metadata for final logging
  3686. chunk_tracking = {} # chunk_id -> {source, frequency, order}
  3687. # Pre-compute embeddings needed by the selected mode in a single batch call.
  3688. # Only embed texts that the active retrieval branches will actually use:
  3689. # - query → used by _get_vector_context (chunks VDB)
  3690. # - ll_keywords → used by _get_node_data (entities VDB) in local/hybrid/mix
  3691. # - hl_keywords → used by _get_edge_data (relationships VDB) in global/hybrid/mix
  3692. # Batching avoids 2-3 sequential API round-trips.
  3693. kg_chunk_pick_method = text_chunks_db.global_config.get(
  3694. "kg_chunk_pick_method", DEFAULT_KG_CHUNK_PICK_METHOD
  3695. )
  3696. actual_embedding_func = text_chunks_db.embedding_func
  3697. query_embedding = None
  3698. ll_embedding = None
  3699. hl_embedding = None
  3700. mode = query_param.mode
  3701. need_ll = mode in ("local", "hybrid", "mix") and bool(ll_keywords)
  3702. need_hl = mode in ("global", "hybrid", "mix") and bool(hl_keywords)
  3703. if actual_embedding_func:
  3704. texts_to_embed: list[str] = []
  3705. text_purposes: list[str] = []
  3706. if query and (kg_chunk_pick_method == "VECTOR" or chunks_vdb):
  3707. texts_to_embed.append(query)
  3708. text_purposes.append("query")
  3709. if need_ll:
  3710. texts_to_embed.append(ll_keywords)
  3711. text_purposes.append("ll")
  3712. if need_hl:
  3713. texts_to_embed.append(hl_keywords)
  3714. text_purposes.append("hl")
  3715. if texts_to_embed:
  3716. try:
  3717. all_embeddings = await actual_embedding_func(
  3718. texts_to_embed, context="query", _priority=5
  3719. )
  3720. for i, purpose in enumerate(text_purposes):
  3721. if purpose == "query":
  3722. query_embedding = all_embeddings[i]
  3723. elif purpose == "ll":
  3724. ll_embedding = all_embeddings[i]
  3725. elif purpose == "hl":
  3726. hl_embedding = all_embeddings[i]
  3727. logger.debug(
  3728. "Pre-computed %d embeddings in single batch (purposes: %s)",
  3729. len(texts_to_embed),
  3730. ", ".join(text_purposes),
  3731. )
  3732. except Exception as e:
  3733. logger.warning(f"Failed to batch pre-compute embeddings: {e}")
  3734. # Handle local and global modes
  3735. if query_param.mode == "local" and len(ll_keywords) > 0:
  3736. local_entities, local_relations = await _get_node_data(
  3737. ll_keywords,
  3738. knowledge_graph_inst,
  3739. entities_vdb,
  3740. query_param,
  3741. query_embedding=ll_embedding,
  3742. )
  3743. elif query_param.mode == "global" and len(hl_keywords) > 0:
  3744. global_relations, global_entities = await _get_edge_data(
  3745. hl_keywords,
  3746. knowledge_graph_inst,
  3747. relationships_vdb,
  3748. query_param,
  3749. query_embedding=hl_embedding,
  3750. )
  3751. else: # hybrid or mix mode
  3752. if len(ll_keywords) > 0:
  3753. local_entities, local_relations = await _get_node_data(
  3754. ll_keywords,
  3755. knowledge_graph_inst,
  3756. entities_vdb,
  3757. query_param,
  3758. query_embedding=ll_embedding,
  3759. )
  3760. if len(hl_keywords) > 0:
  3761. global_relations, global_entities = await _get_edge_data(
  3762. hl_keywords,
  3763. knowledge_graph_inst,
  3764. relationships_vdb,
  3765. query_param,
  3766. query_embedding=hl_embedding,
  3767. )
  3768. # Get vector chunks for mix mode
  3769. if query_param.mode == "mix" and chunks_vdb:
  3770. vector_chunks = await _get_vector_context(
  3771. query,
  3772. chunks_vdb,
  3773. query_param,
  3774. query_embedding,
  3775. )
  3776. # Track vector chunks with source metadata
  3777. for i, chunk in enumerate(vector_chunks):
  3778. chunk_id = chunk.get("chunk_id") or chunk.get("id")
  3779. if chunk_id:
  3780. chunk_tracking[chunk_id] = {
  3781. "source": "C",
  3782. "frequency": 1, # Vector chunks always have frequency 1
  3783. "order": i + 1, # 1-based order in vector search results
  3784. }
  3785. else:
  3786. logger.warning(f"Vector chunk missing chunk_id: {chunk}")
  3787. # Round-robin merge entities
  3788. final_entities = []
  3789. seen_entities = set()
  3790. max_len = max(len(local_entities), len(global_entities))
  3791. for i in range(max_len):
  3792. # First from local
  3793. if i < len(local_entities):
  3794. entity = local_entities[i]
  3795. entity_name = entity.get("entity_name")
  3796. if entity_name and entity_name not in seen_entities:
  3797. final_entities.append(entity)
  3798. seen_entities.add(entity_name)
  3799. # Then from global
  3800. if i < len(global_entities):
  3801. entity = global_entities[i]
  3802. entity_name = entity.get("entity_name")
  3803. if entity_name and entity_name not in seen_entities:
  3804. final_entities.append(entity)
  3805. seen_entities.add(entity_name)
  3806. # Round-robin merge relations
  3807. final_relations = []
  3808. seen_relations = set()
  3809. max_len = max(len(local_relations), len(global_relations))
  3810. for i in range(max_len):
  3811. # First from local
  3812. if i < len(local_relations):
  3813. relation = local_relations[i]
  3814. # Build relation unique identifier
  3815. if "src_tgt" in relation:
  3816. rel_key = tuple(sorted(relation["src_tgt"]))
  3817. else:
  3818. rel_key = tuple(
  3819. sorted([relation.get("src_id"), relation.get("tgt_id")])
  3820. )
  3821. if rel_key not in seen_relations:
  3822. final_relations.append(relation)
  3823. seen_relations.add(rel_key)
  3824. # Then from global
  3825. if i < len(global_relations):
  3826. relation = global_relations[i]
  3827. # Build relation unique identifier
  3828. if "src_tgt" in relation:
  3829. rel_key = tuple(sorted(relation["src_tgt"]))
  3830. else:
  3831. rel_key = tuple(
  3832. sorted([relation.get("src_id"), relation.get("tgt_id")])
  3833. )
  3834. if rel_key not in seen_relations:
  3835. final_relations.append(relation)
  3836. seen_relations.add(rel_key)
  3837. logger.info(
  3838. f"Raw search results: {len(final_entities)} entities, {len(final_relations)} relations, {len(vector_chunks)} vector chunks"
  3839. )
  3840. return {
  3841. "final_entities": final_entities,
  3842. "final_relations": final_relations,
  3843. "vector_chunks": vector_chunks,
  3844. "chunk_tracking": chunk_tracking,
  3845. "query_embedding": query_embedding,
  3846. }
  3847. async def _apply_token_truncation(
  3848. search_result: dict[str, Any],
  3849. query_param: QueryParam,
  3850. global_config: dict[str, str],
  3851. ) -> dict[str, Any]:
  3852. """
  3853. Apply token-based truncation to entities and relations for LLM efficiency.
  3854. """
  3855. tokenizer = global_config.get("tokenizer")
  3856. if not tokenizer:
  3857. logger.warning("No tokenizer found, skipping truncation")
  3858. return {
  3859. "entities_context": [],
  3860. "relations_context": [],
  3861. "filtered_entities": search_result["final_entities"],
  3862. "filtered_relations": search_result["final_relations"],
  3863. "entity_id_to_original": {},
  3864. "relation_id_to_original": {},
  3865. }
  3866. # Get token limits from query_param with fallbacks
  3867. max_entity_tokens = getattr(
  3868. query_param,
  3869. "max_entity_tokens",
  3870. global_config.get("max_entity_tokens", DEFAULT_MAX_ENTITY_TOKENS),
  3871. )
  3872. max_relation_tokens = getattr(
  3873. query_param,
  3874. "max_relation_tokens",
  3875. global_config.get("max_relation_tokens", DEFAULT_MAX_RELATION_TOKENS),
  3876. )
  3877. final_entities = search_result["final_entities"]
  3878. final_relations = search_result["final_relations"]
  3879. # Create mappings from entity/relation identifiers to original data
  3880. entity_id_to_original = {}
  3881. relation_id_to_original = {}
  3882. # Generate entities context for truncation
  3883. entities_context = []
  3884. for i, entity in enumerate(final_entities):
  3885. entity_name = entity["entity_name"]
  3886. created_at = entity.get("created_at", "UNKNOWN")
  3887. if isinstance(created_at, (int, float)):
  3888. created_at = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(created_at))
  3889. # Store mapping from entity name to original data
  3890. entity_id_to_original[entity_name] = entity
  3891. entities_context.append(
  3892. {
  3893. "entity": entity_name,
  3894. "type": entity.get("entity_type", "UNKNOWN"),
  3895. "description": entity.get("description", "UNKNOWN"),
  3896. "created_at": created_at,
  3897. "file_path": entity.get("file_path", "unknown_source"),
  3898. }
  3899. )
  3900. # Generate relations context for truncation
  3901. relations_context = []
  3902. for i, relation in enumerate(final_relations):
  3903. created_at = relation.get("created_at", "UNKNOWN")
  3904. if isinstance(created_at, (int, float)):
  3905. created_at = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(created_at))
  3906. # Handle different relation data formats
  3907. if "src_tgt" in relation:
  3908. entity1, entity2 = relation["src_tgt"]
  3909. else:
  3910. entity1, entity2 = relation.get("src_id"), relation.get("tgt_id")
  3911. # Store mapping from relation pair to original data
  3912. relation_key = (entity1, entity2)
  3913. relation_id_to_original[relation_key] = relation
  3914. relations_context.append(
  3915. {
  3916. "entity1": entity1,
  3917. "entity2": entity2,
  3918. "description": relation.get("description", "UNKNOWN"),
  3919. "created_at": created_at,
  3920. "file_path": relation.get("file_path", "unknown_source"),
  3921. }
  3922. )
  3923. logger.debug(
  3924. f"Before truncation: {len(entities_context)} entities, {len(relations_context)} relations"
  3925. )
  3926. # Apply token-based truncation
  3927. if entities_context:
  3928. # Remove file_path and created_at for token calculation
  3929. entities_context_for_truncation = []
  3930. for entity in entities_context:
  3931. entity_copy = entity.copy()
  3932. entity_copy.pop("file_path", None)
  3933. entity_copy.pop("created_at", None)
  3934. entities_context_for_truncation.append(entity_copy)
  3935. entities_context = truncate_list_by_token_size(
  3936. entities_context_for_truncation,
  3937. key=lambda x: "\n".join(
  3938. json.dumps(item, ensure_ascii=False) for item in [x]
  3939. ),
  3940. max_token_size=max_entity_tokens,
  3941. tokenizer=tokenizer,
  3942. )
  3943. if relations_context:
  3944. # Remove file_path and created_at for token calculation
  3945. relations_context_for_truncation = []
  3946. for relation in relations_context:
  3947. relation_copy = relation.copy()
  3948. relation_copy.pop("file_path", None)
  3949. relation_copy.pop("created_at", None)
  3950. relations_context_for_truncation.append(relation_copy)
  3951. relations_context = truncate_list_by_token_size(
  3952. relations_context_for_truncation,
  3953. key=lambda x: "\n".join(
  3954. json.dumps(item, ensure_ascii=False) for item in [x]
  3955. ),
  3956. max_token_size=max_relation_tokens,
  3957. tokenizer=tokenizer,
  3958. )
  3959. logger.info(
  3960. f"After truncation: {len(entities_context)} entities, {len(relations_context)} relations"
  3961. )
  3962. # Create filtered original data based on truncated context
  3963. filtered_entities = []
  3964. filtered_entity_id_to_original = {}
  3965. if entities_context:
  3966. final_entity_names = {e["entity"] for e in entities_context}
  3967. seen_nodes = set()
  3968. for entity in final_entities:
  3969. name = entity.get("entity_name")
  3970. if name in final_entity_names and name not in seen_nodes:
  3971. filtered_entities.append(entity)
  3972. filtered_entity_id_to_original[name] = entity
  3973. seen_nodes.add(name)
  3974. filtered_relations = []
  3975. filtered_relation_id_to_original = {}
  3976. if relations_context:
  3977. final_relation_pairs = {(r["entity1"], r["entity2"]) for r in relations_context}
  3978. seen_edges = set()
  3979. for relation in final_relations:
  3980. src, tgt = relation.get("src_id"), relation.get("tgt_id")
  3981. if src is None or tgt is None:
  3982. src, tgt = relation.get("src_tgt", (None, None))
  3983. pair = (src, tgt)
  3984. if pair in final_relation_pairs and pair not in seen_edges:
  3985. filtered_relations.append(relation)
  3986. filtered_relation_id_to_original[pair] = relation
  3987. seen_edges.add(pair)
  3988. return {
  3989. "entities_context": entities_context,
  3990. "relations_context": relations_context,
  3991. "filtered_entities": filtered_entities,
  3992. "filtered_relations": filtered_relations,
  3993. "entity_id_to_original": filtered_entity_id_to_original,
  3994. "relation_id_to_original": filtered_relation_id_to_original,
  3995. }
  3996. async def _merge_all_chunks(
  3997. filtered_entities: list[dict],
  3998. filtered_relations: list[dict],
  3999. vector_chunks: list[dict],
  4000. query: str = "",
  4001. knowledge_graph_inst: BaseGraphStorage = None,
  4002. text_chunks_db: BaseKVStorage = None,
  4003. query_param: QueryParam = None,
  4004. chunks_vdb: BaseVectorStorage = None,
  4005. chunk_tracking: dict = None,
  4006. query_embedding: list[float] = None,
  4007. ) -> list[dict]:
  4008. """
  4009. Merge chunks from different sources: vector_chunks + entity_chunks + relation_chunks.
  4010. """
  4011. if chunk_tracking is None:
  4012. chunk_tracking = {}
  4013. # Get chunks from entities
  4014. entity_chunks = []
  4015. if filtered_entities and text_chunks_db:
  4016. entity_chunks = await _find_related_text_unit_from_entities(
  4017. filtered_entities,
  4018. query_param,
  4019. text_chunks_db,
  4020. knowledge_graph_inst,
  4021. query,
  4022. chunks_vdb,
  4023. chunk_tracking=chunk_tracking,
  4024. query_embedding=query_embedding,
  4025. )
  4026. # Get chunks from relations
  4027. relation_chunks = []
  4028. if filtered_relations and text_chunks_db:
  4029. relation_chunks = await _find_related_text_unit_from_relations(
  4030. filtered_relations,
  4031. query_param,
  4032. text_chunks_db,
  4033. entity_chunks, # For deduplication
  4034. query,
  4035. chunks_vdb,
  4036. chunk_tracking=chunk_tracking,
  4037. query_embedding=query_embedding,
  4038. )
  4039. # Round-robin merge chunks from different sources with deduplication
  4040. merged_chunks = []
  4041. seen_chunk_ids = set()
  4042. max_len = max(len(vector_chunks), len(entity_chunks), len(relation_chunks))
  4043. origin_len = len(vector_chunks) + len(entity_chunks) + len(relation_chunks)
  4044. for i in range(max_len):
  4045. # Add from vector chunks first (Naive mode)
  4046. if i < len(vector_chunks):
  4047. chunk = vector_chunks[i]
  4048. chunk_id = chunk.get("chunk_id") or chunk.get("id")
  4049. if chunk_id and chunk_id not in seen_chunk_ids:
  4050. seen_chunk_ids.add(chunk_id)
  4051. merged_chunks.append(
  4052. {
  4053. "content": chunk["content"],
  4054. "file_path": chunk.get("file_path", "unknown_source"),
  4055. "chunk_id": chunk_id,
  4056. }
  4057. )
  4058. # Add from entity chunks (Local mode)
  4059. if i < len(entity_chunks):
  4060. chunk = entity_chunks[i]
  4061. chunk_id = chunk.get("chunk_id") or chunk.get("id")
  4062. if chunk_id and chunk_id not in seen_chunk_ids:
  4063. seen_chunk_ids.add(chunk_id)
  4064. merged_chunks.append(
  4065. {
  4066. "content": chunk["content"],
  4067. "file_path": chunk.get("file_path", "unknown_source"),
  4068. "chunk_id": chunk_id,
  4069. }
  4070. )
  4071. # Add from relation chunks (Global mode)
  4072. if i < len(relation_chunks):
  4073. chunk = relation_chunks[i]
  4074. chunk_id = chunk.get("chunk_id") or chunk.get("id")
  4075. if chunk_id and chunk_id not in seen_chunk_ids:
  4076. seen_chunk_ids.add(chunk_id)
  4077. merged_chunks.append(
  4078. {
  4079. "content": chunk["content"],
  4080. "file_path": chunk.get("file_path", "unknown_source"),
  4081. "chunk_id": chunk_id,
  4082. }
  4083. )
  4084. logger.info(
  4085. f"Round-robin merged chunks: {origin_len} -> {len(merged_chunks)} (deduplicated {origin_len - len(merged_chunks)})"
  4086. )
  4087. return merged_chunks
  4088. async def _build_context_str(
  4089. entities_context: list[dict],
  4090. relations_context: list[dict],
  4091. merged_chunks: list[dict],
  4092. query: str,
  4093. query_param: QueryParam,
  4094. global_config: dict[str, str],
  4095. chunk_tracking: dict = None,
  4096. entity_id_to_original: dict = None,
  4097. relation_id_to_original: dict = None,
  4098. ) -> tuple[str, dict[str, Any]]:
  4099. """
  4100. Build the final LLM context string with token processing.
  4101. This includes dynamic token calculation and final chunk truncation.
  4102. """
  4103. tokenizer = global_config.get("tokenizer")
  4104. if not tokenizer:
  4105. logger.error("Missing tokenizer, cannot build LLM context")
  4106. # Return empty raw data structure when no tokenizer
  4107. empty_raw_data = convert_to_user_format(
  4108. [],
  4109. [],
  4110. [],
  4111. [],
  4112. query_param.mode,
  4113. )
  4114. empty_raw_data["status"] = "failure"
  4115. empty_raw_data["message"] = "Missing tokenizer, cannot build LLM context."
  4116. return "", empty_raw_data
  4117. # Get token limits
  4118. max_total_tokens = getattr(
  4119. query_param,
  4120. "max_total_tokens",
  4121. global_config.get("max_total_tokens", DEFAULT_MAX_TOTAL_TOKENS),
  4122. )
  4123. # Get the system prompt template from PROMPTS or global_config
  4124. sys_prompt_template = global_config.get(
  4125. "system_prompt_template", PROMPTS["rag_response"]
  4126. )
  4127. kg_context_template = PROMPTS["kg_query_context"]
  4128. user_prompt = query_param.user_prompt if query_param.user_prompt else ""
  4129. response_type = (
  4130. query_param.response_type
  4131. if query_param.response_type
  4132. else "Multiple Paragraphs"
  4133. )
  4134. entities_str = "\n".join(
  4135. json.dumps(entity, ensure_ascii=False) for entity in entities_context
  4136. )
  4137. relations_str = "\n".join(
  4138. json.dumps(relation, ensure_ascii=False) for relation in relations_context
  4139. )
  4140. # Calculate preliminary kg context tokens
  4141. pre_kg_context = kg_context_template.format(
  4142. entities_str=entities_str,
  4143. relations_str=relations_str,
  4144. text_chunks_str="",
  4145. reference_list_str="",
  4146. )
  4147. kg_context_tokens = len(tokenizer.encode(pre_kg_context))
  4148. # Calculate preliminary system prompt tokens
  4149. pre_sys_prompt = sys_prompt_template.format(
  4150. context_data="", # Empty for overhead calculation
  4151. response_type=response_type,
  4152. user_prompt=user_prompt,
  4153. )
  4154. sys_prompt_tokens = len(tokenizer.encode(pre_sys_prompt))
  4155. # Calculate available tokens for text chunks
  4156. query_tokens = len(tokenizer.encode(query))
  4157. buffer_tokens = 200 # reserved for reference list and safety buffer
  4158. available_chunk_tokens = max_total_tokens - (
  4159. sys_prompt_tokens + kg_context_tokens + query_tokens + buffer_tokens
  4160. )
  4161. logger.debug(
  4162. f"Token allocation - Total: {max_total_tokens}, SysPrompt: {sys_prompt_tokens}, Query: {query_tokens}, KG: {kg_context_tokens}, Buffer: {buffer_tokens}, Available for chunks: {available_chunk_tokens}"
  4163. )
  4164. # Apply token truncation to chunks using the dynamic limit
  4165. truncated_chunks = await process_chunks_unified(
  4166. query=query,
  4167. unique_chunks=merged_chunks,
  4168. query_param=query_param,
  4169. global_config=global_config,
  4170. source_type=query_param.mode,
  4171. chunk_token_limit=available_chunk_tokens, # Pass dynamic limit
  4172. )
  4173. # Generate reference list from truncated chunks using the new common function
  4174. reference_list, truncated_chunks = generate_reference_list_from_chunks(
  4175. truncated_chunks
  4176. )
  4177. # Rebuild chunks_context with truncated chunks
  4178. # The actual tokens may be slightly less than available_chunk_tokens due to deduplication logic
  4179. chunks_context = []
  4180. for i, chunk in enumerate(truncated_chunks):
  4181. chunks_context.append(
  4182. {
  4183. "reference_id": chunk["reference_id"],
  4184. "content": chunk["content"],
  4185. }
  4186. )
  4187. text_units_str = "\n".join(
  4188. json.dumps(text_unit, ensure_ascii=False) for text_unit in chunks_context
  4189. )
  4190. reference_list_str = "\n".join(
  4191. f"[{ref['reference_id']}] {ref['file_path']}"
  4192. for ref in reference_list
  4193. if ref["reference_id"]
  4194. )
  4195. logger.info(
  4196. f"Final context: {len(entities_context)} entities, {len(relations_context)} relations, {len(chunks_context)} chunks"
  4197. )
  4198. # not necessary to use LLM to generate a response
  4199. if not entities_context and not relations_context and not chunks_context:
  4200. # Return empty raw data structure when no entities/relations
  4201. empty_raw_data = convert_to_user_format(
  4202. [],
  4203. [],
  4204. [],
  4205. [],
  4206. query_param.mode,
  4207. )
  4208. empty_raw_data["status"] = "failure"
  4209. empty_raw_data["message"] = "Query returned empty dataset."
  4210. return "", empty_raw_data
  4211. # output chunks tracking infomations
  4212. # format: <source><frequency>/<order> (e.g., E5/2 R2/1 C1/1)
  4213. if truncated_chunks and chunk_tracking:
  4214. chunk_tracking_log = []
  4215. for chunk in truncated_chunks:
  4216. chunk_id = chunk.get("chunk_id")
  4217. if chunk_id and chunk_id in chunk_tracking:
  4218. tracking_info = chunk_tracking[chunk_id]
  4219. source = tracking_info["source"]
  4220. frequency = tracking_info["frequency"]
  4221. order = tracking_info["order"]
  4222. chunk_tracking_log.append(f"{source}{frequency}/{order}")
  4223. else:
  4224. chunk_tracking_log.append("?0/0")
  4225. if chunk_tracking_log:
  4226. logger.info(f"Final chunks S+F/O: {' '.join(chunk_tracking_log)}")
  4227. result = kg_context_template.format(
  4228. entities_str=entities_str,
  4229. relations_str=relations_str,
  4230. text_chunks_str=text_units_str,
  4231. reference_list_str=reference_list_str,
  4232. )
  4233. # Always return both context and complete data structure (unified approach)
  4234. logger.debug(
  4235. f"[_build_context_str] Converting to user format: {len(entities_context)} entities, {len(relations_context)} relations, {len(truncated_chunks)} chunks"
  4236. )
  4237. final_data = convert_to_user_format(
  4238. entities_context,
  4239. relations_context,
  4240. truncated_chunks,
  4241. reference_list,
  4242. query_param.mode,
  4243. entity_id_to_original,
  4244. relation_id_to_original,
  4245. )
  4246. final_data_payload = final_data.get("data", {})
  4247. logger.debug(
  4248. f"[_build_context_str] Final data after conversion: {len(final_data_payload.get('entities', []))} entities, {len(final_data_payload.get('relationships', []))} relationships, {len(final_data_payload.get('chunks', []))} chunks"
  4249. )
  4250. return result, final_data
  4251. # Now let's update the old _build_query_context to use the new architecture
  4252. async def _build_query_context(
  4253. query: str,
  4254. ll_keywords: str,
  4255. hl_keywords: str,
  4256. knowledge_graph_inst: BaseGraphStorage,
  4257. entities_vdb: BaseVectorStorage,
  4258. relationships_vdb: BaseVectorStorage,
  4259. text_chunks_db: BaseKVStorage,
  4260. query_param: QueryParam,
  4261. chunks_vdb: BaseVectorStorage = None,
  4262. ) -> QueryContextResult | None:
  4263. """
  4264. Main query context building function using the new 4-stage architecture:
  4265. 1. Search -> 2. Truncate -> 3. Merge chunks -> 4. Build LLM context
  4266. Returns unified QueryContextResult containing both context and raw_data.
  4267. """
  4268. if not query:
  4269. logger.warning("Query is empty, skipping context building")
  4270. return None
  4271. # Stage 1: Pure search
  4272. search_result = await _perform_kg_search(
  4273. query,
  4274. ll_keywords,
  4275. hl_keywords,
  4276. knowledge_graph_inst,
  4277. entities_vdb,
  4278. relationships_vdb,
  4279. text_chunks_db,
  4280. query_param,
  4281. chunks_vdb,
  4282. )
  4283. if not search_result["final_entities"] and not search_result["final_relations"]:
  4284. if query_param.mode != "mix":
  4285. return None
  4286. else:
  4287. if not search_result["chunk_tracking"]:
  4288. return None
  4289. # Stage 2: Apply token truncation for LLM efficiency
  4290. truncation_result = await _apply_token_truncation(
  4291. search_result,
  4292. query_param,
  4293. text_chunks_db.global_config,
  4294. )
  4295. # Stage 3: Merge chunks using filtered entities/relations
  4296. merged_chunks = await _merge_all_chunks(
  4297. filtered_entities=truncation_result["filtered_entities"],
  4298. filtered_relations=truncation_result["filtered_relations"],
  4299. vector_chunks=search_result["vector_chunks"],
  4300. query=query,
  4301. knowledge_graph_inst=knowledge_graph_inst,
  4302. text_chunks_db=text_chunks_db,
  4303. query_param=query_param,
  4304. chunks_vdb=chunks_vdb,
  4305. chunk_tracking=search_result["chunk_tracking"],
  4306. query_embedding=search_result["query_embedding"],
  4307. )
  4308. if (
  4309. not merged_chunks
  4310. and not truncation_result["entities_context"]
  4311. and not truncation_result["relations_context"]
  4312. ):
  4313. return None
  4314. # Stage 4: Build final LLM context with dynamic token processing
  4315. # _build_context_str now always returns tuple[str, dict]
  4316. context, raw_data = await _build_context_str(
  4317. entities_context=truncation_result["entities_context"],
  4318. relations_context=truncation_result["relations_context"],
  4319. merged_chunks=merged_chunks,
  4320. query=query,
  4321. query_param=query_param,
  4322. global_config=text_chunks_db.global_config,
  4323. chunk_tracking=search_result["chunk_tracking"],
  4324. entity_id_to_original=truncation_result["entity_id_to_original"],
  4325. relation_id_to_original=truncation_result["relation_id_to_original"],
  4326. )
  4327. # Convert keywords strings to lists and add complete metadata to raw_data
  4328. hl_keywords_list = hl_keywords.split(", ") if hl_keywords else []
  4329. ll_keywords_list = ll_keywords.split(", ") if ll_keywords else []
  4330. # Add complete metadata to raw_data (preserve existing metadata including query_mode)
  4331. if "metadata" not in raw_data:
  4332. raw_data["metadata"] = {}
  4333. # Update keywords while preserving existing metadata
  4334. raw_data["metadata"]["keywords"] = {
  4335. "high_level": hl_keywords_list,
  4336. "low_level": ll_keywords_list,
  4337. }
  4338. raw_data["metadata"]["processing_info"] = {
  4339. "total_entities_found": len(search_result.get("final_entities", [])),
  4340. "total_relations_found": len(search_result.get("final_relations", [])),
  4341. "entities_after_truncation": len(
  4342. truncation_result.get("filtered_entities", [])
  4343. ),
  4344. "relations_after_truncation": len(
  4345. truncation_result.get("filtered_relations", [])
  4346. ),
  4347. "merged_chunks_count": len(merged_chunks),
  4348. "final_chunks_count": len(raw_data.get("data", {}).get("chunks", [])),
  4349. }
  4350. logger.debug(
  4351. f"[_build_query_context] Context length: {len(context) if context else 0}"
  4352. )
  4353. logger.debug(
  4354. f"[_build_query_context] Raw data entities: {len(raw_data.get('data', {}).get('entities', []))}, relationships: {len(raw_data.get('data', {}).get('relationships', []))}, chunks: {len(raw_data.get('data', {}).get('chunks', []))}"
  4355. )
  4356. return QueryContextResult(context=context, raw_data=raw_data)
  4357. async def _get_node_data(
  4358. query: str,
  4359. knowledge_graph_inst: BaseGraphStorage,
  4360. entities_vdb: BaseVectorStorage,
  4361. query_param: QueryParam,
  4362. query_embedding=None,
  4363. ):
  4364. logger.info(
  4365. f"Query nodes: {query} (top_k:{query_param.top_k}, cosine:{entities_vdb.cosine_better_than_threshold})"
  4366. )
  4367. results = await entities_vdb.query(
  4368. query, top_k=query_param.top_k, query_embedding=query_embedding
  4369. )
  4370. if not len(results):
  4371. return [], []
  4372. # Extract all entity IDs from your results list
  4373. node_ids = [r["entity_name"] for r in results]
  4374. # Call the batch node retrieval and degree functions concurrently.
  4375. nodes_dict, degrees_dict = await asyncio.gather(
  4376. knowledge_graph_inst.get_nodes_batch(node_ids),
  4377. knowledge_graph_inst.node_degrees_batch(node_ids),
  4378. )
  4379. # Now, if you need the node data and degree in order:
  4380. node_datas = [nodes_dict.get(nid) for nid in node_ids]
  4381. node_degrees = [degrees_dict.get(nid, 0) for nid in node_ids]
  4382. if not all([n is not None for n in node_datas]):
  4383. logger.warning("Some nodes are missing, maybe the storage is damaged")
  4384. node_datas = [
  4385. {
  4386. **n,
  4387. "entity_name": k["entity_name"],
  4388. "rank": d,
  4389. "created_at": k.get("created_at"),
  4390. }
  4391. for k, n, d in zip(results, node_datas, node_degrees)
  4392. if n is not None
  4393. ]
  4394. use_relations = await _find_most_related_edges_from_entities(
  4395. node_datas,
  4396. query_param,
  4397. knowledge_graph_inst,
  4398. )
  4399. logger.info(
  4400. f"Local query: {len(node_datas)} entites, {len(use_relations)} relations"
  4401. )
  4402. # Entities are sorted by cosine similarity
  4403. # Relations are sorted by rank + weight
  4404. return node_datas, use_relations
  4405. async def _find_most_related_edges_from_entities(
  4406. node_datas: list[dict],
  4407. query_param: QueryParam,
  4408. knowledge_graph_inst: BaseGraphStorage,
  4409. ):
  4410. node_names = [dp["entity_name"] for dp in node_datas]
  4411. batch_edges_dict = await knowledge_graph_inst.get_nodes_edges_batch(node_names)
  4412. all_edges = []
  4413. seen = set()
  4414. for node_name in node_names:
  4415. this_edges = batch_edges_dict.get(node_name, [])
  4416. for e in this_edges:
  4417. sorted_edge = tuple(sorted(e))
  4418. if sorted_edge not in seen:
  4419. seen.add(sorted_edge)
  4420. all_edges.append(sorted_edge)
  4421. # Prepare edge pairs in two forms:
  4422. # For the batch edge properties function, use dicts.
  4423. edge_pairs_dicts = [{"src": e[0], "tgt": e[1]} for e in all_edges]
  4424. # For edge degrees, use tuples.
  4425. edge_pairs_tuples = list(all_edges) # all_edges is already a list of tuples
  4426. # Call the batched functions concurrently.
  4427. edge_data_dict, edge_degrees_dict = await asyncio.gather(
  4428. knowledge_graph_inst.get_edges_batch(edge_pairs_dicts),
  4429. knowledge_graph_inst.edge_degrees_batch(edge_pairs_tuples),
  4430. )
  4431. # Reconstruct edge_datas list in the same order as the deduplicated results.
  4432. all_edges_data = []
  4433. for pair in all_edges:
  4434. edge_props = edge_data_dict.get(pair)
  4435. if edge_props is not None:
  4436. if "weight" not in edge_props:
  4437. logger.warning(
  4438. f"Edge {pair} missing 'weight' attribute, using default value 1.0"
  4439. )
  4440. edge_props["weight"] = 1.0
  4441. combined = {
  4442. "src_tgt": pair,
  4443. "rank": edge_degrees_dict.get(pair, 0),
  4444. **edge_props,
  4445. }
  4446. all_edges_data.append(combined)
  4447. all_edges_data = sorted(
  4448. all_edges_data, key=lambda x: (x["rank"], x["weight"]), reverse=True
  4449. )
  4450. return all_edges_data
  4451. async def _find_related_text_unit_from_entities(
  4452. node_datas: list[dict],
  4453. query_param: QueryParam,
  4454. text_chunks_db: BaseKVStorage,
  4455. knowledge_graph_inst: BaseGraphStorage,
  4456. query: str = None,
  4457. chunks_vdb: BaseVectorStorage = None,
  4458. chunk_tracking: dict = None,
  4459. query_embedding=None,
  4460. ):
  4461. """
  4462. Find text chunks related to entities using configurable chunk selection method.
  4463. This function supports two chunk selection strategies:
  4464. 1. WEIGHT: Linear gradient weighted polling based on chunk occurrence count
  4465. 2. VECTOR: Vector similarity-based selection using embedding cosine similarity
  4466. """
  4467. logger.debug(f"Finding text chunks from {len(node_datas)} entities")
  4468. if not node_datas:
  4469. return []
  4470. # Step 1: Collect all text chunks for each entity
  4471. entities_with_chunks = []
  4472. for entity in node_datas:
  4473. if entity.get("source_id"):
  4474. chunks = split_string_by_multi_markers(
  4475. entity["source_id"], [GRAPH_FIELD_SEP]
  4476. )
  4477. if chunks:
  4478. entities_with_chunks.append(
  4479. {
  4480. "entity_name": entity["entity_name"],
  4481. "chunks": chunks,
  4482. "entity_data": entity,
  4483. }
  4484. )
  4485. if not entities_with_chunks:
  4486. logger.warning("No entities with text chunks found")
  4487. return []
  4488. kg_chunk_pick_method = text_chunks_db.global_config.get(
  4489. "kg_chunk_pick_method", DEFAULT_KG_CHUNK_PICK_METHOD
  4490. )
  4491. max_related_chunks = text_chunks_db.global_config.get(
  4492. "related_chunk_number", DEFAULT_RELATED_CHUNK_NUMBER
  4493. )
  4494. # Step 2: Count chunk occurrences and deduplicate (keep chunks from earlier positioned entities)
  4495. chunk_occurrence_count = {}
  4496. for entity_info in entities_with_chunks:
  4497. deduplicated_chunks = []
  4498. for chunk_id in entity_info["chunks"]:
  4499. chunk_occurrence_count[chunk_id] = (
  4500. chunk_occurrence_count.get(chunk_id, 0) + 1
  4501. )
  4502. # If this is the first occurrence (count == 1), keep it; otherwise skip (duplicate from later position)
  4503. if chunk_occurrence_count[chunk_id] == 1:
  4504. deduplicated_chunks.append(chunk_id)
  4505. # count > 1 means this chunk appeared in an earlier entity, so skip it
  4506. # Update entity's chunks to deduplicated chunks
  4507. entity_info["chunks"] = deduplicated_chunks
  4508. # Step 3: Sort chunks for each entity by occurrence count (higher count = higher priority)
  4509. total_entity_chunks = 0
  4510. for entity_info in entities_with_chunks:
  4511. sorted_chunks = sorted(
  4512. entity_info["chunks"],
  4513. key=lambda chunk_id: chunk_occurrence_count.get(chunk_id, 0),
  4514. reverse=True,
  4515. )
  4516. entity_info["sorted_chunks"] = sorted_chunks
  4517. total_entity_chunks += len(sorted_chunks)
  4518. selected_chunk_ids = [] # Initialize to avoid UnboundLocalError
  4519. # Step 4: Apply the selected chunk selection algorithm
  4520. # Pick by vector similarity:
  4521. # The order of text chunks aligns with the naive retrieval's destination.
  4522. # When reranking is disabled, the text chunks delivered to the LLM tend to favor naive retrieval.
  4523. if kg_chunk_pick_method == "VECTOR" and query and chunks_vdb:
  4524. num_of_chunks = int(max_related_chunks * len(entities_with_chunks) / 2)
  4525. # Get embedding function from global config
  4526. actual_embedding_func = text_chunks_db.embedding_func
  4527. if not actual_embedding_func:
  4528. logger.warning("No embedding function found, falling back to WEIGHT method")
  4529. kg_chunk_pick_method = "WEIGHT"
  4530. else:
  4531. try:
  4532. selected_chunk_ids = await pick_by_vector_similarity(
  4533. query=query,
  4534. text_chunks_storage=text_chunks_db,
  4535. chunks_vdb=chunks_vdb,
  4536. num_of_chunks=num_of_chunks,
  4537. entity_info=entities_with_chunks,
  4538. embedding_func=actual_embedding_func,
  4539. query_embedding=query_embedding,
  4540. )
  4541. if selected_chunk_ids == []:
  4542. kg_chunk_pick_method = "WEIGHT"
  4543. logger.warning(
  4544. "No entity-related chunks selected by vector similarity, falling back to WEIGHT method"
  4545. )
  4546. else:
  4547. logger.info(
  4548. f"Selecting {len(selected_chunk_ids)} from {total_entity_chunks} entity-related chunks by vector similarity"
  4549. )
  4550. except Exception as e:
  4551. logger.error(
  4552. f"Error in vector similarity sorting: {e}, falling back to WEIGHT method"
  4553. )
  4554. kg_chunk_pick_method = "WEIGHT"
  4555. if kg_chunk_pick_method == "WEIGHT":
  4556. # Pick by entity and chunk weight:
  4557. # When reranking is disabled, delivered more solely KG related chunks to the LLM
  4558. selected_chunk_ids = pick_by_weighted_polling(
  4559. entities_with_chunks, max_related_chunks, min_related_chunks=1
  4560. )
  4561. logger.info(
  4562. f"Selecting {len(selected_chunk_ids)} from {total_entity_chunks} entity-related chunks by weighted polling"
  4563. )
  4564. if not selected_chunk_ids:
  4565. return []
  4566. # Step 5: Batch retrieve chunk data
  4567. unique_chunk_ids = list(
  4568. dict.fromkeys(selected_chunk_ids)
  4569. ) # Remove duplicates while preserving order
  4570. chunk_data_list = await text_chunks_db.get_by_ids(unique_chunk_ids)
  4571. # Step 6: Build result chunks with valid data and update chunk tracking
  4572. result_chunks = []
  4573. for i, (chunk_id, chunk_data) in enumerate(zip(unique_chunk_ids, chunk_data_list)):
  4574. if chunk_data is not None and "content" in chunk_data:
  4575. chunk_data_copy = chunk_data.copy()
  4576. chunk_data_copy["source_type"] = "entity"
  4577. chunk_data_copy["chunk_id"] = chunk_id # Add chunk_id for deduplication
  4578. result_chunks.append(chunk_data_copy)
  4579. # Update chunk tracking if provided
  4580. if chunk_tracking is not None:
  4581. chunk_tracking[chunk_id] = {
  4582. "source": "E",
  4583. "frequency": chunk_occurrence_count.get(chunk_id, 1),
  4584. "order": i + 1, # 1-based order in final entity-related results
  4585. }
  4586. return result_chunks
  4587. async def _get_edge_data(
  4588. keywords,
  4589. knowledge_graph_inst: BaseGraphStorage,
  4590. relationships_vdb: BaseVectorStorage,
  4591. query_param: QueryParam,
  4592. query_embedding=None,
  4593. ):
  4594. logger.info(
  4595. f"Query edges: {keywords} (top_k:{query_param.top_k}, cosine:{relationships_vdb.cosine_better_than_threshold})"
  4596. )
  4597. results = await relationships_vdb.query(
  4598. keywords, top_k=query_param.top_k, query_embedding=query_embedding
  4599. )
  4600. if not len(results):
  4601. return [], []
  4602. # Prepare edge pairs in two forms:
  4603. # For the batch edge properties function, use dicts.
  4604. edge_pairs_dicts = [{"src": r["src_id"], "tgt": r["tgt_id"]} for r in results]
  4605. edge_data_dict = await knowledge_graph_inst.get_edges_batch(edge_pairs_dicts)
  4606. # Reconstruct edge_datas list in the same order as results.
  4607. edge_datas = []
  4608. for k in results:
  4609. pair = (k["src_id"], k["tgt_id"])
  4610. edge_props = edge_data_dict.get(pair)
  4611. if edge_props is not None:
  4612. if "weight" not in edge_props:
  4613. logger.warning(
  4614. f"Edge {pair} missing 'weight' attribute, using default value 1.0"
  4615. )
  4616. edge_props["weight"] = 1.0
  4617. # Keep edge data without rank, maintain vector search order
  4618. combined = {
  4619. "src_id": k["src_id"],
  4620. "tgt_id": k["tgt_id"],
  4621. "created_at": k.get("created_at", None),
  4622. **edge_props,
  4623. }
  4624. edge_datas.append(combined)
  4625. # Relations maintain vector search order (sorted by similarity)
  4626. use_entities = await _find_most_related_entities_from_relationships(
  4627. edge_datas,
  4628. query_param,
  4629. knowledge_graph_inst,
  4630. )
  4631. logger.info(
  4632. f"Global query: {len(use_entities)} entites, {len(edge_datas)} relations"
  4633. )
  4634. return edge_datas, use_entities
  4635. async def _find_most_related_entities_from_relationships(
  4636. edge_datas: list[dict],
  4637. query_param: QueryParam,
  4638. knowledge_graph_inst: BaseGraphStorage,
  4639. ):
  4640. entity_names = []
  4641. seen = set()
  4642. for e in edge_datas:
  4643. if e["src_id"] not in seen:
  4644. entity_names.append(e["src_id"])
  4645. seen.add(e["src_id"])
  4646. if e["tgt_id"] not in seen:
  4647. entity_names.append(e["tgt_id"])
  4648. seen.add(e["tgt_id"])
  4649. # Only get nodes data, no need for node degrees
  4650. nodes_dict = await knowledge_graph_inst.get_nodes_batch(entity_names)
  4651. # Rebuild the list in the same order as entity_names
  4652. node_datas = []
  4653. for entity_name in entity_names:
  4654. node = nodes_dict.get(entity_name)
  4655. if node is None:
  4656. logger.warning(f"Node '{entity_name}' not found in batch retrieval.")
  4657. continue
  4658. # Combine the node data with the entity name, no rank needed
  4659. combined = {**node, "entity_name": entity_name}
  4660. node_datas.append(combined)
  4661. return node_datas
  4662. async def _find_related_text_unit_from_relations(
  4663. edge_datas: list[dict],
  4664. query_param: QueryParam,
  4665. text_chunks_db: BaseKVStorage,
  4666. entity_chunks: list[dict] = None,
  4667. query: str = None,
  4668. chunks_vdb: BaseVectorStorage = None,
  4669. chunk_tracking: dict = None,
  4670. query_embedding=None,
  4671. ):
  4672. """
  4673. Find text chunks related to relationships using configurable chunk selection method.
  4674. This function supports two chunk selection strategies:
  4675. 1. WEIGHT: Linear gradient weighted polling based on chunk occurrence count
  4676. 2. VECTOR: Vector similarity-based selection using embedding cosine similarity
  4677. """
  4678. logger.debug(f"Finding text chunks from {len(edge_datas)} relations")
  4679. if not edge_datas:
  4680. return []
  4681. # Step 1: Collect all text chunks for each relationship
  4682. relations_with_chunks = []
  4683. for relation in edge_datas:
  4684. if relation.get("source_id"):
  4685. chunks = split_string_by_multi_markers(
  4686. relation["source_id"], [GRAPH_FIELD_SEP]
  4687. )
  4688. if chunks:
  4689. # Build relation identifier
  4690. if "src_tgt" in relation:
  4691. rel_key = tuple(sorted(relation["src_tgt"]))
  4692. else:
  4693. rel_key = tuple(
  4694. sorted([relation.get("src_id"), relation.get("tgt_id")])
  4695. )
  4696. relations_with_chunks.append(
  4697. {
  4698. "relation_key": rel_key,
  4699. "chunks": chunks,
  4700. "relation_data": relation,
  4701. }
  4702. )
  4703. if not relations_with_chunks:
  4704. logger.warning("No relation-related chunks found")
  4705. return []
  4706. kg_chunk_pick_method = text_chunks_db.global_config.get(
  4707. "kg_chunk_pick_method", DEFAULT_KG_CHUNK_PICK_METHOD
  4708. )
  4709. max_related_chunks = text_chunks_db.global_config.get(
  4710. "related_chunk_number", DEFAULT_RELATED_CHUNK_NUMBER
  4711. )
  4712. # Step 2: Count chunk occurrences and deduplicate (keep chunks from earlier positioned relationships)
  4713. # Also remove duplicates with entity_chunks
  4714. # Extract chunk IDs from entity_chunks for deduplication
  4715. entity_chunk_ids = set()
  4716. if entity_chunks:
  4717. for chunk in entity_chunks:
  4718. chunk_id = chunk.get("chunk_id")
  4719. if chunk_id:
  4720. entity_chunk_ids.add(chunk_id)
  4721. chunk_occurrence_count = {}
  4722. # Track unique chunk_ids that have been removed to avoid double counting
  4723. removed_entity_chunk_ids = set()
  4724. for relation_info in relations_with_chunks:
  4725. deduplicated_chunks = []
  4726. for chunk_id in relation_info["chunks"]:
  4727. # Skip chunks that already exist in entity_chunks
  4728. if chunk_id in entity_chunk_ids:
  4729. # Only count each unique chunk_id once
  4730. removed_entity_chunk_ids.add(chunk_id)
  4731. continue
  4732. chunk_occurrence_count[chunk_id] = (
  4733. chunk_occurrence_count.get(chunk_id, 0) + 1
  4734. )
  4735. # If this is the first occurrence (count == 1), keep it; otherwise skip (duplicate from later position)
  4736. if chunk_occurrence_count[chunk_id] == 1:
  4737. deduplicated_chunks.append(chunk_id)
  4738. # count > 1 means this chunk appeared in an earlier relationship, so skip it
  4739. # Update relationship's chunks to deduplicated chunks
  4740. relation_info["chunks"] = deduplicated_chunks
  4741. # Check if any relations still have chunks after deduplication
  4742. relations_with_chunks = [
  4743. relation_info
  4744. for relation_info in relations_with_chunks
  4745. if relation_info["chunks"]
  4746. ]
  4747. if not relations_with_chunks:
  4748. logger.info(
  4749. f"Find no additional relations-related chunks from {len(edge_datas)} relations"
  4750. )
  4751. return []
  4752. # Step 3: Sort chunks for each relationship by occurrence count (higher count = higher priority)
  4753. total_relation_chunks = 0
  4754. for relation_info in relations_with_chunks:
  4755. sorted_chunks = sorted(
  4756. relation_info["chunks"],
  4757. key=lambda chunk_id: chunk_occurrence_count.get(chunk_id, 0),
  4758. reverse=True,
  4759. )
  4760. relation_info["sorted_chunks"] = sorted_chunks
  4761. total_relation_chunks += len(sorted_chunks)
  4762. logger.info(
  4763. f"Find {total_relation_chunks} additional chunks in {len(relations_with_chunks)} relations (deduplicated {len(removed_entity_chunk_ids)})"
  4764. )
  4765. # Step 4: Apply the selected chunk selection algorithm
  4766. selected_chunk_ids = [] # Initialize to avoid UnboundLocalError
  4767. if kg_chunk_pick_method == "VECTOR" and query and chunks_vdb:
  4768. num_of_chunks = int(max_related_chunks * len(relations_with_chunks) / 2)
  4769. # Get embedding function from global config
  4770. actual_embedding_func = text_chunks_db.embedding_func
  4771. if not actual_embedding_func:
  4772. logger.warning("No embedding function found, falling back to WEIGHT method")
  4773. kg_chunk_pick_method = "WEIGHT"
  4774. else:
  4775. try:
  4776. selected_chunk_ids = await pick_by_vector_similarity(
  4777. query=query,
  4778. text_chunks_storage=text_chunks_db,
  4779. chunks_vdb=chunks_vdb,
  4780. num_of_chunks=num_of_chunks,
  4781. entity_info=relations_with_chunks,
  4782. embedding_func=actual_embedding_func,
  4783. query_embedding=query_embedding,
  4784. )
  4785. if selected_chunk_ids == []:
  4786. kg_chunk_pick_method = "WEIGHT"
  4787. logger.warning(
  4788. "No relation-related chunks selected by vector similarity, falling back to WEIGHT method"
  4789. )
  4790. else:
  4791. logger.info(
  4792. f"Selecting {len(selected_chunk_ids)} from {total_relation_chunks} relation-related chunks by vector similarity"
  4793. )
  4794. except Exception as e:
  4795. logger.error(
  4796. f"Error in vector similarity sorting: {e}, falling back to WEIGHT method"
  4797. )
  4798. kg_chunk_pick_method = "WEIGHT"
  4799. if kg_chunk_pick_method == "WEIGHT":
  4800. # Apply linear gradient weighted polling algorithm
  4801. selected_chunk_ids = pick_by_weighted_polling(
  4802. relations_with_chunks, max_related_chunks, min_related_chunks=1
  4803. )
  4804. logger.info(
  4805. f"Selecting {len(selected_chunk_ids)} from {total_relation_chunks} relation-related chunks by weighted polling"
  4806. )
  4807. logger.debug(
  4808. f"KG related chunks: {len(entity_chunks)} from entitys, {len(selected_chunk_ids)} from relations"
  4809. )
  4810. if not selected_chunk_ids:
  4811. return []
  4812. # Step 5: Batch retrieve chunk data
  4813. unique_chunk_ids = list(
  4814. dict.fromkeys(selected_chunk_ids)
  4815. ) # Remove duplicates while preserving order
  4816. chunk_data_list = await text_chunks_db.get_by_ids(unique_chunk_ids)
  4817. # Step 6: Build result chunks with valid data and update chunk tracking
  4818. result_chunks = []
  4819. for i, (chunk_id, chunk_data) in enumerate(zip(unique_chunk_ids, chunk_data_list)):
  4820. if chunk_data is not None and "content" in chunk_data:
  4821. chunk_data_copy = chunk_data.copy()
  4822. chunk_data_copy["source_type"] = "relationship"
  4823. chunk_data_copy["chunk_id"] = chunk_id # Add chunk_id for deduplication
  4824. result_chunks.append(chunk_data_copy)
  4825. # Update chunk tracking if provided
  4826. if chunk_tracking is not None:
  4827. chunk_tracking[chunk_id] = {
  4828. "source": "R",
  4829. "frequency": chunk_occurrence_count.get(chunk_id, 1),
  4830. "order": i + 1, # 1-based order in final relation-related results
  4831. }
  4832. return result_chunks
  4833. @overload
  4834. async def naive_query(
  4835. query: str,
  4836. chunks_vdb: BaseVectorStorage,
  4837. query_param: QueryParam,
  4838. global_config: dict[str, str],
  4839. hashing_kv: BaseKVStorage | None = None,
  4840. system_prompt: str | None = None,
  4841. return_raw_data: Literal[True] = True,
  4842. ) -> dict[str, Any]: ...
  4843. @overload
  4844. async def naive_query(
  4845. query: str,
  4846. chunks_vdb: BaseVectorStorage,
  4847. query_param: QueryParam,
  4848. global_config: dict[str, str],
  4849. hashing_kv: BaseKVStorage | None = None,
  4850. system_prompt: str | None = None,
  4851. return_raw_data: Literal[False] = False,
  4852. ) -> str | AsyncIterator[str]: ...
  4853. async def naive_query(
  4854. query: str,
  4855. chunks_vdb: BaseVectorStorage,
  4856. query_param: QueryParam,
  4857. global_config: dict[str, str],
  4858. hashing_kv: BaseKVStorage | None = None,
  4859. system_prompt: str | None = None,
  4860. ) -> QueryResult | None:
  4861. """
  4862. Execute naive query and return unified QueryResult object.
  4863. Args:
  4864. query: Query string
  4865. chunks_vdb: Document chunks vector database
  4866. query_param: Query parameters
  4867. global_config: Global configuration
  4868. hashing_kv: Cache storage
  4869. system_prompt: System prompt
  4870. Returns:
  4871. QueryResult | None: Unified query result object containing:
  4872. - content: Non-streaming response text content
  4873. - response_iterator: Streaming response iterator
  4874. - raw_data: Complete structured data (including references and metadata)
  4875. - is_streaming: Whether this is a streaming result
  4876. Returns None when no relevant chunks are retrieved.
  4877. """
  4878. if not query:
  4879. return QueryResult(content=PROMPTS["fail_response"])
  4880. # Apply higher priority (5) to query relation LLM function
  4881. use_model_func = partial(global_config["role_llm_funcs"]["query"], _priority=5)
  4882. llm_cache_identity = get_llm_cache_identity(global_config, "query")
  4883. tokenizer: Tokenizer = global_config["tokenizer"]
  4884. if not tokenizer:
  4885. logger.error("Tokenizer not found in global configuration.")
  4886. return QueryResult(content=PROMPTS["fail_response"])
  4887. chunks = await _get_vector_context(query, chunks_vdb, query_param, None)
  4888. if chunks is None or len(chunks) == 0:
  4889. logger.info(
  4890. "[naive_query] No relevant document chunks found; returning no-result."
  4891. )
  4892. return None
  4893. # Calculate dynamic token limit for chunks
  4894. max_total_tokens = getattr(
  4895. query_param,
  4896. "max_total_tokens",
  4897. global_config.get("max_total_tokens", DEFAULT_MAX_TOTAL_TOKENS),
  4898. )
  4899. # Calculate system prompt template tokens (excluding content_data)
  4900. user_prompt = f"\n\n{query_param.user_prompt}" if query_param.user_prompt else "n/a"
  4901. response_type = (
  4902. query_param.response_type
  4903. if query_param.response_type
  4904. else "Multiple Paragraphs"
  4905. )
  4906. # Use the provided system prompt or default
  4907. sys_prompt_template = (
  4908. system_prompt if system_prompt else PROMPTS["naive_rag_response"]
  4909. )
  4910. # Create a preliminary system prompt with empty content_data to calculate overhead
  4911. pre_sys_prompt = sys_prompt_template.format(
  4912. response_type=response_type,
  4913. user_prompt=user_prompt,
  4914. content_data="", # Empty for overhead calculation
  4915. )
  4916. # Calculate available tokens for chunks
  4917. sys_prompt_tokens = len(tokenizer.encode(pre_sys_prompt))
  4918. query_tokens = len(tokenizer.encode(query))
  4919. buffer_tokens = 200 # reserved for reference list and safety buffer
  4920. available_chunk_tokens = max_total_tokens - (
  4921. sys_prompt_tokens + query_tokens + buffer_tokens
  4922. )
  4923. logger.debug(
  4924. f"Naive query token allocation - Total: {max_total_tokens}, SysPrompt: {sys_prompt_tokens}, Query: {query_tokens}, Buffer: {buffer_tokens}, Available for chunks: {available_chunk_tokens}"
  4925. )
  4926. # Process chunks using unified processing with dynamic token limit
  4927. processed_chunks = await process_chunks_unified(
  4928. query=query,
  4929. unique_chunks=chunks,
  4930. query_param=query_param,
  4931. global_config=global_config,
  4932. source_type="vector",
  4933. chunk_token_limit=available_chunk_tokens, # Pass dynamic limit
  4934. )
  4935. # Generate reference list from processed chunks using the new common function
  4936. reference_list, processed_chunks_with_ref_ids = generate_reference_list_from_chunks(
  4937. processed_chunks
  4938. )
  4939. logger.info(f"Final context: {len(processed_chunks_with_ref_ids)} chunks")
  4940. # Build raw data structure for naive mode using processed chunks with reference IDs
  4941. raw_data = convert_to_user_format(
  4942. [], # naive mode has no entities
  4943. [], # naive mode has no relationships
  4944. processed_chunks_with_ref_ids,
  4945. reference_list,
  4946. "naive",
  4947. )
  4948. # Add complete metadata for naive mode
  4949. if "metadata" not in raw_data:
  4950. raw_data["metadata"] = {}
  4951. raw_data["metadata"]["keywords"] = {
  4952. "high_level": [], # naive mode has no keyword extraction
  4953. "low_level": [], # naive mode has no keyword extraction
  4954. }
  4955. raw_data["metadata"]["processing_info"] = {
  4956. "total_chunks_found": len(chunks),
  4957. "final_chunks_count": len(processed_chunks_with_ref_ids),
  4958. }
  4959. # Build chunks_context from processed chunks with reference IDs
  4960. chunks_context = []
  4961. for i, chunk in enumerate(processed_chunks_with_ref_ids):
  4962. chunks_context.append(
  4963. {
  4964. "reference_id": chunk["reference_id"],
  4965. "content": chunk["content"],
  4966. }
  4967. )
  4968. text_units_str = "\n".join(
  4969. json.dumps(text_unit, ensure_ascii=False) for text_unit in chunks_context
  4970. )
  4971. reference_list_str = "\n".join(
  4972. f"[{ref['reference_id']}] {ref['file_path']}"
  4973. for ref in reference_list
  4974. if ref["reference_id"]
  4975. )
  4976. naive_context_template = PROMPTS["naive_query_context"]
  4977. context_content = naive_context_template.format(
  4978. text_chunks_str=text_units_str,
  4979. reference_list_str=reference_list_str,
  4980. )
  4981. if query_param.only_need_context and not query_param.only_need_prompt:
  4982. return QueryResult(content=context_content, raw_data=raw_data)
  4983. sys_prompt = sys_prompt_template.format(
  4984. response_type=query_param.response_type,
  4985. user_prompt=user_prompt,
  4986. content_data=context_content,
  4987. )
  4988. user_query = query
  4989. if query_param.only_need_prompt:
  4990. prompt_content = "\n\n".join([sys_prompt, "---User Query---", user_query])
  4991. return QueryResult(content=prompt_content, raw_data=raw_data)
  4992. # Handle cache
  4993. args_hash = compute_args_hash(
  4994. query_param.mode,
  4995. query,
  4996. query_param.response_type,
  4997. query_param.top_k,
  4998. query_param.chunk_top_k,
  4999. query_param.max_entity_tokens,
  5000. query_param.max_relation_tokens,
  5001. query_param.max_total_tokens,
  5002. query_param.user_prompt or "",
  5003. query_param.enable_rerank,
  5004. "\n<llm_identity>\n",
  5005. serialize_llm_cache_identity(llm_cache_identity),
  5006. )
  5007. cached_result = await handle_cache(
  5008. hashing_kv, args_hash, user_query, query_param.mode, cache_type="query"
  5009. )
  5010. if cached_result is not None:
  5011. cached_response, _ = cached_result # Extract content, ignore timestamp
  5012. logger.info(
  5013. " == LLM cache == Query cache hit, using cached response as query result"
  5014. )
  5015. response = cached_response
  5016. else:
  5017. response = await use_model_func(
  5018. user_query,
  5019. system_prompt=sys_prompt,
  5020. history_messages=query_param.conversation_history,
  5021. enable_cot=True,
  5022. stream=query_param.stream,
  5023. )
  5024. if hashing_kv and hashing_kv.global_config.get("enable_llm_cache"):
  5025. queryparam_dict = {
  5026. "mode": query_param.mode,
  5027. "response_type": query_param.response_type,
  5028. "top_k": query_param.top_k,
  5029. "chunk_top_k": query_param.chunk_top_k,
  5030. "max_entity_tokens": query_param.max_entity_tokens,
  5031. "max_relation_tokens": query_param.max_relation_tokens,
  5032. "max_total_tokens": query_param.max_total_tokens,
  5033. "user_prompt": query_param.user_prompt or "",
  5034. "enable_rerank": query_param.enable_rerank,
  5035. }
  5036. await save_to_cache(
  5037. hashing_kv,
  5038. CacheData(
  5039. args_hash=args_hash,
  5040. content=response,
  5041. prompt=query,
  5042. mode=query_param.mode,
  5043. cache_type="query",
  5044. queryparam=queryparam_dict,
  5045. ),
  5046. )
  5047. # Return unified result based on actual response type
  5048. if isinstance(response, str):
  5049. # Non-streaming response (string)
  5050. if len(response) > len(sys_prompt):
  5051. response = (
  5052. response[len(sys_prompt) :]
  5053. .replace(sys_prompt, "")
  5054. .replace("user", "")
  5055. .replace("model", "")
  5056. .replace(query, "")
  5057. .replace("<system>", "")
  5058. .replace("</system>", "")
  5059. .strip()
  5060. )
  5061. return QueryResult(content=response, raw_data=raw_data)
  5062. else:
  5063. # Streaming response (AsyncIterator)
  5064. return QueryResult(
  5065. response_iterator=response, raw_data=raw_data, is_streaming=True
  5066. )