| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887 |
- """The LangGraph client implementations connect to the LangGraph API.
- This module provides both asynchronous (`get_client(url="http://localhost:2024")` or
- `LangGraphClient`) and synchronous (`get_sync_client(url="http://localhost:2024")` or
- `SyncLanggraphClient`) clients to interacting with the LangGraph API's core resources
- such as Assistants, Threads, Runs, and Cron jobs, as well as its persistent document
- Store.
- """
- from __future__ import annotations
- import asyncio
- import functools
- import logging
- import os
- import re
- import sys
- import warnings
- from collections.abc import AsyncIterator, Callable, Iterator, Mapping, Sequence
- from types import TracebackType
- from typing import (
- Any,
- Literal,
- cast,
- overload,
- )
- import httpx
- import orjson
- import langgraph_sdk
- from langgraph_sdk.errors import _araise_for_status_typed, _raise_for_status_typed
- from langgraph_sdk.schema import (
- All,
- Assistant,
- AssistantSelectField,
- AssistantSortBy,
- AssistantsSearchResponse,
- AssistantVersion,
- CancelAction,
- Checkpoint,
- Command,
- Config,
- Context,
- Cron,
- CronSelectField,
- CronSortBy,
- DisconnectMode,
- Durability,
- GraphSchema,
- IfNotExists,
- Input,
- Item,
- Json,
- ListNamespaceResponse,
- MultitaskStrategy,
- OnCompletionBehavior,
- OnConflictBehavior,
- QueryParamTypes,
- Run,
- RunCreate,
- RunCreateMetadata,
- RunSelectField,
- RunStatus,
- SearchItemsResponse,
- SortOrder,
- StreamMode,
- StreamPart,
- Subgraphs,
- Thread,
- ThreadSelectField,
- ThreadSortBy,
- ThreadState,
- ThreadStatus,
- ThreadStreamMode,
- ThreadUpdateStateResponse,
- )
- from langgraph_sdk.sse import SSEDecoder, aiter_lines_raw, iter_lines_raw
- logger = logging.getLogger(__name__)
- RESERVED_HEADERS = ("x-api-key",)
- NOT_PROVIDED = cast(None, object())
- def _get_api_key(api_key: str | None = NOT_PROVIDED) -> str | None:
- """Get the API key from the environment.
- Precedence:
- 1. explicit string argument
- 2. LANGGRAPH_API_KEY (if api_key not provided)
- 3. LANGSMITH_API_KEY (if api_key not provided)
- 4. LANGCHAIN_API_KEY (if api_key not provided)
- Args:
- api_key: The API key to use. Can be:
- - A string: use this exact API key
- - None: explicitly skip loading from environment
- - NOT_PROVIDED (default): auto-load from environment variables
- """
- if isinstance(api_key, str):
- return api_key
- if api_key is NOT_PROVIDED:
- # api_key is not explicitly provided, try to load from environment
- for prefix in ["LANGGRAPH", "LANGSMITH", "LANGCHAIN"]:
- if env := os.getenv(f"{prefix}_API_KEY"):
- return env.strip().strip('"').strip("'")
- # api_key is explicitly None, don't load from environment
- return None
- def _get_headers(
- api_key: str | None,
- custom_headers: Mapping[str, str] | None,
- ) -> dict[str, str]:
- """Combine api_key and custom user-provided headers."""
- custom_headers = custom_headers or {}
- for header in RESERVED_HEADERS:
- if header in custom_headers:
- raise ValueError(f"Cannot set reserved header '{header}'")
- headers = {
- "User-Agent": f"langgraph-sdk-py/{langgraph_sdk.__version__}",
- **custom_headers,
- }
- resolved_api_key = _get_api_key(api_key)
- if resolved_api_key:
- headers["x-api-key"] = resolved_api_key
- return headers
- def _orjson_default(obj: Any) -> Any:
- is_class = isinstance(obj, type)
- if hasattr(obj, "model_dump") and callable(obj.model_dump):
- if is_class:
- raise TypeError(
- f"Cannot JSON-serialize type object: {obj!r}. Did you mean to pass an instance of the object instead?"
- f"\nReceived type: {obj!r}"
- )
- return obj.model_dump()
- elif hasattr(obj, "dict") and callable(obj.dict):
- if is_class:
- raise TypeError(
- f"Cannot JSON-serialize type object: {obj!r}. Did you mean to pass an instance of the object instead?"
- f"\nReceived type: {obj!r}"
- )
- return obj.dict()
- elif isinstance(obj, (set, frozenset)):
- return list(obj)
- else:
- raise TypeError(f"Object of type {type(obj)} is not JSON serializable")
- # Compiled regex pattern for extracting run metadata from Content-Location header
- _RUN_METADATA_PATTERN = re.compile(
- r"(\/threads\/(?P<thread_id>.+))?\/runs\/(?P<run_id>.+)"
- )
- def _get_run_metadata_from_response(
- response: httpx.Response,
- ) -> RunCreateMetadata | None:
- """Extract run metadata from the response headers."""
- if (content_location := response.headers.get("Content-Location")) and (
- match := _RUN_METADATA_PATTERN.search(content_location)
- ):
- return RunCreateMetadata(
- run_id=match.group("run_id"),
- thread_id=match.group("thread_id") or None,
- )
- return None
- def get_client(
- *,
- url: str | None = None,
- api_key: str | None = NOT_PROVIDED,
- headers: Mapping[str, str] | None = None,
- timeout: TimeoutTypes | None = None,
- ) -> LangGraphClient:
- """Create and configure a LangGraphClient.
- The client provides programmatic access to LangSmith Deployment. It supports
- both remote servers and local in-process connections (when running inside a LangGraph server).
- Args:
- url:
- Base URL of the LangGraph API.
- - If `None`, the client first attempts an in-process connection via ASGI transport.
- If that fails, it defers registration until after app initialization. This
- only works if the client is used from within the Agent server.
- api_key:
- API key for authentication. Can be:
- - A string: use this exact API key
- - `None`: explicitly skip loading from environment variables
- - Not provided (default): auto-load from environment in this order:
- 1. `LANGGRAPH_API_KEY`
- 2. `LANGSMITH_API_KEY`
- 3. `LANGCHAIN_API_KEY`
- headers:
- Additional HTTP headers to include in requests. Merged with authentication headers.
- timeout:
- HTTP timeout configuration. May be:
- - `httpx.Timeout` instance
- - float (total seconds)
- - tuple `(connect, read, write, pool)` in seconds
- Defaults: connect=5, read=300, write=300, pool=5.
- Returns:
- LangGraphClient:
- A top-level client exposing sub-clients for assistants, threads,
- runs, and cron operations.
- ???+ example "Connect to a remote server:"
- ```python
- from langgraph_sdk import get_client
- # get top-level LangGraphClient
- client = get_client(url="http://localhost:8123")
- # example usage: client.<model>.<method_name>()
- assistants = await client.assistants.get(assistant_id="some_uuid")
- ```
- ???+ example "Connect in-process to a running LangGraph server:"
- ```python
- from langgraph_sdk import get_client
- client = get_client(url=None)
- async def my_node(...):
- subagent_result = await client.runs.wait(
- thread_id=None,
- assistant_id="agent",
- input={"messages": [{"role": "user", "content": "Foo"}]},
- )
- ```
- ???+ example "Skip auto-loading API key from environment:"
- ```python
- from langgraph_sdk import get_client
- # Don't load API key from environment variables
- client = get_client(
- url="http://localhost:8123",
- api_key=None
- )
- ```
- """
- transport: httpx.AsyncBaseTransport | None = None
- if url is None:
- url = "http://api"
- if os.environ.get("__LANGGRAPH_DEFER_LOOPBACK_TRANSPORT") == "true":
- transport = get_asgi_transport()(app=None, root_path="/noauth")
- _registered_transports.append(transport)
- else:
- try:
- from langgraph_api.server import app # type: ignore
- transport = get_asgi_transport()(app, root_path="/noauth")
- except Exception:
- logger.debug(
- "Failed to connect to in-process LangGraph server. Deferring configuration.",
- exc_info=True,
- )
- transport = get_asgi_transport()(app=None, root_path="/noauth")
- _registered_transports.append(transport)
- if transport is None:
- transport = httpx.AsyncHTTPTransport(retries=5)
- client = httpx.AsyncClient(
- base_url=url,
- transport=transport,
- timeout=(
- httpx.Timeout(timeout) # ty: ignore[invalid-argument-type]
- if timeout is not None
- else httpx.Timeout(connect=5, read=300, write=300, pool=5)
- ),
- headers=_get_headers(api_key, headers),
- )
- return LangGraphClient(client)
- class LangGraphClient:
- """Top-level client for LangGraph API.
- Attributes:
- assistants: Manages versioned configuration for your graphs.
- threads: Handles (potentially) multi-turn interactions, such as conversational threads.
- runs: Controls individual invocations of the graph.
- crons: Manages scheduled operations.
- store: Interfaces with persistent, shared data storage.
- """
- def __init__(self, client: httpx.AsyncClient) -> None:
- self.http = HttpClient(client)
- self.assistants = AssistantsClient(self.http)
- self.threads = ThreadsClient(self.http)
- self.runs = RunsClient(self.http)
- self.crons = CronClient(self.http)
- self.store = StoreClient(self.http)
- async def __aenter__(self) -> LangGraphClient:
- """Enter the async context manager."""
- return self
- async def __aexit__(
- self,
- exc_type: type[BaseException] | None,
- exc_val: BaseException | None,
- exc_tb: TracebackType | None,
- ) -> None:
- """Exit the async context manager."""
- await self.aclose()
- async def aclose(self) -> None:
- """Close the underlying HTTP client."""
- if hasattr(self, "http"):
- await self.http.client.aclose()
- class HttpClient:
- """Handle async requests to the LangGraph API.
- Adds additional error messaging & content handling above the
- provided httpx client.
- Attributes:
- client (httpx.AsyncClient): Underlying HTTPX async client.
- """
- def __init__(self, client: httpx.AsyncClient) -> None:
- self.client = client
- async def get(
- self,
- path: str,
- *,
- params: QueryParamTypes | None = None,
- headers: Mapping[str, str] | None = None,
- on_response: Callable[[httpx.Response], None] | None = None,
- ) -> Any:
- """Send a `GET` request."""
- r = await self.client.get(path, params=params, headers=headers)
- if on_response:
- on_response(r)
- await _araise_for_status_typed(r)
- return await _adecode_json(r)
- async def post(
- self,
- path: str,
- *,
- json: dict[str, Any] | list | None,
- params: QueryParamTypes | None = None,
- headers: Mapping[str, str] | None = None,
- on_response: Callable[[httpx.Response], None] | None = None,
- ) -> Any:
- """Send a `POST` request."""
- if json is not None:
- request_headers, content = await _aencode_json(json)
- else:
- request_headers, content = {}, b""
- # Merge headers, with runtime headers taking precedence
- if headers:
- request_headers.update(headers)
- r = await self.client.post(
- path, headers=request_headers, content=content, params=params
- )
- if on_response:
- on_response(r)
- await _araise_for_status_typed(r)
- return await _adecode_json(r)
- async def put(
- self,
- path: str,
- *,
- json: dict,
- params: QueryParamTypes | None = None,
- headers: Mapping[str, str] | None = None,
- on_response: Callable[[httpx.Response], None] | None = None,
- ) -> Any:
- """Send a `PUT` request."""
- request_headers, content = await _aencode_json(json)
- if headers:
- request_headers.update(headers)
- r = await self.client.put(
- path, headers=request_headers, content=content, params=params
- )
- if on_response:
- on_response(r)
- await _araise_for_status_typed(r)
- return await _adecode_json(r)
- async def patch(
- self,
- path: str,
- *,
- json: dict,
- params: QueryParamTypes | None = None,
- headers: Mapping[str, str] | None = None,
- on_response: Callable[[httpx.Response], None] | None = None,
- ) -> Any:
- """Send a `PATCH` request."""
- request_headers, content = await _aencode_json(json)
- if headers:
- request_headers.update(headers)
- r = await self.client.patch(
- path, headers=request_headers, content=content, params=params
- )
- if on_response:
- on_response(r)
- await _araise_for_status_typed(r)
- return await _adecode_json(r)
- async def delete(
- self,
- path: str,
- *,
- json: Any | None = None,
- params: QueryParamTypes | None = None,
- headers: Mapping[str, str] | None = None,
- on_response: Callable[[httpx.Response], None] | None = None,
- ) -> None:
- """Send a `DELETE` request."""
- r = await self.client.request(
- "DELETE", path, json=json, params=params, headers=headers
- )
- if on_response:
- on_response(r)
- await _araise_for_status_typed(r)
- async def request_reconnect(
- self,
- path: str,
- method: str,
- *,
- json: dict[str, Any] | None = None,
- params: QueryParamTypes | None = None,
- headers: Mapping[str, str] | None = None,
- on_response: Callable[[httpx.Response], None] | None = None,
- reconnect_limit: int = 5,
- ) -> Any:
- """Send a request that automatically reconnects to Location header."""
- request_headers, content = await _aencode_json(json)
- if headers:
- request_headers.update(headers)
- async with self.client.stream(
- method, path, headers=request_headers, content=content, params=params
- ) as r:
- if on_response:
- on_response(r)
- try:
- r.raise_for_status()
- except httpx.HTTPStatusError as e:
- body = (await r.aread()).decode()
- if sys.version_info >= (3, 11):
- e.add_note(body)
- else:
- logger.error(f"Error from langgraph-api: {body}", exc_info=e)
- raise e
- loc = r.headers.get("location")
- if reconnect_limit <= 0 or not loc:
- return await _adecode_json(r)
- try:
- return await _adecode_json(r)
- except httpx.HTTPError:
- warnings.warn(
- f"Request failed, attempting reconnect to Location: {loc}",
- stacklevel=2,
- )
- await r.aclose()
- return await self.request_reconnect(
- loc,
- "GET",
- headers=request_headers,
- # don't pass on_response so it's only called once
- reconnect_limit=reconnect_limit - 1,
- )
- async def stream(
- self,
- path: str,
- method: str,
- *,
- json: dict[str, Any] | None = None,
- params: QueryParamTypes | None = None,
- headers: Mapping[str, str] | None = None,
- on_response: Callable[[httpx.Response], None] | None = None,
- ) -> AsyncIterator[StreamPart]:
- """Stream results using SSE."""
- request_headers, content = await _aencode_json(json)
- request_headers["Accept"] = "text/event-stream"
- request_headers["Cache-Control"] = "no-store"
- # Add runtime headers with precedence
- if headers:
- request_headers.update(headers)
- reconnect_headers = {
- key: value
- for key, value in request_headers.items()
- if key.lower() not in {"content-length", "content-type"}
- }
- last_event_id: str | None = None
- reconnect_path: str | None = None
- reconnect_attempts = 0
- max_reconnect_attempts = 5
- while True:
- current_headers = dict(
- request_headers if reconnect_path is None else reconnect_headers
- )
- if last_event_id is not None:
- current_headers["Last-Event-ID"] = last_event_id
- current_method = method if reconnect_path is None else "GET"
- current_content = content if reconnect_path is None else None
- current_params = params if reconnect_path is None else None
- retry = False
- async with self.client.stream(
- current_method,
- reconnect_path or path,
- headers=current_headers,
- content=current_content,
- params=current_params,
- ) as res:
- if reconnect_path is None and on_response:
- on_response(res)
- # check status
- await _araise_for_status_typed(res)
- # check content type
- content_type = res.headers.get("content-type", "").partition(";")[0]
- if "text/event-stream" not in content_type:
- raise httpx.TransportError(
- "Expected response header Content-Type to contain 'text/event-stream', "
- f"got {content_type!r}"
- )
- reconnect_location = res.headers.get("location")
- if reconnect_location:
- reconnect_path = reconnect_location
- # parse SSE
- decoder = SSEDecoder()
- try:
- async for line in aiter_lines_raw(res):
- sse = decoder.decode(line=cast("bytes", line).rstrip(b"\n"))
- if sse is not None:
- if decoder.last_event_id is not None:
- last_event_id = decoder.last_event_id
- if sse.event or sse.data is not None:
- yield sse
- except httpx.HTTPError:
- # httpx.TransportError inherits from HTTPError, so transient
- # disconnects during streaming land here.
- if reconnect_path is None:
- raise
- retry = True
- else:
- if sse := decoder.decode(b""):
- if decoder.last_event_id is not None:
- last_event_id = decoder.last_event_id
- if sse.event or sse.data is not None:
- # decoder.decode(b"") flushes the in-flight event and may
- # return an empty placeholder when there is no pending
- # message. Skip these no-op events so the stream doesn't
- # emit a trailing blank item after reconnects.
- yield sse
- if retry:
- reconnect_attempts += 1
- if reconnect_attempts > max_reconnect_attempts:
- raise httpx.TransportError(
- "Exceeded maximum SSE reconnection attempts"
- )
- continue
- break
- async def _aencode_json(json: Any) -> tuple[dict[str, str], bytes | None]:
- if json is None:
- return {}, None
- body = await asyncio.get_running_loop().run_in_executor(
- None,
- orjson.dumps,
- json,
- _orjson_default,
- orjson.OPT_SERIALIZE_NUMPY | orjson.OPT_NON_STR_KEYS,
- )
- content_length = str(len(body))
- content_type = "application/json"
- headers = {"Content-Length": content_length, "Content-Type": content_type}
- return headers, body
- async def _adecode_json(r: httpx.Response) -> Any:
- body = await r.aread()
- return (
- await asyncio.get_running_loop().run_in_executor(None, orjson.loads, body)
- if body
- else None
- )
- class AssistantsClient:
- """Client for managing assistants in LangGraph.
- This class provides methods to interact with assistants,
- which are versioned configurations of your graph.
- ???+ example "Example"
- ```python
- client = get_client(url="http://localhost:2024")
- assistant = await client.assistants.get("assistant_id_123")
- ```
- """
- def __init__(self, http: HttpClient) -> None:
- self.http = http
- async def get(
- self,
- assistant_id: str,
- *,
- headers: Mapping[str, str] | None = None,
- params: QueryParamTypes | None = None,
- ) -> Assistant:
- """Get an assistant by ID.
- Args:
- assistant_id: The ID of the assistant to get.
- headers: Optional custom headers to include with the request.
- params: Optional query parameters to include with the request.
- Returns:
- Assistant: Assistant Object.
- ???+ example "Example Usage"
- ```python
- assistant = await client.assistants.get(
- assistant_id="my_assistant_id"
- )
- print(assistant)
- ```
- ```shell
- ----------------------------------------------------
- {
- 'assistant_id': 'my_assistant_id',
- 'graph_id': 'agent',
- 'created_at': '2024-06-25T17:10:33.109781+00:00',
- 'updated_at': '2024-06-25T17:10:33.109781+00:00',
- 'config': {},
- 'metadata': {'created_by': 'system'},
- 'version': 1,
- 'name': 'my_assistant'
- }
- ```
- """
- return await self.http.get(
- f"/assistants/{assistant_id}", headers=headers, params=params
- )
- async def get_graph(
- self,
- assistant_id: str,
- *,
- xray: int | bool = False,
- headers: Mapping[str, str] | None = None,
- params: QueryParamTypes | None = None,
- ) -> dict[str, list[dict[str, Any]]]:
- """Get the graph of an assistant by ID.
- Args:
- assistant_id: The ID of the assistant to get the graph of.
- xray: Include graph representation of subgraphs. If an integer value is provided, only subgraphs with a depth less than or equal to the value will be included.
- headers: Optional custom headers to include with the request.
- params: Optional query parameters to include with the request.
- Returns:
- Graph: The graph information for the assistant in JSON format.
- ???+ example "Example Usage"
- ```python
- client = get_client(url="http://localhost:2024")
- graph_info = await client.assistants.get_graph(
- assistant_id="my_assistant_id"
- )
- print(graph_info)
- ```
- ```shell
- --------------------------------------------------------------------------------------------------------------------------
- {
- 'nodes':
- [
- {'id': '__start__', 'type': 'schema', 'data': '__start__'},
- {'id': '__end__', 'type': 'schema', 'data': '__end__'},
- {'id': 'agent','type': 'runnable','data': {'id': ['langgraph', 'utils', 'RunnableCallable'],'name': 'agent'}},
- ],
- 'edges':
- [
- {'source': '__start__', 'target': 'agent'},
- {'source': 'agent','target': '__end__'}
- ]
- }
- ```
- """
- query_params = {"xray": xray}
- if params:
- query_params.update(params)
- return await self.http.get(
- f"/assistants/{assistant_id}/graph", params=query_params, headers=headers
- )
- async def get_schemas(
- self,
- assistant_id: str,
- *,
- headers: Mapping[str, str] | None = None,
- params: QueryParamTypes | None = None,
- ) -> GraphSchema:
- """Get the schemas of an assistant by ID.
- Args:
- assistant_id: The ID of the assistant to get the schema of.
- headers: Optional custom headers to include with the request.
- params: Optional query parameters to include with the request.
- Returns:
- GraphSchema: The graph schema for the assistant.
- ???+ example "Example Usage"
- ```python
- client = get_client(url="http://localhost:2024")
- schema = await client.assistants.get_schemas(
- assistant_id="my_assistant_id"
- )
- print(schema)
- ```
- ```shell
- ----------------------------------------------------------------------------------------------------------------------------
- {
- 'graph_id': 'agent',
- 'state_schema':
- {
- 'title': 'LangGraphInput',
- '$ref': '#/definitions/AgentState',
- 'definitions':
- {
- 'BaseMessage':
- {
- 'title': 'BaseMessage',
- 'description': 'Base abstract Message class. Messages are the inputs and outputs of ChatModels.',
- 'type': 'object',
- 'properties':
- {
- 'content':
- {
- 'title': 'Content',
- 'anyOf': [
- {'type': 'string'},
- {'type': 'array','items': {'anyOf': [{'type': 'string'}, {'type': 'object'}]}}
- ]
- },
- 'additional_kwargs':
- {
- 'title': 'Additional Kwargs',
- 'type': 'object'
- },
- 'response_metadata':
- {
- 'title': 'Response Metadata',
- 'type': 'object'
- },
- 'type':
- {
- 'title': 'Type',
- 'type': 'string'
- },
- 'name':
- {
- 'title': 'Name',
- 'type': 'string'
- },
- 'id':
- {
- 'title': 'Id',
- 'type': 'string'
- }
- },
- 'required': ['content', 'type']
- },
- 'AgentState':
- {
- 'title': 'AgentState',
- 'type': 'object',
- 'properties':
- {
- 'messages':
- {
- 'title': 'Messages',
- 'type': 'array',
- 'items': {'$ref': '#/definitions/BaseMessage'}
- }
- },
- 'required': ['messages']
- }
- }
- },
- 'context_schema':
- {
- 'title': 'Context',
- 'type': 'object',
- 'properties':
- {
- 'model_name':
- {
- 'title': 'Model Name',
- 'enum': ['anthropic', 'openai'],
- 'type': 'string'
- }
- }
- }
- }
- ```
- """
- return await self.http.get(
- f"/assistants/{assistant_id}/schemas", headers=headers, params=params
- )
- async def get_subgraphs(
- self,
- assistant_id: str,
- namespace: str | None = None,
- recurse: bool = False,
- *,
- headers: Mapping[str, str] | None = None,
- params: QueryParamTypes | None = None,
- ) -> Subgraphs:
- """Get the schemas of an assistant by ID.
- Args:
- assistant_id: The ID of the assistant to get the schema of.
- namespace: Optional namespace to filter by.
- recurse: Whether to recursively get subgraphs.
- headers: Optional custom headers to include with the request.
- params: Optional query parameters to include with the request.
- Returns:
- Subgraphs: The graph schema for the assistant.
- """
- get_params = {"recurse": recurse}
- if params:
- get_params = {**get_params, **params}
- if namespace is not None:
- return await self.http.get(
- f"/assistants/{assistant_id}/subgraphs/{namespace}",
- params=get_params,
- headers=headers,
- )
- else:
- return await self.http.get(
- f"/assistants/{assistant_id}/subgraphs",
- params=get_params,
- headers=headers,
- )
- async def create(
- self,
- graph_id: str | None,
- config: Config | None = None,
- *,
- context: Context | None = None,
- metadata: Json = None,
- assistant_id: str | None = None,
- if_exists: OnConflictBehavior | None = None,
- name: str | None = None,
- headers: Mapping[str, str] | None = None,
- description: str | None = None,
- params: QueryParamTypes | None = None,
- ) -> Assistant:
- """Create a new assistant.
- Useful when graph is configurable and you want to create different assistants based on different configurations.
- Args:
- graph_id: The ID of the graph the assistant should use. The graph ID is normally set in your langgraph.json configuration.
- config: Configuration to use for the graph.
- metadata: Metadata to add to assistant.
- context: Static context to add to the assistant.
- !!! version-added "Added in version 0.6.0"
- assistant_id: Assistant ID to use, will default to a random UUID if not provided.
- if_exists: How to handle duplicate creation. Defaults to 'raise' under the hood.
- Must be either 'raise' (raise error if duplicate), or 'do_nothing' (return existing assistant).
- name: The name of the assistant. Defaults to 'Untitled' under the hood.
- headers: Optional custom headers to include with the request.
- description: Optional description of the assistant.
- The description field is available for langgraph-api server version>=0.0.45
- params: Optional query parameters to include with the request.
- Returns:
- Assistant: The created assistant.
- ???+ example "Example Usage"
- ```python
- client = get_client(url="http://localhost:2024")
- assistant = await client.assistants.create(
- graph_id="agent",
- context={"model_name": "openai"},
- metadata={"number":1},
- assistant_id="my-assistant-id",
- if_exists="do_nothing",
- name="my_name"
- )
- ```
- """
- payload: dict[str, Any] = {
- "graph_id": graph_id,
- }
- if config:
- payload["config"] = config
- if context:
- payload["context"] = context
- if metadata:
- payload["metadata"] = metadata
- if assistant_id:
- payload["assistant_id"] = assistant_id
- if if_exists:
- payload["if_exists"] = if_exists
- if name:
- payload["name"] = name
- if description:
- payload["description"] = description
- return await self.http.post(
- "/assistants", json=payload, headers=headers, params=params
- )
- async def update(
- self,
- assistant_id: str,
- *,
- graph_id: str | None = None,
- config: Config | None = None,
- context: Context | None = None,
- metadata: Json = None,
- name: str | None = None,
- headers: Mapping[str, str] | None = None,
- description: str | None = None,
- params: QueryParamTypes | None = None,
- ) -> Assistant:
- """Update an assistant.
- Use this to point to a different graph, update the configuration, or change the metadata of an assistant.
- Args:
- assistant_id: Assistant to update.
- graph_id: The ID of the graph the assistant should use.
- The graph ID is normally set in your langgraph.json configuration. If `None`, assistant will keep pointing to same graph.
- config: Configuration to use for the graph.
- context: Static context to add to the assistant.
- !!! version-added "Added in version 0.6.0"
- metadata: Metadata to merge with existing assistant metadata.
- name: The new name for the assistant.
- headers: Optional custom headers to include with the request.
- description: Optional description of the assistant.
- The description field is available for langgraph-api server version>=0.0.45
- params: Optional query parameters to include with the request.
- Returns:
- The updated assistant.
- ???+ example "Example Usage"
- ```python
- client = get_client(url="http://localhost:2024")
- assistant = await client.assistants.update(
- assistant_id='e280dad7-8618-443f-87f1-8e41841c180f',
- graph_id="other-graph",
- context={"model_name": "anthropic"},
- metadata={"number":2}
- )
- ```
- """
- payload: dict[str, Any] = {}
- if graph_id:
- payload["graph_id"] = graph_id
- if config:
- payload["config"] = config
- if context:
- payload["context"] = context
- if metadata:
- payload["metadata"] = metadata
- if name:
- payload["name"] = name
- if description:
- payload["description"] = description
- return await self.http.patch(
- f"/assistants/{assistant_id}",
- json=payload,
- headers=headers,
- params=params,
- )
- async def delete(
- self,
- assistant_id: str,
- *,
- headers: Mapping[str, str] | None = None,
- params: QueryParamTypes | None = None,
- ) -> None:
- """Delete an assistant.
- Args:
- assistant_id: The assistant ID to delete.
- headers: Optional custom headers to include with the request.
- params: Optional query parameters to include with the request.
- Returns:
- `None`
- ???+ example "Example Usage"
- ```python
- client = get_client(url="http://localhost:2024")
- await client.assistants.delete(
- assistant_id="my_assistant_id"
- )
- ```
- """
- await self.http.delete(
- f"/assistants/{assistant_id}", headers=headers, params=params
- )
- @overload
- async def search(
- self,
- *,
- metadata: Json = None,
- graph_id: str | None = None,
- name: str | None = None,
- limit: int = 10,
- offset: int = 0,
- sort_by: AssistantSortBy | None = None,
- sort_order: SortOrder | None = None,
- select: list[AssistantSelectField] | None = None,
- response_format: Literal["object"],
- headers: Mapping[str, str] | None = None,
- params: QueryParamTypes | None = None,
- ) -> AssistantsSearchResponse: ...
- @overload
- async def search(
- self,
- *,
- metadata: Json = None,
- graph_id: str | None = None,
- name: str | None = None,
- limit: int = 10,
- offset: int = 0,
- sort_by: AssistantSortBy | None = None,
- sort_order: SortOrder | None = None,
- select: list[AssistantSelectField] | None = None,
- response_format: Literal["array"] = "array",
- headers: Mapping[str, str] | None = None,
- params: QueryParamTypes | None = None,
- ) -> list[Assistant]: ...
- async def search(
- self,
- *,
- metadata: Json = None,
- graph_id: str | None = None,
- name: str | None = None,
- limit: int = 10,
- offset: int = 0,
- sort_by: AssistantSortBy | None = None,
- sort_order: SortOrder | None = None,
- select: list[AssistantSelectField] | None = None,
- response_format: Literal["array", "object"] = "array",
- headers: Mapping[str, str] | None = None,
- params: QueryParamTypes | None = None,
- ) -> AssistantsSearchResponse | list[Assistant]:
- """Search for assistants.
- Args:
- metadata: Metadata to filter by. Exact match filter for each KV pair.
- graph_id: The ID of the graph to filter by.
- The graph ID is normally set in your langgraph.json configuration.
- name: The name of the assistant to filter by.
- The filtering logic will match assistants where 'name' is a substring (case insensitive) of the assistant name.
- limit: The maximum number of results to return.
- offset: The number of results to skip.
- sort_by: The field to sort by.
- sort_order: The order to sort by.
- select: Specific assistant fields to include in the response.
- response_format: Controls the response shape. Use ``"array"`` (default)
- to return a bare list of assistants, or ``"object"`` to return
- a mapping containing assistants plus pagination metadata.
- Defaults to "array", though this default will be changed to "object" in a future release.
- headers: Optional custom headers to include with the request.
- params: Optional query parameters to include with the request.
- Returns:
- A list of assistants (when ``response_format=\"array\"``) or a mapping
- with the assistants and the next pagination cursor (when
- ``response_format=\"object\"``).
- ???+ example "Example Usage"
- ```python
- client = get_client(url="http://localhost:2024")
- response = await client.assistants.search(
- metadata = {"name":"my_name"},
- graph_id="my_graph_id",
- limit=5,
- offset=5,
- response_format="object"
- )
- next_cursor = response["next"]
- assistants = response["assistants"]
- ```
- """
- if response_format not in ("array", "object"):
- raise ValueError(
- f"response_format must be 'array' or 'object', got {response_format!r}"
- )
- payload: dict[str, Any] = {
- "limit": limit,
- "offset": offset,
- }
- if metadata:
- payload["metadata"] = metadata
- if graph_id:
- payload["graph_id"] = graph_id
- if name:
- payload["name"] = name
- if sort_by:
- payload["sort_by"] = sort_by
- if sort_order:
- payload["sort_order"] = sort_order
- if select:
- payload["select"] = select
- next_cursor: str | None = None
- def capture_pagination(response: httpx.Response) -> None:
- nonlocal next_cursor
- next_cursor = response.headers.get("X-Pagination-Next")
- assistants = cast(
- list[Assistant],
- await self.http.post(
- "/assistants/search",
- json=payload,
- headers=headers,
- params=params,
- on_response=capture_pagination if response_format == "object" else None,
- ),
- )
- if response_format == "object":
- return {"assistants": assistants, "next": next_cursor}
- return assistants
- async def count(
- self,
- *,
- metadata: Json = None,
- graph_id: str | None = None,
- name: str | None = None,
- headers: Mapping[str, str] | None = None,
- params: QueryParamTypes | None = None,
- ) -> int:
- """Count assistants matching filters.
- Args:
- metadata: Metadata to filter by. Exact match for each key/value.
- graph_id: Optional graph id to filter by.
- name: Optional name to filter by.
- The filtering logic will match assistants where 'name' is a substring (case insensitive) of the assistant name.
- headers: Optional custom headers to include with the request.
- params: Optional query parameters to include with the request.
- Returns:
- int: Number of assistants matching the criteria.
- """
- payload: dict[str, Any] = {}
- if metadata:
- payload["metadata"] = metadata
- if graph_id:
- payload["graph_id"] = graph_id
- if name:
- payload["name"] = name
- return await self.http.post(
- "/assistants/count", json=payload, headers=headers, params=params
- )
- async def get_versions(
- self,
- assistant_id: str,
- metadata: Json = None,
- limit: int = 10,
- offset: int = 0,
- *,
- headers: Mapping[str, str] | None = None,
- params: QueryParamTypes | None = None,
- ) -> list[AssistantVersion]:
- """List all versions of an assistant.
- Args:
- assistant_id: The assistant ID to get versions for.
- metadata: Metadata to filter versions by. Exact match filter for each KV pair.
- limit: The maximum number of versions to return.
- offset: The number of versions to skip.
- headers: Optional custom headers to include with the request.
- params: Optional query parameters to include with the request.
- Returns:
- A list of assistant versions.
- ???+ example "Example Usage"
- ```python
- client = get_client(url="http://localhost:2024")
- assistant_versions = await client.assistants.get_versions(
- assistant_id="my_assistant_id"
- )
- ```
- """
- payload: dict[str, Any] = {
- "limit": limit,
- "offset": offset,
- }
- if metadata:
- payload["metadata"] = metadata
- return await self.http.post(
- f"/assistants/{assistant_id}/versions",
- json=payload,
- headers=headers,
- params=params,
- )
- async def set_latest(
- self,
- assistant_id: str,
- version: int,
- *,
- headers: Mapping[str, str] | None = None,
- params: QueryParamTypes | None = None,
- ) -> Assistant:
- """Change the version of an assistant.
- Args:
- assistant_id: The assistant ID to delete.
- version: The version to change to.
- headers: Optional custom headers to include with the request.
- params: Optional query parameters to include with the request.
- Returns:
- Assistant Object.
- ???+ example "Example Usage"
- ```python
- client = get_client(url="http://localhost:2024")
- new_version_assistant = await client.assistants.set_latest(
- assistant_id="my_assistant_id",
- version=3
- )
- ```
- """
- payload: dict[str, Any] = {"version": version}
- return await self.http.post(
- f"/assistants/{assistant_id}/latest",
- json=payload,
- headers=headers,
- params=params,
- )
- class ThreadsClient:
- """Client for managing threads in LangGraph.
- A thread maintains the state of a graph across multiple interactions/invocations (aka runs).
- It accumulates and persists the graph's state, allowing for continuity between separate
- invocations of the graph.
- ???+ example "Example"
- ```python
- client = get_client(url="http://localhost:2024"))
- new_thread = await client.threads.create(metadata={"user_id": "123"})
- ```
- """
- def __init__(self, http: HttpClient) -> None:
- self.http = http
- async def get(
- self,
- thread_id: str,
- *,
- headers: Mapping[str, str] | None = None,
- params: QueryParamTypes | None = None,
- ) -> Thread:
- """Get a thread by ID.
- Args:
- thread_id: The ID of the thread to get.
- headers: Optional custom headers to include with the request.
- params: Optional query parameters to include with the request.
- Returns:
- Thread object.
- ???+ example "Example Usage"
- ```python
- client = get_client(url="http://localhost:2024")
- thread = await client.threads.get(
- thread_id="my_thread_id"
- )
- print(thread)
- ```
- ```shell
- -----------------------------------------------------
- {
- 'thread_id': 'my_thread_id',
- 'created_at': '2024-07-18T18:35:15.540834+00:00',
- 'updated_at': '2024-07-18T18:35:15.540834+00:00',
- 'metadata': {'graph_id': 'agent'}
- }
- ```
- """
- return await self.http.get(
- f"/threads/{thread_id}", headers=headers, params=params
- )
- async def create(
- self,
- *,
- metadata: Json = None,
- thread_id: str | None = None,
- if_exists: OnConflictBehavior | None = None,
- supersteps: Sequence[dict[str, Sequence[dict[str, Any]]]] | None = None,
- graph_id: str | None = None,
- ttl: int | Mapping[str, Any] | None = None,
- headers: Mapping[str, str] | None = None,
- params: QueryParamTypes | None = None,
- ) -> Thread:
- """Create a new thread.
- Args:
- metadata: Metadata to add to thread.
- thread_id: ID of thread.
- If `None`, ID will be a randomly generated UUID.
- if_exists: How to handle duplicate creation. Defaults to 'raise' under the hood.
- Must be either 'raise' (raise error if duplicate), or 'do_nothing' (return existing thread).
- supersteps: Apply a list of supersteps when creating a thread, each containing a sequence of updates.
- Each update has `values` or `command` and `as_node`. Used for copying a thread between deployments.
- graph_id: Optional graph ID to associate with the thread.
- ttl: Optional time-to-live in minutes for the thread. You can pass an
- integer (minutes) or a mapping with keys `ttl` and optional
- `strategy` (defaults to "delete").
- headers: Optional custom headers to include with the request.
- params: Optional query parameters to include with the request.
- Returns:
- The created thread.
- ???+ example "Example Usage"
- ```python
- client = get_client(url="http://localhost:2024")
- thread = await client.threads.create(
- metadata={"number":1},
- thread_id="my-thread-id",
- if_exists="raise"
- )
- ```
- """
- payload: dict[str, Any] = {}
- if thread_id:
- payload["thread_id"] = thread_id
- if metadata or graph_id:
- payload["metadata"] = {
- **(metadata or {}),
- **({"graph_id": graph_id} if graph_id else {}),
- }
- if if_exists:
- payload["if_exists"] = if_exists
- if supersteps:
- payload["supersteps"] = [
- {
- "updates": [
- {
- "values": u["values"],
- "command": u.get("command"),
- "as_node": u["as_node"],
- }
- for u in s["updates"]
- ]
- }
- for s in supersteps
- ]
- if ttl is not None:
- if isinstance(ttl, (int, float)):
- payload["ttl"] = {"ttl": ttl, "strategy": "delete"}
- else:
- payload["ttl"] = ttl
- return await self.http.post(
- "/threads", json=payload, headers=headers, params=params
- )
- async def update(
- self,
- thread_id: str,
- *,
- metadata: Mapping[str, Any],
- ttl: int | Mapping[str, Any] | None = None,
- headers: Mapping[str, str] | None = None,
- params: QueryParamTypes | None = None,
- ) -> Thread:
- """Update a thread.
- Args:
- thread_id: ID of thread to update.
- metadata: Metadata to merge with existing thread metadata.
- ttl: Optional time-to-live in minutes for the thread. You can pass an
- integer (minutes) or a mapping with keys `ttl` and optional
- `strategy` (defaults to "delete").
- headers: Optional custom headers to include with the request.
- params: Optional query parameters to include with the request.
- Returns:
- The created thread.
- ???+ example "Example Usage"
- ```python
- client = get_client(url="http://localhost:2024")
- thread = await client.threads.update(
- thread_id="my-thread-id",
- metadata={"number":1},
- ttl=43_200,
- )
- ```
- """
- payload: dict[str, Any] = {"metadata": metadata}
- if ttl is not None:
- if isinstance(ttl, (int, float)):
- payload["ttl"] = {"ttl": ttl, "strategy": "delete"}
- else:
- payload["ttl"] = ttl
- return await self.http.patch(
- f"/threads/{thread_id}",
- json=payload,
- headers=headers,
- params=params,
- )
- async def delete(
- self,
- thread_id: str,
- *,
- headers: Mapping[str, str] | None = None,
- params: QueryParamTypes | None = None,
- ) -> None:
- """Delete a thread.
- Args:
- thread_id: The ID of the thread to delete.
- headers: Optional custom headers to include with the request.
- params: Optional query parameters to include with the request.
- Returns:
- `None`
- ???+ example "Example Usage"
- ```python
- client = get_client(url="http://localhost2024)
- await client.threads.delete(
- thread_id="my_thread_id"
- )
- ```
- """
- await self.http.delete(f"/threads/{thread_id}", headers=headers, params=params)
- async def search(
- self,
- *,
- metadata: Json = None,
- values: Json = None,
- ids: Sequence[str] | None = None,
- status: ThreadStatus | None = None,
- limit: int = 10,
- offset: int = 0,
- sort_by: ThreadSortBy | None = None,
- sort_order: SortOrder | None = None,
- select: list[ThreadSelectField] | None = None,
- headers: Mapping[str, str] | None = None,
- params: QueryParamTypes | None = None,
- ) -> list[Thread]:
- """Search for threads.
- Args:
- metadata: Thread metadata to filter on.
- values: State values to filter on.
- ids: List of thread IDs to filter by.
- status: Thread status to filter on.
- Must be one of 'idle', 'busy', 'interrupted' or 'error'.
- limit: Limit on number of threads to return.
- offset: Offset in threads table to start search from.
- sort_by: Sort by field.
- sort_order: Sort order.
- headers: Optional custom headers to include with the request.
- params: Optional query parameters to include with the request.
- Returns:
- List of the threads matching the search parameters.
- ???+ example "Example Usage"
- ```python
- client = get_client(url="http://localhost:2024")
- threads = await client.threads.search(
- metadata={"number":1},
- status="interrupted",
- limit=15,
- offset=5
- )
- ```
- """
- payload: dict[str, Any] = {
- "limit": limit,
- "offset": offset,
- }
- if metadata:
- payload["metadata"] = metadata
- if values:
- payload["values"] = values
- if ids:
- payload["ids"] = ids
- if status:
- payload["status"] = status
- if sort_by:
- payload["sort_by"] = sort_by
- if sort_order:
- payload["sort_order"] = sort_order
- if select:
- payload["select"] = select
- return await self.http.post(
- "/threads/search",
- json=payload,
- headers=headers,
- params=params,
- )
- async def count(
- self,
- *,
- metadata: Json = None,
- values: Json = None,
- status: ThreadStatus | None = None,
- headers: Mapping[str, str] | None = None,
- params: QueryParamTypes | None = None,
- ) -> int:
- """Count threads matching filters.
- Args:
- metadata: Thread metadata to filter on.
- values: State values to filter on.
- status: Thread status to filter on.
- headers: Optional custom headers to include with the request.
- params: Optional query parameters to include with the request.
- Returns:
- int: Number of threads matching the criteria.
- """
- payload: dict[str, Any] = {}
- if metadata:
- payload["metadata"] = metadata
- if values:
- payload["values"] = values
- if status:
- payload["status"] = status
- return await self.http.post(
- "/threads/count", json=payload, headers=headers, params=params
- )
- async def copy(
- self,
- thread_id: str,
- *,
- headers: Mapping[str, str] | None = None,
- params: QueryParamTypes | None = None,
- ) -> None:
- """Copy a thread.
- Args:
- thread_id: The ID of the thread to copy.
- headers: Optional custom headers to include with the request.
- params: Optional query parameters to include with the request.
- Returns:
- `None`
- ???+ example "Example Usage"
- ```python
- client = get_client(url="http://localhost:2024)
- await client.threads.copy(
- thread_id="my_thread_id"
- )
- ```
- """
- return await self.http.post(
- f"/threads/{thread_id}/copy", json=None, headers=headers, params=params
- )
- async def get_state(
- self,
- thread_id: str,
- checkpoint: Checkpoint | None = None,
- checkpoint_id: str | None = None, # deprecated
- *,
- subgraphs: bool = False,
- headers: Mapping[str, str] | None = None,
- params: QueryParamTypes | None = None,
- ) -> ThreadState:
- """Get the state of a thread.
- Args:
- thread_id: The ID of the thread to get the state of.
- checkpoint: The checkpoint to get the state of.
- checkpoint_id: (deprecated) The checkpoint ID to get the state of.
- subgraphs: Include subgraphs states.
- headers: Optional custom headers to include with the request.
- params: Optional query parameters to include with the request.
- Returns:
- The thread of the state.
- ???+ example "Example Usage"
- ```python
- client = get_client(url="http://localhost:2024)
- thread_state = await client.threads.get_state(
- thread_id="my_thread_id",
- checkpoint_id="my_checkpoint_id"
- )
- print(thread_state)
- ```
- ```shell
- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------
- {
- 'values': {
- 'messages': [
- {
- 'content': 'how are you?',
- 'additional_kwargs': {},
- 'response_metadata': {},
- 'type': 'human',
- 'name': None,
- 'id': 'fe0a5778-cfe9-42ee-b807-0adaa1873c10',
- 'example': False
- },
- {
- 'content': "I'm doing well, thanks for asking! I'm an AI assistant created by Anthropic to be helpful, honest, and harmless.",
- 'additional_kwargs': {},
- 'response_metadata': {},
- 'type': 'ai',
- 'name': None,
- 'id': 'run-159b782c-b679-4830-83c6-cef87798fe8b',
- 'example': False,
- 'tool_calls': [],
- 'invalid_tool_calls': [],
- 'usage_metadata': None
- }
- ]
- },
- 'next': [],
- 'checkpoint':
- {
- 'thread_id': 'e2496803-ecd5-4e0c-a779-3226296181c2',
- 'checkpoint_ns': '',
- 'checkpoint_id': '1ef4a9b8-e6fb-67b1-8001-abd5184439d1'
- }
- 'metadata':
- {
- 'step': 1,
- 'run_id': '1ef4a9b8-d7da-679a-a45a-872054341df2',
- 'source': 'loop',
- 'writes':
- {
- 'agent':
- {
- 'messages': [
- {
- 'id': 'run-159b782c-b679-4830-83c6-cef87798fe8b',
- 'name': None,
- 'type': 'ai',
- 'content': "I'm doing well, thanks for asking! I'm an AI assistant created by Anthropic to be helpful, honest, and harmless.",
- 'example': False,
- 'tool_calls': [],
- 'usage_metadata': None,
- 'additional_kwargs': {},
- 'response_metadata': {},
- 'invalid_tool_calls': []
- }
- ]
- }
- },
- 'user_id': None,
- 'graph_id': 'agent',
- 'thread_id': 'e2496803-ecd5-4e0c-a779-3226296181c2',
- 'created_by': 'system',
- 'assistant_id': 'fe096781-5601-53d2-b2f6-0d3403f7e9ca'},
- 'created_at': '2024-07-25T15:35:44.184703+00:00',
- 'parent_config':
- {
- 'thread_id': 'e2496803-ecd5-4e0c-a779-3226296181c2',
- 'checkpoint_ns': '',
- 'checkpoint_id': '1ef4a9b8-d80d-6fa7-8000-9300467fad0f'
- }
- }
- ```
- """
- if checkpoint:
- return await self.http.post(
- f"/threads/{thread_id}/state/checkpoint",
- json={"checkpoint": checkpoint, "subgraphs": subgraphs},
- headers=headers,
- params=params,
- )
- elif checkpoint_id:
- get_params = {"subgraphs": subgraphs}
- if params:
- get_params = {**get_params, **params}
- return await self.http.get(
- f"/threads/{thread_id}/state/{checkpoint_id}",
- params=get_params,
- headers=headers,
- )
- else:
- get_params = {"subgraphs": subgraphs}
- if params:
- get_params = {**get_params, **params}
- return await self.http.get(
- f"/threads/{thread_id}/state",
- params=get_params,
- headers=headers,
- )
- async def update_state(
- self,
- thread_id: str,
- values: dict[str, Any] | Sequence[dict] | None,
- *,
- as_node: str | None = None,
- checkpoint: Checkpoint | None = None,
- checkpoint_id: str | None = None, # deprecated
- headers: Mapping[str, str] | None = None,
- params: QueryParamTypes | None = None,
- ) -> ThreadUpdateStateResponse:
- """Update the state of a thread.
- Args:
- thread_id: The ID of the thread to update.
- values: The values to update the state with.
- as_node: Update the state as if this node had just executed.
- checkpoint: The checkpoint to update the state of.
- checkpoint_id: (deprecated) The checkpoint ID to update the state of.
- headers: Optional custom headers to include with the request.
- params: Optional query parameters to include with the request.
- Returns:
- Response after updating a thread's state.
- ???+ example "Example Usage"
- ```python
- client = get_client(url="http://localhost:2024)
- response = await client.threads.update_state(
- thread_id="my_thread_id",
- values={"messages":[{"role": "user", "content": "hello!"}]},
- as_node="my_node",
- )
- print(response)
- ```
- ```shell
- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------
- {
- 'checkpoint': {
- 'thread_id': 'e2496803-ecd5-4e0c-a779-3226296181c2',
- 'checkpoint_ns': '',
- 'checkpoint_id': '1ef4a9b8-e6fb-67b1-8001-abd5184439d1',
- 'checkpoint_map': {}
- }
- }
- ```
- """
- payload: dict[str, Any] = {
- "values": values,
- }
- if checkpoint_id:
- payload["checkpoint_id"] = checkpoint_id
- if checkpoint:
- payload["checkpoint"] = checkpoint
- if as_node:
- payload["as_node"] = as_node
- return await self.http.post(
- f"/threads/{thread_id}/state", json=payload, headers=headers, params=params
- )
- async def get_history(
- self,
- thread_id: str,
- *,
- limit: int = 10,
- before: str | Checkpoint | None = None,
- metadata: Mapping[str, Any] | None = None,
- checkpoint: Checkpoint | None = None,
- headers: Mapping[str, str] | None = None,
- params: QueryParamTypes | None = None,
- ) -> list[ThreadState]:
- """Get the state history of a thread.
- Args:
- thread_id: The ID of the thread to get the state history for.
- checkpoint: Return states for this subgraph. If empty defaults to root.
- limit: The maximum number of states to return.
- before: Return states before this checkpoint.
- metadata: Filter states by metadata key-value pairs.
- headers: Optional custom headers to include with the request.
- params: Optional query parameters to include with the request.
- Returns:
- The state history of the thread.
- ???+ example "Example Usage"
- ```python
- client = get_client(url="http://localhost:2024)
- thread_state = await client.threads.get_history(
- thread_id="my_thread_id",
- limit=5,
- )
- ```
- """
- payload: dict[str, Any] = {
- "limit": limit,
- }
- if before:
- payload["before"] = before
- if metadata:
- payload["metadata"] = metadata
- if checkpoint:
- payload["checkpoint"] = checkpoint
- return await self.http.post(
- f"/threads/{thread_id}/history",
- json=payload,
- headers=headers,
- params=params,
- )
- async def join_stream(
- self,
- thread_id: str,
- *,
- last_event_id: str | None = None,
- stream_mode: ThreadStreamMode | Sequence[ThreadStreamMode] = "run_modes",
- headers: Mapping[str, str] | None = None,
- params: QueryParamTypes | None = None,
- ) -> AsyncIterator[StreamPart]:
- """Get a stream of events for a thread.
- Args:
- thread_id: The ID of the thread to get the stream for.
- last_event_id: The ID of the last event to get.
- headers: Optional custom headers to include with the request.
- params: Optional query parameters to include with the request.
- Returns:
- An iterator of stream parts.
- ???+ example "Example Usage"
- ```python
- for chunk in client.threads.join_stream(
- thread_id="my_thread_id",
- last_event_id="my_event_id",
- ):
- print(chunk)
- ```
- """
- query_params = {
- "stream_mode": stream_mode,
- }
- if params:
- query_params.update(params)
- return self.http.stream(
- f"/threads/{thread_id}/stream",
- "GET",
- headers={
- **({"Last-Event-ID": last_event_id} if last_event_id else {}),
- **(headers or {}),
- },
- params=query_params,
- )
- class RunsClient:
- """Client for managing runs in LangGraph.
- A run is a single assistant invocation with optional input, config, context, and metadata.
- This client manages runs, which can be stateful (on threads) or stateless.
- ???+ example "Example"
- ```python
- client = get_client(url="http://localhost:2024")
- run = await client.runs.create(assistant_id="asst_123", thread_id="thread_456", input={"query": "Hello"})
- ```
- """
- def __init__(self, http: HttpClient) -> None:
- self.http = http
- @overload
- def stream(
- self,
- thread_id: str,
- assistant_id: str,
- *,
- input: Input | None = None,
- command: Command | None = None,
- stream_mode: StreamMode | Sequence[StreamMode] = "values",
- stream_subgraphs: bool = False,
- stream_resumable: bool = False,
- metadata: Mapping[str, Any] | None = None,
- config: Config | None = None,
- context: Context | None = None,
- checkpoint: Checkpoint | None = None,
- checkpoint_id: str | None = None,
- checkpoint_during: bool | None = None,
- interrupt_before: All | Sequence[str] | None = None,
- interrupt_after: All | Sequence[str] | None = None,
- feedback_keys: Sequence[str] | None = None,
- on_disconnect: DisconnectMode | None = None,
- webhook: str | None = None,
- multitask_strategy: MultitaskStrategy | None = None,
- if_not_exists: IfNotExists | None = None,
- after_seconds: int | None = None,
- headers: Mapping[str, str] | None = None,
- params: QueryParamTypes | None = None,
- on_run_created: Callable[[RunCreateMetadata], None] | None = None,
- ) -> AsyncIterator[StreamPart]: ...
- @overload
- def stream(
- self,
- thread_id: None,
- assistant_id: str,
- *,
- input: Input | None = None,
- command: Command | None = None,
- stream_mode: StreamMode | Sequence[StreamMode] = "values",
- stream_subgraphs: bool = False,
- stream_resumable: bool = False,
- metadata: Mapping[str, Any] | None = None,
- config: Config | None = None,
- checkpoint_during: bool | None = None,
- interrupt_before: All | Sequence[str] | None = None,
- interrupt_after: All | Sequence[str] | None = None,
- feedback_keys: Sequence[str] | None = None,
- on_disconnect: DisconnectMode | None = None,
- on_completion: OnCompletionBehavior | None = None,
- if_not_exists: IfNotExists | None = None,
- webhook: str | None = None,
- after_seconds: int | None = None,
- headers: Mapping[str, str] | None = None,
- params: QueryParamTypes | None = None,
- on_run_created: Callable[[RunCreateMetadata], None] | None = None,
- ) -> AsyncIterator[StreamPart]: ...
- def stream(
- self,
- thread_id: str | None,
- assistant_id: str,
- *,
- input: Input | None = None,
- command: Command | None = None,
- stream_mode: StreamMode | Sequence[StreamMode] = "values",
- stream_subgraphs: bool = False,
- stream_resumable: bool = False,
- metadata: Mapping[str, Any] | None = None,
- config: Config | None = None,
- context: Context | None = None,
- checkpoint: Checkpoint | None = None,
- checkpoint_id: str | None = None,
- checkpoint_during: bool | None = None, # deprecated
- interrupt_before: All | Sequence[str] | None = None,
- interrupt_after: All | Sequence[str] | None = None,
- feedback_keys: Sequence[str] | None = None,
- on_disconnect: DisconnectMode | None = None,
- on_completion: OnCompletionBehavior | None = None,
- webhook: str | None = None,
- multitask_strategy: MultitaskStrategy | None = None,
- if_not_exists: IfNotExists | None = None,
- after_seconds: int | None = None,
- headers: Mapping[str, str] | None = None,
- params: QueryParamTypes | None = None,
- on_run_created: Callable[[RunCreateMetadata], None] | None = None,
- durability: Durability | None = None,
- ) -> AsyncIterator[StreamPart]:
- """Create a run and stream the results.
- Args:
- thread_id: the thread ID to assign to the thread.
- If `None` will create a stateless run.
- assistant_id: The assistant ID or graph name to stream from.
- If using graph name, will default to first assistant created from that graph.
- input: The input to the graph.
- command: A command to execute. Cannot be combined with input.
- stream_mode: The stream mode(s) to use.
- stream_subgraphs: Whether to stream output from subgraphs.
- stream_resumable: Whether the stream is considered resumable.
- If true, the stream can be resumed and replayed in its entirety even after disconnection.
- metadata: Metadata to assign to the run.
- config: The configuration for the assistant.
- context: Static context to add to the assistant.
- !!! version-added "Added in version 0.6.0"
- checkpoint: The checkpoint to resume from.
- checkpoint_during: (deprecated) Whether to checkpoint during the run (or only at the end/interruption).
- interrupt_before: Nodes to interrupt immediately before they get executed.
- interrupt_after: Nodes to Nodes to interrupt immediately after they get executed.
- feedback_keys: Feedback keys to assign to run.
- on_disconnect: The disconnect mode to use.
- Must be one of 'cancel' or 'continue'.
- on_completion: Whether to delete or keep the thread created for a stateless run.
- Must be one of 'delete' or 'keep'.
- webhook: Webhook to call after LangGraph API call is done.
- multitask_strategy: Multitask strategy to use.
- Must be one of 'reject', 'interrupt', 'rollback', or 'enqueue'.
- if_not_exists: How to handle missing thread. Defaults to 'reject'.
- Must be either 'reject' (raise error if missing), or 'create' (create new thread).
- after_seconds: The number of seconds to wait before starting the run.
- Use to schedule future runs.
- headers: Optional custom headers to include with the request.
- params: Optional query parameters to include with the request.
- on_run_created: Callback when a run is created.
- durability: The durability to use for the run. Values are "sync", "async", or "exit".
- "async" means checkpoints are persisted async while next graph step executes, replaces checkpoint_during=True
- "sync" means checkpoints are persisted sync after graph step executes, replaces checkpoint_during=False
- "exit" means checkpoints are only persisted when the run exits, does not save intermediate steps
- Returns:
- Asynchronous iterator of stream results.
- ???+ example "Example Usage"
- ```python
- client = get_client(url="http://localhost:2024)
- async for chunk in client.runs.stream(
- thread_id=None,
- assistant_id="agent",
- input={"messages": [{"role": "user", "content": "how are you?"}]},
- stream_mode=["values","debug"],
- metadata={"name":"my_run"},
- context={"model_name": "anthropic"},
- interrupt_before=["node_to_stop_before_1","node_to_stop_before_2"],
- interrupt_after=["node_to_stop_after_1","node_to_stop_after_2"],
- feedback_keys=["my_feedback_key_1","my_feedback_key_2"],
- webhook="https://my.fake.webhook.com",
- multitask_strategy="interrupt"
- ):
- print(chunk)
- ```
- ```shell
- ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
- StreamPart(event='metadata', data={'run_id': '1ef4a9b8-d7da-679a-a45a-872054341df2'})
- StreamPart(event='values', data={'messages': [{'content': 'how are you?', 'additional_kwargs': {}, 'response_metadata': {}, 'type': 'human', 'name': None, 'id': 'fe0a5778-cfe9-42ee-b807-0adaa1873c10', 'example': False}]})
- StreamPart(event='values', data={'messages': [{'content': 'how are you?', 'additional_kwargs': {}, 'response_metadata': {}, 'type': 'human', 'name': None, 'id': 'fe0a5778-cfe9-42ee-b807-0adaa1873c10', 'example': False}, {'content': "I'm doing well, thanks for asking! I'm an AI assistant created by Anthropic to be helpful, honest, and harmless.", 'additional_kwargs': {}, 'response_metadata': {}, 'type': 'ai', 'name': None, 'id': 'run-159b782c-b679-4830-83c6-cef87798fe8b', 'example': False, 'tool_calls': [], 'invalid_tool_calls': [], 'usage_metadata': None}]})
- StreamPart(event='end', data=None)
- ```
- """
- if checkpoint_during is not None:
- warnings.warn(
- "`checkpoint_during` is deprecated and will be removed in a future version. Use `durability` instead.",
- DeprecationWarning,
- stacklevel=2,
- )
- payload = {
- "input": input,
- "command": (
- {k: v for k, v in command.items() if v is not None} if command else None
- ),
- "config": config,
- "context": context,
- "metadata": metadata,
- "stream_mode": stream_mode,
- "stream_subgraphs": stream_subgraphs,
- "stream_resumable": stream_resumable,
- "assistant_id": assistant_id,
- "interrupt_before": interrupt_before,
- "interrupt_after": interrupt_after,
- "feedback_keys": feedback_keys,
- "webhook": webhook,
- "checkpoint": checkpoint,
- "checkpoint_id": checkpoint_id,
- "checkpoint_during": checkpoint_during,
- "multitask_strategy": multitask_strategy,
- "if_not_exists": if_not_exists,
- "on_disconnect": on_disconnect,
- "on_completion": on_completion,
- "after_seconds": after_seconds,
- "durability": durability,
- }
- endpoint = (
- f"/threads/{thread_id}/runs/stream"
- if thread_id is not None
- else "/runs/stream"
- )
- def on_response(res: httpx.Response):
- """Callback function to handle the response."""
- if on_run_created and (metadata := _get_run_metadata_from_response(res)):
- on_run_created(metadata)
- return self.http.stream(
- endpoint,
- "POST",
- json={k: v for k, v in payload.items() if v is not None},
- params=params,
- headers=headers,
- on_response=on_response if on_run_created else None,
- )
- @overload
- async def create(
- self,
- thread_id: None,
- assistant_id: str,
- *,
- input: Input | None = None,
- command: Command | None = None,
- stream_mode: StreamMode | Sequence[StreamMode] = "values",
- stream_subgraphs: bool = False,
- stream_resumable: bool = False,
- metadata: Mapping[str, Any] | None = None,
- checkpoint_during: bool | None = None,
- config: Config | None = None,
- context: Context | None = None,
- interrupt_before: All | Sequence[str] | None = None,
- interrupt_after: All | Sequence[str] | None = None,
- webhook: str | None = None,
- on_completion: OnCompletionBehavior | None = None,
- if_not_exists: IfNotExists | None = None,
- after_seconds: int | None = None,
- headers: Mapping[str, str] | None = None,
- params: QueryParamTypes | None = None,
- on_run_created: Callable[[RunCreateMetadata], None] | None = None,
- ) -> Run: ...
- @overload
- async def create(
- self,
- thread_id: str,
- assistant_id: str,
- *,
- input: Input | None = None,
- command: Command | None = None,
- stream_mode: StreamMode | Sequence[StreamMode] = "values",
- stream_subgraphs: bool = False,
- stream_resumable: bool = False,
- metadata: Mapping[str, Any] | None = None,
- config: Config | None = None,
- context: Context | None = None,
- checkpoint: Checkpoint | None = None,
- checkpoint_id: str | None = None,
- checkpoint_during: bool | None = None,
- interrupt_before: All | Sequence[str] | None = None,
- interrupt_after: All | Sequence[str] | None = None,
- webhook: str | None = None,
- multitask_strategy: MultitaskStrategy | None = None,
- if_not_exists: IfNotExists | None = None,
- after_seconds: int | None = None,
- headers: Mapping[str, str] | None = None,
- params: QueryParamTypes | None = None,
- on_run_created: Callable[[RunCreateMetadata], None] | None = None,
- ) -> Run: ...
- async def create(
- self,
- thread_id: str | None,
- assistant_id: str,
- *,
- input: Input | None = None,
- command: Command | None = None,
- stream_mode: StreamMode | Sequence[StreamMode] = "values",
- stream_subgraphs: bool = False,
- stream_resumable: bool = False,
- metadata: Mapping[str, Any] | None = None,
- config: Config | None = None,
- context: Context | None = None,
- checkpoint: Checkpoint | None = None,
- checkpoint_id: str | None = None,
- checkpoint_during: bool | None = None, # deprecated
- interrupt_before: All | Sequence[str] | None = None,
- interrupt_after: All | Sequence[str] | None = None,
- webhook: str | None = None,
- multitask_strategy: MultitaskStrategy | None = None,
- if_not_exists: IfNotExists | None = None,
- on_completion: OnCompletionBehavior | None = None,
- after_seconds: int | None = None,
- headers: Mapping[str, str] | None = None,
- params: QueryParamTypes | None = None,
- on_run_created: Callable[[RunCreateMetadata], None] | None = None,
- durability: Durability | None = None,
- ) -> Run:
- """Create a background run.
- Args:
- thread_id: the thread ID to assign to the thread.
- If `None` will create a stateless run.
- assistant_id: The assistant ID or graph name to stream from.
- If using graph name, will default to first assistant created from that graph.
- input: The input to the graph.
- command: A command to execute. Cannot be combined with input.
- stream_mode: The stream mode(s) to use.
- stream_subgraphs: Whether to stream output from subgraphs.
- stream_resumable: Whether the stream is considered resumable.
- If true, the stream can be resumed and replayed in its entirety even after disconnection.
- metadata: Metadata to assign to the run.
- config: The configuration for the assistant.
- context: Static context to add to the assistant.
- !!! version-added "Added in version 0.6.0"
- checkpoint: The checkpoint to resume from.
- checkpoint_during: (deprecated) Whether to checkpoint during the run (or only at the end/interruption).
- interrupt_before: Nodes to interrupt immediately before they get executed.
- interrupt_after: Nodes to Nodes to interrupt immediately after they get executed.
- webhook: Webhook to call after LangGraph API call is done.
- multitask_strategy: Multitask strategy to use.
- Must be one of 'reject', 'interrupt', 'rollback', or 'enqueue'.
- on_completion: Whether to delete or keep the thread created for a stateless run.
- Must be one of 'delete' or 'keep'.
- if_not_exists: How to handle missing thread. Defaults to 'reject'.
- Must be either 'reject' (raise error if missing), or 'create' (create new thread).
- after_seconds: The number of seconds to wait before starting the run.
- Use to schedule future runs.
- headers: Optional custom headers to include with the request.
- on_run_created: Optional callback to call when a run is created.
- durability: The durability to use for the run. Values are "sync", "async", or "exit".
- "async" means checkpoints are persisted async while next graph step executes, replaces checkpoint_during=True
- "sync" means checkpoints are persisted sync after graph step executes, replaces checkpoint_during=False
- "exit" means checkpoints are only persisted when the run exits, does not save intermediate steps
- Returns:
- The created background run.
- ???+ example "Example Usage"
- ```python
- background_run = await client.runs.create(
- thread_id="my_thread_id",
- assistant_id="my_assistant_id",
- input={"messages": [{"role": "user", "content": "hello!"}]},
- metadata={"name":"my_run"},
- context={"model_name": "openai"},
- interrupt_before=["node_to_stop_before_1","node_to_stop_before_2"],
- interrupt_after=["node_to_stop_after_1","node_to_stop_after_2"],
- webhook="https://my.fake.webhook.com",
- multitask_strategy="interrupt"
- )
- print(background_run)
- ```
- ```shell
- --------------------------------------------------------------------------------
- {
- 'run_id': 'my_run_id',
- 'thread_id': 'my_thread_id',
- 'assistant_id': 'my_assistant_id',
- 'created_at': '2024-07-25T15:35:42.598503+00:00',
- 'updated_at': '2024-07-25T15:35:42.598503+00:00',
- 'metadata': {},
- 'status': 'pending',
- 'kwargs':
- {
- 'input':
- {
- 'messages': [
- {
- 'role': 'user',
- 'content': 'how are you?'
- }
- ]
- },
- 'config':
- {
- 'metadata':
- {
- 'created_by': 'system'
- },
- 'configurable':
- {
- 'run_id': 'my_run_id',
- 'user_id': None,
- 'graph_id': 'agent',
- 'thread_id': 'my_thread_id',
- 'checkpoint_id': None,
- 'assistant_id': 'my_assistant_id'
- },
- },
- 'context':
- {
- 'model_name': 'openai'
- }
- 'webhook': "https://my.fake.webhook.com",
- 'temporary': False,
- 'stream_mode': ['values'],
- 'feedback_keys': None,
- 'interrupt_after': ["node_to_stop_after_1","node_to_stop_after_2"],
- 'interrupt_before': ["node_to_stop_before_1","node_to_stop_before_2"]
- },
- 'multitask_strategy': 'interrupt'
- }
- ```
- """
- if checkpoint_during is not None:
- warnings.warn(
- "`checkpoint_during` is deprecated and will be removed in a future version. Use `durability` instead.",
- DeprecationWarning,
- stacklevel=2,
- )
- payload = {
- "input": input,
- "command": (
- {k: v for k, v in command.items() if v is not None} if command else None
- ),
- "stream_mode": stream_mode,
- "stream_subgraphs": stream_subgraphs,
- "stream_resumable": stream_resumable,
- "config": config,
- "context": context,
- "metadata": metadata,
- "assistant_id": assistant_id,
- "interrupt_before": interrupt_before,
- "interrupt_after": interrupt_after,
- "webhook": webhook,
- "checkpoint": checkpoint,
- "checkpoint_id": checkpoint_id,
- "checkpoint_during": checkpoint_during,
- "multitask_strategy": multitask_strategy,
- "if_not_exists": if_not_exists,
- "on_completion": on_completion,
- "after_seconds": after_seconds,
- "durability": durability,
- }
- payload = {k: v for k, v in payload.items() if v is not None}
- def on_response(res: httpx.Response):
- """Callback function to handle the response."""
- if on_run_created and (metadata := _get_run_metadata_from_response(res)):
- on_run_created(metadata)
- return await self.http.post(
- f"/threads/{thread_id}/runs" if thread_id else "/runs",
- json=payload,
- params=params,
- headers=headers,
- on_response=on_response if on_run_created else None,
- )
- async def create_batch(
- self,
- payloads: list[RunCreate],
- *,
- headers: Mapping[str, str] | None = None,
- params: QueryParamTypes | None = None,
- ) -> list[Run]:
- """Create a batch of stateless background runs."""
- def filter_payload(payload: RunCreate):
- return {k: v for k, v in payload.items() if v is not None}
- filtered = [filter_payload(payload) for payload in payloads]
- return await self.http.post(
- "/runs/batch", json=filtered, headers=headers, params=params
- )
- @overload
- async def wait(
- self,
- thread_id: str,
- assistant_id: str,
- *,
- input: Input | None = None,
- command: Command | None = None,
- metadata: Mapping[str, Any] | None = None,
- config: Config | None = None,
- context: Context | None = None,
- checkpoint: Checkpoint | None = None,
- checkpoint_id: str | None = None,
- checkpoint_during: bool | None = None,
- interrupt_before: All | Sequence[str] | None = None,
- interrupt_after: All | Sequence[str] | None = None,
- webhook: str | None = None,
- on_disconnect: DisconnectMode | None = None,
- multitask_strategy: MultitaskStrategy | None = None,
- if_not_exists: IfNotExists | None = None,
- after_seconds: int | None = None,
- raise_error: bool = True,
- headers: Mapping[str, str] | None = None,
- params: QueryParamTypes | None = None,
- on_run_created: Callable[[RunCreateMetadata], None] | None = None,
- ) -> list[dict] | dict[str, Any]: ...
- @overload
- async def wait(
- self,
- thread_id: None,
- assistant_id: str,
- *,
- input: Input | None = None,
- command: Command | None = None,
- metadata: Mapping[str, Any] | None = None,
- config: Config | None = None,
- context: Context | None = None,
- checkpoint_during: bool | None = None,
- interrupt_before: All | Sequence[str] | None = None,
- interrupt_after: All | Sequence[str] | None = None,
- webhook: str | None = None,
- on_disconnect: DisconnectMode | None = None,
- on_completion: OnCompletionBehavior | None = None,
- if_not_exists: IfNotExists | None = None,
- after_seconds: int | None = None,
- raise_error: bool = True,
- headers: Mapping[str, str] | None = None,
- params: QueryParamTypes | None = None,
- on_run_created: Callable[[RunCreateMetadata], None] | None = None,
- ) -> list[dict] | dict[str, Any]: ...
- async def wait(
- self,
- thread_id: str | None,
- assistant_id: str,
- *,
- input: Input | None = None,
- command: Command | None = None,
- metadata: Mapping[str, Any] | None = None,
- config: Config | None = None,
- context: Context | None = None,
- checkpoint: Checkpoint | None = None,
- checkpoint_id: str | None = None,
- checkpoint_during: bool | None = None, # deprecated
- interrupt_before: All | Sequence[str] | None = None,
- interrupt_after: All | Sequence[str] | None = None,
- webhook: str | None = None,
- on_disconnect: DisconnectMode | None = None,
- on_completion: OnCompletionBehavior | None = None,
- multitask_strategy: MultitaskStrategy | None = None,
- if_not_exists: IfNotExists | None = None,
- after_seconds: int | None = None,
- raise_error: bool = True,
- headers: Mapping[str, str] | None = None,
- params: QueryParamTypes | None = None,
- on_run_created: Callable[[RunCreateMetadata], None] | None = None,
- durability: Durability | None = None,
- ) -> list[dict] | dict[str, Any]:
- """Create a run, wait until it finishes and return the final state.
- Args:
- thread_id: the thread ID to create the run on.
- If `None` will create a stateless run.
- assistant_id: The assistant ID or graph name to run.
- If using graph name, will default to first assistant created from that graph.
- input: The input to the graph.
- command: A command to execute. Cannot be combined with input.
- metadata: Metadata to assign to the run.
- config: The configuration for the assistant.
- context: Static context to add to the assistant.
- !!! version-added "Added in version 0.6.0"
- checkpoint: The checkpoint to resume from.
- checkpoint_during: (deprecated) Whether to checkpoint during the run (or only at the end/interruption).
- interrupt_before: Nodes to interrupt immediately before they get executed.
- interrupt_after: Nodes to Nodes to interrupt immediately after they get executed.
- webhook: Webhook to call after LangGraph API call is done.
- on_disconnect: The disconnect mode to use.
- Must be one of 'cancel' or 'continue'.
- on_completion: Whether to delete or keep the thread created for a stateless run.
- Must be one of 'delete' or 'keep'.
- multitask_strategy: Multitask strategy to use.
- Must be one of 'reject', 'interrupt', 'rollback', or 'enqueue'.
- if_not_exists: How to handle missing thread. Defaults to 'reject'.
- Must be either 'reject' (raise error if missing), or 'create' (create new thread).
- after_seconds: The number of seconds to wait before starting the run.
- Use to schedule future runs.
- headers: Optional custom headers to include with the request.
- on_run_created: Optional callback to call when a run is created.
- durability: The durability to use for the run. Values are "sync", "async", or "exit".
- "async" means checkpoints are persisted async while next graph step executes, replaces checkpoint_during=True
- "sync" means checkpoints are persisted sync after graph step executes, replaces checkpoint_during=False
- "exit" means checkpoints are only persisted when the run exits, does not save intermediate steps
- Returns:
- The output of the run.
- ???+ example "Example Usage"
- ```python
- client = get_client(url="http://localhost:2024")
- final_state_of_run = await client.runs.wait(
- thread_id=None,
- assistant_id="agent",
- input={"messages": [{"role": "user", "content": "how are you?"}]},
- metadata={"name":"my_run"},
- context={"model_name": "anthropic"},
- interrupt_before=["node_to_stop_before_1","node_to_stop_before_2"],
- interrupt_after=["node_to_stop_after_1","node_to_stop_after_2"],
- webhook="https://my.fake.webhook.com",
- multitask_strategy="interrupt"
- )
- print(final_state_of_run)
- ```
- ```shell
- -------------------------------------------------------------------------------------------------------------------------------------------
- {
- 'messages': [
- {
- 'content': 'how are you?',
- 'additional_kwargs': {},
- 'response_metadata': {},
- 'type': 'human',
- 'name': None,
- 'id': 'f51a862c-62fe-4866-863b-b0863e8ad78a',
- 'example': False
- },
- {
- 'content': "I'm doing well, thanks for asking! I'm an AI assistant created by Anthropic to be helpful, honest, and harmless.",
- 'additional_kwargs': {},
- 'response_metadata': {},
- 'type': 'ai',
- 'name': None,
- 'id': 'run-bf1cd3c6-768f-4c16-b62d-ba6f17ad8b36',
- 'example': False,
- 'tool_calls': [],
- 'invalid_tool_calls': [],
- 'usage_metadata': None
- }
- ]
- }
- ```
- """
- if checkpoint_during is not None:
- warnings.warn(
- "`checkpoint_during` is deprecated and will be removed in a future version. Use `durability` instead.",
- DeprecationWarning,
- stacklevel=2,
- )
- payload = {
- "input": input,
- "command": (
- {k: v for k, v in command.items() if v is not None} if command else None
- ),
- "config": config,
- "context": context,
- "metadata": metadata,
- "assistant_id": assistant_id,
- "interrupt_before": interrupt_before,
- "interrupt_after": interrupt_after,
- "webhook": webhook,
- "checkpoint": checkpoint,
- "checkpoint_id": checkpoint_id,
- "multitask_strategy": multitask_strategy,
- "checkpoint_during": checkpoint_during,
- "if_not_exists": if_not_exists,
- "on_disconnect": on_disconnect,
- "on_completion": on_completion,
- "after_seconds": after_seconds,
- "durability": durability,
- }
- endpoint = (
- f"/threads/{thread_id}/runs/wait" if thread_id is not None else "/runs/wait"
- )
- def on_response(res: httpx.Response):
- """Callback function to handle the response."""
- if on_run_created and (metadata := _get_run_metadata_from_response(res)):
- on_run_created(metadata)
- response = await self.http.request_reconnect(
- endpoint,
- "POST",
- json={k: v for k, v in payload.items() if v is not None},
- params=params,
- headers=headers,
- on_response=on_response if on_run_created else None,
- )
- if (
- raise_error
- and isinstance(response, dict)
- and "__error__" in response
- and isinstance(response["__error__"], dict)
- ):
- raise Exception(
- f"{response['__error__'].get('error')}: {response['__error__'].get('message')}"
- )
- return response
- async def list(
- self,
- thread_id: str,
- *,
- limit: int = 10,
- offset: int = 0,
- status: RunStatus | None = None,
- select: list[RunSelectField] | None = None,
- headers: Mapping[str, str] | None = None,
- params: QueryParamTypes | None = None,
- ) -> list[Run]:
- """List runs.
- Args:
- thread_id: The thread ID to list runs for.
- limit: The maximum number of results to return.
- offset: The number of results to skip.
- status: The status of the run to filter by.
- headers: Optional custom headers to include with the request.
- params: Optional query parameters to include with the request.
- Returns:
- The runs for the thread.
- ???+ example "Example Usage"
- ```python
- client = get_client(url="http://localhost:2024")
- await client.runs.list(
- thread_id="thread_id",
- limit=5,
- offset=5,
- )
- ```
- """
- query_params: dict[str, Any] = {
- "limit": limit,
- "offset": offset,
- }
- if status is not None:
- query_params["status"] = status
- if select:
- query_params["select"] = select
- if params:
- query_params.update(params)
- return await self.http.get(
- f"/threads/{thread_id}/runs", params=query_params, headers=headers
- )
- async def get(
- self,
- thread_id: str,
- run_id: str,
- *,
- headers: Mapping[str, str] | None = None,
- params: QueryParamTypes | None = None,
- ) -> Run:
- """Get a run.
- Args:
- thread_id: The thread ID to get.
- run_id: The run ID to get.
- headers: Optional custom headers to include with the request.
- params: Optional query parameters to include with the request.
- Returns:
- `Run` object.
- ???+ example "Example Usage"
- ```python
- client = get_client(url="http://localhost:2024")
- run = await client.runs.get(
- thread_id="thread_id_to_delete",
- run_id="run_id_to_delete",
- )
- ```
- """
- return await self.http.get(
- f"/threads/{thread_id}/runs/{run_id}", headers=headers, params=params
- )
- async def cancel(
- self,
- thread_id: str,
- run_id: str,
- *,
- wait: bool = False,
- action: CancelAction = "interrupt",
- headers: Mapping[str, str] | None = None,
- params: QueryParamTypes | None = None,
- ) -> None:
- """Get a run.
- Args:
- thread_id: The thread ID to cancel.
- run_id: The run ID to cancel.
- wait: Whether to wait until run has completed.
- action: Action to take when cancelling the run. Possible values
- are `interrupt` or `rollback`. Default is `interrupt`.
- headers: Optional custom headers to include with the request.
- params: Optional query parameters to include with the request.
- Returns:
- `None`
- ???+ example "Example Usage"
- ```python
- client = get_client(url="http://localhost:2024")
- await client.runs.cancel(
- thread_id="thread_id_to_cancel",
- run_id="run_id_to_cancel",
- wait=True,
- action="interrupt"
- )
- ```
- """
- query_params = {
- "wait": 1 if wait else 0,
- "action": action,
- }
- if params:
- query_params.update(params)
- if wait:
- return await self.http.request_reconnect(
- f"/threads/{thread_id}/runs/{run_id}/cancel",
- "POST",
- params=query_params,
- headers=headers,
- )
- else:
- return await self.http.post(
- f"/threads/{thread_id}/runs/{run_id}/cancel",
- json=None,
- params=query_params,
- headers=headers,
- )
- async def join(
- self,
- thread_id: str,
- run_id: str,
- *,
- headers: Mapping[str, str] | None = None,
- params: QueryParamTypes | None = None,
- ) -> dict:
- """Block until a run is done. Returns the final state of the thread.
- Args:
- thread_id: The thread ID to join.
- run_id: The run ID to join.
- headers: Optional custom headers to include with the request.
- params: Optional query parameters to include with the request.
- Returns:
- `None`
- ???+ example "Example Usage"
- ```python
- client = get_client(url="http://localhost:2024")
- result =await client.runs.join(
- thread_id="thread_id_to_join",
- run_id="run_id_to_join"
- )
- ```
- """
- return await self.http.request_reconnect(
- f"/threads/{thread_id}/runs/{run_id}/join",
- "GET",
- headers=headers,
- params=params,
- )
- def join_stream(
- self,
- thread_id: str,
- run_id: str,
- *,
- cancel_on_disconnect: bool = False,
- stream_mode: StreamMode | Sequence[StreamMode] | None = None,
- headers: Mapping[str, str] | None = None,
- params: QueryParamTypes | None = None,
- last_event_id: str | None = None,
- ) -> AsyncIterator[StreamPart]:
- """Stream output from a run in real-time, until the run is done.
- Output is not buffered, so any output produced before this call will
- not be received here.
- Args:
- thread_id: The thread ID to join.
- run_id: The run ID to join.
- cancel_on_disconnect: Whether to cancel the run when the stream is disconnected.
- stream_mode: The stream mode(s) to use. Must be a subset of the stream modes passed
- when creating the run. Background runs default to having the union of all
- stream modes.
- headers: Optional custom headers to include with the request.
- params: Optional query parameters to include with the request.
- last_event_id: The last event ID to use for the stream.
- Returns:
- The stream of parts.
- ???+ example "Example Usage"
- ```python
- client = get_client(url="http://localhost:2024")
- async for part in client.runs.join_stream(
- thread_id="thread_id_to_join",
- run_id="run_id_to_join",
- stream_mode=["values", "debug"]
- ):
- print(part)
- ```
- """
- query_params = {
- "cancel_on_disconnect": cancel_on_disconnect,
- "stream_mode": stream_mode,
- }
- if params:
- query_params.update(params)
- return self.http.stream(
- f"/threads/{thread_id}/runs/{run_id}/stream",
- "GET",
- params=query_params,
- headers={
- **({"Last-Event-ID": last_event_id} if last_event_id else {}),
- **(headers or {}),
- }
- or None,
- )
- async def delete(
- self,
- thread_id: str,
- run_id: str,
- *,
- headers: Mapping[str, str] | None = None,
- params: QueryParamTypes | None = None,
- ) -> None:
- """Delete a run.
- Args:
- thread_id: The thread ID to delete.
- run_id: The run ID to delete.
- headers: Optional custom headers to include with the request.
- params: Optional query parameters to include with the request.
- Returns:
- `None`
- ???+ example "Example Usage"
- ```python
- client = get_client(url="http://localhost:2024")
- await client.runs.delete(
- thread_id="thread_id_to_delete",
- run_id="run_id_to_delete"
- )
- ```
- """
- await self.http.delete(
- f"/threads/{thread_id}/runs/{run_id}", headers=headers, params=params
- )
- class CronClient:
- """Client for managing recurrent runs (cron jobs) in LangGraph.
- A run is a single invocation of an assistant with optional input, config, and context.
- This client allows scheduling recurring runs to occur automatically.
- ???+ example "Example Usage"
- ```python
- client = get_client(url="http://localhost:2024"))
- cron_job = await client.crons.create_for_thread(
- thread_id="thread_123",
- assistant_id="asst_456",
- schedule="0 9 * * *",
- input={"message": "Daily update"}
- )
- ```
- !!! note "Feature Availability"
- The crons client functionality is not supported on all licenses.
- Please check the relevant license documentation for the most up-to-date
- details on feature availability.
- """
- def __init__(self, http_client: HttpClient) -> None:
- self.http = http_client
- async def create_for_thread(
- self,
- thread_id: str,
- assistant_id: str,
- *,
- schedule: str,
- input: Input | None = None,
- metadata: Mapping[str, Any] | None = None,
- config: Config | None = None,
- context: Context | None = None,
- checkpoint_during: bool | None = None,
- interrupt_before: All | list[str] | None = None,
- interrupt_after: All | list[str] | None = None,
- webhook: str | None = None,
- multitask_strategy: str | None = None,
- headers: Mapping[str, str] | None = None,
- params: QueryParamTypes | None = None,
- ) -> Run:
- """Create a cron job for a thread.
- Args:
- thread_id: the thread ID to run the cron job on.
- assistant_id: The assistant ID or graph name to use for the cron job.
- If using graph name, will default to first assistant created from that graph.
- schedule: The cron schedule to execute this job on.
- input: The input to the graph.
- metadata: Metadata to assign to the cron job runs.
- config: The configuration for the assistant.
- context: Static context to add to the assistant.
- !!! version-added "Added in version 0.6.0"
- checkpoint_during: Whether to checkpoint during the run (or only at the end/interruption).
- interrupt_before: Nodes to interrupt immediately before they get executed.
- interrupt_after: Nodes to Nodes to interrupt immediately after they get executed.
- webhook: Webhook to call after LangGraph API call is done.
- multitask_strategy: Multitask strategy to use.
- Must be one of 'reject', 'interrupt', 'rollback', or 'enqueue'.
- headers: Optional custom headers to include with the request.
- params: Optional query parameters to include with the request.
- Returns:
- The cron run.
- ???+ example "Example Usage"
- ```python
- client = get_client(url="http://localhost:2024")
- cron_run = await client.crons.create_for_thread(
- thread_id="my-thread-id",
- assistant_id="agent",
- schedule="27 15 * * *",
- input={"messages": [{"role": "user", "content": "hello!"}]},
- metadata={"name":"my_run"},
- context={"model_name": "openai"},
- interrupt_before=["node_to_stop_before_1","node_to_stop_before_2"],
- interrupt_after=["node_to_stop_after_1","node_to_stop_after_2"],
- webhook="https://my.fake.webhook.com",
- multitask_strategy="interrupt"
- )
- ```
- """
- payload = {
- "schedule": schedule,
- "input": input,
- "config": config,
- "metadata": metadata,
- "context": context,
- "assistant_id": assistant_id,
- "checkpoint_during": checkpoint_during,
- "interrupt_before": interrupt_before,
- "interrupt_after": interrupt_after,
- "webhook": webhook,
- }
- if multitask_strategy:
- payload["multitask_strategy"] = multitask_strategy
- payload = {k: v for k, v in payload.items() if v is not None}
- return await self.http.post(
- f"/threads/{thread_id}/runs/crons",
- json=payload,
- headers=headers,
- params=params,
- )
- async def create(
- self,
- assistant_id: str,
- *,
- schedule: str,
- input: Input | None = None,
- metadata: Mapping[str, Any] | None = None,
- config: Config | None = None,
- context: Context | None = None,
- checkpoint_during: bool | None = None,
- interrupt_before: All | list[str] | None = None,
- interrupt_after: All | list[str] | None = None,
- webhook: str | None = None,
- multitask_strategy: str | None = None,
- headers: Mapping[str, str] | None = None,
- params: QueryParamTypes | None = None,
- ) -> Run:
- """Create a cron run.
- Args:
- assistant_id: The assistant ID or graph name to use for the cron job.
- If using graph name, will default to first assistant created from that graph.
- schedule: The cron schedule to execute this job on.
- input: The input to the graph.
- metadata: Metadata to assign to the cron job runs.
- config: The configuration for the assistant.
- context: Static context to add to the assistant.
- !!! version-added "Added in version 0.6.0"
- checkpoint_during: Whether to checkpoint during the run (or only at the end/interruption).
- interrupt_before: Nodes to interrupt immediately before they get executed.
- interrupt_after: Nodes to Nodes to interrupt immediately after they get executed.
- webhook: Webhook to call after LangGraph API call is done.
- multitask_strategy: Multitask strategy to use.
- Must be one of 'reject', 'interrupt', 'rollback', or 'enqueue'.
- headers: Optional custom headers to include with the request.
- params: Optional query parameters to include with the request.
- Returns:
- The cron run.
- ???+ example "Example Usage"
- ```python
- client = get_client(url="http://localhost:2024")
- cron_run = client.crons.create(
- assistant_id="agent",
- schedule="27 15 * * *",
- input={"messages": [{"role": "user", "content": "hello!"}]},
- metadata={"name":"my_run"},
- context={"model_name": "openai"},
- interrupt_before=["node_to_stop_before_1","node_to_stop_before_2"],
- interrupt_after=["node_to_stop_after_1","node_to_stop_after_2"],
- webhook="https://my.fake.webhook.com",
- multitask_strategy="interrupt"
- )
- ```
- """
- payload = {
- "schedule": schedule,
- "input": input,
- "config": config,
- "metadata": metadata,
- "context": context,
- "assistant_id": assistant_id,
- "checkpoint_during": checkpoint_during,
- "interrupt_before": interrupt_before,
- "interrupt_after": interrupt_after,
- "webhook": webhook,
- }
- if multitask_strategy:
- payload["multitask_strategy"] = multitask_strategy
- payload = {k: v for k, v in payload.items() if v is not None}
- return await self.http.post(
- "/runs/crons", json=payload, headers=headers, params=params
- )
- async def delete(
- self,
- cron_id: str,
- *,
- headers: Mapping[str, str] | None = None,
- params: QueryParamTypes | None = None,
- ) -> None:
- """Delete a cron.
- Args:
- cron_id: The cron ID to delete.
- headers: Optional custom headers to include with the request.
- params: Optional query parameters to include with the request.
- Returns:
- `None`
- ???+ example "Example Usage"
- ```python
- client = get_client(url="http://localhost:2024")
- await client.crons.delete(
- cron_id="cron_to_delete"
- )
- ```
- """
- await self.http.delete(f"/runs/crons/{cron_id}", headers=headers, params=params)
- async def search(
- self,
- *,
- assistant_id: str | None = None,
- thread_id: str | None = None,
- limit: int = 10,
- offset: int = 0,
- sort_by: CronSortBy | None = None,
- sort_order: SortOrder | None = None,
- select: list[CronSelectField] | None = None,
- headers: Mapping[str, str] | None = None,
- params: QueryParamTypes | None = None,
- ) -> list[Cron]:
- """Get a list of cron jobs.
- Args:
- assistant_id: The assistant ID or graph name to search for.
- thread_id: the thread ID to search for.
- limit: The maximum number of results to return.
- offset: The number of results to skip.
- headers: Optional custom headers to include with the request.
- params: Optional query parameters to include with the request.
- Returns:
- The list of cron jobs returned by the search,
- ???+ example "Example Usage"
- ```python
- client = get_client(url="http://localhost:2024")
- cron_jobs = await client.crons.search(
- assistant_id="my_assistant_id",
- thread_id="my_thread_id",
- limit=5,
- offset=5,
- )
- print(cron_jobs)
- ```
- ```shell
- ----------------------------------------------------------
- [
- {
- 'cron_id': '1ef3cefa-4c09-6926-96d0-3dc97fd5e39b',
- 'assistant_id': 'my_assistant_id',
- 'thread_id': 'my_thread_id',
- 'user_id': None,
- 'payload':
- {
- 'input': {'start_time': ''},
- 'schedule': '4 * * * *',
- 'assistant_id': 'my_assistant_id'
- },
- 'schedule': '4 * * * *',
- 'next_run_date': '2024-07-25T17:04:00+00:00',
- 'end_time': None,
- 'created_at': '2024-07-08T06:02:23.073257+00:00',
- 'updated_at': '2024-07-08T06:02:23.073257+00:00'
- }
- ]
- ```
- """
- payload = {
- "assistant_id": assistant_id,
- "thread_id": thread_id,
- "limit": limit,
- "offset": offset,
- }
- if sort_by:
- payload["sort_by"] = sort_by
- if sort_order:
- payload["sort_order"] = sort_order
- if select:
- payload["select"] = select
- payload = {k: v for k, v in payload.items() if v is not None}
- return await self.http.post(
- "/runs/crons/search", json=payload, headers=headers, params=params
- )
- async def count(
- self,
- *,
- assistant_id: str | None = None,
- thread_id: str | None = None,
- headers: Mapping[str, str] | None = None,
- params: QueryParamTypes | None = None,
- ) -> int:
- """Count cron jobs matching filters.
- Args:
- assistant_id: Assistant ID to filter by.
- thread_id: Thread ID to filter by.
- headers: Optional custom headers to include with the request.
- params: Optional query parameters to include with the request.
- Returns:
- int: Number of crons matching the criteria.
- """
- payload: dict[str, Any] = {}
- if assistant_id:
- payload["assistant_id"] = assistant_id
- if thread_id:
- payload["thread_id"] = thread_id
- return await self.http.post(
- "/runs/crons/count", json=payload, headers=headers, params=params
- )
- class StoreClient:
- """Client for interacting with the graph's shared storage.
- The Store provides a key-value storage system for persisting data across graph executions,
- allowing for stateful operations and data sharing across threads.
- ???+ example "Example"
- ```python
- client = get_client(url="http://localhost:2024")
- await client.store.put_item(["users", "user123"], "mem-123451342", {"name": "Alice", "score": 100})
- ```
- """
- def __init__(self, http: HttpClient) -> None:
- self.http = http
- async def put_item(
- self,
- namespace: Sequence[str],
- /,
- key: str,
- value: Mapping[str, Any],
- index: Literal[False] | list[str] | None = None,
- ttl: int | None = None,
- headers: Mapping[str, str] | None = None,
- params: QueryParamTypes | None = None,
- ) -> None:
- """Store or update an item.
- Args:
- namespace: A list of strings representing the namespace path.
- key: The unique identifier for the item within the namespace.
- value: A dictionary containing the item's data.
- index: Controls search indexing - None (use defaults), False (disable), or list of field paths to index.
- ttl: Optional time-to-live in minutes for the item, or None for no expiration.
- headers: Optional custom headers to include with the request.
- params: Optional query parameters to include with the request.
- Returns:
- `None`
- ???+ example "Example Usage"
- ```python
- client = get_client(url="http://localhost:2024")
- await client.store.put_item(
- ["documents", "user123"],
- key="item456",
- value={"title": "My Document", "content": "Hello World"}
- )
- ```
- """
- for label in namespace:
- if "." in label:
- raise ValueError(
- f"Invalid namespace label '{label}'. Namespace labels cannot contain periods ('.')."
- )
- payload = {
- "namespace": namespace,
- "key": key,
- "value": value,
- "index": index,
- "ttl": ttl,
- }
- await self.http.put(
- "/store/items", json=_provided_vals(payload), headers=headers, params=params
- )
- async def get_item(
- self,
- namespace: Sequence[str],
- /,
- key: str,
- *,
- refresh_ttl: bool | None = None,
- headers: Mapping[str, str] | None = None,
- params: QueryParamTypes | None = None,
- ) -> Item:
- """Retrieve a single item.
- Args:
- key: The unique identifier for the item.
- namespace: Optional list of strings representing the namespace path.
- refresh_ttl: Whether to refresh the TTL on this read operation. If `None`, uses the store's default behavior.
- Returns:
- Item: The retrieved item.
- headers: Optional custom headers to include with the request.
- params: Optional query parameters to include with the request.
- ???+ example "Example Usage"
- ```python
- client = get_client(url="http://localhost:2024")
- item = await client.store.get_item(
- ["documents", "user123"],
- key="item456",
- )
- print(item)
- ```
- ```shell
- ----------------------------------------------------------------
- {
- 'namespace': ['documents', 'user123'],
- 'key': 'item456',
- 'value': {'title': 'My Document', 'content': 'Hello World'},
- 'created_at': '2024-07-30T12:00:00Z',
- 'updated_at': '2024-07-30T12:00:00Z'
- }
- ```
- """
- for label in namespace:
- if "." in label:
- raise ValueError(
- f"Invalid namespace label '{label}'. Namespace labels cannot contain periods ('.')."
- )
- get_params = {"namespace": ".".join(namespace), "key": key}
- if refresh_ttl is not None:
- get_params["refresh_ttl"] = refresh_ttl
- if params:
- get_params = {**get_params, **params}
- return await self.http.get("/store/items", params=get_params, headers=headers)
- async def delete_item(
- self,
- namespace: Sequence[str],
- /,
- key: str,
- headers: Mapping[str, str] | None = None,
- params: QueryParamTypes | None = None,
- ) -> None:
- """Delete an item.
- Args:
- key: The unique identifier for the item.
- namespace: Optional list of strings representing the namespace path.
- headers: Optional custom headers to include with the request.
- params: Optional query parameters to include with the request.
- Returns:
- `None`
- ???+ example "Example Usage"
- ```python
- client = get_client(url="http://localhost:2024")
- await client.store.delete_item(
- ["documents", "user123"],
- key="item456",
- )
- ```
- """
- await self.http.delete(
- "/store/items",
- json={"namespace": namespace, "key": key},
- headers=headers,
- params=params,
- )
- async def search_items(
- self,
- namespace_prefix: Sequence[str],
- /,
- filter: Mapping[str, Any] | None = None,
- limit: int = 10,
- offset: int = 0,
- query: str | None = None,
- refresh_ttl: bool | None = None,
- headers: Mapping[str, str] | None = None,
- params: QueryParamTypes | None = None,
- ) -> SearchItemsResponse:
- """Search for items within a namespace prefix.
- Args:
- namespace_prefix: List of strings representing the namespace prefix.
- filter: Optional dictionary of key-value pairs to filter results.
- limit: Maximum number of items to return (default is 10).
- offset: Number of items to skip before returning results (default is 0).
- query: Optional query for natural language search.
- refresh_ttl: Whether to refresh the TTL on items returned by this search. If `None`, uses the store's default behavior.
- headers: Optional custom headers to include with the request.
- params: Optional query parameters to include with the request.
- Returns:
- A list of items matching the search criteria.
- ???+ example "Example Usage"
- ```python
- client = get_client(url="http://localhost:2024")
- items = await client.store.search_items(
- ["documents"],
- filter={"author": "John Doe"},
- limit=5,
- offset=0
- )
- print(items)
- ```
- ```shell
- ----------------------------------------------------------------
- {
- "items": [
- {
- "namespace": ["documents", "user123"],
- "key": "item789",
- "value": {
- "title": "Another Document",
- "author": "John Doe"
- },
- "created_at": "2024-07-30T12:00:00Z",
- "updated_at": "2024-07-30T12:00:00Z"
- },
- # ... additional items ...
- ]
- }
- ```
- """
- payload = {
- "namespace_prefix": namespace_prefix,
- "filter": filter,
- "limit": limit,
- "offset": offset,
- "query": query,
- "refresh_ttl": refresh_ttl,
- }
- return await self.http.post(
- "/store/items/search",
- json=_provided_vals(payload),
- headers=headers,
- params=params,
- )
- async def list_namespaces(
- self,
- prefix: list[str] | None = None,
- suffix: list[str] | None = None,
- max_depth: int | None = None,
- limit: int = 100,
- offset: int = 0,
- headers: Mapping[str, str] | None = None,
- params: QueryParamTypes | None = None,
- ) -> ListNamespaceResponse:
- """List namespaces with optional match conditions.
- Args:
- prefix: Optional list of strings representing the prefix to filter namespaces.
- suffix: Optional list of strings representing the suffix to filter namespaces.
- max_depth: Optional integer specifying the maximum depth of namespaces to return.
- limit: Maximum number of namespaces to return (default is 100).
- offset: Number of namespaces to skip before returning results (default is 0).
- headers: Optional custom headers to include with the request.
- params: Optional query parameters to include with the request.
- Returns:
- A list of namespaces matching the criteria.
- ???+ example "Example Usage"
- ```python
- client = get_client(url="http://localhost:2024")
- namespaces = await client.store.list_namespaces(
- prefix=["documents"],
- max_depth=3,
- limit=10,
- offset=0
- )
- print(namespaces)
- ----------------------------------------------------------------
- [
- ["documents", "user123", "reports"],
- ["documents", "user456", "invoices"],
- ...
- ]
- ```
- """
- payload = {
- "prefix": prefix,
- "suffix": suffix,
- "max_depth": max_depth,
- "limit": limit,
- "offset": offset,
- }
- return await self.http.post(
- "/store/namespaces",
- json=_provided_vals(payload),
- headers=headers,
- params=params,
- )
- def get_sync_client(
- *,
- url: str | None = None,
- api_key: str | None = NOT_PROVIDED,
- headers: Mapping[str, str] | None = None,
- timeout: TimeoutTypes | None = None,
- ) -> SyncLangGraphClient:
- """Get a synchronous LangGraphClient instance.
- Args:
- url: The URL of the LangGraph API.
- api_key: API key for authentication. Can be:
- - A string: use this exact API key
- - `None`: explicitly skip loading from environment variables
- - Not provided (default): auto-load from environment in this order:
- 1. `LANGGRAPH_API_KEY`
- 2. `LANGSMITH_API_KEY`
- 3. `LANGCHAIN_API_KEY`
- headers: Optional custom headers
- timeout: Optional timeout configuration for the HTTP client.
- Accepts an httpx.Timeout instance, a float (seconds), or a tuple of timeouts.
- Tuple format is (connect, read, write, pool)
- If not provided, defaults to connect=5s, read=300s, write=300s, and pool=5s.
- Returns:
- SyncLangGraphClient: The top-level synchronous client for accessing AssistantsClient,
- ThreadsClient, RunsClient, and CronClient.
- ???+ example "Example"
- ```python
- from langgraph_sdk import get_sync_client
- # get top-level synchronous LangGraphClient
- client = get_sync_client(url="http://localhost:8123")
- # example usage: client.<model>.<method_name>()
- assistant = client.assistants.get(assistant_id="some_uuid")
- ```
- ???+ example "Skip auto-loading API key from environment:"
- ```python
- from langgraph_sdk import get_sync_client
- # Don't load API key from environment variables
- client = get_sync_client(
- url="http://localhost:8123",
- api_key=None
- )
- ```
- """
- if url is None:
- url = "http://localhost:8123"
- transport = httpx.HTTPTransport(retries=5)
- client = httpx.Client(
- base_url=url,
- transport=transport,
- timeout=(
- httpx.Timeout(timeout) # ty: ignore[invalid-argument-type]
- if timeout is not None
- else httpx.Timeout(connect=5, read=300, write=300, pool=5)
- ),
- headers=_get_headers(api_key, headers),
- )
- return SyncLangGraphClient(client)
- class SyncLangGraphClient:
- """Synchronous client for interacting with the LangGraph API.
- This class provides synchronous access to LangGraph API endpoints for managing
- assistants, threads, runs, cron jobs, and data storage.
- ???+ example "Example"
- ```python
- client = get_sync_client(url="http://localhost:2024")
- assistant = client.assistants.get("asst_123")
- ```
- """
- def __init__(self, client: httpx.Client) -> None:
- self.http = SyncHttpClient(client)
- self.assistants = SyncAssistantsClient(self.http)
- self.threads = SyncThreadsClient(self.http)
- self.runs = SyncRunsClient(self.http)
- self.crons = SyncCronClient(self.http)
- self.store = SyncStoreClient(self.http)
- def __enter__(self) -> SyncLangGraphClient:
- """Enter the sync context manager."""
- return self
- def __exit__(
- self,
- exc_type: type[BaseException] | None,
- exc_val: BaseException | None,
- exc_tb: TracebackType | None,
- ) -> None:
- """Exit the sync context manager."""
- self.close()
- def close(self) -> None:
- """Close the underlying HTTP client."""
- if hasattr(self, "http"):
- self.http.client.close()
- class SyncHttpClient:
- """Handle synchronous requests to the LangGraph API.
- Provides error messaging and content handling enhancements above the
- underlying httpx client, mirroring the interface of [HttpClient](#HttpClient)
- but for sync usage.
- Attributes:
- client (httpx.Client): Underlying HTTPX sync client.
- """
- def __init__(self, client: httpx.Client) -> None:
- self.client = client
- def get(
- self,
- path: str,
- *,
- params: QueryParamTypes | None = None,
- headers: Mapping[str, str] | None = None,
- on_response: Callable[[httpx.Response], None] | None = None,
- ) -> Any:
- """Send a `GET` request."""
- r = self.client.get(path, params=params, headers=headers)
- if on_response:
- on_response(r)
- _raise_for_status_typed(r)
- return _decode_json(r)
- def post(
- self,
- path: str,
- *,
- json: dict[str, Any] | list | None,
- params: QueryParamTypes | None = None,
- headers: Mapping[str, str] | None = None,
- on_response: Callable[[httpx.Response], None] | None = None,
- ) -> Any:
- """Send a `POST` request."""
- if json is not None:
- request_headers, content = _encode_json(json)
- else:
- request_headers, content = {}, b""
- if headers:
- request_headers.update(headers)
- r = self.client.post(
- path, headers=request_headers, content=content, params=params
- )
- if on_response:
- on_response(r)
- _raise_for_status_typed(r)
- return _decode_json(r)
- def put(
- self,
- path: str,
- *,
- json: dict,
- params: QueryParamTypes | None = None,
- headers: Mapping[str, str] | None = None,
- on_response: Callable[[httpx.Response], None] | None = None,
- ) -> Any:
- """Send a `PUT` request."""
- request_headers, content = _encode_json(json)
- if headers:
- request_headers.update(headers)
- r = self.client.put(
- path, headers=request_headers, content=content, params=params
- )
- if on_response:
- on_response(r)
- _raise_for_status_typed(r)
- return _decode_json(r)
- def patch(
- self,
- path: str,
- *,
- json: dict,
- params: QueryParamTypes | None = None,
- headers: Mapping[str, str] | None = None,
- on_response: Callable[[httpx.Response], None] | None = None,
- ) -> Any:
- """Send a `PATCH` request."""
- request_headers, content = _encode_json(json)
- if headers:
- request_headers.update(headers)
- r = self.client.patch(
- path, headers=request_headers, content=content, params=params
- )
- if on_response:
- on_response(r)
- _raise_for_status_typed(r)
- return _decode_json(r)
- def delete(
- self,
- path: str,
- *,
- json: Any | None = None,
- params: QueryParamTypes | None = None,
- headers: Mapping[str, str] | None = None,
- on_response: Callable[[httpx.Response], None] | None = None,
- ) -> None:
- """Send a `DELETE` request."""
- r = self.client.request(
- "DELETE", path, json=json, params=params, headers=headers
- )
- if on_response:
- on_response(r)
- _raise_for_status_typed(r)
- def request_reconnect(
- self,
- path: str,
- method: str,
- *,
- json: dict[str, Any] | None = None,
- params: QueryParamTypes | None = None,
- headers: Mapping[str, str] | None = None,
- on_response: Callable[[httpx.Response], None] | None = None,
- reconnect_limit: int = 5,
- ) -> Any:
- """Send a request that automatically reconnects to Location header."""
- request_headers, content = _encode_json(json)
- if headers:
- request_headers.update(headers)
- with self.client.stream(
- method, path, headers=request_headers, content=content, params=params
- ) as r:
- if on_response:
- on_response(r)
- try:
- r.raise_for_status()
- except httpx.HTTPStatusError as e:
- body = r.read().decode()
- if sys.version_info >= (3, 11):
- e.add_note(body)
- else:
- logger.error(f"Error from langgraph-api: {body}", exc_info=e)
- raise e
- loc = r.headers.get("location")
- if reconnect_limit <= 0 or not loc:
- return _decode_json(r)
- try:
- return _decode_json(r)
- except httpx.HTTPError:
- warnings.warn(
- f"Request failed, attempting reconnect to Location: {loc}",
- stacklevel=2,
- )
- r.close()
- return self.request_reconnect(
- loc,
- "GET",
- headers=request_headers,
- # don't pass on_response so it's only called once
- reconnect_limit=reconnect_limit - 1,
- )
- def stream(
- self,
- path: str,
- method: str,
- *,
- json: dict[str, Any] | None = None,
- params: QueryParamTypes | None = None,
- headers: Mapping[str, str] | None = None,
- on_response: Callable[[httpx.Response], None] | None = None,
- ) -> Iterator[StreamPart]:
- """Stream the results of a request using SSE."""
- if json is not None:
- request_headers, content = _encode_json(json)
- else:
- request_headers, content = {}, None
- request_headers["Accept"] = "text/event-stream"
- request_headers["Cache-Control"] = "no-store"
- if headers:
- request_headers.update(headers)
- reconnect_headers = {
- key: value
- for key, value in request_headers.items()
- if key.lower() not in {"content-length", "content-type"}
- }
- last_event_id: str | None = None
- reconnect_path: str | None = None
- reconnect_attempts = 0
- max_reconnect_attempts = 5
- while True:
- current_headers = dict(
- request_headers if reconnect_path is None else reconnect_headers
- )
- if last_event_id is not None:
- current_headers["Last-Event-ID"] = last_event_id
- current_method = method if reconnect_path is None else "GET"
- current_content = content if reconnect_path is None else None
- current_params = params if reconnect_path is None else None
- retry = False
- with self.client.stream(
- current_method,
- reconnect_path or path,
- headers=current_headers,
- content=current_content,
- params=current_params,
- ) as res:
- if reconnect_path is None and on_response:
- on_response(res)
- # check status
- _raise_for_status_typed(res)
- # check content type
- content_type = res.headers.get("content-type", "").partition(";")[0]
- if "text/event-stream" not in content_type:
- raise httpx.TransportError(
- "Expected response header Content-Type to contain 'text/event-stream', "
- f"got {content_type!r}"
- )
- reconnect_location = res.headers.get("location")
- if reconnect_location:
- reconnect_path = reconnect_location
- decoder = SSEDecoder()
- try:
- for line in iter_lines_raw(res):
- sse = decoder.decode(cast(bytes, line).rstrip(b"\n"))
- if sse is not None:
- if decoder.last_event_id is not None:
- last_event_id = decoder.last_event_id
- if sse.event or sse.data is not None:
- yield sse
- except httpx.HTTPError:
- # httpx.TransportError inherits from HTTPError, so transient
- # disconnects during streaming land here.
- if reconnect_path is None:
- raise
- retry = True
- else:
- if sse := decoder.decode(b""):
- if decoder.last_event_id is not None:
- last_event_id = decoder.last_event_id
- if sse.event or sse.data is not None:
- # See async stream implementation for rationale on
- # skipping empty flush events.
- yield sse
- if retry:
- reconnect_attempts += 1
- if reconnect_attempts > max_reconnect_attempts:
- raise httpx.TransportError(
- "Exceeded maximum SSE reconnection attempts"
- )
- continue
- break
- def _encode_json(json: Any) -> tuple[dict[str, str], bytes]:
- body = orjson.dumps(
- json,
- _orjson_default,
- orjson.OPT_SERIALIZE_NUMPY | orjson.OPT_NON_STR_KEYS,
- )
- content_length = str(len(body))
- content_type = "application/json"
- headers = {"Content-Length": content_length, "Content-Type": content_type}
- return headers, body
- def _decode_json(r: httpx.Response) -> Any:
- body = r.read()
- return orjson.loads(body) if body else None
- class SyncAssistantsClient:
- """Client for managing assistants in LangGraph synchronously.
- This class provides methods to interact with assistants, which are versioned configurations of your graph.
- ???+ example "Example"
- ```python
- client = get_sync_client(url="http://localhost:2024")
- assistant = client.assistants.get("assistant_id_123")
- ```
- """
- def __init__(self, http: SyncHttpClient) -> None:
- self.http = http
- def get(
- self,
- assistant_id: str,
- *,
- headers: Mapping[str, str] | None = None,
- params: QueryParamTypes | None = None,
- ) -> Assistant:
- """Get an assistant by ID.
- Args:
- assistant_id: The ID of the assistant to get OR the name of the graph (to use the default assistant).
- headers: Optional custom headers to include with the request.
- params: Optional query parameters to include with the request.
- Returns:
- `Assistant` Object.
- ???+ example "Example Usage"
- ```python
- assistant = client.assistants.get(
- assistant_id="my_assistant_id"
- )
- print(assistant)
- ```
- ```shell
- ----------------------------------------------------
- {
- 'assistant_id': 'my_assistant_id',
- 'graph_id': 'agent',
- 'created_at': '2024-06-25T17:10:33.109781+00:00',
- 'updated_at': '2024-06-25T17:10:33.109781+00:00',
- 'config': {},
- 'context': {},
- 'metadata': {'created_by': 'system'}
- }
- ```
- """
- return self.http.get(
- f"/assistants/{assistant_id}", headers=headers, params=params
- )
- def get_graph(
- self,
- assistant_id: str,
- *,
- xray: int | bool = False,
- headers: Mapping[str, str] | None = None,
- params: QueryParamTypes | None = None,
- ) -> dict[str, list[dict[str, Any]]]:
- """Get the graph of an assistant by ID.
- Args:
- assistant_id: The ID of the assistant to get the graph of.
- xray: Include graph representation of subgraphs. If an integer value is provided, only subgraphs with a depth less than or equal to the value will be included.
- headers: Optional custom headers to include with the request.
- params: Optional query parameters to include with the request.
- Returns:
- The graph information for the assistant in JSON format.
- ???+ example "Example Usage"
- ```python
- client = get_sync_client(url="http://localhost:2024")
- graph_info = client.assistants.get_graph(
- assistant_id="my_assistant_id"
- )
- print(graph_info)
- --------------------------------------------------------------------------------------------------------------------------
- {
- 'nodes':
- [
- {'id': '__start__', 'type': 'schema', 'data': '__start__'},
- {'id': '__end__', 'type': 'schema', 'data': '__end__'},
- {'id': 'agent','type': 'runnable','data': {'id': ['langgraph', 'utils', 'RunnableCallable'],'name': 'agent'}},
- ],
- 'edges':
- [
- {'source': '__start__', 'target': 'agent'},
- {'source': 'agent','target': '__end__'}
- ]
- }
- ```
- """
- query_params = {"xray": xray}
- if params:
- query_params.update(params)
- return self.http.get(
- f"/assistants/{assistant_id}/graph", params=query_params, headers=headers
- )
- def get_schemas(
- self,
- assistant_id: str,
- *,
- headers: Mapping[str, str] | None = None,
- params: QueryParamTypes | None = None,
- ) -> GraphSchema:
- """Get the schemas of an assistant by ID.
- Args:
- assistant_id: The ID of the assistant to get the schema of.
- headers: Optional custom headers to include with the request.
- params: Optional query parameters to include with the request.
- Returns:
- GraphSchema: The graph schema for the assistant.
- ???+ example "Example Usage"
- ```python
- client = get_sync_client(url="http://localhost:2024")
- schema = client.assistants.get_schemas(
- assistant_id="my_assistant_id"
- )
- print(schema)
- ```
- ```shell
- ----------------------------------------------------------------------------------------------------------------------------
- {
- 'graph_id': 'agent',
- 'state_schema':
- {
- 'title': 'LangGraphInput',
- '$ref': '#/definitions/AgentState',
- 'definitions':
- {
- 'BaseMessage':
- {
- 'title': 'BaseMessage',
- 'description': 'Base abstract Message class. Messages are the inputs and outputs of ChatModels.',
- 'type': 'object',
- 'properties':
- {
- 'content':
- {
- 'title': 'Content',
- 'anyOf': [
- {'type': 'string'},
- {'type': 'array','items': {'anyOf': [{'type': 'string'}, {'type': 'object'}]}}
- ]
- },
- 'additional_kwargs':
- {
- 'title': 'Additional Kwargs',
- 'type': 'object'
- },
- 'response_metadata':
- {
- 'title': 'Response Metadata',
- 'type': 'object'
- },
- 'type':
- {
- 'title': 'Type',
- 'type': 'string'
- },
- 'name':
- {
- 'title': 'Name',
- 'type': 'string'
- },
- 'id':
- {
- 'title': 'Id',
- 'type': 'string'
- }
- },
- 'required': ['content', 'type']
- },
- 'AgentState':
- {
- 'title': 'AgentState',
- 'type': 'object',
- 'properties':
- {
- 'messages':
- {
- 'title': 'Messages',
- 'type': 'array',
- 'items': {'$ref': '#/definitions/BaseMessage'}
- }
- },
- 'required': ['messages']
- }
- }
- },
- 'config_schema':
- {
- 'title': 'Configurable',
- 'type': 'object',
- 'properties':
- {
- 'model_name':
- {
- 'title': 'Model Name',
- 'enum': ['anthropic', 'openai'],
- 'type': 'string'
- }
- }
- },
- 'context_schema':
- {
- 'title': 'Context',
- 'type': 'object',
- 'properties':
- {
- 'model_name':
- {
- 'title': 'Model Name',
- 'enum': ['anthropic', 'openai'],
- 'type': 'string'
- }
- }
- }
- }
- ```
- """
- return self.http.get(
- f"/assistants/{assistant_id}/schemas", headers=headers, params=params
- )
- def get_subgraphs(
- self,
- assistant_id: str,
- namespace: str | None = None,
- recurse: bool = False,
- *,
- headers: Mapping[str, str] | None = None,
- params: QueryParamTypes | None = None,
- ) -> Subgraphs:
- """Get the schemas of an assistant by ID.
- Args:
- assistant_id: The ID of the assistant to get the schema of.
- headers: Optional custom headers to include with the request.
- params: Optional query parameters to include with the request.
- Returns:
- Subgraphs: The graph schema for the assistant.
- """
- get_params = {"recurse": recurse}
- if params:
- get_params = {**get_params, **params}
- if namespace is not None:
- return self.http.get(
- f"/assistants/{assistant_id}/subgraphs/{namespace}",
- params=get_params,
- headers=headers,
- )
- else:
- return self.http.get(
- f"/assistants/{assistant_id}/subgraphs",
- params=get_params,
- headers=headers,
- )
- def create(
- self,
- graph_id: str | None,
- config: Config | None = None,
- *,
- context: Context | None = None,
- metadata: Json = None,
- assistant_id: str | None = None,
- if_exists: OnConflictBehavior | None = None,
- name: str | None = None,
- headers: Mapping[str, str] | None = None,
- description: str | None = None,
- params: QueryParamTypes | None = None,
- ) -> Assistant:
- """Create a new assistant.
- Useful when graph is configurable and you want to create different assistants based on different configurations.
- Args:
- graph_id: The ID of the graph the assistant should use. The graph ID is normally set in your langgraph.json configuration.
- config: Configuration to use for the graph.
- context: Static context to add to the assistant.
- !!! version-added "Added in version 0.6.0"
- metadata: Metadata to add to assistant.
- assistant_id: Assistant ID to use, will default to a random UUID if not provided.
- if_exists: How to handle duplicate creation. Defaults to 'raise' under the hood.
- Must be either 'raise' (raise error if duplicate), or 'do_nothing' (return existing assistant).
- name: The name of the assistant. Defaults to 'Untitled' under the hood.
- headers: Optional custom headers to include with the request.
- description: Optional description of the assistant.
- The description field is available for langgraph-api server version>=0.0.45
- params: Optional query parameters to include with the request.
- Returns:
- The created assistant.
- ???+ example "Example Usage"
- ```python
- client = get_sync_client(url="http://localhost:2024")
- assistant = client.assistants.create(
- graph_id="agent",
- context={"model_name": "openai"},
- metadata={"number":1},
- assistant_id="my-assistant-id",
- if_exists="do_nothing",
- name="my_name"
- )
- ```
- """
- payload: dict[str, Any] = {
- "graph_id": graph_id,
- }
- if config:
- payload["config"] = config
- if context:
- payload["context"] = context
- if metadata:
- payload["metadata"] = metadata
- if assistant_id:
- payload["assistant_id"] = assistant_id
- if if_exists:
- payload["if_exists"] = if_exists
- if name:
- payload["name"] = name
- if description:
- payload["description"] = description
- return self.http.post(
- "/assistants", json=payload, headers=headers, params=params
- )
- def update(
- self,
- assistant_id: str,
- *,
- graph_id: str | None = None,
- config: Config | None = None,
- context: Context | None = None,
- metadata: Json = None,
- name: str | None = None,
- headers: Mapping[str, str] | None = None,
- description: str | None = None,
- params: QueryParamTypes | None = None,
- ) -> Assistant:
- """Update an assistant.
- Use this to point to a different graph, update the configuration, or change the metadata of an assistant.
- Args:
- assistant_id: Assistant to update.
- graph_id: The ID of the graph the assistant should use.
- The graph ID is normally set in your langgraph.json configuration. If `None`, assistant will keep pointing to same graph.
- config: Configuration to use for the graph.
- context: Static context to add to the assistant.
- !!! version-added "Added in version 0.6.0"
- metadata: Metadata to merge with existing assistant metadata.
- name: The new name for the assistant.
- headers: Optional custom headers to include with the request.
- description: Optional description of the assistant.
- The description field is available for langgraph-api server version>=0.0.45
- Returns:
- The updated assistant.
- ???+ example "Example Usage"
- ```python
- client = get_sync_client(url="http://localhost:2024")
- assistant = client.assistants.update(
- assistant_id='e280dad7-8618-443f-87f1-8e41841c180f',
- graph_id="other-graph",
- context={"model_name": "anthropic"},
- metadata={"number":2}
- )
- ```
- """
- payload: dict[str, Any] = {}
- if graph_id:
- payload["graph_id"] = graph_id
- if config:
- payload["config"] = config
- if context:
- payload["context"] = context
- if metadata:
- payload["metadata"] = metadata
- if name:
- payload["name"] = name
- if description:
- payload["description"] = description
- return self.http.patch(
- f"/assistants/{assistant_id}",
- json=payload,
- headers=headers,
- params=params,
- )
- def delete(
- self,
- assistant_id: str,
- *,
- headers: Mapping[str, str] | None = None,
- params: QueryParamTypes | None = None,
- ) -> None:
- """Delete an assistant.
- Args:
- assistant_id: The assistant ID to delete.
- headers: Optional custom headers to include with the request.
- params: Optional query parameters to include with the request.
- Returns:
- `None`
- ???+ example "Example Usage"
- ```python
- client = get_sync_client(url="http://localhost:2024")
- client.assistants.delete(
- assistant_id="my_assistant_id"
- )
- ```
- """
- self.http.delete(f"/assistants/{assistant_id}", headers=headers, params=params)
- @overload
- def search(
- self,
- *,
- metadata: Json = None,
- graph_id: str | None = None,
- name: str | None = None,
- limit: int = 10,
- offset: int = 0,
- sort_by: AssistantSortBy | None = None,
- sort_order: SortOrder | None = None,
- select: list[AssistantSelectField] | None = None,
- response_format: Literal["object"],
- headers: Mapping[str, str] | None = None,
- params: QueryParamTypes | None = None,
- ) -> AssistantsSearchResponse: ...
- @overload
- def search(
- self,
- *,
- metadata: Json = None,
- graph_id: str | None = None,
- name: str | None = None,
- limit: int = 10,
- offset: int = 0,
- sort_by: AssistantSortBy | None = None,
- sort_order: SortOrder | None = None,
- select: list[AssistantSelectField] | None = None,
- response_format: Literal["array"] = "array",
- headers: Mapping[str, str] | None = None,
- params: QueryParamTypes | None = None,
- ) -> list[Assistant]: ...
- def search(
- self,
- *,
- metadata: Json = None,
- graph_id: str | None = None,
- name: str | None = None,
- limit: int = 10,
- offset: int = 0,
- sort_by: AssistantSortBy | None = None,
- sort_order: SortOrder | None = None,
- select: list[AssistantSelectField] | None = None,
- response_format: Literal["array", "object"] = "array",
- headers: Mapping[str, str] | None = None,
- params: QueryParamTypes | None = None,
- ) -> AssistantsSearchResponse | list[Assistant]:
- """Search for assistants.
- Args:
- metadata: Metadata to filter by. Exact match filter for each KV pair.
- graph_id: The ID of the graph to filter by.
- The graph ID is normally set in your langgraph.json configuration.
- name: The name of the assistant to filter by.
- The filtering logic will match assistants where 'name' is a substring (case insensitive) of the assistant name.
- limit: The maximum number of results to return.
- offset: The number of results to skip.
- sort_by: The field to sort by.
- sort_order: The order to sort by.
- select: Specific assistant fields to include in the response.
- response_format: Controls the response shape. Use ``"array"`` (default)
- to return a bare list of assistants, or ``"object"`` to return
- a mapping containing assistants plus pagination metadata.
- Defaults to "array", though this default will be changed to "object" in a future release.
- headers: Optional custom headers to include with the request.
- Returns:
- A list of assistants (when ``response_format=\"array\"``) or a mapping
- with the assistants and the next pagination cursor (when
- ``response_format=\"object\"``).
- ???+ example "Example Usage"
- ```python
- client = get_sync_client(url="http://localhost:2024")
- response = client.assistants.search(
- metadata = {"name":"my_name"},
- graph_id="my_graph_id",
- limit=5,
- offset=5,
- response_format="object",
- )
- assistants = response["assistants"]
- next_cursor = response["next"]
- ```
- """
- if response_format not in ("array", "object"):
- raise ValueError("response_format must be 'array' or 'object'")
- payload: dict[str, Any] = {
- "limit": limit,
- "offset": offset,
- }
- if metadata:
- payload["metadata"] = metadata
- if graph_id:
- payload["graph_id"] = graph_id
- if name:
- payload["name"] = name
- if sort_by:
- payload["sort_by"] = sort_by
- if sort_order:
- payload["sort_order"] = sort_order
- if select:
- payload["select"] = select
- next_cursor: str | None = None
- def capture_pagination(response: httpx.Response) -> None:
- nonlocal next_cursor
- next_cursor = response.headers.get("X-Pagination-Next")
- assistants = cast(
- list[Assistant],
- self.http.post(
- "/assistants/search",
- json=payload,
- headers=headers,
- params=params,
- on_response=capture_pagination if response_format == "object" else None,
- ),
- )
- if response_format == "object":
- return {"assistants": assistants, "next": next_cursor}
- return assistants
- def count(
- self,
- *,
- metadata: Json = None,
- graph_id: str | None = None,
- name: str | None = None,
- headers: Mapping[str, str] | None = None,
- params: QueryParamTypes | None = None,
- ) -> int:
- """Count assistants matching filters.
- Args:
- metadata: Metadata to filter by. Exact match for each key/value.
- graph_id: Optional graph id to filter by.
- name: Optional name to filter by.
- The filtering logic will match assistants where 'name' is a substring (case insensitive) of the assistant name.
- headers: Optional custom headers to include with the request.
- params: Optional query parameters to include with the request.
- Returns:
- int: Number of assistants matching the criteria.
- """
- payload: dict[str, Any] = {}
- if metadata:
- payload["metadata"] = metadata
- if graph_id:
- payload["graph_id"] = graph_id
- if name:
- payload["name"] = name
- return self.http.post(
- "/assistants/count", json=payload, headers=headers, params=params
- )
- def get_versions(
- self,
- assistant_id: str,
- metadata: Json = None,
- limit: int = 10,
- offset: int = 0,
- *,
- headers: Mapping[str, str] | None = None,
- params: QueryParamTypes | None = None,
- ) -> list[AssistantVersion]:
- """List all versions of an assistant.
- Args:
- assistant_id: The assistant ID to get versions for.
- metadata: Metadata to filter versions by. Exact match filter for each KV pair.
- limit: The maximum number of versions to return.
- offset: The number of versions to skip.
- headers: Optional custom headers to include with the request.
- Returns:
- A list of assistants.
- ???+ example "Example Usage"
- ```python
- client = get_sync_client(url="http://localhost:2024")
- assistant_versions = client.assistants.get_versions(
- assistant_id="my_assistant_id"
- )
- ```
- """
- payload: dict[str, Any] = {
- "limit": limit,
- "offset": offset,
- }
- if metadata:
- payload["metadata"] = metadata
- return self.http.post(
- f"/assistants/{assistant_id}/versions",
- json=payload,
- headers=headers,
- params=params,
- )
- def set_latest(
- self,
- assistant_id: str,
- version: int,
- *,
- headers: Mapping[str, str] | None = None,
- params: QueryParamTypes | None = None,
- ) -> Assistant:
- """Change the version of an assistant.
- Args:
- assistant_id: The assistant ID to delete.
- version: The version to change to.
- headers: Optional custom headers to include with the request.
- Returns:
- `Assistant` Object.
- ???+ example "Example Usage"
- ```python
- client = get_sync_client(url="http://localhost:2024")
- new_version_assistant = client.assistants.set_latest(
- assistant_id="my_assistant_id",
- version=3
- )
- ```
- """
- payload: dict[str, Any] = {"version": version}
- return self.http.post(
- f"/assistants/{assistant_id}/latest",
- json=payload,
- headers=headers,
- params=params,
- )
- class SyncThreadsClient:
- """Synchronous client for managing threads in LangGraph.
- This class provides methods to create, retrieve, and manage threads,
- which represent conversations or stateful interactions.
- ???+ example "Example"
- ```python
- client = get_sync_client(url="http://localhost:2024")
- thread = client.threads.create(metadata={"user_id": "123"})
- ```
- """
- def __init__(self, http: SyncHttpClient) -> None:
- self.http = http
- def get(
- self,
- thread_id: str,
- *,
- headers: Mapping[str, str] | None = None,
- params: QueryParamTypes | None = None,
- ) -> Thread:
- """Get a thread by ID.
- Args:
- thread_id: The ID of the thread to get.
- headers: Optional custom headers to include with the request.
- Returns:
- `Thread` object.
- ???+ example "Example Usage"
- ```python
- client = get_sync_client(url="http://localhost:2024")
- thread = client.threads.get(
- thread_id="my_thread_id"
- )
- print(thread)
- ```
- ```shell
- -----------------------------------------------------
- {
- 'thread_id': 'my_thread_id',
- 'created_at': '2024-07-18T18:35:15.540834+00:00',
- 'updated_at': '2024-07-18T18:35:15.540834+00:00',
- 'metadata': {'graph_id': 'agent'}
- }
- ```
- """
- return self.http.get(f"/threads/{thread_id}", headers=headers, params=params)
- def create(
- self,
- *,
- metadata: Json = None,
- thread_id: str | None = None,
- if_exists: OnConflictBehavior | None = None,
- supersteps: Sequence[dict[str, Sequence[dict[str, Any]]]] | None = None,
- graph_id: str | None = None,
- ttl: int | Mapping[str, Any] | None = None,
- headers: Mapping[str, str] | None = None,
- params: QueryParamTypes | None = None,
- ) -> Thread:
- """Create a new thread.
- Args:
- metadata: Metadata to add to thread.
- thread_id: ID of thread.
- If `None`, ID will be a randomly generated UUID.
- if_exists: How to handle duplicate creation. Defaults to 'raise' under the hood.
- Must be either 'raise' (raise error if duplicate), or 'do_nothing' (return existing thread).
- supersteps: Apply a list of supersteps when creating a thread, each containing a sequence of updates.
- Each update has `values` or `command` and `as_node`. Used for copying a thread between deployments.
- graph_id: Optional graph ID to associate with the thread.
- ttl: Optional time-to-live in minutes for the thread. You can pass an
- integer (minutes) or a mapping with keys `ttl` and optional
- `strategy` (defaults to "delete").
- headers: Optional custom headers to include with the request.
- Returns:
- The created `Thread`.
- ???+ example "Example Usage"
- ```python
- client = get_sync_client(url="http://localhost:2024")
- thread = client.threads.create(
- metadata={"number":1},
- thread_id="my-thread-id",
- if_exists="raise"
- )
- ```
- )
- """
- payload: dict[str, Any] = {}
- if thread_id:
- payload["thread_id"] = thread_id
- if metadata or graph_id:
- payload["metadata"] = {
- **(metadata or {}),
- **({"graph_id": graph_id} if graph_id else {}),
- }
- if if_exists:
- payload["if_exists"] = if_exists
- if supersteps:
- payload["supersteps"] = [
- {
- "updates": [
- {
- "values": u["values"],
- "command": u.get("command"),
- "as_node": u["as_node"],
- }
- for u in s["updates"]
- ]
- }
- for s in supersteps
- ]
- if ttl is not None:
- if isinstance(ttl, (int, float)):
- payload["ttl"] = {"ttl": ttl, "strategy": "delete"}
- else:
- payload["ttl"] = ttl
- return self.http.post("/threads", json=payload, headers=headers, params=params)
- def update(
- self,
- thread_id: str,
- *,
- metadata: Mapping[str, Any],
- ttl: int | Mapping[str, Any] | None = None,
- headers: Mapping[str, str] | None = None,
- params: QueryParamTypes | None = None,
- ) -> Thread:
- """Update a thread.
- Args:
- thread_id: ID of thread to update.
- metadata: Metadata to merge with existing thread metadata.
- ttl: Optional time-to-live in minutes for the thread. You can pass an
- integer (minutes) or a mapping with keys `ttl` and optional
- `strategy` (defaults to "delete").
- headers: Optional custom headers to include with the request.
- params: Optional query parameters to include with the request.
- Returns:
- The created `Thread`.
- ???+ example "Example Usage"
- ```python
- client = get_sync_client(url="http://localhost:2024")
- thread = client.threads.update(
- thread_id="my-thread-id",
- metadata={"number":1},
- ttl=43_200,
- )
- ```
- """
- payload: dict[str, Any] = {"metadata": metadata}
- if ttl is not None:
- if isinstance(ttl, (int, float)):
- payload["ttl"] = {"ttl": ttl, "strategy": "delete"}
- else:
- payload["ttl"] = ttl
- return self.http.patch(
- f"/threads/{thread_id}",
- json=payload,
- headers=headers,
- params=params,
- )
- def delete(
- self,
- thread_id: str,
- *,
- headers: Mapping[str, str] | None = None,
- params: QueryParamTypes | None = None,
- ) -> None:
- """Delete a thread.
- Args:
- thread_id: The ID of the thread to delete.
- headers: Optional custom headers to include with the request.
- params: Optional query parameters to include with the request.
- Returns:
- `None`
- ???+ example "Example Usage"
- ```python
- client.threads.delete(
- thread_id="my_thread_id"
- )
- ```
- """
- self.http.delete(f"/threads/{thread_id}", headers=headers, params=params)
- def search(
- self,
- *,
- metadata: Json = None,
- values: Json = None,
- ids: Sequence[str] | None = None,
- status: ThreadStatus | None = None,
- limit: int = 10,
- offset: int = 0,
- sort_by: ThreadSortBy | None = None,
- sort_order: SortOrder | None = None,
- select: list[ThreadSelectField] | None = None,
- headers: Mapping[str, str] | None = None,
- params: QueryParamTypes | None = None,
- ) -> list[Thread]:
- """Search for threads.
- Args:
- metadata: Thread metadata to filter on.
- values: State values to filter on.
- ids: List of thread IDs to filter by.
- status: Thread status to filter on.
- Must be one of 'idle', 'busy', 'interrupted' or 'error'.
- limit: Limit on number of threads to return.
- offset: Offset in threads table to start search from.
- headers: Optional custom headers to include with the request.
- Returns:
- List of the threads matching the search parameters.
- ???+ example "Example Usage"
- ```python
- client = get_sync_client(url="http://localhost:2024")
- threads = client.threads.search(
- metadata={"number":1},
- status="interrupted",
- limit=15,
- offset=5
- )
- ```
- """
- payload: dict[str, Any] = {
- "limit": limit,
- "offset": offset,
- }
- if metadata:
- payload["metadata"] = metadata
- if values:
- payload["values"] = values
- if ids:
- payload["ids"] = ids
- if status:
- payload["status"] = status
- if sort_by:
- payload["sort_by"] = sort_by
- if sort_order:
- payload["sort_order"] = sort_order
- if select:
- payload["select"] = select
- return self.http.post(
- "/threads/search", json=payload, headers=headers, params=params
- )
- def count(
- self,
- *,
- metadata: Json = None,
- values: Json = None,
- status: ThreadStatus | None = None,
- headers: Mapping[str, str] | None = None,
- params: QueryParamTypes | None = None,
- ) -> int:
- """Count threads matching filters.
- Args:
- metadata: Thread metadata to filter on.
- values: State values to filter on.
- status: Thread status to filter on.
- headers: Optional custom headers to include with the request.
- params: Optional query parameters to include with the request.
- Returns:
- int: Number of threads matching the criteria.
- """
- payload: dict[str, Any] = {}
- if metadata:
- payload["metadata"] = metadata
- if values:
- payload["values"] = values
- if status:
- payload["status"] = status
- return self.http.post(
- "/threads/count", json=payload, headers=headers, params=params
- )
- def copy(
- self,
- thread_id: str,
- *,
- headers: Mapping[str, str] | None = None,
- params: QueryParamTypes | None = None,
- ) -> None:
- """Copy a thread.
- Args:
- thread_id: The ID of the thread to copy.
- headers: Optional custom headers to include with the request.
- params: Optional query parameters to include with the request.
- Returns:
- `None`
- ???+ example "Example Usage"
- ```python
- client = get_sync_client(url="http://localhost:2024")
- client.threads.copy(
- thread_id="my_thread_id"
- )
- ```
- """
- return self.http.post(
- f"/threads/{thread_id}/copy", json=None, headers=headers, params=params
- )
- def get_state(
- self,
- thread_id: str,
- checkpoint: Checkpoint | None = None,
- checkpoint_id: str | None = None, # deprecated
- *,
- subgraphs: bool = False,
- headers: Mapping[str, str] | None = None,
- params: QueryParamTypes | None = None,
- ) -> ThreadState:
- """Get the state of a thread.
- Args:
- thread_id: The ID of the thread to get the state of.
- checkpoint: The checkpoint to get the state of.
- subgraphs: Include subgraphs states.
- headers: Optional custom headers to include with the request.
- Returns:
- The thread of the state.
- ???+ example "Example Usage"
- ```python
- client = get_sync_client(url="http://localhost:2024")
- thread_state = client.threads.get_state(
- thread_id="my_thread_id",
- checkpoint_id="my_checkpoint_id"
- )
- print(thread_state)
- ```
- ```shell
- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------
- {
- 'values': {
- 'messages': [
- {
- 'content': 'how are you?',
- 'additional_kwargs': {},
- 'response_metadata': {},
- 'type': 'human',
- 'name': None,
- 'id': 'fe0a5778-cfe9-42ee-b807-0adaa1873c10',
- 'example': False
- },
- {
- 'content': "I'm doing well, thanks for asking! I'm an AI assistant created by Anthropic to be helpful, honest, and harmless.",
- 'additional_kwargs': {},
- 'response_metadata': {},
- 'type': 'ai',
- 'name': None,
- 'id': 'run-159b782c-b679-4830-83c6-cef87798fe8b',
- 'example': False,
- 'tool_calls': [],
- 'invalid_tool_calls': [],
- 'usage_metadata': None
- }
- ]
- },
- 'next': [],
- 'checkpoint':
- {
- 'thread_id': 'e2496803-ecd5-4e0c-a779-3226296181c2',
- 'checkpoint_ns': '',
- 'checkpoint_id': '1ef4a9b8-e6fb-67b1-8001-abd5184439d1'
- }
- 'metadata':
- {
- 'step': 1,
- 'run_id': '1ef4a9b8-d7da-679a-a45a-872054341df2',
- 'source': 'loop',
- 'writes':
- {
- 'agent':
- {
- 'messages': [
- {
- 'id': 'run-159b782c-b679-4830-83c6-cef87798fe8b',
- 'name': None,
- 'type': 'ai',
- 'content': "I'm doing well, thanks for asking! I'm an AI assistant created by Anthropic to be helpful, honest, and harmless.",
- 'example': False,
- 'tool_calls': [],
- 'usage_metadata': None,
- 'additional_kwargs': {},
- 'response_metadata': {},
- 'invalid_tool_calls': []
- }
- ]
- }
- },
- 'user_id': None,
- 'graph_id': 'agent',
- 'thread_id': 'e2496803-ecd5-4e0c-a779-3226296181c2',
- 'created_by': 'system',
- 'assistant_id': 'fe096781-5601-53d2-b2f6-0d3403f7e9ca'},
- 'created_at': '2024-07-25T15:35:44.184703+00:00',
- 'parent_config':
- {
- 'thread_id': 'e2496803-ecd5-4e0c-a779-3226296181c2',
- 'checkpoint_ns': '',
- 'checkpoint_id': '1ef4a9b8-d80d-6fa7-8000-9300467fad0f'
- }
- }
- ```
- """
- if checkpoint:
- return self.http.post(
- f"/threads/{thread_id}/state/checkpoint",
- json={"checkpoint": checkpoint, "subgraphs": subgraphs},
- headers=headers,
- params=params,
- )
- elif checkpoint_id:
- get_params = {"subgraphs": subgraphs}
- if params:
- get_params = {**get_params, **params}
- return self.http.get(
- f"/threads/{thread_id}/state/{checkpoint_id}",
- params=get_params,
- headers=headers,
- )
- else:
- get_params = {"subgraphs": subgraphs}
- if params:
- get_params = {**get_params, **params}
- return self.http.get(
- f"/threads/{thread_id}/state",
- params=get_params,
- headers=headers,
- )
- def update_state(
- self,
- thread_id: str,
- values: dict[str, Any] | Sequence[dict] | None,
- *,
- as_node: str | None = None,
- checkpoint: Checkpoint | None = None,
- checkpoint_id: str | None = None, # deprecated
- headers: Mapping[str, str] | None = None,
- params: QueryParamTypes | None = None,
- ) -> ThreadUpdateStateResponse:
- """Update the state of a thread.
- Args:
- thread_id: The ID of the thread to update.
- values: The values to update the state with.
- as_node: Update the state as if this node had just executed.
- checkpoint: The checkpoint to update the state of.
- headers: Optional custom headers to include with the request.
- Returns:
- Response after updating a thread's state.
- ???+ example "Example Usage"
- ```python
- response = await client.threads.update_state(
- thread_id="my_thread_id",
- values={"messages":[{"role": "user", "content": "hello!"}]},
- as_node="my_node",
- )
- print(response)
- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------
- {
- 'checkpoint': {
- 'thread_id': 'e2496803-ecd5-4e0c-a779-3226296181c2',
- 'checkpoint_ns': '',
- 'checkpoint_id': '1ef4a9b8-e6fb-67b1-8001-abd5184439d1',
- 'checkpoint_map': {}
- }
- }
- ```
- """
- payload: dict[str, Any] = {
- "values": values,
- }
- if checkpoint_id:
- payload["checkpoint_id"] = checkpoint_id
- if checkpoint:
- payload["checkpoint"] = checkpoint
- if as_node:
- payload["as_node"] = as_node
- return self.http.post(
- f"/threads/{thread_id}/state", json=payload, headers=headers, params=params
- )
- def get_history(
- self,
- thread_id: str,
- *,
- limit: int = 10,
- before: str | Checkpoint | None = None,
- metadata: Mapping[str, Any] | None = None,
- checkpoint: Checkpoint | None = None,
- headers: Mapping[str, str] | None = None,
- params: QueryParamTypes | None = None,
- ) -> list[ThreadState]:
- """Get the state history of a thread.
- Args:
- thread_id: The ID of the thread to get the state history for.
- checkpoint: Return states for this subgraph. If empty defaults to root.
- limit: The maximum number of states to return.
- before: Return states before this checkpoint.
- metadata: Filter states by metadata key-value pairs.
- headers: Optional custom headers to include with the request.
- Returns:
- The state history of the `Thread`.
- ???+ example "Example Usage"
- ```python
- thread_state = client.threads.get_history(
- thread_id="my_thread_id",
- limit=5,
- before="my_timestamp",
- metadata={"name":"my_name"}
- )
- ```
- """
- payload: dict[str, Any] = {
- "limit": limit,
- }
- if before:
- payload["before"] = before
- if metadata:
- payload["metadata"] = metadata
- if checkpoint:
- payload["checkpoint"] = checkpoint
- return self.http.post(
- f"/threads/{thread_id}/history",
- json=payload,
- headers=headers,
- params=params,
- )
- def join_stream(
- self,
- thread_id: str,
- *,
- stream_mode: ThreadStreamMode | Sequence[ThreadStreamMode] = "run_modes",
- last_event_id: str | None = None,
- headers: Mapping[str, str] | None = None,
- params: QueryParamTypes | None = None,
- ) -> Iterator[StreamPart]:
- """Get a stream of events for a thread.
- Args:
- thread_id: The ID of the thread to get the stream for.
- last_event_id: The ID of the last event to get.
- headers: Optional custom headers to include with the request.
- params: Optional query parameters to include with the request.
- Returns:
- An iterator of stream parts.
- ???+ example "Example Usage"
- ```python
- for chunk in client.threads.join_stream(
- thread_id="my_thread_id",
- last_event_id="my_event_id",
- stream_mode="run_modes",
- ):
- print(chunk)
- ```
- """
- query_params = {
- "stream_mode": stream_mode,
- }
- if params:
- query_params.update(params)
- return self.http.stream(
- f"/threads/{thread_id}/stream",
- "GET",
- headers={
- **({"Last-Event-ID": last_event_id} if last_event_id else {}),
- **(headers or {}),
- },
- params=query_params,
- )
- class SyncRunsClient:
- """Synchronous client for managing runs in LangGraph.
- This class provides methods to create, retrieve, and manage runs, which represent
- individual executions of graphs.
- ???+ example "Example"
- ```python
- client = get_sync_client(url="http://localhost:2024")
- run = client.runs.create(thread_id="thread_123", assistant_id="asst_456")
- ```
- """
- def __init__(self, http: SyncHttpClient) -> None:
- self.http = http
- @overload
- def stream(
- self,
- thread_id: str,
- assistant_id: str,
- *,
- input: Input | None = None,
- command: Command | None = None,
- stream_mode: StreamMode | Sequence[StreamMode] = "values",
- stream_subgraphs: bool = False,
- metadata: Mapping[str, Any] | None = None,
- config: Config | None = None,
- context: Context | None = None,
- checkpoint: Checkpoint | None = None,
- checkpoint_id: str | None = None,
- checkpoint_during: bool | None = None,
- interrupt_before: All | Sequence[str] | None = None,
- interrupt_after: All | Sequence[str] | None = None,
- feedback_keys: Sequence[str] | None = None,
- on_disconnect: DisconnectMode | None = None,
- webhook: str | None = None,
- multitask_strategy: MultitaskStrategy | None = None,
- if_not_exists: IfNotExists | None = None,
- after_seconds: int | None = None,
- headers: Mapping[str, str] | None = None,
- params: QueryParamTypes | None = None,
- on_run_created: Callable[[RunCreateMetadata], None] | None = None,
- ) -> Iterator[StreamPart]: ...
- @overload
- def stream(
- self,
- thread_id: None,
- assistant_id: str,
- *,
- input: Input | None = None,
- command: Command | None = None,
- stream_mode: StreamMode | Sequence[StreamMode] = "values",
- stream_subgraphs: bool = False,
- stream_resumable: bool = False,
- metadata: Mapping[str, Any] | None = None,
- config: Config | None = None,
- context: Context | None = None,
- checkpoint_during: bool | None = None,
- interrupt_before: All | Sequence[str] | None = None,
- interrupt_after: All | Sequence[str] | None = None,
- feedback_keys: Sequence[str] | None = None,
- on_disconnect: DisconnectMode | None = None,
- on_completion: OnCompletionBehavior | None = None,
- if_not_exists: IfNotExists | None = None,
- webhook: str | None = None,
- after_seconds: int | None = None,
- headers: Mapping[str, str] | None = None,
- params: QueryParamTypes | None = None,
- on_run_created: Callable[[RunCreateMetadata], None] | None = None,
- ) -> Iterator[StreamPart]: ...
- def stream(
- self,
- thread_id: str | None,
- assistant_id: str,
- *,
- input: Input | None = None,
- command: Command | None = None,
- stream_mode: StreamMode | Sequence[StreamMode] = "values",
- stream_subgraphs: bool = False,
- stream_resumable: bool = False,
- metadata: Mapping[str, Any] | None = None,
- config: Config | None = None,
- context: Context | None = None,
- checkpoint: Checkpoint | None = None,
- checkpoint_id: str | None = None,
- checkpoint_during: bool | None = None, # deprecated
- interrupt_before: All | Sequence[str] | None = None,
- interrupt_after: All | Sequence[str] | None = None,
- feedback_keys: Sequence[str] | None = None,
- on_disconnect: DisconnectMode | None = None,
- on_completion: OnCompletionBehavior | None = None,
- webhook: str | None = None,
- multitask_strategy: MultitaskStrategy | None = None,
- if_not_exists: IfNotExists | None = None,
- after_seconds: int | None = None,
- headers: Mapping[str, str] | None = None,
- params: QueryParamTypes | None = None,
- on_run_created: Callable[[RunCreateMetadata], None] | None = None,
- durability: Durability | None = None,
- ) -> Iterator[StreamPart]:
- """Create a run and stream the results.
- Args:
- thread_id: the thread ID to assign to the thread.
- If `None` will create a stateless run.
- assistant_id: The assistant ID or graph name to stream from.
- If using graph name, will default to first assistant created from that graph.
- input: The input to the graph.
- command: The command to execute.
- stream_mode: The stream mode(s) to use.
- stream_subgraphs: Whether to stream output from subgraphs.
- stream_resumable: Whether the stream is considered resumable.
- If true, the stream can be resumed and replayed in its entirety even after disconnection.
- metadata: Metadata to assign to the run.
- config: The configuration for the assistant.
- context: Static context to add to the assistant.
- !!! version-added "Added in version 0.6.0"
- checkpoint: The checkpoint to resume from.
- checkpoint_during: (deprecated) Whether to checkpoint during the run (or only at the end/interruption).
- interrupt_before: Nodes to interrupt immediately before they get executed.
- interrupt_after: Nodes to Nodes to interrupt immediately after they get executed.
- feedback_keys: Feedback keys to assign to run.
- on_disconnect: The disconnect mode to use.
- Must be one of 'cancel' or 'continue'.
- on_completion: Whether to delete or keep the thread created for a stateless run.
- Must be one of 'delete' or 'keep'.
- webhook: Webhook to call after LangGraph API call is done.
- multitask_strategy: Multitask strategy to use.
- Must be one of 'reject', 'interrupt', 'rollback', or 'enqueue'.
- if_not_exists: How to handle missing thread. Defaults to 'reject'.
- Must be either 'reject' (raise error if missing), or 'create' (create new thread).
- after_seconds: The number of seconds to wait before starting the run.
- Use to schedule future runs.
- headers: Optional custom headers to include with the request.
- on_run_created: Optional callback to call when a run is created.
- durability: The durability to use for the run. Values are "sync", "async", or "exit".
- "async" means checkpoints are persisted async while next graph step executes, replaces checkpoint_during=True
- "sync" means checkpoints are persisted sync after graph step executes, replaces checkpoint_during=False
- "exit" means checkpoints are only persisted when the run exits, does not save intermediate steps
- Returns:
- Iterator of stream results.
- ???+ example "Example Usage"
- ```python
- client = get_sync_client(url="http://localhost:2024")
- async for chunk in client.runs.stream(
- thread_id=None,
- assistant_id="agent",
- input={"messages": [{"role": "user", "content": "how are you?"}]},
- stream_mode=["values","debug"],
- metadata={"name":"my_run"},
- context={"model_name": "anthropic"},
- interrupt_before=["node_to_stop_before_1","node_to_stop_before_2"],
- interrupt_after=["node_to_stop_after_1","node_to_stop_after_2"],
- feedback_keys=["my_feedback_key_1","my_feedback_key_2"],
- webhook="https://my.fake.webhook.com",
- multitask_strategy="interrupt"
- ):
- print(chunk)
- ```
- ```shell
- ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
- StreamPart(event='metadata', data={'run_id': '1ef4a9b8-d7da-679a-a45a-872054341df2'})
- StreamPart(event='values', data={'messages': [{'content': 'how are you?', 'additional_kwargs': {}, 'response_metadata': {}, 'type': 'human', 'name': None, 'id': 'fe0a5778-cfe9-42ee-b807-0adaa1873c10', 'example': False}]})
- StreamPart(event='values', data={'messages': [{'content': 'how are you?', 'additional_kwargs': {}, 'response_metadata': {}, 'type': 'human', 'name': None, 'id': 'fe0a5778-cfe9-42ee-b807-0adaa1873c10', 'example': False}, {'content': "I'm doing well, thanks for asking! I'm an AI assistant created by Anthropic to be helpful, honest, and harmless.", 'additional_kwargs': {}, 'response_metadata': {}, 'type': 'ai', 'name': None, 'id': 'run-159b782c-b679-4830-83c6-cef87798fe8b', 'example': False, 'tool_calls': [], 'invalid_tool_calls': [], 'usage_metadata': None}]})
- StreamPart(event='end', data=None)
- ```
- """
- if checkpoint_during is not None:
- warnings.warn(
- "`checkpoint_during` is deprecated and will be removed in a future version. Use `durability` instead.",
- DeprecationWarning,
- stacklevel=2,
- )
- payload = {
- "input": input,
- "command": (
- {k: v for k, v in command.items() if v is not None} if command else None
- ),
- "config": config,
- "context": context,
- "metadata": metadata,
- "stream_mode": stream_mode,
- "stream_subgraphs": stream_subgraphs,
- "stream_resumable": stream_resumable,
- "assistant_id": assistant_id,
- "interrupt_before": interrupt_before,
- "interrupt_after": interrupt_after,
- "feedback_keys": feedback_keys,
- "webhook": webhook,
- "checkpoint": checkpoint,
- "checkpoint_id": checkpoint_id,
- "checkpoint_during": checkpoint_during,
- "multitask_strategy": multitask_strategy,
- "if_not_exists": if_not_exists,
- "on_disconnect": on_disconnect,
- "on_completion": on_completion,
- "after_seconds": after_seconds,
- "durability": durability,
- }
- endpoint = (
- f"/threads/{thread_id}/runs/stream"
- if thread_id is not None
- else "/runs/stream"
- )
- def on_response(res: httpx.Response):
- """Callback function to handle the response."""
- if on_run_created and (metadata := _get_run_metadata_from_response(res)):
- on_run_created(metadata)
- return self.http.stream(
- endpoint,
- "POST",
- json={k: v for k, v in payload.items() if v is not None},
- params=params,
- headers=headers,
- on_response=on_response if on_run_created else None,
- )
- @overload
- def create(
- self,
- thread_id: None,
- assistant_id: str,
- *,
- input: Input | None = None,
- command: Command | None = None,
- stream_mode: StreamMode | Sequence[StreamMode] = "values",
- stream_subgraphs: bool = False,
- stream_resumable: bool = False,
- metadata: Mapping[str, Any] | None = None,
- config: Config | None = None,
- context: Context | None = None,
- checkpoint_during: bool | None = None,
- interrupt_before: All | Sequence[str] | None = None,
- interrupt_after: All | Sequence[str] | None = None,
- webhook: str | None = None,
- on_completion: OnCompletionBehavior | None = None,
- if_not_exists: IfNotExists | None = None,
- after_seconds: int | None = None,
- headers: Mapping[str, str] | None = None,
- params: QueryParamTypes | None = None,
- on_run_created: Callable[[RunCreateMetadata], None] | None = None,
- ) -> Run: ...
- @overload
- def create(
- self,
- thread_id: str,
- assistant_id: str,
- *,
- input: Input | None = None,
- command: Command | None = None,
- stream_mode: StreamMode | Sequence[StreamMode] = "values",
- stream_subgraphs: bool = False,
- stream_resumable: bool = False,
- metadata: Mapping[str, Any] | None = None,
- config: Config | None = None,
- context: Context | None = None,
- checkpoint: Checkpoint | None = None,
- checkpoint_id: str | None = None,
- checkpoint_during: bool | None = None,
- interrupt_before: All | Sequence[str] | None = None,
- interrupt_after: All | Sequence[str] | None = None,
- webhook: str | None = None,
- multitask_strategy: MultitaskStrategy | None = None,
- if_not_exists: IfNotExists | None = None,
- after_seconds: int | None = None,
- headers: Mapping[str, str] | None = None,
- params: QueryParamTypes | None = None,
- on_run_created: Callable[[RunCreateMetadata], None] | None = None,
- ) -> Run: ...
- def create(
- self,
- thread_id: str | None,
- assistant_id: str,
- *,
- input: Input | None = None,
- command: Command | None = None,
- stream_mode: StreamMode | Sequence[StreamMode] = "values",
- stream_subgraphs: bool = False,
- stream_resumable: bool = False,
- metadata: Mapping[str, Any] | None = None,
- config: Config | None = None,
- context: Context | None = None,
- checkpoint: Checkpoint | None = None,
- checkpoint_id: str | None = None,
- checkpoint_during: bool | None = None, # deprecated
- interrupt_before: All | Sequence[str] | None = None,
- interrupt_after: All | Sequence[str] | None = None,
- webhook: str | None = None,
- multitask_strategy: MultitaskStrategy | None = None,
- if_not_exists: IfNotExists | None = None,
- on_completion: OnCompletionBehavior | None = None,
- after_seconds: int | None = None,
- headers: Mapping[str, str] | None = None,
- params: QueryParamTypes | None = None,
- on_run_created: Callable[[RunCreateMetadata], None] | None = None,
- durability: Durability | None = None,
- ) -> Run:
- """Create a background run.
- Args:
- thread_id: the thread ID to assign to the thread.
- If `None` will create a stateless run.
- assistant_id: The assistant ID or graph name to stream from.
- If using graph name, will default to first assistant created from that graph.
- input: The input to the graph.
- command: The command to execute.
- stream_mode: The stream mode(s) to use.
- stream_subgraphs: Whether to stream output from subgraphs.
- stream_resumable: Whether the stream is considered resumable.
- If true, the stream can be resumed and replayed in its entirety even after disconnection.
- metadata: Metadata to assign to the run.
- config: The configuration for the assistant.
- context: Static context to add to the assistant.
- !!! version-added "Added in version 0.6.0"
- checkpoint: The checkpoint to resume from.
- checkpoint_during: (deprecated) Whether to checkpoint during the run (or only at the end/interruption).
- interrupt_before: Nodes to interrupt immediately before they get executed.
- interrupt_after: Nodes to Nodes to interrupt immediately after they get executed.
- webhook: Webhook to call after LangGraph API call is done.
- multitask_strategy: Multitask strategy to use.
- Must be one of 'reject', 'interrupt', 'rollback', or 'enqueue'.
- on_completion: Whether to delete or keep the thread created for a stateless run.
- Must be one of 'delete' or 'keep'.
- if_not_exists: How to handle missing thread. Defaults to 'reject'.
- Must be either 'reject' (raise error if missing), or 'create' (create new thread).
- after_seconds: The number of seconds to wait before starting the run.
- Use to schedule future runs.
- headers: Optional custom headers to include with the request.
- on_run_created: Optional callback to call when a run is created.
- durability: The durability to use for the run. Values are "sync", "async", or "exit".
- "async" means checkpoints are persisted async while next graph step executes, replaces checkpoint_during=True
- "sync" means checkpoints are persisted sync after graph step executes, replaces checkpoint_during=False
- "exit" means checkpoints are only persisted when the run exits, does not save intermediate steps
- Returns:
- The created background `Run`.
- ???+ example "Example Usage"
- ```python
- client = get_sync_client(url="http://localhost:2024")
- background_run = client.runs.create(
- thread_id="my_thread_id",
- assistant_id="my_assistant_id",
- input={"messages": [{"role": "user", "content": "hello!"}]},
- metadata={"name":"my_run"},
- context={"model_name": "openai"},
- interrupt_before=["node_to_stop_before_1","node_to_stop_before_2"],
- interrupt_after=["node_to_stop_after_1","node_to_stop_after_2"],
- webhook="https://my.fake.webhook.com",
- multitask_strategy="interrupt"
- )
- print(background_run)
- ```
- ```shell
- --------------------------------------------------------------------------------
- {
- 'run_id': 'my_run_id',
- 'thread_id': 'my_thread_id',
- 'assistant_id': 'my_assistant_id',
- 'created_at': '2024-07-25T15:35:42.598503+00:00',
- 'updated_at': '2024-07-25T15:35:42.598503+00:00',
- 'metadata': {},
- 'status': 'pending',
- 'kwargs':
- {
- 'input':
- {
- 'messages': [
- {
- 'role': 'user',
- 'content': 'how are you?'
- }
- ]
- },
- 'config':
- {
- 'metadata':
- {
- 'created_by': 'system'
- },
- 'configurable':
- {
- 'run_id': 'my_run_id',
- 'user_id': None,
- 'graph_id': 'agent',
- 'thread_id': 'my_thread_id',
- 'checkpoint_id': None,
- 'assistant_id': 'my_assistant_id'
- }
- },
- 'context':
- {
- 'model_name': 'openai'
- },
- 'webhook': "https://my.fake.webhook.com",
- 'temporary': False,
- 'stream_mode': ['values'],
- 'feedback_keys': None,
- 'interrupt_after': ["node_to_stop_after_1","node_to_stop_after_2"],
- 'interrupt_before': ["node_to_stop_before_1","node_to_stop_before_2"]
- },
- 'multitask_strategy': 'interrupt'
- }
- ```
- """
- if checkpoint_during is not None:
- warnings.warn(
- "`checkpoint_during` is deprecated and will be removed in a future version. Use `durability` instead.",
- DeprecationWarning,
- stacklevel=2,
- )
- payload = {
- "input": input,
- "command": (
- {k: v for k, v in command.items() if v is not None} if command else None
- ),
- "stream_mode": stream_mode,
- "stream_subgraphs": stream_subgraphs,
- "stream_resumable": stream_resumable,
- "config": config,
- "context": context,
- "metadata": metadata,
- "assistant_id": assistant_id,
- "interrupt_before": interrupt_before,
- "interrupt_after": interrupt_after,
- "webhook": webhook,
- "checkpoint": checkpoint,
- "checkpoint_id": checkpoint_id,
- "checkpoint_during": checkpoint_during,
- "multitask_strategy": multitask_strategy,
- "if_not_exists": if_not_exists,
- "on_completion": on_completion,
- "after_seconds": after_seconds,
- "durability": durability,
- }
- payload = {k: v for k, v in payload.items() if v is not None}
- def on_response(res: httpx.Response):
- """Callback function to handle the response."""
- if on_run_created and (metadata := _get_run_metadata_from_response(res)):
- on_run_created(metadata)
- return self.http.post(
- f"/threads/{thread_id}/runs" if thread_id else "/runs",
- json=payload,
- params=params,
- headers=headers,
- on_response=on_response if on_run_created else None,
- )
- def create_batch(
- self,
- payloads: list[RunCreate],
- *,
- headers: Mapping[str, str] | None = None,
- params: QueryParamTypes | None = None,
- ) -> list[Run]:
- """Create a batch of stateless background runs."""
- def filter_payload(payload: RunCreate):
- return {k: v for k, v in payload.items() if v is not None}
- filtered = [filter_payload(payload) for payload in payloads]
- return self.http.post(
- "/runs/batch", json=filtered, headers=headers, params=params
- )
- @overload
- def wait(
- self,
- thread_id: str,
- assistant_id: str,
- *,
- input: Input | None = None,
- command: Command | None = None,
- metadata: Mapping[str, Any] | None = None,
- config: Config | None = None,
- context: Context | None = None,
- checkpoint: Checkpoint | None = None,
- checkpoint_id: str | None = None,
- checkpoint_during: bool | None = None,
- interrupt_before: All | Sequence[str] | None = None,
- interrupt_after: All | Sequence[str] | None = None,
- webhook: str | None = None,
- on_disconnect: DisconnectMode | None = None,
- multitask_strategy: MultitaskStrategy | None = None,
- if_not_exists: IfNotExists | None = None,
- after_seconds: int | None = None,
- raise_error: bool = True,
- headers: Mapping[str, str] | None = None,
- params: QueryParamTypes | None = None,
- on_run_created: Callable[[RunCreateMetadata], None] | None = None,
- ) -> list[dict] | dict[str, Any]: ...
- @overload
- def wait(
- self,
- thread_id: None,
- assistant_id: str,
- *,
- input: Input | None = None,
- command: Command | None = None,
- metadata: Mapping[str, Any] | None = None,
- config: Config | None = None,
- context: Context | None = None,
- checkpoint_during: bool | None = None,
- interrupt_before: All | Sequence[str] | None = None,
- interrupt_after: All | Sequence[str] | None = None,
- webhook: str | None = None,
- on_disconnect: DisconnectMode | None = None,
- on_completion: OnCompletionBehavior | None = None,
- if_not_exists: IfNotExists | None = None,
- after_seconds: int | None = None,
- raise_error: bool = True,
- headers: Mapping[str, str] | None = None,
- params: QueryParamTypes | None = None,
- on_run_created: Callable[[RunCreateMetadata], None] | None = None,
- ) -> list[dict] | dict[str, Any]: ...
- def wait(
- self,
- thread_id: str | None,
- assistant_id: str,
- *,
- input: Input | None = None,
- command: Command | None = None,
- metadata: Mapping[str, Any] | None = None,
- config: Config | None = None,
- context: Context | None = None,
- checkpoint_during: bool | None = None, # deprecated
- checkpoint: Checkpoint | None = None,
- checkpoint_id: str | None = None,
- interrupt_before: All | Sequence[str] | None = None,
- interrupt_after: All | Sequence[str] | None = None,
- webhook: str | None = None,
- on_disconnect: DisconnectMode | None = None,
- on_completion: OnCompletionBehavior | None = None,
- multitask_strategy: MultitaskStrategy | None = None,
- if_not_exists: IfNotExists | None = None,
- after_seconds: int | None = None,
- raise_error: bool = True,
- headers: Mapping[str, str] | None = None,
- params: QueryParamTypes | None = None,
- on_run_created: Callable[[RunCreateMetadata], None] | None = None,
- durability: Durability | None = None,
- ) -> list[dict] | dict[str, Any]:
- """Create a run, wait until it finishes and return the final state.
- Args:
- thread_id: the thread ID to create the run on.
- If `None` will create a stateless run.
- assistant_id: The assistant ID or graph name to run.
- If using graph name, will default to first assistant created from that graph.
- input: The input to the graph.
- command: The command to execute.
- metadata: Metadata to assign to the run.
- config: The configuration for the assistant.
- context: Static context to add to the assistant.
- !!! version-added "Added in version 0.6.0"
- checkpoint: The checkpoint to resume from.
- checkpoint_during: (deprecated) Whether to checkpoint during the run (or only at the end/interruption).
- interrupt_before: Nodes to interrupt immediately before they get executed.
- interrupt_after: Nodes to Nodes to interrupt immediately after they get executed.
- webhook: Webhook to call after LangGraph API call is done.
- on_disconnect: The disconnect mode to use.
- Must be one of 'cancel' or 'continue'.
- on_completion: Whether to delete or keep the thread created for a stateless run.
- Must be one of 'delete' or 'keep'.
- multitask_strategy: Multitask strategy to use.
- Must be one of 'reject', 'interrupt', 'rollback', or 'enqueue'.
- if_not_exists: How to handle missing thread. Defaults to 'reject'.
- Must be either 'reject' (raise error if missing), or 'create' (create new thread).
- after_seconds: The number of seconds to wait before starting the run.
- Use to schedule future runs.
- raise_error: Whether to raise an error if the run fails.
- headers: Optional custom headers to include with the request.
- on_run_created: Optional callback to call when a run is created.
- durability: The durability to use for the run. Values are "sync", "async", or "exit".
- "async" means checkpoints are persisted async while next graph step executes, replaces checkpoint_during=True
- "sync" means checkpoints are persisted sync after graph step executes, replaces checkpoint_during=False
- "exit" means checkpoints are only persisted when the run exits, does not save intermediate steps
- Returns:
- The output of the `Run`.
- ???+ example "Example Usage"
- ```python
- final_state_of_run = client.runs.wait(
- thread_id=None,
- assistant_id="agent",
- input={"messages": [{"role": "user", "content": "how are you?"}]},
- metadata={"name":"my_run"},
- context={"model_name": "anthropic"},
- interrupt_before=["node_to_stop_before_1","node_to_stop_before_2"],
- interrupt_after=["node_to_stop_after_1","node_to_stop_after_2"],
- webhook="https://my.fake.webhook.com",
- multitask_strategy="interrupt"
- )
- print(final_state_of_run)
- ```
- ```shell
- -------------------------------------------------------------------------------------------------------------------------------------------
- {
- 'messages': [
- {
- 'content': 'how are you?',
- 'additional_kwargs': {},
- 'response_metadata': {},
- 'type': 'human',
- 'name': None,
- 'id': 'f51a862c-62fe-4866-863b-b0863e8ad78a',
- 'example': False
- },
- {
- 'content': "I'm doing well, thanks for asking! I'm an AI assistant created by Anthropic to be helpful, honest, and harmless.",
- 'additional_kwargs': {},
- 'response_metadata': {},
- 'type': 'ai',
- 'name': None,
- 'id': 'run-bf1cd3c6-768f-4c16-b62d-ba6f17ad8b36',
- 'example': False,
- 'tool_calls': [],
- 'invalid_tool_calls': [],
- 'usage_metadata': None
- }
- ]
- }
- ```
- """
- if checkpoint_during is not None:
- warnings.warn(
- "`checkpoint_during` is deprecated and will be removed in a future version. Use `durability` instead.",
- DeprecationWarning,
- stacklevel=2,
- )
- payload = {
- "input": input,
- "command": (
- {k: v for k, v in command.items() if v is not None} if command else None
- ),
- "config": config,
- "context": context,
- "metadata": metadata,
- "assistant_id": assistant_id,
- "interrupt_before": interrupt_before,
- "interrupt_after": interrupt_after,
- "webhook": webhook,
- "checkpoint": checkpoint,
- "checkpoint_id": checkpoint_id,
- "multitask_strategy": multitask_strategy,
- "if_not_exists": if_not_exists,
- "on_disconnect": on_disconnect,
- "checkpoint_during": checkpoint_during,
- "on_completion": on_completion,
- "after_seconds": after_seconds,
- "raise_error": raise_error,
- "durability": durability,
- }
- def on_response(res: httpx.Response):
- """Callback function to handle the response."""
- if on_run_created and (metadata := _get_run_metadata_from_response(res)):
- on_run_created(metadata)
- endpoint = (
- f"/threads/{thread_id}/runs/wait" if thread_id is not None else "/runs/wait"
- )
- return self.http.request_reconnect(
- endpoint,
- "POST",
- json={k: v for k, v in payload.items() if v is not None},
- params=params,
- headers=headers,
- on_response=on_response if on_run_created else None,
- )
- def list(
- self,
- thread_id: str,
- *,
- limit: int = 10,
- offset: int = 0,
- status: RunStatus | None = None,
- select: list[RunSelectField] | None = None,
- headers: Mapping[str, str] | None = None,
- params: QueryParamTypes | None = None,
- ) -> list[Run]:
- """List runs.
- Args:
- thread_id: The thread ID to list runs for.
- limit: The maximum number of results to return.
- offset: The number of results to skip.
- headers: Optional custom headers to include with the request.
- params: Optional query parameters to include with the request.
- Returns:
- The runs for the thread.
- ???+ example "Example Usage"
- ```python
- client = get_sync_client(url="http://localhost:2024")
- client.runs.list(
- thread_id="thread_id",
- limit=5,
- offset=5,
- )
- ```
- """
- query_params: dict[str, Any] = {"limit": limit, "offset": offset}
- if status is not None:
- query_params["status"] = status
- if select:
- query_params["select"] = select
- if params:
- query_params.update(params)
- return self.http.get(
- f"/threads/{thread_id}/runs", params=query_params, headers=headers
- )
- def get(
- self,
- thread_id: str,
- run_id: str,
- *,
- headers: Mapping[str, str] | None = None,
- params: QueryParamTypes | None = None,
- ) -> Run:
- """Get a run.
- Args:
- thread_id: The thread ID to get.
- run_id: The run ID to get.
- headers: Optional custom headers to include with the request.
- Returns:
- `Run` object.
- ???+ example "Example Usage"
- ```python
- run = client.runs.get(
- thread_id="thread_id_to_delete",
- run_id="run_id_to_delete",
- )
- ```
- """
- return self.http.get(
- f"/threads/{thread_id}/runs/{run_id}", headers=headers, params=params
- )
- def cancel(
- self,
- thread_id: str,
- run_id: str,
- *,
- wait: bool = False,
- action: CancelAction = "interrupt",
- headers: Mapping[str, str] | None = None,
- params: QueryParamTypes | None = None,
- ) -> None:
- """Get a run.
- Args:
- thread_id: The thread ID to cancel.
- run_id: The run ID to cancel.
- wait: Whether to wait until run has completed.
- action: Action to take when cancelling the run. Possible values
- are `interrupt` or `rollback`. Default is `interrupt`.
- headers: Optional custom headers to include with the request.
- params: Optional query parameters to include with the request.
- Returns:
- `None`
- ???+ example "Example Usage"
- ```python
- client = get_sync_client(url="http://localhost:2024")
- client.runs.cancel(
- thread_id="thread_id_to_cancel",
- run_id="run_id_to_cancel",
- wait=True,
- action="interrupt"
- )
- ```
- """
- query_params = {
- "wait": 1 if wait else 0,
- "action": action,
- }
- if params:
- query_params.update(params)
- if wait:
- return self.http.request_reconnect(
- f"/threads/{thread_id}/runs/{run_id}/cancel",
- "POST",
- json=None,
- params=query_params,
- headers=headers,
- )
- return self.http.post(
- f"/threads/{thread_id}/runs/{run_id}/cancel",
- json=None,
- params=query_params,
- headers=headers,
- )
- def join(
- self,
- thread_id: str,
- run_id: str,
- *,
- headers: Mapping[str, str] | None = None,
- params: QueryParamTypes | None = None,
- ) -> dict:
- """Block until a run is done. Returns the final state of the thread.
- Args:
- thread_id: The thread ID to join.
- run_id: The run ID to join.
- headers: Optional custom headers to include with the request.
- params: Optional query parameters to include with the request.
- Returns:
- `None`
- ???+ example "Example Usage"
- ```python
- client = get_sync_client(url="http://localhost:2024")
- client.runs.join(
- thread_id="thread_id_to_join",
- run_id="run_id_to_join"
- )
- ```
- """
- return self.http.request_reconnect(
- f"/threads/{thread_id}/runs/{run_id}/join",
- "GET",
- headers=headers,
- params=params,
- )
- def join_stream(
- self,
- thread_id: str,
- run_id: str,
- *,
- cancel_on_disconnect: bool = False,
- stream_mode: StreamMode | Sequence[StreamMode] | None = None,
- headers: Mapping[str, str] | None = None,
- params: QueryParamTypes | None = None,
- last_event_id: str | None = None,
- ) -> Iterator[StreamPart]:
- """Stream output from a run in real-time, until the run is done.
- Output is not buffered, so any output produced before this call will
- not be received here.
- Args:
- thread_id: The thread ID to join.
- run_id: The run ID to join.
- stream_mode: The stream mode(s) to use. Must be a subset of the stream modes passed
- when creating the run. Background runs default to having the union of all
- stream modes.
- cancel_on_disconnect: Whether to cancel the run when the stream is disconnected.
- headers: Optional custom headers to include with the request.
- params: Optional query parameters to include with the request.
- last_event_id: The last event ID to use for the stream.
- Returns:
- `None`
- ???+ example "Example Usage"
- ```python
- client = get_sync_client(url="http://localhost:2024")
- client.runs.join_stream(
- thread_id="thread_id_to_join",
- run_id="run_id_to_join",
- stream_mode=["values", "debug"]
- )
- ```
- """
- query_params = {
- "stream_mode": stream_mode,
- "cancel_on_disconnect": cancel_on_disconnect,
- }
- if params:
- query_params.update(params)
- return self.http.stream(
- f"/threads/{thread_id}/runs/{run_id}/stream",
- "GET",
- params=query_params,
- headers={
- **({"Last-Event-ID": last_event_id} if last_event_id else {}),
- **(headers or {}),
- }
- or None,
- )
- def delete(
- self,
- thread_id: str,
- run_id: str,
- *,
- headers: Mapping[str, str] | None = None,
- params: QueryParamTypes | None = None,
- ) -> None:
- """Delete a run.
- Args:
- thread_id: The thread ID to delete.
- run_id: The run ID to delete.
- headers: Optional custom headers to include with the request.
- params: Optional query parameters to include with the request.
- Returns:
- `None`
- ???+ example "Example Usage"
- ```python
- client = get_sync_client(url="http://localhost:2024")
- client.runs.delete(
- thread_id="thread_id_to_delete",
- run_id="run_id_to_delete"
- )
- ```
- """
- self.http.delete(
- f"/threads/{thread_id}/runs/{run_id}", headers=headers, params=params
- )
- class SyncCronClient:
- """Synchronous client for managing cron jobs in LangGraph.
- This class provides methods to create and manage scheduled tasks (cron jobs) for automated graph executions.
- ???+ example "Example"
- ```python
- client = get_sync_client(url="http://localhost:8123")
- cron_job = client.crons.create_for_thread(thread_id="thread_123", assistant_id="asst_456", schedule="0 * * * *")
- ```
- !!! note "Feature Availability"
- The crons client functionality is not supported on all licenses.
- Please check the relevant license documentation for the most up-to-date
- details on feature availability.
- """
- def __init__(self, http_client: SyncHttpClient) -> None:
- self.http = http_client
- def create_for_thread(
- self,
- thread_id: str,
- assistant_id: str,
- *,
- schedule: str,
- input: Input | None = None,
- metadata: Mapping[str, Any] | None = None,
- config: Config | None = None,
- context: Context | None = None,
- checkpoint_during: bool | None = None,
- interrupt_before: All | list[str] | None = None,
- interrupt_after: All | list[str] | None = None,
- webhook: str | None = None,
- multitask_strategy: str | None = None,
- headers: Mapping[str, str] | None = None,
- params: QueryParamTypes | None = None,
- ) -> Run:
- """Create a cron job for a thread.
- Args:
- thread_id: the thread ID to run the cron job on.
- assistant_id: The assistant ID or graph name to use for the cron job.
- If using graph name, will default to first assistant created from that graph.
- schedule: The cron schedule to execute this job on.
- input: The input to the graph.
- metadata: Metadata to assign to the cron job runs.
- config: The configuration for the assistant.
- context: Static context to add to the assistant.
- !!! version-added "Added in version 0.6.0"
- checkpoint_during: Whether to checkpoint during the run (or only at the end/interruption).
- interrupt_before: Nodes to interrupt immediately before they get executed.
- interrupt_after: Nodes to Nodes to interrupt immediately after they get executed.
- webhook: Webhook to call after LangGraph API call is done.
- multitask_strategy: Multitask strategy to use.
- Must be one of 'reject', 'interrupt', 'rollback', or 'enqueue'.
- headers: Optional custom headers to include with the request.
- Returns:
- The cron `Run`.
- ???+ example "Example Usage"
- ```python
- client = get_sync_client(url="http://localhost:8123")
- cron_run = client.crons.create_for_thread(
- thread_id="my-thread-id",
- assistant_id="agent",
- schedule="27 15 * * *",
- input={"messages": [{"role": "user", "content": "hello!"}]},
- metadata={"name":"my_run"},
- context={"model_name": "openai"},
- interrupt_before=["node_to_stop_before_1","node_to_stop_before_2"],
- interrupt_after=["node_to_stop_after_1","node_to_stop_after_2"],
- webhook="https://my.fake.webhook.com",
- multitask_strategy="interrupt"
- )
- ```
- """
- payload = {
- "schedule": schedule,
- "input": input,
- "config": config,
- "metadata": metadata,
- "context": context,
- "assistant_id": assistant_id,
- "interrupt_before": interrupt_before,
- "interrupt_after": interrupt_after,
- "checkpoint_during": checkpoint_during,
- "webhook": webhook,
- "multitask_strategy": multitask_strategy,
- }
- payload = {k: v for k, v in payload.items() if v is not None}
- return self.http.post(
- f"/threads/{thread_id}/runs/crons",
- json=payload,
- headers=headers,
- params=params,
- )
- def create(
- self,
- assistant_id: str,
- *,
- schedule: str,
- input: Input | None = None,
- metadata: Mapping[str, Any] | None = None,
- config: Config | None = None,
- context: Context | None = None,
- checkpoint_during: bool | None = None,
- interrupt_before: All | list[str] | None = None,
- interrupt_after: All | list[str] | None = None,
- webhook: str | None = None,
- multitask_strategy: str | None = None,
- headers: Mapping[str, str] | None = None,
- params: QueryParamTypes | None = None,
- ) -> Run:
- """Create a cron run.
- Args:
- assistant_id: The assistant ID or graph name to use for the cron job.
- If using graph name, will default to first assistant created from that graph.
- schedule: The cron schedule to execute this job on.
- input: The input to the graph.
- metadata: Metadata to assign to the cron job runs.
- config: The configuration for the assistant.
- context: Static context to add to the assistant.
- !!! version-added "Added in version 0.6.0"
- checkpoint_during: Whether to checkpoint during the run (or only at the end/interruption).
- interrupt_before: Nodes to interrupt immediately before they get executed.
- interrupt_after: Nodes to Nodes to interrupt immediately after they get executed.
- webhook: Webhook to call after LangGraph API call is done.
- multitask_strategy: Multitask strategy to use.
- Must be one of 'reject', 'interrupt', 'rollback', or 'enqueue'.
- headers: Optional custom headers to include with the request.
- Returns:
- The cron `Run`.
- ???+ example "Example Usage"
- ```python
- client = get_sync_client(url="http://localhost:8123")
- cron_run = client.crons.create(
- assistant_id="agent",
- schedule="27 15 * * *",
- input={"messages": [{"role": "user", "content": "hello!"}]},
- metadata={"name":"my_run"},
- context={"model_name": "openai"},
- checkpoint_during=True,
- interrupt_before=["node_to_stop_before_1","node_to_stop_before_2"],
- interrupt_after=["node_to_stop_after_1","node_to_stop_after_2"],
- webhook="https://my.fake.webhook.com",
- multitask_strategy="interrupt"
- )
- ```
- """
- payload = {
- "schedule": schedule,
- "input": input,
- "config": config,
- "metadata": metadata,
- "context": context,
- "assistant_id": assistant_id,
- "interrupt_before": interrupt_before,
- "interrupt_after": interrupt_after,
- "webhook": webhook,
- "checkpoint_during": checkpoint_during,
- "multitask_strategy": multitask_strategy,
- }
- payload = {k: v for k, v in payload.items() if v is not None}
- return self.http.post(
- "/runs/crons", json=payload, headers=headers, params=params
- )
- def delete(
- self,
- cron_id: str,
- *,
- headers: Mapping[str, str] | None = None,
- params: QueryParamTypes | None = None,
- ) -> None:
- """Delete a cron.
- Args:
- cron_id: The cron ID to delete.
- headers: Optional custom headers to include with the request.
- params: Optional query parameters to include with the request.
- Returns:
- `None`
- ???+ example "Example Usage"
- ```python
- client = get_sync_client(url="http://localhost:8123")
- client.crons.delete(
- cron_id="cron_to_delete"
- )
- ```
- """
- self.http.delete(f"/runs/crons/{cron_id}", headers=headers, params=params)
- def search(
- self,
- *,
- assistant_id: str | None = None,
- thread_id: str | None = None,
- limit: int = 10,
- offset: int = 0,
- sort_by: CronSortBy | None = None,
- sort_order: SortOrder | None = None,
- select: list[CronSelectField] | None = None,
- headers: Mapping[str, str] | None = None,
- params: QueryParamTypes | None = None,
- ) -> list[Cron]:
- """Get a list of cron jobs.
- Args:
- assistant_id: The assistant ID or graph name to search for.
- thread_id: the thread ID to search for.
- limit: The maximum number of results to return.
- offset: The number of results to skip.
- headers: Optional custom headers to include with the request.
- Returns:
- The list of cron jobs returned by the search,
- ???+ example "Example Usage"
- ```python
- client = get_sync_client(url="http://localhost:8123")
- cron_jobs = client.crons.search(
- assistant_id="my_assistant_id",
- thread_id="my_thread_id",
- limit=5,
- offset=5,
- )
- print(cron_jobs)
- ```
- ```shell
- ----------------------------------------------------------
- [
- {
- 'cron_id': '1ef3cefa-4c09-6926-96d0-3dc97fd5e39b',
- 'assistant_id': 'my_assistant_id',
- 'thread_id': 'my_thread_id',
- 'user_id': None,
- 'payload':
- {
- 'input': {'start_time': ''},
- 'schedule': '4 * * * *',
- 'assistant_id': 'my_assistant_id'
- },
- 'schedule': '4 * * * *',
- 'next_run_date': '2024-07-25T17:04:00+00:00',
- 'end_time': None,
- 'created_at': '2024-07-08T06:02:23.073257+00:00',
- 'updated_at': '2024-07-08T06:02:23.073257+00:00'
- }
- ]
- ```
- """
- payload = {
- "assistant_id": assistant_id,
- "thread_id": thread_id,
- "limit": limit,
- "offset": offset,
- }
- if sort_by:
- payload["sort_by"] = sort_by
- if sort_order:
- payload["sort_order"] = sort_order
- if select:
- payload["select"] = select
- payload = {k: v for k, v in payload.items() if v is not None}
- return self.http.post(
- "/runs/crons/search", json=payload, headers=headers, params=params
- )
- def count(
- self,
- *,
- assistant_id: str | None = None,
- thread_id: str | None = None,
- headers: Mapping[str, str] | None = None,
- params: QueryParamTypes | None = None,
- ) -> int:
- """Count cron jobs matching filters.
- Args:
- assistant_id: Assistant ID to filter by.
- thread_id: Thread ID to filter by.
- headers: Optional custom headers to include with the request.
- params: Optional query parameters to include with the request.
- Returns:
- int: Number of crons matching the criteria.
- """
- payload: dict[str, Any] = {}
- if assistant_id:
- payload["assistant_id"] = assistant_id
- if thread_id:
- payload["thread_id"] = thread_id
- return self.http.post(
- "/runs/crons/count", json=payload, headers=headers, params=params
- )
- class SyncStoreClient:
- """A client for synchronous operations on a key-value store.
- Provides methods to interact with a remote key-value store, allowing
- storage and retrieval of items within namespaced hierarchies.
- ???+ example "Example"
- ```python
- client = get_sync_client(url="http://localhost:2024"))
- client.store.put_item(["users", "profiles"], "user123", {"name": "Alice", "age": 30})
- ```
- """
- def __init__(self, http: SyncHttpClient) -> None:
- self.http = http
- def put_item(
- self,
- namespace: Sequence[str],
- /,
- key: str,
- value: Mapping[str, Any],
- index: Literal[False] | list[str] | None = None,
- ttl: int | None = None,
- headers: Mapping[str, str] | None = None,
- params: QueryParamTypes | None = None,
- ) -> None:
- """Store or update an item.
- Args:
- namespace: A list of strings representing the namespace path.
- key: The unique identifier for the item within the namespace.
- value: A dictionary containing the item's data.
- index: Controls search indexing - None (use defaults), False (disable), or list of field paths to index.
- ttl: Optional time-to-live in minutes for the item, or None for no expiration.
- headers: Optional custom headers to include with the request.
- params: Optional query parameters to include with the request.
- Returns:
- `None`
- ???+ example "Example Usage"
- ```python
- client = get_sync_client(url="http://localhost:8123")
- client.store.put_item(
- ["documents", "user123"],
- key="item456",
- value={"title": "My Document", "content": "Hello World"}
- )
- ```
- """
- for label in namespace:
- if "." in label:
- raise ValueError(
- f"Invalid namespace label '{label}'. Namespace labels cannot contain periods ('.')."
- )
- payload = {
- "namespace": namespace,
- "key": key,
- "value": value,
- "index": index,
- "ttl": ttl,
- }
- self.http.put(
- "/store/items", json=_provided_vals(payload), headers=headers, params=params
- )
- def get_item(
- self,
- namespace: Sequence[str],
- /,
- key: str,
- *,
- refresh_ttl: bool | None = None,
- headers: Mapping[str, str] | None = None,
- params: QueryParamTypes | None = None,
- ) -> Item:
- """Retrieve a single item.
- Args:
- key: The unique identifier for the item.
- namespace: Optional list of strings representing the namespace path.
- refresh_ttl: Whether to refresh the TTL on this read operation. If `None`, uses the store's default behavior.
- headers: Optional custom headers to include with the request.
- Returns:
- The retrieved item.
- ???+ example "Example Usage"
- ```python
- client = get_sync_client(url="http://localhost:8123")
- item = client.store.get_item(
- ["documents", "user123"],
- key="item456",
- )
- print(item)
- ```
- ```shell
- ----------------------------------------------------------------
- {
- 'namespace': ['documents', 'user123'],
- 'key': 'item456',
- 'value': {'title': 'My Document', 'content': 'Hello World'},
- 'created_at': '2024-07-30T12:00:00Z',
- 'updated_at': '2024-07-30T12:00:00Z'
- }
- ```
- """
- for label in namespace:
- if "." in label:
- raise ValueError(
- f"Invalid namespace label '{label}'. Namespace labels cannot contain periods ('.')."
- )
- query_params = {"key": key, "namespace": ".".join(namespace)}
- if refresh_ttl is not None:
- query_params["refresh_ttl"] = refresh_ttl
- if params:
- query_params.update(params)
- return self.http.get("/store/items", params=query_params, headers=headers)
- def delete_item(
- self,
- namespace: Sequence[str],
- /,
- key: str,
- headers: Mapping[str, str] | None = None,
- params: QueryParamTypes | None = None,
- ) -> None:
- """Delete an item.
- Args:
- key: The unique identifier for the item.
- namespace: Optional list of strings representing the namespace path.
- headers: Optional custom headers to include with the request.
- params: Optional query parameters to include with the request.
- Returns:
- `None`
- ???+ example "Example Usage"
- ```python
- client = get_sync_client(url="http://localhost:8123")
- client.store.delete_item(
- ["documents", "user123"],
- key="item456",
- )
- ```
- """
- self.http.delete(
- "/store/items",
- json={"key": key, "namespace": namespace},
- headers=headers,
- params=params,
- )
- def search_items(
- self,
- namespace_prefix: Sequence[str],
- /,
- filter: Mapping[str, Any] | None = None,
- limit: int = 10,
- offset: int = 0,
- query: str | None = None,
- refresh_ttl: bool | None = None,
- headers: Mapping[str, str] | None = None,
- params: QueryParamTypes | None = None,
- ) -> SearchItemsResponse:
- """Search for items within a namespace prefix.
- Args:
- namespace_prefix: List of strings representing the namespace prefix.
- filter: Optional dictionary of key-value pairs to filter results.
- limit: Maximum number of items to return (default is 10).
- offset: Number of items to skip before returning results (default is 0).
- query: Optional query for natural language search.
- refresh_ttl: Whether to refresh the TTL on items returned by this search. If `None`, uses the store's default behavior.
- headers: Optional custom headers to include with the request.
- params: Optional query parameters to include with the request.
- Returns:
- A list of items matching the search criteria.
- ???+ example "Example Usage"
- ```python
- client = get_sync_client(url="http://localhost:8123")
- items = client.store.search_items(
- ["documents"],
- filter={"author": "John Doe"},
- limit=5,
- offset=0
- )
- print(items)
- ```
- ```shell
- ----------------------------------------------------------------
- {
- "items": [
- {
- "namespace": ["documents", "user123"],
- "key": "item789",
- "value": {
- "title": "Another Document",
- "author": "John Doe"
- },
- "created_at": "2024-07-30T12:00:00Z",
- "updated_at": "2024-07-30T12:00:00Z"
- },
- # ... additional items ...
- ]
- }
- ```
- """
- payload = {
- "namespace_prefix": namespace_prefix,
- "filter": filter,
- "limit": limit,
- "offset": offset,
- "query": query,
- "refresh_ttl": refresh_ttl,
- }
- return self.http.post(
- "/store/items/search",
- json=_provided_vals(payload),
- headers=headers,
- params=params,
- )
- def list_namespaces(
- self,
- prefix: list[str] | None = None,
- suffix: list[str] | None = None,
- max_depth: int | None = None,
- limit: int = 100,
- offset: int = 0,
- *,
- headers: Mapping[str, str] | None = None,
- params: QueryParamTypes | None = None,
- ) -> ListNamespaceResponse:
- """List namespaces with optional match conditions.
- Args:
- prefix: Optional list of strings representing the prefix to filter namespaces.
- suffix: Optional list of strings representing the suffix to filter namespaces.
- max_depth: Optional integer specifying the maximum depth of namespaces to return.
- limit: Maximum number of namespaces to return (default is 100).
- offset: Number of namespaces to skip before returning results (default is 0).
- headers: Optional custom headers to include with the request.
- Returns:
- A list of namespaces matching the criteria.
- ???+ example "Example Usage"
- ```python
- client = get_sync_client(url="http://localhost:8123")
- namespaces = client.store.list_namespaces(
- prefix=["documents"],
- max_depth=3,
- limit=10,
- offset=0
- )
- print(namespaces)
- ```
- ```shell
- ----------------------------------------------------------------
- [
- ["documents", "user123", "reports"],
- ["documents", "user456", "invoices"],
- ...
- ]
- ```
- """
- payload = {
- "prefix": prefix,
- "suffix": suffix,
- "max_depth": max_depth,
- "limit": limit,
- "offset": offset,
- }
- return self.http.post(
- "/store/namespaces",
- json=_provided_vals(payload),
- headers=headers,
- params=params,
- )
- def _provided_vals(d: Mapping[str, Any]) -> dict[str, Any]:
- return {k: v for k, v in d.items() if v is not None}
- _registered_transports: list[httpx.ASGITransport] = []
- # Do not move; this is used in the server.
- def configure_loopback_transports(app: Any) -> None:
- for transport in _registered_transports:
- transport.app = app
- @functools.lru_cache(maxsize=1)
- def get_asgi_transport() -> type[httpx.ASGITransport]:
- try:
- from langgraph_api import asgi_transport # type: ignore[unresolved-import]
- return asgi_transport.ASGITransport
- except ImportError:
- # Older versions of the server
- return httpx.ASGITransport
- TimeoutTypes = (
- None
- | float
- | tuple[float | None, float | None]
- | tuple[float | None, float | None, float | None, float | None]
- | httpx.Timeout
- )
|