@mcp-use/inspector 0.4.12 → 0.4.13-canary.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/client/assets/{chunk-VL2OQCWN-B6188h-8.js → chunk-VL2OQCWN-D5zTMCrV.js} +2 -2
- package/dist/client/assets/embeddings-T3ulhIAT.js +1 -0
- package/dist/client/assets/{index-x_xzGcAx.js → index-B1m6hcte.js} +1 -1
- package/dist/client/assets/index-BgTUJ2nU.js +81 -0
- package/dist/client/assets/{index-LZZ02vm2.js → index-D2syF8VP.js} +4 -4
- package/dist/client/assets/index-D8wSHXf0.js +70 -0
- package/dist/client/assets/index-DOTQn2XV.js +4 -0
- package/dist/client/assets/{index-azKdcp4V.js → index-X8eKTn1y.js} +4 -4
- package/dist/client/assets/{index-Dhd81mGH.js → index-jpgFjbgb.js} +3 -3
- package/dist/client/assets/{index-B2AaM8iX.js → index-q-FFFyxK.js} +6 -6
- package/dist/client/assets/{langfuse-C4HKZ3NL-DdY799py.js → langfuse-C4HKZ3NL-DxYt-pQv.js} +3 -3
- package/dist/client/assets/{winston-BxLvA24A.js → winston-PkVSuyBJ.js} +1 -1
- package/dist/client/index.html +2 -2
- package/package.json +10 -5
- package/dist/client/assets/embeddings-CmTKipI3.js +0 -1
- package/dist/client/assets/index-CvPVR03j.js +0 -4
- package/dist/client/assets/index-DI2GdDtn.js +0 -150
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import{m as Ft,n as Bt,o as X,q as et,_ as U,r as Ie,s as Se,u as Ae,v as Ne,w as Oe,x as Pe,y as ke,z as Me,D as xe,E as Re,i as wt,G as Le,I as De,J as Fe,K as Be,L as Ue,M as je,N as Ve,k as Ge,O as ze,P as Gt,Q as $e,U as zt,V as Ze,W as He,X as We,Y as H,t as ut,H as Ct,Z as Xe,$ as Ye,a0 as Je,c as $t,a1 as nt,a2 as it,a3 as Zt,a4 as Ht,a5 as ot,l as Ke,a6 as bt,a7 as Ut,a8 as qe,a9 as jt,d as Y,g as Qe,aa as It,b as ta,R as Wt,ab as ea,ac as aa,ad as sa,A as Xt,ae as rt,af as z,ag as Yt,ah as na,ai as Jt,aj as ra,ak as ia,al as oa,am as ca,an as ua,ao as la,ap as ha,aq as ma,ar as fa,as as pa,e as Vt,at as ga,au as da,av as ba,aw as Tt,ax as _a}from"./index-BgTUJ2nU.js";import{g as ya,T as Ta,d as Ea}from"./chunk-VL2OQCWN-D5zTMCrV.js";import{o as Kt,s as qt}from"./index-D2syF8VP.js";function Qt(t,a,n,r,c){if(a!==t){typeof a.toJSON=="function"&&(a=a.toJSON());for(var u=Ft(a),m=Ft(t),l=!1,g=m.length-1;g>=0;g--){var f=m[g],T=t[f];if(Bt(a,f)&&!(a[f]===void 0&&T!==void 0&&Array.isArray(a)===!1)){var _=a[f];typeof T=="object"&&T!=null&&typeof _=="object"&&_!=null&&Array.isArray(T)===Array.isArray(_)?Qt(T,_,n,r+"/"+X(f),c):T!==_&&(c&&n.push({op:"test",path:r+"/"+X(f),value:et(T)}),n.push({op:"replace",path:r+"/"+X(f),value:et(_)}))}else Array.isArray(t)===Array.isArray(a)?(c&&n.push({op:"test",path:r+"/"+X(f),value:et(T)}),n.push({op:"remove",path:r+"/"+X(f)}),l=!0):(c&&n.push({op:"test",path:r,value:t}),n.push({op:"replace",path:r,value:a}))}if(!(!l&&u.length==m.length))for(var g=0;g<u.length;g++){var f=u[g];!Bt(t,f)&&a[f]!==void 0&&n.push({op:"add",path:r+"/"+X(f),value:et(a[f])})}}}function St(t,a,n=!1){var r=[];return Qt(t,a,r,"",n),r}var va={};U(va,{extendInteropZodObject:()=>We,getInteropZodDefaultGetter:()=>He,getInteropZodObjectShape:()=>Ze,getSchemaDescription:()=>zt,interopParse:()=>$e,interopParseAsync:()=>Gt,interopSafeParse:()=>ze,interopSafeParseAsync:()=>Ge,interopZodObjectMakeFieldsOptional:()=>Ve,interopZodObjectPartial:()=>je,interopZodObjectPassthrough:()=>Ue,interopZodObjectStrict:()=>Be,interopZodTransformInputSchema:()=>Fe,isInteropZodLiteral:()=>De,isInteropZodObject:()=>Le,isInteropZodSchema:()=>wt,isShapelessZodSchema:()=>Re,isSimpleStringZodSchema:()=>xe,isZodArrayV4:()=>Me,isZodLiteralV3:()=>ke,isZodLiteralV4:()=>Pe,isZodObjectV3:()=>Oe,isZodObjectV4:()=>Ne,isZodSchema:()=>Ae,isZodSchemaV3:()=>Se,isZodSchemaV4:()=>Ie});function te(t){return t!==void 0&&Array.isArray(t.lc_namespace)}function ee(t){return t!==void 0&&H.isRunnable(t)&&"lc_name"in t.constructor&&typeof t.constructor.lc_name=="function"&&t.constructor.lc_name()==="RunnableToolLike"}function ae(t){return!!t&&typeof t=="object"&&"name"in t&&"schema"in t&&(wt(t.schema)||t.schema!=null&&typeof t.schema=="object"&&"type"in t.schema&&typeof t.schema.type=="string"&&["null","boolean","object","array","number","string"].includes(t.schema.type))}function se(t){return ae(t)||ee(t)||te(t)}var wa={};U(wa,{convertToOpenAIFunction:()=>ne,convertToOpenAITool:()=>Ca,isLangChainTool:()=>se,isRunnableToolLike:()=>ee,isStructuredTool:()=>te,isStructuredToolParams:()=>ae});function ne(t,a){const n=typeof a=="number"?void 0:a;return{name:t.name,description:t.description,parameters:ut(t.schema),...n?.strict!==void 0?{strict:n.strict}:{}}}function Ca(t,a){const n=typeof a=="number"?void 0:a;let r;return se(t)?r={type:"function",function:ne(t)}:r=t,n?.strict!==void 0&&(r.function.strict=n.strict),r}var Ia={};U(Ia,{BasePromptValue:()=>lt,ChatPromptValue:()=>ie,ImagePromptValue:()=>Sa,StringPromptValue:()=>re});var lt=class extends Ye{},re=class extends lt{static lc_name(){return"StringPromptValue"}lc_namespace=["langchain_core","prompt_values"];lc_serializable=!0;value;constructor(t){super({value:t}),this.value=t}toString(){return this.value}toChatMessages(){return[new Ct(this.value)]}},ie=class extends lt{lc_namespace=["langchain_core","prompt_values"];lc_serializable=!0;static lc_name(){return"ChatPromptValue"}messages;constructor(t){Array.isArray(t)&&(t={messages:t}),super(t),this.messages=t.messages}toString(){return Xe(this.messages)}toChatMessages(){return this.messages}},Sa=class extends lt{lc_namespace=["langchain_core","prompt_values"];lc_serializable=!0;static lc_name(){return"ImagePromptValue"}imageUrl;value;constructor(t){"imageUrl"in t||(t={imageUrl:t}),super(t),this.imageUrl=t.imageUrl}toString(){return this.imageUrl.url}toChatMessages(){return[new Ct({content:[{type:"image_url",image_url:{detail:this.imageUrl.detail,url:this.imageUrl.url}}]})]}},p="0123456789abcdef".split(""),Aa=[-2147483648,8388608,32768,128],F=[24,16,8,0],at=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],P=[];function B(t,a){a?(P[0]=P[16]=P[1]=P[2]=P[3]=P[4]=P[5]=P[6]=P[7]=P[8]=P[9]=P[10]=P[11]=P[12]=P[13]=P[14]=P[15]=0,this.blocks=P):this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],t?(this.h0=3238371032,this.h1=914150663,this.h2=812702999,this.h3=4144912697,this.h4=4290775857,this.h5=1750603025,this.h6=1694076839,this.h7=3204075428):(this.h0=1779033703,this.h1=3144134277,this.h2=1013904242,this.h3=2773480762,this.h4=1359893119,this.h5=2600822924,this.h6=528734635,this.h7=1541459225),this.block=this.start=this.bytes=this.hBytes=0,this.finalized=this.hashed=!1,this.first=!0,this.is224=t}B.prototype.update=function(t){if(!this.finalized){var a,n=typeof t;if(n!=="string"){if(n==="object"){if(t===null)throw new Error(ERROR);if(ARRAY_BUFFER&&t.constructor===ArrayBuffer)t=new Uint8Array(t);else if(!Array.isArray(t)&&(!ARRAY_BUFFER||!ArrayBuffer.isView(t)))throw new Error(ERROR)}else throw new Error(ERROR);a=!0}for(var r,c=0,u,m=t.length,l=this.blocks;c<m;){if(this.hashed&&(this.hashed=!1,l[0]=this.block,this.block=l[16]=l[1]=l[2]=l[3]=l[4]=l[5]=l[6]=l[7]=l[8]=l[9]=l[10]=l[11]=l[12]=l[13]=l[14]=l[15]=0),a)for(u=this.start;c<m&&u<64;++c)l[u>>>2]|=t[c]<<F[u++&3];else for(u=this.start;c<m&&u<64;++c)r=t.charCodeAt(c),r<128?l[u>>>2]|=r<<F[u++&3]:r<2048?(l[u>>>2]|=(192|r>>>6)<<F[u++&3],l[u>>>2]|=(128|r&63)<<F[u++&3]):r<55296||r>=57344?(l[u>>>2]|=(224|r>>>12)<<F[u++&3],l[u>>>2]|=(128|r>>>6&63)<<F[u++&3],l[u>>>2]|=(128|r&63)<<F[u++&3]):(r=65536+((r&1023)<<10|t.charCodeAt(++c)&1023),l[u>>>2]|=(240|r>>>18)<<F[u++&3],l[u>>>2]|=(128|r>>>12&63)<<F[u++&3],l[u>>>2]|=(128|r>>>6&63)<<F[u++&3],l[u>>>2]|=(128|r&63)<<F[u++&3]);this.lastByteIndex=u,this.bytes+=u-this.start,u>=64?(this.block=l[16],this.start=u-64,this.hash(),this.hashed=!0):this.start=u}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296<<0,this.bytes=this.bytes%4294967296),this}};B.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var t=this.blocks,a=this.lastByteIndex;t[16]=this.block,t[a>>>2]|=Aa[a&3],this.block=t[16],a>=56&&(this.hashed||this.hash(),t[0]=this.block,t[16]=t[1]=t[2]=t[3]=t[4]=t[5]=t[6]=t[7]=t[8]=t[9]=t[10]=t[11]=t[12]=t[13]=t[14]=t[15]=0),t[14]=this.hBytes<<3|this.bytes>>>29,t[15]=this.bytes<<3,this.hash()}};B.prototype.hash=function(){var t=this.h0,a=this.h1,n=this.h2,r=this.h3,c=this.h4,u=this.h5,m=this.h6,l=this.h7,g=this.blocks,f,T,_,E,d,y,b,v,w,M,S;for(f=16;f<64;++f)d=g[f-15],T=(d>>>7|d<<25)^(d>>>18|d<<14)^d>>>3,d=g[f-2],_=(d>>>17|d<<15)^(d>>>19|d<<13)^d>>>10,g[f]=g[f-16]+T+g[f-7]+_<<0;for(S=a&n,f=0;f<64;f+=4)this.first?(this.is224?(v=300032,d=g[0]-1413257819,l=d-150054599<<0,r=d+24177077<<0):(v=704751109,d=g[0]-210244248,l=d-1521486534<<0,r=d+143694565<<0),this.first=!1):(T=(t>>>2|t<<30)^(t>>>13|t<<19)^(t>>>22|t<<10),_=(c>>>6|c<<26)^(c>>>11|c<<21)^(c>>>25|c<<7),v=t&a,E=v^t&n^S,b=c&u^~c&m,d=l+_+b+at[f]+g[f],y=T+E,l=r+d<<0,r=d+y<<0),T=(r>>>2|r<<30)^(r>>>13|r<<19)^(r>>>22|r<<10),_=(l>>>6|l<<26)^(l>>>11|l<<21)^(l>>>25|l<<7),w=r&t,E=w^r&a^v,b=m&l^~m&c,d=u+_+b+at[f+1]+g[f+1],y=T+E,m=n+d<<0,n=d+y<<0,T=(n>>>2|n<<30)^(n>>>13|n<<19)^(n>>>22|n<<10),_=(m>>>6|m<<26)^(m>>>11|m<<21)^(m>>>25|m<<7),M=n&r,E=M^n&t^w,b=u&m^~u&l,d=c+_+b+at[f+2]+g[f+2],y=T+E,u=a+d<<0,a=d+y<<0,T=(a>>>2|a<<30)^(a>>>13|a<<19)^(a>>>22|a<<10),_=(u>>>6|u<<26)^(u>>>11|u<<21)^(u>>>25|u<<7),S=a&n,E=S^a&r^M,b=u&m^~u&l,d=c+_+b+at[f+3]+g[f+3],y=T+E,c=t+d<<0,t=d+y<<0,this.chromeBugWorkAround=!0;this.h0=this.h0+t<<0,this.h1=this.h1+a<<0,this.h2=this.h2+n<<0,this.h3=this.h3+r<<0,this.h4=this.h4+c<<0,this.h5=this.h5+u<<0,this.h6=this.h6+m<<0,this.h7=this.h7+l<<0};B.prototype.hex=function(){this.finalize();var t=this.h0,a=this.h1,n=this.h2,r=this.h3,c=this.h4,u=this.h5,m=this.h6,l=this.h7,g=p[t>>>28&15]+p[t>>>24&15]+p[t>>>20&15]+p[t>>>16&15]+p[t>>>12&15]+p[t>>>8&15]+p[t>>>4&15]+p[t&15]+p[a>>>28&15]+p[a>>>24&15]+p[a>>>20&15]+p[a>>>16&15]+p[a>>>12&15]+p[a>>>8&15]+p[a>>>4&15]+p[a&15]+p[n>>>28&15]+p[n>>>24&15]+p[n>>>20&15]+p[n>>>16&15]+p[n>>>12&15]+p[n>>>8&15]+p[n>>>4&15]+p[n&15]+p[r>>>28&15]+p[r>>>24&15]+p[r>>>20&15]+p[r>>>16&15]+p[r>>>12&15]+p[r>>>8&15]+p[r>>>4&15]+p[r&15]+p[c>>>28&15]+p[c>>>24&15]+p[c>>>20&15]+p[c>>>16&15]+p[c>>>12&15]+p[c>>>8&15]+p[c>>>4&15]+p[c&15]+p[u>>>28&15]+p[u>>>24&15]+p[u>>>20&15]+p[u>>>16&15]+p[u>>>12&15]+p[u>>>8&15]+p[u>>>4&15]+p[u&15]+p[m>>>28&15]+p[m>>>24&15]+p[m>>>20&15]+p[m>>>16&15]+p[m>>>12&15]+p[m>>>8&15]+p[m>>>4&15]+p[m&15];return this.is224||(g+=p[l>>>28&15]+p[l>>>24&15]+p[l>>>20&15]+p[l>>>16&15]+p[l>>>12&15]+p[l>>>8&15]+p[l>>>4&15]+p[l&15]),g};B.prototype.toString=B.prototype.hex;B.prototype.digest=function(){this.finalize();var t=this.h0,a=this.h1,n=this.h2,r=this.h3,c=this.h4,u=this.h5,m=this.h6,l=this.h7,g=[t>>>24&255,t>>>16&255,t>>>8&255,t&255,a>>>24&255,a>>>16&255,a>>>8&255,a&255,n>>>24&255,n>>>16&255,n>>>8&255,n&255,r>>>24&255,r>>>16&255,r>>>8&255,r&255,c>>>24&255,c>>>16&255,c>>>8&255,c&255,u>>>24&255,u>>>16&255,u>>>8&255,u&255,m>>>24&255,m>>>16&255,m>>>8&255,m&255];return this.is224||g.push(l>>>24&255,l>>>16&255,l>>>8&255,l&255),g};B.prototype.array=B.prototype.digest;B.prototype.arrayBuffer=function(){this.finalize();var t=new ArrayBuffer(this.is224?28:32),a=new DataView(t);return a.setUint32(0,this.h0),a.setUint32(4,this.h1),a.setUint32(8,this.h2),a.setUint32(12,this.h3),a.setUint32(16,this.h4),a.setUint32(20,this.h5),a.setUint32(24,this.h6),this.is224||a.setUint32(28,this.h7),t};const oe=(...t)=>new B(!1,!0).update(t.join("")).hex();var Na={};U(Na,{sha256:()=>oe});var Oa={};U(Oa,{BaseCache:()=>ue,InMemoryCache:()=>le,defaultHashKeyEncoder:()=>ce,deserializeStoredGeneration:()=>Pa,serializeGeneration:()=>ka});const ce=(...t)=>oe(t.join("_"));function Pa(t){return t.message!==void 0?{text:t.text,message:Je(t.message)}:{text:t.text}}function ka(t){const a={text:t.text};return t.message!==void 0&&(a.message=t.message.toDict()),a}var ue=class{keyEncoder=ce;makeDefaultKeyEncoder(t){this.keyEncoder=t}};const Ma=new Map;var le=class he extends ue{cache;constructor(a){super(),this.cache=a??new Map}lookup(a,n){return Promise.resolve(this.cache.get(this.keyEncoder(a,n))??null)}async update(a,n,r){this.cache.set(this.keyEncoder(a,n),r)}static global(){return new he(Ma)}},xa={};U(xa,{encodingForModel:()=>At,getEncoding:()=>me});const st={},Ra=new $t({});async function me(t){return t in st||(st[t]=Ra.fetch(`https://tiktoken.pages.dev/js/${t}.json`).then(a=>a.json()).then(a=>new Ta(a)).catch(a=>{throw delete st[t],a})),await st[t]}async function At(t){return me(ya(t))}var La={};U(La,{BaseLangChain:()=>pe,BaseLanguageModel:()=>ge,calculateMaxTokens:()=>Ba,getEmbeddingContextSize:()=>Da,getModelContextSize:()=>fe,getModelNameForTiktoken:()=>ht,isOpenAITool:()=>Fa});const ht=t=>t.startsWith("gpt-3.5-turbo-16k")?"gpt-3.5-turbo-16k":t.startsWith("gpt-3.5-turbo-")?"gpt-3.5-turbo":t.startsWith("gpt-4-32k")?"gpt-4-32k":t.startsWith("gpt-4-")?"gpt-4":t.startsWith("gpt-4o")?"gpt-4o":t,Da=t=>{switch(t){case"text-embedding-ada-002":return 8191;default:return 2046}},fe=t=>{switch(ht(t)){case"gpt-3.5-turbo-16k":return 16384;case"gpt-3.5-turbo":return 4096;case"gpt-4-32k":return 32768;case"gpt-4":return 8192;case"text-davinci-003":return 4097;case"text-curie-001":return 2048;case"text-babbage-001":return 2048;case"text-ada-001":return 2048;case"code-davinci-002":return 8e3;case"code-cushman-001":return 2048;default:return 4097}};function Fa(t){return typeof t!="object"||!t?!1:!!("type"in t&&t.type==="function"&&"function"in t&&typeof t.function=="object"&&t.function&&"name"in t.function&&"parameters"in t.function)}const Ba=async({prompt:t,modelName:a})=>{let n;try{n=(await At(ht(a))).encode(t).length}catch{console.warn("Failed to calculate number of tokens, falling back to approximate count"),n=Math.ceil(t.length/4)}return fe(a)-n},Ua=()=>!1;var pe=class extends H{verbose;callbacks;tags;metadata;get lc_attributes(){return{callbacks:void 0,verbose:void 0}}constructor(t){super(t),this.verbose=t.verbose??Ua(),this.callbacks=t.callbacks,this.tags=t.tags??[],this.metadata=t.metadata??{}}},ge=class extends pe{get callKeys(){return["stop","timeout","signal","tags","metadata","callbacks"]}caller;cache;constructor({callbacks:t,callbackManager:a,...n}){const{cache:r,...c}=n;super({callbacks:t??a,...c}),typeof r=="object"?this.cache=r:r?this.cache=le.global():this.cache=void 0,this.caller=new $t(n??{})}_encoding;async getNumTokens(t){let a;typeof t=="string"?a=t:a=t.map(r=>typeof r=="string"?r:r.type==="text"&&"text"in r?r.text:"").join("");let n=Math.ceil(a.length/4);if(!this._encoding)try{this._encoding=await At("modelName"in this?ht(this.modelName):"gpt2")}catch(r){console.warn("Failed to calculate number of tokens, falling back to approximate count",r)}if(this._encoding)try{n=this._encoding.encode(a).length}catch(r){console.warn("Failed to calculate number of tokens, falling back to approximate count",r)}return n}static _convertInputToPromptValue(t){return typeof t=="string"?new re(t):Array.isArray(t)?new ie(t.map(nt)):t}_identifyingParams(){return{}}_getSerializedCacheKeyParametersForCall({config:t,...a}){const n={...this._identifyingParams(),...a,_type:this._llmType(),_model:this._modelType()};return Object.entries(n).filter(([u,m])=>m!==void 0).map(([u,m])=>`${u}:${JSON.stringify(m)}`).sort().join(",")}serialize(){return{...this._identifyingParams(),_type:this._llmType(),_model:this._modelType()}}static async deserialize(t){throw new Error("Use .toJSON() instead")}},ct=class extends H{static lc_name(){return"RunnablePassthrough"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;func;constructor(t){super(t),t&&(this.func=t.func)}async invoke(t,a){const n=it(a);return this.func&&await this.func(t,n),this._callWithConfig(r=>Promise.resolve(r),t,n)}async*transform(t,a){const n=it(a);let r,c=!0;for await(const u of this._transformStreamWithConfig(t,m=>m,n))if(yield u,c)if(r===void 0)r=u;else try{r=ot(r,u)}catch{r=void 0,c=!1}this.func&&r!==void 0&&await this.func(r,n)}static assign(t){return new Zt(new Ht({steps:t}))}};const ja=t=>t();function _t(t){const a=t.constructor;return new a({...t,content:t.contentBlocks,response_metadata:{...t.response_metadata,output_version:"v1"}})}var Va={};U(Va,{BaseChatModel:()=>de,SimpleChatModel:()=>Ga});function yt(t){const a=[];for(const n of t){let r=n;if(Array.isArray(n.content))for(let c=0;c<n.content.length;c++){const u=n.content[c];(ea(u)||aa(u))&&r===n&&(r=new n.constructor({...r,content:[...n.content.slice(0,c),sa(u),...n.content.slice(c+1)]}))}a.push(r)}return a}var de=class $ extends ge{lc_namespace=["langchain","chat_models",this._llmType()];disableStreaming=!1;outputVersion;get callKeys(){return[...super.callKeys,"outputVersion"]}constructor(a){super(a),this.outputVersion=ja(()=>{const n=a.outputVersion??Ke("LC_OUTPUT_VERSION");return n&&["v0","v1"].includes(n)?n:"v0"})}_separateRunnableConfigFromCallOptionsCompat(a){const[n,r]=super._separateRunnableConfigFromCallOptions(a);return r.signal=n.signal,[n,r]}async invoke(a,n){const r=$._convertInputToPromptValue(a);return(await this.generatePrompt([r],n,n?.callbacks)).generations[0][0].message}async*_streamResponseChunks(a,n,r){throw new Error("Not implemented.")}async*_streamIterator(a,n){if(this._streamResponseChunks===$.prototype._streamResponseChunks||this.disableStreaming)yield this.invoke(a,n);else{const c=$._convertInputToPromptValue(a).toChatMessages(),[u,m]=this._separateRunnableConfigFromCallOptionsCompat(n),l={...u.metadata,...this.getLsParams(m)},g=await bt.configure(u.callbacks,this.callbacks,u.tags,this.tags,l,this.metadata,{verbose:this.verbose}),f={options:m,invocation_params:this?.invocationParams(m),batch_size:1},T=m.outputVersion??this.outputVersion,_=await g?.handleChatModelStart(this.toJSON(),[yt(c)],u.runId,void 0,f,void 0,void 0,u.runName);let E,d;try{for await(const y of this._streamResponseChunks(c,m,_?.[0])){if(y.message.id==null){const b=_?.at(0)?.runId;b!=null&&y.message._updateId(`run-${b}`)}y.message.response_metadata={...y.generationInfo,...y.message.response_metadata},T==="v1"?yield _t(y.message):yield y.message,E?E=E.concat(y):E=y,Ut(y.message)&&y.message.usage_metadata!==void 0&&(d={tokenUsage:{promptTokens:y.message.usage_metadata.input_tokens,completionTokens:y.message.usage_metadata.output_tokens,totalTokens:y.message.usage_metadata.total_tokens}})}}catch(y){throw await Promise.all((_??[]).map(b=>b?.handleLLMError(y))),y}await Promise.all((_??[]).map(y=>y?.handleLLMEnd({generations:[[E]],llmOutput:d})))}}getLsParams(a){const n=this.getName().startsWith("Chat")?this.getName().replace("Chat",""):this.getName();return{ls_model_type:"chat",ls_stop:a.stop,ls_provider:n}}async _generateUncached(a,n,r,c){const u=a.map(E=>E.map(nt));let m;if(c!==void 0&&c.length===u.length)m=c;else{const E={...r.metadata,...this.getLsParams(n)},d=await bt.configure(r.callbacks,this.callbacks,r.tags,this.tags,E,this.metadata,{verbose:this.verbose}),y={options:n,invocation_params:this?.invocationParams(n),batch_size:1};m=await d?.handleChatModelStart(this.toJSON(),u.map(yt),r.runId,void 0,y,void 0,void 0,r.runName)}const l=n.outputVersion??this.outputVersion,g=[],f=[];if(!!m?.[0].handlers.find(qe)&&!this.disableStreaming&&u.length===1&&this._streamResponseChunks!==$.prototype._streamResponseChunks)try{const E=await this._streamResponseChunks(u[0],n,m?.[0]);let d,y;for await(const b of E){if(b.message.id==null){const v=m?.at(0)?.runId;v!=null&&b.message._updateId(`run-${v}`)}d===void 0?d=b:d=ot(d,b),Ut(b.message)&&b.message.usage_metadata!==void 0&&(y={tokenUsage:{promptTokens:b.message.usage_metadata.input_tokens,completionTokens:b.message.usage_metadata.output_tokens,totalTokens:b.message.usage_metadata.total_tokens}})}if(d===void 0)throw new Error("Received empty response from chat model call.");g.push([d]),await m?.[0].handleLLMEnd({generations:g,llmOutput:y})}catch(E){throw await m?.[0].handleLLMError(E),E}else{const E=await Promise.allSettled(u.map(async(d,y)=>{const b=await this._generate(d,{...n,promptIndex:y},m?.[y]);if(l==="v1")for(const v of b.generations)v.message=_t(v.message);return b}));await Promise.all(E.map(async(d,y)=>{if(d.status==="fulfilled"){const b=d.value;for(const v of b.generations){if(v.message.id==null){const w=m?.at(0)?.runId;w!=null&&v.message._updateId(`run-${w}`)}v.message.response_metadata={...v.generationInfo,...v.message.response_metadata}}return b.generations.length===1&&(b.generations[0].message.response_metadata={...b.llmOutput,...b.generations[0].message.response_metadata}),g[y]=b.generations,f[y]=b.llmOutput,m?.[y]?.handleLLMEnd({generations:[b.generations],llmOutput:b.llmOutput})}else return await m?.[y]?.handleLLMError(d.reason),Promise.reject(d.reason)}))}const _={generations:g,llmOutput:f.length?this._combineLLMOutput?.(...f):void 0};return Object.defineProperty(_,jt,{value:m?{runIds:m?.map(E=>E.runId)}:void 0,configurable:!0}),_}async _generateCached({messages:a,cache:n,llmStringKey:r,parsedOptions:c,handledOptions:u}){const m=a.map(w=>w.map(nt)),l={...u.metadata,...this.getLsParams(c)},g=await bt.configure(u.callbacks,this.callbacks,u.tags,this.tags,l,this.metadata,{verbose:this.verbose}),f={options:c,invocation_params:this?.invocationParams(c),batch_size:1},T=await g?.handleChatModelStart(this.toJSON(),m.map(yt),u.runId,void 0,f,void 0,void 0,u.runName),_=[],d=(await Promise.allSettled(m.map(async(w,M)=>{const S=$._convertInputToPromptValue(w).toString(),R=await n.lookup(S,r);return R==null&&_.push(M),R}))).map((w,M)=>({result:w,runManager:T?.[M]})).filter(({result:w})=>w.status==="fulfilled"&&w.value!=null||w.status==="rejected"),y=c.outputVersion??this.outputVersion,b=[];await Promise.all(d.map(async({result:w,runManager:M},S)=>{if(w.status==="fulfilled"){const R=w.value;return b[S]=R.map(D=>("message"in D&&Y(D.message)&&Qe(D.message)&&(D.message.usage_metadata={input_tokens:0,output_tokens:0,total_tokens:0},y==="v1"&&(D.message=_t(D.message))),D.generationInfo={...D.generationInfo,tokenUsage:{}},D)),R.length&&await M?.handleLLMNewToken(R[0].text),M?.handleLLMEnd({generations:[R]},void 0,void 0,void 0,{cached:!0})}else return await M?.handleLLMError(w.reason,void 0,void 0,void 0,{cached:!0}),Promise.reject(w.reason)}));const v={generations:b,missingPromptIndices:_,startedRunManagers:T};return Object.defineProperty(v,jt,{value:T?{runIds:T?.map(w=>w.runId)}:void 0,configurable:!0}),v}async generate(a,n,r){let c;Array.isArray(n)?c={stop:n}:c=n;const u=a.map(y=>y.map(nt)),[m,l]=this._separateRunnableConfigFromCallOptionsCompat(c);if(m.callbacks=m.callbacks??r,!this.cache)return this._generateUncached(u,l,m);const{cache:g}=this,f=this._getSerializedCacheKeyParametersForCall(l),{generations:T,missingPromptIndices:_,startedRunManagers:E}=await this._generateCached({messages:u,cache:g,llmStringKey:f,parsedOptions:l,handledOptions:m});let d={};if(_.length>0){const y=await this._generateUncached(_.map(b=>u[b]),l,m,E!==void 0?_.map(b=>E?.[b]):void 0);await Promise.all(y.generations.map(async(b,v)=>{const w=_[v];T[w]=b;const M=$._convertInputToPromptValue(u[w]).toString();return g.update(M,f,b)})),d=y.llmOutput??{}}return{generations:T,llmOutput:d}}invocationParams(a){return{}}_modelType(){return"base_chat_model"}async generatePrompt(a,n,r){const c=a.map(u=>u.toChatMessages());return this.generate(c,n,r)}withStructuredOutput(a,n){if(typeof this.bindTools!="function")throw new Error('Chat model must implement ".bindTools()" to use withStructuredOutput.');if(n?.strict)throw new Error('"strict" mode is not supported for this model by default.');const r=a,c=n?.name,u=zt(r)??"A function available to call.",m=n?.method,l=n?.includeRaw;if(m==="jsonMode")throw new Error('Base withStructuredOutput implementation only supports "functionCalling" as a method.');let g=c??"extract",f;wt(r)?f=[{type:"function",function:{name:g,description:u,parameters:ut(r)}}]:("name"in r&&(g=r.name),f=[{type:"function",function:{name:g,description:u,parameters:r}}]);const T=this.bindTools(f),_=It.from(b=>{if(!ta.isInstance(b))throw new Error("Input is not an AIMessageChunk.");if(!b.tool_calls||b.tool_calls.length===0)throw new Error("No tool calls found in the response.");const v=b.tool_calls.find(w=>w.name===g);if(!v)throw new Error(`No tool call found with name ${g}.`);return v.args});if(!l)return T.pipe(_).withConfig({runName:"StructuredOutput"});const E=ct.assign({parsed:(b,v)=>_.invoke(b.raw,v)}),d=ct.assign({parsed:()=>null}),y=E.withFallbacks({fallbacks:[d]});return Wt.from([{raw:T},y]).withConfig({runName:"StructuredOutputRunnable"})}},Ga=class extends de{async _generate(t,a,n){const r=await this._call(t,a,n),c=new Xt(r);if(typeof c.content!="string")throw new Error("Cannot generate with a simple chat model when output is not a string.");return{generations:[{text:c.content,message:c}]}}},za=class extends H{static lc_name(){return"RouterRunnable"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;runnables;constructor(t){super(t),this.runnables=t.runnables}async invoke(t,a){const{key:n,input:r}=t,c=this.runnables[n];if(c===void 0)throw new Error(`No runnable associated with key "${n}".`);return c.invoke(r,it(a))}async batch(t,a,n){const r=t.map(_=>_.key),c=t.map(_=>_.input);if(r.find(_=>this.runnables[_]===void 0)!==void 0)throw new Error("One or more keys do not have a corresponding runnable.");const m=r.map(_=>this.runnables[_]),l=this._getOptionsList(a??{},t.length),g=l[0]?.maxConcurrency??n?.maxConcurrency,f=g&&g>0?g:t.length,T=[];for(let _=0;_<c.length;_+=f){const E=c.slice(_,_+f).map((y,b)=>m[b].invoke(y,l[b])),d=await Promise.all(E);T.push(d)}return T.flat()}async stream(t,a){const{key:n,input:r}=t,c=this.runnables[n];if(c===void 0)throw new Error(`No runnable associated with key "${n}".`);return c.stream(r,a)}},$a=class extends H{static lc_name(){return"RunnableBranch"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;default;branches;constructor(t){super(t),this.branches=t.branches,this.default=t.default}static from(t){if(t.length<1)throw new Error("RunnableBranch requires at least one branch");const n=t.slice(0,-1).map(([c,u])=>[rt(c),rt(u)]),r=rt(t[t.length-1]);return new this({branches:n,default:r})}async _invoke(t,a,n){let r;for(let c=0;c<this.branches.length;c+=1){const[u,m]=this.branches[c];if(await u.invoke(t,z(a,{callbacks:n?.getChild(`condition:${c+1}`)}))){r=await m.invoke(t,z(a,{callbacks:n?.getChild(`branch:${c+1}`)}));break}}return r||(r=await this.default.invoke(t,z(a,{callbacks:n?.getChild("branch:default")}))),r}async invoke(t,a={}){return this._callWithConfig(this._invoke,t,a)}async*_streamIterator(t,a){const r=await(await Yt(a))?.handleChainStart(this.toJSON(),na(t,"input"),a?.runId,void 0,void 0,void 0,a?.runName);let c,u=!0,m;try{for(let l=0;l<this.branches.length;l+=1){const[g,f]=this.branches[l];if(await g.invoke(t,z(a,{callbacks:r?.getChild(`condition:${l+1}`)}))){m=await f.stream(t,z(a,{callbacks:r?.getChild(`branch:${l+1}`)}));for await(const _ of m)if(yield _,u)if(c===void 0)c=_;else try{c=ot(c,_)}catch{c=void 0,u=!1}break}}if(m===void 0){m=await this.default.stream(t,z(a,{callbacks:r?.getChild("branch:default")}));for await(const l of m)if(yield l,u)if(c===void 0)c=l;else try{c=ot(c,l)}catch{c=void 0,u=!1}}}catch(l){throw await r?.handleChainError(l),l}await r?.handleChainEnd(c??{})}},Za=class extends Jt{runnable;inputMessagesKey;outputMessagesKey;historyMessagesKey;getMessageHistory;constructor(t){let a=It.from((u,m)=>this._enterHistory(u,m??{})).withConfig({runName:"loadHistory"});const n=t.historyMessagesKey??t.inputMessagesKey;n&&(a=ct.assign({[n]:a}).withConfig({runName:"insertHistory"}));const r=a.pipe(t.runnable.withListeners({onEnd:(u,m)=>this._exitHistory(u,m??{})})).withConfig({runName:"RunnableWithMessageHistory"}),c=t.config??{};super({...t,config:c,bound:r}),this.runnable=t.runnable,this.getMessageHistory=t.getMessageHistory,this.inputMessagesKey=t.inputMessagesKey,this.outputMessagesKey=t.outputMessagesKey,this.historyMessagesKey=t.historyMessagesKey}_getInputMessages(t){let a;if(typeof t=="object"&&!Array.isArray(t)&&!Y(t)){let n;this.inputMessagesKey?n=this.inputMessagesKey:Object.keys(t).length===1?n=Object.keys(t)[0]:n="input",Array.isArray(t[n])&&Array.isArray(t[n][0])?a=t[n][0]:a=t[n]}else a=t;if(typeof a=="string")return[new Ct(a)];if(Array.isArray(a))return a;if(Y(a))return[a];throw new Error(`Expected a string, BaseMessage, or array of BaseMessages.
|
|
2
|
+
Got ${JSON.stringify(a,null,2)}`)}_getOutputMessages(t){let a;if(!Array.isArray(t)&&!Y(t)&&typeof t!="string"){let n;this.outputMessagesKey!==void 0?n=this.outputMessagesKey:Object.keys(t).length===1?n=Object.keys(t)[0]:n="output",t.generations!==void 0?a=t.generations[0][0].message:a=t[n]}else a=t;if(typeof a=="string")return[new Xt(a)];if(Array.isArray(a))return a;if(Y(a))return[a];throw new Error(`Expected a string, BaseMessage, or array of BaseMessages. Received: ${JSON.stringify(a,null,2)}`)}async _enterHistory(t,a){const r=await(a?.configurable?.messageHistory).getMessages();return this.historyMessagesKey===void 0?r.concat(this._getInputMessages(t)):r}async _exitHistory(t,a){const n=a.configurable?.messageHistory;let r;Array.isArray(t.inputs)&&Array.isArray(t.inputs[0])?r=t.inputs[0]:r=t.inputs;let c=this._getInputMessages(r);if(this.historyMessagesKey===void 0){const l=await n.getMessages();c=c.slice(l.length)}const u=t.outputs;if(!u)throw new Error(`Output values from 'Run' undefined. Run: ${JSON.stringify(t,null,2)}`);const m=this._getOutputMessages(u);await n.addMessages([...c,...m])}async _mergeConfig(...t){const a=await super._mergeConfig(...t);if(!a.configurable||!a.configurable.sessionId){const r={[this.inputMessagesKey??"input"]:"foo"},c={configurable:{sessionId:"123"}};throw new Error(`sessionId is required. Pass it in as part of the config argument to .invoke() or .stream()
|
|
3
|
+
eg. chain.invoke(${JSON.stringify(r)}, ${JSON.stringify(c)})`)}const{sessionId:n}=a.configurable;return a.configurable.messageHistory=await this.getMessageHistory(n),a}},Ha={};U(Ha,{RouterRunnable:()=>za,Runnable:()=>H,RunnableAssign:()=>Zt,RunnableBinding:()=>Jt,RunnableBranch:()=>$a,RunnableEach:()=>ma,RunnableLambda:()=>It,RunnableMap:()=>Ht,RunnableParallel:()=>ha,RunnablePassthrough:()=>ct,RunnablePick:()=>la,RunnableRetry:()=>ua,RunnableSequence:()=>Wt,RunnableToolLike:()=>ca,RunnableWithFallbacks:()=>oa,RunnableWithMessageHistory:()=>Za,_coerceToRunnable:()=>rt,ensureConfig:()=>it,getCallbackManagerForConfig:()=>Yt,mergeConfigs:()=>ia,patchConfig:()=>z,pickRunnableConfigKeys:()=>ra});var be=class extends H{parseResultWithPrompt(t,a,n){return this.parseResult(t,n)}_baseMessageToString(t){return typeof t.content=="string"?t.content:this._baseMessageContentToString(t.content)}_baseMessageContentToString(t){return JSON.stringify(t)}async invoke(t,a){return typeof t=="string"?this._callWithConfig(async(n,r)=>this.parseResult([{text:n}],r?.callbacks),t,{...a,runType:"parser"}):this._callWithConfig(async(n,r)=>this.parseResult([{message:n,text:this._baseMessageToString(n)}],r?.callbacks),t,{...a,runType:"parser"})}},mt=class extends be{parseResult(t,a){return this.parse(t[0].text,a)}async parseWithPrompt(t,a,n){return this.parse(t,n)}_type(){throw new Error("_type not implemented")}},Z=class extends Error{llmOutput;observation;sendToLLM;constructor(t,a,n,r=!1){if(super(t),this.llmOutput=a,this.observation=n,this.sendToLLM=r,r&&(n===void 0||a===void 0))throw new Error("Arguments 'observation' & 'llmOutput' are required if 'sendToLlm' is true");fa(this,"OUTPUT_PARSING_FAILURE")}},q=class extends mt{async*_transform(t){for await(const a of t)typeof a=="string"?yield this.parseResult([{text:a}]):yield this.parseResult([{message:a,text:this._baseMessageToString(a)}])}async*transform(t,a){yield*this._transformStreamWithConfig(t,this._transform.bind(this),{...a,runType:"parser"})}},Nt=class extends q{diff=!1;constructor(t){super(t),this.diff=t?.diff??this.diff}async*_transform(t){let a,n;for await(const r of t){if(typeof r!="string"&&typeof r.content!="string")throw new Error("Cannot handle non-string output.");let c;if(pa(r)){if(typeof r.content!="string")throw new Error("Cannot handle non-string message output.");c=new Vt({message:r,text:r.content})}else if(Y(r)){if(typeof r.content!="string")throw new Error("Cannot handle non-string message output.");c=new Vt({message:ga(r),text:r.content})}else c=new da({text:r});n===void 0?n=c:n=n.concat(c);const u=await this.parsePartialResult([n]);u!=null&&!Ea(u,a)&&(this.diff?yield this._diff(a,u):yield u,a=u)}}getFormatInstructions(){return""}},Wa=class extends q{static lc_name(){return"BytesOutputParser"}lc_namespace=["langchain_core","output_parsers","bytes"];lc_serializable=!0;textEncoder=new TextEncoder;parse(t){return Promise.resolve(this.textEncoder.encode(t))}getFormatInstructions(){return""}},Q=class extends q{re;async*_transform(t){let a="";for await(const n of t)if(typeof n=="string"?a+=n:a+=n.content,this.re){const r=[...a.matchAll(this.re)];if(r.length>1){let c=0;for(const u of r.slice(0,-1))yield[u[1]],c+=(u.index??0)+u[0].length;a=a.slice(c)}}else{const r=await this.parse(a);if(r.length>1){for(const c of r.slice(0,-1))yield[c];a=r[r.length-1]}}for(const n of await this.parse(a))yield[n]}},Xa=class extends Q{static lc_name(){return"CommaSeparatedListOutputParser"}lc_namespace=["langchain_core","output_parsers","list"];lc_serializable=!0;async parse(t){try{return t.trim().split(",").map(a=>a.trim())}catch{throw new Z(`Could not parse output: ${t}`,t)}}getFormatInstructions(){return"Your response should be a list of comma separated values, eg: `foo, bar, baz`"}},Ya=class extends Q{lc_namespace=["langchain_core","output_parsers","list"];length;separator;constructor({length:t,separator:a}){super(...arguments),this.length=t,this.separator=a||","}async parse(t){try{const a=t.trim().split(this.separator).map(n=>n.trim());if(this.length!==void 0&&a.length!==this.length)throw new Z(`Incorrect number of items. Expected ${this.length}, got ${a.length}.`);return a}catch(a){throw Object.getPrototypeOf(a)===Z.prototype?a:new Z(`Could not parse output: ${t}`)}}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\`)`}},Ja=class extends Q{static lc_name(){return"NumberedListOutputParser"}lc_namespace=["langchain_core","output_parsers","list"];lc_serializable=!0;getFormatInstructions(){return`Your response should be a numbered list with each item on a new line. For example:
|
|
4
|
+
|
|
5
|
+
1. foo
|
|
6
|
+
|
|
7
|
+
2. bar
|
|
8
|
+
|
|
9
|
+
3. baz`}re=/\d+\.\s([^\n]+)/g;async parse(t){return[...t.matchAll(this.re)??[]].map(a=>a[1])}},Ka=class extends Q{static lc_name(){return"NumberedListOutputParser"}lc_namespace=["langchain_core","output_parsers","list"];lc_serializable=!0;getFormatInstructions(){return`Your response should be a numbered list with each item on a new line. For example:
|
|
10
|
+
|
|
11
|
+
1. foo
|
|
12
|
+
|
|
13
|
+
2. bar
|
|
14
|
+
|
|
15
|
+
3. baz`}re=/^\s*[-*]\s([^\n]+)$/gm;async parse(t){return[...t.matchAll(this.re)??[]].map(a=>a[1])}},qa=class extends q{static lc_name(){return"StrOutputParser"}lc_namespace=["langchain_core","output_parsers","string"];lc_serializable=!0;parse(t){return Promise.resolve(t)}getFormatInstructions(){return""}_textContentToString(t){return t.text}_imageUrlContentToString(t){throw new Error('Cannot coerce a multimodal "image_url" message part into a string.')}_messageContentToString(t){switch(t.type){case"text":case"text_delta":if("text"in t)return this._textContentToString(t);break;case"image_url":if("image_url"in t)return this._imageUrlContentToString(t);break;default:throw new Error(`Cannot coerce "${t.type}" message part into a string.`)}throw new Error(`Invalid content type: ${t.type}`)}_baseMessageContentToString(t){return t.reduce((a,n)=>a+this._messageContentToString(n),"")}},_e=class extends mt{static lc_name(){return"StructuredOutputParser"}lc_namespace=["langchain","output_parsers","structured"];toJSON(){return this.toJSONNotImplemented()}constructor(t){super(t),this.schema=t}static fromZodSchema(t){return new this(t)}static fromNamesAndDescriptions(t){const a=Kt(Object.fromEntries(Object.entries(t).map(([n,r])=>[n,qt().describe(r)])));return new this(a)}getFormatInstructions(){return`You must format your output as a JSON value that adheres to a given "JSON Schema" instance.
|
|
16
|
+
|
|
17
|
+
"JSON Schema" is a declarative language that allows you to annotate and validate JSON documents.
|
|
18
|
+
|
|
19
|
+
For example, the example "JSON Schema" instance {{"properties": {{"foo": {{"description": "a list of test words", "type": "array", "items": {{"type": "string"}}}}}}, "required": ["foo"]}}
|
|
20
|
+
would match an object with one required property, "foo". The "type" property specifies "foo" must be an "array", and the "description" property semantically describes it as "a list of test words". The items within "foo" must be strings.
|
|
21
|
+
Thus, the object {{"foo": ["bar", "baz"]}} is a well-formatted instance of this example "JSON Schema". The object {{"properties": {{"foo": ["bar", "baz"]}}}} is not well-formatted.
|
|
22
|
+
|
|
23
|
+
Your output will be parsed and type-checked according to the provided schema instance, so make sure all fields in your output match the schema exactly and there are no trailing commas!
|
|
24
|
+
|
|
25
|
+
Here is the JSON Schema instance your output must adhere to. Include the enclosing markdown codeblock:
|
|
26
|
+
\`\`\`json
|
|
27
|
+
${JSON.stringify(ut(this.schema))}
|
|
28
|
+
\`\`\`
|
|
29
|
+
`}async parse(t){try{const a=t.trim(),r=(a.match(/^```(?:json)?\s*([\s\S]*?)```/)?.[1]||a.match(/```json\s*([\s\S]*?)```/)?.[1]||a).replace(/"([^"\\]*(\\.[^"\\]*)*)"/g,(c,u)=>`"${u.replace(/\n/g,"\\n")}"`).replace(/\n/g,"");return await Gt(this.schema,JSON.parse(r))}catch(a){throw new Z(`Failed to parse. Text: "${t}". Error: ${a}`,t)}}},ye=class extends _e{static lc_name(){return"JsonMarkdownStructuredOutputParser"}getFormatInstructions(t){const a=t?.interpolationDepth??1;if(a<1)throw new Error("f string interpolation depth must be at least 1");return`Return a markdown code snippet with a JSON object formatted to look like:
|
|
30
|
+
\`\`\`json
|
|
31
|
+
${this._schemaToInstruction(ut(this.schema)).replaceAll("{","{".repeat(a)).replaceAll("}","}".repeat(a))}
|
|
32
|
+
\`\`\``}_schemaToInstruction(t,a=2){const n=t;if("type"in n){let r=!1,c;if(Array.isArray(n.type)){const l=n.type.findIndex(g=>g==="null");l!==-1&&(r=!0,n.type.splice(l,1)),c=n.type.join(" | ")}else c=n.type;if(n.type==="object"&&n.properties){const l=n.description?` // ${n.description}`:"";return`{
|
|
33
|
+
${Object.entries(n.properties).map(([f,T])=>{const _=n.required?.includes(f)?"":" (optional)";return`${" ".repeat(a)}"${f}": ${this._schemaToInstruction(T,a+2)}${_}`}).join(`
|
|
34
|
+
`)}
|
|
35
|
+
${" ".repeat(a-2)}}${l}`}if(n.type==="array"&&n.items){const l=n.description?` // ${n.description}`:"";return`array[
|
|
36
|
+
${" ".repeat(a)}${this._schemaToInstruction(n.items,a+2)}
|
|
37
|
+
${" ".repeat(a-2)}] ${l}`}const u=r?" (nullable)":"",m=n.description?` // ${n.description}`:"";return`${c}${m}${u}`}if("anyOf"in n)return n.anyOf.map(r=>this._schemaToInstruction(r,a)).join(`
|
|
38
|
+
${" ".repeat(a-2)}`);throw new Error("unsupported schema type")}static fromZodSchema(t){return new this(t)}static fromNamesAndDescriptions(t){const a=Kt(Object.fromEntries(Object.entries(t).map(([n,r])=>[n,qt().describe(r)])));return new this(a)}},Qa=class extends mt{structuredInputParser;constructor({inputSchema:t}){super(...arguments),this.structuredInputParser=new ye(t)}async parse(t){let a;try{a=await this.structuredInputParser.parse(t)}catch(n){throw new Z(`Failed to parse. Text: "${t}". Error: ${n}`,t)}return this.outputProcessor(a)}getFormatInstructions(){return this.structuredInputParser.getFormatInstructions()}},ts={};U(ts,{applyPatch:()=>ba,compare:()=>St});var es=class extends Nt{static lc_name(){return"JsonOutputParser"}lc_namespace=["langchain_core","output_parsers"];lc_serializable=!0;_concatOutputChunks(t,a){return this.diff?super._concatOutputChunks(t,a):a}_diff(t,a){if(a)return t?St(t,a):[{op:"replace",path:"",value:a}]}async parsePartialResult(t){return Tt(t[0].text)}async parse(t){return Tt(t,JSON.parse)}getFormatInstructions(){return""}};const as=function(){const t={};t.parser=function(s,e){return new n(s,e)},t.SAXParser=n,t.SAXStream=f,t.createStream=g,t.MAX_BUFFER_LENGTH=64*1024;const a=["comment","sgmlDecl","textNode","tagName","doctype","procInstName","procInstBody","entity","attribName","attribValue","cdata","script"];t.EVENTS=["text","processinginstruction","sgmldeclaration","doctype","comment","opentagstart","attribute","opentag","closetag","opencdata","cdata","closecdata","error","end","ready","script","opennamespace","closenamespace"];function n(s,e){if(!(this instanceof n))return new n(s,e);var h=this;c(h),h.q=h.c="",h.bufferCheckPosition=t.MAX_BUFFER_LENGTH,h.opt=e||{},h.opt.lowercase=h.opt.lowercase||h.opt.lowercasetags,h.looseCase=h.opt.lowercase?"toLowerCase":"toUpperCase",h.tags=[],h.closed=h.closedRoot=h.sawRoot=!1,h.tag=h.error=null,h.strict=!!s,h.noscript=!!(s||h.opt.noscript),h.state=o.BEGIN,h.strictEntities=h.opt.strictEntities,h.ENTITIES=h.strictEntities?Object.create(t.XML_ENTITIES):Object.create(t.ENTITIES),h.attribList=[],h.opt.xmlns&&(h.ns=Object.create(y)),h.trackPosition=h.opt.position!==!1,h.trackPosition&&(h.position=h.line=h.column=0),J(h,"onready")}Object.create||(Object.create=function(s){function e(){}e.prototype=s;var h=new e;return h}),Object.keys||(Object.keys=function(s){var e=[];for(var h in s)s.hasOwnProperty(h)&&e.push(h);return e});function r(s){for(var e=Math.max(t.MAX_BUFFER_LENGTH,10),h=0,i=0,C=a.length;i<C;i++){var N=s[a[i]].length;if(N>e)switch(a[i]){case"textNode":K(s);break;case"cdata":A(s,"oncdata",s.cdata),s.cdata="";break;case"script":A(s,"onscript",s.script),s.script="";break;default:tt(s,"Max buffer length exceeded: "+a[i])}h=Math.max(h,N)}var O=t.MAX_BUFFER_LENGTH-h;s.bufferCheckPosition=O+s.position}function c(s){for(var e=0,h=a.length;e<h;e++)s[a[e]]=""}function u(s){K(s),s.cdata!==""&&(A(s,"oncdata",s.cdata),s.cdata=""),s.script!==""&&(A(s,"onscript",s.script),s.script="")}n.prototype={end:function(){kt(this)},write:we,resume:function(){return this.error=null,this},close:function(){return this.write(null)},flush:function(){u(this)}};var m=ReadableStream;m||(m=function(){});var l=t.EVENTS.filter(function(s){return s!=="error"&&s!=="end"});function g(s,e){return new f(s,e)}function f(s,e){if(!(this instanceof f))return new f(s,e);m.apply(this),this._parser=new n(s,e),this.writable=!0,this.readable=!0;var h=this;this._parser.onend=function(){h.emit("end")},this._parser.onerror=function(i){h.emit("error",i),h._parser.error=null},this._decoder=null,l.forEach(function(i){Object.defineProperty(h,"on"+i,{get:function(){return h._parser["on"+i]},set:function(C){if(!C)return h.removeAllListeners(i),h._parser["on"+i]=C,C;h.on(i,C)},enumerable:!0,configurable:!1})})}f.prototype=Object.create(m.prototype,{constructor:{value:f}}),f.prototype.write=function(s){return this._parser.write(s.toString()),this.emit("data",s),!0},f.prototype.end=function(s){return s&&s.length&&this.write(s),this._parser.end(),!0},f.prototype.on=function(s,e){var h=this;return!h._parser["on"+s]&&l.indexOf(s)!==-1&&(h._parser["on"+s]=function(){var i=arguments.length===1?[arguments[0]]:Array.apply(null,arguments);i.splice(0,0,s),h.emit.apply(h,i)}),m.prototype.on.call(h,s,e)};var T="[CDATA[",_="DOCTYPE",E="http://www.w3.org/XML/1998/namespace",d="http://www.w3.org/2000/xmlns/",y={xml:E,xmlns:d},b=/[:_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-]/,w=/[#:_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]/,M=/[#:_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 S(s){return s===" "||s===`
|
|
39
|
+
`||s==="\r"||s===" "}function R(s){return s==='"'||s==="'"}function D(s){return s===">"||S(s)}function j(s,e){return s.test(e)}function Ee(s,e){return!j(s,e)}var o=0;t.STATE={BEGIN:o++,BEGIN_WHITESPACE:o++,TEXT:o++,TEXT_ENTITY:o++,OPEN_WAKA:o++,SGML_DECL:o++,SGML_DECL_QUOTED:o++,DOCTYPE:o++,DOCTYPE_QUOTED:o++,DOCTYPE_DTD:o++,DOCTYPE_DTD_QUOTED:o++,COMMENT_STARTING:o++,COMMENT:o++,COMMENT_ENDING:o++,COMMENT_ENDED:o++,CDATA:o++,CDATA_ENDING:o++,CDATA_ENDING_2:o++,PROC_INST:o++,PROC_INST_BODY:o++,PROC_INST_ENDING:o++,OPEN_TAG:o++,OPEN_TAG_SLASH:o++,ATTRIB:o++,ATTRIB_NAME:o++,ATTRIB_NAME_SAW_WHITE:o++,ATTRIB_VALUE:o++,ATTRIB_VALUE_QUOTED:o++,ATTRIB_VALUE_CLOSED:o++,ATTRIB_VALUE_UNQUOTED:o++,ATTRIB_VALUE_ENTITY_Q:o++,ATTRIB_VALUE_ENTITY_U:o++,CLOSE_TAG:o++,CLOSE_TAG_SAW_WHITE:o++,SCRIPT:o++,SCRIPT_ENDING:o++},t.XML_ENTITIES={amp:"&",gt:">",lt:"<",quot:'"',apos:"'"},t.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(t.ENTITIES).forEach(function(s){var e=t.ENTITIES[s],h=typeof e=="number"?String.fromCharCode(e):e;t.ENTITIES[s]=h});for(var Ot in t.STATE)t.STATE[t.STATE[Ot]]=Ot;o=t.STATE;function J(s,e,h){s[e]&&s[e](h)}function A(s,e,h){s.textNode&&K(s),J(s,e,h)}function K(s){s.textNode=Pt(s.opt,s.textNode),s.textNode&&J(s,"ontext",s.textNode),s.textNode=""}function Pt(s,e){return s.trim&&(e=e.trim()),s.normalize&&(e=e.replace(/\s+/g," ")),e}function tt(s,e){return K(s),s.trackPosition&&(e+=`
|
|
40
|
+
Line: `+s.line+`
|
|
41
|
+
Column: `+s.column+`
|
|
42
|
+
Char: `+s.c),e=new Error(e),s.error=e,J(s,"onerror",e),s}function kt(s){return s.sawRoot&&!s.closedRoot&&I(s,"Unclosed root tag"),s.state!==o.BEGIN&&s.state!==o.BEGIN_WHITESPACE&&s.state!==o.TEXT&&tt(s,"Unexpected end"),K(s),s.c="",s.closed=!0,J(s,"onend"),n.call(s,s.strict,s.opt),s}function I(s,e){if(typeof s!="object"||!(s instanceof n))throw new Error("bad call to strictFail");s.strict&&tt(s,e)}function ve(s){s.strict||(s.tagName=s.tagName[s.looseCase]());var e=s.tags[s.tags.length-1]||s,h=s.tag={name:s.tagName,attributes:{}};s.opt.xmlns&&(h.ns=e.ns),s.attribList.length=0,A(s,"onopentagstart",h)}function ft(s,e){var h=s.indexOf(":"),i=h<0?["",s]:s.split(":"),C=i[0],N=i[1];return e&&s==="xmlns"&&(C="xmlns",N=""),{prefix:C,local:N}}function pt(s){if(s.strict||(s.attribName=s.attribName[s.looseCase]()),s.attribList.indexOf(s.attribName)!==-1||s.tag.attributes.hasOwnProperty(s.attribName)){s.attribName=s.attribValue="";return}if(s.opt.xmlns){var e=ft(s.attribName,!0),h=e.prefix,i=e.local;if(h==="xmlns")if(i==="xml"&&s.attribValue!==E)I(s,"xml: prefix must be bound to "+E+`
|
|
43
|
+
Actual: `+s.attribValue);else if(i==="xmlns"&&s.attribValue!==d)I(s,"xmlns: prefix must be bound to "+d+`
|
|
44
|
+
Actual: `+s.attribValue);else{var C=s.tag,N=s.tags[s.tags.length-1]||s;C.ns===N.ns&&(C.ns=Object.create(N.ns)),C.ns[i]=s.attribValue}s.attribList.push([s.attribName,s.attribValue])}else s.tag.attributes[s.attribName]=s.attribValue,A(s,"onattribute",{name:s.attribName,value:s.attribValue});s.attribName=s.attribValue=""}function G(s,e){if(s.opt.xmlns){var h=s.tag,i=ft(s.tagName);h.prefix=i.prefix,h.local=i.local,h.uri=h.ns[i.prefix]||"",h.prefix&&!h.uri&&(I(s,"Unbound namespace prefix: "+JSON.stringify(s.tagName)),h.uri=i.prefix);var C=s.tags[s.tags.length-1]||s;h.ns&&C.ns!==h.ns&&Object.keys(h.ns).forEach(function(Dt){A(s,"onopennamespace",{prefix:Dt,uri:h.ns[Dt]})});for(var N=0,O=s.attribList.length;N<O;N++){var x=s.attribList[N],L=x[0],W=x[1],k=ft(L,!0),V=k.prefix,Ce=k.local,Lt=V===""?"":h.ns[V]||"",dt={name:L,value:W,prefix:V,local:Ce,uri:Lt};V&&V!=="xmlns"&&!Lt&&(I(s,"Unbound namespace prefix: "+JSON.stringify(V)),dt.uri=V),s.tag.attributes[L]=dt,A(s,"onattribute",dt)}s.attribList.length=0}s.tag.isSelfClosing=!!e,s.sawRoot=!0,s.tags.push(s.tag),A(s,"onopentag",s.tag),e||(!s.noscript&&s.tagName.toLowerCase()==="script"?s.state=o.SCRIPT:s.state=o.TEXT,s.tag=null,s.tagName=""),s.attribName=s.attribValue="",s.attribList.length=0}function gt(s){if(!s.tagName){I(s,"Weird empty close tag."),s.textNode+="</>",s.state=o.TEXT;return}if(s.script){if(s.tagName!=="script"){s.script+="</"+s.tagName+">",s.tagName="",s.state=o.SCRIPT;return}A(s,"onscript",s.script),s.script=""}var e=s.tags.length,h=s.tagName;s.strict||(h=h[s.looseCase]());for(var i=h;e--;){var C=s.tags[e];if(C.name!==i)I(s,"Unexpected close tag");else break}if(e<0){I(s,"Unmatched closing tag: "+s.tagName),s.textNode+="</"+s.tagName+">",s.state=o.TEXT;return}s.tagName=h;for(var N=s.tags.length;N-- >e;){var O=s.tag=s.tags.pop();s.tagName=s.tag.name,A(s,"onclosetag",s.tagName);var x={};for(var L in O.ns)x[L]=O.ns[L];var W=s.tags[s.tags.length-1]||s;s.opt.xmlns&&O.ns!==W.ns&&Object.keys(O.ns).forEach(function(k){var V=O.ns[k];A(s,"onclosenamespace",{prefix:k,uri:V})})}e===0&&(s.closedRoot=!0),s.tagName=s.attribValue=s.attribName="",s.attribList.length=0,s.state=o.TEXT}function Mt(s){var e=s.entity,h=e.toLowerCase(),i,C="";return s.ENTITIES[e]?s.ENTITIES[e]:s.ENTITIES[h]?s.ENTITIES[h]:(e=h,e.charAt(0)==="#"&&(e.charAt(1)==="x"?(e=e.slice(2),i=parseInt(e,16),C=i.toString(16)):(e=e.slice(1),i=parseInt(e,10),C=i.toString(10))),e=e.replace(/^0+/,""),isNaN(i)||C.toLowerCase()!==e?(I(s,"Invalid character entity"),"&"+s.entity+";"):String.fromCodePoint(i))}function xt(s,e){e==="<"?(s.state=o.OPEN_WAKA,s.startTagPosition=s.position):S(e)||(I(s,"Non-whitespace before first tag."),s.textNode=e,s.state=o.TEXT)}function Rt(s,e){var h="";return e<s.length&&(h=s.charAt(e)),h}function we(s){var e=this;if(this.error)throw this.error;if(e.closed)return tt(e,"Cannot write after close. Assign an onready handler.");if(s===null)return kt(e);typeof s=="object"&&(s=s.toString());for(var h=0,i="";i=Rt(s,h++),e.c=i,!!i;)switch(e.trackPosition&&(e.position++,i===`
|
|
45
|
+
`?(e.line++,e.column=0):e.column++),e.state){case o.BEGIN:if(e.state=o.BEGIN_WHITESPACE,i==="\uFEFF")continue;xt(e,i);continue;case o.BEGIN_WHITESPACE:xt(e,i);continue;case o.TEXT:if(e.sawRoot&&!e.closedRoot){for(var C=h-1;i&&i!=="<"&&i!=="&";)i=Rt(s,h++),i&&e.trackPosition&&(e.position++,i===`
|
|
46
|
+
`?(e.line++,e.column=0):e.column++);e.textNode+=s.substring(C,h-1)}i==="<"&&!(e.sawRoot&&e.closedRoot&&!e.strict)?(e.state=o.OPEN_WAKA,e.startTagPosition=e.position):(!S(i)&&(!e.sawRoot||e.closedRoot)&&I(e,"Text data outside of root node."),i==="&"?e.state=o.TEXT_ENTITY:e.textNode+=i);continue;case o.SCRIPT:i==="<"?e.state=o.SCRIPT_ENDING:e.script+=i;continue;case o.SCRIPT_ENDING:i==="/"?e.state=o.CLOSE_TAG:(e.script+="<"+i,e.state=o.SCRIPT);continue;case o.OPEN_WAKA:if(i==="!")e.state=o.SGML_DECL,e.sgmlDecl="";else if(!S(i))if(j(b,i))e.state=o.OPEN_TAG,e.tagName=i;else if(i==="/")e.state=o.CLOSE_TAG,e.tagName="";else if(i==="?")e.state=o.PROC_INST,e.procInstName=e.procInstBody="";else{if(I(e,"Unencoded <"),e.startTagPosition+1<e.position){var N=e.position-e.startTagPosition;i=new Array(N).join(" ")+i}e.textNode+="<"+i,e.state=o.TEXT}continue;case o.SGML_DECL:(e.sgmlDecl+i).toUpperCase()===T?(A(e,"onopencdata"),e.state=o.CDATA,e.sgmlDecl="",e.cdata=""):e.sgmlDecl+i==="--"?(e.state=o.COMMENT,e.comment="",e.sgmlDecl=""):(e.sgmlDecl+i).toUpperCase()===_?(e.state=o.DOCTYPE,(e.doctype||e.sawRoot)&&I(e,"Inappropriately located doctype declaration"),e.doctype="",e.sgmlDecl=""):i===">"?(A(e,"onsgmldeclaration",e.sgmlDecl),e.sgmlDecl="",e.state=o.TEXT):(R(i)&&(e.state=o.SGML_DECL_QUOTED),e.sgmlDecl+=i);continue;case o.SGML_DECL_QUOTED:i===e.q&&(e.state=o.SGML_DECL,e.q=""),e.sgmlDecl+=i;continue;case o.DOCTYPE:i===">"?(e.state=o.TEXT,A(e,"ondoctype",e.doctype),e.doctype=!0):(e.doctype+=i,i==="["?e.state=o.DOCTYPE_DTD:R(i)&&(e.state=o.DOCTYPE_QUOTED,e.q=i));continue;case o.DOCTYPE_QUOTED:e.doctype+=i,i===e.q&&(e.q="",e.state=o.DOCTYPE);continue;case o.DOCTYPE_DTD:e.doctype+=i,i==="]"?e.state=o.DOCTYPE:R(i)&&(e.state=o.DOCTYPE_DTD_QUOTED,e.q=i);continue;case o.DOCTYPE_DTD_QUOTED:e.doctype+=i,i===e.q&&(e.state=o.DOCTYPE_DTD,e.q="");continue;case o.COMMENT:i==="-"?e.state=o.COMMENT_ENDING:e.comment+=i;continue;case o.COMMENT_ENDING:i==="-"?(e.state=o.COMMENT_ENDED,e.comment=Pt(e.opt,e.comment),e.comment&&A(e,"oncomment",e.comment),e.comment=""):(e.comment+="-"+i,e.state=o.COMMENT);continue;case o.COMMENT_ENDED:i!==">"?(I(e,"Malformed comment"),e.comment+="--"+i,e.state=o.COMMENT):e.state=o.TEXT;continue;case o.CDATA:i==="]"?e.state=o.CDATA_ENDING:e.cdata+=i;continue;case o.CDATA_ENDING:i==="]"?e.state=o.CDATA_ENDING_2:(e.cdata+="]"+i,e.state=o.CDATA);continue;case o.CDATA_ENDING_2:i===">"?(e.cdata&&A(e,"oncdata",e.cdata),A(e,"onclosecdata"),e.cdata="",e.state=o.TEXT):i==="]"?e.cdata+="]":(e.cdata+="]]"+i,e.state=o.CDATA);continue;case o.PROC_INST:i==="?"?e.state=o.PROC_INST_ENDING:S(i)?e.state=o.PROC_INST_BODY:e.procInstName+=i;continue;case o.PROC_INST_BODY:if(!e.procInstBody&&S(i))continue;i==="?"?e.state=o.PROC_INST_ENDING:e.procInstBody+=i;continue;case o.PROC_INST_ENDING:i===">"?(A(e,"onprocessinginstruction",{name:e.procInstName,body:e.procInstBody}),e.procInstName=e.procInstBody="",e.state=o.TEXT):(e.procInstBody+="?"+i,e.state=o.PROC_INST_BODY);continue;case o.OPEN_TAG:j(v,i)?e.tagName+=i:(ve(e),i===">"?G(e):i==="/"?e.state=o.OPEN_TAG_SLASH:(S(i)||I(e,"Invalid character in tag name"),e.state=o.ATTRIB));continue;case o.OPEN_TAG_SLASH:i===">"?(G(e,!0),gt(e)):(I(e,"Forward-slash in opening tag not followed by >"),e.state=o.ATTRIB);continue;case o.ATTRIB:if(S(i))continue;i===">"?G(e):i==="/"?e.state=o.OPEN_TAG_SLASH:j(b,i)?(e.attribName=i,e.attribValue="",e.state=o.ATTRIB_NAME):I(e,"Invalid attribute name");continue;case o.ATTRIB_NAME:i==="="?e.state=o.ATTRIB_VALUE:i===">"?(I(e,"Attribute without value"),e.attribValue=e.attribName,pt(e),G(e)):S(i)?e.state=o.ATTRIB_NAME_SAW_WHITE:j(v,i)?e.attribName+=i:I(e,"Invalid attribute name");continue;case o.ATTRIB_NAME_SAW_WHITE:if(i==="=")e.state=o.ATTRIB_VALUE;else{if(S(i))continue;I(e,"Attribute without value"),e.tag.attributes[e.attribName]="",e.attribValue="",A(e,"onattribute",{name:e.attribName,value:""}),e.attribName="",i===">"?G(e):j(b,i)?(e.attribName=i,e.state=o.ATTRIB_NAME):(I(e,"Invalid attribute name"),e.state=o.ATTRIB)}continue;case o.ATTRIB_VALUE:if(S(i))continue;R(i)?(e.q=i,e.state=o.ATTRIB_VALUE_QUOTED):(I(e,"Unquoted attribute value"),e.state=o.ATTRIB_VALUE_UNQUOTED,e.attribValue=i);continue;case o.ATTRIB_VALUE_QUOTED:if(i!==e.q){i==="&"?e.state=o.ATTRIB_VALUE_ENTITY_Q:e.attribValue+=i;continue}pt(e),e.q="",e.state=o.ATTRIB_VALUE_CLOSED;continue;case o.ATTRIB_VALUE_CLOSED:S(i)?e.state=o.ATTRIB:i===">"?G(e):i==="/"?e.state=o.OPEN_TAG_SLASH:j(b,i)?(I(e,"No whitespace between attributes"),e.attribName=i,e.attribValue="",e.state=o.ATTRIB_NAME):I(e,"Invalid attribute name");continue;case o.ATTRIB_VALUE_UNQUOTED:if(!D(i)){i==="&"?e.state=o.ATTRIB_VALUE_ENTITY_U:e.attribValue+=i;continue}pt(e),i===">"?G(e):e.state=o.ATTRIB;continue;case o.CLOSE_TAG:if(e.tagName)i===">"?gt(e):j(v,i)?e.tagName+=i:e.script?(e.script+="</"+e.tagName,e.tagName="",e.state=o.SCRIPT):(S(i)||I(e,"Invalid tagname in closing tag"),e.state=o.CLOSE_TAG_SAW_WHITE);else{if(S(i))continue;Ee(b,i)?e.script?(e.script+="</"+i,e.state=o.SCRIPT):I(e,"Invalid tagname in closing tag."):e.tagName=i}continue;case o.CLOSE_TAG_SAW_WHITE:if(S(i))continue;i===">"?gt(e):I(e,"Invalid characters in closing tag");continue;case o.TEXT_ENTITY:case o.ATTRIB_VALUE_ENTITY_Q:case o.ATTRIB_VALUE_ENTITY_U:var O,x;switch(e.state){case o.TEXT_ENTITY:O=o.TEXT,x="textNode";break;case o.ATTRIB_VALUE_ENTITY_Q:O=o.ATTRIB_VALUE_QUOTED,x="attribValue";break;case o.ATTRIB_VALUE_ENTITY_U:O=o.ATTRIB_VALUE_UNQUOTED,x="attribValue";break}if(i===";")if(e.opt.unparsedEntities){var L=Mt(e);e.entity="",e.state=O,e.write(L)}else e[x]+=Mt(e),e.entity="",e.state=O;else j(e.entity.length?M:w,i)?e.entity+=i:(I(e,"Invalid character in entity name"),e[x]+="&"+e.entity+i,e.entity="",e.state=O);continue;default:throw new Error(e,"Unknown state: "+e.state)}return e.position>=e.bufferCheckPosition&&r(e),e}/*! http://mths.be/fromcodepoint v0.1.0 by @mathias */return String.fromCodePoint||(function(){var s=String.fromCharCode,e=Math.floor,h=function(){var i=16384,C=[],N,O,x=-1,L=arguments.length;if(!L)return"";for(var W="";++x<L;){var k=Number(arguments[x]);if(!isFinite(k)||k<0||k>1114111||e(k)!==k)throw RangeError("Invalid code point: "+k);k<=65535?C.push(k):(k-=65536,N=(k>>10)+55296,O=k%1024+56320,C.push(N,O)),(x+1===L||C.length>i)&&(W+=s.apply(null,C),C.length=0)}return W};Object.defineProperty?Object.defineProperty(String,"fromCodePoint",{value:h,configurable:!0,writable:!0}):String.fromCodePoint=h})(),t},ss=as(),Et=`The output should be formatted as a XML file.
|
|
47
|
+
1. Output should conform to the tags below.
|
|
48
|
+
2. If tags are not given, make them on your own.
|
|
49
|
+
3. Remember to always open and close all the tags.
|
|
50
|
+
|
|
51
|
+
As an example, for the tags ["foo", "bar", "baz"]:
|
|
52
|
+
1. String "<foo>
|
|
53
|
+
<bar>
|
|
54
|
+
<baz></baz>
|
|
55
|
+
</bar>
|
|
56
|
+
</foo>" is a well-formatted instance of the schema.
|
|
57
|
+
2. String "<foo>
|
|
58
|
+
<bar>
|
|
59
|
+
</foo>" is a badly-formatted instance.
|
|
60
|
+
3. String "<foo>
|
|
61
|
+
<tag>
|
|
62
|
+
</tag>
|
|
63
|
+
</foo>" is a badly-formatted instance.
|
|
64
|
+
|
|
65
|
+
Here are the output tags:
|
|
66
|
+
\`\`\`
|
|
67
|
+
{tags}
|
|
68
|
+
\`\`\``;var ns=class extends Nt{tags;constructor(t){super(t),this.tags=t?.tags}static lc_name(){return"XMLOutputParser"}lc_namespace=["langchain_core","output_parsers"];lc_serializable=!0;_diff(t,a){if(a)return t?St(t,a):[{op:"replace",path:"",value:a}]}async parsePartialResult(t){return vt(t[0].text)}async parse(t){return vt(t)}getFormatInstructions(){return!!(this.tags&&this.tags.length>0)?Et.replace("{tags}",this.tags?.join(", ")??""):Et}};const rs=t=>t.split(`
|
|
69
|
+
`).map(a=>a.replace(/^\s+/,"")).join(`
|
|
70
|
+
`).trim(),Te=t=>{if(Object.keys(t).length===0)return{};const a={};return t.children.length>0?(a[t.name]=t.children.map(Te),a):(a[t.name]=t.text??void 0,a)};function vt(t){const a=rs(t),n=ss.parser(!0);let r={};const c=[];n.onopentag=l=>{const g={name:l.name,attributes:l.attributes,children:[],text:"",isSelfClosing:l.isSelfClosing};c.length>0?c[c.length-1].children.push(g):r=g,l.isSelfClosing||c.push(g)},n.onclosetag=()=>{if(c.length>0){const l=c.pop();c.length===0&&l&&(r=l)}},n.ontext=l=>{if(c.length>0){const g=c[c.length-1];g.text+=l}},n.onattribute=l=>{if(c.length>0){const g=c[c.length-1];g.attributes[l.name]=l.value}};const u=/```(xml)?(.*)```/s.exec(a),m=u?u[2]:a;return n.write(m).close(),r&&r.name==="?xml"&&(r=r.children[0]),Te(r)}var is={};U(is,{AsymmetricStructuredOutputParser:()=>Qa,BaseCumulativeTransformOutputParser:()=>Nt,BaseLLMOutputParser:()=>be,BaseOutputParser:()=>mt,BaseTransformOutputParser:()=>q,BytesOutputParser:()=>Wa,CommaSeparatedListOutputParser:()=>Xa,CustomListOutputParser:()=>Ya,JsonMarkdownStructuredOutputParser:()=>ye,JsonOutputParser:()=>es,ListOutputParser:()=>Q,MarkdownListOutputParser:()=>Ka,NumberedListOutputParser:()=>Ja,OutputParserException:()=>Z,StringOutputParser:()=>qa,StructuredOutputParser:()=>_e,XMLOutputParser:()=>ns,XML_FORMAT_INSTRUCTIONS:()=>Et,parseJsonMarkdown:()=>Tt,parsePartialJson:()=>_a,parseXMLMarkdown:()=>vt});export{be as B,es as J,Z as O,ct as R,_e as S,Fa as a,de as b,Ca as c,Nt as d,ge as e,ae as f,te as g,ee as h,se as i,pe as j};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import{Langfuse as T}from"./index-B1m6hcte.js";import{B as I,a as v,A as g,b as y,H as M,C as S,S as w,F as D,T as b}from"./index-BgTUJ2nU.js";import"./langfuse-C4HKZ3NL-DxYt-pQv.js";import"./index-D2syF8VP.js";import"./chunk-VL2OQCWN-D5zTMCrV.js";import"./index-DRz5BQNA.js";import"./__vite-browser-external-DFygW7-s.js";import"./path-C9FudP8b.js";const u="langsmith:hidden";class k extends I{constructor(t){super(),this.name="CallbackHandler",this.rootProvided=!1,this.updateRoot=!1,this.debugEnabled=!1,this.completionStartTimes={},t&&"root"in t?(this.langfuse=t.root.client,this.rootObservationId=t.root.observationId??void 0,this.traceId=t.root.traceId,this.rootProvided=!0,this.updateRoot=t.updateRoot??!1,this.metadata=t.metadata):(this.langfuse=new T({...t,persistence:"memory",sdkIntegration:t?.sdkIntegration??"LANGCHAIN"}),this.sessionId=t?.sessionId,this.userId=t?.userId,this.metadata=t?.metadata,this.tags=t?.tags),this.version=t?.version,this.promptToParentRunMap=new Map,this.traceUpdates=new Map}async flushAsync(){return this.langfuse.flushAsync()}async shutdownAsync(){return this.langfuse.shutdownAsync()}debug(t=!0){this.langfuse.debug(t),this.debugEnabled=t}_log(t){this.debugEnabled&&console.log(t)}async handleNewToken(t,e){return e&&!(e in this.completionStartTimes)&&(this._log(`LLM first streaming token: ${e}`),this.completionStartTimes[e]=new Date),Promise.resolve()}async handleLLMNewToken(t,e,s,i,n,a){return s&&!(s in this.completionStartTimes)&&(this._log(`LLM first streaming token: ${s}`),this.completionStartTimes[s]=new Date),Promise.resolve()}getTraceId(){return this.traceId}getTraceUrl(){return this.traceId?`${this.langfuse.baseUrl}/trace/${this.traceId}`:void 0}getLangchainRunId(){return this.topLevelObservationId}async handleRetrieverError(t,e,s){try{this._log(`Retriever error: ${t} with ID: ${e}`),this.langfuse._updateSpan({id:e,traceId:this.traceId,level:"ERROR",statusMessage:t.toString(),endTime:new Date,version:this.version}),this.updateTrace(e,s,t.toString())}catch(i){this._log(i)}}async handleChainStart(t,e,s,i,n,a,o,h){try{this._log(`Chain start with Id: ${s}`);const d=h??t.id.at(-1)?.toString()??"Langchain Run";this.registerLangfusePrompt(i,a);let r=e;typeof e=="object"&&"input"in e&&Array.isArray(e.input)&&e.input.every(l=>l instanceof v)?r=e.input.map(l=>this.extractChatMessageContent(l)):typeof e=="object"&&"content"in e&&typeof e.content=="string"&&(r=e.content),this.generateTrace(d,s,i,n,a,r),this.langfuse.span({id:s,traceId:this.traceId,parentObservationId:i??this.rootObservationId,name:d,metadata:this.joinTagsAndMetaData(n,a),input:r,version:this.version,level:n&&n.includes(u)?"DEBUG":void 0}),i||this.traceUpdates.set(s,{tags:n,userId:a&&"langfuseUserId"in a&&typeof a.langfuseUserId=="string"?a.langfuseUserId:void 0,sessionId:a&&"langfuseSessionId"in a&&typeof a.langfuseSessionId=="string"?a.langfuseSessionId:void 0})}catch(d){this._log(d)}}registerLangfusePrompt(t,e){e&&"langfusePrompt"in e&&t&&this.promptToParentRunMap.set(t,e.langfusePrompt)}deregisterLangfusePrompt(t){this.promptToParentRunMap.delete(t)}async handleAgentAction(t,e,s){try{this._log(`Agent action with ID: ${e}`),this.langfuse.span({id:e,parentObservationId:s,traceId:this.traceId,endTime:new Date,input:t,version:this.version})}catch(i){this._log(i)}}async handleAgentEnd(t,e,s){try{this._log(`Agent finish with ID: ${e}`),this.langfuse._updateSpan({id:e,traceId:this.traceId,endTime:new Date,output:t,version:this.version}),this.updateTrace(e,s,t)}catch(i){this._log(i)}}async handleChainError(t,e,s){try{this._log(`Chain error: ${t} with ID: ${e}`);const i=this.parseAzureRefusalError(t);this.langfuse._updateSpan({id:e,traceId:this.traceId,level:"ERROR",statusMessage:t.toString()+i,endTime:new Date,version:this.version}),this.updateTrace(e,s,t.toString()+i)}catch(i){this._log(i)}}generateTrace(t,e,s,i,n,a){this.traceId&&!s&&!this.rootProvided&&(this.traceId=void 0,this.topLevelObservationId=void 0);const o={name:t,metadata:this.joinTagsAndMetaData(i,n,this.metadata),userId:this.userId,version:this.version,sessionId:this.sessionId,input:a,tags:this.tags};this.traceId||(this.langfuse.trace({id:e,...o}),this.traceId=e),this.rootProvided&&this.updateRoot&&(this.rootObservationId?this.langfuse._updateSpan({id:this.rootObservationId,traceId:this.traceId,...o}):this.langfuse.trace({id:this.traceId,...o})),this.topLevelObservationId=s?this.topLevelObservationId:e}async handleGenerationStart(t,e,s,i,n,a,o,h){this._log(`Generation start with ID: ${s}`);const d=h??t.id.at(-1)?.toString()??"Langchain Generation";this.generateTrace(d,s,i,a,o,e);const r={},l=n?.invocation_params;for(const[f,c]of Object.entries({temperature:l?.temperature,max_tokens:l?.max_tokens,top_p:l?.top_p,frequency_penalty:l?.frequency_penalty,presence_penalty:l?.presence_penalty,request_timeout:l?.request_timeout}))c!=null&&(r[f]=c);let _;if(n){const f=n.invocation_params.model,c=o&&"ls_model_name"in o?o.ls_model_name:void 0;_=f??c}const m=this.promptToParentRunMap.get(i??"root");m&&i&&this.deregisterLangfusePrompt(i),this.langfuse.generation({id:s,traceId:this.traceId,name:h??t.id.at(-1)?.toString(),metadata:this.joinTagsAndMetaData(a,o),parentObservationId:i??this.rootObservationId,input:e,model:_,modelParameters:r,version:this.version,prompt:m,level:a&&a.includes(u)?"DEBUG":void 0})}async handleChatModelStart(t,e,s,i,n,a,o,h){try{this._log(`Chat model start with ID: ${s}`);const d=e.flatMap(r=>r.map(l=>this.extractChatMessageContent(l)));this.handleGenerationStart(t,d,s,i,n,a,o,h)}catch(d){this._log(d)}}async handleChainEnd(t,e,s){try{this._log(`Chain end with ID: ${e}`);let i=t;typeof t=="object"&&"output"in t&&typeof t.output=="string"&&(i=t.output),this.langfuse._updateSpan({id:e,traceId:this.traceId,output:i,endTime:new Date,version:this.version}),this.updateTrace(e,s,i),this.deregisterLangfusePrompt(e)}catch(i){this._log(i)}}async handleLLMStart(t,e,s,i,n,a,o,h){try{this._log(`LLM start with ID: ${s}`),this.handleGenerationStart(t,e,s,i,n,a,o,h)}catch(d){this._log(d)}}async handleToolStart(t,e,s,i,n,a,o){try{this._log(`Tool start with ID: ${s}`),this.langfuse.span({id:s,parentObservationId:i,traceId:this.traceId,name:o??t.id.at(-1)?.toString(),input:e,metadata:this.joinTagsAndMetaData(n,a),version:this.version,level:n&&n.includes(u)?"DEBUG":void 0})}catch(h){this._log(h)}}async handleRetrieverStart(t,e,s,i,n,a,o){try{this._log(`Retriever start with ID: ${s}`),this.langfuse.span({id:s,parentObservationId:i,traceId:this.traceId,name:o??t.id.at(-1)?.toString(),input:e,metadata:this.joinTagsAndMetaData(n,a),version:this.version,level:n&&n.includes(u)?"DEBUG":void 0})}catch(h){this._log(h)}}async handleRetrieverEnd(t,e,s){try{this._log(`Retriever end with ID: ${e}`),this.langfuse._updateSpan({id:e,traceId:this.traceId,output:t,endTime:new Date,version:this.version}),this.updateTrace(e,s,t)}catch(i){this._log(i)}}async handleToolEnd(t,e,s){try{this._log(`Tool end with ID: ${e}`),this.langfuse._updateSpan({id:e,traceId:this.traceId,output:t,endTime:new Date,version:this.version}),this.updateTrace(e,s,t)}catch(i){this._log(i)}}async handleToolError(t,e,s){try{this._log(`Tool error ${t} with ID: ${e}`),this.langfuse._updateSpan({id:e,traceId:this.traceId,level:"ERROR",statusMessage:t.toString(),endTime:new Date,version:this.version}),this.updateTrace(e,s,t.toString())}catch(i){this._log(i)}}async handleLLMEnd(t,e,s){try{this._log(`LLM end with ID: ${e}`);const i=t.generations[t.generations.length-1][t.generations[t.generations.length-1].length-1],n=this.extractUsageMetadata(i)??t.llmOutput?.tokenUsage,a=this.extractModelNameFromMetadata(i),o={input:n?.input_tokens??("promptTokens"in n?n?.promptTokens:void 0),output:n?.output_tokens??("completionTokens"in n?n?.completionTokens:void 0),total:n?.total_tokens??("totalTokens"in n?n?.totalTokens:void 0)};if(n&&"input_token_details"in n)for(const[d,r]of Object.entries(n.input_token_details??{}))o[`input_${d}`]=r,"input"in o&&typeof r=="number"&&(o.input=Math.max(0,o.input-r));if(n&&"output_token_details"in n)for(const[d,r]of Object.entries(n.output_token_details??{}))o[`output_${d}`]=r,"output"in o&&typeof r=="number"&&(o.output=Math.max(0,o.output-r));const h="message"in i&&i.message instanceof v?this.extractChatMessageContent(i.message):i.text;this.langfuse._updateGeneration({id:e,model:a,traceId:this.traceId,output:h,endTime:new Date,completionStartTime:e in this.completionStartTimes?this.completionStartTimes[e]:void 0,usage:o,usageDetails:o,version:this.version}),e in this.completionStartTimes&&delete this.completionStartTimes[e],this.updateTrace(e,s,h)}catch(i){this._log(i)}}extractUsageMetadata(t){try{return"message"in t&&(t.message instanceof g||t.message instanceof y)?t.message.usage_metadata:void 0}catch(e){this._log(`Error extracting usage metadata: ${e}`);return}}extractModelNameFromMetadata(t){try{return"message"in t&&(t.message instanceof g||t.message instanceof y)?t.message.response_metadata.model_name:void 0}catch{}}extractChatMessageContent(t){let e;return t instanceof M?e={content:t.content,role:"user"}:t instanceof S?e={content:t.content,role:t.role}:t instanceof g?e={content:t.content,role:"assistant"}:t instanceof w?e={content:t.content,role:"system"}:t instanceof D?e={content:t.content,additional_kwargs:t.additional_kwargs,role:t.name}:t instanceof b?e={content:t.content,additional_kwargs:t.additional_kwargs,role:t.name}:t.name?e={role:t.name,content:t.content}:e={content:t.content},t.additional_kwargs.function_call||t.additional_kwargs.tool_calls?{...e,additional_kwargs:t.additional_kwargs}:e}async handleLLMError(t,e,s){try{this._log(`LLM error ${t} with ID: ${e}`);const i=this.parseAzureRefusalError(t);this.langfuse._updateGeneration({id:e,traceId:this.traceId,level:"ERROR",statusMessage:t.toString()+i,endTime:new Date,version:this.version}),this.updateTrace(e,s,t.toString()+i)}catch(i){this._log(i)}}parseAzureRefusalError(t){let e="";if(typeof t=="object"&&"error"in t)try{e=`
|
|
2
|
+
|
|
3
|
+
Error details:
|
|
4
|
+
`+JSON.stringify(t.error,null,2)}catch{}return e}updateTrace(t,e,s){const i=this.traceUpdates.get(t);this.traceUpdates.delete(t),!e&&this.traceId&&this.traceId===t&&this.langfuse.trace({id:this.traceId,output:s,...i}),!e&&this.traceId&&this.rootProvided&&this.updateRoot&&(this.rootObservationId?this.langfuse._updateSpan({id:this.rootObservationId,traceId:this.traceId,output:s}):this.langfuse.trace({id:this.traceId,output:s,...i}))}joinTagsAndMetaData(t,e,s){const i={};return t&&t.length>0&&(i.tags=t),e&&Object.assign(i,e),s&&Object.assign(i,s),this.stripLangfuseKeysFromMetadata(i)}stripLangfuseKeysFromMetadata(t){if(!t)return;const e=["langfusePrompt","langfuseUserId","langfuseSessionId"];return Object.fromEntries(Object.entries(t).filter(([s,i])=>!e.includes(s)))}}const U=async p=>{const{runName:t,item:e,langfuseClient:s,options:i}=p,n={dataset_item_id:e.id,dataset_id:e.datasetId,dataset_run_name:t},a=s.trace();return await e.link(a,t,{description:i?.runDescription,metadata:i?.runMetadata}),{handler:new k({root:a,updateRoot:!0,metadata:n}),trace:a}};export{k as CallbackHandler,T as Langfuse,U as createDatasetItemHandler,k as default};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{i as ne,
|
|
1
|
+
import{i as ne,a as oe,B as fe,O as he,b as pe,J as ge,R as D}from"./index-D8wSHXf0.js";import{i as se,t as me,d as Ce,A as ye,e as _e,b as Ee,C as ve,f as we,g as ie,h as Te,j as Ie,p as S,k as Oe,l as Re,R as Ae}from"./index-BgTUJ2nU.js";import{v as ae}from"./index-D2syF8VP.js";import"./embeddings-T3ulhIAT.js";import"./chunk-VL2OQCWN-D5zTMCrV.js";import"./index-DRz5BQNA.js";function _(e){if(typeof e=="object"&&e!==null){const n={...e};"additionalProperties"in n&&delete n.additionalProperties,"$schema"in n&&delete n.$schema,"strict"in n&&delete n.strict;for(const t in n)t in n&&(Array.isArray(n[t])?n[t]=n[t].map(_):typeof n[t]=="object"&&n[t]!==null&&(n[t]=_(n[t])));return n}return e}function N(e){const n=_(se(e)?me(e):e),{$schema:t,...o}=n;return o}function Se(e){const n=_(e),{$schema:t,...o}=n;return o}function Ne(e){const n=e._getType();return ve.isInstance(e)?e.role:n==="tool"?n:e.name??n}function be(e){switch(e){case"supervisor":case"ai":case"model":return"model";case"system":return"system";case"human":return"user";case"tool":case"function":return"function";default:throw new Error(`Unknown / unsupported author: ${e}`)}}function Me(e){if("mimeType"in e&&"data"in e)return{inlineData:{mimeType:e.mimeType,data:e.data}};if("mimeType"in e&&"fileUri"in e)return{fileData:{mimeType:e.mimeType,fileUri:e.fileUri}};throw new Error("Invalid media content")}function xe(e,n){return n.map(t=>ie(t)?t.tool_calls??[]:[]).flat().find(t=>t.id===e.tool_call_id)?.name}function De(e){return{providerName:"Google Gemini",fromStandardTextBlock(t){return{text:t.text}},fromStandardImageBlock(t){if(!e)throw new Error("This model does not support images");if(t.source_type==="url"){const o=S({dataUrl:t.url});return o?{inlineData:{mimeType:o.mime_type,data:o.data}}:{fileData:{mimeType:t.mime_type??"",fileUri:t.url}}}if(t.source_type==="base64")return{inlineData:{mimeType:t.mime_type??"",data:t.data}};throw new Error(`Unsupported source type: ${t.source_type}`)},fromStandardAudioBlock(t){if(!e)throw new Error("This model does not support audio");if(t.source_type==="url"){const o=S({dataUrl:t.url});return o?{inlineData:{mimeType:o.mime_type,data:o.data}}:{fileData:{mimeType:t.mime_type??"",fileUri:t.url}}}if(t.source_type==="base64")return{inlineData:{mimeType:t.mime_type??"",data:t.data}};throw new Error(`Unsupported source type: ${t.source_type}`)},fromStandardFileBlock(t){if(!e)throw new Error("This model does not support files");if(t.source_type==="text")return{text:t.text};if(t.source_type==="url"){const o=S({dataUrl:t.url});return o?{inlineData:{mimeType:o.mime_type,data:o.data}}:{fileData:{mimeType:t.mime_type??"",fileUri:t.url}}}if(t.source_type==="base64")return{inlineData:{mimeType:t.mime_type??"",data:t.data}};throw new Error(`Unsupported source type: ${t.source_type}`)}}}function G(e,n){if(Te(e))return Ie(e,De(n));if(e.type==="text")return{text:e.text};if(e.type==="executableCode")return{executableCode:e.executableCode};if(e.type==="codeExecutionResult")return{codeExecutionResult:e.codeExecutionResult};if(e.type==="image_url"){if(!n)throw new Error("This model does not support images");let t;if(typeof e.image_url=="string")t=e.image_url;else if(typeof e.image_url=="object"&&"url"in e.image_url)t=e.image_url.url;else throw new Error("Please provide image as base64 encoded data URL");const[o,s]=t.split(",");if(!o.startsWith("data:"))throw new Error("Please provide image as base64 encoded data URL");const[i,a]=o.replace(/^data:/,"").split(";");if(a!=="base64")throw new Error("Please provide image as base64 encoded data URL");return{inlineData:{data:s,mimeType:i}}}else{if(e.type==="media")return Me(e);if(e.type==="tool_use")return{functionCall:{name:e.name,args:e.input}};if(e.type?.includes("/")&&e.type.split("/").length===2&&"data"in e&&typeof e.data=="string")return{inlineData:{mimeType:e.type,data:e.data}};if("functionCall"in e)return;throw"type"in e?new Error(`Unknown content type ${e.type}`):new Error(`Unknown content ${JSON.stringify(e)}`)}}function Ge(e,n,t){if(we(e)){const i=e.name??xe(e,t);if(i===void 0)throw new Error(`Google requires a tool name for each tool call response, and we could not infer a called tool name for ToolMessage "${e.id}" from your passed messages. Please populate a "name" field on that ToolMessage explicitly.`);const a=Array.isArray(e.content)?e.content.map(c=>G(c,n)).filter(c=>c!==void 0):e.content;return e.status==="error"?[{functionResponse:{name:i,response:{error:{details:a}}}}]:[{functionResponse:{name:i,response:{result:a}}}]}let o=[];const s=[];return typeof e.content=="string"&&e.content&&s.push({text:e.content}),Array.isArray(e.content)&&s.push(...e.content.map(i=>G(i,n)).filter(i=>i!==void 0)),ie(e)&&e.tool_calls?.length&&(o=e.tool_calls.map(i=>({functionCall:{name:i.name,args:i.args}}))),[...s,...o]}function k(e,n,t=!1){return e.reduce((o,s,i)=>{if(!Ce(s))throw new Error("Unsupported message input");const a=Ne(s);if(a==="system"&&i!==0)throw new Error("System message should be the first one");const c=be(a),u=o.content[o.content.length];if(!o.mergeWithPreviousContent&&u&&u.role===c)throw new Error("Google Generative AI requires alternate messages between authors");const r=Ge(s,n,e.slice(0,i));if(o.mergeWithPreviousContent){const d=o.content[o.content.length-1];if(!d)throw new Error("There was a problem parsing your system message. Please try a prompt without one.");return d.parts.push(...r),{mergeWithPreviousContent:!1,content:o.content}}let p=c;(p==="function"||p==="system"&&!t)&&(p="user");const f={role:p,parts:r};return{mergeWithPreviousContent:a==="system"&&!t,content:[...o.content,f]}},{content:[],mergeWithPreviousContent:!1}).content}function ke(e,n){if(!e.candidates||e.candidates.length===0||!e.candidates[0])return{generations:[],llmOutput:{filters:e.promptFeedback}};const t=e.functionCalls(),[o]=e.candidates,{content:s,...i}=o;let a;Array.isArray(s?.parts)&&s.parts.length===1&&s.parts[0].text?a=s.parts[0].text:Array.isArray(s?.parts)&&s.parts.length>0?a=s.parts.map(r=>"text"in r?{type:"text",text:r.text}:"inlineData"in r?{type:"inlineData",inlineData:r.inlineData}:"functionCall"in r?{type:"functionCall",functionCall:r.functionCall}:"functionResponse"in r?{type:"functionResponse",functionResponse:r.functionResponse}:"fileData"in r?{type:"fileData",fileData:r.fileData}:"executableCode"in r?{type:"executableCode",executableCode:r.executableCode}:"codeExecutionResult"in r?{type:"codeExecutionResult",codeExecutionResult:r.codeExecutionResult}:r):a=[];let c="";return typeof a=="string"?c=a:Array.isArray(a)&&a.length>0&&(c=a.find(p=>"text"in p)?.text??c),{generations:[{text:c,message:new ye({content:a??"",tool_calls:t?.map(r=>({...r,type:"tool_call",id:"id"in r&&typeof r.id=="string"?r.id:ae()})),additional_kwargs:{...i},usage_metadata:n?.usageMetadata}),generationInfo:i}],llmOutput:{tokenUsage:{promptTokens:n?.usageMetadata?.input_tokens,completionTokens:n?.usageMetadata?.output_tokens,totalTokens:n?.usageMetadata?.total_tokens}}}}function Ue(e,n){if(!e.candidates||e.candidates.length===0)return null;const t=e.functionCalls(),[o]=e.candidates,{content:s,...i}=o;let a;Array.isArray(s?.parts)&&s.parts.every(r=>"text"in r)?a=s.parts.map(r=>r.text).join(""):Array.isArray(s?.parts)?a=s.parts.map(r=>"text"in r?{type:"text",text:r.text}:"inlineData"in r?{type:"inlineData",inlineData:r.inlineData}:"functionCall"in r?{type:"functionCall",functionCall:r.functionCall}:"functionResponse"in r?{type:"functionResponse",functionResponse:r.functionResponse}:"fileData"in r?{type:"fileData",fileData:r.fileData}:"executableCode"in r?{type:"executableCode",executableCode:r.executableCode}:"codeExecutionResult"in r?{type:"codeExecutionResult",codeExecutionResult:r.codeExecutionResult}:r):a=[];let c="";a&&typeof a=="string"?c=a:Array.isArray(a)&&(c=a.find(p=>"text"in p)?.text??"");const u=[];return t&&u.push(...t.map(r=>({...r,args:JSON.stringify(r.args),index:n.index,type:"tool_call_chunk",id:"id"in r&&typeof r.id=="string"?r.id:ae()}))),new _e({text:c,message:new Ee({content:a||"",name:s?s.role:void 0,tool_call_chunks:u,additional_kwargs:{},response_metadata:{model_provider:"google-genai"},usage_metadata:n.usageMetadata}),generationInfo:i})}function Le(e){return e.every(n=>"functionDeclarations"in n&&Array.isArray(n.functionDeclarations))?e:[{functionDeclarations:e.map(n=>{if(ne(n)){const t=N(n.schema);return t.type==="object"&&"properties"in t&&Object.keys(t.properties).length===0?{name:n.name,description:n.description}:{name:n.name,description:n.description,parameters:t}}return oe(n)?{name:n.function.name,description:n.function.description??"A function available to call.",parameters:Se(n.function.parameters)}:n})}]}var U=class extends fe{static lc_name(){return"GoogleGenerativeAIToolsOutputParser"}lc_namespace=["langchain","google_genai","output_parsers"];returnId=!1;keyName;returnSingle=!1;zodSchema;constructor(e){super(e),this.keyName=e.keyName,this.returnSingle=e.returnSingle??this.returnSingle,this.zodSchema=e.zodSchema}async _validateResult(e){if(this.zodSchema===void 0)return e;const n=await Oe(this.zodSchema,e);if(n.success)return n.data;throw new he(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(n.error.issues)}`,JSON.stringify(e,null,2))}async parseResult(e){const n=e.flatMap(s=>{const{message:i}=s;return!("tool_calls"in i)||!Array.isArray(i.tool_calls)?[]:i.tool_calls});if(n[0]===void 0)throw new Error("No parseable tool calls provided to GoogleGenerativeAIToolsOutputParser.");const[t]=n;return await this._validateResult(t.args)}},L;(function(e){e.STRING="string",e.NUMBER="number",e.INTEGER="integer",e.BOOLEAN="boolean",e.ARRAY="array",e.OBJECT="object"})(L||(L={}));/**
|
|
2
2
|
* @license
|
|
3
3
|
* Copyright 2024 Google LLC
|
|
4
4
|
*
|
|
@@ -73,8 +73,8 @@ import{i as ne,t as fe,a as he,b as pe,C as ge,c as me,d as Ce,e as ye,f as oe,g
|
|
|
73
73
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
74
74
|
* See the License for the specific language governing permissions and
|
|
75
75
|
* limitations under the License.
|
|
76
|
-
*/function b(e){return e.text=()=>{if(e.candidates&&e.candidates.length>0){if(e.candidates.length>1&&console.warn(`This response had ${e.candidates.length} candidates. Returning text from the first candidate only. Access response.candidates directly to use the other candidates.`),
|
|
77
|
-
`+a.executableCode.code+"\n```\n"),a.codeExecutionResult&&i.push("\n```\n"+a.codeExecutionResult.output+"\n```\n");return i.length>0?i.join(""):""}function W(e){var n,t,o,s;const i=[];if(!((t=(n=e.candidates)===null||n===void 0?void 0:n[0].content)===null||t===void 0)&&t.parts)for(const a of(s=(o=e.candidates)===null||o===void 0?void 0:o[0].content)===null||s===void 0?void 0:s.parts)a.functionCall&&i.push(a.functionCall);if(i.length>0)return i}const Xe=[T.RECITATION,T.SAFETY,T.LANGUAGE];function
|
|
76
|
+
*/function b(e){return e.text=()=>{if(e.candidates&&e.candidates.length>0){if(e.candidates.length>1&&console.warn(`This response had ${e.candidates.length} candidates. Returning text from the first candidate only. Access response.candidates directly to use the other candidates.`),A(e.candidates[0]))throw new v(`${C(e)}`,e);return ze(e)}else if(e.promptFeedback)throw new v(`Text not available. ${C(e)}`,e);return""},e.functionCall=()=>{if(e.candidates&&e.candidates.length>0){if(e.candidates.length>1&&console.warn(`This response had ${e.candidates.length} candidates. Returning function calls from the first candidate only. Access response.candidates directly to use the other candidates.`),A(e.candidates[0]))throw new v(`${C(e)}`,e);return console.warn("response.functionCall() is deprecated. Use response.functionCalls() instead."),W(e)[0]}else if(e.promptFeedback)throw new v(`Function call not available. ${C(e)}`,e)},e.functionCalls=()=>{if(e.candidates&&e.candidates.length>0){if(e.candidates.length>1&&console.warn(`This response had ${e.candidates.length} candidates. Returning function calls from the first candidate only. Access response.candidates directly to use the other candidates.`),A(e.candidates[0]))throw new v(`${C(e)}`,e);return W(e)}else if(e.promptFeedback)throw new v(`Function call not available. ${C(e)}`,e)},e}function ze(e){var n,t,o,s;const i=[];if(!((t=(n=e.candidates)===null||n===void 0?void 0:n[0].content)===null||t===void 0)&&t.parts)for(const a of(s=(o=e.candidates)===null||o===void 0?void 0:o[0].content)===null||s===void 0?void 0:s.parts)a.text&&i.push(a.text),a.executableCode&&i.push("\n```"+a.executableCode.language+`
|
|
77
|
+
`+a.executableCode.code+"\n```\n"),a.codeExecutionResult&&i.push("\n```\n"+a.codeExecutionResult.output+"\n```\n");return i.length>0?i.join(""):""}function W(e){var n,t,o,s;const i=[];if(!((t=(n=e.candidates)===null||n===void 0?void 0:n[0].content)===null||t===void 0)&&t.parts)for(const a of(s=(o=e.candidates)===null||o===void 0?void 0:o[0].content)===null||s===void 0?void 0:s.parts)a.functionCall&&i.push(a.functionCall);if(i.length>0)return i}const Xe=[T.RECITATION,T.SAFETY,T.LANGUAGE];function A(e){return!!e.finishReason&&Xe.includes(e.finishReason)}function C(e){var n,t,o;let s="";if((!e.candidates||e.candidates.length===0)&&e.promptFeedback)s+="Response was blocked",!((n=e.promptFeedback)===null||n===void 0)&&n.blockReason&&(s+=` due to ${e.promptFeedback.blockReason}`),!((t=e.promptFeedback)===null||t===void 0)&&t.blockReasonMessage&&(s+=`: ${e.promptFeedback.blockReasonMessage}`);else if(!((o=e.candidates)===null||o===void 0)&&o[0]){const i=e.candidates[0];A(i)&&(s+=`Candidate was blocked due to ${i.finishReason}`,i.finishMessage&&(s+=`: ${i.finishMessage}`))}return s}function I(e){return this instanceof I?(this.v=e,this):new I(e)}function Qe(e,n,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var o=t.apply(e,n||[]),s,i=[];return s={},a("next"),a("throw"),a("return"),s[Symbol.asyncIterator]=function(){return this},s;function a(d){o[d]&&(s[d]=function(l){return new Promise(function(h,m){i.push([d,l,h,m])>1||c(d,l)})})}function c(d,l){try{u(o[d](l))}catch(h){f(i[0][3],h)}}function u(d){d.value instanceof I?Promise.resolve(d.value.v).then(r,p):f(i[0][2],d)}function r(d){c("next",d)}function p(d){c("throw",d)}function f(d,l){d(l),i.shift(),i.length&&c(i[0][0],i[0][1])}}/**
|
|
78
78
|
* @license
|
|
79
79
|
* Copyright 2024 Google LLC
|
|
80
80
|
*
|
|
@@ -209,4 +209,4 @@ import{i as ne,t as fe,a as he,b as pe,C as ge,c as me,d as Ce,e as ye,f as oe,g
|
|
|
209
209
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
210
210
|
* See the License for the specific language governing permissions and
|
|
211
211
|
* limitations under the License.
|
|
212
|
-
*/class ee{constructor(n){this.apiKey=n}getGenerativeModel(n,t){if(!n.model)throw new g("Must provide a model name. Example: genai.getGenerativeModel({ model: 'my-model-name' })");return new Z(this.apiKey,n,t)}getGenerativeModelFromCachedContent(n,t,o){if(!n.name)throw new y("Cached content must contain a `name` field.");if(!n.model)throw new y("Cached content must contain a `model` field.");const s=["model","systemInstruction"];for(const a of s)if(t?.[a]&&n[a]&&t?.[a]!==n[a]){if(a==="model"){const c=t.model.startsWith("models/")?t.model.replace("models/",""):t.model,u=n.model.startsWith("models/")?n.model.replace("models/",""):n.model;if(c===u)continue}throw new y(`Different value for "${a}" specified in modelParams (${t[a]}) and cachedContent (${n[a]})`)}const i=Object.assign(Object.assign({},t),{model:n.model,tools:n.tools,toolConfig:n.toolConfig,systemInstruction:n.systemInstruction,cachedContent:n});return new Z(this.apiKey,i,o)}}function te(e,n){const t=ht(e),o=gt(t,n);return{tools:t,toolConfig:o}}function ht(e){let n=[];const t=[];return e.forEach(s=>{if(
|
|
212
|
+
*/class ee{constructor(n){this.apiKey=n}getGenerativeModel(n,t){if(!n.model)throw new g("Must provide a model name. Example: genai.getGenerativeModel({ model: 'my-model-name' })");return new Z(this.apiKey,n,t)}getGenerativeModelFromCachedContent(n,t,o){if(!n.name)throw new y("Cached content must contain a `name` field.");if(!n.model)throw new y("Cached content must contain a `model` field.");const s=["model","systemInstruction"];for(const a of s)if(t?.[a]&&n[a]&&t?.[a]!==n[a]){if(a==="model"){const c=t.model.startsWith("models/")?t.model.replace("models/",""):t.model,u=n.model.startsWith("models/")?n.model.replace("models/",""):n.model;if(c===u)continue}throw new y(`Different value for "${a}" specified in modelParams (${t[a]}) and cachedContent (${n[a]})`)}const i=Object.assign(Object.assign({},t),{model:n.model,tools:n.tools,toolConfig:n.toolConfig,systemInstruction:n.systemInstruction,cachedContent:n});return new Z(this.apiKey,i,o)}}function te(e,n){const t=ht(e),o=gt(t,n);return{tools:t,toolConfig:o}}function ht(e){let n=[];const t=[];return e.forEach(s=>{if(ne(s)){const[i]=Le([s]);i.functionDeclarations&&n.push(...i.functionDeclarations)}else if(oe(s)){const{functionDeclarations:i}=pt(s);if(i)n.push(...i);else throw new Error("Failed to convert OpenAI structured tool to GenerativeAI tool")}else t.push(s)}),t.find(s=>"functionDeclarations"in s)?t.map(s=>{if(n?.length>0&&"functionDeclarations"in s){const i={functionDeclarations:[...s.functionDeclarations||[],...n]};return n=[],i}return s}):[...t,...n.length>0?[{functionDeclarations:n}]:[]]}function pt(e){return{functionDeclarations:[{name:e.function.name,description:e.function.description,parameters:_(e.function.parameters)}]}}function gt(e,n){if(!e.length||!n)return;const{toolChoice:t,allowedFunctionNames:o}=n,s={any:w.ANY,auto:w.AUTO,none:w.NONE};if(t&&["any","auto","none"].includes(t))return{functionCallingConfig:{mode:s[t]??"MODE_UNSPECIFIED",allowedFunctionNames:o}};if(typeof t=="string"||o)return{functionCallingConfig:{mode:w.ANY,allowedFunctionNames:[...o??[],...t&&typeof t=="string"?[t]:[]]}}}var wt=class extends pe{static lc_name(){return"ChatGoogleGenerativeAI"}lc_serializable=!0;get lc_secrets(){return{apiKey:"GOOGLE_API_KEY"}}lc_namespace=["langchain","chat_models","google_genai"];get lc_aliases(){return{apiKey:"google_api_key"}}model;temperature;maxOutputTokens;topP;topK;stopSequences=[];safetySettings;apiKey;streaming=!1;json;streamUsage=!0;convertSystemMessageToHumanContent;client;get _isMultimodalModel(){return this.model.includes("vision")||this.model.startsWith("gemini-1.5")||this.model.startsWith("gemini-2")||this.model.startsWith("gemma-3-")&&!this.model.startsWith("gemma-3-1b")}constructor(e){if(super(e),this.model=e.model.replace(/^models\//,""),this.maxOutputTokens=e.maxOutputTokens??this.maxOutputTokens,this.maxOutputTokens&&this.maxOutputTokens<0)throw new Error("`maxOutputTokens` must be a positive integer");if(this.temperature=e.temperature??this.temperature,this.temperature&&(this.temperature<0||this.temperature>2))throw new Error("`temperature` must be in the range of [0.0,2.0]");if(this.topP=e.topP??this.topP,this.topP&&this.topP<0)throw new Error("`topP` must be a positive integer");if(this.topP&&this.topP>1)throw new Error("`topP` must be below 1.");if(this.topK=e.topK??this.topK,this.topK&&this.topK<0)throw new Error("`topK` must be a positive integer");if(this.stopSequences=e.stopSequences??this.stopSequences,this.apiKey=e.apiKey??Re("GOOGLE_API_KEY"),!this.apiKey)throw new Error("Please set an API key for Google GenerativeAI in the environment variable GOOGLE_API_KEY or in the `apiKey` field of the ChatGoogleGenerativeAI constructor");if(this.safetySettings=e.safetySettings??this.safetySettings,this.safetySettings&&this.safetySettings.length>0&&new Set(this.safetySettings.map(t=>t.category)).size!==this.safetySettings.length)throw new Error("The categories in `safetySettings` array must be unique");this.streaming=e.streaming??this.streaming,this.json=e.json,this.client=new ee(this.apiKey).getGenerativeModel({model:this.model,safetySettings:this.safetySettings,generationConfig:{stopSequences:this.stopSequences,maxOutputTokens:this.maxOutputTokens,temperature:this.temperature,topP:this.topP,topK:this.topK,...this.json?{responseMimeType:"application/json"}:{}}},{apiVersion:e.apiVersion,baseUrl:e.baseUrl}),this.streamUsage=e.streamUsage??this.streamUsage}useCachedContent(e,n,t){this.apiKey&&(this.client=new ee(this.apiKey).getGenerativeModelFromCachedContent(e,n,t))}get useSystemInstruction(){return typeof this.convertSystemMessageToHumanContent=="boolean"?!this.convertSystemMessageToHumanContent:this.computeUseSystemInstruction}get computeUseSystemInstruction(){return this.model==="gemini-1.0-pro-001"||this.model.startsWith("gemini-pro-vision")||this.model.startsWith("gemini-1.0-pro-vision")?!1:this.model!=="gemini-pro"}getLsParams(e){return{ls_provider:"google_genai",ls_model_name:this.model,ls_model_type:"chat",ls_temperature:this.client.generationConfig.temperature,ls_max_tokens:this.client.generationConfig.maxOutputTokens,ls_stop:e.stop}}_combineLLMOutput(){return[]}_llmType(){return"googlegenerativeai"}bindTools(e,n){return this.withConfig({tools:te(e)?.tools,...n})}invocationParams(e){const n=e?.tools?.length?te(e.tools,{toolChoice:e.tool_choice,allowedFunctionNames:e.allowedFunctionNames}):void 0;return e?.responseSchema?(this.client.generationConfig.responseSchema=e.responseSchema,this.client.generationConfig.responseMimeType="application/json"):(this.client.generationConfig.responseSchema=void 0,this.client.generationConfig.responseMimeType=this.json?"application/json":void 0),{...n?.tools?{tools:n.tools}:{},...n?.toolConfig?{toolConfig:n.toolConfig}:{}}}async _generate(e,n,t){const o=k(e,this._isMultimodalModel,this.useSystemInstruction);let s=o;if(o[0].role==="system"){const[r]=o;this.client.systemInstruction=r,s=o.slice(1)}const i=this.invocationParams(n);if(this.streaming){const r={},p=this._streamResponseChunks(e,n,t),f={};for await(const l of p){const h=l.generationInfo?.completion??0;f[h]===void 0?f[h]=l:f[h]=f[h].concat(l)}return{generations:Object.entries(f).sort(([l],[h])=>parseInt(l,10)-parseInt(h,10)).map(([l,h])=>h),llmOutput:{estimatedTokenUsage:r}}}const a=await this.completionWithRetry({...i,contents:s});let c;if("usageMetadata"in a.response){const r=a.response.usageMetadata;c={input_tokens:r.promptTokenCount??0,output_tokens:r.candidatesTokenCount??0,total_tokens:r.totalTokenCount??0}}const u=ke(a.response,{usageMetadata:c});return u.generations?.length>0&&await t?.handleLLMNewToken(u.generations[0]?.text??""),u}async*_streamResponseChunks(e,n,t){const o=k(e,this._isMultimodalModel,this.useSystemInstruction);let s=o;if(o[0].role==="system"){const[l]=o;this.client.systemInstruction=l,s=o.slice(1)}const a={...this.invocationParams(n),contents:s},c=await this.caller.callWithOptions({signal:n?.signal},async()=>{const{stream:l}=await this.client.generateContentStream(a);return l});let u,r=0,p=0,f=0,d=0;for await(const l of c){if("usageMetadata"in l&&l.usageMetadata!==void 0&&this.streamUsage!==!1&&n.streamUsage!==!1){u={input_tokens:l.usageMetadata.promptTokenCount??0,output_tokens:l.usageMetadata.candidatesTokenCount??0,total_tokens:l.usageMetadata.totalTokenCount??0};const m=l.usageMetadata.promptTokenCount??0;u.input_tokens=Math.max(0,m-r),r=m;const M=l.usageMetadata.candidatesTokenCount??0;u.output_tokens=Math.max(0,M-p),p=M;const x=l.usageMetadata.totalTokenCount??0;u.total_tokens=Math.max(0,x-f),f=x}const h=Ue(l,{usageMetadata:u,index:d});d+=1,h&&(yield h,await t?.handleLLMNewToken(h.text??""))}}async completionWithRetry(e,n){return this.caller.callWithOptions({signal:n?.signal},async()=>{try{return await this.client.generateContent(e)}catch(t){throw t.message?.includes("400 Bad Request")&&(t.status=400),t}})}withStructuredOutput(e,n){const t=e,o=n?.name,s=n?.method,i=n?.includeRaw;if(s==="jsonMode")throw new Error('ChatGoogleGenerativeAI only supports "jsonSchema" or "functionCalling" as a method.');let a,c;if(s==="functionCalling"){let f=o??"extract",d;if(se(t)){const l=N(t);d=[{functionDeclarations:[{name:f,description:l.description??"A function available to call.",parameters:l}]}],c=new U({returnSingle:!0,keyName:f,zodSchema:t})}else{let l;typeof t.name=="string"&&typeof t.parameters=="object"&&t.parameters!=null?(l=t,l.parameters=_(t.parameters),f=t.name):l={name:f,description:t.description??"",parameters:_(t)},d=[{functionDeclarations:[l]}],c=new U({returnSingle:!0,keyName:f})}a=this.bindTools(d).withConfig({allowedFunctionNames:[f]})}else{const f=N(t);a=this.withConfig({responseSchema:f}),c=new ge}if(!i)return a.pipe(c).withConfig({runName:"ChatGoogleGenerativeAIStructuredOutput"});const u=D.assign({parsed:(f,d)=>c.invoke(f.raw,d)}),r=D.assign({parsed:()=>null}),p=u.withFallbacks({fallbacks:[r]});return Ae.from([{raw:a},p]).withConfig({runName:"StructuredOutputRunnable"})}};export{wt as ChatGoogleGenerativeAI};
|