zen-code 4.9.0 → 4.9.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/app.js +187 -144
- package/dist/{chunk-4nsg4vcd.js → chunk-0pss3s5r.js} +1 -1
- package/dist/chunk-0sxrk9sx.js +1 -0
- package/dist/{chunk-gcm4jp0d.js → chunk-0zk0m93z.js} +1 -1
- package/dist/chunk-178yjjsx.js +1 -0
- package/dist/chunk-1p9xzvpt.js +3 -0
- package/dist/{chunk-hfve7nf5.js → chunk-2eh0sv3s.js} +2 -2
- package/dist/chunk-43xrz4wp.js +2 -0
- package/dist/chunk-48ce2wt0.js +1 -0
- package/dist/chunk-48vkm1yn.js +5 -0
- package/dist/{chunk-va71tsw3.js → chunk-55nx49pj.js} +2 -2
- package/dist/chunk-578m1dhj.js +2 -0
- package/dist/{chunk-trjpzw1n.js → chunk-5dsevrtz.js} +3 -3
- package/dist/{chunk-1y82m5kn.js → chunk-62zh99t6.js} +4 -4
- package/dist/chunk-66890qd3.js +2 -0
- package/dist/{chunk-9k5d9vf1.js → chunk-6nfpdtn6.js} +1 -1
- package/dist/chunk-738m8242.js +53 -0
- package/dist/{chunk-98f6hg43.js → chunk-8f2zh5h6.js} +2 -2
- package/dist/{chunk-jbf8ve63.js → chunk-8ty2zfve.js} +1 -1
- package/dist/{chunk-9dahn9h7.js → chunk-94jawhw7.js} +1 -1
- package/dist/chunk-98wjxsna.js +79 -0
- package/dist/chunk-9b7nj74j.js +1 -0
- package/dist/{chunk-wn43r152.js → chunk-9k64296h.js} +1 -1
- package/dist/chunk-9x562s6p.js +1 -0
- package/dist/chunk-a90fm6gz.js +278 -0
- package/dist/chunk-ac5t2ywn.js +100 -0
- package/dist/chunk-ad2hbq42.js +1 -0
- package/dist/chunk-afhxxkmv.js +16 -0
- package/dist/chunk-b4vvgbav.js +1 -0
- package/dist/{chunk-g7pm00z7.js → chunk-b9pcntkv.js} +9 -9
- package/dist/chunk-c7y5efa0.js +1 -0
- package/dist/chunk-cbjnwrt7.js +2 -0
- package/dist/{chunk-g377vrpj.js → chunk-ce53j63y.js} +1 -1
- package/dist/{chunk-kba8akjs.js → chunk-dcs1r9as.js} +1 -1
- package/dist/chunk-dcwnpdtk.js +9 -0
- package/dist/{chunk-b52b0t16.js → chunk-dxec2q4t.js} +1 -1
- package/dist/{chunk-13nyfrmm.js → chunk-e3tyc24s.js} +1 -1
- package/dist/{chunk-ep2es95e.js → chunk-e8hp8d68.js} +3 -3
- package/dist/chunk-fkrydbn4.js +18 -0
- package/dist/chunk-frhhpxxy.js +2 -0
- package/dist/{chunk-ns6tjjkq.js → chunk-fw3nrwpf.js} +1 -1
- package/dist/chunk-gyhxdxb4.js +1 -0
- package/dist/chunk-h1enhch1.js +2 -0
- package/dist/chunk-hcnx1j2z.js +1 -0
- package/dist/chunk-hfegb4pr.js +2 -0
- package/dist/{chunk-mmq834zt.js → chunk-hfypkhky.js} +1 -1
- package/dist/chunk-hmemx3cw.js +2 -0
- package/dist/chunk-hra0748z.js +2 -0
- package/dist/chunk-hsev32dg.js +4 -0
- package/dist/chunk-hyf24r36.js +2 -0
- package/dist/chunk-jb4yt88g.js +6 -0
- package/dist/chunk-jjcmm167.js +1 -0
- package/dist/chunk-jrepjpft.js +2 -0
- package/dist/chunk-k38fjqj7.js +140 -0
- package/dist/{chunk-cs73xbzz.js → chunk-kym9tb01.js} +1 -1
- package/dist/chunk-mt1g6g89.js +1 -0
- package/dist/chunk-p0vzbr7s.js +585 -0
- package/dist/{chunk-heasksrr.js → chunk-pndhbee8.js} +2 -2
- package/dist/{chunk-cggjws6a.js → chunk-pwrscdkf.js} +1 -1
- package/dist/{chunk-j7a40ww9.js → chunk-r019959h.js} +2 -2
- package/dist/chunk-r10bn684.js +1 -0
- package/dist/{chunk-30sq2w0d.js → chunk-r3pe49q4.js} +3 -3
- package/dist/chunk-r4tq44hr.js +1 -0
- package/dist/chunk-rjrnaka2.js +1 -0
- package/dist/{chunk-8g2zdcy0.js → chunk-rt5mpgbg.js} +2 -2
- package/dist/chunk-rztre6k0.js +1 -0
- package/dist/chunk-s77qbhtz.js +3 -0
- package/dist/chunk-t7rwtc17.js +1 -0
- package/dist/chunk-v8g52kan.js +1 -0
- package/dist/chunk-vd6c87cm.js +2 -0
- package/dist/{chunk-rncpxz1b.js → chunk-vfwbx331.js} +2 -2
- package/dist/chunk-vh9zd1v3.js +5 -0
- package/dist/chunk-w2hbsa9j.js +86 -0
- package/dist/chunk-wabmqprd.js +184 -0
- package/dist/chunk-wpy5r9ma.js +40 -0
- package/dist/chunk-x552nspp.js +6 -0
- package/dist/chunk-x90r4sje.js +1 -0
- package/dist/chunk-yndex7hs.js +1 -0
- package/dist/{chunk-7kdvr78m.js → chunk-yqwxbcc7.js} +4 -4
- package/dist/chunk-z8n7y37k.js +1 -0
- package/dist/chunk-zr7sx9hd.js +1 -0
- package/dist/chunk-zxqmghzf.js +1 -0
- package/dist/cli.js +1 -1
- package/dist/nonInteractive.js +2 -2
- package/dist/zen-keyboard.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-02vv5584.js +0 -1
- package/dist/chunk-1edvf7b5.js +0 -1
- package/dist/chunk-1rmnbdef.js +0 -1
- package/dist/chunk-1ttywx0y.js +0 -6
- package/dist/chunk-32ase1cw.js +0 -2
- package/dist/chunk-3490ntd8.js +0 -1
- package/dist/chunk-3pcybja5.js +0 -7
- package/dist/chunk-5rr85f28.js +0 -1
- package/dist/chunk-5x8nxw0t.js +0 -137
- package/dist/chunk-6rfc36jg.js +0 -1
- package/dist/chunk-76h8pe7x.js +0 -2
- package/dist/chunk-8z38ybz7.js +0 -1
- package/dist/chunk-b8dxq9rq.js +0 -1
- package/dist/chunk-cjqarwdn.js +0 -1
- package/dist/chunk-cyexd09c.js +0 -2
- package/dist/chunk-f8ewggk1.js +0 -1
- package/dist/chunk-j9aysaeb.js +0 -1
- package/dist/chunk-jfhc5c0d.js +0 -1
- package/dist/chunk-jxsfzfac.js +0 -2
- package/dist/chunk-m76ya904.js +0 -1
- package/dist/chunk-mjzeawnq.js +0 -6
- package/dist/chunk-nwy6n6b6.js +0 -274
- package/dist/chunk-qd305hg1.js +0 -1
- package/dist/chunk-qez6ejd4.js +0 -1
- package/dist/chunk-r2h3x9zv.js +0 -2
- package/dist/chunk-rz3b356n.js +0 -1
- package/dist/chunk-xhnvpygg.js +0 -2
- package/dist/chunk-xkz5z0zn.js +0 -1
- package/dist/chunk-zwxjkwqd.js +0 -26
- package/dist/chunk-zz32kgt2.js +0 -1
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import{Ah as m0,Bh as A6,Ch as E6,Dh as F6,Eh as f4,Fh as l4,Gh as c4,Hh as L6,Ih as R6,Lh as N1,Mh as E5,Nh as F5,Oh as L5,Ph as S9,Qh as P6,Rh as n5}from"./chunk-dcwnpdtk.js";import{ui as B6}from"./chunk-vh9zd1v3.js";import{$i as r,$k as N0,Ak as o9,Al as q4,Bi as p0,Bk as i9,Bl as U4,Ci as o0,Cj as u4,Ck as n9,Dk as Z1,Ek as s9,Fi as i0,Fk as r9,Gk as t9,Hj as K8,Hk as J1,Ik as Y1,Ji as V6,Jk as a9,Ki as O6,Kk as e9,Li as _6,Lk as G1,Mi as T6,Mj as A4,Mk as Q0,Ni as Q6,Nk as Z0,Oi as j6,Oj as f,Ok as J0,Pi as s,Pj as q1,Pk as Y0,Qj as H9,Qk as G0,Rj as O8,Rk as H0,Sj as J6,Sk as W0,Ti as P1,Tk as X0,Uj as U1,Uk as z0,Vk as $0,Wj as c8,Wk as K0,Xj as E0,Xk as q0,Yk as U0,Zj as Y6,Zk as w0,_j as w1,_k as D0,aj as B4,ak as C0,al as B0,bk as G6,bl as E4,ck as h8,dj as Z6,dk as H6,ek as W6,el as U6,fk as X6,fl as h,gk as z6,hk as a4,hl as D4,ik as e,il as U8,jl as w6,kk as $6,kl as D6,lk as E1,ll as S0,mk as G4,ml as N6,nj as p8,nk as J8,oj as w8,ok as G8,ol as Z4,pj as F9,pk as H4,pl as y,qk as W4,ql as j8,rl as X4,sk as K6,sl as z4,tk as U5,tl as D1,uk as Y8,ul as z1,vi as F,vl as q8,wi as e5,wk as q6,wl as $4,xi as C8,xj as $8,xk as V8,xl as K4,yi as G9,yk as B1,yl as T8,zk as E8,zl as $1}from"./chunk-w2hbsa9j.js";import{El as l8}from"./chunk-rztre6k0.js";var A0=F({extendInteropZodObject:()=>$0,getInteropZodDefaultGetter:()=>w0,getInteropZodObjectShape:()=>z0,getSchemaDescription:()=>G1,interopParse:()=>e9,interopParseAsync:()=>Y1,interopSafeParse:()=>a9,interopSafeParseAsync:()=>J1,interopZodObjectMakeFieldsOptional:()=>N0,interopZodObjectPartial:()=>K0,interopZodObjectPassthrough:()=>U0,interopZodObjectStrict:()=>q0,interopZodTransformInputSchema:()=>D0,isInteropZodError:()=>B0,isInteropZodLiteral:()=>t9,isInteropZodObject:()=>X0,isInteropZodSchema:()=>Z1,isShapelessZodSchema:()=>Q0,isSimpleStringZodSchema:()=>Z0,isZodArrayV4:()=>G0,isZodLiteralV3:()=>s9,isZodLiteralV4:()=>r9,isZodNullableV4:()=>W0,isZodObjectV3:()=>J0,isZodObjectV4:()=>Y0,isZodOptionalV4:()=>H0,isZodSchema:()=>n9,isZodSchemaV3:()=>i9,isZodSchemaV4:()=>o9});function d1(Q){return E0({clockseq:Q})}function g6(Q,Z){let J=Z.replace(/-/g,"").match(/.{2}/g).map((Y)=>parseInt(Y,16));return c8(Q,new Uint8Array(J))}var F0="__pregel_tasks",m1="__error__",c1="__scheduled__",u1="__interrupt__",l1="__resume__";var L0="[...]",d6="[Circular]",H1=[],P8=[];function m6(){return{depthLimit:Number.MAX_SAFE_INTEGER,edgesLimit:Number.MAX_SAFE_INTEGER}}function R0(Q,Z,J,Y){if(typeof Y>"u")Y=m6();o1(Q,"",0,[],void 0,0,Y);var G;try{if(P8.length===0)G=JSON.stringify(Q,Z,J);else G=JSON.stringify(Q,c6(Z),J)}catch(X){return JSON.stringify("[unable to serialize, circular reference is too complex to analyze]")}finally{while(H1.length!==0){var H=H1.pop();if(H.length===4)Object.defineProperty(H[0],H[1],H[3]);else H[0][H[1]]=H[2]}}return G}function p1(Q,Z,J,Y){var G=Object.getOwnPropertyDescriptor(Y,J);if(G.get!==void 0)if(G.configurable)Object.defineProperty(Y,J,{value:Q}),H1.push([Y,J,Z,G]);else P8.push([Z,J,Q]);else Y[J]=Q,H1.push([Y,J,Z])}function o1(Q,Z,J,Y,G,H,X){H+=1;var $;if(typeof Q==="object"&&Q!==null){for($=0;$<Y.length;$++)if(Y[$]===Q){p1(d6,Q,Z,G);return}if(typeof X.depthLimit<"u"&&H>X.depthLimit){p1(L0,Q,Z,G);return}if(typeof X.edgesLimit<"u"&&J+1>X.edgesLimit){p1(L0,Q,Z,G);return}if(Y.push(Q),Array.isArray(Q))for($=0;$<Q.length;$++)o1(Q[$],$,$,Y,Q,H,X);else{var U=Object.keys(Q);for($=0;$<U.length;$++){var w=U[$];o1(Q[w],w,$,Y,Q,H,X)}}Y.pop()}}function c6(Q){return Q=typeof Q<"u"?Q:function(Z,J){return J},function(Z,J){if(P8.length>0)for(var Y=0;Y<P8.length;Y++){var G=P8[Y];if(G[1]===Z&&G[0]===J){J=G[2],P8.splice(Y,1);break}}return Q.call(this,Z,J)}}var P0=[];var I0=F({});var V0=F({});var O0=F({BaseChatMessageHistory:()=>i1,BaseListChatMessageHistory:()=>W1,InMemoryChatMessageHistory:()=>u6}),i1=class extends s{async addMessages(Q){for(let Z of Q)await this.addMessage(Z)}},W1=class extends s{addUserMessage(Q){return this.addMessage(new $8(Q))}addAIMessage(Q){return this.addMessage(new f(Q))}async addMessages(Q){for(let Z of Q)await this.addMessage(Z)}clear(){throw Error("Not implemented.")}},u6=class extends W1{lc_namespace=["langchain","stores","message","in_memory"];messages=[];constructor(Q){super(...arguments);this.messages=Q??[]}async getMessages(){return this.messages}async addMessage(Q){this.messages.push(Q)}async clear(){this.messages=[]}};var p=class{pageContent;metadata;id;constructor(Q){this.pageContent=Q.pageContent!==void 0?Q.pageContent.toString():"",this.metadata=Q.metadata??{},this.id=Q.id}};var n1=class extends y{lc_namespace=["langchain_core","documents","transformers"];invoke(Q,Z){return this.transformDocuments(Q)}},_0=class extends n1{async transformDocuments(Q){let Z=[];for(let J of Q){let Y=await this._transformDocument(J);Z.push(Y)}return Z}};var T0=F({BaseDocumentTransformer:()=>n1,Document:()=>p,MappingDocumentTransformer:()=>_0});var j0=F({BaseDocumentLoader:()=>s1}),s1=class{};var M0=F({LangSmithLoader:()=>l6}),l6=class extends s1{datasetId;datasetName;exampleIds;asOf;splits;inlineS3Urls;offset;limit;metadata;filter;contentKey;formatContent;client;constructor(Q){super();if(Q.client&&Q.clientConfig)throw Error("client and clientConfig cannot both be provided.");this.client=Q.client??new C0(Q?.clientConfig),this.contentKey=Q.contentKey?Q.contentKey.split("."):[],this.formatContent=Q.formatContent??p6,this.datasetId=Q.datasetId,this.datasetName=Q.datasetName,this.exampleIds=Q.exampleIds,this.asOf=Q.asOf,this.splits=Q.splits,this.inlineS3Urls=Q.inlineS3Urls,this.offset=Q.offset,this.limit=Q.limit,this.metadata=Q.metadata,this.filter=Q.filter}async load(){let Q=[];for await(let Z of this.client.listExamples({datasetId:this.datasetId,datasetName:this.datasetName,exampleIds:this.exampleIds,asOf:this.asOf,splits:this.splits,inlineS3Urls:this.inlineS3Urls,offset:this.offset,limit:this.limit,metadata:this.metadata,filter:this.filter})){let J=Z.inputs;for(let H of this.contentKey)J=J[H];let Y=this.formatContent(J),G=Z;["created_at","modified_at"].forEach((H)=>{if(H in G){if(typeof G[H]==="object")G[H]=G[H].toString()}}),Q.push({pageContent:Y,metadata:G})}return Q}};function p6(Q){if(typeof Q==="string")return Q;else try{return JSON.stringify(Q,null,2)}catch{return String(Q)}}var y0=F({Embeddings:()=>X1}),X1=class{caller;constructor(Q){this.caller=new S0(Q??{})}};var I8=class extends s{lc_namespace=["langchain_core","example_selectors","base"]};var r1=class{async getPromptAsync(Q,Z){return this.getPrompt(Q).partial(Z?.partialVariables??{})}},v0=class extends r1{defaultPrompt;conditionals;constructor(Q,Z=[]){super();this.defaultPrompt=Q,this.conditionals=Z}getPrompt(Q){for(let[Z,J]of this.conditionals)if(Z(Q))return J;return this.defaultPrompt}};function x0(Q){return Q._modelType()==="base_llm"}function k0(Q){return Q._modelType()==="base_chat_model"}function b0(Q){return Q.split(/\n| /).length}var f0=class Q extends I8{examples=[];examplePrompt;getTextLength=b0;maxLength=2048;exampleTextLengths=[];constructor(Z){super(Z);this.examplePrompt=Z.examplePrompt,this.maxLength=Z.maxLength??2048,this.getTextLength=Z.getTextLength??b0}async addExample(Z){this.examples.push(Z);let J=await this.examplePrompt.format(Z);this.exampleTextLengths.push(this.getTextLength(J))}async calculateExampleTextLengths(Z,J){if(Z.length>0)return Z;let{examples:Y,examplePrompt:G}=J;return(await Promise.all(Y.map((H)=>G.format(H)))).map((H)=>this.getTextLength(H))}async selectExamples(Z){let J=Object.values(Z).join(" "),Y=this.maxLength-this.getTextLength(J),G=0,H=[];while(Y>0&&G<this.examples.length){let X=Y-this.exampleTextLengths[G];if(X<0)break;else H.push(this.examples[G]),Y=X;G+=1}return H}static async fromExamples(Z,J){let Y=new Q(J);return await Promise.all(Z.map((G)=>Y.addExample(G))),Y}};function t1(Q){return Object.keys(Q).sort().map((Z)=>Q[Z])}var h0=class Q extends I8{vectorStoreRetriever;exampleKeys;inputKeys;constructor(Z){super(Z);if(this.exampleKeys=Z.exampleKeys,this.inputKeys=Z.inputKeys,Z.vectorStore!==void 0)this.vectorStoreRetriever=Z.vectorStore.asRetriever({k:Z.k??4,filter:Z.filter});else if(Z.vectorStoreRetriever)this.vectorStoreRetriever=Z.vectorStoreRetriever;else throw Error('You must specify one of "vectorStore" and "vectorStoreRetriever".')}async addExample(Z){let J=t1((this.inputKeys??Object.keys(Z)).reduce((Y,G)=>({...Y,[G]:Z[G]}),{})).join(" ");await this.vectorStoreRetriever.addDocuments([new p({pageContent:J,metadata:Z})])}async selectExamples(Z){let J=t1((this.inputKeys??Object.keys(Z)).reduce((G,H)=>({...G,[H]:Z[H]}),{})).join(" "),Y=(await this.vectorStoreRetriever.invoke(J)).map((G)=>G.metadata);if(this.exampleKeys)return Y.map((G)=>this.exampleKeys.reduce((H,X)=>({...H,[X]:G[X]}),{}));return Y}static async fromExamples(Z,J,Y,G={}){let H=G.inputKeys??null,X=Z.map(($)=>t1(H?H.reduce((U,w)=>({...U,[w]:$[w]}),{}):$).join(" "));return new Q({vectorStore:await Y.fromTexts(X,Z,J,G),k:G.k??4,exampleKeys:G.exampleKeys,inputKeys:G.inputKeys})}};var g0=F({BaseExampleSelector:()=>I8,BasePromptSelector:()=>r1,ConditionalPromptSelector:()=>v0,LengthBasedExampleSelector:()=>f0,SemanticSimilarityExampleSelector:()=>h0,isChatModel:()=>k0,isLLM:()=>x0});var u8="10f90ea3-90a4-4962-bf75-83a0f3c1c62a",d0=class extends s{lc_namespace=["langchain","recordmanagers"]};var a1=class{uid;hash_;contentHash;metadataHash;pageContent;metadata;keyEncoder=m0;constructor(Q){this.uid=Q.uid,this.pageContent=Q.pageContent,this.metadata=Q.metadata}makeDefaultKeyEncoder(Q){this.keyEncoder=Q}calculateHashes(){let Q=["hash_","content_hash","metadata_hash"];for(let J of Q)if(J in this.metadata)throw Error(`Metadata cannot contain key ${J} as it is reserved for internal use. Restricted keys: [${Q.join(", ")}]`);let Z=this._hashStringToUUID(this.pageContent);try{let J=this._hashNestedDictToUUID(this.metadata);this.contentHash=Z,this.metadataHash=J}catch(J){throw Error(`Failed to hash metadata: ${J}. Please use a dict that can be serialized using json.`)}if(this.hash_=this._hashStringToUUID(this.contentHash+this.metadataHash),!this.uid)this.uid=this.hash_}toDocument(){return new p({pageContent:this.pageContent,metadata:this.metadata})}static fromDocument(Q,Z){let J=new this({pageContent:Q.pageContent,metadata:Q.metadata,uid:Z||Q.uid});return J.calculateHashes(),J}_hashStringToUUID(Q){return c8(this.keyEncoder(Q),u8)}_hashNestedDictToUUID(Q){let Z=JSON.stringify(Q,Object.keys(Q).sort());return c8(this.keyEncoder(Z),u8)}};function e1(Q,Z){let J=[],Y=[];if(Z.forEach((G)=>{if(Y.push(G),Y.length>=Q)J.push(Y),Y=[]}),Y.length>0)J.push(Y);return J}function Q9(Q){let Z=new Set,J=[];for(let Y of Q){if(!Y.hash_)throw Error("Hashed document does not have a hash");if(!Z.has(Y.hash_))Z.add(Y.hash_),J.push(Y)}return J}function Z9(Q){if(Q===null)return(Z)=>null;else if(typeof Q==="string")return(Z)=>Z.metadata[Q];else if(typeof Q==="function")return Q;else throw Error(`sourceIdKey should be null, a string or a function, got ${typeof Q}`)}var J9=(Q)=>{if("load"in Q&&typeof Q.load==="function"&&"loadAndSplit"in Q&&typeof Q.loadAndSplit==="function")return!0;return!1};async function c0(Q){let{docsSource:Z,recordManager:J,vectorStore:Y,options:G}=Q,{batchSize:H=100,cleanup:X,sourceIdKey:$,cleanupBatchSize:U=1000,forceUpdate:w=!1}=G??{};if(X==="incremental"&&!$)throw Error("sourceIdKey is required when cleanup mode is incremental. Please provide through 'options.sourceIdKey'.");let D=J9(Z)?await Z.load():Z,L=Z9($??null),A=await J.getTime(),E=0,B=0,R=0,P=0,V=e1(H??100,D);for(let I of V){let O=Q9(I.map((S)=>a1.fromDocument(S))),j=O.map((S)=>L(S));if(X==="incremental")O.forEach((S,M)=>{if(j[M]===null)throw Error("sourceIdKey must be provided when cleanup is incremental")});let d=await J.exists(O.map((S)=>S.uid)),x=[],k=[],K=[],R8=new Set;if(O.forEach((S,M)=>{if(d[M])if(w)R8.add(S.uid);else{K.push(S.uid);return}x.push(S.uid),k.push(S.toDocument())}),K.length>0)await J.update(K,{timeAtLeast:A}),P+=K.length;if(k.length>0)await Y.addDocuments(k,{ids:x}),E+=k.length-R8.size,R+=R8.size;if(await J.update(O.map((S)=>S.uid),{timeAtLeast:A,groupIds:j}),X==="incremental"){j.forEach((M)=>{if(!M)throw Error("Source id cannot be null")});let S=await J.listKeys({before:A,groupIds:j});if(S.length>0)await Y.delete({ids:S}),await J.deleteKeys(S),B+=S.length}}if(X==="full"){let I=await J.listKeys({before:A,limit:U});while(I.length>0)await Y.delete({ids:I}),await J.deleteKeys(I),B+=I.length,I=await J.listKeys({before:A,limit:U})}return{numAdded:E,numDeleted:B,numUpdated:R,numSkipped:P}}var u0=F({RecordManager:()=>d0,UUIDV5_NAMESPACE:()=>u8,_HashedDocument:()=>a1,_batch:()=>e1,_deduplicateInOrder:()=>Q9,_getSourceIdAssigner:()=>Z9,_isBaseDocumentLoader:()=>J9,index:()=>c0});var A8=class extends y{static lc_name(){return"RunnablePassthrough"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;func;constructor(Q){super(Q);if(Q)this.func=Q.func}async invoke(Q,Z){let J=J8(Z);if(this.func)await this.func(Q,J);return this._callWithConfig((Y)=>Promise.resolve(Y),Q,J)}async*transform(Q,Z){let J=J8(Z),Y,G=!0;for await(let H of this._transformStreamWithConfig(Q,(X)=>X,J))if(yield H,G)if(Y===void 0)Y=H;else try{Y=Y8(Y,H)}catch{Y=void 0,G=!1}if(this.func&&Y!==void 0)await this.func(Y,J)}static assign(Q){return new $1(new z1({steps:Q}))}};var l0=(Q)=>Q();function K1(Q){return new Q.constructor({...Q,content:Q.contentBlocks,response_metadata:{...Q.response_metadata,output_version:"v1"}})}var n0=F({BaseChatModel:()=>_8,SimpleChatModel:()=>o6});function Y9(Q){let Z=[];for(let J of Q){let Y=J;if(Array.isArray(J.content))for(let G=0;G<J.content.length;G++){let H=J.content[G];if(p0(H)||o0(H)){if(Y===J)Y=new J.constructor({...Y,content:[...J.content.slice(0,G),i0(H),...J.content.slice(G+1)]})}}Z.push(Y)}return Z}var _8=class Q extends N1{lc_namespace=["langchain","chat_models",this._llmType()];disableStreaming=!1;outputVersion;get callKeys(){return[...super.callKeys,"outputVersion"]}constructor(Z){super(Z);this.outputVersion=l0(()=>{let J=Z.outputVersion??U1("LC_OUTPUT_VERSION");if(J&&["v0","v1"].includes(J))return J;return"v0"})}_separateRunnableConfigFromCallOptionsCompat(Z){let[J,Y]=super._separateRunnableConfigFromCallOptions(Z);return Y.signal=J.signal,[J,Y]}async invoke(Z,J){let Y=Q._convertInputToPromptValue(Z);return(await this.generatePrompt([Y],J,J?.callbacks)).generations[0][0].message}async*_streamResponseChunks(Z,J,Y){throw Error("Not implemented.")}async*_streamIterator(Z,J){if(this._streamResponseChunks===Q.prototype._streamResponseChunks||this.disableStreaming)yield this.invoke(Z,J);else{let Y=Q._convertInputToPromptValue(Z).toChatMessages(),[G,H]=this._separateRunnableConfigFromCallOptionsCompat(J),X={...G.metadata,...this.getLsParams(H)},$=await e.configure(G.callbacks,this.callbacks,G.tags,this.tags,X,this.metadata,{verbose:this.verbose}),U={options:H,invocation_params:this?.invocationParams(H),batch_size:1},w=H.outputVersion??this.outputVersion,D=await $?.handleChatModelStart(this.toJSON(),[Y9(Y)],G.runId,void 0,U,void 0,void 0,G.runName),L,A;try{for await(let E of this._streamResponseChunks(Y,H,D?.[0])){if(H.signal?.throwIfAborted(),E.message.id==null){let B=D?.at(0)?.runId;if(B!=null)E.message._updateId(`run-${B}`)}if(E.message.response_metadata={...E.generationInfo,...E.message.response_metadata},w==="v1")yield K1(E.message);else yield E.message;if(!L)L=E;else L=L.concat(E);if(H9(E.message)&&E.message.usage_metadata!==void 0)A={tokenUsage:{promptTokens:E.message.usage_metadata.input_tokens,completionTokens:E.message.usage_metadata.output_tokens,totalTokens:E.message.usage_metadata.total_tokens}}}H.signal?.throwIfAborted()}catch(E){throw await Promise.all((D??[]).map((B)=>B?.handleLLMError(E))),E}await Promise.all((D??[]).map((E)=>E?.handleLLMEnd({generations:[[L]],llmOutput:A})))}}getLsParams(Z){let J=this.getName().startsWith("Chat")?this.getName().replace("Chat",""):this.getName();return{ls_model_type:"chat",ls_stop:Z.stop,ls_provider:J}}async _generateUncached(Z,J,Y,G){let H=Z.map((L)=>L.map(K8)),X;if(G!==void 0&&G.length===H.length)X=G;else{let L={...Y.metadata,...this.getLsParams(J)},A=await e.configure(Y.callbacks,this.callbacks,Y.tags,this.tags,L,this.metadata,{verbose:this.verbose}),E={options:J,invocation_params:this?.invocationParams(J),batch_size:1};X=await A?.handleChatModelStart(this.toJSON(),H.map(Y9),Y.runId,void 0,E,void 0,void 0,Y.runName)}let $=J.outputVersion??this.outputVersion,U=[],w=[];if(!!X?.[0].handlers.find(w1)&&!this.disableStreaming&&H.length===1&&this._streamResponseChunks!==Q.prototype._streamResponseChunks)try{let L=await this._streamResponseChunks(H[0],J,X?.[0]),A,E;for await(let B of L){if(J.signal?.aborted){let R=A?.message;throw new G9("Model invocation was aborted.",R)}if(B.message.id==null){let R=X?.at(0)?.runId;if(R!=null)B.message._updateId(`run-${R}`)}if(A===void 0)A=B;else A=Y8(A,B);if(H9(B.message)&&B.message.usage_metadata!==void 0)E={tokenUsage:{promptTokens:B.message.usage_metadata.input_tokens,completionTokens:B.message.usage_metadata.output_tokens,totalTokens:B.message.usage_metadata.total_tokens}}}if(J.signal?.aborted){let B=A?.message;throw new G9("Model invocation was aborted.",B)}if(A===void 0)throw Error("Received empty response from chat model call.");U.push([A]),await X?.[0].handleLLMEnd({generations:U,llmOutput:E})}catch(L){throw await X?.[0].handleLLMError(L),L}else{let L=await Promise.allSettled(H.map(async(A,E)=>{let B=await this._generate(A,{...J,promptIndex:E},X?.[E]);if($==="v1")for(let R of B.generations)R.message=K1(R.message);return B}));await Promise.all(L.map(async(A,E)=>{if(A.status==="fulfilled"){let B=A.value;for(let R of B.generations){if(R.message.id==null){let P=X?.at(0)?.runId;if(P!=null)R.message._updateId(`run-${P}`)}R.message.response_metadata={...R.generationInfo,...R.message.response_metadata}}if(B.generations.length===1)B.generations[0].message.response_metadata={...B.llmOutput,...B.generations[0].message.response_metadata};return U[E]=B.generations,w[E]=B.llmOutput,X?.[E]?.handleLLMEnd({generations:[B.generations],llmOutput:B.llmOutput})}else return await X?.[E]?.handleLLMError(A.reason),Promise.reject(A.reason)}))}let D={generations:U,llmOutput:w.length?this._combineLLMOutput?.(...w):void 0};return Object.defineProperty(D,V8,{value:X?{runIds:X?.map((L)=>L.runId)}:void 0,configurable:!0}),D}async _generateCached({messages:Z,cache:J,llmStringKey:Y,parsedOptions:G,handledOptions:H}){let X=Z.map((P)=>P.map(K8)),$={...H.metadata,...this.getLsParams(G)},U=await e.configure(H.callbacks,this.callbacks,H.tags,this.tags,$,this.metadata,{verbose:this.verbose}),w={options:G,invocation_params:this?.invocationParams(G),batch_size:1},D=await U?.handleChatModelStart(this.toJSON(),X.map(Y9),H.runId,void 0,w,void 0,void 0,H.runName),L=[],A=(await Promise.allSettled(X.map(async(P,V)=>{let I=Q._convertInputToPromptValue(P).toString(),O=await J.lookup(I,Y);if(O==null)L.push(V);return O}))).map((P,V)=>({result:P,runManager:D?.[V]})).filter(({result:P})=>P.status==="fulfilled"&&P.value!=null||P.status==="rejected"),E=G.outputVersion??this.outputVersion,B=[];await Promise.all(A.map(async({result:P,runManager:V},I)=>{if(P.status==="fulfilled"){let O=P.value;if(B[I]=O.map((j)=>{if("message"in j&&r(j.message)&&q1(j.message)){if(j.message.usage_metadata={input_tokens:0,output_tokens:0,total_tokens:0},E==="v1")j.message=K1(j.message)}return j.generationInfo={...j.generationInfo,tokenUsage:{}},j}),O.length)await V?.handleLLMNewToken(O[0].text);return V?.handleLLMEnd({generations:[O]},void 0,void 0,void 0,{cached:!0})}else return await V?.handleLLMError(P.reason,void 0,void 0,void 0,{cached:!0}),Promise.reject(P.reason)}));let R={generations:B,missingPromptIndices:L,startedRunManagers:D};return Object.defineProperty(R,V8,{value:D?{runIds:D?.map((P)=>P.runId)}:void 0,configurable:!0}),R}async generate(Z,J,Y){let G;if(Array.isArray(J))G={stop:J};else G=J;let H=Z.map((B)=>B.map(K8)),[X,$]=this._separateRunnableConfigFromCallOptionsCompat(G);if(X.callbacks=X.callbacks??Y,!this.cache)return this._generateUncached(H,$,X);let{cache:U}=this,w=this._getSerializedCacheKeyParametersForCall($),{generations:D,missingPromptIndices:L,startedRunManagers:A}=await this._generateCached({messages:H,cache:U,llmStringKey:w,parsedOptions:$,handledOptions:X}),E={};if(L.length>0){let B=await this._generateUncached(L.map((R)=>H[R]),$,X,A!==void 0?L.map((R)=>A?.[R]):void 0);await Promise.all(B.generations.map(async(R,P)=>{let V=L[P];D[V]=R;let I=Q._convertInputToPromptValue(H[V]).toString();return U.update(I,w,R)})),E=B.llmOutput??{}}return{generations:D,llmOutput:E}}invocationParams(Z){return{}}_modelType(){return"base_chat_model"}async generatePrompt(Z,J,Y){let G=Z.map((H)=>H.toChatMessages());return this.generate(G,J,Y)}withStructuredOutput(Z,J){if(typeof this.bindTools!=="function")throw Error('Chat model must implement ".bindTools()" to use withStructuredOutput.');if(J?.strict)throw Error('"strict" mode is not supported for this model by default.');let Y=Z,G=J?.name,H=G1(Y)??"A function available to call.",X=J?.method,$=J?.includeRaw;if(X==="jsonMode")throw Error('Base withStructuredOutput implementation only supports "functionCalling" as a method.');let U=G??"extract",w;if(Z1(Y))w=[{type:"function",function:{name:U,description:H,parameters:h(Y)}}];else{if("name"in Y)U=Y.name;w=[{type:"function",function:{name:U,description:H,parameters:Y}}]}let D=this.bindTools(w),L=q8.from((R)=>{if(!O8.isInstance(R))throw Error("Input is not an AIMessageChunk.");if(!R.tool_calls||R.tool_calls.length===0)throw Error("No tool calls found in the response.");let P=R.tool_calls.find((V)=>V.name===U);if(!P)throw Error(`No tool call found with name ${U}.`);return P.args});if(!$)return D.pipe(L).withConfig({runName:"StructuredOutput"});let A=A8.assign({parsed:(R,P)=>L.invoke(R.raw,P)}),E=A8.assign({parsed:()=>null}),B=A.withFallbacks({fallbacks:[E]});return D1.from([{raw:D},B]).withConfig({runName:"StructuredOutputRunnable"})}},o6=class extends _8{async _generate(Q,Z,J){let Y=new f(await this._call(Q,Z,J));if(typeof Y.content!=="string")throw Error("Cannot generate with a simple chat model when output is not a string.");return{generations:[{text:Y.content,message:Y}]}}};var s0=F({BaseLLM:()=>r0,LLM:()=>A1}),r0=class Q extends N1{lc_namespace=["langchain","llms",this._llmType()];async invoke(Z,J){let Y=Q._convertInputToPromptValue(Z);return(await this.generatePrompt([Y],J,J?.callbacks)).generations[0][0].text}async*_streamResponseChunks(Z,J,Y){throw Error("Not implemented.")}_separateRunnableConfigFromCallOptionsCompat(Z){let[J,Y]=super._separateRunnableConfigFromCallOptions(Z);return Y.signal=J.signal,[J,Y]}async*_streamIterator(Z,J){if(this._streamResponseChunks===Q.prototype._streamResponseChunks)yield this.invoke(Z,J);else{let Y=Q._convertInputToPromptValue(Z),[G,H]=this._separateRunnableConfigFromCallOptionsCompat(J),X=await e.configure(G.callbacks,this.callbacks,G.tags,this.tags,G.metadata,this.metadata,{verbose:this.verbose}),$={options:H,invocation_params:this?.invocationParams(H),batch_size:1},U=await X?.handleLLMStart(this.toJSON(),[Y.toString()],G.runId,void 0,$,void 0,void 0,G.runName),w=new B1({text:""});try{for await(let D of this._streamResponseChunks(Y.toString(),H,U?.[0])){if(!w)w=D;else w=w.concat(D);if(typeof D.text==="string")yield D.text}}catch(D){throw await Promise.all((U??[]).map((L)=>L?.handleLLMError(D))),D}await Promise.all((U??[]).map((D)=>D?.handleLLMEnd({generations:[[w]]})))}}async generatePrompt(Z,J,Y){let G=Z.map((H)=>H.toString());return this.generate(G,J,Y)}invocationParams(Z){return{}}_flattenLLMResult(Z){let J=[];for(let Y=0;Y<Z.generations.length;Y+=1){let G=Z.generations[Y];if(Y===0)J.push({generations:[G],llmOutput:Z.llmOutput});else{let H=Z.llmOutput?{...Z.llmOutput,tokenUsage:{}}:void 0;J.push({generations:[G],llmOutput:H})}}return J}async _generateUncached(Z,J,Y,G){let H;if(G!==void 0&&G.length===Z.length)H=G;else{let w=await e.configure(Y.callbacks,this.callbacks,Y.tags,this.tags,Y.metadata,this.metadata,{verbose:this.verbose}),D={options:J,invocation_params:this?.invocationParams(J),batch_size:Z.length};H=await w?.handleLLMStart(this.toJSON(),Z,Y.runId,void 0,D,void 0,void 0,Y?.runName)}let X=!!H?.[0].handlers.find(w1),$;if(X&&Z.length===1&&this._streamResponseChunks!==Q.prototype._streamResponseChunks)try{let w=await this._streamResponseChunks(Z[0],J,H?.[0]),D;for await(let L of w)if(D===void 0)D=L;else D=Y8(D,L);if(D===void 0)throw Error("Received empty response from chat model call.");$={generations:[[D]],llmOutput:{}},await H?.[0].handleLLMEnd($)}catch(w){throw await H?.[0].handleLLMError(w),w}else{try{$=await this._generate(Z,J,H?.[0])}catch(D){throw await Promise.all((H??[]).map((L)=>L?.handleLLMError(D))),D}let w=this._flattenLLMResult($);await Promise.all((H??[]).map((D,L)=>D?.handleLLMEnd(w[L])))}let U=H?.map((w)=>w.runId)||void 0;return Object.defineProperty($,V8,{value:U?{runIds:U}:void 0,configurable:!0}),$}async _generateCached({prompts:Z,cache:J,llmStringKey:Y,parsedOptions:G,handledOptions:H,runId:X}){let $=await e.configure(H.callbacks,this.callbacks,H.tags,this.tags,H.metadata,this.metadata,{verbose:this.verbose}),U={options:G,invocation_params:this?.invocationParams(G),batch_size:Z.length},w=await $?.handleLLMStart(this.toJSON(),Z,X,void 0,U,void 0,void 0,H?.runName),D=[],L=(await Promise.allSettled(Z.map(async(B,R)=>{let P=await J.lookup(B,Y);if(P==null)D.push(R);return P}))).map((B,R)=>({result:B,runManager:w?.[R]})).filter(({result:B})=>B.status==="fulfilled"&&B.value!=null||B.status==="rejected"),A=[];await Promise.all(L.map(async({result:B,runManager:R},P)=>{if(B.status==="fulfilled"){let V=B.value;if(A[P]=V.map((I)=>{return I.generationInfo={...I.generationInfo,tokenUsage:{}},I}),V.length)await R?.handleLLMNewToken(V[0].text);return R?.handleLLMEnd({generations:[V]},void 0,void 0,void 0,{cached:!0})}else return await R?.handleLLMError(B.reason,void 0,void 0,void 0,{cached:!0}),Promise.reject(B.reason)}));let E={generations:A,missingPromptIndices:D,startedRunManagers:w};return Object.defineProperty(E,V8,{value:w?{runIds:w?.map((B)=>B.runId)}:void 0,configurable:!0}),E}async generate(Z,J,Y){if(!Array.isArray(Z))throw Error("Argument 'prompts' is expected to be a string[]");let G;if(Array.isArray(J))G={stop:J};else G=J;let[H,X]=this._separateRunnableConfigFromCallOptionsCompat(G);if(H.callbacks=H.callbacks??Y,!this.cache)return this._generateUncached(Z,X,H);let{cache:$}=this,U=this._getSerializedCacheKeyParametersForCall(X),{generations:w,missingPromptIndices:D,startedRunManagers:L}=await this._generateCached({prompts:Z,cache:$,llmStringKey:U,parsedOptions:X,handledOptions:H,runId:H.runId}),A={};if(D.length>0){let E=await this._generateUncached(D.map((B)=>Z[B]),X,H,L!==void 0?D.map((B)=>L?.[B]):void 0);await Promise.all(E.generations.map(async(B,R)=>{let P=D[R];return w[P]=B,$.update(Z[P],U,B)})),A=E.llmOutput??{}}return{generations:w,llmOutput:A}}_identifyingParams(){return{}}_modelType(){return"base_llm"}},A1=class extends r0{async _generate(Q,Z,J){return{generations:await Promise.all(Q.map((Y,G)=>this._call(Y,{...Z,promptIndex:G},J).then((H)=>[{text:H}])))}}};var t0=F({});var a0=F({BaseMemory:()=>i6,getInputValue:()=>n6,getOutputValue:()=>s6,getPromptInputKey:()=>r6}),i6=class{},e0=(Q,Z)=>{if(Z!==void 0)return Q[Z];let J=Object.keys(Q);if(J.length===1)return Q[J[0]]},n6=(Q,Z)=>{let J=e0(Q,Z);if(!J){let Y=Object.keys(Q);throw Error(`input values have ${Y.length} keys, you must specify an input key or pass only 1 key as input`)}return J},s6=(Q,Z)=>{let J=e0(Q,Z);if(!J&&J!==""){let Y=Object.keys(Q);throw Error(`output values have ${Y.length} keys, you must specify an output key or pass only 1 key as output`)}return J};function r6(Q,Z){let J=Object.keys(Q).filter((Y)=>!Z.includes(Y)&&Y!=="stop");if(J.length!==1)throw Error(`One input key expected, but got ${J.length}`);return J[0]}var Q4=class extends y{static lc_name(){return"RouterRunnable"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;runnables;constructor(Q){super(Q);this.runnables=Q.runnables}async invoke(Q,Z){let{key:J,input:Y}=Q,G=this.runnables[J];if(G===void 0)throw Error(`No runnable associated with key "${J}".`);return G.invoke(Y,J8(Z))}async batch(Q,Z,J){let Y=Q.map((D)=>D.key),G=Q.map((D)=>D.input);if(Y.find((D)=>this.runnables[D]===void 0)!==void 0)throw Error("One or more keys do not have a corresponding runnable.");let H=Y.map((D)=>this.runnables[D]),X=this._getOptionsList(Z??{},Q.length),$=X[0]?.maxConcurrency??J?.maxConcurrency,U=$&&$>0?$:Q.length,w=[];for(let D=0;D<G.length;D+=U){let L=G.slice(D,D+U).map((E,B)=>H[B].invoke(E,X[B])),A=await Promise.all(L);w.push(A)}return w.flat()}async stream(Q,Z){let{key:J,input:Y}=Q,G=this.runnables[J];if(G===void 0)throw Error(`No runnable associated with key "${J}".`);return G.stream(Y,Z)}};var J4=class extends y{static lc_name(){return"RunnableBranch"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;default;branches;constructor(Q){super(Q);this.branches=Q.branches,this.default=Q.default}static from(Q){if(Q.length<1)throw Error("RunnableBranch requires at least one branch");let Z=Q.slice(0,-1).map(([Y,G])=>[T8(Y),T8(G)]),J=T8(Q[Q.length-1]);return new this({branches:Z,default:J})}async _invoke(Q,Z,J){let Y;for(let G=0;G<this.branches.length;G+=1){let[H,X]=this.branches[G];if(await H.invoke(Q,G8(Z,{callbacks:J?.getChild(`condition:${G+1}`)}))){Y=await X.invoke(Q,G8(Z,{callbacks:J?.getChild(`branch:${G+1}`)}));break}}if(!Y)Y=await this.default.invoke(Q,G8(Z,{callbacks:J?.getChild("branch:default")}));return Y}async invoke(Q,Z={}){return this._callWithConfig(this._invoke,Q,Z)}async*_streamIterator(Q,Z){let J=await(await E1(Z))?.handleChainStart(this.toJSON(),Z4(Q,"input"),Z?.runId,void 0,void 0,void 0,Z?.runName),Y,G=!0,H;try{for(let X=0;X<this.branches.length;X+=1){let[$,U]=this.branches[X];if(await $.invoke(Q,G8(Z,{callbacks:J?.getChild(`condition:${X+1}`)}))){H=await U.stream(Q,G8(Z,{callbacks:J?.getChild(`branch:${X+1}`)}));for await(let w of H)if(yield w,G)if(Y===void 0)Y=w;else try{Y=Y8(Y,w)}catch{Y=void 0,G=!1}break}}if(H===void 0){H=await this.default.stream(Q,G8(Z,{callbacks:J?.getChild("branch:default")}));for await(let X of H)if(yield X,G)if(Y===void 0)Y=X;else try{Y=Y8(Y,X)}catch{Y=void 0,G=!1}}}catch(X){throw await J?.handleChainError(X),X}await J?.handleChainEnd(Y??{})}};var Y4=class extends j8{runnable;inputMessagesKey;outputMessagesKey;historyMessagesKey;getMessageHistory;constructor(Q){let Z=q8.from((H,X)=>this._enterHistory(H,X??{})).withConfig({runName:"loadHistory"}),J=Q.historyMessagesKey??Q.inputMessagesKey;if(J)Z=A8.assign({[J]:Z}).withConfig({runName:"insertHistory"});let Y=Z.pipe(Q.runnable.withListeners({onEnd:(H,X)=>this._exitHistory(H,X??{})})).withConfig({runName:"RunnableWithMessageHistory"}),G=Q.config??{};super({...Q,config:G,bound:Y});this.runnable=Q.runnable,this.getMessageHistory=Q.getMessageHistory,this.inputMessagesKey=Q.inputMessagesKey,this.outputMessagesKey=Q.outputMessagesKey,this.historyMessagesKey=Q.historyMessagesKey}_getInputMessages(Q){let Z;if(typeof Q==="object"&&!Array.isArray(Q)&&!r(Q)){let J;if(this.inputMessagesKey)J=this.inputMessagesKey;else if(Object.keys(Q).length===1)J=Object.keys(Q)[0];else J="input";if(Array.isArray(Q[J])&&Array.isArray(Q[J][0]))Z=Q[J][0];else Z=Q[J]}else Z=Q;if(typeof Z==="string")return[new $8(Z)];else if(Array.isArray(Z))return Z;else if(r(Z))return[Z];else throw Error(`Expected a string, BaseMessage, or array of BaseMessages.
|
|
2
|
+
Got ${JSON.stringify(Z,null,2)}`)}_getOutputMessages(Q){let Z;if(!Array.isArray(Q)&&!r(Q)&&typeof Q!=="string"){let J;if(this.outputMessagesKey!==void 0)J=this.outputMessagesKey;else if(Object.keys(Q).length===1)J=Object.keys(Q)[0];else J="output";if(Q.generations!==void 0)Z=Q.generations[0][0].message;else Z=Q[J]}else Z=Q;if(typeof Z==="string")return[new f(Z)];else if(Array.isArray(Z))return Z;else if(r(Z))return[Z];else throw Error(`Expected a string, BaseMessage, or array of BaseMessages. Received: ${JSON.stringify(Z,null,2)}`)}async _enterHistory(Q,Z){let J=await(Z?.configurable?.messageHistory).getMessages();if(this.historyMessagesKey===void 0)return J.concat(this._getInputMessages(Q));return J}async _exitHistory(Q,Z){let J=Z.configurable?.messageHistory,Y;if(Array.isArray(Q.inputs)&&Array.isArray(Q.inputs[0]))Y=Q.inputs[0];else Y=Q.inputs;let G=this._getInputMessages(Y);if(this.historyMessagesKey===void 0){let $=await J.getMessages();G=G.slice($.length)}let H=Q.outputs;if(!H)throw Error(`Output values from 'Run' undefined. Run: ${JSON.stringify(Q,null,2)}`);let X=this._getOutputMessages(H);await J.addMessages([...G,...X])}async _mergeConfig(...Q){let Z=await super._mergeConfig(...Q);if(!Z.configurable||!Z.configurable.sessionId){let Y={[this.inputMessagesKey??"input"]:"foo"};throw Error(`sessionId is required. Pass it in as part of the config argument to .invoke() or .stream()
|
|
3
|
+
eg. chain.invoke(${JSON.stringify(Y)}, ${JSON.stringify({configurable:{sessionId:"123"}})})`)}let{sessionId:J}=Z.configurable;return Z.configurable.messageHistory=await this.getMessageHistory(J),Z}};var w4=F({RouterRunnable:()=>Q4,Runnable:()=>y,RunnableAssign:()=>$1,RunnableBinding:()=>j8,RunnableBranch:()=>J4,RunnableEach:()=>X4,RunnableLambda:()=>q8,RunnableMap:()=>z1,RunnableParallel:()=>$4,RunnablePassthrough:()=>A8,RunnablePick:()=>q4,RunnableRetry:()=>z4,RunnableSequence:()=>D1,RunnableToolLike:()=>U4,RunnableWithFallbacks:()=>K4,RunnableWithMessageHistory:()=>Y4,_coerceToRunnable:()=>T8,ensureConfig:()=>J8,getCallbackManagerForConfig:()=>E1,mergeConfigs:()=>G4,patchConfig:()=>G8,pickRunnableConfigKeys:()=>H4,raceWithSignal:()=>W4});var N4=F({applyPatch:()=>D4,compare:()=>U8});var M8=class extends y{parseResultWithPrompt(Q,Z,J){return this.parseResult(Q,J)}_baseMessageToString(Q){return typeof Q.content==="string"?Q.content:this._baseMessageContentToString(Q.content)}_baseMessageContentToString(Q){return JSON.stringify(Q)}async invoke(Q,Z){if(typeof Q==="string")return this._callWithConfig(async(J,Y)=>this.parseResult([{text:J}],Y?.callbacks),Q,{...Z,runType:"parser"});else return this._callWithConfig(async(J,Y)=>this.parseResult([{message:J,text:this._baseMessageToString(J)}],Y?.callbacks),Q,{...Z,runType:"parser"})}},H8=class extends M8{parseResult(Q,Z){return this.parse(Q[0].text,Z)}async parseWithPrompt(Q,Z,J){return this.parse(Q,J)}_type(){throw Error("_type not implemented")}},o=class extends Error{llmOutput;observation;sendToLLM;constructor(Q,Z,J,Y=!1){super(Q);if(this.llmOutput=Z,this.observation=J,this.sendToLLM=Y,Y){if(J===void 0||Z===void 0)throw Error("Arguments 'observation' & 'llmOutput' are required if 'sendToLlm' is true")}C8(this,"OUTPUT_PARSING_FAILURE")}};var W8=class extends H8{async*_transform(Q){for await(let Z of Q)if(typeof Z==="string")yield this.parseResult([{text:Z}]);else yield this.parseResult([{message:Z,text:this._baseMessageToString(Z)}])}async*transform(Q,Z){yield*this._transformStreamWithConfig(Q,this._transform.bind(this),{...Z,runType:"parser"})}},Q8=class extends W8{diff=!1;constructor(Q){super(Q);this.diff=Q?.diff??this.diff}async*_transform(Q){let Z,J;for await(let Y of Q){if(typeof Y!=="string"&&typeof Y.content!=="string")throw Error("Cannot handle non-string output.");let G;if(B4(Y)){if(typeof Y.content!=="string")throw Error("Cannot handle non-string message output.");G=new E8({message:Y,text:Y.content})}else if(r(Y)){if(typeof Y.content!=="string")throw Error("Cannot handle non-string message output.");G=new E8({message:A4(Y),text:Y.content})}else G=new B1({text:Y});if(J===void 0)J=G;else J=J.concat(G);let H=await this.parsePartialResult([J]);if(H!==void 0&&H!==null&&!E4(H,Z)){if(this.diff)yield this._diff(Z,H);else yield H;Z=H}}}getFormatInstructions(){return""}};var F4=class extends W8{static lc_name(){return"BytesOutputParser"}lc_namespace=["langchain_core","output_parsers","bytes"];lc_serializable=!0;textEncoder=new TextEncoder;parse(Q){return Promise.resolve(this.textEncoder.encode(Q))}getFormatInstructions(){return""}};var S8=class extends W8{re;async*_transform(Q){let Z="";for await(let J of Q){if(typeof J==="string")Z+=J;else Z+=J.content;if(!this.re){let Y=await this.parse(Z);if(Y.length>1){for(let G of Y.slice(0,-1))yield[G];Z=Y[Y.length-1]}}else{let Y=[...Z.matchAll(this.re)];if(Y.length>1){let G=0;for(let H of Y.slice(0,-1))yield[H[1]],G+=(H.index??0)+H[0].length;Z=Z.slice(G)}}}for(let J of await this.parse(Z))yield[J]}},L4=class extends S8{static lc_name(){return"CommaSeparatedListOutputParser"}lc_namespace=["langchain_core","output_parsers","list"];lc_serializable=!0;async parse(Q){try{return Q.trim().split(",").map((Z)=>Z.trim())}catch{throw new o(`Could not parse output: ${Q}`,Q)}}getFormatInstructions(){return"Your response should be a list of comma separated values, eg: `foo, bar, baz`"}},R4=class extends S8{lc_namespace=["langchain_core","output_parsers","list"];length;separator;constructor({length:Q,separator:Z}){super(...arguments);this.length=Q,this.separator=Z||","}async parse(Q){try{let Z=Q.trim().split(this.separator).map((J)=>J.trim());if(this.length!==void 0&&Z.length!==this.length)throw new o(`Incorrect number of items. Expected ${this.length}, got ${Z.length}.`);return Z}catch(Z){if(Object.getPrototypeOf(Z)===o.prototype)throw Z;throw new o(`Could not parse output: ${Q}`)}}getFormatInstructions(){return`Your response should be a list of ${this.length===void 0?"":`${this.length} `}items separated by "${this.separator}" (eg: \`foo${this.separator} bar${this.separator} baz\`)`}},P4=class extends S8{static lc_name(){return"NumberedListOutputParser"}lc_namespace=["langchain_core","output_parsers","list"];lc_serializable=!0;getFormatInstructions(){return`Your response should be a numbered list with each item on a new line. For example:
|
|
4
|
+
|
|
5
|
+
1. foo
|
|
6
|
+
|
|
7
|
+
2. bar
|
|
8
|
+
|
|
9
|
+
3. baz`}re=/\d+\.\s([^\n]+)/g;async parse(Q){return[...Q.matchAll(this.re)??[]].map((Z)=>Z[1])}},I4=class extends S8{static lc_name(){return"NumberedListOutputParser"}lc_namespace=["langchain_core","output_parsers","list"];lc_serializable=!0;getFormatInstructions(){return`Your response should be a numbered list with each item on a new line. For example:
|
|
10
|
+
|
|
11
|
+
1. foo
|
|
12
|
+
|
|
13
|
+
2. bar
|
|
14
|
+
|
|
15
|
+
3. baz`}re=/^\s*[-*]\s([^\n]+)$/gm;async parse(Q){return[...Q.matchAll(this.re)??[]].map((Z)=>Z[1])}};var V4=class extends W8{static lc_name(){return"StrOutputParser"}lc_namespace=["langchain_core","output_parsers","string"];lc_serializable=!0;parse(Q){return Promise.resolve(Q)}getFormatInstructions(){return""}_textContentToString(Q){return Q.text}_imageUrlContentToString(Q){throw Error('Cannot coerce a multimodal "image_url" message part into a string.')}_messageContentToString(Q){switch(Q.type){case"text":case"text_delta":if("text"in Q)return this._textContentToString(Q);break;case"image_url":if("image_url"in Q)return this._imageUrlContentToString(Q);break;case"reasoning":case"thinking":case"redacted_thinking":return"";default:throw Error(`Cannot coerce "${Q.type}" message part into a string.`)}throw Error(`Invalid content type: ${Q.type}`)}_baseMessageContentToString(Q){return Q.reduce((Z,J)=>Z+this._messageContentToString(J),"")}};var W9=class extends H8{static lc_name(){return"StructuredOutputParser"}lc_namespace=["langchain","output_parsers","structured"];toJSON(){return this.toJSONNotImplemented()}constructor(Q){super(Q);this.schema=Q}static fromZodSchema(Q){return new this(Q)}static fromNamesAndDescriptions(Q){let Z=l8.object(Object.fromEntries(Object.entries(Q).map(([J,Y])=>[J,l8.string().describe(Y)])));return new this(Z)}getFormatInstructions(){return`You must format your output as a JSON value that adheres to a given "JSON Schema" instance.
|
|
16
|
+
|
|
17
|
+
"JSON Schema" is a declarative language that allows you to annotate and validate JSON documents.
|
|
18
|
+
|
|
19
|
+
For example, the example "JSON Schema" instance {{"properties": {{"foo": {{"description": "a list of test words", "type": "array", "items": {{"type": "string"}}}}}}, "required": ["foo"]}}
|
|
20
|
+
would match an object with one required property, "foo". The "type" property specifies "foo" must be an "array", and the "description" property semantically describes it as "a list of test words". The items within "foo" must be strings.
|
|
21
|
+
Thus, the object {{"foo": ["bar", "baz"]}} is a well-formatted instance of this example "JSON Schema". The object {{"properties": {{"foo": ["bar", "baz"]}}}} is not well-formatted.
|
|
22
|
+
|
|
23
|
+
Your output will be parsed and type-checked according to the provided schema instance, so make sure all fields in your output match the schema exactly and there are no trailing commas!
|
|
24
|
+
|
|
25
|
+
Here is the JSON Schema instance your output must adhere to. Include the enclosing markdown codeblock:
|
|
26
|
+
\`\`\`json
|
|
27
|
+
${JSON.stringify(h(this.schema))}
|
|
28
|
+
\`\`\`
|
|
29
|
+
`}async parse(Q){try{let Z=Q.trim(),J=(Z.match(/^```(?:json)?\s*([\s\S]*?)```/)?.[1]||Z.match(/```json\s*([\s\S]*?)```/)?.[1]||Z).replace(/"([^"\\]*(\\.[^"\\]*)*)"/g,(Y,G)=>{return`"${G.replace(/\n/g,"\\n")}"`}).replace(/\n/g,"");return await Y1(this.schema,JSON.parse(J))}catch(Z){throw new o(`Failed to parse. Text: "${Q}". Error: ${Z}`,Q)}}},X9=class extends W9{static lc_name(){return"JsonMarkdownStructuredOutputParser"}getFormatInstructions(Q){let Z=Q?.interpolationDepth??1;if(Z<1)throw Error("f string interpolation depth must be at least 1");return`Return a markdown code snippet with a JSON object formatted to look like:
|
|
30
|
+
\`\`\`json
|
|
31
|
+
${this._schemaToInstruction(h(this.schema)).replaceAll("{","{".repeat(Z)).replaceAll("}","}".repeat(Z))}
|
|
32
|
+
\`\`\``}_schemaToInstruction(Q,Z=2){let J=Q;if("type"in J){let Y=!1,G;if(Array.isArray(J.type)){let $=J.type.findIndex((U)=>U==="null");if($!==-1)Y=!0,J.type.splice($,1);G=J.type.join(" | ")}else G=J.type;if(J.type==="object"&&J.properties){let $=J.description?` // ${J.description}`:"";return`{
|
|
33
|
+
${Object.entries(J.properties).map(([U,w])=>{let D=J.required?.includes(U)?"":" (optional)";return`${" ".repeat(Z)}"${U}": ${this._schemaToInstruction(w,Z+2)}${D}`}).join(`
|
|
34
|
+
`)}
|
|
35
|
+
${" ".repeat(Z-2)}}${$}`}if(J.type==="array"&&J.items){let $=J.description?` // ${J.description}`:"";return`array[
|
|
36
|
+
${" ".repeat(Z)}${this._schemaToInstruction(J.items,Z+2)}
|
|
37
|
+
${" ".repeat(Z-2)}] ${$}`}let H=Y?" (nullable)":"",X=J.description?` // ${J.description}`:"";return`${G}${X}${H}`}if("anyOf"in J)return J.anyOf.map((Y)=>this._schemaToInstruction(Y,Z)).join(`
|
|
38
|
+
${" ".repeat(Z-2)}`);throw Error("unsupported schema type")}static fromZodSchema(Q){return new this(Q)}static fromNamesAndDescriptions(Q){let Z=l8.object(Object.fromEntries(Object.entries(Q).map(([J,Y])=>[J,l8.string().describe(Y)])));return new this(Z)}},O4=class extends H8{structuredInputParser;constructor({inputSchema:Q}){super(...arguments);this.structuredInputParser=new X9(Q)}async parse(Q){let Z;try{Z=await this.structuredInputParser.parse(Q)}catch(J){throw new o(`Failed to parse. Text: "${Q}". Error: ${J}`,Q)}return this.outputProcessor(Z)}getFormatInstructions(){return this.structuredInputParser.getFormatInstructions()}};var _4=class extends Q8{static lc_name(){return"JsonOutputParser"}lc_namespace=["langchain_core","output_parsers"];lc_serializable=!0;_concatOutputChunks(Q,Z){if(this.diff)return super._concatOutputChunks(Q,Z);return Z}_diff(Q,Z){if(!Z)return;if(!Q)return[{op:"replace",path:"",value:Z}];return U8(Q,Z)}async parsePartialResult(Q){return p8(Q[0].text)}async parse(Q){return p8(Q,JSON.parse)}getFormatInstructions(){return""}_baseMessageToString(Q){return Q.text}};var t6=function(){let Q={};Q.parser=function(z,W){return new J(z,W)},Q.SAXParser=J,Q.SAXStream=w,Q.createStream=U,Q.MAX_BUFFER_LENGTH=65536;let Z=["comment","sgmlDecl","textNode","tagName","doctype","procInstName","procInstBody","entity","attribName","attribValue","cdata","script"];Q.EVENTS=["text","processinginstruction","sgmldeclaration","doctype","comment","opentagstart","attribute","opentag","closetag","opencdata","cdata","closecdata","error","end","ready","script","opennamespace","closenamespace"];function J(z,W){if(!(this instanceof J))return new J(z,W);var N=this;if(G(N),N.q=N.c="",N.bufferCheckPosition=Q.MAX_BUFFER_LENGTH,N.opt=W||{},N.opt.lowercase=N.opt.lowercase||N.opt.lowercasetags,N.looseCase=N.opt.lowercase?"toLowerCase":"toUpperCase",N.tags=[],N.closed=N.closedRoot=N.sawRoot=!1,N.tag=N.error=null,N.strict=!!z,N.noscript=!!(z||N.opt.noscript),N.state=K.BEGIN,N.strictEntities=N.opt.strictEntities,N.ENTITIES=N.strictEntities?Object.create(Q.XML_ENTITIES):Object.create(Q.ENTITIES),N.attribList=[],N.opt.xmlns)N.ns=Object.create(B);if(N.trackPosition=N.opt.position!==!1,N.trackPosition)N.position=N.line=N.column=0;S(N,"onready")}if(!Object.create)Object.create=function(z){function W(){}return W.prototype=z,new W};if(!Object.keys)Object.keys=function(z){var W=[];for(var N in z)if(z.hasOwnProperty(N))W.push(N);return W};function Y(z){var W=Math.max(Q.MAX_BUFFER_LENGTH,10),N=0;for(var q=0,T=Z.length;q<T;q++){var v=z[Z[q]].length;if(v>W)switch(Z[q]){case"textNode":m8(z);break;case"cdata":M(z,"oncdata",z.cdata),z.cdata="";break;case"script":M(z,"onscript",z.script),z.script="";break;default:Q1(z,"Max buffer length exceeded: "+Z[q])}N=Math.max(N,v)}z.bufferCheckPosition=Q.MAX_BUFFER_LENGTH-N+z.position}function G(z){for(var W=0,N=Z.length;W<N;W++)z[Z[W]]=""}function H(z){if(m8(z),z.cdata!=="")M(z,"oncdata",z.cdata),z.cdata="";if(z.script!=="")M(z,"onscript",z.script),z.script=""}J.prototype={end:function(){d9(this)},write:f6,resume:function(){return this.error=null,this},close:function(){return this.write(null)},flush:function(){H(this)}};var X=ReadableStream;if(!X)X=function(){};var $=Q.EVENTS.filter(function(z){return z!=="error"&&z!=="end"});function U(z,W){return new w(z,W)}function w(z,W){if(!(this instanceof w))return new w(z,W);X.apply(this),this._parser=new J(z,W),this.writable=!0,this.readable=!0;var N=this;this._parser.onend=function(){N.emit("end")},this._parser.onerror=function(q){N.emit("error",q),N._parser.error=null},this._decoder=null,$.forEach(function(q){Object.defineProperty(N,"on"+q,{get:function(){return N._parser["on"+q]},set:function(T){if(!T)return N.removeAllListeners(q),N._parser["on"+q]=T,T;N.on(q,T)},enumerable:!0,configurable:!1})})}w.prototype=Object.create(X.prototype,{constructor:{value:w}}),w.prototype.write=function(z){return this._parser.write(z.toString()),this.emit("data",z),!0},w.prototype.end=function(z){if(z&&z.length)this.write(z);return this._parser.end(),!0},w.prototype.on=function(z,W){var N=this;if(!N._parser["on"+z]&&$.indexOf(z)!==-1)N._parser["on"+z]=function(){var q=arguments.length===1?[arguments[0]]:Array.apply(null,arguments);q.splice(0,0,z),N.emit.apply(N,q)};return X.prototype.on.call(N,z,W)};var D="[CDATA[",L="DOCTYPE",A="http://www.w3.org/XML/1998/namespace",E="http://www.w3.org/2000/xmlns/",B={xml:A,xmlns:E},R=/[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/,P=/[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/,V=/[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/,I=/[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/;function O(z){return z===" "||z===`
|
|
39
|
+
`||z==="\r"||z==="\t"}function j(z){return z==='"'||z==="'"}function d(z){return z===">"||O(z)}function x(z,W){return z.test(W)}function k(z,W){return!x(z,W)}var K=0;Q.STATE={BEGIN:K++,BEGIN_WHITESPACE:K++,TEXT:K++,TEXT_ENTITY:K++,OPEN_WAKA:K++,SGML_DECL:K++,SGML_DECL_QUOTED:K++,DOCTYPE:K++,DOCTYPE_QUOTED:K++,DOCTYPE_DTD:K++,DOCTYPE_DTD_QUOTED:K++,COMMENT_STARTING:K++,COMMENT:K++,COMMENT_ENDING:K++,COMMENT_ENDED:K++,CDATA:K++,CDATA_ENDING:K++,CDATA_ENDING_2:K++,PROC_INST:K++,PROC_INST_BODY:K++,PROC_INST_ENDING:K++,OPEN_TAG:K++,OPEN_TAG_SLASH:K++,ATTRIB:K++,ATTRIB_NAME:K++,ATTRIB_NAME_SAW_WHITE:K++,ATTRIB_VALUE:K++,ATTRIB_VALUE_QUOTED:K++,ATTRIB_VALUE_CLOSED:K++,ATTRIB_VALUE_UNQUOTED:K++,ATTRIB_VALUE_ENTITY_Q:K++,ATTRIB_VALUE_ENTITY_U:K++,CLOSE_TAG:K++,CLOSE_TAG_SAW_WHITE:K++,SCRIPT:K++,SCRIPT_ENDING:K++},Q.XML_ENTITIES={amp:"&",gt:">",lt:"<",quot:'"',apos:"'"},Q.ENTITIES={amp:"&",gt:">",lt:"<",quot:'"',apos:"'",AElig:198,Aacute:193,Acirc:194,Agrave:192,Aring:197,Atilde:195,Auml:196,Ccedil:199,ETH:208,Eacute:201,Ecirc:202,Egrave:200,Euml:203,Iacute:205,Icirc:206,Igrave:204,Iuml:207,Ntilde:209,Oacute:211,Ocirc:212,Ograve:210,Oslash:216,Otilde:213,Ouml:214,THORN:222,Uacute:218,Ucirc:219,Ugrave:217,Uuml:220,Yacute:221,aacute:225,acirc:226,aelig:230,agrave:224,aring:229,atilde:227,auml:228,ccedil:231,eacute:233,ecirc:234,egrave:232,eth:240,euml:235,iacute:237,icirc:238,igrave:236,iuml:239,ntilde:241,oacute:243,ocirc:244,ograve:242,oslash:248,otilde:245,ouml:246,szlig:223,thorn:254,uacute:250,ucirc:251,ugrave:249,uuml:252,yacute:253,yuml:255,copy:169,reg:174,nbsp:160,iexcl:161,cent:162,pound:163,curren:164,yen:165,brvbar:166,sect:167,uml:168,ordf:170,laquo:171,not:172,shy:173,macr:175,deg:176,plusmn:177,sup1:185,sup2:178,sup3:179,acute:180,micro:181,para:182,middot:183,cedil:184,ordm:186,raquo:187,frac14:188,frac12:189,frac34:190,iquest:191,times:215,divide:247,OElig:338,oelig:339,Scaron:352,scaron:353,Yuml:376,fnof:402,circ:710,tilde:732,Alpha:913,Beta:914,Gamma:915,Delta:916,Epsilon:917,Zeta:918,Eta:919,Theta:920,Iota:921,Kappa:922,Lambda:923,Mu:924,Nu:925,Xi:926,Omicron:927,Pi:928,Rho:929,Sigma:931,Tau:932,Upsilon:933,Phi:934,Chi:935,Psi:936,Omega:937,alpha:945,beta:946,gamma:947,delta:948,epsilon:949,zeta:950,eta:951,theta:952,iota:953,kappa:954,lambda:955,mu:956,nu:957,xi:958,omicron:959,pi:960,rho:961,sigmaf:962,sigma:963,tau:964,upsilon:965,phi:966,chi:967,psi:968,omega:969,thetasym:977,upsih:978,piv:982,ensp:8194,emsp:8195,thinsp:8201,zwnj:8204,zwj:8205,lrm:8206,rlm:8207,ndash:8211,mdash:8212,lsquo:8216,rsquo:8217,sbquo:8218,ldquo:8220,rdquo:8221,bdquo:8222,dagger:8224,Dagger:8225,bull:8226,hellip:8230,permil:8240,prime:8242,Prime:8243,lsaquo:8249,rsaquo:8250,oline:8254,frasl:8260,euro:8364,image:8465,weierp:8472,real:8476,trade:8482,alefsym:8501,larr:8592,uarr:8593,rarr:8594,darr:8595,harr:8596,crarr:8629,lArr:8656,uArr:8657,rArr:8658,dArr:8659,hArr:8660,forall:8704,part:8706,exist:8707,empty:8709,nabla:8711,isin:8712,notin:8713,ni:8715,prod:8719,sum:8721,minus:8722,lowast:8727,radic:8730,prop:8733,infin:8734,ang:8736,and:8743,or:8744,cap:8745,cup:8746,int:8747,there4:8756,sim:8764,cong:8773,asymp:8776,ne:8800,equiv:8801,le:8804,ge:8805,sub:8834,sup:8835,nsub:8836,sube:8838,supe:8839,oplus:8853,otimes:8855,perp:8869,sdot:8901,lceil:8968,rceil:8969,lfloor:8970,rfloor:8971,lang:9001,rang:9002,loz:9674,spades:9824,clubs:9827,hearts:9829,diams:9830},Object.keys(Q.ENTITIES).forEach(function(z){var W=Q.ENTITIES[z],N=typeof W==="number"?String.fromCharCode(W):W;Q.ENTITIES[z]=N});for(var R8 in Q.STATE)Q.STATE[Q.STATE[R8]]=R8;K=Q.STATE;function S(z,W,N){z[W]&&z[W](N)}function M(z,W,N){if(z.textNode)m8(z);S(z,W,N)}function m8(z){if(z.textNode=g9(z.opt,z.textNode),z.textNode)S(z,"ontext",z.textNode);z.textNode=""}function g9(z,W){if(z.trim)W=W.trim();if(z.normalize)W=W.replace(/\s+/g," ");return W}function Q1(z,W){if(m8(z),z.trackPosition)W+=`
|
|
40
|
+
Line: `+z.line+`
|
|
41
|
+
Column: `+z.column+`
|
|
42
|
+
Char: `+z.c;return W=Error(W),z.error=W,S(z,"onerror",W),z}function d9(z){if(z.sawRoot&&!z.closedRoot)C(z,"Unclosed root tag");if(z.state!==K.BEGIN&&z.state!==K.BEGIN_WHITESPACE&&z.state!==K.TEXT)Q1(z,"Unexpected end");return m8(z),z.c="",z.closed=!0,S(z,"onend"),J.call(z,z.strict,z.opt),z}function C(z,W){if(typeof z!=="object"||!(z instanceof J))throw Error("bad call to strictFail");if(z.strict)Q1(z,W)}function b6(z){if(!z.strict)z.tagName=z.tagName[z.looseCase]();var W=z.tags[z.tags.length-1]||z,N=z.tag={name:z.tagName,attributes:{}};if(z.opt.xmlns)N.ns=W.ns;z.attribList.length=0,M(z,"onopentagstart",N)}function b1(z,W){var N=z.indexOf(":")<0?["",z]:z.split(":"),q=N[0],T=N[1];if(W&&z==="xmlns")q="xmlns",T="";return{prefix:q,local:T}}function f1(z){if(!z.strict)z.attribName=z.attribName[z.looseCase]();if(z.attribList.indexOf(z.attribName)!==-1||z.tag.attributes.hasOwnProperty(z.attribName)){z.attribName=z.attribValue="";return}if(z.opt.xmlns){var W=b1(z.attribName,!0),N=W.prefix,q=W.local;if(N==="xmlns")if(q==="xml"&&z.attribValue!==A)C(z,"xml: prefix must be bound to "+A+`
|
|
43
|
+
Actual: `+z.attribValue);else if(q==="xmlns"&&z.attribValue!==E)C(z,"xmlns: prefix must be bound to "+E+`
|
|
44
|
+
Actual: `+z.attribValue);else{var T=z.tag,v=z.tags[z.tags.length-1]||z;if(T.ns===v.ns)T.ns=Object.create(v.ns);T.ns[q]=z.attribValue}z.attribList.push([z.attribName,z.attribValue])}else z.tag.attributes[z.attribName]=z.attribValue,M(z,"onattribute",{name:z.attribName,value:z.attribValue});z.attribName=z.attribValue=""}function D8(z,W){if(z.opt.xmlns){var N=z.tag,q=b1(z.tagName);if(N.prefix=q.prefix,N.local=q.local,N.uri=N.ns[q.prefix]||"",N.prefix&&!N.uri)C(z,"Unbound namespace prefix: "+JSON.stringify(z.tagName)),N.uri=q.prefix;var T=z.tags[z.tags.length-1]||z;if(N.ns&&T.ns!==N.ns)Object.keys(N.ns).forEach(function(p9){M(z,"onopennamespace",{prefix:p9,uri:N.ns[p9]})});for(var v=0,l=z.attribList.length;v<l;v++){var m=z.attribList[v],n=m[0],N8=m[1],b=b1(n,!0),B8=b.prefix,h6=b.local,l9=B8===""?"":N.ns[B8]||"",g1={name:n,value:N8,prefix:B8,local:h6,uri:l9};if(B8&&B8!=="xmlns"&&!l9)C(z,"Unbound namespace prefix: "+JSON.stringify(B8)),g1.uri=B8;z.tag.attributes[n]=g1,M(z,"onattribute",g1)}z.attribList.length=0}if(z.tag.isSelfClosing=!!W,z.sawRoot=!0,z.tags.push(z.tag),M(z,"onopentag",z.tag),!W){if(!z.noscript&&z.tagName.toLowerCase()==="script")z.state=K.SCRIPT;else z.state=K.TEXT;z.tag=null,z.tagName=""}z.attribName=z.attribValue="",z.attribList.length=0}function h1(z){if(!z.tagName){C(z,"Weird empty close tag."),z.textNode+="</>",z.state=K.TEXT;return}if(z.script){if(z.tagName!=="script"){z.script+="</"+z.tagName+">",z.tagName="",z.state=K.SCRIPT;return}M(z,"onscript",z.script),z.script=""}var W=z.tags.length,N=z.tagName;if(!z.strict)N=N[z.looseCase]();var q=N;while(W--)if(z.tags[W].name!==q)C(z,"Unexpected close tag");else break;if(W<0){C(z,"Unmatched closing tag: "+z.tagName),z.textNode+="</"+z.tagName+">",z.state=K.TEXT;return}z.tagName=N;var T=z.tags.length;while(T-- >W){var v=z.tag=z.tags.pop();z.tagName=z.tag.name,M(z,"onclosetag",z.tagName);var l={};for(var m in v.ns)l[m]=v.ns[m];var n=z.tags[z.tags.length-1]||z;if(z.opt.xmlns&&v.ns!==n.ns)Object.keys(v.ns).forEach(function(N8){var b=v.ns[N8];M(z,"onclosenamespace",{prefix:N8,uri:b})})}if(W===0)z.closedRoot=!0;z.tagName=z.attribValue=z.attribName="",z.attribList.length=0,z.state=K.TEXT}function m9(z){var W=z.entity,N=W.toLowerCase(),q,T="";if(z.ENTITIES[W])return z.ENTITIES[W];if(z.ENTITIES[N])return z.ENTITIES[N];if(W=N,W.charAt(0)==="#")if(W.charAt(1)==="x")W=W.slice(2),q=parseInt(W,16),T=q.toString(16);else W=W.slice(1),q=parseInt(W,10),T=q.toString(10);if(W=W.replace(/^0+/,""),isNaN(q)||T.toLowerCase()!==W)return C(z,"Invalid character entity"),"&"+z.entity+";";return String.fromCodePoint(q)}function c9(z,W){if(W==="<")z.state=K.OPEN_WAKA,z.startTagPosition=z.position;else if(!O(W))C(z,"Non-whitespace before first tag."),z.textNode=W,z.state=K.TEXT}function u9(z,W){var N="";if(W<z.length)N=z.charAt(W);return N}function f6(z){var W=this;if(this.error)throw this.error;if(W.closed)return Q1(W,"Cannot write after close. Assign an onready handler.");if(z===null)return d9(W);if(typeof z==="object")z=z.toString();var N=0,q="";while(!0){if(q=u9(z,N++),W.c=q,!q)break;if(W.trackPosition)if(W.position++,q===`
|
|
45
|
+
`)W.line++,W.column=0;else W.column++;switch(W.state){case K.BEGIN:if(W.state=K.BEGIN_WHITESPACE,q==="\uFEFF")continue;c9(W,q);continue;case K.BEGIN_WHITESPACE:c9(W,q);continue;case K.TEXT:if(W.sawRoot&&!W.closedRoot){var T=N-1;while(q&&q!=="<"&&q!=="&")if(q=u9(z,N++),q&&W.trackPosition)if(W.position++,q===`
|
|
46
|
+
`)W.line++,W.column=0;else W.column++;W.textNode+=z.substring(T,N-1)}if(q==="<"&&!(W.sawRoot&&W.closedRoot&&!W.strict))W.state=K.OPEN_WAKA,W.startTagPosition=W.position;else{if(!O(q)&&(!W.sawRoot||W.closedRoot))C(W,"Text data outside of root node.");if(q==="&")W.state=K.TEXT_ENTITY;else W.textNode+=q}continue;case K.SCRIPT:if(q==="<")W.state=K.SCRIPT_ENDING;else W.script+=q;continue;case K.SCRIPT_ENDING:if(q==="/")W.state=K.CLOSE_TAG;else W.script+="<"+q,W.state=K.SCRIPT;continue;case K.OPEN_WAKA:if(q==="!")W.state=K.SGML_DECL,W.sgmlDecl="";else if(O(q));else if(x(R,q))W.state=K.OPEN_TAG,W.tagName=q;else if(q==="/")W.state=K.CLOSE_TAG,W.tagName="";else if(q==="?")W.state=K.PROC_INST,W.procInstName=W.procInstBody="";else{if(C(W,"Unencoded <"),W.startTagPosition+1<W.position){var v=W.position-W.startTagPosition;q=Array(v).join(" ")+q}W.textNode+="<"+q,W.state=K.TEXT}continue;case K.SGML_DECL:if((W.sgmlDecl+q).toUpperCase()===D)M(W,"onopencdata"),W.state=K.CDATA,W.sgmlDecl="",W.cdata="";else if(W.sgmlDecl+q==="--")W.state=K.COMMENT,W.comment="",W.sgmlDecl="";else if((W.sgmlDecl+q).toUpperCase()===L){if(W.state=K.DOCTYPE,W.doctype||W.sawRoot)C(W,"Inappropriately located doctype declaration");W.doctype="",W.sgmlDecl=""}else if(q===">")M(W,"onsgmldeclaration",W.sgmlDecl),W.sgmlDecl="",W.state=K.TEXT;else if(j(q))W.state=K.SGML_DECL_QUOTED,W.sgmlDecl+=q;else W.sgmlDecl+=q;continue;case K.SGML_DECL_QUOTED:if(q===W.q)W.state=K.SGML_DECL,W.q="";W.sgmlDecl+=q;continue;case K.DOCTYPE:if(q===">")W.state=K.TEXT,M(W,"ondoctype",W.doctype),W.doctype=!0;else if(W.doctype+=q,q==="[")W.state=K.DOCTYPE_DTD;else if(j(q))W.state=K.DOCTYPE_QUOTED,W.q=q;continue;case K.DOCTYPE_QUOTED:if(W.doctype+=q,q===W.q)W.q="",W.state=K.DOCTYPE;continue;case K.DOCTYPE_DTD:if(W.doctype+=q,q==="]")W.state=K.DOCTYPE;else if(j(q))W.state=K.DOCTYPE_DTD_QUOTED,W.q=q;continue;case K.DOCTYPE_DTD_QUOTED:if(W.doctype+=q,q===W.q)W.state=K.DOCTYPE_DTD,W.q="";continue;case K.COMMENT:if(q==="-")W.state=K.COMMENT_ENDING;else W.comment+=q;continue;case K.COMMENT_ENDING:if(q==="-"){if(W.state=K.COMMENT_ENDED,W.comment=g9(W.opt,W.comment),W.comment)M(W,"oncomment",W.comment);W.comment=""}else W.comment+="-"+q,W.state=K.COMMENT;continue;case K.COMMENT_ENDED:if(q!==">")C(W,"Malformed comment"),W.comment+="--"+q,W.state=K.COMMENT;else W.state=K.TEXT;continue;case K.CDATA:if(q==="]")W.state=K.CDATA_ENDING;else W.cdata+=q;continue;case K.CDATA_ENDING:if(q==="]")W.state=K.CDATA_ENDING_2;else W.cdata+="]"+q,W.state=K.CDATA;continue;case K.CDATA_ENDING_2:if(q===">"){if(W.cdata)M(W,"oncdata",W.cdata);M(W,"onclosecdata"),W.cdata="",W.state=K.TEXT}else if(q==="]")W.cdata+="]";else W.cdata+="]]"+q,W.state=K.CDATA;continue;case K.PROC_INST:if(q==="?")W.state=K.PROC_INST_ENDING;else if(O(q))W.state=K.PROC_INST_BODY;else W.procInstName+=q;continue;case K.PROC_INST_BODY:if(!W.procInstBody&&O(q))continue;else if(q==="?")W.state=K.PROC_INST_ENDING;else W.procInstBody+=q;continue;case K.PROC_INST_ENDING:if(q===">")M(W,"onprocessinginstruction",{name:W.procInstName,body:W.procInstBody}),W.procInstName=W.procInstBody="",W.state=K.TEXT;else W.procInstBody+="?"+q,W.state=K.PROC_INST_BODY;continue;case K.OPEN_TAG:if(x(P,q))W.tagName+=q;else if(b6(W),q===">")D8(W);else if(q==="/")W.state=K.OPEN_TAG_SLASH;else{if(!O(q))C(W,"Invalid character in tag name");W.state=K.ATTRIB}continue;case K.OPEN_TAG_SLASH:if(q===">")D8(W,!0),h1(W);else C(W,"Forward-slash in opening tag not followed by >"),W.state=K.ATTRIB;continue;case K.ATTRIB:if(O(q))continue;else if(q===">")D8(W);else if(q==="/")W.state=K.OPEN_TAG_SLASH;else if(x(R,q))W.attribName=q,W.attribValue="",W.state=K.ATTRIB_NAME;else C(W,"Invalid attribute name");continue;case K.ATTRIB_NAME:if(q==="=")W.state=K.ATTRIB_VALUE;else if(q===">")C(W,"Attribute without value"),W.attribValue=W.attribName,f1(W),D8(W);else if(O(q))W.state=K.ATTRIB_NAME_SAW_WHITE;else if(x(P,q))W.attribName+=q;else C(W,"Invalid attribute name");continue;case K.ATTRIB_NAME_SAW_WHITE:if(q==="=")W.state=K.ATTRIB_VALUE;else if(O(q))continue;else if(C(W,"Attribute without value"),W.tag.attributes[W.attribName]="",W.attribValue="",M(W,"onattribute",{name:W.attribName,value:""}),W.attribName="",q===">")D8(W);else if(x(R,q))W.attribName=q,W.state=K.ATTRIB_NAME;else C(W,"Invalid attribute name"),W.state=K.ATTRIB;continue;case K.ATTRIB_VALUE:if(O(q))continue;else if(j(q))W.q=q,W.state=K.ATTRIB_VALUE_QUOTED;else C(W,"Unquoted attribute value"),W.state=K.ATTRIB_VALUE_UNQUOTED,W.attribValue=q;continue;case K.ATTRIB_VALUE_QUOTED:if(q!==W.q){if(q==="&")W.state=K.ATTRIB_VALUE_ENTITY_Q;else W.attribValue+=q;continue}f1(W),W.q="",W.state=K.ATTRIB_VALUE_CLOSED;continue;case K.ATTRIB_VALUE_CLOSED:if(O(q))W.state=K.ATTRIB;else if(q===">")D8(W);else if(q==="/")W.state=K.OPEN_TAG_SLASH;else if(x(R,q))C(W,"No whitespace between attributes"),W.attribName=q,W.attribValue="",W.state=K.ATTRIB_NAME;else C(W,"Invalid attribute name");continue;case K.ATTRIB_VALUE_UNQUOTED:if(!d(q)){if(q==="&")W.state=K.ATTRIB_VALUE_ENTITY_U;else W.attribValue+=q;continue}if(f1(W),q===">")D8(W);else W.state=K.ATTRIB;continue;case K.CLOSE_TAG:if(!W.tagName)if(O(q))continue;else if(k(R,q))if(W.script)W.script+="</"+q,W.state=K.SCRIPT;else C(W,"Invalid tagname in closing tag.");else W.tagName=q;else if(q===">")h1(W);else if(x(P,q))W.tagName+=q;else if(W.script)W.script+="</"+W.tagName,W.tagName="",W.state=K.SCRIPT;else{if(!O(q))C(W,"Invalid tagname in closing tag");W.state=K.CLOSE_TAG_SAW_WHITE}continue;case K.CLOSE_TAG_SAW_WHITE:if(O(q))continue;if(q===">")h1(W);else C(W,"Invalid characters in closing tag");continue;case K.TEXT_ENTITY:case K.ATTRIB_VALUE_ENTITY_Q:case K.ATTRIB_VALUE_ENTITY_U:var l,m;switch(W.state){case K.TEXT_ENTITY:l=K.TEXT,m="textNode";break;case K.ATTRIB_VALUE_ENTITY_Q:l=K.ATTRIB_VALUE_QUOTED,m="attribValue";break;case K.ATTRIB_VALUE_ENTITY_U:l=K.ATTRIB_VALUE_UNQUOTED,m="attribValue";break}if(q===";")if(W.opt.unparsedEntities){var n=m9(W);W.entity="",W.state=l,W.write(n)}else W[m]+=m9(W),W.entity="",W.state=l;else if(x(W.entity.length?I:V,q))W.entity+=q;else C(W,"Invalid character in entity name"),W[m]+="&"+W.entity+q,W.entity="",W.state=l;continue;default:throw Error(W,"Unknown state: "+W.state)}}if(W.position>=W.bufferCheckPosition)Y(W);return W}/*! http://mths.be/fromcodepoint v0.1.0 by @mathias */if(!String.fromCodePoint)(function(){var z=String.fromCharCode,W=Math.floor,N=function(){var q=16384,T=[],v,l,m=-1,n=arguments.length;if(!n)return"";var N8="";while(++m<n){var b=Number(arguments[m]);if(!isFinite(b)||b<0||b>1114111||W(b)!==b)throw RangeError("Invalid code point: "+b);if(b<=65535)T.push(b);else b-=65536,v=(b>>10)+55296,l=b%1024+56320,T.push(v,l);if(m+1===n||T.length>q)N8+=z.apply(null,T),T.length=0}return N8};if(Object.defineProperty)Object.defineProperty(String,"fromCodePoint",{value:N,configurable:!0,writable:!0});else String.fromCodePoint=N})();return Q},T4=t6();var F1=`The output should be formatted as a XML file.
|
|
47
|
+
1. Output should conform to the tags below.
|
|
48
|
+
2. If tags are not given, make them on your own.
|
|
49
|
+
3. Remember to always open and close all the tags.
|
|
50
|
+
|
|
51
|
+
As an example, for the tags ["foo", "bar", "baz"]:
|
|
52
|
+
1. String "<foo>
|
|
53
|
+
<bar>
|
|
54
|
+
<baz></baz>
|
|
55
|
+
</bar>
|
|
56
|
+
</foo>" is a well-formatted instance of the schema.
|
|
57
|
+
2. String "<foo>
|
|
58
|
+
<bar>
|
|
59
|
+
</foo>" is a badly-formatted instance.
|
|
60
|
+
3. String "<foo>
|
|
61
|
+
<tag>
|
|
62
|
+
</tag>
|
|
63
|
+
</foo>" is a badly-formatted instance.
|
|
64
|
+
|
|
65
|
+
Here are the output tags:
|
|
66
|
+
\`\`\`
|
|
67
|
+
{tags}
|
|
68
|
+
\`\`\``,j4=class extends Q8{tags;constructor(Q){super(Q);this.tags=Q?.tags}static lc_name(){return"XMLOutputParser"}lc_namespace=["langchain_core","output_parsers"];lc_serializable=!0;_diff(Q,Z){if(!Z)return;if(!Q)return[{op:"replace",path:"",value:Z}];return U8(Q,Z)}async parsePartialResult(Q){return L1(Q[0].text)}async parse(Q){return L1(Q)}getFormatInstructions(){return this.tags&&this.tags.length>0?F1.replace("{tags}",this.tags?.join(", ")??""):F1}},a6=(Q)=>Q.split(`
|
|
69
|
+
`).map((Z)=>Z.replace(/^\s+/,"")).join(`
|
|
70
|
+
`).trim(),C4=(Q)=>{if(Object.keys(Q).length===0)return{};let Z={};if(Q.children.length>0)return Z[Q.name]=Q.children.map(C4),Z;else return Z[Q.name]=Q.text??void 0,Z};function L1(Q){let Z=a6(Q),J=T4.parser(!0),Y={},G=[];J.onopentag=($)=>{let U={name:$.name,attributes:$.attributes,children:[],text:"",isSelfClosing:$.isSelfClosing};if(G.length>0)G[G.length-1].children.push(U);else Y=U;if(!$.isSelfClosing)G.push(U)},J.onclosetag=()=>{if(G.length>0){let $=G.pop();if(G.length===0&&$)Y=$}},J.ontext=($)=>{if(G.length>0){let U=G[G.length-1];U.text+=$}},J.onattribute=($)=>{if(G.length>0){let U=G[G.length-1];U.attributes[$.name]=$.value}};let H=/```(xml)?(.*)```/s.exec(Z),X=H?H[2]:Z;if(J.write(X).close(),Y&&Y.name==="?xml")Y=Y.children[0];return C4(Y)}var M4=F({AsymmetricStructuredOutputParser:()=>O4,BaseCumulativeTransformOutputParser:()=>Q8,BaseLLMOutputParser:()=>M8,BaseOutputParser:()=>H8,BaseTransformOutputParser:()=>W8,BytesOutputParser:()=>F4,CommaSeparatedListOutputParser:()=>L4,CustomListOutputParser:()=>R4,JsonMarkdownStructuredOutputParser:()=>X9,JsonOutputParser:()=>_4,ListOutputParser:()=>S8,MarkdownListOutputParser:()=>I4,NumberedListOutputParser:()=>P4,OutputParserException:()=>o,StringOutputParser:()=>V4,StructuredOutputParser:()=>W9,XMLOutputParser:()=>j4,XML_FORMAT_INSTRUCTIONS:()=>F1,parseJsonMarkdown:()=>p8,parsePartialJson:()=>w8,parseXMLMarkdown:()=>L1});var z9=class extends M8{static lc_name(){return"OutputFunctionsParser"}lc_namespace=["langchain","output_parsers","openai_functions"];lc_serializable=!0;argsOnly=!0;constructor(Q){super();this.argsOnly=Q?.argsOnly??this.argsOnly}async parseResult(Q){if("message"in Q[0]){let Z=Q[0].message.additional_kwargs.function_call;if(!Z)throw Error(`No function_call in message ${JSON.stringify(Q)}`);if(!Z.arguments)throw Error(`No arguments in function_call ${JSON.stringify(Q)}`);if(this.argsOnly)return Z.arguments;return JSON.stringify(Z)}else throw Error(`No message in generations ${JSON.stringify(Q)}`)}},$9=class extends Q8{static lc_name(){return"JsonOutputFunctionsParser"}lc_namespace=["langchain","output_parsers","openai_functions"];lc_serializable=!0;outputParser;argsOnly=!0;constructor(Q){super(Q);this.argsOnly=Q?.argsOnly??this.argsOnly,this.outputParser=new z9(Q)}_diff(Q,Z){if(!Z)return;return U8(Q??{},Z)}async parsePartialResult(Q){let Z=Q[0];if(!Z.message)return;let{message:J}=Z,Y=J.additional_kwargs.function_call;if(!Y)return;if(this.argsOnly)return w8(Y.arguments);return{...Y,arguments:w8(Y.arguments)}}async parseResult(Q){let Z=await this.outputParser.parseResult(Q);if(!Z)throw Error(`No result from "OutputFunctionsParser" ${JSON.stringify(Q)}`);return this.parse(Z)}async parse(Q){let Z=JSON.parse(Q);if(this.argsOnly)return Z;return Z.arguments=JSON.parse(Z.arguments),Z}getFormatInstructions(){return""}},S4=class extends M8{static lc_name(){return"JsonKeyOutputFunctionsParser"}lc_namespace=["langchain","output_parsers","openai_functions"];lc_serializable=!0;outputParser=new $9;attrName;get lc_aliases(){return{attrName:"key_name"}}constructor(Q){super(Q);this.attrName=Q.attrName}async parseResult(Q){return(await this.outputParser.parseResult(Q))[this.attrName]}};var y4=F({JsonKeyOutputFunctionsParser:()=>S4,JsonOutputFunctionsParser:()=>$9,OutputFunctionsParser:()=>z9});function K9(Q,Z){if(Q.function===void 0)return;let J;if(Z?.partial)try{J=w8(Q.function.arguments??"{}")}catch{return}else try{J=JSON.parse(Q.function.arguments)}catch(G){throw new o([`Function "${Q.function.name}" arguments:`,"",Q.function.arguments,"","are not valid JSON.",`Error: ${G.message}`].join(`
|
|
71
|
+
`))}let Y={name:Q.function.name,args:J,type:"tool_call"};if(Z?.returnId)Y.id=Q.id;return Y}function v4(Q){if(Q.id===void 0)throw Error('All OpenAI tool calls must have an "id" field.');return{id:Q.id,type:"function",function:{name:Q.name,arguments:JSON.stringify(Q.args)}}}function x4(Q,Z){return{name:Q.function?.name,args:Q.function?.arguments,id:Q.id,error:Z,type:"invalid_tool_call"}}var q9=class extends Q8{static lc_name(){return"JsonOutputToolsParser"}returnId=!1;lc_namespace=["langchain","output_parsers","openai_tools"];lc_serializable=!0;constructor(Q){super(Q);this.returnId=Q?.returnId??this.returnId}_diff(){throw Error("Not supported.")}async parse(){throw Error("Not implemented.")}async parseResult(Q){return await this.parsePartialResult(Q,!1)}async parsePartialResult(Q,Z=!0){let J=Q[0].message,Y;if(q1(J)&&J.tool_calls?.length)Y=J.tool_calls.map((H)=>{let{id:X,...$}=H;if(!this.returnId)return $;return{id:X,...$}});else if(J.additional_kwargs.tool_calls!==void 0)Y=JSON.parse(JSON.stringify(J.additional_kwargs.tool_calls)).map((H)=>{return K9(H,{returnId:this.returnId,partial:Z})});if(!Y)return[];let G=[];for(let H of Y)if(H!==void 0){let X={type:H.name,args:H.args,id:H.id};G.push(X)}return G}},k4=class extends q9{static lc_name(){return"JsonOutputKeyToolsParser"}lc_namespace=["langchain","output_parsers","openai_tools"];lc_serializable=!0;returnId=!1;keyName;returnSingle=!1;zodSchema;constructor(Q){super(Q);this.keyName=Q.keyName,this.returnSingle=Q.returnSingle??this.returnSingle,this.zodSchema=Q.zodSchema}async _validateResult(Q){if(this.zodSchema===void 0)return Q;let Z=await J1(this.zodSchema,Q);if(Z.success)return Z.data;else throw new o(`Failed to parse. Text: "${JSON.stringify(Q,null,2)}". Error: ${JSON.stringify(Z.error?.issues)}`,JSON.stringify(Q,null,2))}async parsePartialResult(Q){let Z=(await super.parsePartialResult(Q)).filter((Y)=>Y.type===this.keyName),J=Z;if(!Z.length)return;if(!this.returnId)J=Z.map((Y)=>Y.args);if(this.returnSingle)return J[0];return J}async parseResult(Q){let Z=(await super.parsePartialResult(Q,!1)).filter((Y)=>Y.type===this.keyName),J=Z;if(!Z.length)return;if(!this.returnId)J=Z.map((Y)=>Y.args);if(this.returnSingle)return this._validateResult(J[0]);return await Promise.all(J.map((Y)=>this._validateResult(Y)))}};var b4=F({JsonOutputKeyToolsParser:()=>k4,JsonOutputToolsParser:()=>q9,convertLangChainToolCallToOpenAI:()=>v4,makeInvalidToolCall:()=>x4,parseToolCall:()=>K9});var Z8=class extends y{lc_serializable=!0;lc_namespace=["langchain_core","prompts",this._getPromptType()];get lc_attributes(){return{partialVariables:void 0}}inputVariables;outputParser;partialVariables;metadata;tags;constructor(Q){super(Q);let{inputVariables:Z}=Q;if(Z.includes("stop"))throw Error("Cannot have an input variable named 'stop', as it is used internally, please rename.");Object.assign(this,Q)}async mergePartialAndUserVariables(Q){let Z=this.partialVariables??{},J={};for(let[Y,G]of Object.entries(Z))if(typeof G==="string")J[Y]=G;else J[Y]=await G();return{...J,...Q}}async invoke(Q,Z){let J={...this.metadata,...Z?.metadata},Y=[...this.tags??[],...Z?.tags??[]];return this._callWithConfig((G)=>this.formatPromptValue(G),Q,{...Z,tags:Y,metadata:J,runType:"prompt"})}};var X8=class extends Z8{async formatPromptValue(Q){return new f4(await this.format(Q))}};/*!
|
|
72
|
+
* mustache.js - Logic-less {{mustache}} templates with JavaScript
|
|
73
|
+
* http://github.com/janl/mustache.js
|
|
74
|
+
*/var e6=Object.prototype.toString,v8=Array.isArray||function(Z){return e6.call(Z)==="[object Array]"};function w9(Q){return typeof Q==="function"}function QQ(Q){return v8(Q)?"array":typeof Q}function U9(Q){return Q.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function h4(Q,Z){return Q!=null&&typeof Q==="object"&&Z in Q}function ZQ(Q,Z){return Q!=null&&typeof Q!=="object"&&Q.hasOwnProperty&&Q.hasOwnProperty(Z)}var JQ=RegExp.prototype.test;function YQ(Q,Z){return JQ.call(Q,Z)}var GQ=/\S/;function HQ(Q){return!YQ(GQ,Q)}var WQ={"&":"&","<":"<",">":">",'"':""","'":"'","/":"/","`":"`","=":"="};function XQ(Q){return String(Q).replace(/[&<>"'`=\/]/g,function(J){return WQ[J]})}var zQ=/\s*/,$Q=/\s+/,g4=/\s*=/,KQ=/\s*\}/,qQ=/#|\^|\/|>|\{|&|=|!/;function UQ(Q,Z){if(!Q)return[];var J=!1,Y=[],G=[],H=[],X=!1,$=!1,U="",w=0;function D(){if(X&&!$)while(H.length)delete G[H.pop()];else H=[];X=!1,$=!1}var L,A,E;function B(K){if(typeof K==="string")K=K.split($Q,2);if(!v8(K)||K.length!==2)throw Error("Invalid tags: "+K);L=new RegExp(U9(K[0])+"\\s*"),A=new RegExp("\\s*"+U9(K[1])),E=new RegExp("\\s*"+U9("}"+K[1]))}B(Z||i.tags);var R=new i8(Q),P,V,I,O,j,d;while(!R.eos()){if(P=R.pos,I=R.scanUntil(L),I)for(var x=0,k=I.length;x<k;++x){if(O=I.charAt(x),HQ(O))H.push(G.length),U+=O;else $=!0,J=!0,U+=" ";if(G.push(["text",O,P,P+1]),P+=1,O===`
|
|
75
|
+
`)D(),U="",w=0,J=!1}if(!R.scan(L))break;if(X=!0,V=R.scan(qQ)||"name",R.scan(zQ),V==="=")I=R.scanUntil(g4),R.scan(g4),R.scanUntil(A);else if(V==="{")I=R.scanUntil(E),R.scan(KQ),R.scanUntil(A),V="&";else I=R.scanUntil(A);if(!R.scan(A))throw Error("Unclosed tag at "+R.pos);if(V==">")j=[V,I,P,R.pos,U,w,J];else j=[V,I,P,R.pos];if(w++,G.push(j),V==="#"||V==="^")Y.push(j);else if(V==="/"){if(d=Y.pop(),!d)throw Error('Unopened section "'+I+'" at '+P);if(d[1]!==I)throw Error('Unclosed section "'+d[1]+'" at '+P)}else if(V==="name"||V==="{"||V==="&")$=!0;else if(V==="=")B(I)}if(D(),d=Y.pop(),d)throw Error('Unclosed section "'+d[1]+'" at '+R.pos);return DQ(wQ(G))}function wQ(Q){var Z=[],J,Y;for(var G=0,H=Q.length;G<H;++G)if(J=Q[G],J)if(J[0]==="text"&&Y&&Y[0]==="text")Y[1]+=J[1],Y[3]=J[3];else Z.push(J),Y=J;return Z}function DQ(Q){var Z=[],J=Z,Y=[],G,H;for(var X=0,$=Q.length;X<$;++X)switch(G=Q[X],G[0]){case"#":case"^":J.push(G),Y.push(G),J=G[4]=[];break;case"/":H=Y.pop(),H[5]=G[2],J=Y.length>0?Y[Y.length-1][4]:Z;break;default:J.push(G)}return Z}function i8(Q){this.string=Q,this.tail=Q,this.pos=0}i8.prototype.eos=function(){return this.tail===""};i8.prototype.scan=function(Z){var J=this.tail.match(Z);if(!J||J.index!==0)return"";var Y=J[0];return this.tail=this.tail.substring(Y.length),this.pos+=Y.length,Y};i8.prototype.scanUntil=function(Z){var J=this.tail.search(Z),Y;switch(J){case-1:Y=this.tail,this.tail="";break;case 0:Y="";break;default:Y=this.tail.substring(0,J),this.tail=this.tail.substring(J)}return this.pos+=Y.length,Y};function y8(Q,Z){this.view=Q,this.cache={".":this.view},this.parent=Z}y8.prototype.push=function(Z){return new y8(Z,this)};y8.prototype.lookup=function(Z){var J=this.cache,Y;if(J.hasOwnProperty(Z))Y=J[Z];else{var G=this,H,X,$,U=!1;while(G){if(Z.indexOf(".")>0){H=G.view,X=Z.split("."),$=0;while(H!=null&&$<X.length){if($===X.length-1)U=h4(H,X[$])||ZQ(H,X[$]);H=H[X[$++]]}}else H=G.view[Z],U=h4(G.view,Z);if(U){Y=H;break}G=G.parent}J[Z]=Y}if(w9(Y))Y=Y.call(this.view);return Y};function c(){this.templateCache={_cache:{},set:function(Z,J){this._cache[Z]=J},get:function(Z){return this._cache[Z]},clear:function(){this._cache={}}}}c.prototype.clearCache=function(){if(typeof this.templateCache<"u")this.templateCache.clear()};c.prototype.parse=function(Z,J){var Y=this.templateCache,G=Z+":"+(J||i.tags).join(":"),H=typeof Y<"u",X=H?Y.get(G):void 0;if(X==null)X=UQ(Z,J),H&&Y.set(G,X);return X};c.prototype.render=function(Z,J,Y,G){var H=this.getConfigTags(G),X=this.parse(Z,H),$=J instanceof y8?J:new y8(J,void 0);return this.renderTokens(X,$,Y,Z,G)};c.prototype.renderTokens=function(Z,J,Y,G,H){var X="",$,U,w;for(var D=0,L=Z.length;D<L;++D){if(w=void 0,$=Z[D],U=$[0],U==="#")w=this.renderSection($,J,Y,G,H);else if(U==="^")w=this.renderInverted($,J,Y,G,H);else if(U===">")w=this.renderPartial($,J,Y,H);else if(U==="&")w=this.unescapedValue($,J);else if(U==="name")w=this.escapedValue($,J,H);else if(U==="text")w=this.rawValue($);if(w!==void 0)X+=w}return X};c.prototype.renderSection=function(Z,J,Y,G,H){var X=this,$="",U=J.lookup(Z[1]);function w(A){return X.render(A,J,Y,H)}if(!U)return;if(v8(U))for(var D=0,L=U.length;D<L;++D)$+=this.renderTokens(Z[4],J.push(U[D]),Y,G,H);else if(typeof U==="object"||typeof U==="string"||typeof U==="number")$+=this.renderTokens(Z[4],J.push(U),Y,G,H);else if(w9(U)){if(typeof G!=="string")throw Error("Cannot use higher-order sections without the original template");if(U=U.call(J.view,G.slice(Z[3],Z[5]),w),U!=null)$+=U}else $+=this.renderTokens(Z[4],J,Y,G,H);return $};c.prototype.renderInverted=function(Z,J,Y,G,H){var X=J.lookup(Z[1]);if(!X||v8(X)&&X.length===0)return this.renderTokens(Z[4],J,Y,G,H)};c.prototype.indentPartial=function(Z,J,Y){var G=J.replace(/[^ \t]/g,""),H=Z.split(`
|
|
76
|
+
`);for(var X=0;X<H.length;X++)if(H[X].length&&(X>0||!Y))H[X]=G+H[X];return H.join(`
|
|
77
|
+
`)};c.prototype.renderPartial=function(Z,J,Y,G){if(!Y)return;var H=this.getConfigTags(G),X=w9(Y)?Y(Z[1]):Y[Z[1]];if(X!=null){var $=Z[6],U=Z[5],w=Z[4],D=X;if(U==0&&w)D=this.indentPartial(X,w,$);var L=this.parse(D,H);return this.renderTokens(L,J,Y,D,G)}};c.prototype.unescapedValue=function(Z,J){var Y=J.lookup(Z[1]);if(Y!=null)return Y};c.prototype.escapedValue=function(Z,J,Y){var G=this.getConfigEscape(Y)||i.escape,H=J.lookup(Z[1]);if(H!=null)return typeof H==="number"&&G===i.escape?String(H):G(H)};c.prototype.rawValue=function(Z){return Z[1]};c.prototype.getConfigTags=function(Z){if(v8(Z))return Z;else if(Z&&typeof Z==="object")return Z.tags;else return};c.prototype.getConfigEscape=function(Z){if(Z&&typeof Z==="object"&&!v8(Z))return Z.escape;else return};var i={name:"mustache.js",version:"4.2.0",tags:["{{","}}"],clearCache:void 0,escape:void 0,parse:void 0,render:void 0,Scanner:void 0,Context:void 0,Writer:void 0,set templateCache(Q){o8.templateCache=Q},get templateCache(){return o8.templateCache}},o8=new c;i.clearCache=function(){return o8.clearCache()};i.parse=function(Z,J){return o8.parse(Z,J)};i.render=function(Z,J,Y,G){if(typeof Z!=="string")throw TypeError('Invalid template! Template should be a "string" but "'+QQ(Z)+'" was given as the first argument for mustache#render(template, view, partials)');return o8.render(Z,J,Y,G)};i.escape=XQ;i.Scanner=i8;i.Context=y8;i.Writer=c;var R1=i;function d4(){R1.escape=(Q)=>Q}var F8=(Q)=>{let Z=Q.split(""),J=[],Y=(H,X)=>{for(let $=X;$<Z.length;$+=1)if(H.includes(Z[$]))return $;return-1},G=0;while(G<Z.length)if(Z[G]==="{"&&G+1<Z.length&&Z[G+1]==="{")J.push({type:"literal",text:"{"}),G+=2;else if(Z[G]==="}"&&G+1<Z.length&&Z[G+1]==="}")J.push({type:"literal",text:"}"}),G+=2;else if(Z[G]==="{"){let H=Y("}",G);if(H<0)throw Error("Unclosed '{' in template.");J.push({type:"variable",name:Z.slice(G+1,H).join("")}),G=H+1}else if(Z[G]==="}")throw Error("Single '}' in template.");else{let H=Y("{}",G),X=(H<0?Z.slice(G):Z.slice(G,H)).join("");J.push({type:"literal",text:X}),G=H<0?Z.length:H}return J},m4=(Q,Z=[])=>{let J=[];for(let Y of Q)if(Y[0]==="name"){let G=Y[1].includes(".")?Y[1].split(".")[0]:Y[1];J.push({type:"variable",name:G})}else if(["#","&","^",">"].includes(Y[0])){if(J.push({type:"variable",name:Y[1]}),Y[0]==="#"&&Y.length>4&&Array.isArray(Y[4])){let G=[...Z,Y[1]],H=m4(Y[4],G);J.push(...H)}}else J.push({type:"literal",text:Y[1]});return J},x8=(Q)=>{return d4(),m4(R1.parse(Q))},D9=(Q,Z)=>{return F8(Q).reduce((J,Y)=>{if(Y.type==="variable"){if(Y.name in Z)return J+(typeof Z[Y.name]==="string"?Z[Y.name]:JSON.stringify(Z[Y.name]));throw Error(`(f-string) Missing value for input ${Y.name}`)}return J+Y.text},"")},N9=(Q,Z)=>{return d4(),R1.render(Q,Z)},n8={"f-string":D9,mustache:N9},B9={"f-string":F8,mustache:x8},g=(Q,Z,J)=>{try{return n8[Z](Q,J)}catch(Y){throw C8(Y,"INVALID_PROMPT_INPUT")}},L8=(Q,Z)=>B9[Z](Q),z8=(Q,Z,J)=>{if(!(Z in n8)){let Y=Object.keys(n8);throw Error(`Invalid template format. Got \`${Z}\`;
|
|
78
|
+
should be one of ${Y}`)}try{let Y=Object.fromEntries(J.map((G)=>[G,"foo"]));if(Array.isArray(Q))Q.forEach((G)=>{if(G.type==="text"&&"text"in G&&typeof G.text==="string")g(G.text,Z,Y);else if(G.type==="image_url"){if(typeof G.image_url==="string")g(G.image_url,Z,Y);else if(typeof G.image_url==="object"&&G.image_url!==null&&"url"in G.image_url&&typeof G.image_url.url==="string"){let H=G.image_url.url;g(H,Z,Y)}}else throw Error(`Invalid message template received. ${JSON.stringify(G,null,2)}`)});else g(Q,Z,Y)}catch(Y){throw Error(`Invalid prompt schema: ${Y.message}`)}};var t=class Q extends X8{static lc_name(){return"PromptTemplate"}template;templateFormat="f-string";validateTemplate=!0;additionalContentFields;constructor(Z){super(Z);if(Z.templateFormat==="mustache"&&Z.validateTemplate===void 0)this.validateTemplate=!1;if(Object.assign(this,Z),this.validateTemplate){if(this.templateFormat==="mustache")throw Error("Mustache templates cannot be validated.");let J=this.inputVariables;if(this.partialVariables)J=J.concat(Object.keys(this.partialVariables));z8(this.template,this.templateFormat,J)}}_getPromptType(){return"prompt"}async format(Z){let J=await this.mergePartialAndUserVariables(Z);return g(this.template,this.templateFormat,J)}static fromExamples(Z,J,Y,G=`
|
|
79
|
+
|
|
80
|
+
`,H=""){return new Q({inputVariables:Y,template:[H,...Z,J].join(G)})}static fromTemplate(Z,J){let{templateFormat:Y="f-string",...G}=J??{},H=new Set;return L8(Z,Y).forEach((X)=>{if(X.type==="variable")H.add(X.name)}),new Q({inputVariables:[...H],templateFormat:Y,template:Z,...G})}async partial(Z){let J=this.inputVariables.filter((G)=>!(G in Z)),Y={...this.partialVariables??{},...Z};return new Q({...this,inputVariables:J,partialVariables:Y})}serialize(){if(this.outputParser!==void 0)throw Error("Cannot serialize a prompt template with an output parser");return{_type:this._getPromptType(),input_variables:this.inputVariables,template:this.template,template_format:this.templateFormat}}static async deserialize(Z){if(!Z.template)throw Error("Prompt template must have a template");return new Q({inputVariables:Z.input_variables,template:Z.template,templateFormat:Z.template_format})}};var k8=class Q extends Z8{static lc_name(){return"ImagePromptTemplate"}lc_namespace=["langchain_core","prompts","image"];template;templateFormat="f-string";validateTemplate=!0;additionalContentFields;constructor(Z){super(Z);if(this.template=Z.template,this.templateFormat=Z.templateFormat??this.templateFormat,this.validateTemplate=Z.validateTemplate??this.validateTemplate,this.additionalContentFields=Z.additionalContentFields,this.validateTemplate){let J=this.inputVariables;if(this.partialVariables)J=J.concat(Object.keys(this.partialVariables));z8([{type:"image_url",image_url:this.template}],this.templateFormat,J)}}_getPromptType(){return"prompt"}async partial(Z){let J=this.inputVariables.filter((G)=>!(G in Z)),Y={...this.partialVariables??{},...Z};return new Q({...this,inputVariables:J,partialVariables:Y})}async format(Z){let J={};for(let[X,$]of Object.entries(this.template))if(typeof $==="string")J[X]=g($,this.templateFormat,Z);else J[X]=$;let Y=Z.url||J.url,G=Z.detail||J.detail;if(!Y)throw Error("Must provide either an image URL.");if(typeof Y!=="string")throw Error("url must be a string.");let H={url:Y};if(G)H.detail=G;return H}async formatPromptValue(Z){return new c4(await this.format(Z))}};var s8=class extends y{lc_namespace=["langchain_core","prompts","dict"];lc_serializable=!0;template;templateFormat;inputVariables;static lc_name(){return"DictPromptTemplate"}constructor(Q){let Z=Q.templateFormat??"f-string",J=A9(Q.template,Z);super({inputVariables:J,...Q});this.template=Q.template,this.templateFormat=Z,this.inputVariables=J}async format(Q){return E9(this.template,Q,this.templateFormat)}async invoke(Q){return await this._callWithConfig(this.format.bind(this),Q,{runType:"prompt"})}};function A9(Q,Z){let J=[];for(let Y of Object.values(Q))if(typeof Y==="string")L8(Y,Z).forEach((G)=>{if(G.type==="variable")J.push(G.name)});else if(Array.isArray(Y)){for(let G of Y)if(typeof G==="string")L8(G,Z).forEach((H)=>{if(H.type==="variable")J.push(H.name)});else if(typeof G==="object")J.push(...A9(G,Z))}else if(typeof Y==="object"&&Y!==null)J.push(...A9(Y,Z));return Array.from(new Set(J))}function E9(Q,Z,J){let Y={};for(let[G,H]of Object.entries(Q))if(typeof H==="string")Y[G]=g(H,J,Z);else if(Array.isArray(H)){let X=[];for(let $ of H)if(typeof $==="string")X.push(g($,J,Z));else if(typeof $==="object")X.push(E9($,Z,J));Y[G]=X}else if(typeof H==="object"&&H!==null)Y[G]=E9(H,Z,J);else Y[G]=H;return Y}var r8=class extends y{lc_namespace=["langchain_core","prompts","chat"];lc_serializable=!0;async invoke(Q,Z){return this._callWithConfig((J)=>this.formatMessages(J),Q,{...Z,runType:"prompt"})}},I1=class extends r8{static lc_name(){return"MessagesPlaceholder"}variableName;optional;constructor(Q){if(typeof Q==="string")Q={variableName:Q};super(Q);this.variableName=Q.variableName,this.optional=Q.optional??!1}get inputVariables(){return[this.variableName]}async formatMessages(Q){let Z=Q[this.variableName];if(this.optional&&!Z)return[];else if(!Z){let Y=Error(`Field "${this.variableName}" in prompt uses a MessagesPlaceholder, which expects an array of BaseMessages as an input value. Received: undefined`);throw Y.name="InputFormatError",Y}let J;try{if(Array.isArray(Z))J=Z.map(K8);else J=[K8(Z)]}catch(Y){let G=typeof Z==="string"?Z:JSON.stringify(Z,null,2),H=Error([`Field "${this.variableName}" in prompt uses a MessagesPlaceholder, which expects an array of BaseMessages or coerceable values as input.`,`Received value: ${G}`,`Additional message: ${Y.message}`].join(`
|
|
81
|
+
|
|
82
|
+
`));throw H.name="InputFormatError",H.lc_error_code=Y.lc_error_code,H}return J}},L9=class extends r8{prompt;constructor(Q){if(!("prompt"in Q))Q={prompt:Q};super(Q);this.prompt=Q.prompt}get inputVariables(){return this.prompt.inputVariables}async formatMessages(Q){return[await this.format(Q)]}},t8=class extends Z8{constructor(Q){super(Q)}async format(Q){return(await this.formatPromptValue(Q)).toString()}async formatPromptValue(Q){return new l4(await this.formatMessages(Q))}},R9=class extends L9{static lc_name(){return"ChatMessagePromptTemplate"}role;constructor(Q,Z){if(!("prompt"in Q))Q={prompt:Q,role:Z};super(Q);this.role=Q.role}async format(Q){return new F9(await this.prompt.format(Q),this.role)}static fromTemplate(Q,Z,J){return new this(t.fromTemplate(Q,{templateFormat:J?.templateFormat}),Z)}};function NQ(Q){if(Q===null||typeof Q!=="object"||Array.isArray(Q))return!1;return Object.keys(Q).length===1&&"text"in Q&&typeof Q.text==="string"}function BQ(Q){if(Q===null||typeof Q!=="object"||Array.isArray(Q))return!1;return"image_url"in Q&&(typeof Q.image_url==="string"||typeof Q.image_url==="object"&&Q.image_url!==null&&("url"in Q.image_url)&&typeof Q.image_url.url==="string")}var P9=class extends r8{lc_namespace=["langchain_core","prompts","chat"];lc_serializable=!0;inputVariables=[];additionalOptions={};prompt;messageClass;static _messageClass(){throw Error("Can not invoke _messageClass from inside _StringImageMessagePromptTemplate")}chatMessageClass;constructor(Q,Z){if(!("prompt"in Q))Q={prompt:Q};super(Q);if(this.prompt=Q.prompt,Array.isArray(this.prompt)){let J=[];this.prompt.forEach((Y)=>{if("inputVariables"in Y)J=J.concat(Y.inputVariables)}),this.inputVariables=J}else this.inputVariables=this.prompt.inputVariables;this.additionalOptions=Z??this.additionalOptions}createMessage(Q){let Z=this.constructor;if(Z._messageClass())return new(Z._messageClass())({content:Q});else if(Z.chatMessageClass){let J=Z.chatMessageClass();return new J({content:Q,role:this.getRoleFromMessageClass(J.lc_name())})}else throw Error("No message class defined")}getRoleFromMessageClass(Q){switch(Q){case"HumanMessage":return"human";case"AIMessage":return"ai";case"SystemMessage":return"system";case"ChatMessage":return"chat";default:throw Error("Invalid message class name")}}static fromTemplate(Q,Z){if(typeof Q==="string")return new this(t.fromTemplate(Q,Z));let J=[];for(let Y of Q)if(typeof Y==="string")J.push(t.fromTemplate(Y,Z));else if(Y===null);else if(NQ(Y)){let G="";if(typeof Y.text==="string")G=Y.text??"";let H={...Z,additionalContentFields:Y};J.push(t.fromTemplate(G,H))}else if(BQ(Y)){let G=Y.image_url??"",H,X=[];if(typeof G==="string"){let $;if(Z?.templateFormat==="mustache")$=x8(G);else $=F8(G);let U=$.flatMap((w)=>w.type==="variable"?[w.name]:[]);if((U?.length??0)>0){if(U.length>1)throw Error(`Only one format variable allowed per image template.
|
|
83
|
+
Got: ${U}
|
|
84
|
+
From: ${G}`);X=[U[0]]}else X=[];G={url:G},H=new k8({template:G,inputVariables:X,templateFormat:Z?.templateFormat,additionalContentFields:Y})}else if(typeof G==="object"){if("url"in G){let $;if(Z?.templateFormat==="mustache")$=x8(G.url);else $=F8(G.url);X=$.flatMap((U)=>U.type==="variable"?[U.name]:[])}else X=[];H=new k8({template:G,inputVariables:X,templateFormat:Z?.templateFormat,additionalContentFields:Y})}else throw Error("Invalid image template");J.push(H)}else if(typeof Y==="object")J.push(new s8({template:Y,templateFormat:Z?.templateFormat}));return new this({prompt:J,additionalOptions:Z})}async format(Q){if(this.prompt instanceof X8){let Z=await this.prompt.format(Q);return this.createMessage(Z)}else{let Z=[];for(let J of this.prompt){let Y={};if(!("inputVariables"in J))throw Error(`Prompt ${J} does not have inputVariables defined.`);for(let G of J.inputVariables){if(!Y)Y={[G]:Q[G]};Y={...Y,[G]:Q[G]}}if(J instanceof X8){let G=await J.format(Y),H;if("additionalContentFields"in J)H=J.additionalContentFields;if(G!=="")Z.push({...H,type:"text",text:G})}else if(J instanceof k8){let G=await J.format(Y),H;if("additionalContentFields"in J)H=J.additionalContentFields;Z.push({...H,type:"image_url",image_url:G})}else if(J instanceof s8){let G=await J.format(Y),H;if("additionalContentFields"in J)H=J.additionalContentFields;Z.push({...H,...G})}}return this.createMessage(Z)}}async formatMessages(Q){return[await this.format(Q)]}},V1=class extends P9{static _messageClass(){return $8}static lc_name(){return"HumanMessagePromptTemplate"}},I9=class extends P9{static _messageClass(){return f}static lc_name(){return"AIMessagePromptTemplate"}},V9=class extends P9{static _messageClass(){return u4}static lc_name(){return"SystemMessagePromptTemplate"}};function AQ(Q){return typeof Q.formatMessages==="function"}function EQ(Q,Z){if(AQ(Q)||r(Q))return Q;if(Array.isArray(Q)&&Q[0]==="placeholder"){let G=Q[1];if(Z?.templateFormat==="mustache"&&typeof G==="string"&&G.slice(0,2)==="{{"&&G.slice(-2)==="}}")return new I1({variableName:G.slice(2,-2),optional:!0});else if(typeof G==="string"&&G[0]==="{"&&G[G.length-1]==="}")return new I1({variableName:G.slice(1,-1),optional:!0});throw Error(`Invalid placeholder template for format ${Z?.templateFormat??'"f-string"'}: "${Q[1]}". Expected a variable name surrounded by ${Z?.templateFormat==="mustache"?"double":"single"} curly braces.`)}let J=K8(Q),Y;if(typeof J.content==="string")Y=J.content;else Y=J.content.map((G)=>{if("text"in G)return{...G,text:G.text};else if("image_url"in G)return{...G,image_url:G.image_url};else return G});if(J._getType()==="human")return V1.fromTemplate(Y,Z);else if(J._getType()==="ai")return I9.fromTemplate(Y,Z);else if(J._getType()==="system")return V9.fromTemplate(Y,Z);else if(F9.isInstance(J))return R9.fromTemplate(J.content,J.role,Z);else throw Error(`Could not coerce message prompt template from input. Received message type: "${J._getType()}".`)}function FQ(Q){return Q.constructor.lc_name()==="MessagesPlaceholder"}var b8=class Q extends t8{static lc_name(){return"ChatPromptTemplate"}get lc_aliases(){return{promptMessages:"messages"}}promptMessages;validateTemplate=!0;templateFormat="f-string";constructor(Z){super(Z);if(Z.templateFormat==="mustache"&&Z.validateTemplate===void 0)this.validateTemplate=!1;if(Object.assign(this,Z),this.validateTemplate){let J=new Set;for(let $ of this.promptMessages){if($ instanceof P1)continue;for(let U of $.inputVariables)J.add(U)}let Y=this.inputVariables,G=new Set(this.partialVariables?Y.concat(Object.keys(this.partialVariables)):Y),H=new Set([...G].filter(($)=>!J.has($)));if(H.size>0)throw Error(`Input variables \`${[...H]}\` are not used in any of the prompt messages.`);let X=new Set([...J].filter(($)=>!G.has($)));if(X.size>0)throw Error(`Input variables \`${[...X]}\` are used in prompt messages but not in the prompt template.`)}}_getPromptType(){return"chat"}async _parseImagePrompts(Z,J){if(typeof Z.content==="string")return Z;return Z.content=await Promise.all(Z.content.map(async(Y)=>{if(Y.type!=="image_url")return Y;let G="";if(typeof Y.image_url==="string")G=Y.image_url;else if(typeof Y.image_url==="object"&&Y.image_url!==null&&"url"in Y.image_url&&typeof Y.image_url.url==="string")G=Y.image_url.url;let H=await t.fromTemplate(G,{templateFormat:this.templateFormat}).format(J);if(typeof Y.image_url==="object"&&Y.image_url!==null&&"url"in Y.image_url)Y.image_url.url=H;else Y.image_url=H;return Y})),Z}async formatMessages(Z){let J=await this.mergePartialAndUserVariables(Z),Y=[];for(let G of this.promptMessages)if(G instanceof P1)Y.push(await this._parseImagePrompts(G,J));else{let H;if(this.templateFormat==="mustache")H={...J};else H=G.inputVariables.reduce(($,U)=>{if(!(U in J)&&!(FQ(G)&&G.optional))throw C8(Error(`Missing value for input variable \`${U.toString()}\``),"INVALID_PROMPT_INPUT");return $[U]=J[U],$},{});let X=await G.formatMessages(H);Y=Y.concat(X)}return Y}async partial(Z){let J=this.inputVariables.filter((G)=>!(G in Z)),Y={...this.partialVariables??{},...Z};return new Q({...this,inputVariables:J,partialVariables:Y})}static fromTemplate(Z,J){let Y=new V1({prompt:t.fromTemplate(Z,J)});return this.fromMessages([Y])}static fromMessages(Z,J){let Y=Z.reduce((X,$)=>X.concat($ instanceof Q?$.promptMessages:[EQ($,J)]),[]),G=Z.reduce((X,$)=>$ instanceof Q?Object.assign(X,$.partialVariables):X,Object.create(null)),H=new Set;for(let X of Y){if(X instanceof P1)continue;for(let $ of X.inputVariables){if($ in G)continue;H.add($)}}return new this({...J,inputVariables:[...H],promptMessages:Y,partialVariables:G,templateFormat:J?.templateFormat})}};var p4=class Q extends X8{lc_serializable=!1;examples;exampleSelector;examplePrompt;suffix="";exampleSeparator=`
|
|
85
|
+
|
|
86
|
+
`;prefix="";templateFormat="f-string";validateTemplate=!0;constructor(Z){super(Z);if(Object.assign(this,Z),this.examples!==void 0&&this.exampleSelector!==void 0)throw Error("Only one of 'examples' and 'example_selector' should be provided");if(this.examples===void 0&&this.exampleSelector===void 0)throw Error("One of 'examples' and 'example_selector' should be provided");if(this.validateTemplate){let J=this.inputVariables;if(this.partialVariables)J=J.concat(Object.keys(this.partialVariables));z8(this.prefix+this.suffix,this.templateFormat,J)}}_getPromptType(){return"few_shot"}static lc_name(){return"FewShotPromptTemplate"}async getExamples(Z){if(this.examples!==void 0)return this.examples;if(this.exampleSelector!==void 0)return this.exampleSelector.selectExamples(Z);throw Error("One of 'examples' and 'example_selector' should be provided")}async partial(Z){let J=this.inputVariables.filter((G)=>!(G in Z)),Y={...this.partialVariables??{},...Z};return new Q({...this,inputVariables:J,partialVariables:Y})}async format(Z){let J=await this.mergePartialAndUserVariables(Z),Y=await this.getExamples(J),G=await Promise.all(Y.map((H)=>this.examplePrompt.format(H)));return g([this.prefix,...G,this.suffix].join(this.exampleSeparator),this.templateFormat,J)}serialize(){if(this.exampleSelector||!this.examples)throw Error("Serializing an example selector is not currently supported");if(this.outputParser!==void 0)throw Error("Serializing an output parser is not currently supported");return{_type:this._getPromptType(),input_variables:this.inputVariables,example_prompt:this.examplePrompt.serialize(),example_separator:this.exampleSeparator,suffix:this.suffix,prefix:this.prefix,template_format:this.templateFormat,examples:this.examples}}static async deserialize(Z){let{example_prompt:J}=Z;if(!J)throw Error("Missing example prompt");let Y=await t.deserialize(J),G;if(Array.isArray(Z.examples))G=Z.examples;else throw Error("Invalid examples format. Only list or string are supported.");return new Q({inputVariables:Z.input_variables,examplePrompt:Y,examples:G,exampleSeparator:Z.example_separator,prefix:Z.prefix,suffix:Z.suffix,templateFormat:Z.template_format})}},o4=class Q extends t8{lc_serializable=!0;examples;exampleSelector;examplePrompt;suffix="";exampleSeparator=`
|
|
87
|
+
|
|
88
|
+
`;prefix="";templateFormat="f-string";validateTemplate=!0;_getPromptType(){return"few_shot_chat"}static lc_name(){return"FewShotChatMessagePromptTemplate"}constructor(Z){super(Z);if(this.examples=Z.examples,this.examplePrompt=Z.examplePrompt,this.exampleSeparator=Z.exampleSeparator??`
|
|
89
|
+
|
|
90
|
+
`,this.exampleSelector=Z.exampleSelector,this.prefix=Z.prefix??"",this.suffix=Z.suffix??"",this.templateFormat=Z.templateFormat??"f-string",this.validateTemplate=Z.validateTemplate??!0,this.examples!==void 0&&this.exampleSelector!==void 0)throw Error("Only one of 'examples' and 'example_selector' should be provided");if(this.examples===void 0&&this.exampleSelector===void 0)throw Error("One of 'examples' and 'example_selector' should be provided");if(this.validateTemplate){let J=this.inputVariables;if(this.partialVariables)J=J.concat(Object.keys(this.partialVariables));z8(this.prefix+this.suffix,this.templateFormat,J)}}async getExamples(Z){if(this.examples!==void 0)return this.examples;if(this.exampleSelector!==void 0)return this.exampleSelector.selectExamples(Z);throw Error("One of 'examples' and 'example_selector' should be provided")}async formatMessages(Z){let J=await this.mergePartialAndUserVariables(Z),Y=await this.getExamples(J);Y=Y.map((H)=>{let X={};return this.examplePrompt.inputVariables.forEach(($)=>{X[$]=H[$]}),X});let G=[];for(let H of Y){let X=await this.examplePrompt.formatMessages(H);G.push(...X)}return G}async format(Z){let J=await this.mergePartialAndUserVariables(Z),Y=await this.getExamples(J),G=(await Promise.all(Y.map((H)=>this.examplePrompt.formatMessages(H)))).flat().map((H)=>H.content);return g([this.prefix,...G,this.suffix].join(this.exampleSeparator),this.templateFormat,J)}async partial(Z){let J=this.inputVariables.filter((G)=>!(G in Z)),Y={...this.partialVariables??{},...Z};return new Q({...this,inputVariables:J,partialVariables:Y})}};var i4=class Q extends Z8{static lc_name(){return"PipelinePromptTemplate"}pipelinePrompts;finalPrompt;constructor(Z){super({...Z,inputVariables:[]});this.pipelinePrompts=Z.pipelinePrompts,this.finalPrompt=Z.finalPrompt,this.inputVariables=this.computeInputValues()}computeInputValues(){let Z=this.pipelinePrompts.map((Y)=>Y.name),J=this.pipelinePrompts.map((Y)=>Y.prompt.inputVariables.filter((G)=>!Z.includes(G))).flat();return[...new Set(J)]}static extractRequiredInputValues(Z,J){return J.reduce((Y,G)=>{return Y[G]=Z[G],Y},{})}async formatPipelinePrompts(Z){let J=await this.mergePartialAndUserVariables(Z);for(let{name:Y,prompt:G}of this.pipelinePrompts){let H=Q.extractRequiredInputValues(J,G.inputVariables);if(G instanceof b8)J[Y]=await G.formatMessages(H);else J[Y]=await G.format(H)}return Q.extractRequiredInputValues(J,this.finalPrompt.inputVariables)}async formatPromptValue(Z){return this.finalPrompt.formatPromptValue(await this.formatPipelinePrompts(Z))}async format(Z){return this.finalPrompt.format(await this.formatPipelinePrompts(Z))}async partial(Z){let J={...this};return J.inputVariables=this.inputVariables.filter((Y)=>!(Y in Z)),J.partialVariables={...this.partialVariables??{},...Z},new Q(J)}serialize(){throw Error("Not implemented.")}_getPromptType(){return"pipeline"}};function n4(Q){return typeof Q==="object"&&Q!=null&&"withStructuredOutput"in Q&&typeof Q.withStructuredOutput==="function"}function LQ(Q){return typeof Q==="object"&&Q!=null&&"lc_id"in Q&&Array.isArray(Q.lc_id)&&Q.lc_id.join("/")==="langchain_core/runnables/RunnableBinding"}var s4=class Q extends b8{schema;method;lc_namespace=["langchain_core","prompts","structured"];get lc_aliases(){return{...super.lc_aliases,schema:"schema_"}}constructor(Z){super(Z);this.schema=Z.schema,this.method=Z.method}pipe(Z){if(n4(Z))return super.pipe(Z.withStructuredOutput(this.schema));if(LQ(Z)&&n4(Z.bound))return super.pipe(new j8({bound:Z.bound.withStructuredOutput(this.schema,...this.method?[{method:this.method}]:[]),kwargs:Z.kwargs??{},config:Z.config,configFactories:Z.configFactories}));throw Error('Structured prompts need to be piped to a language model that supports the "withStructuredOutput()" method.')}static fromMessagesAndSchema(Z,J,Y){return Q.fromMessages(Z,{schema:J,method:Y})}};var r4=F({AIMessagePromptTemplate:()=>I9,BaseChatPromptTemplate:()=>t8,BaseMessagePromptTemplate:()=>r8,BaseMessageStringPromptTemplate:()=>L9,BasePromptTemplate:()=>Z8,BaseStringPromptTemplate:()=>X8,ChatMessagePromptTemplate:()=>R9,ChatPromptTemplate:()=>b8,DEFAULT_FORMATTER_MAPPING:()=>n8,DEFAULT_PARSER_MAPPING:()=>B9,DictPromptTemplate:()=>s8,FewShotChatMessagePromptTemplate:()=>o4,FewShotPromptTemplate:()=>p4,HumanMessagePromptTemplate:()=>V1,ImagePromptTemplate:()=>k8,MessagesPlaceholder:()=>I1,PipelinePromptTemplate:()=>i4,PromptTemplate:()=>t,StructuredPrompt:()=>s4,SystemMessagePromptTemplate:()=>V9,checkValidTemplate:()=>z8,interpolateFString:()=>D9,interpolateMustache:()=>N9,parseFString:()=>F8,parseMustache:()=>x8,parseTemplate:()=>L8,renderTemplate:()=>g});var t4=F({BaseDocumentCompressor:()=>RQ}),RQ=class{static isBaseDocumentCompressor(Q){return Q?.compressDocuments!==void 0}};var e4=F({BaseRetriever:()=>a8}),a8=class extends y{callbacks;tags;metadata;verbose;constructor(Q){super(Q);this.callbacks=Q?.callbacks,this.tags=Q?.tags??[],this.metadata=Q?.metadata??{},this.verbose=Q?.verbose??!1}_getRelevantDocuments(Q,Z){throw Error("Not implemented!")}async invoke(Q,Z){let J=J8(a4(Z)),Y=await(await e.configure(J.callbacks,this.callbacks,J.tags,this.tags,J.metadata,this.metadata,{verbose:this.verbose}))?.handleRetrieverStart(this.toJSON(),Q,J.runId,void 0,void 0,void 0,J.runName);try{let G=await this._getRelevantDocuments(Q,Y);return await Y?.handleRetrieverEnd(G),G}catch(G){throw await Y?.handleRetrieverError(G),G}}};var Q5=F({BaseStore:()=>Z5,InMemoryStore:()=>PQ}),Z5=class extends s{},PQ=class extends Z5{lc_namespace=["langchain","storage"];store={};async mget(Q){return Q.map((Z)=>this.store[Z])}async mset(Q){for(let[Z,J]of Q)this.store[Z]=J}async mdelete(Q){for(let Z of Q)delete this.store[Z]}async*yieldKeys(Q){let Z=Object.keys(this.store);for(let J of Z)if(Q===void 0||J.startsWith(Q))yield J}};var a={and:"and",or:"or",not:"not"},_={eq:"eq",ne:"ne",lt:"lt",gt:"gt",lte:"lte",gte:"gte"},O1=class{},_1=class{accept(Q){if(this.exprName==="Operation")return Q.visitOperation(this);else if(this.exprName==="Comparison")return Q.visitComparison(this);else if(this.exprName==="StructuredQuery")return Q.visitStructuredQuery(this);else throw Error("Unknown Expression type")}},T1=class extends _1{},J5=class extends T1{exprName="Comparison";constructor(Q,Z,J){super();this.comparator=Q,this.attribute=Z,this.value=J}},Y5=class extends T1{exprName="Operation";constructor(Q,Z){super();this.operator=Q,this.args=Z}},G5=class extends _1{exprName="StructuredQuery";constructor(Q,Z){super();this.query=Q,this.filter=Z}};function O9(Q){return Q&&typeof Q==="object"&&!Array.isArray(Q)}function u(Q){if(!Q)return!0;if(typeof Q==="string"&&Q.length>0)return!1;if(typeof Q==="function")return!1;return O9(Q)&&Object.keys(Q).length===0}function _9(Q){if(typeof Q==="number")return Q%1===0;else if(typeof Q==="string"){let Z=parseInt(Q,10);return!Number.isNaN(Z)&&Z%1===0&&Z.toString()===Q}return!1}function T9(Q){if(typeof Q==="number")return Q%1!==0;else if(typeof Q==="string"){let Z=parseFloat(Q);return!Number.isNaN(Z)&&Z%1!==0&&Z.toString()===Q}return!1}function j9(Q){return typeof Q==="string"&&(Number.isNaN(parseFloat(Q))||parseFloat(Q).toString()!==Q)}function C9(Q){return typeof Q==="boolean"}function f8(Q){let Z;if(j9(Q))Z=Q;else if(_9(Q))Z=parseInt(Q,10);else if(T9(Q))Z=parseFloat(Q);else if(C9(Q))Z=Boolean(Q);else throw Error("Unsupported value type");return Z}var e8=class extends O1{},H5=class extends e8{allowedOperators;allowedComparators;constructor(Q){super();this.allowedOperators=Q?.allowedOperators??[a.and,a.or],this.allowedComparators=Q?.allowedComparators??[_.eq,_.ne,_.gt,_.gte,_.lt,_.lte]}formatFunction(Q){if(Q in _){if(this.allowedComparators.length>0&&this.allowedComparators.indexOf(Q)===-1)throw Error(`Comparator ${Q} not allowed. Allowed comparators: ${this.allowedComparators.join(", ")}`)}else if(Q in a){if(this.allowedOperators.length>0&&this.allowedOperators.indexOf(Q)===-1)throw Error(`Operator ${Q} not allowed. Allowed operators: ${this.allowedOperators.join(", ")}`)}else throw Error("Unknown comparator or operator");return`$${Q}`}visitOperation(Q){let Z=Q.args?.map((J)=>J.accept(this));return{[this.formatFunction(Q.operator)]:Z}}visitComparison(Q){return{[Q.attribute]:{[this.formatFunction(Q.comparator)]:f8(Q.value)}}}visitStructuredQuery(Q){let Z={};if(Q.filter)Z={filter:Q.filter.accept(this)};return Z}mergeFilters(Q,Z,J="and",Y=!1){if(u(Q)&&u(Z))return;if(u(Q)||J==="replace"){if(u(Z))return;return Z}if(u(Z)){if(Y)return Q;if(J==="and")return;return Q}if(J==="and")return{$and:[Q,Z]};else if(J==="or")return{$or:[Q,Z]};else throw Error("Unknown merge type")}};var W5=class extends e8{allowedOperators=[a.and,a.or];allowedComparators=[_.eq,_.ne,_.gt,_.gte,_.lt,_.lte];formatFunction(){throw Error("Not implemented")}getAllowedComparatorsForType(Q){switch(Q){case"string":return[_.eq,_.ne,_.gt,_.gte,_.lt,_.lte];case"number":return[_.eq,_.ne,_.gt,_.gte,_.lt,_.lte];case"boolean":return[_.eq,_.ne];default:throw Error(`Unsupported data type: ${Q}`)}}getComparatorFunction(Q){switch(Q){case _.eq:return(Z,J)=>Z===J;case _.ne:return(Z,J)=>Z!==J;case _.gt:return(Z,J)=>Z>J;case _.gte:return(Z,J)=>Z>=J;case _.lt:return(Z,J)=>Z<J;case _.lte:return(Z,J)=>Z<=J;default:throw Error("Unknown comparator")}}getOperatorFunction(Q){switch(Q){case a.and:return(Z,J)=>Z&&J;case a.or:return(Z,J)=>Z||J;default:throw Error("Unknown operator")}}visitOperation(Q){let{operator:Z,args:J}=Q;if(this.allowedOperators.includes(Z)){let Y=this.getOperatorFunction(Z);return(G)=>{if(!J)return!0;return J.reduce((H,X)=>{let $=X.accept(this);if(typeof $==="function")return Y(H,$(G));else throw Error("Filter is not a function")},!0)}}else throw Error("Operator not allowed")}visitComparison(Q){let{comparator:Z,attribute:J,value:Y}=Q,G=[_.ne];if(this.allowedComparators.includes(Z)){if(!this.getAllowedComparatorsForType(typeof Y).includes(Z))throw Error(`'${Z}' comparator not allowed to be used with ${typeof Y}`);let H=this.getComparatorFunction(Z);return(X)=>{let $=X.metadata[J];if($===void 0){if(G.includes(Z))return!0;return!1}return H($,f8(Y))}}else throw Error("Comparator not allowed")}visitStructuredQuery(Q){if(!Q.filter)return{};let Z=Q.filter?.accept(this);if(typeof Z!=="function")throw Error("Structured query filter is not a function");return{filter:Z}}mergeFilters(Q,Z,J="and"){if(u(Q)&&u(Z))return;if(u(Q)||J==="replace"){if(u(Z))return;return Z}if(u(Z)){if(J==="and")return;return Q}if(J==="and")return(Y)=>Q(Y)&&Z(Y);else if(J==="or")return(Y)=>Q(Y)||Z(Y);else throw Error("Unknown merge type")}};var X5=F({BaseTranslator:()=>e8,BasicTranslator:()=>H5,Comparators:()=>_,Comparison:()=>J5,Expression:()=>_1,FilterDirective:()=>T1,FunctionalTranslator:()=>W5,Operation:()=>Y5,Operators:()=>a,StructuredQuery:()=>G5,Visitor:()=>O1,castValue:()=>f8,isBoolean:()=>C9,isFilterEmpty:()=>u,isFloat:()=>T9,isInt:()=>_9,isObject:()=>O9,isString:()=>j9});var z5=F({RunCollectorCallbackHandler:()=>IQ}),IQ=class extends h8{name="run_collector";exampleId;tracedRuns;constructor({exampleId:Q}={}){super({_awaitHandler:!0});this.exampleId=Q,this.tracedRuns=[]}async persistRun(Q){let Z={...Q};Z.reference_example_id=this.exampleId,this.tracedRuns.push(Z)}};var $5=F({});var K5=F({chunkArray:()=>VQ}),VQ=(Q,Z)=>Q.reduce((J,Y,G)=>{let H=Math.floor(G/Z);return J[H]=(J[H]||[]).concat([Y]),J},[]);var q5=F({context:()=>OQ});function OQ(Q,...Z){let J=Q.raw,Y="";for(let G=0;G<J.length;G++){let H=J[G].replace(/\\\n[ \t]*/g,"").replace(/\\`/g,"`").replace(/\\\$/g,"$").replace(/\\\{/g,"{");if(Y+=H,G<Z.length){let X=_Q(Z[G],Y);Y+=typeof X==="string"?X:JSON.stringify(X)}}return Y=TQ(Y),Y=Y.trim(),Y=Y.replace(/\\n/g,`
|
|
91
|
+
`),Y}function _Q(Q,Z){if(typeof Q!=="string"||!Q.includes(`
|
|
92
|
+
`))return Q;let J=Z.slice(Z.lastIndexOf(`
|
|
93
|
+
`)+1).match(/^(\s+)/);if(J){let Y=J[1];return Q.replace(/\n/g,`
|
|
94
|
+
${Y}`)}return Q}function TQ(Q){let Z=Q.split(`
|
|
95
|
+
`),J=null;for(let Y of Z){let G=Y.match(/^(\s+)\S+/);if(G){let H=G[1].length;if(J===null)J=H;else J=Math.min(J,H)}}if(J===null)return Q;return Z.map((Y)=>Y[0]===" "||Y[0]==="\t"?Y.slice(J):Y).join(`
|
|
96
|
+
`)}var w5=F({EventStreamContentType:()=>jQ,convertEventStreamToIterableReadableDataStream:()=>MQ,getBytes:()=>D5,getLines:()=>N5,getMessages:()=>B5}),jQ="text/event-stream";async function D5(Q,Z){if(Q instanceof ReadableStream){let J=Q.getReader();while(!0){let Y=await J.read();if(Y.done){Z(new Uint8Array,!0);break}Z(Y.value)}}else try{for await(let J of Q)Z(new Uint8Array(J));Z(new Uint8Array,!0)}catch(J){throw Error(["Parsing event source stream failed.","Ensure your implementation of fetch returns a web or Node readable stream.",`Error: ${J.message}`].join(`
|
|
97
|
+
`))}}var g8=function(Q){return Q[Q.NewLine=10]="NewLine",Q[Q.CarriageReturn=13]="CarriageReturn",Q[Q.Space=32]="Space",Q[Q.Colon=58]="Colon",Q}(g8||{});function N5(Q){let Z,J,Y,G=!1;return function(X,$){if($){Q(X,0,!0);return}if(Z===void 0)Z=X,J=0,Y=-1;else Z=CQ(Z,X);let U=Z.length,w=0;while(J<U){if(G){if(Z[J]===g8.NewLine)w=++J;G=!1}let D=-1;for(;J<U&&D===-1;++J)switch(Z[J]){case g8.Colon:if(Y===-1)Y=J-w;break;case g8.CarriageReturn:G=!0;case g8.NewLine:D=J;break}if(D===-1)break;Q(Z.subarray(w,D),Y),w=J,Y=-1}if(w===U)Z=void 0;else if(w!==0)Z=Z.subarray(w),J-=w}}function B5(Q,Z,J){let Y=M9(),G=new TextDecoder;return function(X,$,U){if(U){if(!SQ(Y))Q?.(Y),Y=M9();return}if(X.length===0)Q?.(Y),Y=M9();else if($>0){let w=G.decode(X.subarray(0,$)),D=$+(X[$+1]===g8.Space?2:1),L=G.decode(X.subarray(D));switch(w){case"data":Y.data=Y.data?Y.data+`
|
|
98
|
+
`+L:L;break;case"event":Y.event=L;break;case"id":Z?.(Y.id=L);break;case"retry":{let A=parseInt(L,10);if(!Number.isNaN(A))J?.(Y.retry=A);break}}}}}function CQ(Q,Z){let J=new Uint8Array(Q.length+Z.length);return J.set(Q),J.set(Z,Q.length),J}function M9(){return{data:"",event:"",id:"",retry:void 0}}function MQ(Q,Z){let J=new ReadableStream({async start(Y){let G=B5((X)=>{if(X.event==="error")throw Error(X.data??"Unspecified event streaming error.");else if(X.event==="metadata")Z?.(X);else if(X.data)Y.enqueue(X.data)});await D5(Q,N5((X,$,U)=>{if(G(X,$,U),U)Y.close()}))}});return U5.fromReadableStream(J)}function SQ(Q){return Q.data===""&&Q.event===""&&Q.id===""&&Q.retry===void 0}var A5=F({});var R5=F({convertToOpenAIFunction:()=>P5,convertToOpenAITool:()=>yQ,isLangChainTool:()=>S9,isRunnableToolLike:()=>F5,isStructuredTool:()=>E5,isStructuredToolParams:()=>L5});function P5(Q,Z){let J=typeof Z==="number"?void 0:Z;return{name:Q.name,description:Q.description,parameters:h(Q.schema),...J?.strict!==void 0?{strict:J.strict}:{}}}function yQ(Q,Z){let J=typeof Z==="number"?void 0:Z,Y;if(S9(Q))Y={type:"function",function:P5(Q)};else Y=Q;if(J?.strict!==void 0)Y.function.strict=J.strict;return Y}function j1(Q,Z){let J=0,Y=0,G=0;for(let H=0;H<Q.length;H++)J+=Q[H]*Z[H],Y+=Q[H]*Q[H],G+=Z[H]*Z[H];return J/(Math.sqrt(Y)*Math.sqrt(G))}function I5(Q,Z){let J=0;for(let Y=0;Y<Q.length;Y++)J+=Q[Y]*Z[Y];return J}function vQ(Q,Z){let J=0;for(let Y=0;Y<Q.length;Y++)J+=(Q[Y]-Z[Y])*(Q[Y]-Z[Y]);return J}function V5(Q,Z){return Math.sqrt(vQ(Q,Z))}var O5=F({cosineSimilarity:()=>y9,euclideanDistance:()=>bQ,innerProduct:()=>kQ,matrixFunc:()=>C1,maximalMarginalRelevance:()=>fQ,normalize:()=>xQ});function C1(Q,Z,J){if(Q.length===0||Q[0].length===0||Z.length===0||Z[0].length===0)return[[]];if(Q[0].length!==Z[0].length)throw Error(`Number of columns in X and Y must be the same. X has shape ${[Q.length,Q[0].length]} and Y has shape ${[Z.length,Z[0].length]}.`);return Q.map((Y)=>Z.map((G)=>J(Y,G)).map((G)=>Number.isNaN(G)?0:G))}function xQ(Q,Z=!1){let J=hQ(Q);return Q.map((Y)=>Y.map((G)=>Z?1-G/J:G/J))}function y9(Q,Z){return C1(Q,Z,j1)}function kQ(Q,Z){return C1(Q,Z,I5)}function bQ(Q,Z){return C1(Q,Z,V5)}function fQ(Q,Z,J=0.5,Y=4){if(Math.min(Y,Z.length)<=0)return[];let G=y9(Array.isArray(Q[0])?Q:[Q],Z)[0],H=_5(G).maxIndex,X=[Z[H]],$=[H];while($.length<Math.min(Y,Z.length)){let U=-1/0,w=-1,D=y9(Z,X);G.forEach((L,A)=>{if($.includes(A))return;let E=Math.max(...D[A]),B=J*L-(1-J)*E;if(B>U)U=B,w=A}),X.push(Z[w]),$.push(w)}return $}function _5(Q){if(Q.length===0)return{maxIndex:-1,maxValue:NaN};let Z=Q[0],J=0;for(let Y=1;Y<Q.length;Y+=1)if(Q[Y]>Z)J=Y,Z=Q[Y];return{maxIndex:J,maxValue:Z}}function hQ(Q){return Q.reduce((Z,J)=>Math.max(Z,_5(J).maxValue),0)}var T5=F({isCloudMetadata:()=>v9,isLocalhost:()=>x9,isPrivateIp:()=>y5,isSafeUrl:()=>oQ,isSameOrigin:()=>iQ,validateSafeUrl:()=>v5}),gQ=["10.0.0.0/8","172.16.0.0/12","192.168.0.0/16","127.0.0.0/8","169.254.0.0/16","0.0.0.0/8","::1/128","fc00::/7","fe80::/10","ff00::/8"],dQ=["169.254.169.254","169.254.170.2","100.100.100.200"],mQ=["metadata.google.internal","metadata","instance-data"],cQ=["localhost","localhost.localdomain"],uQ=/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/;function j5(Q){return uQ.test(Q)}function M1(Q){return S5(Q)!==null}function C5(Q){return j5(Q)||M1(Q)}function M5(Q){if(j5(Q))return Q.split(".").map((Z)=>parseInt(Z,10));else if(M1(Q)){let Z=S5(Q);if(!Z)return null;let J=Z.split(":"),Y=[];for(let G of J)Y.push(parseInt(G,16));return Y}return null}function S5(Q){if(!Q||typeof Q!=="string")return null;if(!Q.includes(":"))return null;if(!/^[0-9a-fA-F:]+$/.test(Q))return null;let Z=Q;if(Z.includes("::")){let Y=Z.split("::");if(Y.length>2)return null;let[G,H]=Y,X=G?G.split(":"):[],$=H?H.split(":"):[],U=8-(X.length+$.length);if(U<0)return null;let w=Array(U).fill("0");Z=[...X,...w,...$].filter((D)=>D!=="").join(":")}let J=Z.split(":");if(J.length!==8)return null;for(let Y of J){if(Y.length===0||Y.length>4)return null;if(!/^[0-9a-fA-F]+$/.test(Y))return null}return J.map((Y)=>Y.padStart(4,"0").toLowerCase()).join(":")}function lQ(Q){let[Z,J]=Q.split("/");if(!Z||!J)return null;let Y=M5(Z);if(!Y)return null;let G=parseInt(J,10);if(isNaN(G))return null;let H=M1(Z);if(H&&G>128)return null;if(!H&&G>32)return null;return{addr:Y,prefixLen:G,isIpv6:H}}function pQ(Q,Z){let J=M5(Q);if(!J)return!1;let Y=lQ(Z);if(!Y)return!1;let G=M1(Q);if(G!==Y.isIpv6)return!1;let{addr:H,prefixLen:X}=Y;if(G)for(let $=0;$<Math.ceil(X/16);$++){let U=65535<<16-Math.min(16,X-$*16)&65535;if((J[$]&U)!==(H[$]&U))return!1}else for(let $=0;$<Math.ceil(X/8);$++){let U=255<<8-Math.min(8,X-$*8)&255;if((J[$]&U)!==(H[$]&U))return!1}return!0}function y5(Q){if(!C5(Q))return!1;for(let Z of gQ)if(pQ(Q,Z))return!0;return!1}function v9(Q,Z){if(dQ.includes(Z||""))return!0;let J=Q.toLowerCase();if(mQ.includes(J))return!0;return!1}function x9(Q,Z){if(Z){if(Z==="127.0.0.1"||Z==="::1"||Z==="0.0.0.0")return!0;if(Z.startsWith("127."))return!0}let J=Q.toLowerCase();if(cQ.includes(J))return!0;return!1}function v5(Q,Z){let J=Z?.allowPrivate??!1,Y=Z?.allowHttp??!1;try{let G;try{G=new URL(Q)}catch{throw Error(`Invalid URL: ${Q}`)}let H=G.hostname;if(!H)throw Error("URL missing hostname.");if(v9(H))throw Error(`URL points to cloud metadata endpoint: ${H}`);if(x9(H)){if(!J)throw Error(`URL points to localhost: ${H}`);return Q}let X=G.protocol;if(X!=="http:"&&X!=="https:")throw Error(`Invalid URL scheme: ${X}. Only http and https are allowed.`);if(X==="http:"&&!Y)throw Error("HTTP scheme not allowed. Use HTTPS or set allowHttp: true.");if(C5(H)){let $=H;if(x9(H,$)){if(!J)throw Error(`URL points to localhost: ${H}`);return Q}if(v9(H,$))throw Error(`URL resolves to cloud metadata IP: ${$} (${H})`);if(y5($)){if(!J)throw Error(`URL resolves to private IP: ${$} (${H}). Set allowPrivate: true to allow.`)}return Q}return Q}catch(G){if(G&&typeof G==="object"&&"message"in G)throw G;throw Error(`URL validation failed: ${G}`)}}function oQ(Q,Z){try{return v5(Q,Z),!0}catch{return!1}}function iQ(Q,Z){try{return new URL(Q).origin===new URL(Z).origin}catch{return!1}}var x5=F({SaveableVectorStore:()=>nQ,VectorStore:()=>y1,VectorStoreRetriever:()=>S1}),S1=class extends a8{static lc_name(){return"VectorStoreRetriever"}get lc_namespace(){return["langchain_core","vectorstores"]}vectorStore;k=4;searchType="similarity";searchKwargs;filter;_vectorstoreType(){return this.vectorStore._vectorstoreType()}constructor(Q){super(Q);if(this.vectorStore=Q.vectorStore,this.k=Q.k??this.k,this.searchType=Q.searchType??this.searchType,this.filter=Q.filter,Q.searchType==="mmr")this.searchKwargs=Q.searchKwargs}async _getRelevantDocuments(Q,Z){if(this.searchType==="mmr"){if(typeof this.vectorStore.maxMarginalRelevanceSearch!=="function")throw Error(`The vector store backing this retriever, ${this._vectorstoreType()} does not support max marginal relevance search.`);return this.vectorStore.maxMarginalRelevanceSearch(Q,{k:this.k,filter:this.filter,...this.searchKwargs},Z?.getChild("vectorstore"))}return this.vectorStore.similaritySearch(Q,this.k,this.filter,Z?.getChild("vectorstore"))}async addDocuments(Q,Z){return this.vectorStore.addDocuments(Q,Z)}},y1=class extends s{lc_namespace=["langchain","vectorstores",this._vectorstoreType()];embeddings;constructor(Q,Z){super(Z);this.embeddings=Q}async delete(Q){throw Error("Not implemented.")}async similaritySearch(Q,Z=4,J=void 0,Y=void 0){return(await this.similaritySearchVectorWithScore(await this.embeddings.embedQuery(Q),Z,J)).map((G)=>G[0])}async similaritySearchWithScore(Q,Z=4,J=void 0,Y=void 0){return this.similaritySearchVectorWithScore(await this.embeddings.embedQuery(Q),Z,J)}static fromTexts(Q,Z,J,Y){throw Error("the Langchain vectorstore implementation you are using forgot to override this, please report a bug")}static fromDocuments(Q,Z,J){throw Error("the Langchain vectorstore implementation you are using forgot to override this, please report a bug")}asRetriever(Q,Z,J,Y,G,H){if(typeof Q==="number")return new S1({vectorStore:this,k:Q,filter:Z,tags:[...Y??[],this._vectorstoreType()],metadata:G,verbose:H,callbacks:J});else{let X={vectorStore:this,k:Q?.k,filter:Q?.filter,tags:[...Q?.tags??[],this._vectorstoreType()],metadata:Q?.metadata,verbose:Q?.verbose,callbacks:Q?.callbacks,searchType:Q?.searchType};if(Q?.searchType==="mmr")return new S1({...X,searchKwargs:Q.searchKwargs});return new S1({...X})}}},nQ=class extends y1{static load(Q,Z){throw Error("Not implemented")}};var k5=class extends _8{_combineLLMOutput(){return[]}_llmType(){return"fake"}async _generate(Q,Z,J){if(Z?.stop?.length)return{generations:[{message:new f(Z.stop[0]),text:Z.stop[0]}]};let Y=Q.map((G)=>{if(typeof G.content==="string")return G.content;return JSON.stringify(G.content,null,2)}).join(`
|
|
99
|
+
`);return await J?.handleLLMNewToken(Y),{generations:[{message:new f(Y),text:Y}],llmOutput:{}}}},b5=class Q extends _8{sleep=50;responses=[];chunks=[];toolStyle="openai";thrownErrorString;tools=[];constructor({sleep:Z=50,responses:J=[],chunks:Y=[],toolStyle:G="openai",thrownErrorString:H,...X}){super(X);this.sleep=Z,this.responses=J,this.chunks=Y,this.toolStyle=G,this.thrownErrorString=H}_llmType(){return"fake"}bindTools(Z){let J=[...this.tools,...Z],Y=J.map((X)=>{switch(this.toolStyle){case"openai":return{type:"function",function:{name:X.name,description:X.description,parameters:h(X.schema)}};case"anthropic":return{name:X.name,description:X.description,input_schema:h(X.schema)};case"bedrock":return{toolSpec:{name:X.name,description:X.description,inputSchema:h(X.schema)}};case"google":return{name:X.name,description:X.description,parameters:h(X.schema)};default:throw Error(`Unsupported tool style: ${this.toolStyle}`)}}),G=this.toolStyle==="google"?[{functionDeclarations:Y}]:Y,H=new Q({sleep:this.sleep,responses:this.responses,chunks:this.chunks,toolStyle:this.toolStyle,thrownErrorString:this.thrownErrorString});return H.tools=J,H.withConfig({tools:G})}async _generate(Z,J,Y){if(this.thrownErrorString)throw Error(this.thrownErrorString);return{generations:[{text:"",message:new f({content:this.responses?.[0]?.content??Z[0].content??"",tool_calls:this.chunks?.[0]?.tool_calls})}]}}async*_streamResponseChunks(Z,J,Y){if(this.thrownErrorString)throw Error(this.thrownErrorString);if(this.chunks?.length){for(let X of this.chunks){let $=new E8({message:new O8({content:X.content,tool_calls:X.tool_calls,additional_kwargs:X.additional_kwargs??{}}),text:X.content?.toString()??""});if(J.signal?.aborted)break;yield $,await Y?.handleLLMNewToken(X.content,void 0,void 0,void 0,void 0,{chunk:$})}return}let G=this.responses?.[0]??new f(typeof Z[0].content==="string"?Z[0].content:""),H=typeof G.content==="string"?G.content:"";for(let X of H){await new Promise((U)=>setTimeout(U,this.sleep));let $=new E8({message:new O8({content:X}),text:X});if(J.signal?.aborted)break;yield $,await Y?.handleLLMNewToken(X,void 0,void 0,void 0,void 0,{chunk:$})}}},f5=class Q extends _8{static lc_name(){return"FakeListChatModel"}lc_serializable=!0;responses;i=0;sleep;emitCustomEvent=!1;generationInfo;tools=[];toolStyle="openai";constructor(Z){super(Z);let{responses:J,sleep:Y,emitCustomEvent:G,generationInfo:H}=Z;this.responses=J,this.sleep=Y,this.emitCustomEvent=G??this.emitCustomEvent,this.generationInfo=H}_combineLLMOutput(){return[]}_llmType(){return"fake-list"}async _generate(Z,J,Y){if(await this._sleepIfRequested(),J?.thrownErrorString)throw Error(J.thrownErrorString);if(this.emitCustomEvent)await Y?.handleCustomEvent("some_test_event",{someval:!0});if(J?.stop?.length)return{generations:[this._formatGeneration(J.stop[0])]};else{let G=this._currentResponse();return this._incrementResponse(),{generations:[this._formatGeneration(G)],llmOutput:{}}}}_formatGeneration(Z){return{message:new f(Z),text:Z}}async*_streamResponseChunks(Z,J,Y){let G=this._currentResponse();if(this._incrementResponse(),this.emitCustomEvent)await Y?.handleCustomEvent("some_test_event",{someval:!0});let H=[...G];for(let X=0;X<H.length;X++){let $=H[X],U=X===H.length-1;if(await this._sleepIfRequested(),J?.thrownErrorString)throw Error(J.thrownErrorString);let w=this._createResponseChunk($,U?this.generationInfo:void 0);if(J.signal?.aborted)break;yield w,Y?.handleLLMNewToken($)}}async _sleepIfRequested(){if(this.sleep!==void 0)await this._sleep()}async _sleep(){return new Promise((Z)=>{setTimeout(()=>Z(),this.sleep)})}_createResponseChunk(Z,J){return new E8({message:new O8({content:Z}),text:Z,generationInfo:J})}_currentResponse(){return this.responses[this.i]}_incrementResponse(){if(this.i<this.responses.length-1)this.i+=1;else this.i=0}bindTools(Z){let J=[...this.tools,...Z],Y=J.map((X)=>{switch(this.toolStyle){case"openai":return{type:"function",function:{name:X.name,description:X.description,parameters:h(X.schema)}};case"anthropic":return{name:X.name,description:X.description,input_schema:h(X.schema)};case"bedrock":return{toolSpec:{name:X.name,description:X.description,inputSchema:h(X.schema)}};case"google":return{name:X.name,description:X.description,parameters:h(X.schema)};default:throw Error(`Unsupported tool style: ${this.toolStyle}`)}}),G=this.toolStyle==="google"?[{functionDeclarations:Y}]:Y,H=new Q({responses:this.responses,sleep:this.sleep,emitCustomEvent:this.emitCustomEvent,generationInfo:this.generationInfo});return H.tools=J,H.toolStyle=this.toolStyle,H.i=this.i,H.withConfig({tools:G})}withStructuredOutput(Z,J){return q8.from(async(Y)=>{let G=await this.invoke(Y);if(G.tool_calls?.[0]?.args)return G.tool_calls[0].args;if(typeof G.content==="string")return JSON.parse(G.content);throw Error("No structured output found")})}};var h5=class extends X1{vectorSize;constructor(Q){super(Q??{});this.vectorSize=Q?.vectorSize??4}async embedDocuments(Q){return Promise.all(Q.map((Z)=>this.embedQuery(Z)))}async embedQuery(Q){let Z=Q;Z=Z.toLowerCase().replaceAll(/[^a-z ]/g,"");let J=Z.length%this.vectorSize,Y=J===0?0:this.vectorSize-J,G=Z.length+Y;Z=Z.padEnd(G," ");let H=Z.length/this.vectorSize,X=[];for(let $=0;$<Z.length;$+=H)X.push(Z.slice($,$+H));return X.map(($)=>{let U=0;for(let w=0;w<$.length;w+=1)U+=$===" "?0:$.charCodeAt(w);return U%26/26})}},g5=class extends X1{constructor(Q){super(Q??{})}embedDocuments(Q){return Promise.resolve(Q.map(()=>[0.1,0.2,0.3,0.4]))}embedQuery(Q){return Promise.resolve([0.1,0.2,0.3,0.4])}};var d5=class extends A1{response;thrownErrorString;constructor(Q){super(Q);this.response=Q.response,this.thrownErrorString=Q.thrownErrorString}_llmType(){return"fake"}async _call(Q,Z,J){if(this.thrownErrorString)throw Error(this.thrownErrorString);let Y=this.response??Q;return await J?.handleLLMNewToken(Y),Y}},m5=class extends A1{sleep=50;responses;thrownErrorString;constructor(Q){super(Q);this.sleep=Q.sleep??this.sleep,this.responses=Q.responses,this.thrownErrorString=Q.thrownErrorString}_llmType(){return"fake"}async _call(Q){if(this.thrownErrorString)throw Error(this.thrownErrorString);let Z=this.responses?.[0];return this.responses=this.responses?.slice(1),Z??Q}async*_streamResponseChunks(Q,Z,J){if(this.thrownErrorString)throw Error(this.thrownErrorString);let Y=this.responses?.[0];this.responses=this.responses?.slice(1);for(let G of Y??Q)await new Promise((H)=>setTimeout(H,this.sleep)),yield{text:G,generationInfo:{}},await J?.handleLLMNewToken(G)}};var c5=class extends i1{lc_namespace=["langchain_core","message","fake"];messages=[];constructor(){super()}async getMessages(){return this.messages}async addMessage(Q){this.messages.push(Q)}async addUserMessage(Q){this.messages.push(new $8(Q))}async addAIMessage(Q){this.messages.push(new f(Q))}async clear(){this.messages=[]}},u5=class extends W1{lc_namespace=["langchain_core","message","fake"];messages=[];constructor(){super()}async addMessage(Q){this.messages.push(Q)}async getMessages(){return this.messages}},l5=class extends h8{name="fake_tracer";runs=[];constructor(){super()}persistRun(Q){return this.runs.push(Q),Promise.resolve()}};var p5=class extends H8{lc_namespace=["tests","fake"];getFormatInstructions(){return""}async parse(Q){return Q.split(",").map((Z)=>Z.trim())}};var o5=class extends a8{lc_namespace=["test","fake"];output=[new p({pageContent:"foo"}),new p({pageContent:"bar"})];constructor(Q){super();this.output=Q?.output??this.output}async _getRelevantDocuments(Q){return this.output}};var i5=class extends y{lc_namespace=["tests","fake"];returnOptions;constructor(Q){super(Q);this.returnOptions=Q.returnOptions}async invoke(Q,Z){if(this.returnOptions)return Z??{};return{input:Q}}};var s5=class extends n5{name;description;schema;constructor(Q){super(Q);this.name=Q.name,this.description=Q.description,this.schema=Q.schema}async _call(Q,Z){return JSON.stringify(Q)}};var r5=class extends h8{runPromiseResolver;runPromise;name="single_run_extractor";constructor(){super();this.runPromise=new Promise((Q)=>{this.runPromiseResolver=Q})}async persistRun(Q){this.runPromiseResolver(Q)}async extract(){return this.runPromise}};var t5=class Q extends y1{memoryVectors=[];similarity;_vectorstoreType(){return"memory"}constructor(Z,{similarity:J,...Y}={}){super(Z,Y);this.similarity=J??j1}async addDocuments(Z){let J=Z.map(({pageContent:Y})=>Y);return this.addVectors(await this.embeddings.embedDocuments(J),Z)}async addVectors(Z,J){let Y=Z.map((G,H)=>({content:J[H].pageContent,embedding:G,metadata:J[H].metadata}));this.memoryVectors=this.memoryVectors.concat(Y)}async similaritySearchVectorWithScore(Z,J,Y){let G=(X)=>{if(!Y)return!0;return Y(new p({metadata:X.metadata,pageContent:X.content}))},H=this.memoryVectors.filter(G);return H.map((X,$)=>({similarity:this.similarity(Z,X.embedding),index:$})).sort((X,$)=>X.similarity>$.similarity?-1:0).slice(0,J).map((X)=>[new p({metadata:H[X.index].metadata,pageContent:H[X.index].content}),X.similarity])}static async fromTexts(Z,J,Y,G){let H=[];for(let X=0;X<Z.length;X+=1){let $=Array.isArray(J)?J[X]:J,U=new p({pageContent:Z[X],metadata:$});H.push(U)}return Q.fromDocuments(H,Y,G)}static async fromDocuments(Z,J,Y){let G=new this(J,Y);return await G.addDocuments(Z),G}static async fromExistingIndex(Z,J){return new this(Z,J)}};var a5=F({FakeChatMessageHistory:()=>c5,FakeChatModel:()=>k5,FakeEmbeddings:()=>g5,FakeLLM:()=>d5,FakeListChatMessageHistory:()=>u5,FakeListChatModel:()=>f5,FakeRetriever:()=>o5,FakeRunnable:()=>i5,FakeSplitIntoListParser:()=>p5,FakeStreamingChatModel:()=>b5,FakeStreamingLLM:()=>m5,FakeTool:()=>s5,FakeTracer:()=>l5,FakeVectorStore:()=>t5,SingleRunExtractor:()=>r5,SyntheticEmbeddings:()=>h5});var I6=F({agents:()=>V0,caches:()=>E6,callbacks__base:()=>Y6,callbacks__manager:()=>z6,callbacks__promises:()=>X6,chat_history:()=>O0,document_loaders__base:()=>j0,document_loaders__langsmith:()=>M0,documents:()=>T0,embeddings:()=>y0,errors:()=>e5,example_selectors:()=>g0,index:()=>I0,indexing:()=>u0,language_models__base:()=>R6,language_models__chat_models:()=>n0,language_models__llms:()=>s0,language_models__profile:()=>t0,load__serializable:()=>Q6,memory:()=>a0,messages:()=>B6,messages__tool:()=>Z6,output_parsers:()=>M4,output_parsers__openai_functions:()=>y4,output_parsers__openai_tools:()=>b4,outputs:()=>q6,prompt_values:()=>F6,prompts:()=>r4,retrievers:()=>e4,retrievers__document_compressors:()=>t4,runnables:()=>w4,runnables__graph:()=>N6,singletons:()=>$6,stores:()=>Q5,structured_query:()=>X5,tools:()=>P6,tracers__base:()=>G6,tracers__console:()=>H6,tracers__log_stream:()=>w6,tracers__run_collector:()=>z5,tracers__tracer_langchain:()=>W6,types__stream:()=>$5,utils__async_caller:()=>D6,utils__chunk_array:()=>K5,utils__context:()=>q5,utils__env:()=>J6,utils__event_source_parse:()=>w5,utils__format:()=>A5,utils__function_calling:()=>R5,utils__hash:()=>A6,utils__json_patch:()=>N4,utils__json_schema:()=>U6,utils__math:()=>O5,utils__ssrf:()=>T5,utils__stream:()=>K6,utils__testing:()=>a5,utils__tiktoken:()=>L6,utils__types:()=>A0,vectorstores:()=>x5});var sQ=50;function rQ(Q){let Z={};for(let J=Q;J&&J.prototype;J=Object.getPrototypeOf(J))Object.assign(Z,Reflect.get(J.prototype,"lc_aliases"));return Object.entries(Z).reduce((J,[Y,G])=>{return J[G]=Y,J},{})}async function v1(Q){let{optionalImportsMap:Z,optionalImportEntrypoints:J,importMap:Y,secretsMap:G,secretsFromEnv:H,path:X,depth:$,maxDepth:U}=this,w=X.join(".");if($>U)throw Error(`Maximum recursion depth (${U}) exceeded during deserialization. This may indicate a malicious payload or you may need to increase maxDepth.`);if(typeof Q!=="object"||Q==null)return Q;if(Array.isArray(Q))return Promise.all(Q.map((A,E)=>v1.call({...this,path:[...X,`${E}`],depth:$+1},A)));let D=Q;if(_6(D))return T6(D);if("lc"in D&&"type"in D&&"id"in D&&D.lc===1&&D.type==="secret"){let[A]=D.id;if(A in G)return G[A];else if(H){let E=U1(A);if(E)return E}throw Error(`Missing secret "${A}" at ${w}`)}if("lc"in D&&"type"in D&&"id"in D&&D.lc===1&&D.type==="not_implemented"){let E=JSON.stringify(D);throw Error(`Trying to load an object that doesn't implement serialization: ${w} -> ${E}`)}if("lc"in D&&"type"in D&&"id"in D&&"kwargs"in D&&D.lc===1&&D.type==="constructor"){let A=D,E=JSON.stringify(A),[B,...R]=A.id.slice().reverse(),P=R.reverse(),V={langchain_core:I6,langchain:Y},I=null,O=[P.join("/")];if(P[0]==="langchain_community")O.push(["langchain",...P.slice(1)].join("/"));let j=O.find((k)=>(k in Z));if(P0.concat(J).includes(P.join("/"))||j)if(j!==void 0)I=await Z[j];else throw Error(`Missing key "${P.join("/")}" for ${w} in load(optionalImportsMap={})`);else{let k;if(P[0]==="langchain"||P[0]==="langchain_core")k=V[P[0]],P.shift();else throw Error(`Invalid namespace: ${w} -> ${E}`);if(P.length===0)throw Error(`Invalid namespace: ${w} -> ${E}`);let K;do if(K=P.join("__"),K in k)break;else P.pop();while(P.length>0);if(K in k)I=k[K]}if(typeof I!=="object"||I===null)throw Error(`Invalid namespace: ${w} -> ${E}`);let d=I[B]??Object.values(I).find((k)=>typeof k==="function"&&j6(k)===B);if(typeof d!=="function")throw Error(`Invalid identifer: ${w} -> ${E}`);let x=new d(O6(await v1.call({...this,path:[...X,"kwargs"],depth:$+1},A.kwargs),V6,rQ(d)));return Object.defineProperty(x.constructor,"name",{value:B}),x}let L={};for(let[A,E]of Object.entries(D))L[A]=await v1.call({...this,path:[...X,A],depth:$+1},E);return L}async function C6(Q,Z){let J=JSON.parse(Q),Y={optionalImportsMap:Z?.optionalImportsMap??{},optionalImportEntrypoints:Z?.optionalImportEntrypoints??[],secretsMap:Z?.secretsMap??{},secretsFromEnv:Z?.secretsFromEnv??!1,importMap:Z?.importMap??{},path:["$"],depth:0,maxDepth:Z?.maxDepth??sQ};return v1.call(Y,J)}function tQ(Q){return Q!==null&&Q.lc===1&&Q.type==="constructor"&&Array.isArray(Q.id)}async function b9(Q){if(Q&&typeof Q==="object")if(Array.isArray(Q))return await Promise.all(Q.map((J)=>b9(J)));else{let Z={};for(let[J,Y]of Object.entries(Q))Z[J]=await b9(Y);if(Z.lc===2&&Z.type==="undefined")return;else if(Z.lc===2&&Z.type==="constructor"&&Array.isArray(Z.id))try{let J=Z.id[Z.id.length-1],Y;switch(J){case"Set":Y=Set;break;case"Map":Y=Map;break;case"RegExp":Y=RegExp;break;case"Error":Y=Error;break;default:return Z}if(Z.method)return Y[Z.method](...Z.args||[]);else return new Y(...Z.args||[])}catch(J){return Z}else if(tQ(Z))return C6(JSON.stringify(Z));return Z}return Q}function k9(Q,Z,J,Y){return{lc:2,type:"constructor",id:[Q.name],method:Z??null,args:J??[],kwargs:Y??{}}}function aQ(Q){if(Q===void 0)return{lc:2,type:"undefined"};else if(Q instanceof Set||Q instanceof Map)return k9(Q.constructor,void 0,[Array.from(Q)]);else if(Q instanceof RegExp)return k9(RegExp,void 0,[Q.source,Q.flags]);else if(Q instanceof Error)return k9(Q.constructor,void 0,[Q.message]);else if(Q?.lg_name==="Send")return{node:Q.node,args:Q.args};else return Q}var x1=class{_dumps(Q){return new TextEncoder().encode(R0(Q,(J,Y)=>{return aQ(Y)}))}async dumpsTyped(Q){if(Q instanceof Uint8Array)return["bytes",Q];else return["json",this._dumps(Q)]}async _loads(Q){let Z=JSON.parse(Q);return b9(Z)}async loadsTyped(Q,Z){if(Q==="bytes")return typeof Z==="string"?new TextEncoder().encode(Z):Z;else if(Q==="json")return this._loads(typeof Z==="string"?Z:new TextDecoder().decode(Z));else throw Error(`Unknown serialization type: ${Q}`)}};function f9(Q){if(typeof Q!=="object"||Q===null)return Q;let Z=Array.isArray(Q)?[]:{};for(let J in Q)if(Object.prototype.hasOwnProperty.call(Q,J))Z[J]=f9(Q[J]);return Z}function eQ(){return{v:4,id:d1(-2),ts:new Date().toISOString(),channel_values:{},channel_versions:{},versions_seen:{}}}function M6(Q){return{v:Q.v,id:Q.id,ts:Q.ts,channel_values:{...Q.channel_values},channel_versions:{...Q.channel_versions},versions_seen:f9(Q.versions_seen)}}var S6=class{serde=new x1;constructor(Q){this.serde=Q||this.serde}async get(Q){let Z=await this.getTuple(Q);return Z?Z.checkpoint:void 0}getNextVersion(Q){if(typeof Q==="string")throw Error("Please override this method to use string versions.");return Q!==void 0&&typeof Q==="number"?Q+1:1}};function y6(Q,Z){if(typeof Q==="number"&&typeof Z==="number")return Math.sign(Q-Z);return String(Q).localeCompare(String(Z))}function v6(...Q){return Q.reduce((Z,J,Y)=>{if(Y===0)return J;return y6(Z,J)>=0?Z:J})}var x6={[m1]:-1,[c1]:-2,[u1]:-3,[l1]:-4};function k6(Q){return Q.configurable?.checkpoint_id||Q.configurable?.thread_ts||""}var d8=class extends Error{constructor(Q){super(Q);this.name="InvalidNamespaceError"}};function Q3(Q){if(Q.length===0)throw new d8("Namespace cannot be empty.");for(let Z of Q){if(typeof Z!=="string")throw new d8(`Invalid namespace label '${Z}' found in ${Q}. Namespace labels must be strings, but got ${typeof Z}.`);if(Z.includes("."))throw new d8(`Invalid namespace label '${Z}' found in ${Q}. Namespace labels cannot contain periods ('.').`);if(Z==="")throw new d8(`Namespace labels cannot be empty strings. Got ${Z} in ${Q}`)}if(Q[0]==="langgraph")throw new d8(`Root label for namespace cannot be "langgraph". Got: ${Q}`)}var k1=class{async get(Q,Z){return(await this.batch([{namespace:Q,key:Z}]))[0]}async search(Q,Z={}){let{filter:J,limit:Y=10,offset:G=0,query:H}=Z;return(await this.batch([{namespacePrefix:Q,filter:J,limit:Y,offset:G,query:H}]))[0]}async put(Q,Z,J,Y){Q3(Q),await this.batch([{namespace:Q,key:Z,value:J,index:Y}])}async delete(Q,Z){await this.batch([{namespace:Q,key:Z,value:null}])}async listNamespaces(Q={}){let{prefix:Z,suffix:J,maxDepth:Y,limit:G=100,offset:H=0}=Q,X=[];if(Z)X.push({matchType:"prefix",path:Z});if(J)X.push({matchType:"suffix",path:J});return(await this.batch([{matchConditions:X.length?X:void 0,maxDepth:Y,limit:G,offset:H}]))[0]}start(){}stop(){}};var Z3=(Q)=>{if("lg_name"in Q&&Q.lg_name==="AsyncBatchedStore")return Q.store;return Q},J3=class extends k1{lg_name="AsyncBatchedStore";store;queue=new Map;nextKey=0;running=!1;processingTask=null;constructor(Q){super();this.store=Z3(Q)}get isRunning(){return this.running}async batch(Q){throw Error("The `batch` method is not implemented on `AsyncBatchedStore`.\n Instead, it calls the `batch` method on the wrapped store.\n If you are seeing this error, something is wrong.")}async get(Q,Z){return this.enqueueOperation({namespace:Q,key:Z})}async search(Q,Z){let{filter:J,limit:Y=10,offset:G=0,query:H}=Z||{};return this.enqueueOperation({namespacePrefix:Q,filter:J,limit:Y,offset:G,query:H})}async put(Q,Z,J){return this.enqueueOperation({namespace:Q,key:Z,value:J})}async delete(Q,Z){return this.enqueueOperation({namespace:Q,key:Z,value:null})}start(){if(!this.running)this.running=!0,this.processingTask=this.processBatchQueue()}async stop(){if(this.running=!1,this.processingTask)await this.processingTask}enqueueOperation(Q){return new Promise((Z,J)=>{let Y=this.nextKey;this.nextKey+=1,this.queue.set(Y,{operation:Q,resolve:Z,reject:J})})}async processBatchQueue(){while(this.running){if(await new Promise((Z)=>{setTimeout(Z,0)}),this.queue.size===0)continue;let Q=new Map(this.queue);this.queue.clear();try{let Z=Array.from(Q.values()).map(({operation:Y})=>Y),J=await this.store.batch(Z);Q.forEach(({resolve:Y},G)=>{let H=Array.from(Q.keys()).indexOf(G);Y(J[H])})}catch(Z){Q.forEach(({reject:J})=>{J(Z)})}}}toJSON(){return{queue:this.queue,nextKey:this.nextKey,running:this.running,store:"[LangGraphStore]"}}};var h9=class{serde=new x1;constructor(Q){this.serde=Q||this.serde}};
|
|
100
|
+
export{A8 as $g,_8 as ah,d1 as bh,g6 as ch,F0 as dh,c1 as eh,p as fh,M8 as gh,o as hh,W9 as ih,_4 as jh,K9 as kh,v4 as lh,x4 as mh,k4 as nh,PQ as oh,yQ as ph,C6 as qh,eQ as rh,M6 as sh,S6 as th,y6 as uh,v6 as vh,x6 as wh,k6 as xh,J3 as yh,h9 as zh};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Of as J}from"./chunk-fkrydbn4.js";import{ri as K}from"./chunk-cbjnwrt7.js";import{iq as $,jq as D}from"./chunk-578m1dhj.js";import{tq as E}from"./chunk-dcs1r9as.js";class X{manager;routes=[];constructor(B){this.manager=B,this.registerRoutes()}registerRoutes(){this.addRoute("GET","/api/config",this.getConfig.bind(this)),this.addRoute("POST","/api/config",this.updateConfig.bind(this)),this.addRoute("GET","/api/skills",this.listSkills.bind(this)),this.addRoute("GET","/api/skill",this.getSkill.bind(this)),this.addRoute("PUT","/api/skill",this.saveSkill.bind(this)),this.addRoute("DELETE","/api/skill",this.deleteSkill.bind(this)),this.addRoute("POST","/api/skills/sync",this.syncSkills.bind(this)),this.addRoute("GET","/api/plugins",this.listPlugins.bind(this)),this.addRoute("GET","/api/plugin/config",this.getPluginConfig.bind(this)),this.addRoute("PUT","/api/plugin/config",this.updatePluginConfig.bind(this)),this.addRoute("POST","/api/plugin/install",this.installPlugin.bind(this)),this.addRoute("DELETE","/api/plugin",this.uninstallPlugin.bind(this)),this.addRoute("GET","/api/health",this.healthCheck.bind(this))}addRoute(B,G,Q){this.routes.push({method:B,pathname:G,handler:Q})}matchRoute(B,G){return B===G}async fetch(B){let G=new URL(B.url),Q=B.method,V=G.pathname;for(let W of this.routes){if(W.method!==Q)continue;if(!this.matchRoute(W.pathname,V))continue;try{return await W.handler(B)}catch(F){return this.errorResponse(F)}}return this.notFoundResponse()}jsonResponse(B,G=200){return new Response(JSON.stringify(B),{status:G,headers:{"Content-Type":"application/json"}})}errorResponse(B){console.error("Request error:",B);let G=B instanceof Error?B.message:"Internal server error";return this.jsonResponse({error:G},500)}notFoundResponse(){return this.jsonResponse({error:"Not found"},404)}async parseJson(B){let G=await B.text();if(!G)throw Error("Request body is empty");return JSON.parse(G)}getQueryParam(B,G){return new URL(B.url).searchParams.get(G)}requireQueryParam(B,G){let Q=this.getQueryParam(B,G);if(!Q)throw Error(`Missing required query parameter: ${G}`);return Q}async healthCheck(){return this.jsonResponse({status:"ok",timestamp:Date.now()})}async getConfig(){let B=await this.manager.getConfig();return this.jsonResponse(B)}async updateConfig(B){let G=await this.parseJson(B);return await this.manager.updateConfig(G),this.jsonResponse({success:!0})}async listSkills(){let B=await this.manager.listSkills();return this.jsonResponse(B)}async getSkill(B){let G=this.requireQueryParam(B,"name"),Q=await this.manager.getSkill(G);if(!Q)return this.jsonResponse({error:"Skill not found"},404);return this.jsonResponse(Q)}async saveSkill(B){let G=await this.parseJson(B);return await this.manager.saveSkill(G.name,G.content),this.jsonResponse({success:!0})}async deleteSkill(B){let G=await this.parseJson(B);return await this.manager.deleteSkill(G.name),this.jsonResponse({success:!0})}async syncSkills(){return await this.manager.syncSkillsFromRemote(),this.jsonResponse({success:!0})}async listPlugins(){let B=await this.manager.listPlugins();return this.jsonResponse(B)}async getPluginConfig(B){let G=this.requireQueryParam(B,"name"),Q=await this.manager.getPluginConfig(G);if(!Q)return this.jsonResponse({error:"Plugin config not found"},404);return this.jsonResponse(Q)}async updatePluginConfig(B){let G=await this.parseJson(B);return await this.manager.updatePluginConfig(G.name,G.config),this.jsonResponse({success:!0})}async installPlugin(B){let G=await this.parseJson(B);return await this.manager.installPlugin(G.name,G.source),this.jsonResponse({success:!0})}async uninstallPlugin(B){let G=await this.parseJson(B);return await this.manager.uninstallPlugin(G.name),this.jsonResponse({success:!0})}}async function w(){let{createFSManager:B}=await import("./chunk-hcnx1j2z.js"),G=await B();return new X(G)}function v(B){return new X(B)}class Y{baseUrl;constructor(B="http://localhost:3000"){this.baseUrl=B}async request(B,G){let Q=`${this.baseUrl}${B}`,V=await fetch(Q,G);if(!V.ok){let W=await V.json().catch(()=>({error:"Unknown error"}));throw Error(W.error||`HTTP ${V.status}`)}return V.json()}async initialize(){}async getConfig(){return this.request("/api/config")}async updateConfig(B){await this.request("/api/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(B)})}}class Z{baseUrl;constructor(B="http://localhost:3000"){this.baseUrl=B}async request(B,G){let Q=`${this.baseUrl}${B}`,V=await fetch(Q,G);if(!V.ok){let W=await V.json().catch(()=>({error:"Unknown error"}));throw Error(W.error||`HTTP ${V.status}`)}return V.json()}async initialize(){}async listSkills(){return this.request("/api/skills")}async getSkill(B){let G=`/api/skill?name=${encodeURIComponent(B)}`;return this.request(G)}async saveSkill(B,G){await this.request("/api/skill",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:B,content:G})})}async deleteSkill(B){await this.request("/api/skill",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:B})})}async syncFromRemote(B){await this.request("/api/skills/sync",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({remote:B})})}}class _{baseUrl;constructor(B="http://localhost:3000"){this.baseUrl=B}async request(B,G){let Q=`${this.baseUrl}${B}`,V=await fetch(Q,G);if(!V.ok){let W=await V.json().catch(()=>({error:"Unknown error"}));throw Error(W.error||`HTTP ${V.status}`)}return V.json()}async initialize(){}async listPlugins(){return this.request("/api/plugins")}async getPluginConfig(B){let G=`/api/plugin/config?name=${encodeURIComponent(B)}`;return this.request(G)}async updatePluginConfig(B,G){await this.request("/api/plugin/config",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:B,config:G})})}async installPlugin(B,G){await this.request("/api/plugin/install",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:B,source:G})})}async uninstallPlugin(B){await this.request("/api/plugin",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:B})})}}async function C(B="http://localhost:3000"){let G=new Y(B),Q=new Z(B),V=new _(B),W=new J(G,Q,V);return await W.initialize(),W}var U=K.enum(["idea","bug_report","feature","refactor"]),R=K.enum(["low","medium","high","critical"]),P=K.enum(["pending","planned","archived"]),T=K.enum(["user_input","ai_suggestion","conversation_derived"]),j=K.object({id:K.string().uuid(),type:U,title:K.string().min(1).max(200),description:K.string(),priority:R.default("medium"),source:T,status:P.default("pending"),createdAt:K.string().datetime(),tags:K.array(K.string()).default([]),metadata:K.object({relatedFiles:K.array(K.string()).optional(),conversationContext:K.string().optional(),estimatedComplexity:K.enum(["simple","medium","complex"]).optional()}).optional()}),n=K.object({version:K.literal("1.0"),sparks:K.array(j),lastUpdated:K.string().datetime()}),A=K.enum(["pickup","running","complete","error","review","feedback"]),L=K.enum(["default","planner","reviewer","refactor","finder","debugger","architect"]),b=K.enum(["serial","parallel"]),M=K.lazy(()=>K.object({id:K.string(),title:K.string().min(1).max(200),description:K.string(),execution:b.optional(),children:K.array(K.lazy(()=>M)).optional(),agentType:L.optional(),threadId:K.string().optional(),estimatedTime:K.string().optional(),complexity:K.enum(["simple","medium","complex"]).optional(),dependencies:K.array(K.string()).optional(),acceptanceCriteria:K.array(K.string()).optional(),status:A.optional(),startedAt:K.string().datetime().optional(),completedAt:K.string().datetime().optional(),assignedTo:L.optional(),error:K.object({message:K.string(),stack:K.string().optional(),retryCount:K.number().optional()}).optional()})),I=K.object({taskId:K.string(),planId:K.string(),threadId:K.string(),agentType:L,status:A,startedAt:K.string().datetime(),completedAt:K.string().datetime().optional(),output:K.string().optional(),error:K.string().optional(),changedFiles:K.array(K.string()).optional()}),o=K.object({version:K.literal("1.0"),lastUpdated:K.string().datetime(),activePlanId:K.string().optional(),tasks:K.record(K.string(),M),history:K.array(I),config:K.object({maxConcurrentAgents:K.number().min(1).max(10).default(3),retryLimit:K.number().min(0).max(10).default(3),autoResume:K.boolean().default(!1)})});import N from"path";class O{db;dbPath;constructor(B){this.dbPath=N.join(B,".claude","spark.json");let G=new D(this.dbPath);this.db=new $(G,this.getDefaultData())}getDefaultData(){return{version:"1.0",sparks:[],lastUpdated:new Date().toISOString()}}async initialize(){let B=await import("fs"),G=N.dirname(this.dbPath);if(!B.existsSync(G))B.mkdirSync(G,{recursive:!0});if(await this.db.read(),!this.db.data)this.db.data=this.getDefaultData(),await this.db.write()}generateId(){return crypto.randomUUID()}async addSpark(B){await this.db.read();let G={id:this.generateId(),type:B.type,title:B.title,description:B.description,priority:B.priority||"medium",source:"user_input",status:"pending",createdAt:new Date().toISOString(),tags:B.tags||[]};return this.db.data.sparks.push(G),this.db.data.lastUpdated=new Date().toISOString(),await this.db.write(),G}async getAllSparks(){return await this.db.read(),this.db.data.sparks}async getSparksByStatus(B){return await this.db.read(),this.db.data.sparks.filter((G)=>G.status===B)}async getSparksByType(B){return await this.db.read(),this.db.data.sparks.filter((G)=>G.type===B)}async updateSparkStatus(B,G){await this.db.read();let Q=this.db.data.sparks.find((V)=>V.id===B);if(!Q)return!1;return Q.status=G,this.db.data.lastUpdated=new Date().toISOString(),await this.db.write(),!0}async deleteSpark(B){await this.db.read();let G=this.db.data.sparks.findIndex((Q)=>Q.id===B);if(G===-1)return!1;return this.db.data.sparks.splice(G,1),this.db.data.lastUpdated=new Date().toISOString(),await this.db.write(),!0}getDbPath(){return this.dbPath}}import x from"path";class H{db;dbPath;constructor(B){this.dbPath=x.join(B,".claude","task.json");let G=new D(this.dbPath);this.db=new $(G,this.getDefaultData())}getDefaultData(){return{version:"1.0",lastUpdated:new Date().toISOString(),tasks:{},history:[],config:{maxConcurrentAgents:3,retryLimit:3,autoResume:!1}}}async initialize(){let B=await import("fs"),G=x.dirname(this.dbPath);if(!B.existsSync(G))B.mkdirSync(G,{recursive:!0});if(await this.db.read(),!this.db.data)this.db.data=this.getDefaultData(),await this.db.write()}async getTask(B){return await this.db.read(),this.db.data.tasks[B]}async updateTask(B,G){await this.db.read();let Q=this.db.data.tasks[B];if(!Q)return!1;if(this.db.data.tasks[B]={...Q,...G},G.status){if(G.status==="running"&&!Q.startedAt)this.db.data.tasks[B].startedAt=new Date().toISOString();else if(["complete","error","review"].includes(G.status)&&!Q.completedAt)this.db.data.tasks[B].completedAt=new Date().toISOString()}return this.db.data.lastUpdated=new Date().toISOString(),await this.db.write(),!0}async addTasks(B){await this.db.read();for(let G of B)this.db.data.tasks[G.id]=G;this.db.data.lastUpdated=new Date().toISOString(),await this.db.write()}async getTasksByStatus(B){return await this.db.read(),Object.values(this.db.data.tasks).filter((G)=>G.status===B)}async getAllTasks(){return await this.db.read(),Object.values(this.db.data.tasks)}async addHistory(B){await this.db.read(),this.db.data.history.push(B),await this.db.write()}async getHistory(B){if(await this.db.read(),B)return this.db.data.history.filter((G)=>G.planId===B);return this.db.data.history}async setActivePlan(B){await this.db.read(),this.db.data.activePlanId=B,this.db.data.lastUpdated=new Date().toISOString(),await this.db.write()}async getActivePlan(){return await this.db.read(),this.db.data.activePlanId}async updateConfig(B){await this.db.read(),this.db.data.config={...this.db.data.config,...B},this.db.data.lastUpdated=new Date().toISOString(),await this.db.write()}async getConfig(){return await this.db.read(),this.db.data.config}async clearAllTasks(){await this.db.read(),this.db.data.tasks={},this.db.data.activePlanId=void 0,this.db.data.lastUpdated=new Date().toISOString(),await this.db.write()}async deleteTask(B){if(await this.db.read(),!this.db.data.tasks[B])return!1;return delete this.db.data.tasks[B],this.db.data.lastUpdated=new Date().toISOString(),await this.db.write(),!0}getDbPath(){return this.dbPath}}export{X as sf,w as tf,v as uf,Y as vf,Z as wf,_ as xf,C as yf,U as zf,R as Af,P as Bf,T as Cf,j as Df,n as Ef,A as Ff,L as Gf,b as Hf,M as If,I as Jf,o as Kf,O as Lf,H as Mf};
|