zen-code 4.10.0 → 4.10.1

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.
Files changed (83) hide show
  1. package/dist/app.js +2615 -157
  2. package/dist/cli.js +3116 -1
  3. package/dist/nonInteractive.js +1950 -180
  4. package/dist/zen-keyboard.js +358 -3
  5. package/package.json +1 -1
  6. package/dist/chunk-075hks9v.js +0 -1
  7. package/dist/chunk-0fj768k4.js +0 -112
  8. package/dist/chunk-19mf2aa7.js +0 -1
  9. package/dist/chunk-1mq2jmfy.js +0 -2
  10. package/dist/chunk-1v863afn.js +0 -278
  11. package/dist/chunk-1vn8d8b8.js +0 -1
  12. package/dist/chunk-1w19w1bm.js +0 -2
  13. package/dist/chunk-3dnayvgx.js +0 -224
  14. package/dist/chunk-4hg13vwj.js +0 -1
  15. package/dist/chunk-4scrkcqv.js +0 -1
  16. package/dist/chunk-54cdhhqm.js +0 -1
  17. package/dist/chunk-5m4yb9av.js +0 -91
  18. package/dist/chunk-5yd4ntp6.js +0 -8
  19. package/dist/chunk-6scjjkn3.js +0 -23
  20. package/dist/chunk-7jatn15w.js +0 -2
  21. package/dist/chunk-7w9y11hj.js +0 -88
  22. package/dist/chunk-7yzv6385.js +0 -1
  23. package/dist/chunk-875hayaj.js +0 -3
  24. package/dist/chunk-8bs8r50r.js +0 -1
  25. package/dist/chunk-8waww0j9.js +0 -6
  26. package/dist/chunk-8ysg0rga.js +0 -1
  27. package/dist/chunk-9czhw5k6.js +0 -4
  28. package/dist/chunk-9tgp14v7.js +0 -16
  29. package/dist/chunk-a239dn0b.js +0 -1
  30. package/dist/chunk-arv4h3h1.js +0 -2
  31. package/dist/chunk-b2551zfb.js +0 -2
  32. package/dist/chunk-b9emn03n.js +0 -1
  33. package/dist/chunk-bm7578sn.js +0 -1
  34. package/dist/chunk-bytq4kd1.js +0 -176
  35. package/dist/chunk-c2wfgbj6.js +0 -1
  36. package/dist/chunk-cef4vbtb.js +0 -26
  37. package/dist/chunk-cnzhxgn5.js +0 -4
  38. package/dist/chunk-d2770b2z.js +0 -1
  39. package/dist/chunk-d72063sm.js +0 -2
  40. package/dist/chunk-d988tv30.js +0 -1
  41. package/dist/chunk-dx9k6sdd.js +0 -7
  42. package/dist/chunk-e6ggkg36.js +0 -2
  43. package/dist/chunk-fjqtrakn.js +0 -1
  44. package/dist/chunk-gbfpab0j.js +0 -1
  45. package/dist/chunk-gkvx829z.js +0 -1
  46. package/dist/chunk-gwf8b14k.js +0 -3
  47. package/dist/chunk-gz7fz9fg.js +0 -1
  48. package/dist/chunk-h0q3dvnv.js +0 -5
  49. package/dist/chunk-h0qb9jk1.js +0 -1
  50. package/dist/chunk-h9y136h8.js +0 -1
  51. package/dist/chunk-hrcxdj3c.js +0 -54
  52. package/dist/chunk-hz9yw7cs.js +0 -166
  53. package/dist/chunk-j4y5rjne.js +0 -79
  54. package/dist/chunk-k12y05c3.js +0 -3
  55. package/dist/chunk-k6fxqssr.js +0 -18
  56. package/dist/chunk-kmxdq21k.js +0 -2
  57. package/dist/chunk-mcb8rewr.js +0 -213
  58. package/dist/chunk-mm9w91rj.js +0 -4
  59. package/dist/chunk-mv0xzmq8.js +0 -2
  60. package/dist/chunk-n849zsd3.js +0 -1
  61. package/dist/chunk-nm253hhf.js +0 -81
  62. package/dist/chunk-prg6489q.js +0 -1
  63. package/dist/chunk-pxdgy0vr.js +0 -2
  64. package/dist/chunk-qhzm2qw9.js +0 -2
  65. package/dist/chunk-qmxtys9q.js +0 -2
  66. package/dist/chunk-r0cfe5c1.js +0 -294
  67. package/dist/chunk-rtjytfhh.js +0 -1
  68. package/dist/chunk-s7ttf0pm.js +0 -2
  69. package/dist/chunk-t01t72t2.js +0 -140
  70. package/dist/chunk-t0f66x64.js +0 -1
  71. package/dist/chunk-tn356gwf.js +0 -93
  72. package/dist/chunk-vd8kwzra.js +0 -41
  73. package/dist/chunk-vhn13anh.js +0 -233
  74. package/dist/chunk-vnewbtjy.js +0 -1
  75. package/dist/chunk-wbm7rn9w.js +0 -2
  76. package/dist/chunk-wd3gkd45.js +0 -3
  77. package/dist/chunk-whdf0vbb.js +0 -1
  78. package/dist/chunk-ws232ksq.js +0 -2
  79. package/dist/chunk-yerf10k7.js +0 -6
  80. package/dist/chunk-yzv3n8mw.js +0 -2
  81. package/dist/chunk-z3e4c424.js +0 -2
  82. package/dist/chunk-znw7fpep.js +0 -6
  83. package/dist/chunk-zq2g4rfd.js +0 -1
@@ -1,166 +0,0 @@
1
- import{$h as J4,$i as N6,$j as g,Ah as eQ,Ai as D4,Aj as A8,Ak as p5,Bh as _Q,Bi as B4,Bj as _4,Bk as o5,Ch as Q3,Ci as N4,Cj as j4,Ck as K0,Dh as Z8,Di as X8,Dj as T4,Dk as nQ,Eh as d0,Ei as A4,Ej as I1,Ek as LQ,Fh as R1,Fi as E4,Fj as O1,Gh as V1,Gi as F4,Gj as S4,Hh as m0,Hi as L4,Hj as C4,Ih as c0,Ii as O8,Ij as _1,Jh as P1,Ji as R4,Jj as M4,Kh as u0,Ki as TQ,Kj as y4,Lh as l0,Lj as v4,Mh as p0,Mi as m1,Mj as b4,Nh as o0,Ni as SQ,Nj as x4,Oh as i0,Oi as c1,Oj as f4,Ph as n0,Pj as k4,Qh as Q8,Qi as G6,Qj as h4,Rh as r0,Ri as CQ,Rj as g4,Sh as s0,Si as r8,Sj as d4,Th as t0,Ti as MQ,Tj as m4,Uh as a0,Ui as yQ,Uj as c4,Vh as e0,Vi as vQ,Vj as u4,Wh as Q4,Wi as bQ,Wj as l4,Xh as Z4,Xi as L5,Xj as p4,Yh as n,Yi as z8,Yj as o4,Zh as y8,Zj as i4,_h as jQ,_i as xQ,_j as uQ,ai as B8,aj as fQ,ak as lQ,bi as Z1,bj as kQ,ci as Y4,cj as y1,ck as L6,di as G4,dj as P6,dk as v,ei as X4,ej as H8,ek as k8,fi as W4,fj as K8,fk as _6,gi as z4,gj as I6,gk as j6,hi as C,hj as O6,hk as v1,ii as v8,ij as hQ,ik as C1,jh as x6,ji as W1,jj as h5,jk as p,ki as e,kj as q8,kk as T6,li as N8,lk as S6,mi as J1,mj as v6,mk as f8,ni as $4,nj as E8,nk as M1,oi as H4,oj as gQ,ok as C6,ph as L,pi as Y1,pj as dQ,pk as M6,qh as OQ,qi as G1,qj as c8,qk as pQ,rh as h8,ri as q4,rj as b1,rk as W5,sh as b9,si as K4,sj as j8,sk as U5,ti as u,tj as mQ,tk as K5,ui as X1,uj as W6,uk as oQ,vh as T8,vi as U4,vj as cQ,vk as iQ,wh as F8,wi as w4,wj as m8,xh as sQ,xi as Q1,xj as P4,yh as tQ,yi as a,yj as I4,yk as u1,zh as aQ,zi as I8,zj as O4,zk as l5}from"./chunk-tn356gwf.js";import{Jk as $1}from"./chunk-n849zsd3.js";import{Al as e8,Bl as _0,El as j0}from"./chunk-arv4h3h1.js";j0();function q9(Q){return _0({clockseq:Q})}function K3(Q,Z){let J=Z.replace(/-/g,"").match(/.{2}/g).map((Y)=>parseInt(Y,16));return e8(Q,new Uint8Array(J))}var T0="__pregel_tasks",K9="__error__",U9="__scheduled__",w9="__interrupt__",D9="__resume__";var L1=(Q,Z)=>{let J=[...new Set(Z?.map((G)=>{if(typeof G==="string")return G;let X=new G({});if(!("getType"in X)||typeof X.getType!=="function")throw Error("Invalid type provided.");return X.getType()}))],Y=Q.getType();return J.some((G)=>G===Y)};function v0(Q,Z){if(Array.isArray(Q))return S0(Q,Z);return p.from((J)=>{return S0(J,Q)})}function S0(Q,Z={}){let{includeNames:J,excludeNames:Y,includeTypes:G,excludeTypes:X,includeIds:W,excludeIds:$}=Z,q=[];for(let w of Q){if(Y&&w.name&&Y.includes(w.name))continue;else if(X&&L1(w,X))continue;else if($&&w.id&&$.includes(w.id))continue;if(!(G||W||J))q.push(w);else if(J&&w.name&&J.some((D)=>D===w.name))q.push(w);else if(G&&L1(w,G))q.push(w);else if(W&&w.id&&W.some((D)=>D===w.id))q.push(w)}return q}function b0(Q){if(Array.isArray(Q))return C0(Q);return p.from(C0)}function C0(Q){if(!Q.length)return[];let Z=[];for(let J of Q){let Y=J,G=Z.pop();if(!G)Z.push(Y);else if(Y.getType()==="tool"||Y.getType()!==G.getType())Z.push(G,Y);else{let X=O8(G),W=O8(Y),$=X.concat(W);if(typeof X.content==="string"&&typeof W.content==="string")$.content=`${X.content}
2
- ${W.content}`;Z.push(w3($))}}return Z}function x0(Q,Z){if(Array.isArray(Q)){let J=Q;if(!Z)throw Error("Options parameter is required when providing messages.");return M0(J,Z)}else{let J=Q;return p.from((Y)=>M0(Y,J)).withConfig({runName:"trim_messages"})}}async function M0(Q,Z){let{maxTokens:J,tokenCounter:Y,strategy:G="last",allowPartial:X=!1,endOn:W,startOn:$,includeSystem:q=!1,textSplitter:w}=Z;if($&&G==="first")throw Error("`startOn` should only be specified if `strategy` is 'last'.");if(q&&G==="first")throw Error("`includeSystem` should only be specified if `strategy` is 'last'.");let D;if("getNumTokens"in Y)D=async(N)=>{return(await Promise.all(N.map((F)=>Y.getNumTokens(F.content)))).reduce((F,E)=>F+E,0)};else D=async(N)=>Y(N);let A=N9;if(w)if("splitText"in w)A=w.splitText;else A=async(N)=>w(N);if(G==="first")return f0(Q,{maxTokens:J,tokenCounter:D,textSplitter:A,partialStrategy:X?"first":void 0,endOn:W});else if(G==="last")return U3(Q,{maxTokens:J,tokenCounter:D,textSplitter:A,allowPartial:X,includeSystem:q,startOn:$,endOn:W});else throw Error(`Unrecognized strategy: '${G}'. Must be one of 'first' or 'last'.`)}async function f0(Q,Z){let{maxTokens:J,tokenCounter:Y,textSplitter:G,partialStrategy:X,endOn:W}=Z,$=[...Q],q=0;for(let w=0;w<$.length;w+=1)if(await Y(w>0?$.slice(0,-w):$)<=J){q=$.length-w;break}if(q<$.length&&X){let w=!1;if(Array.isArray($[q].content)){let D=$[q];if(typeof D.content==="string")throw Error("Expected content to be an array.");let A=D.content.length,N=X==="last"?[...D.content].reverse():D.content;for(let F=1;F<=A;F+=1){let E=X==="first"?N.slice(0,F):N.slice(-F),R=Object.fromEntries(Object.entries(D).filter(([P])=>P!=="type"&&!P.startsWith("lc_"))),V=B9(D.getType(),{...R,content:E}),I=[...$.slice(0,q),V];if(await Y(I)<=J)$=I,q+=1,w=!0;else break}if(w&&X==="last")D.content=[...N].reverse()}if(!w){let D=$[q],A;if(Array.isArray(D.content)&&D.content.some((N)=>typeof N==="string"||N.type==="text"))A=D.content.find((N)=>N.type==="text"&&N.text)?.text;else if(typeof D.content==="string")A=D.content;if(A){let N=await G(A),F=N.length;if(X==="last")N.reverse();for(let E=0;E<F-1;E+=1)if(N.pop(),D.content=N.join(""),await Y([...$.slice(0,q),D])<=J){if(X==="last")D.content=[...N].reverse().join("");$=[...$.slice(0,q),D],q+=1;break}}}}if(W){let w=Array.isArray(W)?W:[W];while(q>0&&!L1($[q-1],w))q-=1}return $.slice(0,q)}async function U3(Q,Z){let{allowPartial:J=!1,includeSystem:Y=!1,endOn:G,startOn:X,...W}=Z,$=Q.map((D)=>{let A=Object.fromEntries(Object.entries(D).filter(([N])=>N!=="type"&&!N.startsWith("lc_")));return B9(D.getType(),A,y8(D))});if(G){let D=Array.isArray(G)?G:[G];while($.length>0&&!L1($[$.length-1],D))$=$.slice(0,-1)}let q=Y&&$[0]?.getType()==="system",w=q?$.slice(0,1).concat($.slice(1).reverse()):$.reverse();if(w=await f0(w,{...W,partialStrategy:J?"last":void 0,endOn:X}),q)return[w[0],...w.slice(1).reverse()];else return w.reverse()}var y0={human:{message:u,messageChunk:X1},ai:{message:C,messageChunk:e},system:{message:a,messageChunk:I8},developer:{message:a,messageChunk:I8},tool:{message:B8,messageChunk:Z1},function:{message:Y1,messageChunk:G1},generic:{message:N8,messageChunk:J1},remove:{message:Q1,messageChunk:Q1}};function B9(Q,Z,J){let Y,G;switch(Q){case"human":if(J)Y=new X1(Z);else G=new u(Z);break;case"ai":if(J){let X={...Z};if("tool_calls"in X)X={...X,tool_call_chunks:X.tool_calls?.map((W)=>({...W,type:"tool_call_chunk",index:void 0,args:JSON.stringify(W.args)}))};Y=new e(X)}else G=new C(Z);break;case"system":if(J)Y=new I8(Z);else G=new a(Z);break;case"developer":if(J)Y=new I8({...Z,additional_kwargs:{...Z.additional_kwargs,__openai_role__:"developer"}});else G=new a({...Z,additional_kwargs:{...Z.additional_kwargs,__openai_role__:"developer"}});break;case"tool":if("tool_call_id"in Z)if(J)Y=new Z1(Z);else G=new B8(Z);else throw Error("Can not convert ToolMessage to ToolMessageChunk if 'tool_call_id' field is not defined.");break;case"function":if(J)Y=new G1(Z);else{if(!Z.name)throw Error("FunctionMessage must have a 'name' field");G=new Y1(Z)}break;case"generic":if("role"in Z)if(J)Y=new J1(Z);else G=new N8(Z);else throw Error("Can not convert ChatMessage to ChatMessageChunk if 'role' field is not defined.");break;default:throw Error(`Unrecognized message type ${Q}`)}if(J&&Y)return Y;if(G)return G;throw Error(`Unrecognized message type ${Q}`)}function w3(Q){let Z=Q.getType(),J,Y=Object.fromEntries(Object.entries(Q).filter(([G])=>!["type","tool_call_chunks"].includes(G)&&!G.startsWith("lc_")));if(Z in y0)J=B9(Z,Y);if(!J)throw Error(`Unrecognized message chunk class ${Z}. Supported classes are ${Object.keys(y0)}`);return J}function N9(Q){let Z=Q.split(`
3
- `);return Promise.resolve([...Z.slice(0,-1).map((J)=>`${J}
4
- `),Z[Z.length-1]])}var k0=["tool_call","tool_call_chunk","invalid_tool_call","server_tool_call","server_tool_call_chunk","server_tool_call_result"];var h0=["image","video","audio","text-plain","file"];var g0=["text","reasoning",...k0,...h0];var V4=L({AIMessage:()=>C,AIMessageChunk:()=>e,BaseMessage:()=>Q8,BaseMessageChunk:()=>Q4,ChatMessage:()=>N8,ChatMessageChunk:()=>J1,DEFAULT_MERGE_IGNORE_KEYS:()=>s0,FunctionMessage:()=>Y1,FunctionMessageChunk:()=>G1,HumanMessage:()=>u,HumanMessageChunk:()=>X1,KNOWN_BLOCK_TYPES:()=>g0,RemoveMessage:()=>Q1,SystemMessage:()=>a,SystemMessageChunk:()=>I8,ToolMessage:()=>B8,ToolMessageChunk:()=>Z1,_isMessageFieldWithRole:()=>Z4,_mergeDicts:()=>t0,_mergeLists:()=>a0,_mergeObj:()=>e0,_mergeStatus:()=>n0,coerceMessageLikeToMessage:()=>X8,collapseToolCallChunks:()=>R4,convertToChunk:()=>O8,convertToOpenAIImageBlock:()=>P1,convertToProviderContentBlock:()=>p0,defaultTextSplitter:()=>N9,defaultToolCallParser:()=>Y4,filterMessages:()=>v0,getBufferString:()=>A4,iife:()=>N4,isAIMessage:()=>v8,isAIMessageChunk:()=>W1,isBase64ContentBlock:()=>V1,isBaseMessage:()=>n,isBaseMessageChunk:()=>y8,isChatMessage:()=>$4,isChatMessageChunk:()=>H4,isDataContentBlock:()=>d0,isDirectToolOutput:()=>J4,isFunctionMessage:()=>q4,isFunctionMessageChunk:()=>K4,isHumanMessage:()=>U4,isHumanMessageChunk:()=>w4,isIDContentBlock:()=>c0,isMessage:()=>o0,isOpenAIToolCallArray:()=>r0,isPlainTextContentBlock:()=>m0,isSystemMessage:()=>D4,isSystemMessageChunk:()=>B4,isToolMessage:()=>G4,isToolMessageChunk:()=>X4,isURLContentBlock:()=>R1,mapChatMessagesToStoredMessages:()=>L4,mapStoredMessageToChatMessage:()=>E4,mapStoredMessagesToChatMessages:()=>F4,mergeContent:()=>i0,mergeMessageRuns:()=>b0,mergeResponseMetadata:()=>W4,mergeUsageMetadata:()=>z4,parseBase64DataUrl:()=>l0,parseMimeType:()=>u0,trimMessages:()=>x0});var n4=L({extendInteropZodObject:()=>d4,getInteropZodDefaultGetter:()=>l4,getInteropZodObjectShape:()=>g4,getSchemaDescription:()=>_1,interopParse:()=>C4,interopParseAsync:()=>O1,interopSafeParse:()=>S4,interopSafeParseAsync:()=>I1,interopZodObjectMakeFieldsOptional:()=>o4,interopZodObjectPartial:()=>m4,interopZodObjectPassthrough:()=>u4,interopZodObjectStrict:()=>c4,interopZodTransformInputSchema:()=>p4,isInteropZodError:()=>i4,isInteropZodLiteral:()=>T4,isInteropZodObject:()=>h4,isInteropZodSchema:()=>A8,isShapelessZodSchema:()=>M4,isSimpleStringZodSchema:()=>y4,isZodArrayV4:()=>x4,isZodLiteralV3:()=>_4,isZodLiteralV4:()=>j4,isZodNullableV4:()=>k4,isZodObjectV3:()=>v4,isZodObjectV4:()=>b4,isZodOptionalV4:()=>f4,isZodSchema:()=>O4,isZodSchemaV3:()=>I4,isZodSchemaV4:()=>P4});var r4="[...]",D3="[Circular]",j1=[],b8=[];function B3(){return{depthLimit:Number.MAX_SAFE_INTEGER,edgesLimit:Number.MAX_SAFE_INTEGER}}function s4(Q,Z,J,Y){if(typeof Y>"u")Y=B3();E9(Q,"",0,[],void 0,0,Y);var G;try{if(b8.length===0)G=JSON.stringify(Q,Z,J);else G=JSON.stringify(Q,N3(Z),J)}catch(W){return JSON.stringify("[unable to serialize, circular reference is too complex to analyze]")}finally{while(j1.length!==0){var X=j1.pop();if(X.length===4)Object.defineProperty(X[0],X[1],X[3]);else X[0][X[1]]=X[2]}}return G}function A9(Q,Z,J,Y){var G=Object.getOwnPropertyDescriptor(Y,J);if(G.get!==void 0)if(G.configurable)Object.defineProperty(Y,J,{value:Q}),j1.push([Y,J,Z,G]);else b8.push([Z,J,Q]);else Y[J]=Q,j1.push([Y,J,Z])}function E9(Q,Z,J,Y,G,X,W){X+=1;var $;if(typeof Q==="object"&&Q!==null){for($=0;$<Y.length;$++)if(Y[$]===Q){A9(D3,Q,Z,G);return}if(typeof W.depthLimit<"u"&&X>W.depthLimit){A9(r4,Q,Z,G);return}if(typeof W.edgesLimit<"u"&&J+1>W.edgesLimit){A9(r4,Q,Z,G);return}if(Y.push(Q),Array.isArray(Q))for($=0;$<Q.length;$++)E9(Q[$],$,$,Y,Q,X,W);else{var q=Object.keys(Q);for($=0;$<q.length;$++){var w=q[$];E9(Q[w],w,$,Y,Q,X,W)}}Y.pop()}}function N3(Q){return Q=typeof Q<"u"?Q:function(Z,J){return J},function(Z,J){if(b8.length>0)for(var Y=0;Y<b8.length;Y++){var G=b8[Y];if(G[1]===Z&&G[0]===J){J=G[2],b8.splice(Y,1);break}}return Q.call(this,Z,J)}}var t4=[];var a4=L({});var e4=L({});var Q6=L({BaseChatMessageHistory:()=>F9,BaseListChatMessageHistory:()=>T1,InMemoryChatMessageHistory:()=>A3}),F9=class extends Z8{async addMessages(Q){for(let Z of Q)await this.addMessage(Z)}},T1=class extends Z8{addUserMessage(Q){return this.addMessage(new u(Q))}addAIMessage(Q){return this.addMessage(new C(Q))}async addMessages(Q){for(let Z of Q)await this.addMessage(Z)}clear(){throw Error("Not implemented.")}},A3=class extends T1{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 r=class{pageContent;metadata;id;constructor(Q){this.pageContent=Q.pageContent!==void 0?Q.pageContent.toString():"",this.metadata=Q.metadata??{},this.id=Q.id}};var L9=class extends v{lc_namespace=["langchain_core","documents","transformers"];invoke(Q,Z){return this.transformDocuments(Q)}},Z6=class extends L9{async transformDocuments(Q){let Z=[];for(let J of Q){let Y=await this._transformDocument(J);Z.push(Y)}return Z}};var J6=L({BaseDocumentTransformer:()=>L9,Document:()=>r,MappingDocumentTransformer:()=>Z6});var Y6=L({BaseDocumentLoader:()=>R9}),R9=class{};var X6=L({LangSmithLoader:()=>E3}),E3=class extends R9{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 G6(Q?.clientConfig),this.contentKey=Q.contentKey?Q.contentKey.split("."):[],this.formatContent=Q.formatContent??F3,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 X of this.contentKey)J=J[X];let Y=this.formatContent(J),G=Z;["created_at","modified_at"].forEach((X)=>{if(X in G){if(typeof G[X]==="object")G[X]=G[X].toString()}}),Q.push({pageContent:Y,metadata:G})}return Q}};function F3(Q){if(typeof Q==="string")return Q;else try{return JSON.stringify(Q,null,2)}catch{return String(Q)}}var z6=L({Embeddings:()=>S1}),S1=class{caller;constructor(Q){this.caller=new W6(Q??{})}};var x8=class extends Z8{lc_namespace=["langchain_core","example_selectors","base"]};var V9=class{async getPromptAsync(Q,Z){return this.getPrompt(Q).partial(Z?.partialVariables??{})}},$6=class extends V9{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 H6(Q){return Q._modelType()==="base_llm"}function q6(Q){return Q._modelType()==="base_chat_model"}function K6(Q){return Q.split(/\n| /).length}var U6=class Q extends x8{examples=[];examplePrompt;getTextLength=K6;maxLength=2048;exampleTextLengths=[];constructor(Z){super(Z);this.examplePrompt=Z.examplePrompt,this.maxLength=Z.maxLength??2048,this.getTextLength=Z.getTextLength??K6}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((X)=>G.format(X)))).map((X)=>this.getTextLength(X))}async selectExamples(Z){let J=Object.values(Z).join(" "),Y=this.maxLength-this.getTextLength(J),G=0,X=[];while(Y>0&&G<this.examples.length){let W=Y-this.exampleTextLengths[G];if(W<0)break;else X.push(this.examples[G]),Y=W;G+=1}return X}static async fromExamples(Z,J){let Y=new Q(J);return await Promise.all(Z.map((G)=>Y.addExample(G))),Y}};function P9(Q){return Object.keys(Q).sort().map((Z)=>Q[Z])}var w6=class Q extends x8{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=P9((this.inputKeys??Object.keys(Z)).reduce((Y,G)=>({...Y,[G]:Z[G]}),{})).join(" ");await this.vectorStoreRetriever.addDocuments([new r({pageContent:J,metadata:Z})])}async selectExamples(Z){let J=P9((this.inputKeys??Object.keys(Z)).reduce((G,X)=>({...G,[X]:Z[X]}),{})).join(" "),Y=(await this.vectorStoreRetriever.invoke(J)).map((G)=>G.metadata);if(this.exampleKeys)return Y.map((G)=>this.exampleKeys.reduce((X,W)=>({...X,[W]:G[W]}),{}));return Y}static async fromExamples(Z,J,Y,G={}){let X=G.inputKeys??null,W=Z.map(($)=>P9(X?X.reduce((q,w)=>({...q,[w]:$[w]}),{}):$).join(" "));return new Q({vectorStore:await Y.fromTexts(W,Z,J,G),k:G.k??4,exampleKeys:G.exampleKeys,inputKeys:G.inputKeys})}};var D6=L({BaseExampleSelector:()=>x8,BasePromptSelector:()=>V9,ConditionalPromptSelector:()=>$6,LengthBasedExampleSelector:()=>U6,SemanticSimilarityExampleSelector:()=>w6,isChatModel:()=>q6,isLLM:()=>H6});var z1="10f90ea3-90a4-4962-bf75-83a0f3c1c62a",B6=class extends Z8{lc_namespace=["langchain","recordmanagers"]};j0();var I9=class{uid;hash_;contentHash;metadataHash;pageContent;metadata;keyEncoder=N6;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 r({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 e8(this.keyEncoder(Q),z1)}_hashNestedDictToUUID(Q){let Z=JSON.stringify(Q,Object.keys(Q).sort());return e8(this.keyEncoder(Z),z1)}};function O9(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 _9(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 j9(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 T9=(Q)=>{if("load"in Q&&typeof Q.load==="function"&&"loadAndSplit"in Q&&typeof Q.loadAndSplit==="function")return!0;return!1};async function A6(Q){let{docsSource:Z,recordManager:J,vectorStore:Y,options:G}=Q,{batchSize:X=100,cleanup:W,sourceIdKey:$,cleanupBatchSize:q=1000,forceUpdate:w=!1}=G??{};if(W==="incremental"&&!$)throw Error("sourceIdKey is required when cleanup mode is incremental. Please provide through 'options.sourceIdKey'.");let D=T9(Z)?await Z.load():Z,A=j9($??null),N=await J.getTime(),F=0,E=0,R=0,V=0,I=O9(X??100,D);for(let P of I){let O=_9(P.map((y)=>I9.fromDocument(y))),T=O.map((y)=>A(y));if(W==="incremental")O.forEach((y,M)=>{if(T[M]===null)throw Error("sourceIdKey must be provided when cleanup is incremental")});let m=await J.exists(O.map((y)=>y.uid)),x=[],f=[],K=[],M8=new Set;if(O.forEach((y,M)=>{if(m[M])if(w)M8.add(y.uid);else{K.push(y.uid);return}x.push(y.uid),f.push(y.toDocument())}),K.length>0)await J.update(K,{timeAtLeast:N}),V+=K.length;if(f.length>0)await Y.addDocuments(f,{ids:x}),F+=f.length-M8.size,R+=M8.size;if(await J.update(O.map((y)=>y.uid),{timeAtLeast:N,groupIds:T}),W==="incremental"){T.forEach((M)=>{if(!M)throw Error("Source id cannot be null")});let y=await J.listKeys({before:N,groupIds:T});if(y.length>0)await Y.delete({ids:y}),await J.deleteKeys(y),E+=y.length}}if(W==="full"){let P=await J.listKeys({before:N,limit:q});while(P.length>0)await Y.delete({ids:P}),await J.deleteKeys(P),E+=P.length,P=await J.listKeys({before:N,limit:q})}return{numAdded:F,numDeleted:E,numUpdated:R,numSkipped:V}}var E6=L({RecordManager:()=>B6,UUIDV5_NAMESPACE:()=>z1,_HashedDocument:()=>I9,_batch:()=>O9,_deduplicateInOrder:()=>_9,_getSourceIdAssigner:()=>j9,_isBaseDocumentLoader:()=>T9,index:()=>A6});var _8=class extends v{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=H8(Z);if(this.func)await this.func(Q,J);return this._callWithConfig((Y)=>Promise.resolve(Y),Q,J)}async*transform(Q,Z){let J=H8(Z),Y,G=!0;for await(let X of this._transformStreamWithConfig(Q,(W)=>W,J))if(yield X,G)if(Y===void 0)Y=X;else try{Y=q8(Y,X)}catch{Y=void 0,G=!1}if(this.func&&Y!==void 0)await this.func(Y,J)}static assign(Q){return new M1(new C1({steps:Q}))}};var F6=class extends v{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,H8(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 X=Y.map((D)=>this.runnables[D]),W=this._getOptionsList(Z??{},Q.length),$=W[0]?.maxConcurrency??J?.maxConcurrency,q=$&&$>0?$:Q.length,w=[];for(let D=0;D<G.length;D+=q){let A=G.slice(D,D+q).map((F,E)=>X[E].invoke(F,W[E])),N=await Promise.all(A);w.push(N)}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 R6=class extends v{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])=>[f8(Y),f8(G)]),J=f8(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[X,W]=this.branches[G];if(await X.invoke(Q,K8(Z,{callbacks:J?.getChild(`condition:${G+1}`)}))){Y=await W.invoke(Q,K8(Z,{callbacks:J?.getChild(`branch:${G+1}`)}));break}}if(!Y)Y=await this.default.invoke(Q,K8(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 y1(Z))?.handleChainStart(this.toJSON(),L6(Q,"input"),Z?.runId,void 0,void 0,void 0,Z?.runName),Y,G=!0,X;try{for(let W=0;W<this.branches.length;W+=1){let[$,q]=this.branches[W];if(await $.invoke(Q,K8(Z,{callbacks:J?.getChild(`condition:${W+1}`)}))){X=await q.stream(Q,K8(Z,{callbacks:J?.getChild(`branch:${W+1}`)}));for await(let w of X)if(yield w,G)if(Y===void 0)Y=w;else try{Y=q8(Y,w)}catch{Y=void 0,G=!1}break}}if(X===void 0){X=await this.default.stream(Q,K8(Z,{callbacks:J?.getChild("branch:default")}));for await(let W of X)if(yield W,G)if(Y===void 0)Y=W;else try{Y=q8(Y,W)}catch{Y=void 0,G=!1}}}catch(W){throw await J?.handleChainError(W),W}await J?.handleChainEnd(Y??{})}};var V6=class extends k8{runnable;inputMessagesKey;outputMessagesKey;historyMessagesKey;getMessageHistory;constructor(Q){let Z=p.from((X,W)=>this._enterHistory(X,W??{})).withConfig({runName:"loadHistory"}),J=Q.historyMessagesKey??Q.inputMessagesKey;if(J)Z=_8.assign({[J]:Z}).withConfig({runName:"insertHistory"});let Y=Z.pipe(Q.runnable.withListeners({onEnd:(X,W)=>this._exitHistory(X,W??{})})).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)&&!n(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 u(Z)];else if(Array.isArray(Z))return Z;else if(n(Z))return[Z];else throw Error(`Expected a string, BaseMessage, or array of BaseMessages.
5
- Got ${JSON.stringify(Z,null,2)}`)}_getOutputMessages(Q){let Z;if(!Array.isArray(Q)&&!n(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 C(Z)];else if(Array.isArray(Z))return Z;else if(n(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 X=Q.outputs;if(!X)throw Error(`Output values from 'Run' undefined. Run: ${JSON.stringify(Q,null,2)}`);let W=this._getOutputMessages(X);await J.addMessages([...G,...W])}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()
6
- 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 y6=L({RouterRunnable:()=>F6,Runnable:()=>v,RunnableAssign:()=>M1,RunnableBinding:()=>k8,RunnableBranch:()=>R6,RunnableEach:()=>_6,RunnableLambda:()=>p,RunnableMap:()=>C1,RunnableParallel:()=>T6,RunnablePassthrough:()=>_8,RunnablePick:()=>C6,RunnableRetry:()=>j6,RunnableSequence:()=>v1,RunnableToolLike:()=>M6,RunnableWithFallbacks:()=>S6,RunnableWithMessageHistory:()=>V6,_coerceToRunnable:()=>f8,ensureConfig:()=>H8,getCallbackManagerForConfig:()=>y1,mergeConfigs:()=>P6,patchConfig:()=>K8,pickRunnableConfigKeys:()=>I6,raceWithSignal:()=>O6});var b6=L({applyPatch:()=>v6,compare:()=>E8});var g8=class extends v{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"})}},J8=class extends g8{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")}},h=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")}h8(this,"OUTPUT_PARSING_FAILURE")}};var U8=class extends J8{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"})}},W8=class extends U8{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(y8(Y)){if(typeof Y.content!=="string")throw Error("Cannot handle non-string message output.");G=new j8({message:Y,text:Y.content})}else if(n(Y)){if(typeof Y.content!=="string")throw Error("Cannot handle non-string message output.");G=new j8({message:O8(Y),text:Y.content})}else G=new b1({text:Y});if(J===void 0)J=G;else J=J.concat(G);let X=await this.parsePartialResult([J]);if(X!==void 0&&X!==null&&!x6(X,Z)){if(this.diff)yield this._diff(Z,X);else yield X;Z=X}}}getFormatInstructions(){return""}};var f6=class extends U8{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 d8=class extends U8{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 X of Y.slice(0,-1))yield[X[1]],G+=(X.index??0)+X[0].length;Z=Z.slice(G)}}}for(let J of await this.parse(Z))yield[J]}},k6=class extends d8{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 h(`Could not parse output: ${Q}`,Q)}}getFormatInstructions(){return"Your response should be a list of comma separated values, eg: `foo, bar, baz`"}},h6=class extends d8{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 h(`Incorrect number of items. Expected ${this.length}, got ${Z.length}.`);return Z}catch(Z){if(Object.getPrototypeOf(Z)===h.prototype)throw Z;throw new h(`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\`)`}},g6=class extends d8{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:
7
-
8
- 1. foo
9
-
10
- 2. bar
11
-
12
- 3. baz`}re=/\d+\.\s([^\n]+)/g;async parse(Q){return[...Q.matchAll(this.re)??[]].map((Z)=>Z[1])}},d6=class extends d8{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:
13
-
14
- 1. foo
15
-
16
- 2. bar
17
-
18
- 3. baz`}re=/^\s*[-*]\s([^\n]+)$/gm;async parse(Q){return[...Q.matchAll(this.re)??[]].map((Z)=>Z[1])}};var m6=class extends U8{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 x1=class extends W8{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 E8(Q,Z)}async parsePartialResult(Q){return T8(Q[0].text)}async parse(Q){return T8(Q,JSON.parse)}getFormatInstructions(){return""}_baseMessageToString(Q){return Q.text}};var f1=class extends J8{static lc_name(){return"StandardSchemaOutputParser"}lc_namespace=["langchain","output_parsers","standard_schema"];schema;constructor(Q){super();this.schema=Q}static fromSerializableSchema(Q){return new this(Q)}async parse(Q){try{let Z=T8(Q,JSON.parse),J=await this.schema["~standard"].validate(Z);if(J.issues)throw Error(`Validation failed: ${JSON.stringify(J.issues)}`);return J.value}catch(Z){throw new h(`Failed to parse. Text: "${Q}". Error: ${Z}`,Q)}}getFormatInstructions(){return""}};var H1=class extends J8{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=$1.object(Object.fromEntries(Object.entries(Q).map(([J,Y])=>[J,$1.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.
19
-
20
- "JSON Schema" is a declarative language that allows you to annotate and validate JSON documents.
21
-
22
- For example, the example "JSON Schema" instance {{"properties": {{"foo": {{"description": "a list of test words", "type": "array", "items": {{"type": "string"}}}}}}, "required": ["foo"]}}
23
- 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.
24
- 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.
25
-
26
- 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!
27
-
28
- Here is the JSON Schema instance your output must adhere to. Include the enclosing markdown codeblock:
29
- \`\`\`json
30
- ${JSON.stringify(g(this.schema))}
31
- \`\`\`
32
- `}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 O1(this.schema,JSON.parse(J))}catch(Z){throw new h(`Failed to parse. Text: "${Q}". Error: ${Z}`,Q)}}},S9=class extends H1{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:
33
- \`\`\`json
34
- ${this._schemaToInstruction(g(this.schema)).replaceAll("{","{".repeat(Z)).replaceAll("}","}".repeat(Z))}
35
- \`\`\``}_schemaToInstruction(Q,Z=2){let J=Q;if("type"in J){let Y=!1,G;if(Array.isArray(J.type)){let $=J.type.findIndex((q)=>q==="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`{
36
- ${Object.entries(J.properties).map(([q,w])=>{let D=J.required?.includes(q)?"":" (optional)";return`${" ".repeat(Z)}"${q}": ${this._schemaToInstruction(w,Z+2)}${D}`}).join(`
37
- `)}
38
- ${" ".repeat(Z-2)}}${$}`}if(J.type==="array"&&J.items){let $=J.description?` // ${J.description}`:"";return`array[
39
- ${" ".repeat(Z)}${this._schemaToInstruction(J.items,Z+2)}
40
- ${" ".repeat(Z-2)}] ${$}`}let X=Y?" (nullable)":"",W=J.description?` // ${J.description}`:"";return`${G}${W}${X}`}if("anyOf"in J)return J.anyOf.map((Y)=>this._schemaToInstruction(Y,Z)).join(`
41
- ${" ".repeat(Z-2)}`);throw Error("unsupported schema type")}static fromZodSchema(Q){return new this(Q)}static fromNamesAndDescriptions(Q){let Z=$1.object(Object.fromEntries(Object.entries(Q).map(([J,Y])=>[J,$1.string().describe(Y)])));return new this(Z)}},c6=class extends J8{structuredInputParser;constructor({inputSchema:Q}){super(...arguments);this.structuredInputParser=new S9(Q)}async parse(Q){let Z;try{Z=await this.structuredInputParser.parse(Q)}catch(J){throw new h(`Failed to parse. Text: "${Q}". Error: ${J}`,Q)}return this.outputProcessor(Z)}getFormatInstructions(){return this.structuredInputParser.getFormatInstructions()}};var L3=function(){let Q={};Q.parser=function(H,z){return new J(H,z)},Q.SAXParser=J,Q.SAXStream=w,Q.createStream=q,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(H,z){if(!(this instanceof J))return new J(H,z);var B=this;if(G(B),B.q=B.c="",B.bufferCheckPosition=Q.MAX_BUFFER_LENGTH,B.opt=z||{},B.opt.lowercase=B.opt.lowercase||B.opt.lowercasetags,B.looseCase=B.opt.lowercase?"toLowerCase":"toUpperCase",B.tags=[],B.closed=B.closedRoot=B.sawRoot=!1,B.tag=B.error=null,B.strict=!!H,B.noscript=!!(H||B.opt.noscript),B.state=K.BEGIN,B.strictEntities=B.opt.strictEntities,B.ENTITIES=B.strictEntities?Object.create(Q.XML_ENTITIES):Object.create(Q.ENTITIES),B.attribList=[],B.opt.xmlns)B.ns=Object.create(E);if(B.trackPosition=B.opt.position!==!1,B.trackPosition)B.position=B.line=B.column=0;y(B,"onready")}if(!Object.create)Object.create=function(H){function z(){}return z.prototype=H,new z};if(!Object.keys)Object.keys=function(H){var z=[];for(var B in H)if(H.hasOwnProperty(B))z.push(B);return z};function Y(H){var z=Math.max(Q.MAX_BUFFER_LENGTH,10),B=0;for(var U=0,j=Z.length;U<j;U++){var b=H[Z[U]].length;if(b>z)switch(Z[U]){case"textNode":a8(H);break;case"cdata":M(H,"oncdata",H.cdata),H.cdata="";break;case"script":M(H,"onscript",H.script),H.script="";break;default:F1(H,"Max buffer length exceeded: "+Z[U])}B=Math.max(B,b)}H.bufferCheckPosition=Q.MAX_BUFFER_LENGTH-B+H.position}function G(H){for(var z=0,B=Z.length;z<B;z++)H[Z[z]]=""}function X(H){if(a8(H),H.cdata!=="")M(H,"oncdata",H.cdata),H.cdata="";if(H.script!=="")M(H,"onscript",H.script),H.script=""}J.prototype={end:function(){L0(this)},write:H3,resume:function(){return this.error=null,this},close:function(){return this.write(null)},flush:function(){X(this)}};var W=ReadableStream;if(!W)W=function(){};var $=Q.EVENTS.filter(function(H){return H!=="error"&&H!=="end"});function q(H,z){return new w(H,z)}function w(H,z){if(!(this instanceof w))return new w(H,z);W.apply(this),this._parser=new J(H,z),this.writable=!0,this.readable=!0;var B=this;this._parser.onend=function(){B.emit("end")},this._parser.onerror=function(U){B.emit("error",U),B._parser.error=null},this._decoder=null,$.forEach(function(U){Object.defineProperty(B,"on"+U,{get:function(){return B._parser["on"+U]},set:function(j){if(!j)return B.removeAllListeners(U),B._parser["on"+U]=j,j;B.on(U,j)},enumerable:!0,configurable:!1})})}w.prototype=Object.create(W.prototype,{constructor:{value:w}}),w.prototype.write=function(H){return this._parser.write(H.toString()),this.emit("data",H),!0},w.prototype.end=function(H){if(H&&H.length)this.write(H);return this._parser.end(),!0},w.prototype.on=function(H,z){var B=this;if(!B._parser["on"+H]&&$.indexOf(H)!==-1)B._parser["on"+H]=function(){var U=arguments.length===1?[arguments[0]]:Array.apply(null,arguments);U.splice(0,0,H),B.emit.apply(B,U)};return W.prototype.on.call(B,H,z)};var D="[CDATA[",A="DOCTYPE",N="http://www.w3.org/XML/1998/namespace",F="http://www.w3.org/2000/xmlns/",E={xml:N,xmlns:F},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]/,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\u00B7\u0300-\u036F\u203F-\u2040.\d-]/,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]/,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-]/;function O(H){return H===" "||H===`
42
- `||H==="\r"||H==="\t"}function T(H){return H==='"'||H==="'"}function m(H){return H===">"||O(H)}function x(H,z){return H.test(z)}function f(H,z){return!x(H,z)}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(H){var z=Q.ENTITIES[H],B=typeof z==="number"?String.fromCharCode(z):z;Q.ENTITIES[H]=B});for(var M8 in Q.STATE)Q.STATE[Q.STATE[M8]]=M8;K=Q.STATE;function y(H,z,B){H[z]&&H[z](B)}function M(H,z,B){if(H.textNode)a8(H);y(H,z,B)}function a8(H){if(H.textNode=F0(H.opt,H.textNode),H.textNode)y(H,"ontext",H.textNode);H.textNode=""}function F0(H,z){if(H.trim)z=z.trim();if(H.normalize)z=z.replace(/\s+/g," ");return z}function F1(H,z){if(a8(H),H.trackPosition)z+=`
43
- Line: `+H.line+`
44
- Column: `+H.column+`
45
- Char: `+H.c;return z=Error(z),H.error=z,y(H,"onerror",z),H}function L0(H){if(H.sawRoot&&!H.closedRoot)S(H,"Unclosed root tag");if(H.state!==K.BEGIN&&H.state!==K.BEGIN_WHITESPACE&&H.state!==K.TEXT)F1(H,"Unexpected end");return a8(H),H.c="",H.closed=!0,y(H,"onend"),J.call(H,H.strict,H.opt),H}function S(H,z){if(typeof H!=="object"||!(H instanceof J))throw Error("bad call to strictFail");if(H.strict)F1(H,z)}function $3(H){if(!H.strict)H.tagName=H.tagName[H.looseCase]();var z=H.tags[H.tags.length-1]||H,B=H.tag={name:H.tagName,attributes:{}};if(H.opt.xmlns)B.ns=z.ns;H.attribList.length=0,M(H,"onopentagstart",B)}function W9(H,z){var B=H.indexOf(":")<0?["",H]:H.split(":"),U=B[0],j=B[1];if(z&&H==="xmlns")U="xmlns",j="";return{prefix:U,local:j}}function z9(H){if(!H.strict)H.attribName=H.attribName[H.looseCase]();if(H.attribList.indexOf(H.attribName)!==-1||H.tag.attributes.hasOwnProperty(H.attribName)){H.attribName=H.attribValue="";return}if(H.opt.xmlns){var z=W9(H.attribName,!0),B=z.prefix,U=z.local;if(B==="xmlns")if(U==="xml"&&H.attribValue!==N)S(H,"xml: prefix must be bound to "+N+`
46
- Actual: `+H.attribValue);else if(U==="xmlns"&&H.attribValue!==F)S(H,"xmlns: prefix must be bound to "+F+`
47
- Actual: `+H.attribValue);else{var j=H.tag,b=H.tags[H.tags.length-1]||H;if(j.ns===b.ns)j.ns=Object.create(b.ns);j.ns[U]=H.attribValue}H.attribList.push([H.attribName,H.attribValue])}else H.tag.attributes[H.attribName]=H.attribValue,M(H,"onattribute",{name:H.attribName,value:H.attribValue});H.attribName=H.attribValue=""}function R8(H,z){if(H.opt.xmlns){var B=H.tag,U=W9(H.tagName);if(B.prefix=U.prefix,B.local=U.local,B.uri=B.ns[U.prefix]||"",B.prefix&&!B.uri)S(H,"Unbound namespace prefix: "+JSON.stringify(H.tagName)),B.uri=U.prefix;var j=H.tags[H.tags.length-1]||H;if(B.ns&&j.ns!==B.ns)Object.keys(B.ns).forEach(function(O0){M(H,"onopennamespace",{prefix:O0,uri:B.ns[O0]})});for(var b=0,i=H.attribList.length;b<i;b++){var c=H.attribList[b],t=c[0],V8=c[1],k=W9(t,!0),P8=k.prefix,q3=k.local,I0=P8===""?"":B.ns[P8]||"",H9={name:t,value:V8,prefix:P8,local:q3,uri:I0};if(P8&&P8!=="xmlns"&&!I0)S(H,"Unbound namespace prefix: "+JSON.stringify(P8)),H9.uri=P8;H.tag.attributes[t]=H9,M(H,"onattribute",H9)}H.attribList.length=0}if(H.tag.isSelfClosing=!!z,H.sawRoot=!0,H.tags.push(H.tag),M(H,"onopentag",H.tag),!z){if(!H.noscript&&H.tagName.toLowerCase()==="script")H.state=K.SCRIPT;else H.state=K.TEXT;H.tag=null,H.tagName=""}H.attribName=H.attribValue="",H.attribList.length=0}function $9(H){if(!H.tagName){S(H,"Weird empty close tag."),H.textNode+="</>",H.state=K.TEXT;return}if(H.script){if(H.tagName!=="script"){H.script+="</"+H.tagName+">",H.tagName="",H.state=K.SCRIPT;return}M(H,"onscript",H.script),H.script=""}var z=H.tags.length,B=H.tagName;if(!H.strict)B=B[H.looseCase]();var U=B;while(z--)if(H.tags[z].name!==U)S(H,"Unexpected close tag");else break;if(z<0){S(H,"Unmatched closing tag: "+H.tagName),H.textNode+="</"+H.tagName+">",H.state=K.TEXT;return}H.tagName=B;var j=H.tags.length;while(j-- >z){var b=H.tag=H.tags.pop();H.tagName=H.tag.name,M(H,"onclosetag",H.tagName);var i={};for(var c in b.ns)i[c]=b.ns[c];var t=H.tags[H.tags.length-1]||H;if(H.opt.xmlns&&b.ns!==t.ns)Object.keys(b.ns).forEach(function(V8){var k=b.ns[V8];M(H,"onclosenamespace",{prefix:V8,uri:k})})}if(z===0)H.closedRoot=!0;H.tagName=H.attribValue=H.attribName="",H.attribList.length=0,H.state=K.TEXT}function R0(H){var z=H.entity,B=z.toLowerCase(),U,j="";if(H.ENTITIES[z])return H.ENTITIES[z];if(H.ENTITIES[B])return H.ENTITIES[B];if(z=B,z.charAt(0)==="#")if(z.charAt(1)==="x")z=z.slice(2),U=parseInt(z,16),j=U.toString(16);else z=z.slice(1),U=parseInt(z,10),j=U.toString(10);if(z=z.replace(/^0+/,""),isNaN(U)||j.toLowerCase()!==z)return S(H,"Invalid character entity"),"&"+H.entity+";";return String.fromCodePoint(U)}function V0(H,z){if(z==="<")H.state=K.OPEN_WAKA,H.startTagPosition=H.position;else if(!O(z))S(H,"Non-whitespace before first tag."),H.textNode=z,H.state=K.TEXT}function P0(H,z){var B="";if(z<H.length)B=H.charAt(z);return B}function H3(H){var z=this;if(this.error)throw this.error;if(z.closed)return F1(z,"Cannot write after close. Assign an onready handler.");if(H===null)return L0(z);if(typeof H==="object")H=H.toString();var B=0,U="";while(!0){if(U=P0(H,B++),z.c=U,!U)break;if(z.trackPosition)if(z.position++,U===`
48
- `)z.line++,z.column=0;else z.column++;switch(z.state){case K.BEGIN:if(z.state=K.BEGIN_WHITESPACE,U==="\uFEFF")continue;V0(z,U);continue;case K.BEGIN_WHITESPACE:V0(z,U);continue;case K.TEXT:if(z.sawRoot&&!z.closedRoot){var j=B-1;while(U&&U!=="<"&&U!=="&")if(U=P0(H,B++),U&&z.trackPosition)if(z.position++,U===`
49
- `)z.line++,z.column=0;else z.column++;z.textNode+=H.substring(j,B-1)}if(U==="<"&&!(z.sawRoot&&z.closedRoot&&!z.strict))z.state=K.OPEN_WAKA,z.startTagPosition=z.position;else{if(!O(U)&&(!z.sawRoot||z.closedRoot))S(z,"Text data outside of root node.");if(U==="&")z.state=K.TEXT_ENTITY;else z.textNode+=U}continue;case K.SCRIPT:if(U==="<")z.state=K.SCRIPT_ENDING;else z.script+=U;continue;case K.SCRIPT_ENDING:if(U==="/")z.state=K.CLOSE_TAG;else z.script+="<"+U,z.state=K.SCRIPT;continue;case K.OPEN_WAKA:if(U==="!")z.state=K.SGML_DECL,z.sgmlDecl="";else if(O(U));else if(x(R,U))z.state=K.OPEN_TAG,z.tagName=U;else if(U==="/")z.state=K.CLOSE_TAG,z.tagName="";else if(U==="?")z.state=K.PROC_INST,z.procInstName=z.procInstBody="";else{if(S(z,"Unencoded <"),z.startTagPosition+1<z.position){var b=z.position-z.startTagPosition;U=Array(b).join(" ")+U}z.textNode+="<"+U,z.state=K.TEXT}continue;case K.SGML_DECL:if((z.sgmlDecl+U).toUpperCase()===D)M(z,"onopencdata"),z.state=K.CDATA,z.sgmlDecl="",z.cdata="";else if(z.sgmlDecl+U==="--")z.state=K.COMMENT,z.comment="",z.sgmlDecl="";else if((z.sgmlDecl+U).toUpperCase()===A){if(z.state=K.DOCTYPE,z.doctype||z.sawRoot)S(z,"Inappropriately located doctype declaration");z.doctype="",z.sgmlDecl=""}else if(U===">")M(z,"onsgmldeclaration",z.sgmlDecl),z.sgmlDecl="",z.state=K.TEXT;else if(T(U))z.state=K.SGML_DECL_QUOTED,z.sgmlDecl+=U;else z.sgmlDecl+=U;continue;case K.SGML_DECL_QUOTED:if(U===z.q)z.state=K.SGML_DECL,z.q="";z.sgmlDecl+=U;continue;case K.DOCTYPE:if(U===">")z.state=K.TEXT,M(z,"ondoctype",z.doctype),z.doctype=!0;else if(z.doctype+=U,U==="[")z.state=K.DOCTYPE_DTD;else if(T(U))z.state=K.DOCTYPE_QUOTED,z.q=U;continue;case K.DOCTYPE_QUOTED:if(z.doctype+=U,U===z.q)z.q="",z.state=K.DOCTYPE;continue;case K.DOCTYPE_DTD:if(z.doctype+=U,U==="]")z.state=K.DOCTYPE;else if(T(U))z.state=K.DOCTYPE_DTD_QUOTED,z.q=U;continue;case K.DOCTYPE_DTD_QUOTED:if(z.doctype+=U,U===z.q)z.state=K.DOCTYPE_DTD,z.q="";continue;case K.COMMENT:if(U==="-")z.state=K.COMMENT_ENDING;else z.comment+=U;continue;case K.COMMENT_ENDING:if(U==="-"){if(z.state=K.COMMENT_ENDED,z.comment=F0(z.opt,z.comment),z.comment)M(z,"oncomment",z.comment);z.comment=""}else z.comment+="-"+U,z.state=K.COMMENT;continue;case K.COMMENT_ENDED:if(U!==">")S(z,"Malformed comment"),z.comment+="--"+U,z.state=K.COMMENT;else z.state=K.TEXT;continue;case K.CDATA:if(U==="]")z.state=K.CDATA_ENDING;else z.cdata+=U;continue;case K.CDATA_ENDING:if(U==="]")z.state=K.CDATA_ENDING_2;else z.cdata+="]"+U,z.state=K.CDATA;continue;case K.CDATA_ENDING_2:if(U===">"){if(z.cdata)M(z,"oncdata",z.cdata);M(z,"onclosecdata"),z.cdata="",z.state=K.TEXT}else if(U==="]")z.cdata+="]";else z.cdata+="]]"+U,z.state=K.CDATA;continue;case K.PROC_INST:if(U==="?")z.state=K.PROC_INST_ENDING;else if(O(U))z.state=K.PROC_INST_BODY;else z.procInstName+=U;continue;case K.PROC_INST_BODY:if(!z.procInstBody&&O(U))continue;else if(U==="?")z.state=K.PROC_INST_ENDING;else z.procInstBody+=U;continue;case K.PROC_INST_ENDING:if(U===">")M(z,"onprocessinginstruction",{name:z.procInstName,body:z.procInstBody}),z.procInstName=z.procInstBody="",z.state=K.TEXT;else z.procInstBody+="?"+U,z.state=K.PROC_INST_BODY;continue;case K.OPEN_TAG:if(x(V,U))z.tagName+=U;else if($3(z),U===">")R8(z);else if(U==="/")z.state=K.OPEN_TAG_SLASH;else{if(!O(U))S(z,"Invalid character in tag name");z.state=K.ATTRIB}continue;case K.OPEN_TAG_SLASH:if(U===">")R8(z,!0),$9(z);else S(z,"Forward-slash in opening tag not followed by >"),z.state=K.ATTRIB;continue;case K.ATTRIB:if(O(U))continue;else if(U===">")R8(z);else if(U==="/")z.state=K.OPEN_TAG_SLASH;else if(x(R,U))z.attribName=U,z.attribValue="",z.state=K.ATTRIB_NAME;else S(z,"Invalid attribute name");continue;case K.ATTRIB_NAME:if(U==="=")z.state=K.ATTRIB_VALUE;else if(U===">")S(z,"Attribute without value"),z.attribValue=z.attribName,z9(z),R8(z);else if(O(U))z.state=K.ATTRIB_NAME_SAW_WHITE;else if(x(V,U))z.attribName+=U;else S(z,"Invalid attribute name");continue;case K.ATTRIB_NAME_SAW_WHITE:if(U==="=")z.state=K.ATTRIB_VALUE;else if(O(U))continue;else if(S(z,"Attribute without value"),z.tag.attributes[z.attribName]="",z.attribValue="",M(z,"onattribute",{name:z.attribName,value:""}),z.attribName="",U===">")R8(z);else if(x(R,U))z.attribName=U,z.state=K.ATTRIB_NAME;else S(z,"Invalid attribute name"),z.state=K.ATTRIB;continue;case K.ATTRIB_VALUE:if(O(U))continue;else if(T(U))z.q=U,z.state=K.ATTRIB_VALUE_QUOTED;else S(z,"Unquoted attribute value"),z.state=K.ATTRIB_VALUE_UNQUOTED,z.attribValue=U;continue;case K.ATTRIB_VALUE_QUOTED:if(U!==z.q){if(U==="&")z.state=K.ATTRIB_VALUE_ENTITY_Q;else z.attribValue+=U;continue}z9(z),z.q="",z.state=K.ATTRIB_VALUE_CLOSED;continue;case K.ATTRIB_VALUE_CLOSED:if(O(U))z.state=K.ATTRIB;else if(U===">")R8(z);else if(U==="/")z.state=K.OPEN_TAG_SLASH;else if(x(R,U))S(z,"No whitespace between attributes"),z.attribName=U,z.attribValue="",z.state=K.ATTRIB_NAME;else S(z,"Invalid attribute name");continue;case K.ATTRIB_VALUE_UNQUOTED:if(!m(U)){if(U==="&")z.state=K.ATTRIB_VALUE_ENTITY_U;else z.attribValue+=U;continue}if(z9(z),U===">")R8(z);else z.state=K.ATTRIB;continue;case K.CLOSE_TAG:if(!z.tagName)if(O(U))continue;else if(f(R,U))if(z.script)z.script+="</"+U,z.state=K.SCRIPT;else S(z,"Invalid tagname in closing tag.");else z.tagName=U;else if(U===">")$9(z);else if(x(V,U))z.tagName+=U;else if(z.script)z.script+="</"+z.tagName,z.tagName="",z.state=K.SCRIPT;else{if(!O(U))S(z,"Invalid tagname in closing tag");z.state=K.CLOSE_TAG_SAW_WHITE}continue;case K.CLOSE_TAG_SAW_WHITE:if(O(U))continue;if(U===">")$9(z);else S(z,"Invalid characters in closing tag");continue;case K.TEXT_ENTITY:case K.ATTRIB_VALUE_ENTITY_Q:case K.ATTRIB_VALUE_ENTITY_U:var i,c;switch(z.state){case K.TEXT_ENTITY:i=K.TEXT,c="textNode";break;case K.ATTRIB_VALUE_ENTITY_Q:i=K.ATTRIB_VALUE_QUOTED,c="attribValue";break;case K.ATTRIB_VALUE_ENTITY_U:i=K.ATTRIB_VALUE_UNQUOTED,c="attribValue";break}if(U===";")if(z.opt.unparsedEntities){var t=R0(z);z.entity="",z.state=i,z.write(t)}else z[c]+=R0(z),z.entity="",z.state=i;else if(x(z.entity.length?P:I,U))z.entity+=U;else S(z,"Invalid character in entity name"),z[c]+="&"+z.entity+U,z.entity="",z.state=i;continue;default:throw Error(z,"Unknown state: "+z.state)}}if(z.position>=z.bufferCheckPosition)Y(z);return z}/*! http://mths.be/fromcodepoint v0.1.0 by @mathias */if(!String.fromCodePoint)(function(){var H=String.fromCharCode,z=Math.floor,B=function(){var U=16384,j=[],b,i,c=-1,t=arguments.length;if(!t)return"";var V8="";while(++c<t){var k=Number(arguments[c]);if(!isFinite(k)||k<0||k>1114111||z(k)!==k)throw RangeError("Invalid code point: "+k);if(k<=65535)j.push(k);else k-=65536,b=(k>>10)+55296,i=k%1024+56320,j.push(b,i);if(c+1===t||j.length>U)V8+=H.apply(null,j),j.length=0}return V8};if(Object.defineProperty)Object.defineProperty(String,"fromCodePoint",{value:B,configurable:!0,writable:!0});else String.fromCodePoint=B})();return Q},u6=L3();var k1=`The output should be formatted as a XML file.
50
- 1. Output should conform to the tags below.
51
- 2. If tags are not given, make them on your own.
52
- 3. Remember to always open and close all the tags.
53
-
54
- As an example, for the tags ["foo", "bar", "baz"]:
55
- 1. String "<foo>
56
- <bar>
57
- <baz></baz>
58
- </bar>
59
- </foo>" is a well-formatted instance of the schema.
60
- 2. String "<foo>
61
- <bar>
62
- </foo>" is a badly-formatted instance.
63
- 3. String "<foo>
64
- <tag>
65
- </tag>
66
- </foo>" is a badly-formatted instance.
67
-
68
- Here are the output tags:
69
- \`\`\`
70
- {tags}
71
- \`\`\``,l6=class extends W8{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 E8(Q,Z)}async parsePartialResult(Q){return h1(Q[0].text)}async parse(Q){return h1(Q)}getFormatInstructions(){return this.tags&&this.tags.length>0?k1.replace("{tags}",this.tags?.join(", ")??""):k1}},R3=(Q)=>Q.split(`
72
- `).map((Z)=>Z.replace(/^\s+/,"")).join(`
73
- `).trim(),p6=(Q)=>{if(Object.keys(Q).length===0)return{};let Z={};if(Q.children.length>0)return Z[Q.name]=Q.children.map(p6),Z;else return Z[Q.name]=Q.text??void 0,Z};function h1(Q){let Z=R3(Q),J=u6.parser(!0),Y={},G=[];J.onopentag=($)=>{let q={name:$.name,attributes:$.attributes,children:[],text:"",isSelfClosing:$.isSelfClosing};if(G.length>0)G[G.length-1].children.push(q);else Y=q;if(!$.isSelfClosing)G.push(q)},J.onclosetag=()=>{if(G.length>0){let $=G.pop();if(G.length===0&&$)Y=$}},J.ontext=($)=>{if(G.length>0){let q=G[G.length-1];q.text+=$}},J.onattribute=($)=>{if(G.length>0){let q=G[G.length-1];q.attributes[$.name]=$.value}};let X=/```(xml)?(.*)```/s.exec(Z),W=X?X[2]:Z;if(J.write(W).close(),Y&&Y.name==="?xml")Y=Y.children[0];return p6(Y)}var o6=L({AsymmetricStructuredOutputParser:()=>c6,BaseCumulativeTransformOutputParser:()=>W8,BaseLLMOutputParser:()=>g8,BaseOutputParser:()=>J8,BaseTransformOutputParser:()=>U8,BytesOutputParser:()=>f6,CommaSeparatedListOutputParser:()=>k6,CustomListOutputParser:()=>h6,JsonMarkdownStructuredOutputParser:()=>S9,JsonOutputParser:()=>x1,ListOutputParser:()=>d8,MarkdownListOutputParser:()=>d6,NumberedListOutputParser:()=>g6,OutputParserException:()=>h,StandardSchemaOutputParser:()=>f1,StringOutputParser:()=>m6,StructuredOutputParser:()=>H1,XMLOutputParser:()=>l6,XML_FORMAT_INSTRUCTIONS:()=>k1,parseJsonMarkdown:()=>T8,parsePartialJson:()=>F8,parseXMLMarkdown:()=>h1});function C9(Q,Z){if(Q.function===void 0)return;let J;if(Z?.partial)try{J=F8(Q.function.arguments??"{}")}catch{return}else try{J=JSON.parse(Q.function.arguments)}catch(G){throw new h([`Function "${Q.function.name}" arguments:`,"",Q.function.arguments,"","are not valid JSON.",`Error: ${G.message}`].join(`
74
- `))}let Y={name:Q.function.name,args:J,type:"tool_call"};if(Z?.returnId)Y.id=Q.id;return Y}function i6(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 n6(Q,Z){return{name:Q.function?.name,args:Q.function?.arguments,id:Q.id,error:Z,type:"invalid_tool_call"}}var M9=class extends W8{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(v8(J)&&J.tool_calls?.length)Y=J.tool_calls.map((X)=>{let{id:W,...$}=X;if(!this.returnId)return $;return{id:W,...$}});else if(J.additional_kwargs.tool_calls!==void 0)Y=JSON.parse(JSON.stringify(J.additional_kwargs.tool_calls)).map((X)=>{return C9(X,{returnId:this.returnId,partial:Z})});if(!Y)return[];let G=[];for(let X of Y)if(X!==void 0){let W={type:X.name,args:X.args,id:X.id};G.push(W)}return G}},g1=class extends M9{static lc_name(){return"JsonOutputKeyToolsParser"}lc_namespace=["langchain","output_parsers","openai_tools"];lc_serializable=!0;returnId=!1;keyName;returnSingle=!1;zodSchema;serializableSchema;constructor(Q){super(Q);if(this.keyName=Q.keyName,this.returnSingle=Q.returnSingle??this.returnSingle,"zodSchema"in Q)this.zodSchema=Q.zodSchema;if("serializableSchema"in Q)this.serializableSchema=Q.serializableSchema}async _validateResult(Q){if(this.serializableSchema!==void 0){let J=await this.serializableSchema["~standard"].validate(Q);if(J.issues)throw new h(`Failed to parse. Text: "${JSON.stringify(Q,null,2)}". Error: ${JSON.stringify(J.issues)}`,JSON.stringify(Q,null,2));return J.value}if(this.zodSchema===void 0)return Q;let Z=await I1(this.zodSchema,Q);if(Z.success)return Z.data;else throw new h(`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 r6=L({assembleStructuredOutputPipeline:()=>y9,createContentParser:()=>V3,createFunctionCallingParser:()=>P3});function V3(Q){if(A8(Q))return H1.fromZodSchema(Q);if(m8(Q))return f1.fromSerializableSchema(Q);return new x1}function P3(Q,Z,J){let Y=J??g1;if(A8(Q))return new Y({returnSingle:!0,keyName:Z,zodSchema:Q});if(m8(Q))return new Y({returnSingle:!0,keyName:Z,serializableSchema:Q});return new Y({returnSingle:!0,keyName:Z})}function y9(Q,Z,J,Y){if(!J){let q=Q.pipe(Z);return Y?q.withConfig({runName:Y}):q}let G=_8.assign({parsed:(q,w)=>Z.invoke(q.raw,w)}),X=_8.assign({parsed:()=>null}),W=G.withFallbacks({fallbacks:[X]}),$=v1.from([{raw:Q},W]);return Y?$.withConfig({runName:Y}):$}var s6=(Q)=>Q();function d1(Q){return new Q.constructor({...Q,content:Q.contentBlocks,response_metadata:{...Q.response_metadata,output_version:"v1"}})}var t6=L({BaseChatModel:()=>L8,SimpleChatModel:()=>I3});function v9(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 X=J.content[G];if(R1(X)||V1(X)){if(Y===J)Y=new J.constructor({...Y,content:[...J.content.slice(0,G),P1(X),...J.content.slice(G+1)]})}}Z.push(Y)}return Z}var L8=class Q extends u1{lc_namespace=["langchain","chat_models",this._llmType()];disableStreaming=!1;outputVersion;get callKeys(){return[...super.callKeys,"outputVersion"]}constructor(Z){super(Z);this.outputVersion=s6(()=>{let J=Z.outputVersion??m1("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,X]=this._separateRunnableConfigFromCallOptionsCompat(J),W={...G.metadata,...this.getLsParams(X)},$=await z8.configure(G.callbacks,this.callbacks,G.tags,this.tags,W,this.metadata,{verbose:this.verbose}),q={options:X,invocation_params:this?.invocationParams(X),batch_size:1},w=X.outputVersion??this.outputVersion,D=await $?.handleChatModelStart(this.toJSON(),[v9(Y)],G.runId,void 0,q,void 0,void 0,G.runName),A,N;try{for await(let F of this._streamResponseChunks(Y,X,D?.[0])){if(X.signal?.throwIfAborted(),F.message.id==null){let E=D?.at(0)?.runId;if(E!=null)F.message._updateId(`run-${E}`)}if(F.message.response_metadata={...F.generationInfo,...F.message.response_metadata},w==="v1")yield d1(F.message);else yield F.message;if(!A)A=F;else A=A.concat(F);if(W1(F.message)&&F.message.usage_metadata!==void 0)N={tokenUsage:{promptTokens:F.message.usage_metadata.input_tokens,completionTokens:F.message.usage_metadata.output_tokens,totalTokens:F.message.usage_metadata.total_tokens}}}X.signal?.throwIfAborted()}catch(F){throw await Promise.all((D??[]).map((E)=>E?.handleLLMError(F))),F}await Promise.all((D??[]).map((F)=>F?.handleLLMEnd({generations:[[A]],llmOutput:N})))}}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 X=Z.map((A)=>A.map(X8)),W;if(G!==void 0&&G.length===X.length)W=G;else{let A={...Y.metadata,...this.getLsParams(J)},N=await z8.configure(Y.callbacks,this.callbacks,Y.tags,this.tags,A,this.metadata,{verbose:this.verbose}),F={options:J,invocation_params:this?.invocationParams(J),batch_size:1};W=await N?.handleChatModelStart(this.toJSON(),X.map(v9),Y.runId,void 0,F,void 0,void 0,Y.runName)}let $=J.outputVersion??this.outputVersion,q=[],w=[];if(!!W?.[0].handlers.find(c1)&&!this.disableStreaming&&X.length===1&&this._streamResponseChunks!==Q.prototype._streamResponseChunks)try{let A=await this._streamResponseChunks(X[0],J,W?.[0]),N,F;for await(let E of A){if(J.signal?.aborted){let R=N?.message;throw new b9("Model invocation was aborted.",R)}if(E.message.id==null){let R=W?.at(0)?.runId;if(R!=null)E.message._updateId(`run-${R}`)}if(N===void 0)N=E;else N=q8(N,E);if(W1(E.message)&&E.message.usage_metadata!==void 0)F={tokenUsage:{promptTokens:E.message.usage_metadata.input_tokens,completionTokens:E.message.usage_metadata.output_tokens,totalTokens:E.message.usage_metadata.total_tokens}}}if(J.signal?.aborted){let E=N?.message;throw new b9("Model invocation was aborted.",E)}if(N===void 0)throw Error("Received empty response from chat model call.");q.push([N]),await W?.[0].handleLLMEnd({generations:q,llmOutput:F})}catch(A){throw await W?.[0].handleLLMError(A),A}else{let A=await Promise.allSettled(X.map(async(N,F)=>{let E=await this._generate(N,{...J,promptIndex:F},W?.[F]);if($==="v1")for(let R of E.generations)R.message=d1(R.message);return E}));await Promise.all(A.map(async(N,F)=>{if(N.status==="fulfilled"){let E=N.value;for(let R of E.generations){if(R.message.id==null){let V=W?.at(0)?.runId;if(V!=null)R.message._updateId(`run-${V}`)}R.message.response_metadata={...R.generationInfo,...R.message.response_metadata}}if(E.generations.length===1)E.generations[0].message.response_metadata={...E.llmOutput,...E.generations[0].message.response_metadata};return q[F]=E.generations,w[F]=E.llmOutput,W?.[F]?.handleLLMEnd({generations:[E.generations],llmOutput:E.llmOutput})}else return await W?.[F]?.handleLLMError(N.reason),Promise.reject(N.reason)}))}let D={generations:q,llmOutput:w.length?this._combineLLMOutput?.(...w):void 0};return Object.defineProperty(D,c8,{value:W?{runIds:W?.map((A)=>A.runId)}:void 0,configurable:!0}),D}async _generateCached({messages:Z,cache:J,llmStringKey:Y,parsedOptions:G,handledOptions:X}){let W=Z.map((V)=>V.map(X8)),$={...X.metadata,...this.getLsParams(G)},q=await z8.configure(X.callbacks,this.callbacks,X.tags,this.tags,$,this.metadata,{verbose:this.verbose}),w={options:G,invocation_params:this?.invocationParams(G),batch_size:1},D=await q?.handleChatModelStart(this.toJSON(),W.map(v9),X.runId,void 0,w,void 0,void 0,X.runName),A=[],N=(await Promise.allSettled(W.map(async(V,I)=>{let P=Q._convertInputToPromptValue(V).toString(),O=await J.lookup(P,Y);if(O==null)A.push(I);return O}))).map((V,I)=>({result:V,runManager:D?.[I]})).filter(({result:V})=>V.status==="fulfilled"&&V.value!=null||V.status==="rejected"),F=G.outputVersion??this.outputVersion,E=[];await Promise.all(N.map(async({result:V,runManager:I},P)=>{if(V.status==="fulfilled"){let O=V.value;if(E[P]=O.map((T)=>{if("message"in T&&n(T.message)&&v8(T.message)){if(T.message.usage_metadata={input_tokens:0,output_tokens:0,total_tokens:0},F==="v1")T.message=d1(T.message)}return T.generationInfo={...T.generationInfo,tokenUsage:{}},T}),O.length)await I?.handleLLMNewToken(O[0].text);return I?.handleLLMEnd({generations:[O]},void 0,void 0,void 0,{cached:!0})}else return await I?.handleLLMError(V.reason,void 0,void 0,void 0,{cached:!0}),Promise.reject(V.reason)}));let R={generations:E,missingPromptIndices:A,startedRunManagers:D};return Object.defineProperty(R,c8,{value:D?{runIds:D?.map((V)=>V.runId)}:void 0,configurable:!0}),R}async generate(Z,J,Y){let G;if(Array.isArray(J))G={stop:J};else G=J;let X=Z.map((E)=>E.map(X8)),[W,$]=this._separateRunnableConfigFromCallOptionsCompat(G);if(W.callbacks=W.callbacks??Y,!this.cache)return this._generateUncached(X,$,W);let{cache:q}=this,w=this._getSerializedCacheKeyParametersForCall($),{generations:D,missingPromptIndices:A,startedRunManagers:N}=await this._generateCached({messages:X,cache:q,llmStringKey:w,parsedOptions:$,handledOptions:W}),F={};if(A.length>0){let E=await this._generateUncached(A.map((R)=>X[R]),$,W,N!==void 0?A.map((R)=>N?.[R]):void 0);await Promise.all(E.generations.map(async(R,V)=>{let I=A[V];D[I]=R;let P=Q._convertInputToPromptValue(X[I]).toString();return q.update(P,w,R)})),F=E.llmOutput??{}}return{generations:D,llmOutput:F}}invocationParams(Z){return{}}_modelType(){return"base_chat_model"}async generatePrompt(Z,J,Y){let G=Z.map((X)=>X.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,X=_1(Y)??"A function available to call.",W=J?.method,$=J?.includeRaw;if(W==="jsonMode")throw Error('Base withStructuredOutput implementation only supports "functionCalling" as a method.');let q=G??"extract";if(!A8(Y)&&!m8(Y)&&"name"in Y)q=Y.name;let w=A8(Y)||m8(Y)?g(Y):Y,D=[{type:"function",function:{name:q,description:X,parameters:w}}];return y9(this.bindTools(D),p.from((A)=>{if(!e.isInstance(A))throw Error("Input is not an AIMessageChunk.");if(!A.tool_calls||A.tool_calls.length===0)throw Error("No tool calls found in the response.");let N=A.tool_calls.find((F)=>F.name===q);if(!N)throw Error(`No tool call found with name ${q}.`);return N.args}),$,$?"StructuredOutputRunnable":"StructuredOutput")}},I3=class extends L8{async _generate(Q,Z,J){let Y=new C(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 a6=L({BaseLLM:()=>e6,LLM:()=>l1}),e6=class Q extends u1{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,X]=this._separateRunnableConfigFromCallOptionsCompat(J),W=await z8.configure(G.callbacks,this.callbacks,G.tags,this.tags,G.metadata,this.metadata,{verbose:this.verbose}),$={options:X,invocation_params:this?.invocationParams(X),batch_size:1},q=await W?.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(),X,q?.[0])){if(!w)w=D;else w=w.concat(D);if(typeof D.text==="string")yield D.text}}catch(D){throw await Promise.all((q??[]).map((A)=>A?.handleLLMError(D))),D}await Promise.all((q??[]).map((D)=>D?.handleLLMEnd({generations:[[w]]})))}}async generatePrompt(Z,J,Y){let G=Z.map((X)=>X.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 X=Z.llmOutput?{...Z.llmOutput,tokenUsage:{}}:void 0;J.push({generations:[G],llmOutput:X})}}return J}async _generateUncached(Z,J,Y,G){let X;if(G!==void 0&&G.length===Z.length)X=G;else{let w=await z8.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};X=await w?.handleLLMStart(this.toJSON(),Z,Y.runId,void 0,D,void 0,void 0,Y?.runName)}let W=!!X?.[0].handlers.find(c1),$;if(W&&Z.length===1&&this._streamResponseChunks!==Q.prototype._streamResponseChunks)try{let w=await this._streamResponseChunks(Z[0],J,X?.[0]),D;for await(let A of w)if(D===void 0)D=A;else D=q8(D,A);if(D===void 0)throw Error("Received empty response from chat model call.");$={generations:[[D]],llmOutput:{}},await X?.[0].handleLLMEnd($)}catch(w){throw await X?.[0].handleLLMError(w),w}else{try{$=await this._generate(Z,J,X?.[0])}catch(D){throw await Promise.all((X??[]).map((A)=>A?.handleLLMError(D))),D}let w=this._flattenLLMResult($);await Promise.all((X??[]).map((D,A)=>D?.handleLLMEnd(w[A])))}let q=X?.map((w)=>w.runId)||void 0;return Object.defineProperty($,c8,{value:q?{runIds:q}:void 0,configurable:!0}),$}async _generateCached({prompts:Z,cache:J,llmStringKey:Y,parsedOptions:G,handledOptions:X,runId:W}){let $=await z8.configure(X.callbacks,this.callbacks,X.tags,this.tags,X.metadata,this.metadata,{verbose:this.verbose}),q={options:G,invocation_params:this?.invocationParams(G),batch_size:Z.length},w=await $?.handleLLMStart(this.toJSON(),Z,W,void 0,q,void 0,void 0,X?.runName),D=[],A=(await Promise.allSettled(Z.map(async(E,R)=>{let V=await J.lookup(E,Y);if(V==null)D.push(R);return V}))).map((E,R)=>({result:E,runManager:w?.[R]})).filter(({result:E})=>E.status==="fulfilled"&&E.value!=null||E.status==="rejected"),N=[];await Promise.all(A.map(async({result:E,runManager:R},V)=>{if(E.status==="fulfilled"){let I=E.value;if(N[V]=I.map((P)=>{return P.generationInfo={...P.generationInfo,tokenUsage:{}},P}),I.length)await R?.handleLLMNewToken(I[0].text);return R?.handleLLMEnd({generations:[I]},void 0,void 0,void 0,{cached:!0})}else return await R?.handleLLMError(E.reason,void 0,void 0,void 0,{cached:!0}),Promise.reject(E.reason)}));let F={generations:N,missingPromptIndices:D,startedRunManagers:w};return Object.defineProperty(F,c8,{value:w?{runIds:w?.map((E)=>E.runId)}:void 0,configurable:!0}),F}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[X,W]=this._separateRunnableConfigFromCallOptionsCompat(G);if(X.callbacks=X.callbacks??Y,!this.cache)return this._generateUncached(Z,W,X);let{cache:$}=this,q=this._getSerializedCacheKeyParametersForCall(W),{generations:w,missingPromptIndices:D,startedRunManagers:A}=await this._generateCached({prompts:Z,cache:$,llmStringKey:q,parsedOptions:W,handledOptions:X,runId:X.runId}),N={};if(D.length>0){let F=await this._generateUncached(D.map((E)=>Z[E]),W,X,A!==void 0?D.map((E)=>A?.[E]):void 0);await Promise.all(F.generations.map(async(E,R)=>{let V=D[R];return w[V]=E,$.update(Z[V],q,E)})),N=F.llmOutput??{}}return{generations:w,llmOutput:N}}_identifyingParams(){return{}}_modelType(){return"base_llm"}},l1=class extends e6{async _generate(Q,Z,J){return{generations:await Promise.all(Q.map((Y,G)=>this._call(Y,{...Z,promptIndex:G},J).then((X)=>[{text:X}])))}}};var Q5=L({});var Z5=L({BaseMemory:()=>O3,getInputValue:()=>_3,getOutputValue:()=>j3,getPromptInputKey:()=>T3}),O3=class{},J5=(Q,Z)=>{if(Z!==void 0)return Q[Z];let J=Object.keys(Q);if(J.length===1)return Q[J[0]]},_3=(Q,Z)=>{let J=J5(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},j3=(Q,Z)=>{let J=J5(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 T3(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 x9=class extends g8{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)}`)}},f9=class extends W8{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 x9(Q)}_diff(Q,Z){if(!Z)return;return E8(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 F8(Y.arguments);return{...Y,arguments:F8(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""}},Y5=class extends g8{static lc_name(){return"JsonKeyOutputFunctionsParser"}lc_namespace=["langchain","output_parsers","openai_functions"];lc_serializable=!0;outputParser=new f9;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 G5=L({JsonKeyOutputFunctionsParser:()=>Y5,JsonOutputFunctionsParser:()=>f9,OutputFunctionsParser:()=>x9});var X5=L({JsonOutputKeyToolsParser:()=>g1,JsonOutputToolsParser:()=>M9,convertLangChainToolCallToOpenAI:()=>i6,makeInvalidToolCall:()=>n6,parseToolCall:()=>C9});var $8=class extends v{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 w8=class extends $8{async formatPromptValue(Q){return new W5(await this.format(Q))}};/*!
75
- * mustache.js - Logic-less {{mustache}} templates with JavaScript
76
- * http://github.com/janl/mustache.js
77
- */var S3=Object.prototype.toString,l8=Array.isArray||function(Z){return S3.call(Z)==="[object Array]"};function h9(Q){return typeof Q==="function"}function C3(Q){return l8(Q)?"array":typeof Q}function k9(Q){return Q.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function z5(Q,Z){return Q!=null&&typeof Q==="object"&&Z in Q}function M3(Q,Z){return Q!=null&&typeof Q!=="object"&&Q.hasOwnProperty&&Q.hasOwnProperty(Z)}var y3=RegExp.prototype.test;function v3(Q,Z){return y3.call(Q,Z)}var b3=/\S/;function x3(Q){return!v3(b3,Q)}var f3={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#x2F;","`":"&#x60;","=":"&#x3D;"};function k3(Q){return String(Q).replace(/[&<>"'`=\/]/g,function(J){return f3[J]})}var h3=/\s*/,g3=/\s+/,$5=/\s*=/,d3=/\s*\}/,m3=/#|\^|\/|>|\{|&|=|!/;function c3(Q,Z){if(!Q)return[];var J=!1,Y=[],G=[],X=[],W=!1,$=!1,q="",w=0;function D(){if(W&&!$)while(X.length)delete G[X.pop()];else X=[];W=!1,$=!1}var A,N,F;function E(K){if(typeof K==="string")K=K.split(g3,2);if(!l8(K)||K.length!==2)throw Error("Invalid tags: "+K);A=new RegExp(k9(K[0])+"\\s*"),N=new RegExp("\\s*"+k9(K[1])),F=new RegExp("\\s*"+k9("}"+K[1]))}E(Z||s.tags);var R=new K1(Q),V,I,P,O,T,m;while(!R.eos()){if(V=R.pos,P=R.scanUntil(A),P)for(var x=0,f=P.length;x<f;++x){if(O=P.charAt(x),x3(O))X.push(G.length),q+=O;else $=!0,J=!0,q+=" ";if(G.push(["text",O,V,V+1]),V+=1,O===`
78
- `)D(),q="",w=0,J=!1}if(!R.scan(A))break;if(W=!0,I=R.scan(m3)||"name",R.scan(h3),I==="=")P=R.scanUntil($5),R.scan($5),R.scanUntil(N);else if(I==="{")P=R.scanUntil(F),R.scan(d3),R.scanUntil(N),I="&";else P=R.scanUntil(N);if(!R.scan(N))throw Error("Unclosed tag at "+R.pos);if(I==">")T=[I,P,V,R.pos,q,w,J];else T=[I,P,V,R.pos];if(w++,G.push(T),I==="#"||I==="^")Y.push(T);else if(I==="/"){if(m=Y.pop(),!m)throw Error('Unopened section "'+P+'" at '+V);if(m[1]!==P)throw Error('Unclosed section "'+m[1]+'" at '+V)}else if(I==="name"||I==="{"||I==="&")$=!0;else if(I==="=")E(P)}if(D(),m=Y.pop(),m)throw Error('Unclosed section "'+m[1]+'" at '+R.pos);return l3(u3(G))}function u3(Q){var Z=[],J,Y;for(var G=0,X=Q.length;G<X;++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 l3(Q){var Z=[],J=Z,Y=[],G,X;for(var W=0,$=Q.length;W<$;++W)switch(G=Q[W],G[0]){case"#":case"^":J.push(G),Y.push(G),J=G[4]=[];break;case"/":X=Y.pop(),X[5]=G[2],J=Y.length>0?Y[Y.length-1][4]:Z;break;default:J.push(G)}return Z}function K1(Q){this.string=Q,this.tail=Q,this.pos=0}K1.prototype.eos=function(){return this.tail===""};K1.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};K1.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 u8(Q,Z){this.view=Q,this.cache={".":this.view},this.parent=Z}u8.prototype.push=function(Z){return new u8(Z,this)};u8.prototype.lookup=function(Z){var J=this.cache,Y;if(J.hasOwnProperty(Z))Y=J[Z];else{var G=this,X,W,$,q=!1;while(G){if(Z.indexOf(".")>0){X=G.view,W=Z.split("."),$=0;while(X!=null&&$<W.length){if($===W.length-1)q=z5(X,W[$])||M3(X,W[$]);X=X[W[$++]]}}else X=G.view[Z],q=z5(G.view,Z);if(q){Y=X;break}G=G.parent}J[Z]=Y}if(h9(Y))Y=Y.call(this.view);return Y};function l(){this.templateCache={_cache:{},set:function(Z,J){this._cache[Z]=J},get:function(Z){return this._cache[Z]},clear:function(){this._cache={}}}}l.prototype.clearCache=function(){if(typeof this.templateCache<"u")this.templateCache.clear()};l.prototype.parse=function(Z,J){var Y=this.templateCache,G=Z+":"+(J||s.tags).join(":"),X=typeof Y<"u",W=X?Y.get(G):void 0;if(W==null)W=c3(Z,J),X&&Y.set(G,W);return W};l.prototype.render=function(Z,J,Y,G){var X=this.getConfigTags(G),W=this.parse(Z,X),$=J instanceof u8?J:new u8(J,void 0);return this.renderTokens(W,$,Y,Z,G)};l.prototype.renderTokens=function(Z,J,Y,G,X){var W="",$,q,w;for(var D=0,A=Z.length;D<A;++D){if(w=void 0,$=Z[D],q=$[0],q==="#")w=this.renderSection($,J,Y,G,X);else if(q==="^")w=this.renderInverted($,J,Y,G,X);else if(q===">")w=this.renderPartial($,J,Y,X);else if(q==="&")w=this.unescapedValue($,J);else if(q==="name")w=this.escapedValue($,J,X);else if(q==="text")w=this.rawValue($);if(w!==void 0)W+=w}return W};l.prototype.renderSection=function(Z,J,Y,G,X){var W=this,$="",q=J.lookup(Z[1]);function w(N){return W.render(N,J,Y,X)}if(!q)return;if(l8(q))for(var D=0,A=q.length;D<A;++D)$+=this.renderTokens(Z[4],J.push(q[D]),Y,G,X);else if(typeof q==="object"||typeof q==="string"||typeof q==="number")$+=this.renderTokens(Z[4],J.push(q),Y,G,X);else if(h9(q)){if(typeof G!=="string")throw Error("Cannot use higher-order sections without the original template");if(q=q.call(J.view,G.slice(Z[3],Z[5]),w),q!=null)$+=q}else $+=this.renderTokens(Z[4],J,Y,G,X);return $};l.prototype.renderInverted=function(Z,J,Y,G,X){var W=J.lookup(Z[1]);if(!W||l8(W)&&W.length===0)return this.renderTokens(Z[4],J,Y,G,X)};l.prototype.indentPartial=function(Z,J,Y){var G=J.replace(/[^ \t]/g,""),X=Z.split(`
79
- `);for(var W=0;W<X.length;W++)if(X[W].length&&(W>0||!Y))X[W]=G+X[W];return X.join(`
80
- `)};l.prototype.renderPartial=function(Z,J,Y,G){if(!Y)return;var X=this.getConfigTags(G),W=h9(Y)?Y(Z[1]):Y[Z[1]];if(W!=null){var $=Z[6],q=Z[5],w=Z[4],D=W;if(q==0&&w)D=this.indentPartial(W,w,$);var A=this.parse(D,X);return this.renderTokens(A,J,Y,D,G)}};l.prototype.unescapedValue=function(Z,J){var Y=J.lookup(Z[1]);if(Y!=null)return Y};l.prototype.escapedValue=function(Z,J,Y){var G=this.getConfigEscape(Y)||s.escape,X=J.lookup(Z[1]);if(X!=null)return typeof X==="number"&&G===s.escape?String(X):G(X)};l.prototype.rawValue=function(Z){return Z[1]};l.prototype.getConfigTags=function(Z){if(l8(Z))return Z;else if(Z&&typeof Z==="object")return Z.tags;else return};l.prototype.getConfigEscape=function(Z){if(Z&&typeof Z==="object"&&!l8(Z))return Z.escape;else return};var s={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){q1.templateCache=Q},get templateCache(){return q1.templateCache}},q1=new l;s.clearCache=function(){return q1.clearCache()};s.parse=function(Z,J){return q1.parse(Z,J)};s.render=function(Z,J,Y,G){if(typeof Z!=="string")throw TypeError('Invalid template! Template should be a "string" but "'+C3(Z)+'" was given as the first argument for mustache#render(template, view, partials)');return q1.render(Z,J,Y,G)};s.escape=k3;s.Scanner=K1;s.Context=u8;s.Writer=l;var p1=s;function H5(){p1.escape=(Q)=>Q}var S8=(Q)=>{let Z=Q.split(""),J=[],Y=(X,W)=>{for(let $=W;$<Z.length;$+=1)if(X.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 X=Y("}",G);if(X<0)throw Error("Unclosed '{' in template.");J.push({type:"variable",name:Z.slice(G+1,X).join("")}),G=X+1}else if(Z[G]==="}")throw Error("Single '}' in template.");else{let X=Y("{}",G),W=(X<0?Z.slice(G):Z.slice(G,X)).join("");J.push({type:"literal",text:W}),G=X<0?Z.length:X}return J},q5=(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]],X=q5(Y[4],G);J.push(...X)}}else J.push({type:"literal",text:Y[1]});return J},p8=(Q)=>{return H5(),q5(p1.parse(Q))},g9=(Q,Z)=>{return S8(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},"")},d9=(Q,Z)=>{return H5(),p1.render(Q,Z)},U1={"f-string":g9,mustache:d9},m9={"f-string":S8,mustache:p8},d=(Q,Z,J)=>{try{return U1[Z](Q,J)}catch(Y){throw h8(Y,"INVALID_PROMPT_INPUT")}},C8=(Q,Z)=>m9[Z](Q),D8=(Q,Z,J)=>{if(!(Z in U1)){let Y=Object.keys(U1);throw Error(`Invalid template format. Got \`${Z}\`;
81
- 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")d(G.text,Z,Y);else if(G.type==="image_url"){if(typeof G.image_url==="string")d(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 X=G.image_url.url;d(X,Z,Y)}}else throw Error(`Invalid message template received. ${JSON.stringify(G,null,2)}`)});else d(Q,Z,Y)}catch(Y){throw Error(`Invalid prompt schema: ${Y.message}`)}};var Y8=class Q extends w8{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));D8(this.template,this.templateFormat,J)}}_getPromptType(){return"prompt"}async format(Z){let J=await this.mergePartialAndUserVariables(Z);return d(this.template,this.templateFormat,J)}static fromExamples(Z,J,Y,G=`
82
-
83
- `,X=""){return new Q({inputVariables:Y,template:[X,...Z,J].join(G)})}static fromTemplate(Z,J){let{templateFormat:Y="f-string",...G}=J??{},X=new Set;return C8(Z,Y).forEach((W)=>{if(W.type==="variable")X.add(W.name)}),new Q({inputVariables:[...X],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 o8=class Q extends $8{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));D8([{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[W,$]of Object.entries(this.template))if(typeof $==="string")J[W]=d($,this.templateFormat,Z);else J[W]=$;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 X={url:Y};if(G)X.detail=G;return X}async formatPromptValue(Z){return new K5(await this.format(Z))}};var w1=class extends v{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=c9(Q.template,Z);super({inputVariables:J,...Q});this.template=Q.template,this.templateFormat=Z,this.inputVariables=J}async format(Q){return u9(this.template,Q,this.templateFormat)}async invoke(Q){return await this._callWithConfig(this.format.bind(this),Q,{runType:"prompt"})}};function c9(Q,Z){let J=[];for(let Y of Object.values(Q))if(typeof Y==="string")C8(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")C8(G,Z).forEach((X)=>{if(X.type==="variable")J.push(X.name)});else if(typeof G==="object")J.push(...c9(G,Z))}else if(typeof Y==="object"&&Y!==null)J.push(...c9(Y,Z));return Array.from(new Set(J))}function u9(Q,Z,J){let Y={};for(let[G,X]of Object.entries(Q))if(typeof X==="string")Y[G]=d(X,J,Z);else if(Array.isArray(X)){let W=[];for(let $ of X)if(typeof $==="string")W.push(d($,J,Z));else if(typeof $==="object")W.push(u9($,Z,J));Y[G]=W}else if(typeof X==="object"&&X!==null)Y[G]=u9(X,Z,J);else Y[G]=X;return Y}var D1=class extends v{lc_namespace=["langchain_core","prompts","chat"];lc_serializable=!0;async invoke(Q,Z){return this._callWithConfig((J)=>this.formatMessages(J),Q,{...Z,runType:"prompt"})}},o1=class extends D1{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(X8);else J=[X8(Z)]}catch(Y){let G=typeof Z==="string"?Z:JSON.stringify(Z,null,2),X=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(`
84
-
85
- `));throw X.name="InputFormatError",X.lc_error_code=Y.lc_error_code,X}return J}},l9=class extends D1{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)]}},B1=class extends $8{constructor(Q){super(Q)}async format(Q){return(await this.formatPromptValue(Q)).toString()}async formatPromptValue(Q){return new U5(await this.formatMessages(Q))}},p9=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 N8(await this.prompt.format(Q),this.role)}static fromTemplate(Q,Z,J){return new this(Y8.fromTemplate(Q,{templateFormat:J?.templateFormat}),Z)}};function p3(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 o3(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 o9=class extends D1{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(Y8.fromTemplate(Q,Z));let J=[];for(let Y of Q)if(typeof Y==="string")J.push(Y8.fromTemplate(Y,Z));else if(Y===null);else if(p3(Y)){let G="";if(typeof Y.text==="string")G=Y.text??"";let X={...Z,additionalContentFields:Y};J.push(Y8.fromTemplate(G,X))}else if(o3(Y)){let G=Y.image_url??"",X,W=[];if(typeof G==="string"){let $;if(Z?.templateFormat==="mustache")$=p8(G);else $=S8(G);let q=$.flatMap((w)=>w.type==="variable"?[w.name]:[]);if((q?.length??0)>0){if(q.length>1)throw Error(`Only one format variable allowed per image template.
86
- Got: ${q}
87
- From: ${G}`);W=[q[0]]}else W=[];G={url:G},X=new o8({template:G,inputVariables:W,templateFormat:Z?.templateFormat,additionalContentFields:Y})}else if(typeof G==="object"){if("url"in G){let $;if(Z?.templateFormat==="mustache")$=p8(G.url);else $=S8(G.url);W=$.flatMap((q)=>q.type==="variable"?[q.name]:[])}else W=[];X=new o8({template:G,inputVariables:W,templateFormat:Z?.templateFormat,additionalContentFields:Y})}else throw Error("Invalid image template");J.push(X)}else if(typeof Y==="object")J.push(new w1({template:Y,templateFormat:Z?.templateFormat}));return new this({prompt:J,additionalOptions:Z})}async format(Q){if(this.prompt instanceof w8){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 w8){let G=await J.format(Y),X;if("additionalContentFields"in J)X=J.additionalContentFields;if(G!=="")Z.push({...X,type:"text",text:G})}else if(J instanceof o8){let G=await J.format(Y),X;if("additionalContentFields"in J)X=J.additionalContentFields;Z.push({...X,type:"image_url",image_url:G})}else if(J instanceof w1){let G=await J.format(Y),X;if("additionalContentFields"in J)X=J.additionalContentFields;Z.push({...X,...G})}}return this.createMessage(Z)}}async formatMessages(Q){return[await this.format(Q)]}},i1=class extends o9{static _messageClass(){return u}static lc_name(){return"HumanMessagePromptTemplate"}},i9=class extends o9{static _messageClass(){return C}static lc_name(){return"AIMessagePromptTemplate"}},n9=class extends o9{static _messageClass(){return a}static lc_name(){return"SystemMessagePromptTemplate"}};function i3(Q){return typeof Q.formatMessages==="function"}function n3(Q,Z){if(i3(Q)||n(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 o1({variableName:G.slice(2,-2),optional:!0});else if(typeof G==="string"&&G[0]==="{"&&G[G.length-1]==="}")return new o1({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=X8(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 i1.fromTemplate(Y,Z);else if(J._getType()==="ai")return i9.fromTemplate(Y,Z);else if(J._getType()==="system")return n9.fromTemplate(Y,Z);else if(N8.isInstance(J))return p9.fromTemplate(J.content,J.role,Z);else throw Error(`Could not coerce message prompt template from input. Received message type: "${J._getType()}".`)}function r3(Q){return Q.constructor.lc_name()==="MessagesPlaceholder"}var i8=class Q extends B1{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 Q8)continue;for(let q of $.inputVariables)J.add(q)}let Y=this.inputVariables,G=new Set(this.partialVariables?Y.concat(Object.keys(this.partialVariables)):Y),X=new Set([...G].filter(($)=>!J.has($)));if(X.size>0)throw Error(`Input variables \`${[...X]}\` are not used in any of the prompt messages.`);let W=new Set([...J].filter(($)=>!G.has($)));if(W.size>0)throw Error(`Input variables \`${[...W]}\` 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 X=await Y8.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=X;else Y.image_url=X;return Y})),Z}async formatMessages(Z){let J=await this.mergePartialAndUserVariables(Z),Y=[];for(let G of this.promptMessages)if(G instanceof Q8)Y.push(await this._parseImagePrompts(G,J));else{let X;if(this.templateFormat==="mustache")X={...J};else X=G.inputVariables.reduce(($,q)=>{if(!(q in J)&&!(r3(G)&&G.optional))throw h8(Error(`Missing value for input variable \`${q.toString()}\``),"INVALID_PROMPT_INPUT");return $[q]=J[q],$},{});let W=await G.formatMessages(X);Y=Y.concat(W)}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 i1({prompt:Y8.fromTemplate(Z,J)});return this.fromMessages([Y])}static fromMessages(Z,J){let Y=Z.reduce((W,$)=>W.concat($ instanceof Q?$.promptMessages:[n3($,J)]),[]),G=Z.reduce((W,$)=>$ instanceof Q?Object.assign(W,$.partialVariables):W,Object.create(null)),X=new Set;for(let W of Y){if(W instanceof Q8)continue;for(let $ of W.inputVariables){if($ in G)continue;X.add($)}}return new this({...J,inputVariables:[...X],promptMessages:Y,partialVariables:G,templateFormat:J?.templateFormat})}};var w5=class Q extends w8{lc_serializable=!1;examples;exampleSelector;examplePrompt;suffix="";exampleSeparator=`
88
-
89
- `;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));D8(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((X)=>this.examplePrompt.format(X)));return d([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 Y8.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})}},D5=class Q extends B1{lc_serializable=!0;examples;exampleSelector;examplePrompt;suffix="";exampleSeparator=`
90
-
91
- `;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??`
92
-
93
- `,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));D8(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((X)=>{let W={};return this.examplePrompt.inputVariables.forEach(($)=>{W[$]=X[$]}),W});let G=[];for(let X of Y){let W=await this.examplePrompt.formatMessages(X);G.push(...W)}return G}async format(Z){let J=await this.mergePartialAndUserVariables(Z),Y=await this.getExamples(J),G=(await Promise.all(Y.map((X)=>this.examplePrompt.formatMessages(X)))).flat().map((X)=>X.content);return d([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 B5=class Q extends $8{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 X=Q.extractRequiredInputValues(J,G.inputVariables);if(G instanceof i8)J[Y]=await G.formatMessages(X);else J[Y]=await G.format(X)}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 N5(Q){return typeof Q==="object"&&Q!=null&&"withStructuredOutput"in Q&&typeof Q.withStructuredOutput==="function"}function s3(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 A5=class Q extends i8{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(N5(Z))return super.pipe(Z.withStructuredOutput(this.schema));if(s3(Z)&&N5(Z.bound))return super.pipe(new k8({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 E5=L({AIMessagePromptTemplate:()=>i9,BaseChatPromptTemplate:()=>B1,BaseMessagePromptTemplate:()=>D1,BaseMessageStringPromptTemplate:()=>l9,BasePromptTemplate:()=>$8,BaseStringPromptTemplate:()=>w8,ChatMessagePromptTemplate:()=>p9,ChatPromptTemplate:()=>i8,DEFAULT_FORMATTER_MAPPING:()=>U1,DEFAULT_PARSER_MAPPING:()=>m9,DictPromptTemplate:()=>w1,FewShotChatMessagePromptTemplate:()=>D5,FewShotPromptTemplate:()=>w5,HumanMessagePromptTemplate:()=>i1,ImagePromptTemplate:()=>o8,MessagesPlaceholder:()=>o1,PipelinePromptTemplate:()=>B5,PromptTemplate:()=>Y8,StructuredPrompt:()=>A5,SystemMessagePromptTemplate:()=>n9,checkValidTemplate:()=>D8,interpolateFString:()=>g9,interpolateMustache:()=>d9,parseFString:()=>S8,parseMustache:()=>p8,parseTemplate:()=>C8,renderTemplate:()=>d});var F5=L({BaseDocumentCompressor:()=>t3}),t3=class{static isBaseDocumentCompressor(Q){return Q?.compressDocuments!==void 0}};var R5=L({BaseRetriever:()=>N1}),N1=class extends v{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=H8(L5(Z)),Y=await(await z8.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 V5=L({BaseStore:()=>P5,InMemoryStore:()=>a3}),P5=class extends Z8{},a3=class extends P5{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 G8={and:"and",or:"or",not:"not"},_={eq:"eq",ne:"ne",lt:"lt",gt:"gt",lte:"lte",gte:"gte"},n1=class{},r1=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")}},s1=class extends r1{},I5=class extends s1{exprName="Comparison";constructor(Q,Z,J){super();this.comparator=Q,this.attribute=Z,this.value=J}},O5=class extends s1{exprName="Operation";constructor(Q,Z){super();this.operator=Q,this.args=Z}},_5=class extends r1{exprName="StructuredQuery";constructor(Q,Z){super();this.query=Q,this.filter=Z}};function r9(Q){return Q&&typeof Q==="object"&&!Array.isArray(Q)}function o(Q){if(!Q)return!0;if(typeof Q==="string"&&Q.length>0)return!1;if(typeof Q==="function")return!1;return r9(Q)&&Object.keys(Q).length===0}function s9(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 a9(Q){return typeof Q==="string"&&(Number.isNaN(parseFloat(Q))||parseFloat(Q).toString()!==Q)}function e9(Q){return typeof Q==="boolean"}function n8(Q){let Z;if(a9(Q))Z=Q;else if(s9(Q))Z=parseInt(Q,10);else if(t9(Q))Z=parseFloat(Q);else if(e9(Q))Z=Boolean(Q);else throw Error("Unsupported value type");return Z}var A1=class extends n1{},j5=class extends A1{allowedOperators;allowedComparators;constructor(Q){super();this.allowedOperators=Q?.allowedOperators??[G8.and,G8.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 G8){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)]:n8(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(o(Q)&&o(Z))return;if(o(Q)||J==="replace"){if(o(Z))return;return Z}if(o(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 T5=class extends A1{allowedOperators=[G8.and,G8.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 G8.and:return(Z,J)=>Z&&J;case G8.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((X,W)=>{let $=W.accept(this);if(typeof $==="function")return Y(X,$(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 X=this.getComparatorFunction(Z);return(W)=>{let $=W.metadata[J];if($===void 0){if(G.includes(Z))return!0;return!1}return X($,n8(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(o(Q)&&o(Z))return;if(o(Q)||J==="replace"){if(o(Z))return;return Z}if(o(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 S5=L({BaseTranslator:()=>A1,BasicTranslator:()=>j5,Comparators:()=>_,Comparison:()=>I5,Expression:()=>r1,FilterDirective:()=>s1,FunctionalTranslator:()=>T5,Operation:()=>O5,Operators:()=>G8,StructuredQuery:()=>_5,Visitor:()=>n1,castValue:()=>n8,isBoolean:()=>e9,isFilterEmpty:()=>o,isFloat:()=>t9,isInt:()=>s9,isObject:()=>r9,isString:()=>a9});function E1(Q){if(!Q8.isInstance(Q))return typeof Q;return Q.constructor.name||Q.type}function t1(Q,Z){return function(J,Y){let{isNot:G,utils:X}=this;if(!Z(J))return{pass:!1,message:()=>`${X.matcherHint(`toBe${Q}`,void 0,void 0)}
94
-
95
- Expected: ${G?"not ":""}${Q}
96
- Received: ${E1(J)}`,actual:E1(J),expected:Q};if(Y===void 0)return{pass:!0,message:()=>`${X.matcherHint(`toBe${Q}`,void 0,void 0)}
97
-
98
- Expected: not ${Q}
99
- Received: ${Q}`};let W=J;if(typeof Y==="string")return{pass:W.content===Y,message:()=>`${X.matcherHint(`toBe${Q}`,void 0,void 0)}
100
-
101
- Expected: ${Q} with content ${X.printExpected(Y)}
102
- Received: ${Q} with content ${X.printReceived(W.content)}`,actual:W.content,expected:Y};return{pass:Object.entries(Y).every(([$,q])=>this.equals(W[$],q)),message:()=>{let $={};for(let q of Object.keys(Y))$[q]=W[q];return`${X.matcherHint(`toBe${Q}`,void 0,void 0)}
103
-
104
- Expected: ${Q} matching ${X.printExpected(Y)}
105
- Received: ${Q} with ${X.printReceived($)}`},actual:(()=>{let $={};for(let q of Object.keys(Y))$[q]=W[q];return $})(),expected:Y}}}var Q0=t1("HumanMessage",u.isInstance),Z0=t1("AIMessage",C.isInstance),J0=t1("SystemMessage",a.isInstance),Y0=t1("ToolMessage",B8.isInstance);function G0(Q,Z){let{isNot:J,utils:Y}=this;if(!C.isInstance(Q))return{pass:!1,message:()=>`${Y.matcherHint("toHaveToolCalls")}
106
-
107
- Expected: AIMessage
108
- Received: ${E1(Q)}`};let G=Q.tool_calls??[];if(G.length!==Z.length)return{pass:!1,message:()=>`${Y.matcherHint("toHaveToolCalls")}
109
-
110
- Expected ${J?"not ":""}${Z.length} tool call(s), received ${G.length}`,actual:G.length,expected:Z.length};let X=Z.filter((W)=>!G.some(($)=>Object.entries(W).every(([q,w])=>this.equals($[q],w))));if(X.length>0)return{pass:!1,message:()=>`${Y.matcherHint("toHaveToolCalls")}
111
-
112
- Could not find matching tool call(s) for:
113
- ${Y.printExpected(X)}
114
- Received tool calls: ${Y.printReceived(G.map((W)=>({name:W.name,id:W.id,args:W.args})))}`,actual:G.map((W)=>({name:W.name,id:W.id,args:W.args})),expected:Z};return{pass:!0,message:()=>`${Y.matcherHint("toHaveToolCalls")}
115
-
116
- Expected AIMessage not to have matching tool calls`}}function X0(Q,Z){let{isNot:J,utils:Y}=this;if(!C.isInstance(Q))return{pass:!1,message:()=>`${Y.matcherHint("toHaveToolCallCount")}
117
-
118
- Expected: AIMessage
119
- Received: ${E1(Q)}`};let G=Q.tool_calls?.length??0;return{pass:G===Z,message:()=>`${Y.matcherHint("toHaveToolCallCount")}
120
-
121
- Expected ${J?"not ":""}${Z} tool call(s)
122
- Received: ${G}`,actual:G,expected:Z}}function W0(Q,Z){let{isNot:J,utils:Y}=this;if(!C.isInstance(Q))return{pass:!1,message:()=>`${Y.matcherHint("toContainToolCall")}
123
-
124
- Expected: AIMessage
125
- Received: ${E1(Q)}`};let G=Q.tool_calls??[];return{pass:G.some((X)=>Object.entries(Z).every(([W,$])=>this.equals(X[W],$))),message:()=>`${Y.matcherHint("toContainToolCall")}
126
-
127
- Expected AIMessage ${J?"not ":""}to contain a tool call matching ${Y.printExpected(Z)}
128
- Received tool calls: ${Y.printReceived(G.map((X)=>({name:X.name,id:X.id})))}`,actual:G.map((X)=>({name:X.name,id:X.id})),expected:Z}}function z0(Q,Z){let{isNot:J,utils:Y}=this;if(!Array.isArray(Q))return{pass:!1,message:()=>`${Y.matcherHint("toHaveToolMessages")}
129
-
130
- Expected an array of messages
131
- Received: ${typeof Q}`};let G=Q.filter(B8.isInstance);if(G.length!==Z.length)return{pass:!1,message:()=>`${Y.matcherHint("toHaveToolMessages")}
132
-
133
- Expected ${J?"not ":""}${Z.length} tool message(s), found ${G.length}`,actual:G.length,expected:Z.length};for(let X=0;X<Z.length;X++)if(!Object.entries(Z[X]).every(([W,$])=>this.equals(G[X][W],$)))return{pass:!1,message:()=>{let W={};for(let $ of Object.keys(Z[X]))W[$]=G[X][$];return`${Y.matcherHint("toHaveToolMessages")}
134
-
135
- Tool message at index ${X} did not match:
136
- Expected: ${Y.printExpected(Z[X])}
137
- Received: ${Y.printReceived(W)}`},actual:G[X],expected:Z[X]};return{pass:!0,message:()=>`${Y.matcherHint("toHaveToolMessages")}
138
-
139
- Expected messages not to contain matching tool messages`}}function $0(Q,Z){let{isNot:J,utils:Y}=this,G=Q?.__interrupt__;if(!(Array.isArray(G)&&G.length>0))return{pass:!1,message:()=>`${Y.matcherHint("toHaveBeenInterrupted")}
140
-
141
- Expected result ${J?"not ":""}to have been interrupted
142
- Received __interrupt__: ${Y.printReceived(G)}`};if(Z===void 0)return{pass:!0,message:()=>`${Y.matcherHint("toHaveBeenInterrupted")}
143
-
144
- Expected result not to have been interrupted
145
- Received ${G.length} interrupt(s)`};let X=G[0]?.value;return{pass:this.equals(X,Z),message:()=>`${Y.matcherHint("toHaveBeenInterrupted")}
146
-
147
- Expected interrupt value: ${Y.printExpected(Z)}
148
- Received interrupt value: ${Y.printReceived(X)}`,actual:X,expected:Z}}function H0(Q,Z){let{isNot:J,utils:Y}=this,G=Q?.structuredResponse;if(G===void 0)return{pass:!1,message:()=>`${Y.matcherHint("toHaveStructuredResponse")}
149
-
150
- Expected result ${J?"not ":""}to have a structured response
151
- Received structuredResponse: undefined`};if(Z===void 0)return{pass:!0,message:()=>`${Y.matcherHint("toHaveStructuredResponse")}
152
-
153
- Expected result not to have a structured response`};return{pass:Object.entries(Z).every(([X,W])=>this.equals(G[X],W)),message:()=>`${Y.matcherHint("toHaveStructuredResponse")}
154
-
155
- Expected structured response: ${Y.printExpected(Z)}
156
- Received structured response: ${Y.printReceived(G)}`,actual:G,expected:Z}}var C5={toBeHumanMessage:Q0,toBeAIMessage:Z0,toBeSystemMessage:J0,toBeToolMessage:Y0,toHaveToolCalls:G0,toHaveToolCallCount:X0,toContainToolCall:W0,toHaveToolMessages:z0,toHaveBeenInterrupted:$0,toHaveStructuredResponse:H0};function e3(Q){return Q.map((Z)=>Z.text).filter(Boolean).join("-")}var M5=0;function Q7(){return M5+=1,`fake_tc_${M5}`}var Z7=class Q extends L8{queue=[];_alwaysThrowError;_structuredResponseValue;_tools=[];_callIndex=0;_calls=[];get calls(){return this._calls}get callCount(){return this._calls.length}constructor(){super({})}_llmType(){return"fake-model-builder"}_combineLLMOutput(){return[]}respond(Z){if(typeof Z==="function")this.queue.push({kind:"factory",factory:Z});else if(Q8.isInstance(Z))this.queue.push({kind:"message",message:Z});else this.queue.push({kind:"error",error:Z});return this}respondWithTools(Z){return this.queue.push({kind:"toolCalls",toolCalls:Z.map((J)=>({name:J.name,args:J.args,id:J.id??Q7(),type:"tool_call"}))}),this}alwaysThrow(Z){return this._alwaysThrowError=Z,this}structuredResponse(Z){return this._structuredResponseValue=Z,this}bindTools(Z){let J=[...this._tools,...Z],Y=new Q;return Y.queue=this.queue,Y._alwaysThrowError=this._alwaysThrowError,Y._structuredResponseValue=this._structuredResponseValue,Y._tools=J,Y._calls=this._calls,Y._callIndex=this._callIndex,Y.withConfig({})}withStructuredOutput(Z,J){let{_structuredResponseValue:Y}=this;return p.from(async()=>{return Y})}async _generate(Z,J,Y){this._calls.push({messages:[...Z],options:J});let G=this._callIndex;if(this._callIndex+=1,this._alwaysThrowError)throw this._alwaysThrowError;let X=this.queue[G];if(!X)throw Error(`FakeModel: no response queued for invocation ${G} (${this.queue.length} total queued).`);if(X.kind==="error")throw X.error;if(X.kind==="factory"){let $=X.factory(Z);if(!Q8.isInstance($))throw $;return{generations:[{text:"",message:$}]}}if(X.kind==="message")return{generations:[{text:"",message:X.message}]};let W=e3(Z);return{generations:[{text:W,message:new C({content:W,id:G.toString(),tool_calls:X.toolCalls.length>0?X.toolCalls.map(($)=>({...$,type:"tool_call"})):void 0})}],llmOutput:{}}}};function y5(){return new Z7}var v5=L({fakeModel:()=>y5,langchainMatchers:()=>C5,toBeAIMessage:()=>Z0,toBeHumanMessage:()=>Q0,toBeSystemMessage:()=>J0,toBeToolMessage:()=>Y0,toContainToolCall:()=>W0,toHaveBeenInterrupted:()=>$0,toHaveStructuredResponse:()=>H0,toHaveToolCallCount:()=>X0,toHaveToolCalls:()=>G0,toHaveToolMessages:()=>z0});var b5=L({RunCollectorCallbackHandler:()=>J7}),J7=class extends r8{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 x5=L({});var f5=L({chunkArray:()=>Y7}),Y7=(Q,Z)=>Q.reduce((J,Y,G)=>{let X=Math.floor(G/Z);return J[X]=(J[X]||[]).concat([Y]),J},[]);var k5=L({context:()=>G7});function G7(Q,...Z){let J=Q.raw,Y="";for(let G=0;G<J.length;G++){let X=J[G].replace(/\\\n[ \t]*/g,"").replace(/\\`/g,"`").replace(/\\\$/g,"$").replace(/\\\{/g,"{");if(Y+=X,G<Z.length){let W=X7(Z[G],Y);Y+=typeof W==="string"?W:JSON.stringify(W)}}return Y=W7(Y),Y=Y.trim(),Y=Y.replace(/\\n/g,`
157
- `),Y}function X7(Q,Z){if(typeof Q!=="string"||!Q.includes(`
158
- `))return Q;let J=Z.slice(Z.lastIndexOf(`
159
- `)+1).match(/^(\s+)/);if(J){let Y=J[1];return Q.replace(/\n/g,`
160
- ${Y}`)}return Q}function W7(Q){let Z=Q.split(`
161
- `),J=null;for(let Y of Z){let G=Y.match(/^(\s+)\S+/);if(G){let X=G[1].length;if(J===null)J=X;else J=Math.min(J,X)}}if(J===null)return Q;return Z.map((Y)=>Y[0]===" "||Y[0]==="\t"?Y.slice(J):Y).join(`
162
- `)}var g5=L({EventStreamContentType:()=>z7,convertEventStreamToIterableReadableDataStream:()=>H7,getBytes:()=>d5,getLines:()=>m5,getMessages:()=>c5}),z7="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(`
163
- `))}}var s8=function(Q){return Q[Q.NewLine=10]="NewLine",Q[Q.CarriageReturn=13]="CarriageReturn",Q[Q.Space=32]="Space",Q[Q.Colon=58]="Colon",Q}(s8||{});function m5(Q){let Z,J,Y,G=!1;return function(W,$){if($){Q(W,0,!0);return}if(Z===void 0)Z=W,J=0,Y=-1;else Z=$7(Z,W);let q=Z.length,w=0;while(J<q){if(G){if(Z[J]===s8.NewLine)w=++J;G=!1}let D=-1;for(;J<q&&D===-1;++J)switch(Z[J]){case s8.Colon:if(Y===-1)Y=J-w;break;case s8.CarriageReturn:G=!0;case s8.NewLine:D=J;break}if(D===-1)break;Q(Z.subarray(w,D),Y),w=J,Y=-1}if(w===q)Z=void 0;else if(w!==0)Z=Z.subarray(w),J-=w}}function c5(Q,Z,J){let Y=q0(),G=new TextDecoder;return function(W,$,q){if(q){if(!q7(Y))Q?.(Y),Y=q0();return}if(W.length===0)Q?.(Y),Y=q0();else if($>0){let w=G.decode(W.subarray(0,$)),D=$+(W[$+1]===s8.Space?2:1),A=G.decode(W.subarray(D));switch(w){case"data":Y.data=Y.data?Y.data+`
164
- `+A:A;break;case"event":Y.event=A;break;case"id":Z?.(Y.id=A);break;case"retry":{let N=parseInt(A,10);if(!Number.isNaN(N))J?.(Y.retry=N);break}}}}}function $7(Q,Z){let J=new Uint8Array(Q.length+Z.length);return J.set(Q),J.set(Z,Q.length),J}function q0(){return{data:"",event:"",id:"",retry:void 0}}function H7(Q,Z){let J=new ReadableStream({async start(Y){let G=c5((W)=>{if(W.event==="error")throw Error(W.data??"Unspecified event streaming error.");else if(W.event==="metadata")Z?.(W);else if(W.data)Y.enqueue(W.data)});await d5(Q,m5((W,$,q)=>{if(G(W,$,q),q)Y.close()}))}});return h5.fromReadableStream(J)}function q7(Q){return Q.data===""&&Q.event===""&&Q.id===""&&Q.retry===void 0}var u5=L({});var i5=L({convertToOpenAIFunction:()=>n5,convertToOpenAITool:()=>K7,isLangChainTool:()=>K0,isRunnableToolLike:()=>p5,isStructuredTool:()=>l5,isStructuredToolParams:()=>o5});function n5(Q,Z){let J=typeof Z==="number"?void 0:Z;return{name:Q.name,description:Q.description,parameters:g(Q.schema),...J?.strict!==void 0?{strict:J.strict}:{}}}function K7(Q,Z){let J=typeof Z==="number"?void 0:Z,Y;if(K0(Q))Y={type:"function",function:n5(Q)};else Y=Q;if(J?.strict!==void 0)Y.function.strict=J.strict;return Y}function a1(Q,Z){let J=0,Y=0,G=0;for(let X=0;X<Q.length;X++)J+=Q[X]*Z[X],Y+=Q[X]*Q[X],G+=Z[X]*Z[X];return J/(Math.sqrt(Y)*Math.sqrt(G))}function r5(Q,Z){let J=0;for(let Y=0;Y<Q.length;Y++)J+=Q[Y]*Z[Y];return J}function U7(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 s5(Q,Z){return Math.sqrt(U7(Q,Z))}var t5=L({cosineSimilarity:()=>U0,euclideanDistance:()=>B7,innerProduct:()=>D7,matrixFunc:()=>e1,maximalMarginalRelevance:()=>N7,normalize:()=>w7});function e1(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 w7(Q,Z=!1){let J=A7(Q);return Q.map((Y)=>Y.map((G)=>Z?1-G/J:G/J))}function U0(Q,Z){return e1(Q,Z,a1)}function D7(Q,Z){return e1(Q,Z,r5)}function B7(Q,Z){return e1(Q,Z,s5)}function N7(Q,Z,J=0.5,Y=4){if(Math.min(Y,Z.length)<=0)return[];let G=U0(Array.isArray(Q[0])?Q:[Q],Z)[0],X=a5(G).maxIndex,W=[Z[X]],$=[X];while($.length<Math.min(Y,Z.length)){let q=-1/0,w=-1,D=U0(Z,W);G.forEach((A,N)=>{if($.includes(N))return;let F=Math.max(...D[N]),E=J*A-(1-J)*F;if(E>q)q=E,w=N}),W.push(Z[w]),$.push(w)}return $}function a5(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 A7(Q){return Q.reduce((Z,J)=>Math.max(Z,a5(J).maxValue),0)}var e5=L({isCloudMetadata:()=>w0,isLocalhost:()=>D0,isPrivateIp:()=>GQ,isSafeUrl:()=>O7,isSameOrigin:()=>_7,validateSafeUrl:()=>XQ}),E7=["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"],F7=["169.254.169.254","169.254.170.2","100.100.100.200"],L7=["metadata.google.internal","metadata","instance-data"],R7=["localhost","localhost.localdomain"],V7=/^(?:(?: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 QQ(Q){return V7.test(Q)}function Q9(Q){return YQ(Q)!==null}function ZQ(Q){return QQ(Q)||Q9(Q)}function JQ(Q){if(QQ(Q))return Q.split(".").map((Z)=>parseInt(Z,10));else if(Q9(Q)){let Z=YQ(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 YQ(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,X]=Y,W=G?G.split(":"):[],$=X?X.split(":"):[],q=8-(W.length+$.length);if(q<0)return null;let w=Array(q).fill("0");Z=[...W,...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 P7(Q){let[Z,J]=Q.split("/");if(!Z||!J)return null;let Y=JQ(Z);if(!Y)return null;let G=parseInt(J,10);if(isNaN(G))return null;let X=Q9(Z);if(X&&G>128)return null;if(!X&&G>32)return null;return{addr:Y,prefixLen:G,isIpv6:X}}function I7(Q,Z){let J=JQ(Q);if(!J)return!1;let Y=P7(Z);if(!Y)return!1;let G=Q9(Q);if(G!==Y.isIpv6)return!1;let{addr:X,prefixLen:W}=Y;if(G)for(let $=0;$<Math.ceil(W/16);$++){let q=65535<<16-Math.min(16,W-$*16)&65535;if((J[$]&q)!==(X[$]&q))return!1}else for(let $=0;$<Math.ceil(W/8);$++){let q=255<<8-Math.min(8,W-$*8)&255;if((J[$]&q)!==(X[$]&q))return!1}return!0}function GQ(Q){if(!ZQ(Q))return!1;for(let Z of E7)if(I7(Q,Z))return!0;return!1}function w0(Q,Z){if(F7.includes(Z||""))return!0;let J=Q.toLowerCase();if(L7.includes(J))return!0;return!1}function D0(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(R7.includes(J))return!0;return!1}function XQ(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 X=G.hostname;if(!X)throw Error("URL missing hostname.");if(w0(X))throw Error(`URL points to cloud metadata endpoint: ${X}`);if(D0(X)){if(!J)throw Error(`URL points to localhost: ${X}`);return Q}let W=G.protocol;if(W!=="http:"&&W!=="https:")throw Error(`Invalid URL scheme: ${W}. Only http and https are allowed.`);if(W==="http:"&&!Y)throw Error("HTTP scheme not allowed. Use HTTPS or set allowHttp: true.");if(ZQ(X)){let $=X;if(D0(X,$)){if(!J)throw Error(`URL points to localhost: ${X}`);return Q}if(w0(X,$))throw Error(`URL resolves to cloud metadata IP: ${$} (${X})`);if(GQ($)){if(!J)throw Error(`URL resolves to private IP: ${$} (${X}). 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 O7(Q,Z){try{return XQ(Q,Z),!0}catch{return!1}}function _7(Q,Z){try{return new URL(Q).origin===new URL(Z).origin}catch{return!1}}var WQ=L({SaveableVectorStore:()=>j7,VectorStore:()=>J9,VectorStoreRetriever:()=>Z9}),Z9=class extends N1{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)}},J9=class extends Z8{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,X){if(typeof Q==="number")return new Z9({vectorStore:this,k:Q,filter:Z,tags:[...Y??[],this._vectorstoreType()],metadata:G,verbose:X,callbacks:J});else{let W={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 Z9({...W,searchKwargs:Q.searchKwargs});return new Z9({...W})}}},j7=class extends J9{static load(Q,Z){throw Error("Not implemented")}};var zQ=class extends L8{_combineLLMOutput(){return[]}_llmType(){return"fake"}async _generate(Q,Z,J){if(Z?.stop?.length)return{generations:[{message:new C(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(`
165
- `);return await J?.handleLLMNewToken(Y),{generations:[{message:new C(Y),text:Y}],llmOutput:{}}}},$Q=class Q extends L8{sleep=50;responses=[];chunks=[];toolStyle="openai";thrownErrorString;tools=[];constructor({sleep:Z=50,responses:J=[],chunks:Y=[],toolStyle:G="openai",thrownErrorString:X,...W}){super(W);this.sleep=Z,this.responses=J,this.chunks=Y,this.toolStyle=G,this.thrownErrorString=X}_llmType(){return"fake"}bindTools(Z){let J=[...this.tools,...Z],Y=J.map((W)=>{switch(this.toolStyle){case"openai":return{type:"function",function:{name:W.name,description:W.description,parameters:g(W.schema)}};case"anthropic":return{name:W.name,description:W.description,input_schema:g(W.schema)};case"bedrock":return{toolSpec:{name:W.name,description:W.description,inputSchema:g(W.schema)}};case"google":return{name:W.name,description:W.description,parameters:g(W.schema)};default:throw Error(`Unsupported tool style: ${this.toolStyle}`)}}),G=this.toolStyle==="google"?[{functionDeclarations:Y}]:Y,X=new Q({sleep:this.sleep,responses:this.responses,chunks:this.chunks,toolStyle:this.toolStyle,thrownErrorString:this.thrownErrorString});return X.tools=J,X.withConfig({tools:G})}async _generate(Z,J,Y){if(this.thrownErrorString)throw Error(this.thrownErrorString);return{generations:[{text:"",message:new C({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 W of this.chunks){let $=new j8({message:new e({content:W.content,tool_calls:W.tool_calls,additional_kwargs:W.additional_kwargs??{}}),text:W.content?.toString()??""});if(J.signal?.aborted)break;yield $,await Y?.handleLLMNewToken(W.content,void 0,void 0,void 0,void 0,{chunk:$})}return}let G=this.responses?.[0]??new C(typeof Z[0].content==="string"?Z[0].content:""),X=typeof G.content==="string"?G.content:"";for(let W of X){await new Promise((q)=>setTimeout(q,this.sleep));let $=new j8({message:new e({content:W}),text:W});if(J.signal?.aborted)break;yield $,await Y?.handleLLMNewToken(W,void 0,void 0,void 0,void 0,{chunk:$})}}},HQ=class Q extends L8{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:X}=Z;this.responses=J,this.sleep=Y,this.emitCustomEvent=G??this.emitCustomEvent,this.generationInfo=X}_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 C(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 X=[...G];for(let W=0;W<X.length;W++){let $=X[W],q=W===X.length-1;if(await this._sleepIfRequested(),J?.thrownErrorString)throw Error(J.thrownErrorString);let w=this._createResponseChunk($,q?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 j8({message:new e({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((W)=>{switch(this.toolStyle){case"openai":return{type:"function",function:{name:W.name,description:W.description,parameters:g(W.schema)}};case"anthropic":return{name:W.name,description:W.description,input_schema:g(W.schema)};case"bedrock":return{toolSpec:{name:W.name,description:W.description,inputSchema:g(W.schema)}};case"google":return{name:W.name,description:W.description,parameters:g(W.schema)};default:throw Error(`Unsupported tool style: ${this.toolStyle}`)}}),G=this.toolStyle==="google"?[{functionDeclarations:Y}]:Y,X=new Q({responses:this.responses,sleep:this.sleep,emitCustomEvent:this.emitCustomEvent,generationInfo:this.generationInfo});return X.tools=J,X.toolStyle=this.toolStyle,X.i=this.i,X.withConfig({tools:G})}withStructuredOutput(Z,J){return p.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 qQ=class extends S1{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 X=Z.length/this.vectorSize,W=[];for(let $=0;$<Z.length;$+=X)W.push(Z.slice($,$+X));return W.map(($)=>{let q=0;for(let w=0;w<$.length;w+=1)q+=$===" "?0:$.charCodeAt(w);return q%26/26})}},KQ=class extends S1{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 UQ=class extends l1{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}},wQ=class extends l1{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((X)=>setTimeout(X,this.sleep)),yield{text:G,generationInfo:{}},await J?.handleLLMNewToken(G)}};var DQ=class extends F9{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 u(Q))}async addAIMessage(Q){this.messages.push(new C(Q))}async clear(){this.messages=[]}},BQ=class extends T1{lc_namespace=["langchain_core","message","fake"];messages=[];constructor(){super()}async addMessage(Q){this.messages.push(Q)}async getMessages(){return this.messages}},NQ=class extends r8{name="fake_tracer";runs=[];constructor(){super()}persistRun(Q){return this.runs.push(Q),Promise.resolve()}};var AQ=class extends J8{lc_namespace=["tests","fake"];getFormatInstructions(){return""}async parse(Q){return Q.split(",").map((Z)=>Z.trim())}};var EQ=class extends N1{lc_namespace=["test","fake"];output=[new r({pageContent:"foo"}),new r({pageContent:"bar"})];constructor(Q){super();this.output=Q?.output??this.output}async _getRelevantDocuments(Q){return this.output}};var FQ=class extends v{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 RQ=class extends LQ{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 VQ=class extends r8{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 PQ=class Q extends J9{memoryVectors=[];similarity;_vectorstoreType(){return"memory"}constructor(Z,{similarity:J,...Y}={}){super(Z,Y);this.similarity=J??a1}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,X)=>({content:J[X].pageContent,embedding:G,metadata:J[X].metadata}));this.memoryVectors=this.memoryVectors.concat(Y)}async similaritySearchVectorWithScore(Z,J,Y){let G=(W)=>{if(!Y)return!0;return Y(new r({metadata:W.metadata,pageContent:W.content}))},X=this.memoryVectors.filter(G);return X.map((W,$)=>({similarity:this.similarity(Z,W.embedding),index:$})).sort((W,$)=>W.similarity>$.similarity?-1:0).slice(0,J).map((W)=>[new r({metadata:X[W.index].metadata,pageContent:X[W.index].content}),W.similarity])}static async fromTexts(Z,J,Y,G){let X=[];for(let W=0;W<Z.length;W+=1){let $=Array.isArray(J)?J[W]:J,q=new r({pageContent:Z[W],metadata:$});X.push(q)}return Q.fromDocuments(X,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 IQ=L({FakeChatMessageHistory:()=>DQ,FakeChatModel:()=>zQ,FakeEmbeddings:()=>KQ,FakeLLM:()=>UQ,FakeListChatMessageHistory:()=>BQ,FakeListChatModel:()=>HQ,FakeRetriever:()=>EQ,FakeRunnable:()=>FQ,FakeSplitIntoListParser:()=>AQ,FakeStreamingChatModel:()=>$Q,FakeStreamingLLM:()=>wQ,FakeTool:()=>RQ,FakeTracer:()=>NQ,FakeVectorStore:()=>PQ,SingleRunExtractor:()=>VQ,SyntheticEmbeddings:()=>qQ});var rQ=L({agents:()=>e4,caches:()=>kQ,callbacks__base:()=>SQ,callbacks__manager:()=>bQ,callbacks__promises:()=>vQ,chat_history:()=>Q6,document_loaders__base:()=>Y6,document_loaders__langsmith:()=>X6,documents:()=>J6,embeddings:()=>z6,errors:()=>OQ,example_selectors:()=>D6,index:()=>a4,indexing:()=>E6,language_models__base:()=>iQ,language_models__chat_models:()=>t6,language_models__llms:()=>a6,language_models__profile:()=>Q5,language_models__structured_output:()=>r6,load__serializable:()=>_Q,memory:()=>Z5,messages:()=>V4,messages__tool:()=>jQ,output_parsers:()=>o6,output_parsers__openai_functions:()=>G5,output_parsers__openai_tools:()=>X5,outputs:()=>dQ,prompt_values:()=>pQ,prompts:()=>E5,retrievers:()=>R5,retrievers__document_compressors:()=>F5,runnables:()=>y6,runnables__graph:()=>lQ,singletons:()=>xQ,stores:()=>V5,structured_query:()=>S5,testing:()=>v5,tools:()=>nQ,tracers__base:()=>CQ,tracers__console:()=>MQ,tracers__log_stream:()=>gQ,tracers__run_collector:()=>b5,tracers__tracer_langchain:()=>yQ,types__stream:()=>x5,utils__async_caller:()=>mQ,utils__chunk_array:()=>f5,utils__context:()=>k5,utils__env:()=>TQ,utils__event_source_parse:()=>g5,utils__format:()=>u5,utils__function_calling:()=>i5,utils__hash:()=>fQ,utils__json_patch:()=>b6,utils__json_schema:()=>uQ,utils__math:()=>t5,utils__ssrf:()=>e5,utils__standard_schema:()=>cQ,utils__stream:()=>hQ,utils__testing:()=>IQ,utils__tiktoken:()=>oQ,utils__types:()=>n4,vectorstores:()=>WQ});var T7=50;function S7(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 Y9(Q){let{optionalImportsMap:Z,optionalImportEntrypoints:J,importMap:Y,secretsMap:G,secretsFromEnv:X,path:W,depth:$,maxDepth:q}=this,w=W.join(".");if($>q)throw Error(`Maximum recursion depth (${q}) 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((N,F)=>Y9.call({...this,path:[...W,`${F}`],depth:$+1},N)));let D=Q;if(aQ(D))return eQ(D);if("lc"in D&&"type"in D&&"id"in D&&D.lc===1&&D.type==="secret"){let[N]=D.id;if(N in G)return G[N];else if(X){let F=m1(N);if(F)return F}throw Error(`Missing secret "${N}" at ${w}`)}if("lc"in D&&"type"in D&&"id"in D&&D.lc===1&&D.type==="not_implemented"){let F=JSON.stringify(D);throw Error(`Trying to load an object that doesn't implement serialization: ${w} -> ${F}`)}if("lc"in D&&"type"in D&&"id"in D&&"kwargs"in D&&D.lc===1&&D.type==="constructor"){let N=D,F=JSON.stringify(N),[E,...R]=N.id.slice().reverse(),V=R.reverse(),I={langchain_core:rQ,langchain:Y},P=null,O=[V.join("/")];if(V[0]==="langchain_community")O.push(["langchain",...V.slice(1)].join("/"));let T=O.find((f)=>(f in Z));if(t4.concat(J).includes(V.join("/"))||T)if(T!==void 0)P=await Z[T];else throw Error(`Missing key "${V.join("/")}" for ${w} in load(optionalImportsMap={})`);else{let f;if(V[0]==="langchain"||V[0]==="langchain_core")f=I[V[0]],V.shift();else throw Error(`Invalid namespace: ${w} -> ${F}`);if(V.length===0)throw Error(`Invalid namespace: ${w} -> ${F}`);let K;do if(K=V.join("__"),K in f)break;else V.pop();while(V.length>0);if(K in f)P=f[K]}if(typeof P!=="object"||P===null)throw Error(`Invalid namespace: ${w} -> ${F}`);let m=P[E]??Object.values(P).find((f)=>typeof f==="function"&&Q3(f)===E);if(typeof m!=="function")throw Error(`Invalid identifer: ${w} -> ${F}`);let x=new m(tQ(await Y9.call({...this,path:[...W,"kwargs"],depth:$+1},N.kwargs),sQ,S7(m)));return Object.defineProperty(x.constructor,"name",{value:E}),x}let A={};for(let[N,F]of Object.entries(D))A[N]=await Y9.call({...this,path:[...W,N],depth:$+1},F);return A}async function Z3(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??T7};return Y9.call(Y,J)}function C7(Q){return Q!==null&&Q.lc===1&&Q.type==="constructor"&&Array.isArray(Q.id)}async function N0(Q){if(Q&&typeof Q==="object")if(Array.isArray(Q))return await Promise.all(Q.map((J)=>N0(J)));else{let Z={};for(let[J,Y]of Object.entries(Q))Z[J]=await N0(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(C7(Z))return Z3(JSON.stringify(Z));return Z}return Q}function B0(Q,Z,J,Y){return{lc:2,type:"constructor",id:[Q.name],method:Z??null,args:J??[],kwargs:Y??{}}}function M7(Q){if(Q===void 0)return{lc:2,type:"undefined"};else if(Q instanceof Set||Q instanceof Map)return B0(Q.constructor,void 0,[Array.from(Q)]);else if(Q instanceof RegExp)return B0(RegExp,void 0,[Q.source,Q.flags]);else if(Q instanceof Error)return B0(Q.constructor,void 0,[Q.message]);else if(Q?.lg_name==="Send")return{node:Q.node,args:Q.args};else return Q}var G9=class{_dumps(Q){return new TextEncoder().encode(s4(Q,(J,Y)=>{return M7(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 N0(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 A0(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]=A0(Q[J]);return Z}function y7(){return{v:4,id:q9(-2),ts:new Date().toISOString(),channel_values:{},channel_versions:{},versions_seen:{}}}function J3(Q){return{v:Q.v,id:Q.id,ts:Q.ts,channel_values:{...Q.channel_values},channel_versions:{...Q.channel_versions},versions_seen:A0(Q.versions_seen)}}var Y3=class{serde=new G9;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 G3(Q,Z){if(typeof Q==="number"&&typeof Z==="number")return Math.sign(Q-Z);return String(Q).localeCompare(String(Z))}function X3(...Q){return Q.reduce((Z,J,Y)=>{if(Y===0)return J;return G3(Z,J)>=0?Z:J})}var W3={[K9]:-1,[U9]:-2,[w9]:-3,[D9]:-4};function z3(Q){return Q.configurable?.checkpoint_id||Q.configurable?.thread_ts||""}var t8=class extends Error{constructor(Q){super(Q);this.name="InvalidNamespaceError"}};function v7(Q){if(Q.length===0)throw new t8("Namespace cannot be empty.");for(let Z of Q){if(typeof Z!=="string")throw new t8(`Invalid namespace label '${Z}' found in ${Q}. Namespace labels must be strings, but got ${typeof Z}.`);if(Z.includes("."))throw new t8(`Invalid namespace label '${Z}' found in ${Q}. Namespace labels cannot contain periods ('.').`);if(Z==="")throw new t8(`Namespace labels cannot be empty strings. Got ${Z} in ${Q}`)}if(Q[0]==="langgraph")throw new t8(`Root label for namespace cannot be "langgraph". Got: ${Q}`)}var X9=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:X}=Z;return(await this.batch([{namespacePrefix:Q,filter:J,limit:Y,offset:G,query:X}]))[0]}async put(Q,Z,J,Y){v7(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:X=0}=Q,W=[];if(Z)W.push({matchType:"prefix",path:Z});if(J)W.push({matchType:"suffix",path:J});return(await this.batch([{matchConditions:W.length?W:void 0,maxDepth:Y,limit:G,offset:X}]))[0]}start(){}stop(){}};var b7=(Q)=>{if("lg_name"in Q&&Q.lg_name==="AsyncBatchedStore")return Q.store;return Q},x7=class extends X9{lg_name="AsyncBatchedStore";store;queue=new Map;nextKey=0;running=!1;processingTask=null;constructor(Q){super();this.store=b7(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:X}=Z||{};return this.enqueueOperation({namespacePrefix:Q,filter:J,limit:Y,offset:G,query:X})}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 X=Array.from(Q.keys()).indexOf(G);Y(J[X])})}catch(Z){Q.forEach(({reject:J})=>{J(Z)})}}}toJSON(){return{queue:this.queue,nextKey:this.nextKey,running:this.running,store:"[LangGraphStore]"}}};var E0=class{serde=new G9;constructor(Q){this.serde=Q||this.serde}};
166
- export{p1 as Eg,q9 as Fg,K3 as Gg,T0 as Hg,U9 as Ig,_8 as Jg,g8 as Kg,h as Lg,x1 as Mg,H1 as Ng,C9 as Og,i6 as Pg,n6 as Qg,g1 as Rg,V3 as Sg,P3 as Tg,y9 as Ug,L8 as Vg,K7 as Wg,Z3 as Xg,y7 as Yg,J3 as Zg,Y3 as _g,G3 as $g,X3 as ah,W3 as bh,z3 as ch,x7 as dh,E0 as eh};