@mcp-use/inspector 0.9.2 → 0.10.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/{browser-BaWfMf0m.js → browser-B0j7NxIO.js} +24 -24
- package/dist/client/assets/{display-A5IEINAP-C7C5ZEWf.js → display-A5IEINAP-D6ub1rVT.js} +2 -2
- package/dist/client/assets/{embeddings-Cd_IFijr.js → embeddings-DSYSWoMY.js} +1 -1
- package/dist/client/assets/{index-D-t8kYzy.js → index-BOKDheu2.js} +1 -1
- package/dist/client/assets/index-BlKiZ9Yy.css +1 -0
- package/dist/client/assets/index-C1fAPMt_.js +8 -0
- package/dist/client/assets/index-C86qnUPq.js +1683 -0
- package/dist/client/assets/{index-BaFuUxbj.js → index-CmrpwsvF.js} +1 -1
- package/dist/client/assets/index-DLvycrCn.js +80 -0
- package/dist/client/assets/{index-BDueMm07.js → index-DMpSV0MO.js} +2 -2
- package/dist/client/assets/{index-Dwx0D9tm.js → index-dcwAFu32.js} +11 -11
- package/dist/client/assets/{index-FfhUz5GP.js → index-jXEm6Yfx.js} +3 -3
- package/dist/client/assets/index-uLaqVHqx.js +71 -0
- package/dist/client/assets/{winston-D_OHtP4E.js → winston-BG6TqujU.js} +1 -1
- package/dist/client/index.html +3 -3
- package/package.json +2 -2
- package/dist/client/assets/index-BxlzAdRz.js +0 -150
- package/dist/client/assets/index-CHNXgq6o.css +0 -1
- package/dist/client/assets/index-CejJnjhQ.js +0 -8
- package/dist/client/assets/index-DZxMwvFi.js +0 -1683
|
@@ -1,150 +0,0 @@
|
|
|
1
|
-
import{e as gr,f as We,h as Pc,i as Zt,j as Dl,$ as Ul,k as Mc,d as Hs,l as Fl,m as Bl,n as zl,o as ql,t as ki}from"./index-DZxMwvFi.js";import{r as Gl}from"./index-DRz5BQNA.js";var ue;(function(t){t.assertEqual=a=>{};function e(a){}t.assertIs=e;function r(a){throw new Error}t.assertNever=r,t.arrayToEnum=a=>{const s={};for(const i of a)s[i]=i;return s},t.getValidEnumValues=a=>{const s=t.objectKeys(a).filter(o=>typeof a[a[o]]!="number"),i={};for(const o of s)i[o]=a[o];return t.objectValues(i)},t.objectValues=a=>t.objectKeys(a).map(function(s){return a[s]}),t.objectKeys=typeof Object.keys=="function"?a=>Object.keys(a):a=>{const s=[];for(const i in a)Object.prototype.hasOwnProperty.call(a,i)&&s.push(i);return s},t.find=(a,s)=>{for(const i of a)if(s(i))return i},t.isInteger=typeof Number.isInteger=="function"?a=>Number.isInteger(a):a=>typeof a=="number"&&Number.isFinite(a)&&Math.floor(a)===a;function n(a,s=" | "){return a.map(i=>typeof i=="string"?`'${i}'`:i).join(s)}t.joinValues=n,t.jsonStringifyReplacer=(a,s)=>typeof s=="bigint"?s.toString():s})(ue||(ue={}));var Ri;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(Ri||(Ri={}));const M=ue.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Rt=t=>{switch(typeof t){case"undefined":return M.undefined;case"string":return M.string;case"number":return Number.isNaN(t)?M.nan:M.number;case"boolean":return M.boolean;case"function":return M.function;case"bigint":return M.bigint;case"symbol":return M.symbol;case"object":return Array.isArray(t)?M.array:t===null?M.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?M.promise:typeof Map<"u"&&t instanceof Map?M.map:typeof Set<"u"&&t instanceof Set?M.set:typeof Date<"u"&&t instanceof Date?M.date:M.object;default:return M.unknown}},I=ue.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class Xe extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};const r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){const r=e||function(s){return s.message},n={_errors:[]},a=s=>{for(const i of s.issues)if(i.code==="invalid_union")i.unionErrors.map(a);else if(i.code==="invalid_return_type")a(i.returnTypeError);else if(i.code==="invalid_arguments")a(i.argumentsError);else if(i.path.length===0)n._errors.push(r(i));else{let o=n,c=0;for(;c<i.path.length;){const u=i.path[c];c===i.path.length-1?(o[u]=o[u]||{_errors:[]},o[u]._errors.push(r(i))):o[u]=o[u]||{_errors:[]},o=o[u],c++}}};return a(this),n}static assert(e){if(!(e instanceof Xe))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,ue.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){const r=Object.create(null),n=[];for(const a of this.issues)if(a.path.length>0){const s=a.path[0];r[s]=r[s]||[],r[s].push(e(a))}else n.push(e(a));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}}Xe.create=t=>new Xe(t);const Cr=(t,e)=>{let r;switch(t.code){case I.invalid_type:t.received===M.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case I.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,ue.jsonStringifyReplacer)}`;break;case I.unrecognized_keys:r=`Unrecognized key(s) in object: ${ue.joinValues(t.keys,", ")}`;break;case I.invalid_union:r="Invalid input";break;case I.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${ue.joinValues(t.options)}`;break;case I.invalid_enum_value:r=`Invalid enum value. Expected ${ue.joinValues(t.options)}, received '${t.received}'`;break;case I.invalid_arguments:r="Invalid function arguments";break;case I.invalid_return_type:r="Invalid function return type";break;case I.invalid_date:r="Invalid date";break;case I.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:ue.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case I.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case I.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case I.custom:r="Invalid input";break;case I.invalid_intersection_types:r="Intersection results could not be merged";break;case I.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case I.not_finite:r="Number must be finite";break;default:r=e.defaultError,ue.assertNever(t)}return{message:r}};let Hl=Cr;function us(){return Hl}const ls=t=>{const{data:e,path:r,errorMaps:n,issueData:a}=t,s=[...r,...a.path||[]],i={...a,path:s};if(a.message!==void 0)return{...a,path:s,message:a.message};let o="";const c=n.filter(u=>!!u).slice().reverse();for(const u of c)o=u(i,{data:e,defaultError:o}).message;return{...a,path:s,message:o}};function $(t,e){const r=us(),n=ls({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===Cr?void 0:Cr].filter(a=>!!a)});t.common.issues.push(n)}class Ue{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){const n=[];for(const a of r){if(a.status==="aborted")return X;a.status==="dirty"&&e.dirty(),n.push(a.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){const n=[];for(const a of r){const s=await a.key,i=await a.value;n.push({key:s,value:i})}return Ue.mergeObjectSync(e,n)}static mergeObjectSync(e,r){const n={};for(const a of r){const{key:s,value:i}=a;if(s.status==="aborted"||i.status==="aborted")return X;s.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),s.value!=="__proto__"&&(typeof i.value<"u"||a.alwaysSet)&&(n[s.value]=i.value)}return{status:e.value,value:n}}}const X=Object.freeze({status:"aborted"}),Sr=t=>({status:"dirty",value:t}),He=t=>({status:"valid",value:t}),Ci=t=>t.status==="aborted",Ni=t=>t.status==="dirty",or=t=>t.status==="valid",hn=t=>typeof Promise<"u"&&t instanceof Promise;var z;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(z||(z={}));class _t{constructor(e,r,n,a){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=a}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const $i=(t,e)=>{if(or(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const r=new Xe(t.common.issues);return this._error=r,this._error}}};function ne(t){if(!t)return{};const{errorMap:e,invalid_type_error:r,required_error:n,description:a}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:a}:{errorMap:(i,o)=>{const{message:c}=t;return i.code==="invalid_enum_value"?{message:c??o.defaultError}:typeof o.data>"u"?{message:c??n??o.defaultError}:i.code!=="invalid_type"?{message:o.defaultError}:{message:c??r??o.defaultError}},description:a}}class ie{get description(){return this._def.description}_getType(e){return Rt(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:Rt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Ue,ctx:{common:e.parent.common,data:e.data,parsedType:Rt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const r=this._parse(e);if(hn(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){const r=this._parse(e);return Promise.resolve(r)}parse(e,r){const n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){const n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Rt(e)},a=this._parseSync({data:e,path:n.path,parent:n});return $i(n,a)}"~validate"(e){const r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Rt(e)};if(!this["~standard"].async)try{const n=this._parseSync({data:e,path:[],parent:r});return or(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(n=>or(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(e,r){const n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){const n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Rt(e)},a=this._parse({data:e,path:n.path,parent:n}),s=await(hn(a)?a:Promise.resolve(a));return $i(n,s)}refine(e,r){const n=a=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(a):r;return this._refinement((a,s)=>{const i=e(a),o=()=>s.addIssue({code:I.custom,...n(a)});return typeof Promise<"u"&&i instanceof Promise?i.then(c=>c?!0:(o(),!1)):i?!0:(o(),!1)})}refinement(e,r){return this._refinement((n,a)=>e(n)?!0:(a.addIssue(typeof r=="function"?r(n,a):r),!1))}_refinement(e){return new lr({schema:this,typeName:x.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return Nt.create(this,this._def)}nullable(){return dr.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ft.create(this)}promise(){return Mr.create(this,this._def)}or(e){return pn.create([this,e],this._def)}and(e){return mn.create(this,e,this._def)}transform(e){return new lr({...ne(this._def),schema:this,typeName:x.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const r=typeof e=="function"?e:()=>e;return new ms({...ne(this._def),innerType:this,defaultValue:r,typeName:x.ZodDefault})}brand(){return new pd({typeName:x.ZodBranded,type:this,...ne(this._def)})}catch(e){const r=typeof e=="function"?e:()=>e;return new gs({...ne(this._def),innerType:this,catchValue:r,typeName:x.ZodCatch})}describe(e){const r=this.constructor;return new r({...this._def,description:e})}pipe(e){return Zs.create(this,e)}readonly(){return _s.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const Zl=/^c[^\s-]{8,}$/i,Vl=/^[0-9a-z]+$/,Wl=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Jl=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Kl=/^[a-z0-9_-]{21}$/i,Yl=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Xl=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Ql=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,ed="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let Zn;const td=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,rd=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,nd=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,ad=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,sd=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,id=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Lc="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",od=new RegExp(`^${Lc}$`);function jc(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);const r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function cd(t){return new RegExp(`^${jc(t)}$`)}function ud(t){let e=`${Lc}T${jc(t)}`;const r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function ld(t,e){return!!((e==="v4"||!e)&&td.test(t)||(e==="v6"||!e)&&nd.test(t))}function dd(t,e){if(!Yl.test(t))return!1;try{const[r]=t.split(".");if(!r)return!1;const n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),a=JSON.parse(atob(n));return!(typeof a!="object"||a===null||"typ"in a&&a?.typ!=="JWT"||!a.alg||e&&a.alg!==e)}catch{return!1}}function hd(t,e){return!!((e==="v4"||!e)&&rd.test(t)||(e==="v6"||!e)&&ad.test(t))}class bt extends ie{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==M.string){const s=this._getOrReturnCtx(e);return $(s,{code:I.invalid_type,expected:M.string,received:s.parsedType}),X}const n=new Ue;let a;for(const s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(a=this._getOrReturnCtx(e,a),$(a,{code:I.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="max")e.data.length>s.value&&(a=this._getOrReturnCtx(e,a),$(a,{code:I.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="length"){const i=e.data.length>s.value,o=e.data.length<s.value;(i||o)&&(a=this._getOrReturnCtx(e,a),i?$(a,{code:I.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):o&&$(a,{code:I.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")Ql.test(e.data)||(a=this._getOrReturnCtx(e,a),$(a,{validation:"email",code:I.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")Zn||(Zn=new RegExp(ed,"u")),Zn.test(e.data)||(a=this._getOrReturnCtx(e,a),$(a,{validation:"emoji",code:I.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")Jl.test(e.data)||(a=this._getOrReturnCtx(e,a),$(a,{validation:"uuid",code:I.invalid_string,message:s.message}),n.dirty());else if(s.kind==="nanoid")Kl.test(e.data)||(a=this._getOrReturnCtx(e,a),$(a,{validation:"nanoid",code:I.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")Zl.test(e.data)||(a=this._getOrReturnCtx(e,a),$(a,{validation:"cuid",code:I.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")Vl.test(e.data)||(a=this._getOrReturnCtx(e,a),$(a,{validation:"cuid2",code:I.invalid_string,message:s.message}),n.dirty());else if(s.kind==="ulid")Wl.test(e.data)||(a=this._getOrReturnCtx(e,a),$(a,{validation:"ulid",code:I.invalid_string,message:s.message}),n.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{a=this._getOrReturnCtx(e,a),$(a,{validation:"url",code:I.invalid_string,message:s.message}),n.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(e.data)||(a=this._getOrReturnCtx(e,a),$(a,{validation:"regex",code:I.invalid_string,message:s.message}),n.dirty())):s.kind==="trim"?e.data=e.data.trim():s.kind==="includes"?e.data.includes(s.value,s.position)||(a=this._getOrReturnCtx(e,a),$(a,{code:I.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),n.dirty()):s.kind==="toLowerCase"?e.data=e.data.toLowerCase():s.kind==="toUpperCase"?e.data=e.data.toUpperCase():s.kind==="startsWith"?e.data.startsWith(s.value)||(a=this._getOrReturnCtx(e,a),$(a,{code:I.invalid_string,validation:{startsWith:s.value},message:s.message}),n.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(a=this._getOrReturnCtx(e,a),$(a,{code:I.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?ud(s).test(e.data)||(a=this._getOrReturnCtx(e,a),$(a,{code:I.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?od.test(e.data)||(a=this._getOrReturnCtx(e,a),$(a,{code:I.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?cd(s).test(e.data)||(a=this._getOrReturnCtx(e,a),$(a,{code:I.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?Xl.test(e.data)||(a=this._getOrReturnCtx(e,a),$(a,{validation:"duration",code:I.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?ld(e.data,s.version)||(a=this._getOrReturnCtx(e,a),$(a,{validation:"ip",code:I.invalid_string,message:s.message}),n.dirty()):s.kind==="jwt"?dd(e.data,s.alg)||(a=this._getOrReturnCtx(e,a),$(a,{validation:"jwt",code:I.invalid_string,message:s.message}),n.dirty()):s.kind==="cidr"?hd(e.data,s.version)||(a=this._getOrReturnCtx(e,a),$(a,{validation:"cidr",code:I.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?sd.test(e.data)||(a=this._getOrReturnCtx(e,a),$(a,{validation:"base64",code:I.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?id.test(e.data)||(a=this._getOrReturnCtx(e,a),$(a,{validation:"base64url",code:I.invalid_string,message:s.message}),n.dirty()):ue.assertNever(s);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(a=>e.test(a),{validation:r,code:I.invalid_string,...z.errToObj(n)})}_addCheck(e){return new bt({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...z.errToObj(e)})}url(e){return this._addCheck({kind:"url",...z.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...z.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...z.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...z.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...z.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...z.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...z.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...z.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...z.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...z.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...z.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...z.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...z.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...z.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...z.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...z.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...z.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...z.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...z.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...z.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...z.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...z.errToObj(r)})}nonempty(e){return this.min(1,z.errToObj(e))}trim(){return new bt({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new bt({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new bt({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}}bt.create=t=>new bt({checks:[],typeName:x.ZodString,coerce:t?.coerce??!1,...ne(t)});function fd(t,e){const r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,a=r>n?r:n,s=Number.parseInt(t.toFixed(a).replace(".","")),i=Number.parseInt(e.toFixed(a).replace(".",""));return s%i/10**a}class cr extends ie{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==M.number){const s=this._getOrReturnCtx(e);return $(s,{code:I.invalid_type,expected:M.number,received:s.parsedType}),X}let n;const a=new Ue;for(const s of this._def.checks)s.kind==="int"?ue.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),$(n,{code:I.invalid_type,expected:"integer",received:"float",message:s.message}),a.dirty()):s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),$(n,{code:I.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),a.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),$(n,{code:I.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),a.dirty()):s.kind==="multipleOf"?fd(e.data,s.value)!==0&&(n=this._getOrReturnCtx(e,n),$(n,{code:I.not_multiple_of,multipleOf:s.value,message:s.message}),a.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),$(n,{code:I.not_finite,message:s.message}),a.dirty()):ue.assertNever(s);return{status:a.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,z.toString(r))}gt(e,r){return this.setLimit("min",e,!1,z.toString(r))}lte(e,r){return this.setLimit("max",e,!0,z.toString(r))}lt(e,r){return this.setLimit("max",e,!1,z.toString(r))}setLimit(e,r,n,a){return new cr({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:z.toString(a)}]})}_addCheck(e){return new cr({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:z.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:z.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:z.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:z.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:z.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:z.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:z.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:z.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:z.toString(e)})}get minValue(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&ue.isInteger(e.value))}get isFinite(){let e=null,r=null;for(const n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(r)&&Number.isFinite(e)}}cr.create=t=>new cr({checks:[],typeName:x.ZodNumber,coerce:t?.coerce||!1,...ne(t)});class Nr extends ie{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==M.bigint)return this._getInvalidInput(e);let n;const a=new Ue;for(const s of this._def.checks)s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),$(n,{code:I.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),a.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),$(n,{code:I.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),a.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),$(n,{code:I.not_multiple_of,multipleOf:s.value,message:s.message}),a.dirty()):ue.assertNever(s);return{status:a.value,value:e.data}}_getInvalidInput(e){const r=this._getOrReturnCtx(e);return $(r,{code:I.invalid_type,expected:M.bigint,received:r.parsedType}),X}gte(e,r){return this.setLimit("min",e,!0,z.toString(r))}gt(e,r){return this.setLimit("min",e,!1,z.toString(r))}lte(e,r){return this.setLimit("max",e,!0,z.toString(r))}lt(e,r){return this.setLimit("max",e,!1,z.toString(r))}setLimit(e,r,n,a){return new Nr({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:z.toString(a)}]})}_addCheck(e){return new Nr({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:z.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:z.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:z.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:z.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:z.toString(r)})}get minValue(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}}Nr.create=t=>new Nr({checks:[],typeName:x.ZodBigInt,coerce:t?.coerce??!1,...ne(t)});class ds extends ie{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==M.boolean){const n=this._getOrReturnCtx(e);return $(n,{code:I.invalid_type,expected:M.boolean,received:n.parsedType}),X}return He(e.data)}}ds.create=t=>new ds({typeName:x.ZodBoolean,coerce:t?.coerce||!1,...ne(t)});class fn extends ie{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==M.date){const s=this._getOrReturnCtx(e);return $(s,{code:I.invalid_type,expected:M.date,received:s.parsedType}),X}if(Number.isNaN(e.data.getTime())){const s=this._getOrReturnCtx(e);return $(s,{code:I.invalid_date}),X}const n=new Ue;let a;for(const s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(a=this._getOrReturnCtx(e,a),$(a,{code:I.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),n.dirty()):s.kind==="max"?e.data.getTime()>s.value&&(a=this._getOrReturnCtx(e,a),$(a,{code:I.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):ue.assertNever(s);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new fn({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:z.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:z.toString(r)})}get minDate(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}}fn.create=t=>new fn({checks:[],coerce:t?.coerce||!1,typeName:x.ZodDate,...ne(t)});class Pi extends ie{_parse(e){if(this._getType(e)!==M.symbol){const n=this._getOrReturnCtx(e);return $(n,{code:I.invalid_type,expected:M.symbol,received:n.parsedType}),X}return He(e.data)}}Pi.create=t=>new Pi({typeName:x.ZodSymbol,...ne(t)});class hs extends ie{_parse(e){if(this._getType(e)!==M.undefined){const n=this._getOrReturnCtx(e);return $(n,{code:I.invalid_type,expected:M.undefined,received:n.parsedType}),X}return He(e.data)}}hs.create=t=>new hs({typeName:x.ZodUndefined,...ne(t)});class Mi extends ie{_parse(e){if(this._getType(e)!==M.null){const n=this._getOrReturnCtx(e);return $(n,{code:I.invalid_type,expected:M.null,received:n.parsedType}),X}return He(e.data)}}Mi.create=t=>new Mi({typeName:x.ZodNull,...ne(t)});class $r extends ie{constructor(){super(...arguments),this._any=!0}_parse(e){return He(e.data)}}$r.create=t=>new $r({typeName:x.ZodAny,...ne(t)});class ir extends ie{constructor(){super(...arguments),this._unknown=!0}_parse(e){return He(e.data)}}ir.create=t=>new ir({typeName:x.ZodUnknown,...ne(t)});class Pt extends ie{_parse(e){const r=this._getOrReturnCtx(e);return $(r,{code:I.invalid_type,expected:M.never,received:r.parsedType}),X}}Pt.create=t=>new Pt({typeName:x.ZodNever,...ne(t)});class Li extends ie{_parse(e){if(this._getType(e)!==M.undefined){const n=this._getOrReturnCtx(e);return $(n,{code:I.invalid_type,expected:M.void,received:n.parsedType}),X}return He(e.data)}}Li.create=t=>new Li({typeName:x.ZodVoid,...ne(t)});class ft extends ie{_parse(e){const{ctx:r,status:n}=this._processInputParams(e),a=this._def;if(r.parsedType!==M.array)return $(r,{code:I.invalid_type,expected:M.array,received:r.parsedType}),X;if(a.exactLength!==null){const i=r.data.length>a.exactLength.value,o=r.data.length<a.exactLength.value;(i||o)&&($(r,{code:i?I.too_big:I.too_small,minimum:o?a.exactLength.value:void 0,maximum:i?a.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:a.exactLength.message}),n.dirty())}if(a.minLength!==null&&r.data.length<a.minLength.value&&($(r,{code:I.too_small,minimum:a.minLength.value,type:"array",inclusive:!0,exact:!1,message:a.minLength.message}),n.dirty()),a.maxLength!==null&&r.data.length>a.maxLength.value&&($(r,{code:I.too_big,maximum:a.maxLength.value,type:"array",inclusive:!0,exact:!1,message:a.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((i,o)=>a.type._parseAsync(new _t(r,i,r.path,o)))).then(i=>Ue.mergeArray(n,i));const s=[...r.data].map((i,o)=>a.type._parseSync(new _t(r,i,r.path,o)));return Ue.mergeArray(n,s)}get element(){return this._def.type}min(e,r){return new ft({...this._def,minLength:{value:e,message:z.toString(r)}})}max(e,r){return new ft({...this._def,maxLength:{value:e,message:z.toString(r)}})}length(e,r){return new ft({...this._def,exactLength:{value:e,message:z.toString(r)}})}nonempty(e){return this.min(1,e)}}ft.create=(t,e)=>new ft({type:t,minLength:null,maxLength:null,exactLength:null,typeName:x.ZodArray,...ne(e)});function tr(t){if(t instanceof Ae){const e={};for(const r in t.shape){const n=t.shape[r];e[r]=Nt.create(tr(n))}return new Ae({...t._def,shape:()=>e})}else return t instanceof ft?new ft({...t._def,type:tr(t.element)}):t instanceof Nt?Nt.create(tr(t.unwrap())):t instanceof dr?dr.create(tr(t.unwrap())):t instanceof St?St.create(t.items.map(e=>tr(e))):t}class Ae extends ie{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),r=ue.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==M.object){const u=this._getOrReturnCtx(e);return $(u,{code:I.invalid_type,expected:M.object,received:u.parsedType}),X}const{status:n,ctx:a}=this._processInputParams(e),{shape:s,keys:i}=this._getCached(),o=[];if(!(this._def.catchall instanceof Pt&&this._def.unknownKeys==="strip"))for(const u in a.data)i.includes(u)||o.push(u);const c=[];for(const u of i){const l=s[u],d=a.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new _t(a,d,a.path,u)),alwaysSet:u in a.data})}if(this._def.catchall instanceof Pt){const u=this._def.unknownKeys;if(u==="passthrough")for(const l of o)c.push({key:{status:"valid",value:l},value:{status:"valid",value:a.data[l]}});else if(u==="strict")o.length>0&&($(a,{code:I.unrecognized_keys,keys:o}),n.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const u=this._def.catchall;for(const l of o){const d=a.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new _t(a,d,a.path,l)),alwaysSet:l in a.data})}}return a.common.async?Promise.resolve().then(async()=>{const u=[];for(const l of c){const d=await l.key,h=await l.value;u.push({key:d,value:h,alwaysSet:l.alwaysSet})}return u}).then(u=>Ue.mergeObjectSync(n,u)):Ue.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return z.errToObj,new Ae({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{const a=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:z.errToObj(e).message??a}:{message:a}}}:{}})}strip(){return new Ae({...this._def,unknownKeys:"strip"})}passthrough(){return new Ae({...this._def,unknownKeys:"passthrough"})}extend(e){return new Ae({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new Ae({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:x.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new Ae({...this._def,catchall:e})}pick(e){const r={};for(const n of ue.objectKeys(e))e[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new Ae({...this._def,shape:()=>r})}omit(e){const r={};for(const n of ue.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new Ae({...this._def,shape:()=>r})}deepPartial(){return tr(this)}partial(e){const r={};for(const n of ue.objectKeys(this.shape)){const a=this.shape[n];e&&!e[n]?r[n]=a:r[n]=a.optional()}return new Ae({...this._def,shape:()=>r})}required(e){const r={};for(const n of ue.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof Nt;)s=s._def.innerType;r[n]=s}return new Ae({...this._def,shape:()=>r})}keyof(){return Dc(ue.objectKeys(this.shape))}}Ae.create=(t,e)=>new Ae({shape:()=>t,unknownKeys:"strip",catchall:Pt.create(),typeName:x.ZodObject,...ne(e)});Ae.strictCreate=(t,e)=>new Ae({shape:()=>t,unknownKeys:"strict",catchall:Pt.create(),typeName:x.ZodObject,...ne(e)});Ae.lazycreate=(t,e)=>new Ae({shape:t,unknownKeys:"strip",catchall:Pt.create(),typeName:x.ZodObject,...ne(e)});class pn extends ie{_parse(e){const{ctx:r}=this._processInputParams(e),n=this._def.options;function a(s){for(const o of s)if(o.result.status==="valid")return o.result;for(const o of s)if(o.result.status==="dirty")return r.common.issues.push(...o.ctx.common.issues),o.result;const i=s.map(o=>new Xe(o.ctx.common.issues));return $(r,{code:I.invalid_union,unionErrors:i}),X}if(r.common.async)return Promise.all(n.map(async s=>{const i={...r,common:{...r.common,issues:[]},parent:null};return{result:await s._parseAsync({data:r.data,path:r.path,parent:i}),ctx:i}})).then(a);{let s;const i=[];for(const c of n){const u={...r,common:{...r.common,issues:[]},parent:null},l=c._parseSync({data:r.data,path:r.path,parent:u});if(l.status==="valid")return l;l.status==="dirty"&&!s&&(s={result:l,ctx:u}),u.common.issues.length&&i.push(u.common.issues)}if(s)return r.common.issues.push(...s.ctx.common.issues),s.result;const o=i.map(c=>new Xe(c));return $(r,{code:I.invalid_union,unionErrors:o}),X}}get options(){return this._def.options}}pn.create=(t,e)=>new pn({options:t,typeName:x.ZodUnion,...ne(e)});function fs(t,e){const r=Rt(t),n=Rt(e);if(t===e)return{valid:!0,data:t};if(r===M.object&&n===M.object){const a=ue.objectKeys(e),s=ue.objectKeys(t).filter(o=>a.indexOf(o)!==-1),i={...t,...e};for(const o of s){const c=fs(t[o],e[o]);if(!c.valid)return{valid:!1};i[o]=c.data}return{valid:!0,data:i}}else if(r===M.array&&n===M.array){if(t.length!==e.length)return{valid:!1};const a=[];for(let s=0;s<t.length;s++){const i=t[s],o=e[s],c=fs(i,o);if(!c.valid)return{valid:!1};a.push(c.data)}return{valid:!0,data:a}}else return r===M.date&&n===M.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}class mn extends ie{_parse(e){const{status:r,ctx:n}=this._processInputParams(e),a=(s,i)=>{if(Ci(s)||Ci(i))return X;const o=fs(s.value,i.value);return o.valid?((Ni(s)||Ni(i))&&r.dirty(),{status:r.value,value:o.data}):($(n,{code:I.invalid_intersection_types}),X)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([s,i])=>a(s,i)):a(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}}mn.create=(t,e,r)=>new mn({left:t,right:e,typeName:x.ZodIntersection,...ne(r)});class St extends ie{_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==M.array)return $(n,{code:I.invalid_type,expected:M.array,received:n.parsedType}),X;if(n.data.length<this._def.items.length)return $(n,{code:I.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),X;!this._def.rest&&n.data.length>this._def.items.length&&($(n,{code:I.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());const s=[...n.data].map((i,o)=>{const c=this._def.items[o]||this._def.rest;return c?c._parse(new _t(n,i,n.path,o)):null}).filter(i=>!!i);return n.common.async?Promise.all(s).then(i=>Ue.mergeArray(r,i)):Ue.mergeArray(r,s)}get items(){return this._def.items}rest(e){return new St({...this._def,rest:e})}}St.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new St({items:t,typeName:x.ZodTuple,rest:null,...ne(e)})};class gn extends ie{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==M.object)return $(n,{code:I.invalid_type,expected:M.object,received:n.parsedType}),X;const a=[],s=this._def.keyType,i=this._def.valueType;for(const o in n.data)a.push({key:s._parse(new _t(n,o,n.path,o)),value:i._parse(new _t(n,n.data[o],n.path,o)),alwaysSet:o in n.data});return n.common.async?Ue.mergeObjectAsync(r,a):Ue.mergeObjectSync(r,a)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof ie?new gn({keyType:e,valueType:r,typeName:x.ZodRecord,...ne(n)}):new gn({keyType:bt.create(),valueType:e,typeName:x.ZodRecord,...ne(r)})}}class ji extends ie{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==M.map)return $(n,{code:I.invalid_type,expected:M.map,received:n.parsedType}),X;const a=this._def.keyType,s=this._def.valueType,i=[...n.data.entries()].map(([o,c],u)=>({key:a._parse(new _t(n,o,n.path,[u,"key"])),value:s._parse(new _t(n,c,n.path,[u,"value"]))}));if(n.common.async){const o=new Map;return Promise.resolve().then(async()=>{for(const c of i){const u=await c.key,l=await c.value;if(u.status==="aborted"||l.status==="aborted")return X;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),o.set(u.value,l.value)}return{status:r.value,value:o}})}else{const o=new Map;for(const c of i){const u=c.key,l=c.value;if(u.status==="aborted"||l.status==="aborted")return X;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),o.set(u.value,l.value)}return{status:r.value,value:o}}}}ji.create=(t,e,r)=>new ji({valueType:e,keyType:t,typeName:x.ZodMap,...ne(r)});class Pr extends ie{_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==M.set)return $(n,{code:I.invalid_type,expected:M.set,received:n.parsedType}),X;const a=this._def;a.minSize!==null&&n.data.size<a.minSize.value&&($(n,{code:I.too_small,minimum:a.minSize.value,type:"set",inclusive:!0,exact:!1,message:a.minSize.message}),r.dirty()),a.maxSize!==null&&n.data.size>a.maxSize.value&&($(n,{code:I.too_big,maximum:a.maxSize.value,type:"set",inclusive:!0,exact:!1,message:a.maxSize.message}),r.dirty());const s=this._def.valueType;function i(c){const u=new Set;for(const l of c){if(l.status==="aborted")return X;l.status==="dirty"&&r.dirty(),u.add(l.value)}return{status:r.value,value:u}}const o=[...n.data.values()].map((c,u)=>s._parse(new _t(n,c,n.path,u)));return n.common.async?Promise.all(o).then(c=>i(c)):i(o)}min(e,r){return new Pr({...this._def,minSize:{value:e,message:z.toString(r)}})}max(e,r){return new Pr({...this._def,maxSize:{value:e,message:z.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}}Pr.create=(t,e)=>new Pr({valueType:t,minSize:null,maxSize:null,typeName:x.ZodSet,...ne(e)});class Ar extends ie{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:r}=this._processInputParams(e);if(r.parsedType!==M.function)return $(r,{code:I.invalid_type,expected:M.function,received:r.parsedType}),X;function n(o,c){return ls({data:o,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,us(),Cr].filter(u=>!!u),issueData:{code:I.invalid_arguments,argumentsError:c}})}function a(o,c){return ls({data:o,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,us(),Cr].filter(u=>!!u),issueData:{code:I.invalid_return_type,returnTypeError:c}})}const s={errorMap:r.common.contextualErrorMap},i=r.data;if(this._def.returns instanceof Mr){const o=this;return He(async function(...c){const u=new Xe([]),l=await o._def.args.parseAsync(c,s).catch(p=>{throw u.addIssue(n(c,p)),u}),d=await Reflect.apply(i,this,l);return await o._def.returns._def.type.parseAsync(d,s).catch(p=>{throw u.addIssue(a(d,p)),u})})}else{const o=this;return He(function(...c){const u=o._def.args.safeParse(c,s);if(!u.success)throw new Xe([n(c,u.error)]);const l=Reflect.apply(i,this,u.data),d=o._def.returns.safeParse(l,s);if(!d.success)throw new Xe([a(l,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new Ar({...this._def,args:St.create(e).rest(ir.create())})}returns(e){return new Ar({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,n){return new Ar({args:e||St.create([]).rest(ir.create()),returns:r||ir.create(),typeName:x.ZodFunction,...ne(n)})}}class Di extends ie{get schema(){return this._def.getter()}_parse(e){const{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}}Di.create=(t,e)=>new Di({getter:t,typeName:x.ZodLazy,...ne(e)});class ps extends ie{_parse(e){if(e.data!==this._def.value){const r=this._getOrReturnCtx(e);return $(r,{received:r.data,code:I.invalid_literal,expected:this._def.value}),X}return{status:"valid",value:e.data}}get value(){return this._def.value}}ps.create=(t,e)=>new ps({value:t,typeName:x.ZodLiteral,...ne(e)});function Dc(t,e){return new ur({values:t,typeName:x.ZodEnum,...ne(e)})}class ur extends ie{_parse(e){if(typeof e.data!="string"){const r=this._getOrReturnCtx(e),n=this._def.values;return $(r,{expected:ue.joinValues(n),received:r.parsedType,code:I.invalid_type}),X}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const r=this._getOrReturnCtx(e),n=this._def.values;return $(r,{received:r.data,code:I.invalid_enum_value,options:n}),X}return He(e.data)}get options(){return this._def.values}get enum(){const e={};for(const r of this._def.values)e[r]=r;return e}get Values(){const e={};for(const r of this._def.values)e[r]=r;return e}get Enum(){const e={};for(const r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return ur.create(e,{...this._def,...r})}exclude(e,r=this._def){return ur.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}}ur.create=Dc;class Ui extends ie{_parse(e){const r=ue.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==M.string&&n.parsedType!==M.number){const a=ue.objectValues(r);return $(n,{expected:ue.joinValues(a),received:n.parsedType,code:I.invalid_type}),X}if(this._cache||(this._cache=new Set(ue.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const a=ue.objectValues(r);return $(n,{received:n.data,code:I.invalid_enum_value,options:a}),X}return He(e.data)}get enum(){return this._def.values}}Ui.create=(t,e)=>new Ui({values:t,typeName:x.ZodNativeEnum,...ne(e)});class Mr extends ie{unwrap(){return this._def.type}_parse(e){const{ctx:r}=this._processInputParams(e);if(r.parsedType!==M.promise&&r.common.async===!1)return $(r,{code:I.invalid_type,expected:M.promise,received:r.parsedType}),X;const n=r.parsedType===M.promise?r.data:Promise.resolve(r.data);return He(n.then(a=>this._def.type.parseAsync(a,{path:r.path,errorMap:r.common.contextualErrorMap})))}}Mr.create=(t,e)=>new Mr({type:t,typeName:x.ZodPromise,...ne(e)});class lr extends ie{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===x.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:r,ctx:n}=this._processInputParams(e),a=this._def.effect||null,s={addIssue:i=>{$(n,i),i.fatal?r.abort():r.dirty()},get path(){return n.path}};if(s.addIssue=s.addIssue.bind(s),a.type==="preprocess"){const i=a.transform(n.data,s);if(n.common.async)return Promise.resolve(i).then(async o=>{if(r.value==="aborted")return X;const c=await this._def.schema._parseAsync({data:o,path:n.path,parent:n});return c.status==="aborted"?X:c.status==="dirty"||r.value==="dirty"?Sr(c.value):c});{if(r.value==="aborted")return X;const o=this._def.schema._parseSync({data:i,path:n.path,parent:n});return o.status==="aborted"?X:o.status==="dirty"||r.value==="dirty"?Sr(o.value):o}}if(a.type==="refinement"){const i=o=>{const c=a.refinement(o,s);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return o};if(n.common.async===!1){const o=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?X:(o.status==="dirty"&&r.dirty(),i(o.value),{status:r.value,value:o.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(o=>o.status==="aborted"?X:(o.status==="dirty"&&r.dirty(),i(o.value).then(()=>({status:r.value,value:o.value}))))}if(a.type==="transform")if(n.common.async===!1){const i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!or(i))return X;const o=a.transform(i.value,s);if(o instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:o}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(i=>or(i)?Promise.resolve(a.transform(i.value,s)).then(o=>({status:r.value,value:o})):X);ue.assertNever(a)}}lr.create=(t,e,r)=>new lr({schema:t,typeName:x.ZodEffects,effect:e,...ne(r)});lr.createWithPreprocess=(t,e,r)=>new lr({schema:e,effect:{type:"preprocess",transform:t},typeName:x.ZodEffects,...ne(r)});class Nt extends ie{_parse(e){return this._getType(e)===M.undefined?He(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Nt.create=(t,e)=>new Nt({innerType:t,typeName:x.ZodOptional,...ne(e)});class dr extends ie{_parse(e){return this._getType(e)===M.null?He(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}dr.create=(t,e)=>new dr({innerType:t,typeName:x.ZodNullable,...ne(e)});class ms extends ie{_parse(e){const{ctx:r}=this._processInputParams(e);let n=r.data;return r.parsedType===M.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}}ms.create=(t,e)=>new ms({innerType:t,typeName:x.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...ne(e)});class gs extends ie{_parse(e){const{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},a=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return hn(a)?a.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Xe(n.common.issues)},input:n.data})})):{status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new Xe(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}}gs.create=(t,e)=>new gs({innerType:t,typeName:x.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...ne(e)});class Fi extends ie{_parse(e){if(this._getType(e)!==M.nan){const n=this._getOrReturnCtx(e);return $(n,{code:I.invalid_type,expected:M.nan,received:n.parsedType}),X}return{status:"valid",value:e.data}}}Fi.create=t=>new Fi({typeName:x.ZodNaN,...ne(t)});class pd extends ie{_parse(e){const{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}}class Zs extends ie{_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{const s=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?X:s.status==="dirty"?(r.dirty(),Sr(s.value)):this._def.out._parseAsync({data:s.value,path:n.path,parent:n})})();{const a=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?X:a.status==="dirty"?(r.dirty(),{status:"dirty",value:a.value}):this._def.out._parseSync({data:a.value,path:n.path,parent:n})}}static create(e,r){return new Zs({in:e,out:r,typeName:x.ZodPipeline})}}class _s extends ie{_parse(e){const r=this._def.innerType._parse(e),n=a=>(or(a)&&(a.value=Object.freeze(a.value)),a);return hn(r)?r.then(a=>n(a)):n(r)}unwrap(){return this._def.innerType}}_s.create=(t,e)=>new _s({innerType:t,typeName:x.ZodReadonly,...ne(e)});function Bi(t,e){const r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function md(t,e={},r){return t?$r.create().superRefine((n,a)=>{const s=t(n);if(s instanceof Promise)return s.then(i=>{if(!i){const o=Bi(e,n),c=o.fatal??r??!0;a.addIssue({code:"custom",...o,fatal:c})}});if(!s){const i=Bi(e,n),o=i.fatal??r??!0;a.addIssue({code:"custom",...i,fatal:o})}}):$r.create()}var x;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(x||(x={}));const yy=(t,e={message:`Input not instance of ${t.name}`})=>md(r=>r instanceof t,e),Vs=bt.create,vy=cr.create,wy=ds.create,by=hs.create,zi=$r.create;ir.create;Pt.create;const Ey=ft.create,Ws=Ae.create,Ty=pn.create;mn.create;St.create;const Sy=gn.create,Iy=Ar.create,xy=ps.create,Ay=ur.create,Oy=Mr.create;Nt.create;dr.create;var gd=Object.defineProperty,pe=(t,e)=>{for(var r in e)gd(t,r,{get:e[r],enumerable:!0})};function Mt(t){return typeof t=="object"&&t!==null&&"type"in t&&typeof t.type=="string"&&"source_type"in t&&(t.source_type==="url"||t.source_type==="base64"||t.source_type==="text"||t.source_type==="id")}function Js(t){return Mt(t)&&t.source_type==="url"&&"url"in t&&typeof t.url=="string"}function Ks(t){return Mt(t)&&t.source_type==="base64"&&"data"in t&&typeof t.data=="string"}function _d(t){return Mt(t)&&t.source_type==="text"&&"text"in t&&typeof t.text=="string"}function Uc(t){return Mt(t)&&t.source_type==="id"&&"id"in t&&typeof t.id=="string"}function Fc(t){if(Mt(t)){if(t.source_type==="url")return{type:"image_url",image_url:{url:t.url}};if(t.source_type==="base64"){if(!t.mime_type)throw new Error("mime_type key is required for base64 data.");return{type:"image_url",image_url:{url:`data:${t.mime_type};base64,${t.data}`}}}}throw new Error("Unsupported source type. Only 'url' and 'base64' are supported.")}function yd(t){const e=t.split(";")[0].split("/");if(e.length!==2)throw new Error(`Invalid mime type: "${t}" - does not match type/subtype format.`);const r=e[0].trim(),n=e[1].trim();if(r===""||n==="")throw new Error(`Invalid mime type: "${t}" - type or subtype is empty.`);const a={};for(const s of t.split(";").slice(1)){const i=s.split("=");if(i.length!==2)throw new Error(`Invalid parameter syntax in mime type: "${t}".`);const o=i[0].trim(),c=i[1].trim();if(o==="")throw new Error(`Invalid parameter syntax in mime type: "${t}".`);a[o]=c}return{type:r,subtype:n,parameters:a}}function ys({dataUrl:t,asTypedArray:e=!1}){const r=t.match(/^data:(\w+\/\w+);base64,([A-Za-z0-9+/]+=*)$/);let n;if(r){n=r[1].toLowerCase();const a=e?Uint8Array.from(atob(r[2]),s=>s.charCodeAt(0)):r[2];return{mime_type:n,data:a}}}function vd(t,e){if(t.type==="text"){if(!e.fromStandardTextBlock)throw new Error(`Converter for ${e.providerName} does not implement \`fromStandardTextBlock\` method.`);return e.fromStandardTextBlock(t)}if(t.type==="image"){if(!e.fromStandardImageBlock)throw new Error(`Converter for ${e.providerName} does not implement \`fromStandardImageBlock\` method.`);return e.fromStandardImageBlock(t)}if(t.type==="audio"){if(!e.fromStandardAudioBlock)throw new Error(`Converter for ${e.providerName} does not implement \`fromStandardAudioBlock\` method.`);return e.fromStandardAudioBlock(t)}if(t.type==="file"){if(!e.fromStandardFileBlock)throw new Error(`Converter for ${e.providerName} does not implement \`fromStandardFileBlock\` method.`);return e.fromStandardFileBlock(t)}throw new Error(`Unable to convert content block type '${t.type}' to provider-specific format: not recognized.`)}function Bc(t){return typeof t=="object"&&t!==null&&"type"in t&&"content"in t&&(typeof t.content=="string"||Array.isArray(t.content))}var Vn,qi;function wd(){return qi||(qi=1,Vn=function(t,e){if(typeof t!="string")throw new TypeError("Expected a string");return e=typeof e>"u"?"_":e,t.replace(/([a-z\d])([A-Z])/g,"$1"+e+"$2").replace(/([A-Z]+)([A-Z][a-z\d]+)/g,"$1"+e+"$2").toLowerCase()}),Vn}var bd=wd();const Ed=gr(bd);var Yr={exports:{}},Gi;function Td(){if(Gi)return Yr.exports;Gi=1;const t=/[\p{Lu}]/u,e=/[\p{Ll}]/u,r=/^[\p{Lu}](?![\p{Lu}])/gu,n=/([\p{Alpha}\p{N}_]|$)/u,a=/[_.\- ]+/,s=new RegExp("^"+a.source),i=new RegExp(a.source+n.source,"gu"),o=new RegExp("\\d+"+n.source,"gu"),c=(h,p,g)=>{let y=!1,v=!1,b=!1;for(let S=0;S<h.length;S++){const E=h[S];y&&t.test(E)?(h=h.slice(0,S)+"-"+h.slice(S),y=!1,b=v,v=!0,S++):v&&b&&e.test(E)?(h=h.slice(0,S-1)+"-"+h.slice(S-1),b=v,v=!1,y=!0):(y=p(E)===E&&g(E)!==E,b=v,v=g(E)===E&&p(E)!==E)}return h},u=(h,p)=>(r.lastIndex=0,h.replace(r,g=>p(g))),l=(h,p)=>(i.lastIndex=0,o.lastIndex=0,h.replace(i,(g,y)=>p(y)).replace(o,g=>p(g))),d=(h,p)=>{if(!(typeof h=="string"||Array.isArray(h)))throw new TypeError("Expected the input to be `string | string[]`");if(p={pascalCase:!1,preserveConsecutiveUppercase:!1,...p},Array.isArray(h)?h=h.map(b=>b.trim()).filter(b=>b.length).join("-"):h=h.trim(),h.length===0)return"";const g=p.locale===!1?b=>b.toLowerCase():b=>b.toLocaleLowerCase(p.locale),y=p.locale===!1?b=>b.toUpperCase():b=>b.toLocaleUpperCase(p.locale);return h.length===1?p.pascalCase?y(h):g(h):(h!==g(h)&&(h=c(h,g,y)),h=h.replace(s,""),p.preserveConsecutiveUppercase?h=u(h,g):h=g(h),p.pascalCase&&(h=y(h.charAt(0))+h.slice(1)),l(h,y))};return Yr.exports=d,Yr.exports.default=d,Yr.exports}var Sd=Td();const Id=gr(Sd);function xd(t,e){return e?.[t]||Ed(t)}function ky(t,e){return e?.[t]||Id(t)}function Ad(t,e,r){const n={};for(const a in t)Object.hasOwn(t,a)&&(n[e(a,r)]=t[a]);return n}var Od={};pe(Od,{Serializable:()=>hr,get_lc_unique_name:()=>Ys});function Hi(t){return Array.isArray(t)?[...t]:{...t}}function kd(t,e){const r=Hi(t);for(const[n,a]of Object.entries(e)){const[s,...i]=n.split(".").reverse();let o=r;for(const c of i.reverse()){if(o[c]===void 0)break;o[c]=Hi(o[c]),o=o[c]}o[s]!==void 0&&(o[s]={lc:1,type:"secret",id:[a]})}return r}function Ys(t){const e=Object.getPrototypeOf(t);return typeof t.lc_name=="function"&&(typeof e.lc_name!="function"||t.lc_name()!==e.lc_name())?t.lc_name():t.name}var hr=class zc{lc_serializable=!1;lc_kwargs;static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,Ys(this.constructor)]}get lc_secrets(){}get lc_attributes(){}get lc_aliases(){}get lc_serializable_keys(){}constructor(e,...r){this.lc_serializable_keys!==void 0?this.lc_kwargs=Object.fromEntries(Object.entries(e||{}).filter(([n])=>this.lc_serializable_keys?.includes(n))):this.lc_kwargs=e??{}}toJSON(){if(!this.lc_serializable)return this.toJSONNotImplemented();if(this.lc_kwargs instanceof zc||typeof this.lc_kwargs!="object"||Array.isArray(this.lc_kwargs))return this.toJSONNotImplemented();const e={},r={},n=Object.keys(this.lc_kwargs).reduce((a,s)=>(a[s]=s in this?this[s]:this.lc_kwargs[s],a),{});for(let a=Object.getPrototypeOf(this);a;a=Object.getPrototypeOf(a))Object.assign(e,Reflect.get(a,"lc_aliases",this)),Object.assign(r,Reflect.get(a,"lc_secrets",this)),Object.assign(n,Reflect.get(a,"lc_attributes",this));return Object.keys(r).forEach(a=>{let s=this,i=n;const[o,...c]=a.split(".").reverse();for(const u of c.reverse()){if(!(u in s)||s[u]===void 0)return;(!(u in i)||i[u]===void 0)&&(typeof s[u]=="object"&&s[u]!=null?i[u]={}:Array.isArray(s[u])&&(i[u]=[])),s=s[u],i=i[u]}o in s&&s[o]!==void 0&&(i[o]=i[o]||s[o])}),{lc:1,type:"constructor",id:this.lc_id,kwargs:Ad(Object.keys(r).length?kd(n,r):n,xd,e)}}toJSONNotImplemented(){return{lc:1,type:"not_implemented",id:this.lc_id}}};function Z(t,e){return te(t)&&t.type===e}function te(t){return typeof t=="object"&&t!==null}function pt(t){return Array.isArray(t)}function L(t){return typeof t=="string"}function at(t){return typeof t=="number"}function Xs(t){return t instanceof Uint8Array}function Zi(t){try{return JSON.parse(t)}catch{return}}const Lr=t=>t();function Rd(t){if(t.type==="char_location"&&L(t.document_title)&&at(t.start_char_index)&&at(t.end_char_index)&&L(t.cited_text)){const{document_title:e,start_char_index:r,end_char_index:n,cited_text:a,...s}=t;return{...s,type:"citation",source:"char",title:e??void 0,startIndex:r,endIndex:n,citedText:a}}if(t.type==="page_location"&&L(t.document_title)&&at(t.start_page_number)&&at(t.end_page_number)&&L(t.cited_text)){const{document_title:e,start_page_number:r,end_page_number:n,cited_text:a,...s}=t;return{...s,type:"citation",source:"page",title:e??void 0,startIndex:r,endIndex:n,citedText:a}}if(t.type==="content_block_location"&&L(t.document_title)&&at(t.start_block_index)&&at(t.end_block_index)&&L(t.cited_text)){const{document_title:e,start_block_index:r,end_block_index:n,cited_text:a,...s}=t;return{...s,type:"citation",source:"block",title:e??void 0,startIndex:r,endIndex:n,citedText:a}}if(t.type==="web_search_result_location"&&L(t.url)&&L(t.title)&&L(t.encrypted_index)&&L(t.cited_text)){const{url:e,title:r,encrypted_index:n,cited_text:a,...s}=t;return{...s,type:"citation",source:"url",url:e,title:r,startIndex:Number(n),endIndex:Number(n),citedText:a}}if(t.type==="search_result_location"&&L(t.source)&&L(t.title)&&at(t.start_block_index)&&at(t.end_block_index)&&L(t.cited_text)){const{source:e,title:r,start_block_index:n,end_block_index:a,cited_text:s,...i}=t;return{...i,type:"citation",source:"search",url:e,title:r??void 0,startIndex:n,endIndex:a,citedText:s}}}function qc(t){if(Z(t,"document")&&te(t.source)&&"type"in t.source){if(t.source.type==="base64"&&L(t.source.media_type)&&L(t.source.data))return{type:"file",mimeType:t.source.media_type,data:t.source.data};if(t.source.type==="url"&&L(t.source.url))return{type:"file",url:t.source.url};if(t.source.type==="file"&&L(t.source.file_id))return{type:"file",fileId:t.source.file_id};if(t.source.type==="text"&&L(t.source.data))return{type:"file",mimeType:String(t.source.media_type??"text/plain"),data:t.source.data}}else if(Z(t,"image")&&te(t.source)&&"type"in t.source){if(t.source.type==="base64"&&L(t.source.media_type)&&L(t.source.data))return{type:"image",mimeType:t.source.media_type,data:t.source.data};if(t.source.type==="url"&&L(t.source.url))return{type:"image",url:t.source.url};if(t.source.type==="file"&&L(t.source.file_id))return{type:"image",fileId:t.source.file_id}}}function Cd(t){function*e(){for(const r of t){const n=qc(r);n?yield n:yield r}}return Array.from(e())}function Vi(t){function*e(){const r=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(const n of r){if(Z(n,"text")&&L(n.text)){const{text:a,citations:s,...i}=n;if(pt(s)&&s.length){const o=s.reduce((c,u)=>{const l=Rd(u);return l?[...c,l]:c},[]);yield{...i,type:"text",text:a,annotations:o};continue}else{yield{...i,type:"text",text:a};continue}}else if(Z(n,"thinking")&&L(n.thinking)){const{thinking:a,signature:s,...i}=n;yield{...i,type:"reasoning",reasoning:a,signature:s};continue}else if(Z(n,"redacted_thinking")){yield{type:"non_standard",value:n};continue}else if(Z(n,"tool_use")&&L(n.name)&&L(n.id)){yield{type:"tool_call",id:n.id,name:n.name,args:n.input};continue}else if(Z(n,"input_json_delta")){if($d(t)&&t.tool_call_chunks?.length){const a=t.tool_call_chunks[0];yield{type:"tool_call_chunk",id:a.id,name:a.name,args:a.args,index:a.index};continue}}else if(Z(n,"server_tool_use")&&L(n.name)&&L(n.id)){const{name:a,id:s}=n;if(a==="web_search"){const i=Lr(()=>{if(typeof n.input=="string")return n.input;if(te(n.input)&&L(n.input.query))return n.input.query;if(L(n.partial_json)){const o=Zi(n.partial_json);if(o?.query)return o.query}return""});yield{id:s,type:"server_tool_call",name:"web_search",args:{query:i}};continue}else if(n.name==="code_execution"){const i=Lr(()=>{if(typeof n.input=="string")return n.input;if(te(n.input)&&L(n.input.code))return n.input.code;if(L(n.partial_json)){const o=Zi(n.partial_json);if(o?.code)return o.code}return""});yield{id:s,type:"server_tool_call",name:"code_execution",args:{code:i}};continue}}else if(Z(n,"web_search_tool_result")&&L(n.tool_use_id)&&pt(n.content)){const{content:a,tool_use_id:s}=n,i=a.reduce((o,c)=>Z(c,"web_search_result")?[...o,c.url]:o,[]);yield{type:"server_tool_call_result",name:"web_search",toolCallId:s,status:"success",output:{urls:i}};continue}else if(Z(n,"code_execution_tool_result")&&L(n.tool_use_id)&&te(n.content)){yield{type:"server_tool_call_result",name:"code_execution",toolCallId:n.tool_use_id,status:"success",output:n.content};continue}else if(Z(n,"mcp_tool_use")){yield{id:n.id,type:"server_tool_call",name:"mcp_tool_use",args:n.input};continue}else if(Z(n,"mcp_tool_result")&&L(n.tool_use_id)&&te(n.content)){yield{type:"server_tool_call_result",name:"mcp_tool_use",toolCallId:n.tool_use_id,status:"success",output:n.content};continue}else if(Z(n,"container_upload")){yield{type:"server_tool_call",name:"container_upload",args:n.input};continue}else if(Z(n,"search_result")){yield{id:n.id,type:"non_standard",value:n};continue}else if(Z(n,"tool_result")){yield{id:n.id,type:"non_standard",value:n};continue}else{const a=qc(n);if(a){yield a;continue}}yield{type:"non_standard",value:n}}}return Array.from(e())}const Nd={translateContent:Vi,translateContentChunk:Vi};function $d(t){return typeof t?._getType=="function"&&typeof t.concat=="function"&&t._getType()==="ai"}function Pd(t){return Js(t)?{type:t.type,mimeType:t.mime_type,url:t.url,metadata:t.metadata}:Ks(t)?{type:t.type,mimeType:t.mime_type??"application/octet-stream",data:t.data,metadata:t.metadata}:Uc(t)?{type:t.type,mimeType:t.mime_type,fileId:t.id,metadata:t.metadata}:t}function Md(t){return t.map(Pd)}function Ld(t){return!!(Z(t,"image_url")&&te(t.image_url)||Z(t,"input_audio")&&te(t.input_audio)||Z(t,"file")&&te(t.file))}function jd(t){if(Z(t,"image_url")&&te(t.image_url)&&L(t.image_url.url)){const e=ys({dataUrl:t.image_url.url});return e?{type:"image",mimeType:e.mime_type,data:e.data}:{type:"image",url:t.image_url.url}}else{if(Z(t,"input_audio")&&te(t.input_audio)&&L(t.input_audio.data)&&L(t.input_audio.format))return{type:"audio",data:t.input_audio.data,mimeType:`audio/${t.input_audio.format}`};if(Z(t,"file")&&te(t.file)&&L(t.file.data)){const e=ys({dataUrl:t.file.data});if(e)return{type:"file",data:e.data,mimeType:e.mime_type};if(L(t.file.file_id))return{type:"file",fileId:t.file.file_id}}}return t}function Dd(t){const e=[];typeof t.content=="string"?e.push({type:"text",text:t.content}):e.push(...Qs(t.content));for(const r of t.tool_calls??[])e.push({type:"tool_call",id:r.id,name:r.name,args:r.args});return e}function Ud(t){const e=[];typeof t.content=="string"?e.push({type:"text",text:t.content}):e.push(...Qs(t.content));for(const r of t.tool_calls??[])e.push({type:"tool_call",id:r.id,name:r.name,args:r.args});return e}function Qs(t){const e=[];for(const r of t)Ld(r)?e.push(jd(r)):e.push(r);return e}function Fd(t){if(t.type==="url_citation"){const{url:e,title:r,start_index:n,end_index:a}=t;return{type:"citation",url:e,title:r,startIndex:n,endIndex:a}}if(t.type==="file_citation"){const{file_id:e,filename:r,index:n}=t;return{type:"citation",title:r,startIndex:n,endIndex:n,fileId:e}}return t}function Gc(t){function*e(){te(t.additional_kwargs?.reasoning)&&pt(t.additional_kwargs.reasoning.summary)&&(yield{type:"reasoning",reasoning:t.additional_kwargs.reasoning.summary.reduce((a,s)=>te(s)&&L(s.text)?`${a}${s.text}`:a,"")});const r=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(const n of r)if(Z(n,"text")){const{text:a,annotations:s,...i}=n;Array.isArray(s)?yield{...i,type:"text",text:String(a),annotations:s.map(Fd)}:yield{...i,type:"text",text:String(a)}}for(const n of t.tool_calls??[])yield{type:"tool_call",id:n.id,name:n.name,args:n.args};if(te(t.additional_kwargs)&&pt(t.additional_kwargs.tool_outputs))for(const n of t.additional_kwargs.tool_outputs){if(Z(n,"web_search_call")){yield{id:n.id,type:"server_tool_call",name:"web_search",args:{query:n.query}};continue}else if(Z(n,"file_search_call")){yield{id:n.id,type:"server_tool_call",name:"file_search",args:{query:n.query}};continue}else if(Z(n,"computer_call")){yield{type:"non_standard",value:n};continue}else if(Z(n,"code_interpreter_call")){if(L(n.code)&&(yield{id:n.id,type:"server_tool_call",name:"code_interpreter",args:{code:n.code}}),pt(n.outputs)){const a=Lr(()=>{if(n.status!=="in_progress"){if(n.status==="completed")return 0;if(n.status==="incomplete")return 127;if(n.status!=="interpreting"&&n.status==="failed")return 1}});for(const s of n.outputs)if(Z(s,"logs")){yield{type:"server_tool_call_result",toolCallId:n.id??"",status:"success",output:{type:"code_interpreter_output",returnCode:a??0,stderr:[0,void 0].includes(a)?void 0:String(s.logs),stdout:[0,void 0].includes(a)?String(s.logs):void 0}};continue}}continue}else if(Z(n,"mcp_call")){yield{id:n.id,type:"server_tool_call",name:"mcp_call",args:n.input};continue}else if(Z(n,"mcp_list_tools")){yield{id:n.id,type:"server_tool_call",name:"mcp_list_tools",args:n.input};continue}else if(Z(n,"mcp_approval_request")){yield{type:"non_standard",value:n};continue}else if(Z(n,"image_generation_call")){yield{type:"non_standard",value:n};continue}te(n)&&(yield{type:"non_standard",value:n})}}return Array.from(e())}function Bd(t){function*e(){yield*Gc(t);for(const r of t.tool_call_chunks??[])yield{type:"tool_call_chunk",id:r.id,name:r.name,args:r.args}}return Array.from(e())}const zd={translateContent:t=>typeof t.content=="string"?Dd(t):Gc(t),translateContentChunk:t=>typeof t.content=="string"?Ud(t):Bd(t)};function qd(t,e="pretty"){return e==="pretty"?Gd(t):JSON.stringify(t)}function Gd(t){const e=[],r=` ${t.type.charAt(0).toUpperCase()+t.type.slice(1)} Message `,n=Math.floor((80-r.length)/2),a="=".repeat(n),s=r.length%2===0?a:`${a}=`;if(e.push(`${a}${r}${s}`),t.type==="ai"){const i=t;if(i.tool_calls&&i.tool_calls.length>0){e.push("Tool Calls:");for(const o of i.tool_calls){e.push(` ${o.name} (${o.id})`),e.push(` Call ID: ${o.id}`),e.push(" Args:");for(const[c,u]of Object.entries(o.args))e.push(` ${c}: ${u}`)}}}if(t.type==="tool"){const i=t;i.name&&e.push(`Name: ${i.name}`)}return typeof t.content=="string"&&t.content.trim()&&(e.length>1&&e.push(""),e.push(t.content)),e.join(`
|
|
2
|
-
`)}const Wn=Symbol.for("langchain.message");function Jt(t,e){return typeof t=="string"?t===""?e:typeof e=="string"?t+e:Array.isArray(e)&&e.some(r=>Mt(r))?[{type:"text",source_type:"text",text:t},...e]:[{type:"text",text:t},...e]:Array.isArray(e)?zr(t,e)??[...t,...e]:e===""?t:Array.isArray(t)&&t.some(r=>Mt(r))?[...t,{type:"file",source_type:"text",text:e}]:[...t,{type:"text",text:e}]}function Hc(t,e){return t==="error"||e==="error"?"error":"success"}function Hd(t,e){function r(n,a){if(typeof n!="object"||n===null||n===void 0)return n;if(a>=e)return Array.isArray(n)?"[Array]":"[Object]";if(Array.isArray(n))return n.map(i=>r(i,a+1));const s={};for(const i of Object.keys(n))s[i]=r(n[i],a+1);return s}return JSON.stringify(r(t,0),null,2)}var xt=class extends hr{lc_namespace=["langchain_core","messages"];lc_serializable=!0;get lc_aliases(){return{additional_kwargs:"additional_kwargs",response_metadata:"response_metadata"}}[Wn]=!0;id;name;content;additional_kwargs;response_metadata;_getType(){return this.type}getType(){return this._getType()}constructor(t){const e=typeof t=="string"||Array.isArray(t)?{content:t}:t;e.additional_kwargs||(e.additional_kwargs={}),e.response_metadata||(e.response_metadata={}),super(e),this.name=e.name,e.content===void 0&&e.contentBlocks!==void 0?(this.content=e.contentBlocks,this.response_metadata={output_version:"v1",...e.response_metadata}):e.content!==void 0?(this.content=e.content??[],this.response_metadata=e.response_metadata):(this.content=[],this.response_metadata=e.response_metadata),this.additional_kwargs=e.additional_kwargs,this.id=e.id}get text(){return typeof this.content=="string"?this.content:Array.isArray(this.content)?this.content.map(t=>typeof t=="string"?t:t.type==="text"?t.text:"").join(""):""}get contentBlocks(){const t=typeof this.content=="string"?[{type:"text",text:this.content}]:this.content;return[Md,Qs,Cd].reduce((n,a)=>a(n),t)}toDict(){return{type:this.getType(),data:this.toJSON().kwargs}}static lc_name(){return"BaseMessage"}get _printableFields(){return{id:this.id,content:this.content,name:this.name,additional_kwargs:this.additional_kwargs,response_metadata:this.response_metadata}}static isInstance(t){return typeof t=="object"&&t!==null&&Wn in t&&t[Wn]===!0&&Bc(t)}_updateId(t){this.id=t,this.lc_kwargs.id=t}get[Symbol.toStringTag](){return this.constructor.lc_name()}[Symbol.for("nodejs.util.inspect.custom")](t){if(t===null)return this;const e=Hd(this._printableFields,Math.max(4,t));return`${this.constructor.lc_name()} ${e}`}toFormattedString(t="pretty"){return qd(this,t)}};function Zd(t){return Array.isArray(t)&&t.every(e=>typeof e.index=="number")}function Me(t={},e={}){const r={...t};for(const[n,a]of Object.entries(e))if(r[n]==null)r[n]=a;else{if(a==null)continue;if(typeof r[n]!=typeof a||Array.isArray(r[n])!==Array.isArray(a))throw new Error(`field[${n}] already exists in the message chunk, but with a different type.`);if(typeof r[n]=="string"){if(n==="type")continue;["id","name","output_version","model_provider"].includes(n)?r[n]=a:r[n]+=a}else if(typeof r[n]=="object"&&!Array.isArray(r[n]))r[n]=Me(r[n],a);else if(Array.isArray(r[n]))r[n]=zr(r[n],a);else{if(r[n]===a)continue;console.warn(`field[${n}] already exists in this message chunk and value has unsupported type.`)}}return r}function zr(t,e){if(!(t===void 0&&e===void 0)){if(t===void 0||e===void 0)return t||e;{const r=[...t];for(const n of e)if(typeof n=="object"&&n!==null&&"index"in n&&typeof n.index=="number"){const a=r.findIndex(s=>{const i=typeof s=="object",o="index"in s&&s.index===n.index,c="id"in s&&"id"in n&&s?.id===n?.id,u=!("id"in s)||!s?.id||!("id"in n)||!n?.id;return i&&o&&(c||u)});a!==-1&&typeof r[a]=="object"&&r[a]!==null?r[a]=Me(r[a],n):r.push(n)}else{if(typeof n=="object"&&n!==null&&"text"in n&&n.text==="")continue;r.push(n)}return r}}}function Zc(t,e){if(!t&&!e)throw new Error("Cannot merge two undefined objects.");if(!t||!e)return t||e;if(typeof t!=typeof e)throw new Error(`Cannot merge objects of different types.
|
|
3
|
-
Left ${typeof t}
|
|
4
|
-
Right ${typeof e}`);if(typeof t=="string"&&typeof e=="string")return t+e;if(Array.isArray(t)&&Array.isArray(e))return zr(t,e);if(typeof t=="object"&&typeof e=="object")return Me(t,e);if(t===e)return t;throw new Error(`Can not merge objects of different types.
|
|
5
|
-
Left ${t}
|
|
6
|
-
Right ${e}`)}var Kt=class extends xt{static isInstance(t){return super.isInstance(t)&&"concat"in t&&typeof t.concat=="function"}};function Vc(t){return typeof t.role=="string"}function Et(t){return typeof t?._getType=="function"}function ei(t){return Et(t)&&typeof t.concat=="function"}function Wc(t,e){return Me(t??{},e??{})}function Jc(t,e){const r={};return(t?.audio!==void 0||e?.audio!==void 0)&&(r.audio=(t?.audio??0)+(e?.audio??0)),(t?.image!==void 0||e?.image!==void 0)&&(r.image=(t?.image??0)+(e?.image??0)),(t?.video!==void 0||e?.video!==void 0)&&(r.video=(t?.video??0)+(e?.video??0)),(t?.document!==void 0||e?.document!==void 0)&&(r.document=(t?.document??0)+(e?.document??0)),(t?.text!==void 0||e?.text!==void 0)&&(r.text=(t?.text??0)+(e?.text??0)),r}function Vd(t,e){const r={...Jc(t,e)};return(t?.cache_read!==void 0||e?.cache_read!==void 0)&&(r.cache_read=(t?.cache_read??0)+(e?.cache_read??0)),(t?.cache_creation!==void 0||e?.cache_creation!==void 0)&&(r.cache_creation=(t?.cache_creation??0)+(e?.cache_creation??0)),r}function Wd(t,e){const r={...Jc(t,e)};return(t?.reasoning!==void 0||e?.reasoning!==void 0)&&(r.reasoning=(t?.reasoning??0)+(e?.reasoning??0)),r}function Kc(t,e){return{input_tokens:(t?.input_tokens??0)+(e?.input_tokens??0),output_tokens:(t?.output_tokens??0)+(e?.output_tokens??0),total_tokens:(t?.total_tokens??0)+(e?.total_tokens??0),input_token_details:Vd(t?.input_token_details,e?.input_token_details),output_token_details:Wd(t?.output_token_details,e?.output_token_details)}}var Jd={};pe(Jd,{ToolMessage:()=>_r,ToolMessageChunk:()=>kn,defaultToolCallParser:()=>ti,isDirectToolOutput:()=>Yc,isToolMessage:()=>Xc,isToolMessageChunk:()=>Qc});function Yc(t){return t!=null&&typeof t=="object"&&"lc_direct_tool_output"in t&&t.lc_direct_tool_output===!0}var _r=class extends xt{static lc_name(){return"ToolMessage"}get lc_aliases(){return{tool_call_id:"tool_call_id"}}lc_direct_tool_output=!0;type="tool";status;tool_call_id;metadata;artifact;constructor(t,e,r){const n=typeof t=="string"||Array.isArray(t)?{content:t,name:r,tool_call_id:e}:t;super(n),this.tool_call_id=n.tool_call_id,this.artifact=n.artifact,this.status=n.status,this.metadata=n.metadata}static isInstance(t){return super.isInstance(t)&&t.type==="tool"}get _printableFields(){return{...super._printableFields,tool_call_id:this.tool_call_id,artifact:this.artifact}}},kn=class extends Kt{type="tool";tool_call_id;status;artifact;constructor(t){super(t),this.tool_call_id=t.tool_call_id,this.artifact=t.artifact,this.status=t.status}static lc_name(){return"ToolMessageChunk"}concat(t){const e=this.constructor;return new e({content:Jt(this.content,t.content),additional_kwargs:Me(this.additional_kwargs,t.additional_kwargs),response_metadata:Me(this.response_metadata,t.response_metadata),artifact:Zc(this.artifact,t.artifact),tool_call_id:this.tool_call_id,id:this.id??t.id,status:Hc(this.status,t.status)})}get _printableFields(){return{...super._printableFields,tool_call_id:this.tool_call_id,artifact:this.artifact}}};function ti(t){const e=[],r=[];for(const n of t)if(n.function){const a=n.function.name;try{const s=JSON.parse(n.function.arguments);e.push({name:a||"",args:s||{},id:n.id})}catch{r.push({name:a,args:n.function.arguments,id:n.id,error:"Malformed args."})}}else continue;return[e,r]}function Xc(t){return typeof t=="object"&&t!==null&&"getType"in t&&typeof t.getType=="function"&&t.getType()==="tool"}function Qc(t){return t._getType()==="tool"}function vs(t,e=ri){t=t.trim();const r=t.indexOf("```");if(r===-1)return e(t);let n=t.substring(r+3);n.startsWith(`json
|
|
7
|
-
`)?n=n.substring(5):n.startsWith("json")?n=n.substring(4):n.startsWith(`
|
|
8
|
-
`)&&(n=n.substring(1));const a=n.indexOf("```");let s=n;return a!==-1&&(s=n.substring(0,a)),e(s.trim())}function ri(t){if(typeof t>"u")return null;try{return JSON.parse(t)}catch{}let e="";const r=[];let n=!1,a=!1;for(let s of t){if(n)s==='"'&&!a?n=!1:s===`
|
|
9
|
-
`&&!a?s="\\n":s==="\\"?a=!a:a=!1;else if(s==='"')n=!0,a=!1;else if(s==="{")r.push("}");else if(s==="[")r.push("]");else if(s==="}"||s==="]")if(r&&r[r.length-1]===s)r.pop();else return null;e+=s}n&&(e+='"');for(let s=r.length-1;s>=0;s-=1)e+=r[s];try{return JSON.parse(e)}catch{return null}}function ni(t){switch(t){case"csv":return"text/csv";case"doc":return"application/vnd.openxmlformats-officedocument.wordprocessingml.document";case"docx":return"application/vnd.openxmlformats-officedocument.wordprocessingml.document";case"html":return"text/html";case"md":return"text/markdown";case"pdf":return"application/pdf";case"txt":return"text/plain";case"xls":return"application/vnd.ms-excel";case"xlsx":return"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";case"gif":return"image/gif";case"jpeg":return"image/jpeg";case"jpg":return"image/jpeg";case"png":return"image/png";case"webp":return"image/webp";case"flv":return"video/flv";case"mkv":return"video/mkv";case"mov":return"video/mov";case"mp4":return"video/mp4";case"mpeg":return"video/mpeg";case"mpg":return"video/mpg";case"three_gp":return"video/three_gp";case"webm":return"video/webm";case"wmv":return"video/wmv";default:return"application/octet-stream"}}function Kd(t){if(te(t.document)&&te(t.document.source)){const e=te(t.document)&&L(t.document.format)?t.document.format:"",r=ni(e);if(te(t.document.source)){if(te(t.document.source.s3Location)&&L(t.document.source.s3Location.uri))return{type:"file",mimeType:r,fileId:t.document.source.s3Location.uri};if(Xs(t.document.source.bytes))return{type:"file",mimeType:r,data:t.document.source.bytes};if(L(t.document.source.text))return{type:"file",mimeType:r,data:Buffer.from(t.document.source.text).toString("base64")};if(pt(t.document.source.content)){const n=t.document.source.content.reduce((a,s)=>te(s)&&L(s.text)?a+s.text:a,"");return{type:"file",mimeType:r,data:n}}}}return{type:"non_standard",value:t}}function Yd(t){if(Z(t,"image")&&te(t.image)){const e=te(t.image)&&L(t.image.format)?t.image.format:"",r=ni(e);if(te(t.image.source)){if(te(t.image.source.s3Location)&&L(t.image.source.s3Location.uri))return{type:"image",mimeType:r,fileId:t.image.source.s3Location.uri};if(Xs(t.image.source.bytes))return{type:"image",mimeType:r,data:t.image.source.bytes}}}return{type:"non_standard",value:t}}function Xd(t){if(Z(t,"video")&&te(t.video)){const e=te(t.video)&&L(t.video.format)?t.video.format:"",r=ni(e);if(te(t.video.source)){if(te(t.video.source.s3Location)&&L(t.video.source.s3Location.uri))return{type:"video",mimeType:r,fileId:t.video.source.s3Location.uri};if(Xs(t.video.source.bytes))return{type:"video",mimeType:r,data:t.video.source.bytes}}}return{type:"non_standard",value:t}}function Wi(t){function*e(){const r=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(const n of r){if(Z(n,"cache_point")){yield{type:"non_standard",value:n};continue}else if(Z(n,"citations_content")&&te(n.citationsContent)){const a=pt(n.citationsContent.content)?n.citationsContent.content.reduce((i,o)=>te(o)&&L(o.text)?i+o.text:i,""):"",s=pt(n.citationsContent.citations)?n.citationsContent.citations.reduce((i,o)=>{if(te(o)){const c=pt(o.sourceContent)?o.sourceContent.reduce((l,d)=>te(d)&&L(d.text)?l+d.text:l,""):"",u=Lr(()=>{if(te(o.location)){const l=o.location.documentChar||o.location.documentPage||o.location.documentChunk;if(te(l))return{source:at(l.documentIndex)?l.documentIndex.toString():void 0,startIndex:at(l.start)?l.start:void 0,endIndex:at(l.end)?l.end:void 0}}return{}});i.push({type:"citation",citedText:c,...u})}return i},[]):[];yield{type:"text",text:a,annotations:s};continue}else if(Z(n,"document")&&te(n.document)){yield Kd(n);continue}else if(Z(n,"guard_content")){yield{type:"non_standard",value:n};continue}else if(Z(n,"image")&&te(n.image)){yield Yd(n);continue}else if(Z(n,"reasoning_content")&&L(n.reasoningText)){yield{type:"reasoning",reasoning:n.reasoningText};continue}else if(Z(n,"text")&&L(n.text)){yield{type:"text",text:n.text};continue}else if(Z(n,"tool_result")){yield{type:"non_standard",value:n};continue}else{if(Z(n,"tool_call"))continue;if(Z(n,"video")&&te(n.video)){yield Xd(n);continue}}yield{type:"non_standard",value:n}}}return Array.from(e())}const Qd={translateContent:Wi,translateContentChunk:Wi};function Ji(t){function*e(){const r=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(const n of r){if(Z(n,"text")&&L(n.text)){yield{type:"text",text:n.text};continue}else if(Z(n,"inlineData")&&te(n.inlineData)&&L(n.inlineData.mimeType)&&L(n.inlineData.data)){yield{type:"file",mimeType:n.inlineData.mimeType,data:n.inlineData.data};continue}else if(Z(n,"functionCall")&&te(n.functionCall)&&L(n.functionCall.name)&&te(n.functionCall.args)){yield{type:"tool_call",id:t.id,name:n.functionCall.name,args:n.functionCall.args};continue}else if(Z(n,"functionResponse")){yield{type:"non_standard",value:n};continue}else if(Z(n,"fileData")&&te(n.fileData)&&L(n.fileData.mimeType)&&L(n.fileData.fileUri)){yield{type:"file",mimeType:n.fileData.mimeType,fileId:n.fileData.fileUri};continue}else if(Z(n,"executableCode")){yield{type:"non_standard",value:n};continue}else if(Z(n,"codeExecutionResult")){yield{type:"non_standard",value:n};continue}yield{type:"non_standard",value:n}}}return Array.from(e())}const eh={translateContent:Ji,translateContentChunk:Ji};function Ki(t){function*e(){const r=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(const n of r){if(Z(n,"reasoning")&&L(n.reasoning)){const a=Lr(()=>{const s=r.indexOf(n);if(pt(t.additional_kwargs?.signatures)&&s>=0)return t.additional_kwargs.signatures.at(s)});L(a)?yield{type:"reasoning",reasoning:n.reasoning,signature:a}:yield{type:"reasoning",reasoning:n.reasoning};continue}else if(Z(n,"text")&&L(n.text)){yield{type:"text",text:n.text};continue}else if(Z(n,"image_url")){if(L(n.image_url))if(n.image_url.startsWith("data:")){const a=/^data:([^;]+);base64,(.+)$/,s=n.image_url.match(a);s?yield{type:"image",data:s[2],mimeType:s[1]}:yield{type:"image",url:n.image_url}}else yield{type:"image",url:n.image_url};continue}else if(Z(n,"media")&&L(n.mimeType)&&L(n.data)){yield{type:"file",mimeType:n.mimeType,data:n.data};continue}yield{type:"non_standard",value:n}}}return Array.from(e())}const th={translateContent:Ki,translateContentChunk:Ki};globalThis.lc_block_translators_registry??=new Map([["anthropic",Nd],["bedrock-converse",Qd],["google-genai",eh],["google-vertexai",th],["openai",zd]]);function eu(t){return globalThis.lc_block_translators_registry.get(t)}var Lt=class extends xt{type="ai";tool_calls=[];invalid_tool_calls=[];usage_metadata;get lc_aliases(){return{...super.lc_aliases,tool_calls:"tool_calls",invalid_tool_calls:"invalid_tool_calls"}}constructor(t){let e;if(typeof t=="string"||Array.isArray(t))e={content:t,tool_calls:[],invalid_tool_calls:[],additional_kwargs:{}};else{e=t;const r=e.additional_kwargs?.tool_calls,n=e.tool_calls;r!=null&&r.length>0&&(n===void 0||n.length===0)&&console.warn(["New LangChain packages are available that more efficiently handle",`tool calling.
|
|
10
|
-
|
|
11
|
-
Please upgrade your packages to versions that set`,"message tool calls. e.g., `pnpm install @langchain/anthropic`,","pnpm install @langchain/openai`, etc."].join(" "));try{if(r!=null&&n===void 0){const[a,s]=ti(r);e.tool_calls=a??[],e.invalid_tool_calls=s??[]}else e.tool_calls=e.tool_calls??[],e.invalid_tool_calls=e.invalid_tool_calls??[]}catch{e.tool_calls=[],e.invalid_tool_calls=[]}if(e.response_metadata!==void 0&&"output_version"in e.response_metadata&&e.response_metadata.output_version==="v1"&&(e.contentBlocks=e.content,e.content=void 0),e.contentBlocks!==void 0){e.contentBlocks.push(...e.tool_calls.map(s=>({type:"tool_call",id:s.id,name:s.name,args:s.args})));const a=e.contentBlocks.filter(s=>s.type==="tool_call").filter(s=>!e.tool_calls?.some(i=>i.id===s.id&&i.name===s.name));a.length>0&&(e.tool_calls=a.map(s=>({type:"tool_call",id:s.id,name:s.name,args:s.args})))}}super(e),typeof e!="string"&&(this.tool_calls=e.tool_calls??this.tool_calls,this.invalid_tool_calls=e.invalid_tool_calls??this.invalid_tool_calls),this.usage_metadata=e.usage_metadata}static lc_name(){return"AIMessage"}get contentBlocks(){if(this.response_metadata&&"output_version"in this.response_metadata&&this.response_metadata.output_version==="v1")return this.content;if(this.response_metadata&&"model_provider"in this.response_metadata&&typeof this.response_metadata.model_provider=="string"){const e=eu(this.response_metadata.model_provider);if(e)return e.translateContent(this)}const t=super.contentBlocks;if(this.tool_calls){const e=this.tool_calls.filter(r=>!t.some(n=>n.id===r.id&&n.name===r.name));t.push(...e.map(r=>({...r,type:"tool_call",id:r.id,name:r.name,args:r.args})))}return t}get _printableFields(){return{...super._printableFields,tool_calls:this.tool_calls,invalid_tool_calls:this.invalid_tool_calls,usage_metadata:this.usage_metadata}}static isInstance(t){return super.isInstance(t)&&t.type==="ai"}};function tu(t){return t._getType()==="ai"}function ws(t){return t._getType()==="ai"}var Yt=class extends Kt{type="ai";tool_calls=[];invalid_tool_calls=[];tool_call_chunks=[];usage_metadata;constructor(t){let e;if(typeof t=="string"||Array.isArray(t))e={content:t,tool_calls:[],invalid_tool_calls:[],tool_call_chunks:[]};else if(t.tool_call_chunks===void 0||t.tool_call_chunks.length===0)e={...t,tool_calls:t.tool_calls??[],invalid_tool_calls:[],tool_call_chunks:[],usage_metadata:t.usage_metadata!==void 0?t.usage_metadata:void 0};else{const n=(t.tool_call_chunks??[]).reduce((i,o)=>{const c=i.findIndex(([u])=>"id"in o&&o.id&&"index"in o&&o.index!==void 0?o.id===u.id&&o.index===u.index:"id"in o&&o.id?o.id===u.id:"index"in o&&o.index!==void 0?o.index===u.index:!1);return c!==-1?i[c].push(o):i.push([o]),i},[]),a=[],s=[];for(const i of n){let o=null;const c=i[0]?.name??"",u=i.map(h=>h.args||"").join(""),l=u.length?u:"{}",d=i[0]?.id;try{if(o=ri(l),!d||o===null||typeof o!="object"||Array.isArray(o))throw new Error("Malformed tool call chunk args.");a.push({name:c,args:o,id:d,type:"tool_call"})}catch{s.push({name:c,args:l,id:d,error:"Malformed args.",type:"invalid_tool_call"})}}e={...t,tool_calls:a,invalid_tool_calls:s,usage_metadata:t.usage_metadata!==void 0?t.usage_metadata:void 0}}super(e),this.tool_call_chunks=e.tool_call_chunks??this.tool_call_chunks,this.tool_calls=e.tool_calls??this.tool_calls,this.invalid_tool_calls=e.invalid_tool_calls??this.invalid_tool_calls,this.usage_metadata=e.usage_metadata}get lc_aliases(){return{...super.lc_aliases,tool_calls:"tool_calls",invalid_tool_calls:"invalid_tool_calls",tool_call_chunks:"tool_call_chunks"}}static lc_name(){return"AIMessageChunk"}get contentBlocks(){if(this.response_metadata&&"output_version"in this.response_metadata&&this.response_metadata.output_version==="v1")return this.content;if(this.response_metadata&&"model_provider"in this.response_metadata&&typeof this.response_metadata.model_provider=="string"){const e=eu(this.response_metadata.model_provider);if(e)return e.translateContent(this)}const t=super.contentBlocks;if(this.tool_calls&&typeof this.content!="string"){const e=this.content.filter(r=>r.type==="tool_call").map(r=>r.id);for(const r of this.tool_calls)r.id&&!e.includes(r.id)&&t.push({...r,type:"tool_call",id:r.id,name:r.name,args:r.args})}return t}get _printableFields(){return{...super._printableFields,tool_calls:this.tool_calls,tool_call_chunks:this.tool_call_chunks,invalid_tool_calls:this.invalid_tool_calls,usage_metadata:this.usage_metadata}}concat(t){const e={content:Jt(this.content,t.content),additional_kwargs:Me(this.additional_kwargs,t.additional_kwargs),response_metadata:Wc(this.response_metadata,t.response_metadata),tool_call_chunks:[],id:this.id??t.id};if(this.tool_call_chunks!==void 0||t.tool_call_chunks!==void 0){const n=zr(this.tool_call_chunks,t.tool_call_chunks);n!==void 0&&n.length>0&&(e.tool_call_chunks=n)}(this.usage_metadata!==void 0||t.usage_metadata!==void 0)&&(e.usage_metadata=Kc(this.usage_metadata,t.usage_metadata));const r=this.constructor;return new r(e)}static isInstance(t){return super.isInstance(t)&&t.type==="ai"}},qr=class ru extends xt{static lc_name(){return"ChatMessage"}type="generic";role;static _chatMessageClass(){return ru}constructor(e,r){(typeof e=="string"||Array.isArray(e))&&(e={content:e,role:r}),super(e),this.role=e.role}static isInstance(e){return super.isInstance(e)&&e.type==="generic"}get _printableFields(){return{...super._printableFields,role:this.role}}},Rn=class extends Kt{static lc_name(){return"ChatMessageChunk"}type="generic";role;constructor(t,e){(typeof t=="string"||Array.isArray(t))&&(t={content:t,role:e}),super(t),this.role=t.role}concat(t){const e=this.constructor;return new e({content:Jt(this.content,t.content),additional_kwargs:Me(this.additional_kwargs,t.additional_kwargs),response_metadata:Me(this.response_metadata,t.response_metadata),role:this.role,id:this.id??t.id})}static isInstance(t){return super.isInstance(t)&&t.type==="generic"}get _printableFields(){return{...super._printableFields,role:this.role}}};function rh(t){return t._getType()==="generic"}function nh(t){return t._getType()==="generic"}var Cn=class extends xt{static lc_name(){return"FunctionMessage"}type="function";name;constructor(t){super(t),this.name=t.name}},Nn=class extends Kt{static lc_name(){return"FunctionMessageChunk"}type="function";concat(t){const e=this.constructor;return new e({content:Jt(this.content,t.content),additional_kwargs:Me(this.additional_kwargs,t.additional_kwargs),response_metadata:Me(this.response_metadata,t.response_metadata),name:this.name??"",id:this.id??t.id})}};function ah(t){return t._getType()==="function"}function sh(t){return t._getType()==="function"}var At=class extends xt{static lc_name(){return"HumanMessage"}type="human";constructor(t){super(t)}static isInstance(t){return super.isInstance(t)&&t.type==="human"}},$n=class extends Kt{static lc_name(){return"HumanMessageChunk"}type="human";constructor(t){super(t)}concat(t){const e=this.constructor;return new e({content:Jt(this.content,t.content),additional_kwargs:Me(this.additional_kwargs,t.additional_kwargs),response_metadata:Me(this.response_metadata,t.response_metadata),id:this.id??t.id})}static isInstance(t){return super.isInstance(t)&&t.type==="human"}};function ih(t){return t.getType()==="human"}function oh(t){return t.getType()==="human"}var jt=class extends xt{static lc_name(){return"SystemMessage"}type="system";constructor(t){super(t)}static isInstance(t){return super.isInstance(t)&&t.type==="system"}},fr=class extends Kt{static lc_name(){return"SystemMessageChunk"}type="system";constructor(t){super(t)}concat(t){const e=this.constructor;return new e({content:Jt(this.content,t.content),additional_kwargs:Me(this.additional_kwargs,t.additional_kwargs),response_metadata:Me(this.response_metadata,t.response_metadata),id:this.id??t.id})}static isInstance(t){return super.isInstance(t)&&t.type==="system"}};function ch(t){return t._getType()==="system"}function uh(t){return t._getType()==="system"}var _n=class extends xt{type="remove";id;constructor(t){super({...t,content:[]}),this.id=t.id}get _printableFields(){return{...super._printableFields,id:this.id}}static isInstance(t){return super.isInstance(t)&&t.type==="remove"}};function nu(t,e){return t.lc_error_code=e,t.message=`${t.message}
|
|
12
|
-
|
|
13
|
-
Troubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${e}/
|
|
14
|
-
`,t}function au(t){return!!(t&&typeof t=="object"&&"type"in t&&t.type==="tool_call")}function Ry(t){return!!(t&&typeof t=="object"&&"toolCall"in t&&t.toolCall!=null&&typeof t.toolCall=="object"&&"id"in t.toolCall&&typeof t.toolCall.id=="string")}var lh=class extends Error{output;constructor(t,e){super(t),this.output=e}};const dh=t=>t();function hh(t){return au(t)?t:typeof t.id=="string"&&t.type==="function"&&typeof t.function=="object"&&t.function!==null&&"arguments"in t.function&&typeof t.function.arguments=="string"&&"name"in t.function&&typeof t.function.name=="string"?{id:t.id,args:JSON.parse(t.function.arguments),name:t.function.name,type:"tool_call"}:t}function fh(t){return typeof t=="object"&&t!=null&&t.lc===1&&Array.isArray(t.id)&&t.kwargs!=null&&typeof t.kwargs=="object"}function Jn(t){let e,r;if(fh(t)){const n=t.id.at(-1);n==="HumanMessage"||n==="HumanMessageChunk"?e="user":n==="AIMessage"||n==="AIMessageChunk"?e="assistant":n==="SystemMessage"||n==="SystemMessageChunk"?e="system":n==="FunctionMessage"||n==="FunctionMessageChunk"?e="function":n==="ToolMessage"||n==="ToolMessageChunk"?e="tool":e="unknown",r=t.kwargs}else{const{type:n,...a}=t;e=n,r=a}if(e==="human"||e==="user")return new At(r);if(e==="ai"||e==="assistant"){const{tool_calls:n,...a}=r;if(!Array.isArray(n))return new Lt(r);const s=n.map(hh);return new Lt({...a,tool_calls:s})}else{if(e==="system")return new jt(r);if(e==="developer")return new jt({...r,additional_kwargs:{...r.additional_kwargs,__openai_role__:"developer"}});if(e==="tool"&&"tool_call_id"in r)return new _r({...r,content:r.content,tool_call_id:r.tool_call_id,name:r.name});if(e==="remove"&&"id"in r&&typeof r.id=="string")return new _n({...r,id:r.id});throw nu(new Error(`Unable to coerce message from array: only human, AI, system, developer, or tool message coercion is currently supported.
|
|
15
|
-
|
|
16
|
-
Received: ${JSON.stringify(t,null,2)}`),"MESSAGE_COERCION_FAILURE")}}function Or(t){if(typeof t=="string")return new At(t);if(Et(t))return t;if(Array.isArray(t)){const[e,r]=t;return Jn({type:e,content:r})}else if(Vc(t)){const{role:e,...r}=t;return Jn({...r,type:e})}else return Jn(t)}function ai(t,e="Human",r="AI"){const n=[];for(const a of t){let s;if(a._getType()==="human")s=e;else if(a._getType()==="ai")s=r;else if(a._getType()==="system")s="System";else if(a._getType()==="tool")s="Tool";else if(a._getType()==="generic")s=a.role;else throw new Error(`Got unsupported message type: ${a._getType()}`);const i=a.name?`${a.name}, `:"",o=typeof a.content=="string"?a.content:JSON.stringify(a.content,null,2);n.push(`${s}: ${i}${o}`)}return n.join(`
|
|
17
|
-
`)}function ph(t){if(t.data!==void 0)return t;{const e=t;return{type:e.type,data:{content:e.text,role:e.role,name:void 0,tool_call_id:void 0}}}}function si(t){const e=ph(t);switch(e.type){case"human":return new At(e.data);case"ai":return new Lt(e.data);case"system":return new jt(e.data);case"function":if(e.data.name===void 0)throw new Error("Name must be defined for function messages");return new Cn(e.data);case"tool":if(e.data.tool_call_id===void 0)throw new Error("Tool call ID must be defined for tool messages");return new _r(e.data);case"generic":if(e.data.role===void 0)throw new Error("Role must be defined for chat messages");return new qr(e.data);default:throw new Error(`Got unexpected type: ${e.type}`)}}function mh(t){return t.map(si)}function gh(t){return t.map(e=>e.toDict())}function yn(t){const e=t._getType();if(e==="human")return new $n({...t});if(e==="ai"){let r={...t};return"tool_calls"in r&&(r={...r,tool_call_chunks:r.tool_calls?.map(n=>({...n,type:"tool_call_chunk",index:void 0,args:JSON.stringify(n.args)}))}),new Yt({...r})}else{if(e==="system")return new fr({...t});if(e==="function")return new Nn({...t});if(qr.isInstance(t))return new Rn({...t});throw new Error("Unknown message type.")}}const su=Symbol.for("ls:tracing_async_local_storage"),kr=Symbol.for("lc:context_variables"),_h=t=>{globalThis[su]=t},jr=()=>globalThis[su];var yh={},vh={};pe(vh,{getEnv:()=>lu,getEnvironmentVariable:()=>$t,getRuntimeEnvironment:()=>du,isBrowser:()=>iu,isDeno:()=>Pn,isJsDom:()=>cu,isNode:()=>uu,isWebWorker:()=>ou});const iu=()=>typeof window<"u"&&typeof window.document<"u",ou=()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope",cu=()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),Pn=()=>typeof Deno<"u",uu=()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!Pn(),lu=()=>{let t;return iu()?t="browser":uu()?t="node":ou()?t="webworker":cu()?t="jsdom":Pn()?t="deno":t="other",t};let Kn;function du(){return Kn===void 0&&(Kn={library:"langchain-js",runtime:lu()}),Kn}function $t(t){try{return typeof process<"u"?yh?.[t]:Pn()?Deno?.env.get(t):void 0}catch{return}}const wh=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;function Rr(t){return typeof t=="string"&&wh.test(t)}function bh(t){if(!Rr(t))throw TypeError("Invalid UUID");var e,r=new Uint8Array(16);return r[0]=(e=parseInt(t.slice(0,8),16))>>>24,r[1]=e>>>16&255,r[2]=e>>>8&255,r[3]=e&255,r[4]=(e=parseInt(t.slice(9,13),16))>>>8,r[5]=e&255,r[6]=(e=parseInt(t.slice(14,18),16))>>>8,r[7]=e&255,r[8]=(e=parseInt(t.slice(19,23),16))>>>8,r[9]=e&255,r[10]=(e=parseInt(t.slice(24,36),16))/1099511627776&255,r[11]=e/4294967296&255,r[12]=e>>>24&255,r[13]=e>>>16&255,r[14]=e>>>8&255,r[15]=e&255,r}var Pe=[];for(var Yn=0;Yn<256;++Yn)Pe.push((Yn+256).toString(16).slice(1));function hu(t,e=0){return(Pe[t[e+0]]+Pe[t[e+1]]+Pe[t[e+2]]+Pe[t[e+3]]+"-"+Pe[t[e+4]]+Pe[t[e+5]]+"-"+Pe[t[e+6]]+Pe[t[e+7]]+"-"+Pe[t[e+8]]+Pe[t[e+9]]+"-"+Pe[t[e+10]]+Pe[t[e+11]]+Pe[t[e+12]]+Pe[t[e+13]]+Pe[t[e+14]]+Pe[t[e+15]]).toLowerCase()}var Xr,Eh=new Uint8Array(16);function Th(){if(!Xr&&(Xr=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!Xr))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Xr(Eh)}function Sh(t){t=unescape(encodeURIComponent(t));for(var e=[],r=0;r<t.length;++r)e.push(t.charCodeAt(r));return e}var Ih="6ba7b810-9dad-11d1-80b4-00c04fd430c8",xh="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function Ah(t,e,r){function n(a,s,i,o){var c;if(typeof a=="string"&&(a=Sh(a)),typeof s=="string"&&(s=bh(s)),((c=s)===null||c===void 0?void 0:c.length)!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");var u=new Uint8Array(16+a.length);if(u.set(s),u.set(a,s.length),u=r(u),u[6]=u[6]&15|e,u[8]=u[8]&63|128,i){o=o||0;for(var l=0;l<16;++l)i[o+l]=u[l];return i}return hu(u)}try{n.name=t}catch{}return n.DNS=Ih,n.URL=xh,n}var Oh=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);const Yi={randomUUID:Oh};function De(t,e,r){if(Yi.randomUUID&&!t)return Yi.randomUUID();t=t||{};var n=t.random||(t.rng||Th)();return n[6]=n[6]&15|64,n[8]=n[8]&63|128,hu(n)}function kh(t,e,r,n){switch(t){case 0:return e&r^~e&n;case 1:return e^r^n;case 2:return e&r^e&n^r&n;case 3:return e^r^n}}function Xn(t,e){return t<<e|t>>>32-e}function Rh(t){var e=[1518500249,1859775393,2400959708,3395469782],r=[1732584193,4023233417,2562383102,271733878,3285377520];if(typeof t=="string"){var n=unescape(encodeURIComponent(t));t=[];for(var a=0;a<n.length;++a)t.push(n.charCodeAt(a))}else Array.isArray(t)||(t=Array.prototype.slice.call(t));t.push(128);for(var s=t.length/4+2,i=Math.ceil(s/16),o=new Array(i),c=0;c<i;++c){for(var u=new Uint32Array(16),l=0;l<16;++l)u[l]=t[c*64+l*4]<<24|t[c*64+l*4+1]<<16|t[c*64+l*4+2]<<8|t[c*64+l*4+3];o[c]=u}o[i-1][14]=(t.length-1)*8/Math.pow(2,32),o[i-1][14]=Math.floor(o[i-1][14]),o[i-1][15]=(t.length-1)*8&4294967295;for(var d=0;d<i;++d){for(var h=new Uint32Array(80),p=0;p<16;++p)h[p]=o[d][p];for(var g=16;g<80;++g)h[g]=Xn(h[g-3]^h[g-8]^h[g-14]^h[g-16],1);for(var y=r[0],v=r[1],b=r[2],S=r[3],E=r[4],k=0;k<80;++k){var C=Math.floor(k/20),F=Xn(y,5)+kh(C,v,b,S)+E+e[C]+h[k]>>>0;E=S,S=b,b=Xn(v,30)>>>0,v=y,y=F}r[0]=r[0]+y>>>0,r[1]=r[1]+v>>>0,r[2]=r[2]+b>>>0,r[3]=r[3]+S>>>0,r[4]=r[4]+E>>>0}return[r[0]>>24&255,r[0]>>16&255,r[0]>>8&255,r[0]&255,r[1]>>24&255,r[1]>>16&255,r[1]>>8&255,r[1]&255,r[2]>>24&255,r[2]>>16&255,r[2]>>8&255,r[2]&255,r[3]>>24&255,r[3]>>16&255,r[3]>>8&255,r[3]&255,r[4]>>24&255,r[4]>>16&255,r[4]>>8&255,r[4]&255]}var Xi=Ah("v5",80,Rh),Ch={};pe(Ch,{BaseCallbackHandler:()=>Gr,callbackHandlerPrefersStreaming:()=>fu,isBaseCallbackHandler:()=>pu});var Nh=class{};function fu(t){return"lc_prefer_streaming"in t&&t.lc_prefer_streaming}var Gr=class extends Nh{lc_serializable=!1;get lc_namespace(){return["langchain_core","callbacks",this.name]}get lc_secrets(){}get lc_attributes(){}get lc_aliases(){}get lc_serializable_keys(){}static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,Ys(this.constructor)]}lc_kwargs;ignoreLLM=!1;ignoreChain=!1;ignoreAgent=!1;ignoreRetriever=!1;ignoreCustomEvent=!1;raiseError=!1;awaitHandlers=$t("LANGCHAIN_CALLBACKS_BACKGROUND")==="false";constructor(t){super(),this.lc_kwargs=t||{},t&&(this.ignoreLLM=t.ignoreLLM??this.ignoreLLM,this.ignoreChain=t.ignoreChain??this.ignoreChain,this.ignoreAgent=t.ignoreAgent??this.ignoreAgent,this.ignoreRetriever=t.ignoreRetriever??this.ignoreRetriever,this.ignoreCustomEvent=t.ignoreCustomEvent??this.ignoreCustomEvent,this.raiseError=t.raiseError??this.raiseError,this.awaitHandlers=this.raiseError||(t._awaitHandler??this.awaitHandlers))}copy(){return new this.constructor(this)}toJSON(){return hr.prototype.toJSON.call(this)}toJSONNotImplemented(){return hr.prototype.toJSONNotImplemented.call(this)}static fromMethods(t){class e extends Gr{name=De();constructor(){super(),Object.assign(this,t)}}return new e}};const pu=t=>{const e=t;return e!==void 0&&typeof e.copy=="function"&&typeof e.name=="string"&&typeof e.awaitHandlers=="boolean"},$h="gen_ai.operation.name",Ph="gen_ai.system",Qi="gen_ai.request.model",Mh="gen_ai.response.model",eo="gen_ai.usage.input_tokens",to="gen_ai.usage.output_tokens",ro="gen_ai.usage.total_tokens",Lh="gen_ai.request.max_tokens",jh="gen_ai.request.temperature",Dh="gen_ai.request.top_p",Uh="gen_ai.request.frequency_penalty",Fh="gen_ai.request.presence_penalty",Bh="gen_ai.response.finish_reasons",zh="gen_ai.prompt",qh="gen_ai.completion",Gh="gen_ai.request.extra_query",Hh="gen_ai.request.extra_body",Zh="gen_ai.serialized.name",Vh="gen_ai.serialized.signature",Wh="gen_ai.serialized.doc",Jh="gen_ai.response.id",Kh="gen_ai.response.service_tier",Yh="gen_ai.response.system_fingerprint",Xh="gen_ai.usage.input_token_details",Qh="gen_ai.usage.output_token_details",ef="langsmith.trace.session_id",tf="langsmith.trace.session_name",rf="langsmith.span.kind",nf="langsmith.trace.name",af="langsmith.metadata",no="langsmith.span.tags",sf="langsmith.request.streaming",of="langsmith.request.headers",cf=(...t)=>fetch(...t),mu=Symbol.for("ls:fetch_implementation"),uf=()=>{const t=globalThis[mu];return t?typeof t=="function"&&"Headers"in t&&"Request"in t&&"Response"in t:!1},lf=t=>async(...e)=>{if(t||Ge("DEBUG")==="true"){const[n,a]=e;console.log(`→ ${a?.method||"GET"} ${n}`)}const r=await(globalThis[mu]??cf)(...e);return(t||Ge("DEBUG")==="true")&&console.log(`← ${r.status} ${r.statusText} ${r.url}`),r},gu=()=>Ge("PROJECT")??yt("LANGCHAIN_SESSION")??"default",_u="0.3.79";var bs={};let dt;const df=()=>typeof window<"u"&&typeof window.document<"u",hf=()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope",ff=()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),yu=()=>typeof Deno<"u",pf=()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!yu(),vu=()=>dt||(typeof Bun<"u"?dt="bun":df()?dt="browser":pf()?dt="node":hf()?dt="webworker":ff()?dt="jsdom":yu()?dt="deno":dt="other",dt);let Qn;function wu(){if(Qn===void 0){const t=vu(),e=gf();Qn={library:"langsmith",runtime:t,sdk:"langsmith-js",sdk_version:_u,...e}}return Qn}function bu(){const t=mf(),e={},r=["LANGCHAIN_API_KEY","LANGCHAIN_ENDPOINT","LANGCHAIN_TRACING_V2","LANGCHAIN_PROJECT","LANGCHAIN_SESSION","LANGSMITH_API_KEY","LANGSMITH_ENDPOINT","LANGSMITH_TRACING_V2","LANGSMITH_PROJECT","LANGSMITH_SESSION"];for(const[n,a]of Object.entries(t))typeof a=="string"&&!r.includes(n)&&!n.toLowerCase().includes("key")&&!n.toLowerCase().includes("secret")&&!n.toLowerCase().includes("token")&&(n==="LANGCHAIN_REVISION_ID"?e.revision_id=a:e[n]=a);return e}function mf(){const t={};try{if(typeof process<"u"&&bs)for(const[e,r]of Object.entries(bs))(e.startsWith("LANGCHAIN_")||e.startsWith("LANGSMITH_"))&&r!=null&&((e.toLowerCase().includes("key")||e.toLowerCase().includes("secret")||e.toLowerCase().includes("token"))&&typeof r=="string"?t[e]=r.slice(0,2)+"*".repeat(r.length-4)+r.slice(-2):t[e]=r)}catch{}return t}function yt(t){try{return typeof process<"u"?bs?.[t]:void 0}catch{return}}function Ge(t){return yt(`LANGSMITH_${t}`)||yt(`LANGCHAIN_${t}`)}let ea;function gf(){if(ea!==void 0)return ea;const t=["VERCEL_GIT_COMMIT_SHA","NEXT_PUBLIC_VERCEL_GIT_COMMIT_SHA","COMMIT_REF","RENDER_GIT_COMMIT","CI_COMMIT_SHA","CIRCLE_SHA1","CF_PAGES_COMMIT_SHA","REACT_APP_GIT_SHA","SOURCE_VERSION","GITHUB_SHA","TRAVIS_COMMIT","GIT_COMMIT","BUILD_VCS_NUMBER","bamboo_planRepository_revision","Build.SourceVersion","BITBUCKET_COMMIT","DRONE_COMMIT_SHA","SEMAPHORE_GIT_SHA","BUILDKITE_COMMIT"],e={};for(const r of t){const n=yt(r);n!==void 0&&(e[r]=n)}return ea=e,e}function Eu(){return yt("OTEL_ENABLED")==="true"||Ge("OTEL_ENABLED")==="true"}class _f{constructor(){Object.defineProperty(this,"hasWarned",{enumerable:!0,configurable:!0,writable:!0,value:!1})}startActiveSpan(e,...r){!this.hasWarned&&Eu()&&(console.warn('You have enabled OTEL export via the `OTEL_ENABLED` or `LANGSMITH_OTEL_ENABLED` environment variable, but have not initialized the required OTEL instances. Please add:\n```\nimport { initializeOTEL } from "langsmith/experimental/otel/setup";\ninitializeOTEL();\n```\nat the beginning of your code.'),this.hasWarned=!0);let n;if(r.length===1&&typeof r[0]=="function"?n=r[0]:r.length===2&&typeof r[1]=="function"?n=r[1]:r.length===3&&typeof r[2]=="function"&&(n=r[2]),typeof n=="function")return n()}}class yf{constructor(){Object.defineProperty(this,"mockTracer",{enumerable:!0,configurable:!0,writable:!0,value:new _f})}getTracer(e,r){return this.mockTracer}getActiveSpan(){}setSpan(e,r){return e}getSpan(e){}setSpanContext(e,r){return e}getTracerProvider(){}setGlobalTracerProvider(e){return!1}}class vf{active(){return{}}with(e,r){return r()}}const ta=Symbol.for("ls:otel_trace"),ra=Symbol.for("ls:otel_context"),ao=Symbol.for("ls:otel_get_default_otlp_tracer_provider"),wf=new yf,bf=new vf;class Ef{getTraceInstance(){return globalThis[ta]??wf}getContextInstance(){return globalThis[ra]??bf}initializeGlobalInstances(e){globalThis[ta]===void 0&&(globalThis[ta]=e.trace),globalThis[ra]===void 0&&(globalThis[ra]=e.context)}setDefaultOTLPTracerComponents(e){globalThis[ao]=e}getDefaultOTLPTracerComponents(){return globalThis[ao]??void 0}}const ii=new Ef;function Tu(){return ii.getTraceInstance()}function Tf(){return ii.getContextInstance()}function Sf(){return ii.getDefaultOTLPTracerComponents()}const If={llm:"chat",tool:"execute_tool",retriever:"embeddings",embedding:"embeddings",prompt:"chat"};function xf(t){return If[t]||t}class Af{constructor(){Object.defineProperty(this,"spans",{enumerable:!0,configurable:!0,writable:!0,value:new Map})}exportBatch(e,r){for(const n of e)try{if(!n.run)continue;if(n.operation==="post"){const a=this.createSpanForRun(n,n.run,r.get(n.id));a&&!n.run.end_time&&this.spans.set(n.id,a)}else this.updateSpanForRun(n,n.run)}catch(a){console.error(`Error processing operation ${n.id}:`,a)}}createSpanForRun(e,r,n){const a=n&&Tu().getSpan(n);if(a)try{return this.finishSpanSetup(a,r,e)}catch(s){console.error(`Failed to create span for run ${e.id}:`,s);return}}finishSpanSetup(e,r,n){return this.setSpanAttributes(e,r,n),r.error?(e.setStatus({code:2}),e.recordException(new Error(r.error))):e.setStatus({code:1}),r.end_time&&e.end(new Date(r.end_time)),e}updateSpanForRun(e,r){try{const n=this.spans.get(e.id);if(!n){console.debug(`No span found for run ${e.id} during update`);return}this.setSpanAttributes(n,r,e),r.error?(n.setStatus({code:2}),n.recordException(new Error(r.error))):n.setStatus({code:1});const a=r.end_time;a&&(n.end(new Date(a)),this.spans.delete(e.id))}catch(n){console.error(`Failed to update span for run ${e.id}:`,n)}}extractModelName(e){if(e.extra?.metadata){const r=e.extra.metadata;if(r.ls_model_name)return r.ls_model_name;if(r.invocation_params){const n=r.invocation_params;if(n.model)return n.model;if(n.model_name)return n.model_name}}}setSpanAttributes(e,r,n){if("run_type"in r&&r.run_type){e.setAttribute(rf,r.run_type);const o=xf(r.run_type||"chain");e.setAttribute($h,o)}"name"in r&&r.name&&e.setAttribute(nf,r.name),"session_id"in r&&r.session_id&&e.setAttribute(ef,r.session_id),"session_name"in r&&r.session_name&&e.setAttribute(tf,r.session_name),this.setGenAiSystem(e,r);const a=this.extractModelName(r);a&&e.setAttribute(Qi,a),"prompt_tokens"in r&&typeof r.prompt_tokens=="number"&&e.setAttribute(eo,r.prompt_tokens),"completion_tokens"in r&&typeof r.completion_tokens=="number"&&e.setAttribute(to,r.completion_tokens),"total_tokens"in r&&typeof r.total_tokens=="number"&&e.setAttribute(ro,r.total_tokens),this.setInvocationParameters(e,r);const s=r.extra?.metadata||{};for(const[o,c]of Object.entries(s))c!=null&&e.setAttribute(`${af}.${o}`,String(c));const i=r.tags;if(i&&Array.isArray(i)?e.setAttribute(no,i.join(", ")):i&&e.setAttribute(no,String(i)),"serialized"in r&&typeof r.serialized=="object"){const o=r.serialized;o.name&&e.setAttribute(Zh,String(o.name)),o.signature&&e.setAttribute(Vh,String(o.signature)),o.doc&&e.setAttribute(Wh,String(o.doc))}this.setIOAttributes(e,n)}setGenAiSystem(e,r){let n="langchain";const a=this.extractModelName(r);if(a){const s=a.toLowerCase();s.includes("anthropic")||s.startsWith("claude")?n="anthropic":s.includes("bedrock")?n="aws.bedrock":s.includes("azure")&&s.includes("openai")?n="az.ai.openai":s.includes("azure")&&s.includes("inference")?n="az.ai.inference":s.includes("cohere")?n="cohere":s.includes("deepseek")?n="deepseek":s.includes("gemini")?n="gemini":s.includes("groq")?n="groq":s.includes("watson")||s.includes("ibm")?n="ibm.watsonx.ai":s.includes("mistral")?n="mistral_ai":s.includes("gpt")||s.includes("openai")?n="openai":s.includes("perplexity")||s.includes("sonar")?n="perplexity":s.includes("vertex")?n="vertex_ai":(s.includes("xai")||s.includes("grok"))&&(n="xai")}e.setAttribute(Ph,n)}setInvocationParameters(e,r){if(!r.extra?.metadata?.invocation_params)return;const n=r.extra.metadata.invocation_params;n.max_tokens!==void 0&&e.setAttribute(Lh,n.max_tokens),n.temperature!==void 0&&e.setAttribute(jh,n.temperature),n.top_p!==void 0&&e.setAttribute(Dh,n.top_p),n.frequency_penalty!==void 0&&e.setAttribute(Uh,n.frequency_penalty),n.presence_penalty!==void 0&&e.setAttribute(Fh,n.presence_penalty)}setIOAttributes(e,r){if(r.run.inputs)try{const n=r.run.inputs;typeof n=="object"&&n!==null&&(n.model&&Array.isArray(n.messages)&&e.setAttribute(Qi,n.model),n.stream!==void 0&&e.setAttribute(sf,n.stream),n.extra_headers&&e.setAttribute(of,JSON.stringify(n.extra_headers)),n.extra_query&&e.setAttribute(Gh,JSON.stringify(n.extra_query)),n.extra_body&&e.setAttribute(Hh,JSON.stringify(n.extra_body))),e.setAttribute(zh,JSON.stringify(n))}catch(n){console.debug(`Failed to process inputs for run ${r.id}`,n)}if(r.run.outputs)try{const n=r.run.outputs,a=this.getUnifiedRunTokens(n);if(a&&(e.setAttribute(eo,a[0]),e.setAttribute(to,a[1]),e.setAttribute(ro,a[0]+a[1])),n&&typeof n=="object"){if(n.model&&e.setAttribute(Mh,String(n.model)),n.id&&e.setAttribute(Jh,n.id),n.choices&&Array.isArray(n.choices)){const s=n.choices.map(i=>i.finish_reason).filter(i=>i).map(String);s.length>0&&e.setAttribute(Bh,s.join(", "))}if(n.service_tier&&e.setAttribute(Kh,n.service_tier),n.system_fingerprint&&e.setAttribute(Yh,n.system_fingerprint),n.usage_metadata&&typeof n.usage_metadata=="object"){const s=n.usage_metadata;s.input_token_details&&e.setAttribute(Xh,JSON.stringify(s.input_token_details)),s.output_token_details&&e.setAttribute(Qh,JSON.stringify(s.output_token_details))}}e.setAttribute(qh,JSON.stringify(n))}catch(n){console.debug(`Failed to process outputs for run ${r.id}`,n)}}getUnifiedRunTokens(e){if(!e)return null;let r=this.extractUnifiedRunTokens(e.usage_metadata);if(r)return r;const n=Object.keys(e);for(const i of n){const o=e[i];if(!(!o||typeof o!="object")&&(r=this.extractUnifiedRunTokens(o.usage_metadata),r||o.lc===1&&o.kwargs&&typeof o.kwargs=="object"&&(r=this.extractUnifiedRunTokens(o.kwargs.usage_metadata),r)))return r}const a=e.generations||[];if(!Array.isArray(a))return null;const s=Array.isArray(a[0])?a.flat():a;for(const i of s)if(typeof i=="object"&&i.message&&typeof i.message=="object"&&i.message.kwargs&&typeof i.message.kwargs=="object"&&(r=this.extractUnifiedRunTokens(i.message.kwargs.usage_metadata),r))return r;return null}extractUnifiedRunTokens(e){return!e||typeof e!="object"||typeof e.input_tokens!="number"||typeof e.output_tokens!="number"?null:[e.input_tokens,e.output_tokens]}}var Er={exports:{}},na={},aa,so;function Of(){if(so)return aa;so=1;function t(e,r){typeof r=="boolean"&&(r={forever:r}),this._originalTimeouts=JSON.parse(JSON.stringify(e)),this._timeouts=e,this._options=r||{},this._maxRetryTime=r&&r.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}return aa=t,t.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)},t.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null},t.prototype.retry=function(e){if(this._timeout&&clearTimeout(this._timeout),!e)return!1;var r=new Date().getTime();if(e&&r-this._operationStart>=this._maxRetryTime)return this._errors.push(e),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(e);var n=this._timeouts.shift();if(n===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),n=this._cachedTimeouts.slice(-1);else return!1;var a=this;return this._timer=setTimeout(function(){a._attempts++,a._operationTimeoutCb&&(a._timeout=setTimeout(function(){a._operationTimeoutCb(a._attempts)},a._operationTimeout),a._options.unref&&a._timeout.unref()),a._fn(a._attempts)},n),this._options.unref&&this._timer.unref(),!0},t.prototype.attempt=function(e,r){this._fn=e,r&&(r.timeout&&(this._operationTimeout=r.timeout),r.cb&&(this._operationTimeoutCb=r.cb));var n=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){n._operationTimeoutCb()},n._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)},t.prototype.try=function(e){console.log("Using RetryOperation.try() is deprecated"),this.attempt(e)},t.prototype.start=function(e){console.log("Using RetryOperation.start() is deprecated"),this.attempt(e)},t.prototype.start=t.prototype.try,t.prototype.errors=function(){return this._errors},t.prototype.attempts=function(){return this._attempts},t.prototype.mainError=function(){if(this._errors.length===0)return null;for(var e={},r=null,n=0,a=0;a<this._errors.length;a++){var s=this._errors[a],i=s.message,o=(e[i]||0)+1;e[i]=o,o>=n&&(r=s,n=o)}return r},aa}var io;function kf(){return io||(io=1,(function(t){var e=Of();t.operation=function(r){var n=t.timeouts(r);return new e(n,{forever:r&&(r.forever||r.retries===1/0),unref:r&&r.unref,maxRetryTime:r&&r.maxRetryTime})},t.timeouts=function(r){if(r instanceof Array)return[].concat(r);var n={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var a in r)n[a]=r[a];if(n.minTimeout>n.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var s=[],i=0;i<n.retries;i++)s.push(this.createTimeout(i,n));return r&&r.forever&&!s.length&&s.push(this.createTimeout(i,n)),s.sort(function(o,c){return o-c}),s},t.createTimeout=function(r,n){var a=n.randomize?Math.random()+1:1,s=Math.round(a*Math.max(n.minTimeout,1)*Math.pow(n.factor,r));return s=Math.min(s,n.maxTimeout),s},t.wrap=function(r,n,a){if(n instanceof Array&&(a=n,n=null),!a){a=[];for(var s in r)typeof r[s]=="function"&&a.push(s)}for(var i=0;i<a.length;i++){var o=a[i],c=r[o];r[o]=(function(l){var d=t.operation(n),h=Array.prototype.slice.call(arguments,1),p=h.pop();h.push(function(g){d.retry(g)||(g&&(arguments[0]=d.mainError()),p.apply(this,arguments))}),d.attempt(function(){l.apply(r,h)})}).bind(r,c),r[o].options=n}}})(na)),na}var sa,oo;function Rf(){return oo||(oo=1,sa=kf()),sa}var co;function Cf(){if(co)return Er.exports;co=1;const t=Rf(),e=["Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed"];class r extends Error{constructor(o){super(),o instanceof Error?(this.originalError=o,{message:o}=o):(this.originalError=new Error(o),this.originalError.stack=this.stack),this.name="AbortError",this.message=o}}const n=(i,o,c)=>{const u=c.retries-(o-1);return i.attemptNumber=o,i.retriesLeft=u,i},a=i=>e.includes(i),s=(i,o)=>new Promise((c,u)=>{o={onFailedAttempt:()=>{},retries:10,...o};const l=t.operation(o);l.attempt(async d=>{try{c(await i(d))}catch(h){if(!(h instanceof Error)){u(new TypeError(`Non-error was thrown: "${h}". You should only throw errors.`));return}if(h instanceof r)l.stop(),u(h.originalError);else if(h instanceof TypeError&&!a(h.message))l.stop(),u(h);else{n(h,d,o);try{await o.onFailedAttempt(h)}catch(p){u(p);return}l.retry(h)||u(l.mainError())}}})});return Er.exports=s,Er.exports.default=s,Er.exports.AbortError=r,Er.exports}var Nf=Cf();const vn=gr(Nf);var Qr={},ia={exports:{}},uo;function $f(){return uo||(uo=1,(function(t){var e=Object.prototype.hasOwnProperty,r="~";function n(){}Object.create&&(n.prototype=Object.create(null),new n().__proto__||(r=!1));function a(c,u,l){this.fn=c,this.context=u,this.once=l||!1}function s(c,u,l,d,h){if(typeof l!="function")throw new TypeError("The listener must be a function");var p=new a(l,d||c,h),g=r?r+u:u;return c._events[g]?c._events[g].fn?c._events[g]=[c._events[g],p]:c._events[g].push(p):(c._events[g]=p,c._eventsCount++),c}function i(c,u){--c._eventsCount===0?c._events=new n:delete c._events[u]}function o(){this._events=new n,this._eventsCount=0}o.prototype.eventNames=function(){var u=[],l,d;if(this._eventsCount===0)return u;for(d in l=this._events)e.call(l,d)&&u.push(r?d.slice(1):d);return Object.getOwnPropertySymbols?u.concat(Object.getOwnPropertySymbols(l)):u},o.prototype.listeners=function(u){var l=r?r+u:u,d=this._events[l];if(!d)return[];if(d.fn)return[d.fn];for(var h=0,p=d.length,g=new Array(p);h<p;h++)g[h]=d[h].fn;return g},o.prototype.listenerCount=function(u){var l=r?r+u:u,d=this._events[l];return d?d.fn?1:d.length:0},o.prototype.emit=function(u,l,d,h,p,g){var y=r?r+u:u;if(!this._events[y])return!1;var v=this._events[y],b=arguments.length,S,E;if(v.fn){switch(v.once&&this.removeListener(u,v.fn,void 0,!0),b){case 1:return v.fn.call(v.context),!0;case 2:return v.fn.call(v.context,l),!0;case 3:return v.fn.call(v.context,l,d),!0;case 4:return v.fn.call(v.context,l,d,h),!0;case 5:return v.fn.call(v.context,l,d,h,p),!0;case 6:return v.fn.call(v.context,l,d,h,p,g),!0}for(E=1,S=new Array(b-1);E<b;E++)S[E-1]=arguments[E];v.fn.apply(v.context,S)}else{var k=v.length,C;for(E=0;E<k;E++)switch(v[E].once&&this.removeListener(u,v[E].fn,void 0,!0),b){case 1:v[E].fn.call(v[E].context);break;case 2:v[E].fn.call(v[E].context,l);break;case 3:v[E].fn.call(v[E].context,l,d);break;case 4:v[E].fn.call(v[E].context,l,d,h);break;default:if(!S)for(C=1,S=new Array(b-1);C<b;C++)S[C-1]=arguments[C];v[E].fn.apply(v[E].context,S)}}return!0},o.prototype.on=function(u,l,d){return s(this,u,l,d,!1)},o.prototype.once=function(u,l,d){return s(this,u,l,d,!0)},o.prototype.removeListener=function(u,l,d,h){var p=r?r+u:u;if(!this._events[p])return this;if(!l)return i(this,p),this;var g=this._events[p];if(g.fn)g.fn===l&&(!h||g.once)&&(!d||g.context===d)&&i(this,p);else{for(var y=0,v=[],b=g.length;y<b;y++)(g[y].fn!==l||h&&!g[y].once||d&&g[y].context!==d)&&v.push(g[y]);v.length?this._events[p]=v.length===1?v[0]:v:i(this,p)}return this},o.prototype.removeAllListeners=function(u){var l;return u?(l=r?r+u:u,this._events[l]&&i(this,l)):(this._events=new n,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=r,o.EventEmitter=o,t.exports=o})(ia)),ia.exports}var Tr={exports:{}},oa,lo;function Pf(){return lo||(lo=1,oa=(t,e)=>(e=e||(()=>{}),t.then(r=>new Promise(n=>{n(e())}).then(()=>r),r=>new Promise(n=>{n(e())}).then(()=>{throw r})))),oa}var ho;function Mf(){if(ho)return Tr.exports;ho=1;const t=Pf();class e extends Error{constructor(a){super(a),this.name="TimeoutError"}}const r=(n,a,s)=>new Promise((i,o)=>{if(typeof a!="number"||a<0)throw new TypeError("Expected `milliseconds` to be a positive number");if(a===1/0){i(n);return}const c=setTimeout(()=>{if(typeof s=="function"){try{i(s())}catch(d){o(d)}return}const u=typeof s=="string"?s:`Promise timed out after ${a} milliseconds`,l=s instanceof Error?s:new e(u);typeof n.cancel=="function"&&n.cancel(),o(l)},a);t(n.then(i,o),()=>{clearTimeout(c)})});return Tr.exports=r,Tr.exports.default=r,Tr.exports.TimeoutError=e,Tr.exports}var en={},tn={},fo;function Lf(){if(fo)return tn;fo=1,Object.defineProperty(tn,"__esModule",{value:!0});function t(e,r,n){let a=0,s=e.length;for(;s>0;){const i=s/2|0;let o=a+i;n(e[o],r)<=0?(a=++o,s-=i+1):s=i}return a}return tn.default=t,tn}var po;function jf(){if(po)return en;po=1,Object.defineProperty(en,"__esModule",{value:!0});const t=Lf();class e{constructor(){this._queue=[]}enqueue(n,a){a=Object.assign({priority:0},a);const s={priority:a.priority,run:n};if(this.size&&this._queue[this.size-1].priority>=a.priority){this._queue.push(s);return}const i=t.default(this._queue,s,(o,c)=>c.priority-o.priority);this._queue.splice(i,0,s)}dequeue(){const n=this._queue.shift();return n?.run}filter(n){return this._queue.filter(a=>a.priority===n.priority).map(a=>a.run)}get size(){return this._queue.length}}return en.default=e,en}var mo;function Df(){if(mo)return Qr;mo=1,Object.defineProperty(Qr,"__esModule",{value:!0});const t=$f(),e=Mf(),r=jf(),n=()=>{},a=new e.TimeoutError;class s extends t{constructor(o){var c,u,l,d;if(super(),this._intervalCount=0,this._intervalEnd=0,this._pendingCount=0,this._resolveEmpty=n,this._resolveIdle=n,o=Object.assign({carryoverConcurrencyCount:!1,intervalCap:1/0,interval:0,concurrency:1/0,autoStart:!0,queueClass:r.default},o),!(typeof o.intervalCap=="number"&&o.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${(u=(c=o.intervalCap)===null||c===void 0?void 0:c.toString())!==null&&u!==void 0?u:""}\` (${typeof o.intervalCap})`);if(o.interval===void 0||!(Number.isFinite(o.interval)&&o.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${(d=(l=o.interval)===null||l===void 0?void 0:l.toString())!==null&&d!==void 0?d:""}\` (${typeof o.interval})`);this._carryoverConcurrencyCount=o.carryoverConcurrencyCount,this._isIntervalIgnored=o.intervalCap===1/0||o.interval===0,this._intervalCap=o.intervalCap,this._interval=o.interval,this._queue=new o.queueClass,this._queueClass=o.queueClass,this.concurrency=o.concurrency,this._timeout=o.timeout,this._throwOnTimeout=o.throwOnTimeout===!0,this._isPaused=o.autoStart===!1}get _doesIntervalAllowAnother(){return this._isIntervalIgnored||this._intervalCount<this._intervalCap}get _doesConcurrentAllowAnother(){return this._pendingCount<this._concurrency}_next(){this._pendingCount--,this._tryToStartAnother(),this.emit("next")}_resolvePromises(){this._resolveEmpty(),this._resolveEmpty=n,this._pendingCount===0&&(this._resolveIdle(),this._resolveIdle=n,this.emit("idle"))}_onResumeInterval(){this._onInterval(),this._initializeIntervalIfNeeded(),this._timeoutId=void 0}_isIntervalPaused(){const o=Date.now();if(this._intervalId===void 0){const c=this._intervalEnd-o;if(c<0)this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0;else return this._timeoutId===void 0&&(this._timeoutId=setTimeout(()=>{this._onResumeInterval()},c)),!0}return!1}_tryToStartAnother(){if(this._queue.size===0)return this._intervalId&&clearInterval(this._intervalId),this._intervalId=void 0,this._resolvePromises(),!1;if(!this._isPaused){const o=!this._isIntervalPaused();if(this._doesIntervalAllowAnother&&this._doesConcurrentAllowAnother){const c=this._queue.dequeue();return c?(this.emit("active"),c(),o&&this._initializeIntervalIfNeeded(),!0):!1}}return!1}_initializeIntervalIfNeeded(){this._isIntervalIgnored||this._intervalId!==void 0||(this._intervalId=setInterval(()=>{this._onInterval()},this._interval),this._intervalEnd=Date.now()+this._interval)}_onInterval(){this._intervalCount===0&&this._pendingCount===0&&this._intervalId&&(clearInterval(this._intervalId),this._intervalId=void 0),this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0,this._processQueue()}_processQueue(){for(;this._tryToStartAnother(););}get concurrency(){return this._concurrency}set concurrency(o){if(!(typeof o=="number"&&o>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${o}\` (${typeof o})`);this._concurrency=o,this._processQueue()}async add(o,c={}){return new Promise((u,l)=>{const d=async()=>{this._pendingCount++,this._intervalCount++;try{const h=this._timeout===void 0&&c.timeout===void 0?o():e.default(Promise.resolve(o()),c.timeout===void 0?this._timeout:c.timeout,()=>{(c.throwOnTimeout===void 0?this._throwOnTimeout:c.throwOnTimeout)&&l(a)});u(await h)}catch(h){l(h)}this._next()};this._queue.enqueue(d,c),this._tryToStartAnother(),this.emit("add")})}async addAll(o,c){return Promise.all(o.map(async u=>this.add(u,c)))}start(){return this._isPaused?(this._isPaused=!1,this._processQueue(),this):this}pause(){this._isPaused=!0}clear(){this._queue=new this._queueClass}async onEmpty(){if(this._queue.size!==0)return new Promise(o=>{const c=this._resolveEmpty;this._resolveEmpty=()=>{c(),o()}})}async onIdle(){if(!(this._pendingCount===0&&this._queue.size===0))return new Promise(o=>{const c=this._resolveIdle;this._resolveIdle=()=>{c(),o()}})}get size(){return this._queue.size}sizeBy(o){return this._queue.filter(o).length}get pending(){return this._pendingCount}get isPaused(){return this._isPaused}get timeout(){return this._timeout}set timeout(o){this._timeout=o}}return Qr.default=s,Qr}var Uf=Df();const Tt=gr(Uf),Ff=[429,500,502,503,504];let go=class{constructor(e){Object.defineProperty(this,"maxConcurrency",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"maxRetries",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"queue",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onFailedResponseHook",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxConcurrency=e.maxConcurrency??1/0,this.maxRetries=e.maxRetries??6,"default"in Tt?this.queue=new Tt.default({concurrency:this.maxConcurrency}):this.queue=new Tt({concurrency:this.maxConcurrency}),this.onFailedResponseHook=e?.onFailedResponseHook}call(e,...r){const n=this.onFailedResponseHook;return this.queue.add(()=>vn(()=>e(...r).catch(a=>{throw a instanceof Error?a:new Error(a)}),{async onFailedAttempt(a){if(a.message.startsWith("Cancel")||a.message.startsWith("TimeoutError")||a.name==="TimeoutError"||a.message.startsWith("AbortError")||a?.code==="ECONNABORTED")throw a;const s=a?.response;if(n&&await n(s))return;const i=s?.status??a?.status;if(i&&!Ff.includes(+i))throw a},retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0})}callWithOptions(e,r,...n){return e.signal?Promise.race([this.call(r,...n),new Promise((a,s)=>{e.signal?.addEventListener("abort",()=>{s(new Error("AbortError"))})})]):this.call(r,...n)}};function _o(t){return typeof t?._getType=="function"}function yo(t){const e={type:t._getType(),data:{content:t.content}};return t?.additional_kwargs&&Object.keys(t.additional_kwargs).length>0&&(e.data.additional_kwargs={...t.additional_kwargs}),e}const Bf=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function re(t,e){if(!Bf.test(t)){const r=e!==void 0?`Invalid UUID for ${e}: ${t}`:`Invalid UUID: ${t}`;throw new Error(r)}return t}const vo={};function Es(t){vo[t]||(console.warn(t),vo[t]=!0)}var rn={exports:{}},ca,wo;function Mn(){if(wo)return ca;wo=1;const t="2.0.0",e=256,r=Number.MAX_SAFE_INTEGER||9007199254740991,n=16,a=e-6;return ca={MAX_LENGTH:e,MAX_SAFE_COMPONENT_LENGTH:n,MAX_SAFE_BUILD_LENGTH:a,MAX_SAFE_INTEGER:r,RELEASE_TYPES:["major","premajor","minor","preminor","patch","prepatch","prerelease"],SEMVER_SPEC_VERSION:t,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2},ca}var ua,bo;function Ln(){if(bo)return ua;bo=1;var t={};return ua=typeof process=="object"&&t&&t.NODE_DEBUG&&/\bsemver\b/i.test(t.NODE_DEBUG)?(...r)=>console.error("SEMVER",...r):()=>{},ua}var Eo;function Hr(){return Eo||(Eo=1,(function(t,e){const{MAX_SAFE_COMPONENT_LENGTH:r,MAX_SAFE_BUILD_LENGTH:n,MAX_LENGTH:a}=Mn(),s=Ln();e=t.exports={};const i=e.re=[],o=e.safeRe=[],c=e.src=[],u=e.safeSrc=[],l=e.t={};let d=0;const h="[a-zA-Z0-9-]",p=[["\\s",1],["\\d",a],[h,n]],g=v=>{for(const[b,S]of p)v=v.split(`${b}*`).join(`${b}{0,${S}}`).split(`${b}+`).join(`${b}{1,${S}}`);return v},y=(v,b,S)=>{const E=g(b),k=d++;s(v,k,b),l[v]=k,c[k]=b,u[k]=E,i[k]=new RegExp(b,S?"g":void 0),o[k]=new RegExp(E,S?"g":void 0)};y("NUMERICIDENTIFIER","0|[1-9]\\d*"),y("NUMERICIDENTIFIERLOOSE","\\d+"),y("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${h}*`),y("MAINVERSION",`(${c[l.NUMERICIDENTIFIER]})\\.(${c[l.NUMERICIDENTIFIER]})\\.(${c[l.NUMERICIDENTIFIER]})`),y("MAINVERSIONLOOSE",`(${c[l.NUMERICIDENTIFIERLOOSE]})\\.(${c[l.NUMERICIDENTIFIERLOOSE]})\\.(${c[l.NUMERICIDENTIFIERLOOSE]})`),y("PRERELEASEIDENTIFIER",`(?:${c[l.NONNUMERICIDENTIFIER]}|${c[l.NUMERICIDENTIFIER]})`),y("PRERELEASEIDENTIFIERLOOSE",`(?:${c[l.NONNUMERICIDENTIFIER]}|${c[l.NUMERICIDENTIFIERLOOSE]})`),y("PRERELEASE",`(?:-(${c[l.PRERELEASEIDENTIFIER]}(?:\\.${c[l.PRERELEASEIDENTIFIER]})*))`),y("PRERELEASELOOSE",`(?:-?(${c[l.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${c[l.PRERELEASEIDENTIFIERLOOSE]})*))`),y("BUILDIDENTIFIER",`${h}+`),y("BUILD",`(?:\\+(${c[l.BUILDIDENTIFIER]}(?:\\.${c[l.BUILDIDENTIFIER]})*))`),y("FULLPLAIN",`v?${c[l.MAINVERSION]}${c[l.PRERELEASE]}?${c[l.BUILD]}?`),y("FULL",`^${c[l.FULLPLAIN]}$`),y("LOOSEPLAIN",`[v=\\s]*${c[l.MAINVERSIONLOOSE]}${c[l.PRERELEASELOOSE]}?${c[l.BUILD]}?`),y("LOOSE",`^${c[l.LOOSEPLAIN]}$`),y("GTLT","((?:<|>)?=?)"),y("XRANGEIDENTIFIERLOOSE",`${c[l.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`),y("XRANGEIDENTIFIER",`${c[l.NUMERICIDENTIFIER]}|x|X|\\*`),y("XRANGEPLAIN",`[v=\\s]*(${c[l.XRANGEIDENTIFIER]})(?:\\.(${c[l.XRANGEIDENTIFIER]})(?:\\.(${c[l.XRANGEIDENTIFIER]})(?:${c[l.PRERELEASE]})?${c[l.BUILD]}?)?)?`),y("XRANGEPLAINLOOSE",`[v=\\s]*(${c[l.XRANGEIDENTIFIERLOOSE]})(?:\\.(${c[l.XRANGEIDENTIFIERLOOSE]})(?:\\.(${c[l.XRANGEIDENTIFIERLOOSE]})(?:${c[l.PRERELEASELOOSE]})?${c[l.BUILD]}?)?)?`),y("XRANGE",`^${c[l.GTLT]}\\s*${c[l.XRANGEPLAIN]}$`),y("XRANGELOOSE",`^${c[l.GTLT]}\\s*${c[l.XRANGEPLAINLOOSE]}$`),y("COERCEPLAIN",`(^|[^\\d])(\\d{1,${r}})(?:\\.(\\d{1,${r}}))?(?:\\.(\\d{1,${r}}))?`),y("COERCE",`${c[l.COERCEPLAIN]}(?:$|[^\\d])`),y("COERCEFULL",c[l.COERCEPLAIN]+`(?:${c[l.PRERELEASE]})?(?:${c[l.BUILD]})?(?:$|[^\\d])`),y("COERCERTL",c[l.COERCE],!0),y("COERCERTLFULL",c[l.COERCEFULL],!0),y("LONETILDE","(?:~>?)"),y("TILDETRIM",`(\\s*)${c[l.LONETILDE]}\\s+`,!0),e.tildeTrimReplace="$1~",y("TILDE",`^${c[l.LONETILDE]}${c[l.XRANGEPLAIN]}$`),y("TILDELOOSE",`^${c[l.LONETILDE]}${c[l.XRANGEPLAINLOOSE]}$`),y("LONECARET","(?:\\^)"),y("CARETTRIM",`(\\s*)${c[l.LONECARET]}\\s+`,!0),e.caretTrimReplace="$1^",y("CARET",`^${c[l.LONECARET]}${c[l.XRANGEPLAIN]}$`),y("CARETLOOSE",`^${c[l.LONECARET]}${c[l.XRANGEPLAINLOOSE]}$`),y("COMPARATORLOOSE",`^${c[l.GTLT]}\\s*(${c[l.LOOSEPLAIN]})$|^$`),y("COMPARATOR",`^${c[l.GTLT]}\\s*(${c[l.FULLPLAIN]})$|^$`),y("COMPARATORTRIM",`(\\s*)${c[l.GTLT]}\\s*(${c[l.LOOSEPLAIN]}|${c[l.XRANGEPLAIN]})`,!0),e.comparatorTrimReplace="$1$2$3",y("HYPHENRANGE",`^\\s*(${c[l.XRANGEPLAIN]})\\s+-\\s+(${c[l.XRANGEPLAIN]})\\s*$`),y("HYPHENRANGELOOSE",`^\\s*(${c[l.XRANGEPLAINLOOSE]})\\s+-\\s+(${c[l.XRANGEPLAINLOOSE]})\\s*$`),y("STAR","(<|>)?=?\\s*\\*"),y("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$"),y("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")})(rn,rn.exports)),rn.exports}var la,To;function oi(){if(To)return la;To=1;const t=Object.freeze({loose:!0}),e=Object.freeze({});return la=n=>n?typeof n!="object"?t:n:e,la}var da,So;function Su(){if(So)return da;So=1;const t=/^[0-9]+$/,e=(n,a)=>{if(typeof n=="number"&&typeof a=="number")return n===a?0:n<a?-1:1;const s=t.test(n),i=t.test(a);return s&&i&&(n=+n,a=+a),n===a?0:s&&!i?-1:i&&!s?1:n<a?-1:1};return da={compareIdentifiers:e,rcompareIdentifiers:(n,a)=>e(a,n)},da}var ha,Io;function Fe(){if(Io)return ha;Io=1;const t=Ln(),{MAX_LENGTH:e,MAX_SAFE_INTEGER:r}=Mn(),{safeRe:n,t:a}=Hr(),s=oi(),{compareIdentifiers:i}=Su();class o{constructor(u,l){if(l=s(l),u instanceof o){if(u.loose===!!l.loose&&u.includePrerelease===!!l.includePrerelease)return u;u=u.version}else if(typeof u!="string")throw new TypeError(`Invalid version. Must be a string. Got type "${typeof u}".`);if(u.length>e)throw new TypeError(`version is longer than ${e} characters`);t("SemVer",u,l),this.options=l,this.loose=!!l.loose,this.includePrerelease=!!l.includePrerelease;const d=u.trim().match(l.loose?n[a.LOOSE]:n[a.FULL]);if(!d)throw new TypeError(`Invalid Version: ${u}`);if(this.raw=u,this.major=+d[1],this.minor=+d[2],this.patch=+d[3],this.major>r||this.major<0)throw new TypeError("Invalid major version");if(this.minor>r||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>r||this.patch<0)throw new TypeError("Invalid patch version");d[4]?this.prerelease=d[4].split(".").map(h=>{if(/^[0-9]+$/.test(h)){const p=+h;if(p>=0&&p<r)return p}return h}):this.prerelease=[],this.build=d[5]?d[5].split("."):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(".")}`),this.version}toString(){return this.version}compare(u){if(t("SemVer.compare",this.version,this.options,u),!(u instanceof o)){if(typeof u=="string"&&u===this.version)return 0;u=new o(u,this.options)}return u.version===this.version?0:this.compareMain(u)||this.comparePre(u)}compareMain(u){return u instanceof o||(u=new o(u,this.options)),this.major<u.major?-1:this.major>u.major?1:this.minor<u.minor?-1:this.minor>u.minor?1:this.patch<u.patch?-1:this.patch>u.patch?1:0}comparePre(u){if(u instanceof o||(u=new o(u,this.options)),this.prerelease.length&&!u.prerelease.length)return-1;if(!this.prerelease.length&&u.prerelease.length)return 1;if(!this.prerelease.length&&!u.prerelease.length)return 0;let l=0;do{const d=this.prerelease[l],h=u.prerelease[l];if(t("prerelease compare",l,d,h),d===void 0&&h===void 0)return 0;if(h===void 0)return 1;if(d===void 0)return-1;if(d===h)continue;return i(d,h)}while(++l)}compareBuild(u){u instanceof o||(u=new o(u,this.options));let l=0;do{const d=this.build[l],h=u.build[l];if(t("build compare",l,d,h),d===void 0&&h===void 0)return 0;if(h===void 0)return 1;if(d===void 0)return-1;if(d===h)continue;return i(d,h)}while(++l)}inc(u,l,d){if(u.startsWith("pre")){if(!l&&d===!1)throw new Error("invalid increment argument: identifier is empty");if(l){const h=`-${l}`.match(this.options.loose?n[a.PRERELEASELOOSE]:n[a.PRERELEASE]);if(!h||h[1]!==l)throw new Error(`invalid identifier: ${l}`)}}switch(u){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",l,d);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",l,d);break;case"prepatch":this.prerelease.length=0,this.inc("patch",l,d),this.inc("pre",l,d);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",l,d),this.inc("pre",l,d);break;case"release":if(this.prerelease.length===0)throw new Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case"patch":this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case"pre":{const h=Number(d)?1:0;if(this.prerelease.length===0)this.prerelease=[h];else{let p=this.prerelease.length;for(;--p>=0;)typeof this.prerelease[p]=="number"&&(this.prerelease[p]++,p=-2);if(p===-1){if(l===this.prerelease.join(".")&&d===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(h)}}if(l){let p=[l,h];d===!1&&(p=[l]),i(this.prerelease[0],l)===0?isNaN(this.prerelease[1])&&(this.prerelease=p):this.prerelease=p}break}default:throw new Error(`invalid increment argument: ${u}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}}return ha=o,ha}var fa,xo;function yr(){if(xo)return fa;xo=1;const t=Fe();return fa=(r,n,a=!1)=>{if(r instanceof t)return r;try{return new t(r,n)}catch(s){if(!a)return null;throw s}},fa}var pa,Ao;function zf(){if(Ao)return pa;Ao=1;const t=yr();return pa=(r,n)=>{const a=t(r,n);return a?a.version:null},pa}var ma,Oo;function qf(){if(Oo)return ma;Oo=1;const t=yr();return ma=(r,n)=>{const a=t(r.trim().replace(/^[=v]+/,""),n);return a?a.version:null},ma}var ga,ko;function Gf(){if(ko)return ga;ko=1;const t=Fe();return ga=(r,n,a,s,i)=>{typeof a=="string"&&(i=s,s=a,a=void 0);try{return new t(r instanceof t?r.version:r,a).inc(n,s,i).version}catch{return null}},ga}var _a,Ro;function Hf(){if(Ro)return _a;Ro=1;const t=yr();return _a=(r,n)=>{const a=t(r,null,!0),s=t(n,null,!0),i=a.compare(s);if(i===0)return null;const o=i>0,c=o?a:s,u=o?s:a,l=!!c.prerelease.length;if(!!u.prerelease.length&&!l){if(!u.patch&&!u.minor)return"major";if(u.compareMain(c)===0)return u.minor&&!u.patch?"minor":"patch"}const h=l?"pre":"";return a.major!==s.major?h+"major":a.minor!==s.minor?h+"minor":a.patch!==s.patch?h+"patch":"prerelease"},_a}var ya,Co;function Zf(){if(Co)return ya;Co=1;const t=Fe();return ya=(r,n)=>new t(r,n).major,ya}var va,No;function Vf(){if(No)return va;No=1;const t=Fe();return va=(r,n)=>new t(r,n).minor,va}var wa,$o;function Wf(){if($o)return wa;$o=1;const t=Fe();return wa=(r,n)=>new t(r,n).patch,wa}var ba,Po;function Jf(){if(Po)return ba;Po=1;const t=yr();return ba=(r,n)=>{const a=t(r,n);return a&&a.prerelease.length?a.prerelease:null},ba}var Ea,Mo;function ut(){if(Mo)return Ea;Mo=1;const t=Fe();return Ea=(r,n,a)=>new t(r,a).compare(new t(n,a)),Ea}var Ta,Lo;function Kf(){if(Lo)return Ta;Lo=1;const t=ut();return Ta=(r,n,a)=>t(n,r,a),Ta}var Sa,jo;function Yf(){if(jo)return Sa;jo=1;const t=ut();return Sa=(r,n)=>t(r,n,!0),Sa}var Ia,Do;function ci(){if(Do)return Ia;Do=1;const t=Fe();return Ia=(r,n,a)=>{const s=new t(r,a),i=new t(n,a);return s.compare(i)||s.compareBuild(i)},Ia}var xa,Uo;function Xf(){if(Uo)return xa;Uo=1;const t=ci();return xa=(r,n)=>r.sort((a,s)=>t(a,s,n)),xa}var Aa,Fo;function Qf(){if(Fo)return Aa;Fo=1;const t=ci();return Aa=(r,n)=>r.sort((a,s)=>t(s,a,n)),Aa}var Oa,Bo;function jn(){if(Bo)return Oa;Bo=1;const t=ut();return Oa=(r,n,a)=>t(r,n,a)>0,Oa}var ka,zo;function ui(){if(zo)return ka;zo=1;const t=ut();return ka=(r,n,a)=>t(r,n,a)<0,ka}var Ra,qo;function Iu(){if(qo)return Ra;qo=1;const t=ut();return Ra=(r,n,a)=>t(r,n,a)===0,Ra}var Ca,Go;function xu(){if(Go)return Ca;Go=1;const t=ut();return Ca=(r,n,a)=>t(r,n,a)!==0,Ca}var Na,Ho;function li(){if(Ho)return Na;Ho=1;const t=ut();return Na=(r,n,a)=>t(r,n,a)>=0,Na}var $a,Zo;function di(){if(Zo)return $a;Zo=1;const t=ut();return $a=(r,n,a)=>t(r,n,a)<=0,$a}var Pa,Vo;function Au(){if(Vo)return Pa;Vo=1;const t=Iu(),e=xu(),r=jn(),n=li(),a=ui(),s=di();return Pa=(o,c,u,l)=>{switch(c){case"===":return typeof o=="object"&&(o=o.version),typeof u=="object"&&(u=u.version),o===u;case"!==":return typeof o=="object"&&(o=o.version),typeof u=="object"&&(u=u.version),o!==u;case"":case"=":case"==":return t(o,u,l);case"!=":return e(o,u,l);case">":return r(o,u,l);case">=":return n(o,u,l);case"<":return a(o,u,l);case"<=":return s(o,u,l);default:throw new TypeError(`Invalid operator: ${c}`)}},Pa}var Ma,Wo;function ep(){if(Wo)return Ma;Wo=1;const t=Fe(),e=yr(),{safeRe:r,t:n}=Hr();return Ma=(s,i)=>{if(s instanceof t)return s;if(typeof s=="number"&&(s=String(s)),typeof s!="string")return null;i=i||{};let o=null;if(!i.rtl)o=s.match(i.includePrerelease?r[n.COERCEFULL]:r[n.COERCE]);else{const p=i.includePrerelease?r[n.COERCERTLFULL]:r[n.COERCERTL];let g;for(;(g=p.exec(s))&&(!o||o.index+o[0].length!==s.length);)(!o||g.index+g[0].length!==o.index+o[0].length)&&(o=g),p.lastIndex=g.index+g[1].length+g[2].length;p.lastIndex=-1}if(o===null)return null;const c=o[2],u=o[3]||"0",l=o[4]||"0",d=i.includePrerelease&&o[5]?`-${o[5]}`:"",h=i.includePrerelease&&o[6]?`+${o[6]}`:"";return e(`${c}.${u}.${l}${d}${h}`,i)},Ma}var La,Jo;function tp(){if(Jo)return La;Jo=1;class t{constructor(){this.max=1e3,this.map=new Map}get(r){const n=this.map.get(r);if(n!==void 0)return this.map.delete(r),this.map.set(r,n),n}delete(r){return this.map.delete(r)}set(r,n){if(!this.delete(r)&&n!==void 0){if(this.map.size>=this.max){const s=this.map.keys().next().value;this.delete(s)}this.map.set(r,n)}return this}}return La=t,La}var ja,Ko;function lt(){if(Ko)return ja;Ko=1;const t=/\s+/g;class e{constructor(A,O){if(O=a(O),A instanceof e)return A.loose===!!O.loose&&A.includePrerelease===!!O.includePrerelease?A:new e(A.raw,O);if(A instanceof s)return this.raw=A.value,this.set=[[A]],this.formatted=void 0,this;if(this.options=O,this.loose=!!O.loose,this.includePrerelease=!!O.includePrerelease,this.raw=A.trim().replace(t," "),this.set=this.raw.split("||").map(B=>this.parseRange(B.trim())).filter(B=>B.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){const B=this.set[0];if(this.set=this.set.filter(q=>!y(q[0])),this.set.length===0)this.set=[B];else if(this.set.length>1){for(const q of this.set)if(q.length===1&&v(q[0])){this.set=[q];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let A=0;A<this.set.length;A++){A>0&&(this.formatted+="||");const O=this.set[A];for(let B=0;B<O.length;B++)B>0&&(this.formatted+=" "),this.formatted+=O[B].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(A){const B=((this.options.includePrerelease&&p)|(this.options.loose&&g))+":"+A,q=n.get(B);if(q)return q;const U=this.options.loose,V=U?c[u.HYPHENRANGELOOSE]:c[u.HYPHENRANGE];A=A.replace(V,Ne(this.options.includePrerelease)),i("hyphen replace",A),A=A.replace(c[u.COMPARATORTRIM],l),i("comparator trim",A),A=A.replace(c[u.TILDETRIM],d),i("tilde trim",A),A=A.replace(c[u.CARETTRIM],h),i("caret trim",A);let ae=A.split(" ").map(ce=>S(ce,this.options)).join(" ").split(/\s+/).map(ce=>oe(ce,this.options));U&&(ae=ae.filter(ce=>(i("loose invalid filter",ce,this.options),!!ce.match(c[u.COMPARATORLOOSE])))),i("range list",ae);const ee=new Map,le=ae.map(ce=>new s(ce,this.options));for(const ce of le){if(y(ce))return[ce];ee.set(ce.value,ce)}ee.size>1&&ee.has("")&&ee.delete("");const Te=[...ee.values()];return n.set(B,Te),Te}intersects(A,O){if(!(A instanceof e))throw new TypeError("a Range is required");return this.set.some(B=>b(B,O)&&A.set.some(q=>b(q,O)&&B.every(U=>q.every(V=>U.intersects(V,O)))))}test(A){if(!A)return!1;if(typeof A=="string")try{A=new o(A,this.options)}catch{return!1}for(let O=0;O<this.set.length;O++)if(vt(this.set[O],A,this.options))return!0;return!1}}ja=e;const r=tp(),n=new r,a=oi(),s=Dn(),i=Ln(),o=Fe(),{safeRe:c,t:u,comparatorTrimReplace:l,tildeTrimReplace:d,caretTrimReplace:h}=Hr(),{FLAG_INCLUDE_PRERELEASE:p,FLAG_LOOSE:g}=Mn(),y=R=>R.value==="<0.0.0-0",v=R=>R.value==="",b=(R,A)=>{let O=!0;const B=R.slice();let q=B.pop();for(;O&&B.length;)O=B.every(U=>q.intersects(U,A)),q=B.pop();return O},S=(R,A)=>(R=R.replace(c[u.BUILD],""),i("comp",R,A),R=F(R,A),i("caret",R),R=k(R,A),i("tildes",R),R=_(R,A),i("xrange",R),R=ye(R,A),i("stars",R),R),E=R=>!R||R.toLowerCase()==="x"||R==="*",k=(R,A)=>R.trim().split(/\s+/).map(O=>C(O,A)).join(" "),C=(R,A)=>{const O=A.loose?c[u.TILDELOOSE]:c[u.TILDE];return R.replace(O,(B,q,U,V,ae)=>{i("tilde",R,B,q,U,V,ae);let ee;return E(q)?ee="":E(U)?ee=`>=${q}.0.0 <${+q+1}.0.0-0`:E(V)?ee=`>=${q}.${U}.0 <${q}.${+U+1}.0-0`:ae?(i("replaceTilde pr",ae),ee=`>=${q}.${U}.${V}-${ae} <${q}.${+U+1}.0-0`):ee=`>=${q}.${U}.${V} <${q}.${+U+1}.0-0`,i("tilde return",ee),ee})},F=(R,A)=>R.trim().split(/\s+/).map(O=>W(O,A)).join(" "),W=(R,A)=>{i("caret",R,A);const O=A.loose?c[u.CARETLOOSE]:c[u.CARET],B=A.includePrerelease?"-0":"";return R.replace(O,(q,U,V,ae,ee)=>{i("caret",R,q,U,V,ae,ee);let le;return E(U)?le="":E(V)?le=`>=${U}.0.0${B} <${+U+1}.0.0-0`:E(ae)?U==="0"?le=`>=${U}.${V}.0${B} <${U}.${+V+1}.0-0`:le=`>=${U}.${V}.0${B} <${+U+1}.0.0-0`:ee?(i("replaceCaret pr",ee),U==="0"?V==="0"?le=`>=${U}.${V}.${ae}-${ee} <${U}.${V}.${+ae+1}-0`:le=`>=${U}.${V}.${ae}-${ee} <${U}.${+V+1}.0-0`:le=`>=${U}.${V}.${ae}-${ee} <${+U+1}.0.0-0`):(i("no pr"),U==="0"?V==="0"?le=`>=${U}.${V}.${ae}${B} <${U}.${V}.${+ae+1}-0`:le=`>=${U}.${V}.${ae}${B} <${U}.${+V+1}.0-0`:le=`>=${U}.${V}.${ae} <${+U+1}.0.0-0`),i("caret return",le),le})},_=(R,A)=>(i("replaceXRanges",R,A),R.split(/\s+/).map(O=>ge(O,A)).join(" ")),ge=(R,A)=>{R=R.trim();const O=A.loose?c[u.XRANGELOOSE]:c[u.XRANGE];return R.replace(O,(B,q,U,V,ae,ee)=>{i("xRange",R,B,q,U,V,ae,ee);const le=E(U),Te=le||E(V),ce=Te||E(ae),m=ce;return q==="="&&m&&(q=""),ee=A.includePrerelease?"-0":"",le?q===">"||q==="<"?B="<0.0.0-0":B="*":q&&m?(Te&&(V=0),ae=0,q===">"?(q=">=",Te?(U=+U+1,V=0,ae=0):(V=+V+1,ae=0)):q==="<="&&(q="<",Te?U=+U+1:V=+V+1),q==="<"&&(ee="-0"),B=`${q+U}.${V}.${ae}${ee}`):Te?B=`>=${U}.0.0${ee} <${+U+1}.0.0-0`:ce&&(B=`>=${U}.${V}.0${ee} <${U}.${+V+1}.0-0`),i("xRange return",B),B})},ye=(R,A)=>(i("replaceStars",R,A),R.trim().replace(c[u.STAR],"")),oe=(R,A)=>(i("replaceGTE0",R,A),R.trim().replace(c[A.includePrerelease?u.GTE0PRE:u.GTE0],"")),Ne=R=>(A,O,B,q,U,V,ae,ee,le,Te,ce,m)=>(E(B)?O="":E(q)?O=`>=${B}.0.0${R?"-0":""}`:E(U)?O=`>=${B}.${q}.0${R?"-0":""}`:V?O=`>=${O}`:O=`>=${O}${R?"-0":""}`,E(le)?ee="":E(Te)?ee=`<${+le+1}.0.0-0`:E(ce)?ee=`<${le}.${+Te+1}.0-0`:m?ee=`<=${le}.${Te}.${ce}-${m}`:R?ee=`<${le}.${Te}.${+ce+1}-0`:ee=`<=${ee}`,`${O} ${ee}`.trim()),vt=(R,A,O)=>{for(let B=0;B<R.length;B++)if(!R[B].test(A))return!1;if(A.prerelease.length&&!O.includePrerelease){for(let B=0;B<R.length;B++)if(i(R[B].semver),R[B].semver!==s.ANY&&R[B].semver.prerelease.length>0){const q=R[B].semver;if(q.major===A.major&&q.minor===A.minor&&q.patch===A.patch)return!0}return!1}return!0};return ja}var Da,Yo;function Dn(){if(Yo)return Da;Yo=1;const t=Symbol("SemVer ANY");class e{static get ANY(){return t}constructor(l,d){if(d=r(d),l instanceof e){if(l.loose===!!d.loose)return l;l=l.value}l=l.trim().split(/\s+/).join(" "),i("comparator",l,d),this.options=d,this.loose=!!d.loose,this.parse(l),this.semver===t?this.value="":this.value=this.operator+this.semver.version,i("comp",this)}parse(l){const d=this.options.loose?n[a.COMPARATORLOOSE]:n[a.COMPARATOR],h=l.match(d);if(!h)throw new TypeError(`Invalid comparator: ${l}`);this.operator=h[1]!==void 0?h[1]:"",this.operator==="="&&(this.operator=""),h[2]?this.semver=new o(h[2],this.options.loose):this.semver=t}toString(){return this.value}test(l){if(i("Comparator.test",l,this.options.loose),this.semver===t||l===t)return!0;if(typeof l=="string")try{l=new o(l,this.options)}catch{return!1}return s(l,this.operator,this.semver,this.options)}intersects(l,d){if(!(l instanceof e))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new c(l.value,d).test(this.value):l.operator===""?l.value===""?!0:new c(this.value,d).test(l.semver):(d=r(d),d.includePrerelease&&(this.value==="<0.0.0-0"||l.value==="<0.0.0-0")||!d.includePrerelease&&(this.value.startsWith("<0.0.0")||l.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&l.operator.startsWith(">")||this.operator.startsWith("<")&&l.operator.startsWith("<")||this.semver.version===l.semver.version&&this.operator.includes("=")&&l.operator.includes("=")||s(this.semver,"<",l.semver,d)&&this.operator.startsWith(">")&&l.operator.startsWith("<")||s(this.semver,">",l.semver,d)&&this.operator.startsWith("<")&&l.operator.startsWith(">")))}}Da=e;const r=oi(),{safeRe:n,t:a}=Hr(),s=Au(),i=Ln(),o=Fe(),c=lt();return Da}var Ua,Xo;function Un(){if(Xo)return Ua;Xo=1;const t=lt();return Ua=(r,n,a)=>{try{n=new t(n,a)}catch{return!1}return n.test(r)},Ua}var Fa,Qo;function rp(){if(Qo)return Fa;Qo=1;const t=lt();return Fa=(r,n)=>new t(r,n).set.map(a=>a.map(s=>s.value).join(" ").trim().split(" ")),Fa}var Ba,ec;function np(){if(ec)return Ba;ec=1;const t=Fe(),e=lt();return Ba=(n,a,s)=>{let i=null,o=null,c=null;try{c=new e(a,s)}catch{return null}return n.forEach(u=>{c.test(u)&&(!i||o.compare(u)===-1)&&(i=u,o=new t(i,s))}),i},Ba}var za,tc;function ap(){if(tc)return za;tc=1;const t=Fe(),e=lt();return za=(n,a,s)=>{let i=null,o=null,c=null;try{c=new e(a,s)}catch{return null}return n.forEach(u=>{c.test(u)&&(!i||o.compare(u)===1)&&(i=u,o=new t(i,s))}),i},za}var qa,rc;function sp(){if(rc)return qa;rc=1;const t=Fe(),e=lt(),r=jn();return qa=(a,s)=>{a=new e(a,s);let i=new t("0.0.0");if(a.test(i)||(i=new t("0.0.0-0"),a.test(i)))return i;i=null;for(let o=0;o<a.set.length;++o){const c=a.set[o];let u=null;c.forEach(l=>{const d=new t(l.semver.version);switch(l.operator){case">":d.prerelease.length===0?d.patch++:d.prerelease.push(0),d.raw=d.format();case"":case">=":(!u||r(d,u))&&(u=d);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${l.operator}`)}}),u&&(!i||r(i,u))&&(i=u)}return i&&a.test(i)?i:null},qa}var Ga,nc;function ip(){if(nc)return Ga;nc=1;const t=lt();return Ga=(r,n)=>{try{return new t(r,n).range||"*"}catch{return null}},Ga}var Ha,ac;function hi(){if(ac)return Ha;ac=1;const t=Fe(),e=Dn(),{ANY:r}=e,n=lt(),a=Un(),s=jn(),i=ui(),o=di(),c=li();return Ha=(l,d,h,p)=>{l=new t(l,p),d=new n(d,p);let g,y,v,b,S;switch(h){case">":g=s,y=o,v=i,b=">",S=">=";break;case"<":g=i,y=c,v=s,b="<",S="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(a(l,d,p))return!1;for(let E=0;E<d.set.length;++E){const k=d.set[E];let C=null,F=null;if(k.forEach(W=>{W.semver===r&&(W=new e(">=0.0.0")),C=C||W,F=F||W,g(W.semver,C.semver,p)?C=W:v(W.semver,F.semver,p)&&(F=W)}),C.operator===b||C.operator===S||(!F.operator||F.operator===b)&&y(l,F.semver))return!1;if(F.operator===S&&v(l,F.semver))return!1}return!0},Ha}var Za,sc;function op(){if(sc)return Za;sc=1;const t=hi();return Za=(r,n,a)=>t(r,n,">",a),Za}var Va,ic;function cp(){if(ic)return Va;ic=1;const t=hi();return Va=(r,n,a)=>t(r,n,"<",a),Va}var Wa,oc;function up(){if(oc)return Wa;oc=1;const t=lt();return Wa=(r,n,a)=>(r=new t(r,a),n=new t(n,a),r.intersects(n,a)),Wa}var Ja,cc;function lp(){if(cc)return Ja;cc=1;const t=Un(),e=ut();return Ja=(r,n,a)=>{const s=[];let i=null,o=null;const c=r.sort((h,p)=>e(h,p,a));for(const h of c)t(h,n,a)?(o=h,i||(i=h)):(o&&s.push([i,o]),o=null,i=null);i&&s.push([i,null]);const u=[];for(const[h,p]of s)h===p?u.push(h):!p&&h===c[0]?u.push("*"):p?h===c[0]?u.push(`<=${p}`):u.push(`${h} - ${p}`):u.push(`>=${h}`);const l=u.join(" || "),d=typeof n.raw=="string"?n.raw:String(n);return l.length<d.length?l:n},Ja}var Ka,uc;function dp(){if(uc)return Ka;uc=1;const t=lt(),e=Dn(),{ANY:r}=e,n=Un(),a=ut(),s=(d,h,p={})=>{if(d===h)return!0;d=new t(d,p),h=new t(h,p);let g=!1;e:for(const y of d.set){for(const v of h.set){const b=c(y,v,p);if(g=g||b!==null,b)continue e}if(g)return!1}return!0},i=[new e(">=0.0.0-0")],o=[new e(">=0.0.0")],c=(d,h,p)=>{if(d===h)return!0;if(d.length===1&&d[0].semver===r){if(h.length===1&&h[0].semver===r)return!0;p.includePrerelease?d=i:d=o}if(h.length===1&&h[0].semver===r){if(p.includePrerelease)return!0;h=o}const g=new Set;let y,v;for(const _ of d)_.operator===">"||_.operator===">="?y=u(y,_,p):_.operator==="<"||_.operator==="<="?v=l(v,_,p):g.add(_.semver);if(g.size>1)return null;let b;if(y&&v){if(b=a(y.semver,v.semver,p),b>0)return null;if(b===0&&(y.operator!==">="||v.operator!=="<="))return null}for(const _ of g){if(y&&!n(_,String(y),p)||v&&!n(_,String(v),p))return null;for(const ge of h)if(!n(_,String(ge),p))return!1;return!0}let S,E,k,C,F=v&&!p.includePrerelease&&v.semver.prerelease.length?v.semver:!1,W=y&&!p.includePrerelease&&y.semver.prerelease.length?y.semver:!1;F&&F.prerelease.length===1&&v.operator==="<"&&F.prerelease[0]===0&&(F=!1);for(const _ of h){if(C=C||_.operator===">"||_.operator===">=",k=k||_.operator==="<"||_.operator==="<=",y){if(W&&_.semver.prerelease&&_.semver.prerelease.length&&_.semver.major===W.major&&_.semver.minor===W.minor&&_.semver.patch===W.patch&&(W=!1),_.operator===">"||_.operator===">="){if(S=u(y,_,p),S===_&&S!==y)return!1}else if(y.operator===">="&&!n(y.semver,String(_),p))return!1}if(v){if(F&&_.semver.prerelease&&_.semver.prerelease.length&&_.semver.major===F.major&&_.semver.minor===F.minor&&_.semver.patch===F.patch&&(F=!1),_.operator==="<"||_.operator==="<="){if(E=l(v,_,p),E===_&&E!==v)return!1}else if(v.operator==="<="&&!n(v.semver,String(_),p))return!1}if(!_.operator&&(v||y)&&b!==0)return!1}return!(y&&k&&!v&&b!==0||v&&C&&!y&&b!==0||W||F)},u=(d,h,p)=>{if(!d)return h;const g=a(d.semver,h.semver,p);return g>0?d:g<0||h.operator===">"&&d.operator===">="?h:d},l=(d,h,p)=>{if(!d)return h;const g=a(d.semver,h.semver,p);return g<0?d:g>0||h.operator==="<"&&d.operator==="<="?h:d};return Ka=s,Ka}var Ya,lc;function hp(){if(lc)return Ya;lc=1;const t=Hr(),e=Mn(),r=Fe(),n=Su(),a=yr(),s=zf(),i=qf(),o=Gf(),c=Hf(),u=Zf(),l=Vf(),d=Wf(),h=Jf(),p=ut(),g=Kf(),y=Yf(),v=ci(),b=Xf(),S=Qf(),E=jn(),k=ui(),C=Iu(),F=xu(),W=li(),_=di(),ge=Au(),ye=ep(),oe=Dn(),Ne=lt(),vt=Un(),R=rp(),A=np(),O=ap(),B=sp(),q=ip(),U=hi(),V=op(),ae=cp(),ee=up(),le=lp(),Te=dp();return Ya={parse:a,valid:s,clean:i,inc:o,diff:c,major:u,minor:l,patch:d,prerelease:h,compare:p,rcompare:g,compareLoose:y,compareBuild:v,sort:b,rsort:S,gt:E,lt:k,eq:C,neq:F,gte:W,lte:_,cmp:ge,coerce:ye,Comparator:oe,Range:Ne,satisfies:vt,toComparators:R,maxSatisfying:A,minSatisfying:O,minVersion:B,validRange:q,outside:U,gtr:V,ltr:ae,intersects:ee,simplifyRange:le,subset:Te,SemVer:r,re:t.re,src:t.src,tokens:t.t,SEMVER_SPEC_VERSION:e.SEMVER_SPEC_VERSION,RELEASE_TYPES:e.RELEASE_TYPES,compareIdentifiers:n.compareIdentifiers,rcompareIdentifiers:n.rcompareIdentifiers},Ya}hp();function Ot(t){if(!t||t.split("/").length>2||t.startsWith("/")||t.endsWith("/")||t.split(":").length>2)throw new Error(`Invalid identifier format: ${t}`);const[e,r]=t.split(":"),n=r||"latest";if(e.includes("/")){const[a,s]=e.split("/",2);if(!a||!s)throw new Error(`Invalid identifier format: ${t}`);return[a,s,n]}else{if(!e)throw new Error(`Invalid identifier format: ${t}`);return["-",e,n]}}class fp extends Error{constructor(e){super(e),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="LangSmithConflictError",this.status=409}}async function G(t,e,r){let n;if(t.ok){r&&(n=await t.text());return}if(t.status===403)try{(await t.json())?.error==="org_scoped_key_requires_workspace"&&(n="This API key is org-scoped and requires workspace specification. Please provide 'workspaceId' parameter, or set LANGSMITH_WORKSPACE_ID environment variable.")}catch{const o=new Error(`${t.status} ${t.statusText}`);throw o.status=t?.status,o}if(n===void 0)try{n=await t.text()}catch{n=""}const a=`Failed to ${e}. Received status [${t.status}]: ${t.statusText}. Message: ${n}`;if(t.status===409)throw new fp(a);const s=new Error(a);throw s.status=t.status,s}const Ou="ERR_CONFLICTING_ENDPOINTS";class pp extends Error{constructor(){super("You cannot provide both LANGSMITH_ENDPOINT / LANGCHAIN_ENDPOINT and LANGSMITH_RUNS_ENDPOINTS."),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:Ou}),this.name="ConflictingEndpointsError"}}function mp(t){return typeof t=="object"&&t!==null&&t.code===Ou}var dc="[...]",gp={result:"[Circular]"},wn=[],nr=[];const _p=new TextEncoder;function yp(){return{depthLimit:Number.MAX_SAFE_INTEGER,edgesLimit:Number.MAX_SAFE_INTEGER}}function nn(t){return _p.encode(t)}function ku(t){if(t&&typeof t=="object"&&t!==null){if(t instanceof Map)return Object.fromEntries(t);if(t instanceof Set)return Array.from(t);if(t instanceof Date)return t.toISOString();if(t instanceof RegExp)return t.toString();if(t instanceof Error)return{name:t.name,message:t.message}}else if(typeof t=="bigint")return t.toString();return t}function vp(t){return function(e,r){return ku(r)}}function Ve(t,e,r,n,a){try{const s=JSON.stringify(t,vp(r),n);return nn(s)}catch(s){if(!s.message?.includes("Converting circular structure to JSON"))return console.warn(`[WARNING]: LangSmith received unserializable value.${e?`
|
|
18
|
-
Context: ${e}`:""}`),nn("[Unserializable]");Ge("SUPPRESS_CIRCULAR_JSON_WARNINGS")!=="true"&&console.warn(`[WARNING]: LangSmith received circular JSON. This will decrease tracer performance. ${e?`
|
|
19
|
-
Context: ${e}`:""}`),typeof a>"u"&&(a=yp()),Ts(t,"",0,[],void 0,0,a);let i;try{nr.length===0?i=JSON.stringify(t,r,n):i=JSON.stringify(t,wp(r),n)}catch{return nn("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;wn.length!==0;){const o=wn.pop();o.length===4?Object.defineProperty(o[0],o[1],o[3]):o[0][o[1]]=o[2]}}return nn(i)}}function Xa(t,e,r,n){var a=Object.getOwnPropertyDescriptor(n,r);a.get!==void 0?a.configurable?(Object.defineProperty(n,r,{value:t}),wn.push([n,r,e,a])):nr.push([e,r,t]):(n[r]=t,wn.push([n,r,e]))}function Ts(t,e,r,n,a,s,i){s+=1;var o;if(typeof t=="object"&&t!==null){for(o=0;o<n.length;o++)if(n[o]===t){Xa(gp,t,e,a);return}if(typeof i.depthLimit<"u"&&s>i.depthLimit){Xa(dc,t,e,a);return}if(typeof i.edgesLimit<"u"&&r+1>i.edgesLimit){Xa(dc,t,e,a);return}if(n.push(t),Array.isArray(t))for(o=0;o<t.length;o++)Ts(t[o],o,o,n,t,s,i);else{t=ku(t);var c=Object.keys(t);for(o=0;o<c.length;o++){var u=c[o];Ts(t[u],u,o,n,t,s,i)}}n.pop()}}function wp(t){return t=typeof t<"u"?t:function(e,r){return r},function(e,r){if(nr.length>0)for(var n=0;n<nr.length;n++){var a=nr[n];if(a[1]===e&&a[0]===r){r=a[2],nr.splice(n,1);break}}return t.call(this,e,r)}}function hc(t,e){const r=wu(),n=e??bu(),a=t.extra??{},s=a.metadata;return t.extra={...a,runtime:{...r,...a?.runtime},metadata:{...n,...n.revision_id||"revision_id"in t&&t.revision_id?{revision_id:("revision_id"in t?t.revision_id:void 0)??n.revision_id}:{},...s}},t}const bp=t=>{const e=t?.toString()??Ge("TRACING_SAMPLING_RATE");if(e===void 0)return;const r=parseFloat(e);if(r<0||r>1)throw new Error(`LANGSMITH_TRACING_SAMPLING_RATE must be between 0 and 1 if set. Got: ${r}`);return r},Ep=t=>{const r=t.replace("http://","").replace("https://","").split("/")[0].split(":")[0];return r==="localhost"||r==="127.0.0.1"||r==="::1"};async function Tp(t){const e=[];for await(const r of t)e.push(r);return e}function an(t){if(t!==void 0)return t.trim().replace(/^"(.*)"$/,"$1").replace(/^'(.*)'$/,"$1")}const Sp=async t=>{if(t?.status===429){const e=parseInt(t.headers.get("retry-after")??"10",10)*1e3;if(e>0)return await new Promise(r=>setTimeout(r,e)),!0}return!1};function fc(t){return typeof t=="number"?Number(t.toFixed(4)):t}class Ip{constructor(){Object.defineProperty(this,"items",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"sizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:0})}peek(){return this.items[0]}push(e){let r;const n=new Promise(s=>{r=s}),a=Ve(e.item,`Serializing run with id: ${e.item.id}`).length;return this.items.push({action:e.action,payload:e.item,otelContext:e.otelContext,apiKey:e.apiKey,apiUrl:e.apiUrl,itemPromiseResolve:r,itemPromise:n,size:a}),this.sizeBytes+=a,n}pop({upToSizeBytes:e,upToSize:r}){if(e<1)throw new Error("Number of bytes to pop off may not be less than 1.");const n=[];let a=0;for(;a+(this.peek()?.size??0)<e&&this.items.length>0&&n.length<r;){const s=this.items.shift();s&&(n.push(s),a+=s.size,this.sizeBytes-=s.size)}if(n.length===0&&this.items.length>0){const s=this.items.shift();n.push(s),a+=s.size,this.sizeBytes-=s.size}return[n.map(s=>({action:s.action,item:s.payload,otelContext:s.otelContext,apiKey:s.apiKey,apiUrl:s.apiUrl})),()=>n.forEach(s=>s.itemPromiseResolve())]}}const xp=24*1024*1024,Ap=1e4,Op=100,pc="https://api.smith.langchain.com";class Dr{get _fetch(){return this.fetchImplementation||lf(this.debug)}constructor(e={}){Object.defineProperty(this,"apiKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"apiUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"webUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"workspaceId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"caller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"batchIngestCaller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"timeout_ms",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_tenantId",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"hideInputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"hideOutputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tracingSampleRate",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"filteredPostUuids",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"autoBatchTracing",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"autoBatchQueue",{enumerable:!0,configurable:!0,writable:!0,value:new Ip}),Object.defineProperty(this,"autoBatchTimeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"autoBatchAggregationDelayMs",{enumerable:!0,configurable:!0,writable:!0,value:250}),Object.defineProperty(this,"batchSizeBytesLimit",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"batchSizeLimit",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"fetchOptions",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"settings",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"blockOnRootRunFinalization",{enumerable:!0,configurable:!0,writable:!0,value:yt("LANGSMITH_TRACING_BACKGROUND")==="false"}),Object.defineProperty(this,"traceBatchConcurrency",{enumerable:!0,configurable:!0,writable:!0,value:5}),Object.defineProperty(this,"_serverInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_getServerInfoPromise",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"manualFlushMode",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"langSmithToOTELTranslator",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"fetchImplementation",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cachedLSEnvVarsForMetadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"multipartStreamingDisabled",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"debug",{enumerable:!0,configurable:!0,writable:!0,value:yt("LANGSMITH_DEBUG")==="true"});const r=Dr.getDefaultClientConfig();if(this.tracingSampleRate=bp(e.tracingSamplingRate),this.apiUrl=an(e.apiUrl??r.apiUrl)??"",this.apiUrl.endsWith("/")&&(this.apiUrl=this.apiUrl.slice(0,-1)),this.apiKey=an(e.apiKey??r.apiKey),this.webUrl=an(e.webUrl??r.webUrl),this.webUrl?.endsWith("/")&&(this.webUrl=this.webUrl.slice(0,-1)),this.workspaceId=an(e.workspaceId??Ge("WORKSPACE_ID")),this.timeout_ms=e.timeout_ms??9e4,this.caller=new go({...e.callerOptions??{},maxRetries:4,debug:e.debug??this.debug}),this.traceBatchConcurrency=e.traceBatchConcurrency??this.traceBatchConcurrency,this.traceBatchConcurrency<1)throw new Error("Trace batch concurrency must be positive.");this.debug=e.debug??this.debug,this.fetchImplementation=e.fetchImplementation,this.batchIngestCaller=new go({maxRetries:2,maxConcurrency:this.traceBatchConcurrency,...e.callerOptions??{},onFailedResponseHook:Sp,debug:e.debug??this.debug}),this.hideInputs=e.hideInputs??e.anonymizer??r.hideInputs,this.hideOutputs=e.hideOutputs??e.anonymizer??r.hideOutputs,this.autoBatchTracing=e.autoBatchTracing??this.autoBatchTracing,this.blockOnRootRunFinalization=e.blockOnRootRunFinalization??this.blockOnRootRunFinalization,this.batchSizeBytesLimit=e.batchSizeBytesLimit,this.batchSizeLimit=e.batchSizeLimit,this.fetchOptions=e.fetchOptions||{},this.manualFlushMode=e.manualFlushMode??this.manualFlushMode,Eu()&&(this.langSmithToOTELTranslator=new Af),this.cachedLSEnvVarsForMetadata=bu()}static getDefaultClientConfig(){const e=Ge("API_KEY"),r=Ge("ENDPOINT")??pc,n=Ge("HIDE_INPUTS")==="true",a=Ge("HIDE_OUTPUTS")==="true";return{apiUrl:r,apiKey:e,webUrl:void 0,hideInputs:n,hideOutputs:a}}getHostUrl(){return this.webUrl?this.webUrl:Ep(this.apiUrl)?(this.webUrl="http://localhost:3000",this.webUrl):this.apiUrl.endsWith("/api/v1")?(this.webUrl=this.apiUrl.replace("/api/v1",""),this.webUrl):this.apiUrl.includes("/api")&&!this.apiUrl.split(".",1)[0].endsWith("api")?(this.webUrl=this.apiUrl.replace("/api",""),this.webUrl):this.apiUrl.split(".",1)[0].includes("dev")?(this.webUrl="https://dev.smith.langchain.com",this.webUrl):this.apiUrl.split(".",1)[0].includes("eu")?(this.webUrl="https://eu.smith.langchain.com",this.webUrl):this.apiUrl.split(".",1)[0].includes("beta")?(this.webUrl="https://beta.smith.langchain.com",this.webUrl):(this.webUrl="https://smith.langchain.com",this.webUrl)}get headers(){const e={"User-Agent":`langsmith-js/${_u}`};return this.apiKey&&(e["x-api-key"]=`${this.apiKey}`),this.workspaceId&&(e["x-tenant-id"]=this.workspaceId),e}_getPlatformEndpointPath(e){return this.apiUrl.slice(-3)!=="/v1"&&this.apiUrl.slice(-4)!=="/v1/"?`/v1/platform/${e}`:`/platform/${e}`}async processInputs(e){return this.hideInputs===!1?e:this.hideInputs===!0?{}:typeof this.hideInputs=="function"?this.hideInputs(e):e}async processOutputs(e){return this.hideOutputs===!1?e:this.hideOutputs===!0?{}:typeof this.hideOutputs=="function"?this.hideOutputs(e):e}async prepareRunCreateOrUpdateInputs(e){const r={...e};return r.inputs!==void 0&&(r.inputs=await this.processInputs(r.inputs)),r.outputs!==void 0&&(r.outputs=await this.processOutputs(r.outputs)),r}async _getResponse(e,r){const n=r?.toString()??"",a=`${this.apiUrl}${e}?${n}`;return await this.caller.call(async()=>{const i=await this._fetch(a,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await G(i,`fetch ${e}`),i})}async _get(e,r){return(await this._getResponse(e,r)).json()}async*_getPaginated(e,r=new URLSearchParams,n){let a=Number(r.get("offset"))||0;const s=Number(r.get("limit"))||100;for(;;){r.set("offset",String(a)),r.set("limit",String(s));const i=`${this.apiUrl}${e}?${r}`,o=await this.caller.call(async()=>{const u=await this._fetch(i,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await G(u,`fetch ${e}`),u}),c=n?n(await o.json()):await o.json();if(c.length===0||(yield c,c.length<s))break;a+=c.length}}async*_getCursorPaginatedList(e,r=null,n="POST",a="runs"){const s=r?{...r}:{};for(;;){const i=JSON.stringify(s),c=await(await this.caller.call(async()=>{const l=await this._fetch(`${this.apiUrl}${e}`,{method:n,headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await G(l,`fetch ${e}`),l})).json();if(!c||!c[a])break;yield c[a];const u=c.cursors;if(!u||!u.next)break;s.cursor=u.next}}_shouldSample(){return this.tracingSampleRate===void 0?!0:Math.random()<this.tracingSampleRate}_filterForSampling(e,r=!1){if(this.tracingSampleRate===void 0)return e;if(r){const n=[];for(const a of e)this.filteredPostUuids.has(a.trace_id)?a.id===a.trace_id&&this.filteredPostUuids.delete(a.trace_id):n.push(a);return n}else{const n=[];for(const a of e){const s=a.trace_id??a.id;this.filteredPostUuids.has(s)||(a.id===s?this._shouldSample()?n.push(a):this.filteredPostUuids.add(s):n.push(a))}return n}}async _getBatchSizeLimitBytes(){const e=await this._ensureServerInfo();return this.batchSizeBytesLimit??e.batch_ingest_config?.size_limit_bytes??xp}async _getBatchSizeLimit(){const e=await this._ensureServerInfo();return this.batchSizeLimit??e.batch_ingest_config?.size_limit??Op}async _getDatasetExamplesMultiPartSupport(){return(await this._ensureServerInfo()).instance_flags?.dataset_examples_multipart_enabled??!1}drainAutoBatchQueue({batchSizeLimitBytes:e,batchSizeLimit:r}){const n=[];for(;this.autoBatchQueue.items.length>0;){const[a,s]=this.autoBatchQueue.pop({upToSizeBytes:e,upToSize:r});if(!a.length){s();break}const i=a.reduce((u,l)=>{const d=l.apiUrl??this.apiUrl,h=l.apiKey??this.apiKey,g=l.apiKey===this.apiKey&&l.apiUrl===this.apiUrl?"default":`${d}|${h}`;return u[g]||(u[g]=[]),u[g].push(l),u},{}),o=[];for(const[u,l]of Object.entries(i)){const d=this._processBatch(l,{apiUrl:u==="default"?void 0:u.split("|")[0],apiKey:u==="default"?void 0:u.split("|")[1]});o.push(d)}const c=Promise.all(o).finally(s);n.push(c)}return Promise.all(n)}async _processBatch(e,r){if(e.length)try{if(this.langSmithToOTELTranslator!==void 0)this._sendBatchToOTELTranslator(e);else{const n={runCreates:e.filter(s=>s.action==="create").map(s=>s.item),runUpdates:e.filter(s=>s.action==="update").map(s=>s.item)},a=await this._ensureServerInfo();if(a?.batch_ingest_config?.use_multipart_endpoint){const s=a?.instance_flags?.gzip_body_enabled;await this.multipartIngestRuns(n,{...r,useGzip:s})}else await this.batchIngestRuns(n,r)}}catch(n){console.error("Error exporting batch:",n)}}_sendBatchToOTELTranslator(e){if(this.langSmithToOTELTranslator!==void 0){const r=new Map,n=[];for(const a of e)a.item.id&&a.otelContext&&(r.set(a.item.id,a.otelContext),a.action==="create"?n.push({operation:"post",id:a.item.id,trace_id:a.item.trace_id??a.item.id,run:a.item}):n.push({operation:"patch",id:a.item.id,trace_id:a.item.trace_id??a.item.id,run:a.item}));this.langSmithToOTELTranslator.exportBatch(n,r)}}async processRunOperation(e){clearTimeout(this.autoBatchTimeout),this.autoBatchTimeout=void 0,e.item=hc(e.item,this.cachedLSEnvVarsForMetadata);const r=this.autoBatchQueue.push(e);if(this.manualFlushMode)return r;const n=await this._getBatchSizeLimitBytes(),a=await this._getBatchSizeLimit();return(this.autoBatchQueue.sizeBytes>n||this.autoBatchQueue.items.length>a)&&this.drainAutoBatchQueue({batchSizeLimitBytes:n,batchSizeLimit:a}),this.autoBatchQueue.items.length>0&&(this.autoBatchTimeout=setTimeout(()=>{this.autoBatchTimeout=void 0,this.drainAutoBatchQueue({batchSizeLimitBytes:n,batchSizeLimit:a})},this.autoBatchAggregationDelayMs)),r}async _getServerInfo(){const r=await(await this.caller.call(async()=>{const n=await this._fetch(`${this.apiUrl}/info`,{method:"GET",headers:{Accept:"application/json"},signal:AbortSignal.timeout(Ap),...this.fetchOptions});return await G(n,"get server info"),n})).json();return this.debug&&console.log(`
|
|
20
|
-
=== LangSmith Server Configuration ===
|
|
21
|
-
`+JSON.stringify(r,null,2)+`
|
|
22
|
-
`),r}async _ensureServerInfo(){return this._getServerInfoPromise===void 0&&(this._getServerInfoPromise=(async()=>{if(this._serverInfo===void 0)try{this._serverInfo=await this._getServerInfo()}catch(e){console.warn(`[LANGSMITH]: Failed to fetch info on supported operations. Falling back to batch operations and default limits. Info: ${e.status??"Unspecified status code"} ${e.message}`)}return this._serverInfo??{}})()),this._getServerInfoPromise.then(e=>(this._serverInfo===void 0&&(this._getServerInfoPromise=void 0),e))}async _getSettings(){return this.settings||(this.settings=this._get("/settings")),await this.settings}async flush(){const e=await this._getBatchSizeLimitBytes(),r=await this._getBatchSizeLimit();await this.drainAutoBatchQueue({batchSizeLimitBytes:e,batchSizeLimit:r})}_cloneCurrentOTELContext(){const e=Tu(),r=Tf();if(this.langSmithToOTELTranslator!==void 0){const n=e.getActiveSpan();if(n)return e.setSpan(r.active(),n)}}async createRun(e,r){if(!this._filterForSampling([e]).length)return;const n={...this.headers,"Content-Type":"application/json"},a=e.project_name;delete e.project_name;const s=await this.prepareRunCreateOrUpdateInputs({session_name:a,...e,start_time:e.start_time??Date.now()});if(this.autoBatchTracing&&s.trace_id!==void 0&&s.dotted_order!==void 0){const c=this._cloneCurrentOTELContext();this.processRunOperation({action:"create",item:s,otelContext:c,apiKey:r?.apiKey,apiUrl:r?.apiUrl}).catch(console.error);return}const i=hc(s,this.cachedLSEnvVarsForMetadata);r?.apiKey!==void 0&&(n["x-api-key"]=r.apiKey),r?.workspaceId!==void 0&&(n["x-tenant-id"]=r.workspaceId);const o=Ve(i,`Creating run with id: ${i.id}`);await this.caller.call(async()=>{const c=await this._fetch(`${r?.apiUrl??this.apiUrl}/runs`,{method:"POST",headers:n,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await G(c,"create run",!0),c})}async batchIngestRuns({runCreates:e,runUpdates:r},n){if(e===void 0&&r===void 0)return;let a=await Promise.all(e?.map(c=>this.prepareRunCreateOrUpdateInputs(c))??[]),s=await Promise.all(r?.map(c=>this.prepareRunCreateOrUpdateInputs(c))??[]);if(a.length>0&&s.length>0){const c=a.reduce((l,d)=>(d.id&&(l[d.id]=d),l),{}),u=[];for(const l of s)l.id!==void 0&&c[l.id]?c[l.id]={...c[l.id],...l}:u.push(l);a=Object.values(c),s=u}const i={post:a,patch:s};if(!i.post.length&&!i.patch.length)return;const o={post:[],patch:[]};for(const c of["post","patch"]){const u=c,l=i[u].reverse();let d=l.pop();for(;d!==void 0;)o[u].push(d),d=l.pop()}if(o.post.length>0||o.patch.length>0){const c=o.post.map(u=>u.id).concat(o.patch.map(u=>u.id)).join(",");await this._postBatchIngestRuns(Ve(o,`Ingesting runs with ids: ${c}`),n)}}async _postBatchIngestRuns(e,r){const n={...this.headers,"Content-Type":"application/json",Accept:"application/json"};r?.apiKey!==void 0&&(n["x-api-key"]=r.apiKey),await this.batchIngestCaller.call(async()=>{const a=await this._fetch(`${r?.apiUrl??this.apiUrl}/runs/batch`,{method:"POST",headers:n,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:e});return await G(a,"batch create run",!0),a})}async multipartIngestRuns({runCreates:e,runUpdates:r},n){if(e===void 0&&r===void 0)return;const a={};let s=[];for(const d of e??[]){const h=await this.prepareRunCreateOrUpdateInputs(d);h.id!==void 0&&h.attachments!==void 0&&(a[h.id]=h.attachments),delete h.attachments,s.push(h)}let i=[];for(const d of r??[])i.push(await this.prepareRunCreateOrUpdateInputs(d));if(s.find(d=>d.trace_id===void 0||d.dotted_order===void 0)!==void 0)throw new Error('Multipart ingest requires "trace_id" and "dotted_order" to be set when creating a run');if(i.find(d=>d.trace_id===void 0||d.dotted_order===void 0)!==void 0)throw new Error('Multipart ingest requires "trace_id" and "dotted_order" to be set when updating a run');if(s.length>0&&i.length>0){const d=s.reduce((p,g)=>(g.id&&(p[g.id]=g),p),{}),h=[];for(const p of i)p.id!==void 0&&d[p.id]?d[p.id]={...d[p.id],...p}:h.push(p);s=Object.values(d),i=h}if(s.length===0&&i.length===0)return;const u=[],l=[];for(const[d,h]of[["post",s],["patch",i]])for(const p of h){const{inputs:g,outputs:y,events:v,extra:b,error:S,serialized:E,attachments:k,...C}=p,F={inputs:g,outputs:y,events:v,extra:b,error:S,serialized:E},W=Ve(C,`Serializing for multipart ingestion of run with id: ${C.id}`);l.push({name:`${d}.${C.id}`,payload:new Blob([W],{type:`application/json; length=${W.length}`})});for(const[_,ge]of Object.entries(F)){if(ge===void 0)continue;const ye=Ve(ge,`Serializing ${_} for multipart ingestion of run with id: ${C.id}`);l.push({name:`${d}.${C.id}.${_}`,payload:new Blob([ye],{type:`application/json; length=${ye.length}`})})}if(C.id!==void 0){const _=a[C.id];if(_){delete a[C.id];for(const[ge,ye]of Object.entries(_)){let oe,Ne;if(Array.isArray(ye)?[oe,Ne]=ye:(oe=ye.mimeType,Ne=ye.data),ge.includes(".")){console.warn(`Skipping attachment '${ge}' for run ${C.id}: Invalid attachment name. Attachment names must not contain periods ('.'). Please rename the attachment and try again.`);continue}l.push({name:`attachment.${C.id}.${ge}`,payload:new Blob([Ne],{type:`${oe}; length=${Ne.byteLength}`})})}}}u.push(`trace=${C.trace_id},id=${C.id}`)}await this._sendMultipartRequest(l,u.join("; "),n)}async _createNodeFetchBody(e,r){const n=[];for(const i of e)n.push(new Blob([`--${r}\r
|
|
23
|
-
`])),n.push(new Blob([`Content-Disposition: form-data; name="${i.name}"\r
|
|
24
|
-
`,`Content-Type: ${i.payload.type}\r
|
|
25
|
-
\r
|
|
26
|
-
`])),n.push(i.payload),n.push(new Blob([`\r
|
|
27
|
-
`]));return n.push(new Blob([`--${r}--\r
|
|
28
|
-
`])),await new Blob(n).arrayBuffer()}async _createMultipartStream(e,r){const n=new TextEncoder;return new ReadableStream({async start(s){const i=async o=>{typeof o=="string"?s.enqueue(n.encode(o)):s.enqueue(o)};for(const o of e){await i(`--${r}\r
|
|
29
|
-
`),await i(`Content-Disposition: form-data; name="${o.name}"\r
|
|
30
|
-
`),await i(`Content-Type: ${o.payload.type}\r
|
|
31
|
-
\r
|
|
32
|
-
`);const u=o.payload.stream().getReader();try{let l;for(;!(l=await u.read()).done;)s.enqueue(l.value)}finally{u.releaseLock()}await i(`\r
|
|
33
|
-
`)}await i(`--${r}--\r
|
|
34
|
-
`),s.close()}})}async _sendMultipartRequest(e,r,n){const a="----LangSmithFormBoundary"+Math.random().toString(36).slice(2),s=uf(),i=()=>this._createNodeFetchBody(e,a),o=()=>this._createMultipartStream(e,a),c=async u=>this.batchIngestCaller.call(async()=>{const l=await u(),d={...this.headers,"Content-Type":`multipart/form-data; boundary=${a}`};n?.apiKey!==void 0&&(d["x-api-key"]=n.apiKey);let h=l;n?.useGzip&&typeof l=="object"&&"pipeThrough"in l&&(h=l.pipeThrough(new CompressionStream("gzip")),d["Content-Encoding"]="gzip");const p=await this._fetch(`${n?.apiUrl??this.apiUrl}/runs/multipart`,{method:"POST",headers:d,body:h,duplex:"half",signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await G(p,"Failed to send multipart request",!0),p});try{let u,l=!1;!s&&!this.multipartStreamingDisabled&&vu()!=="bun"?(l=!0,u=await c(o)):u=await c(i),(!this.multipartStreamingDisabled||l)&&u.status===422&&(n?.apiUrl??this.apiUrl)!==pc&&(console.warn(`Streaming multipart upload to ${n?.apiUrl??this.apiUrl}/runs/multipart failed. This usually means the host does not support chunked uploads. Retrying with a buffered upload for operation "${r}".`),this.multipartStreamingDisabled=!0,u=await c(i))}catch(u){console.warn(`${u.message.trim()}
|
|
35
|
-
|
|
36
|
-
Context: ${r}`)}}async updateRun(e,r,n){re(e),r.inputs&&(r.inputs=await this.processInputs(r.inputs)),r.outputs&&(r.outputs=await this.processOutputs(r.outputs));const a={...r,id:e};if(!this._filterForSampling([a],!0).length)return;if(this.autoBatchTracing&&a.trace_id!==void 0&&a.dotted_order!==void 0){const o=this._cloneCurrentOTELContext();if(r.end_time!==void 0&&a.parent_run_id===void 0&&this.blockOnRootRunFinalization&&!this.manualFlushMode){await this.processRunOperation({action:"update",item:a,otelContext:o,apiKey:n?.apiKey,apiUrl:n?.apiUrl}).catch(console.error);return}else this.processRunOperation({action:"update",item:a,otelContext:o,apiKey:n?.apiKey,apiUrl:n?.apiUrl}).catch(console.error);return}const s={...this.headers,"Content-Type":"application/json"};n?.apiKey!==void 0&&(s["x-api-key"]=n.apiKey),n?.workspaceId!==void 0&&(s["x-tenant-id"]=n.workspaceId);const i=Ve(r,`Serializing payload to update run with id: ${e}`);await this.caller.call(async()=>{const o=await this._fetch(`${n?.apiUrl??this.apiUrl}/runs/${e}`,{method:"PATCH",headers:s,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await G(o,"update run",!0),o})}async readRun(e,{loadChildRuns:r}={loadChildRuns:!1}){re(e);let n=await this._get(`/runs/${e}`);return r&&(n=await this._loadChildRuns(n)),n}async getRunUrl({runId:e,run:r,projectOpts:n}){if(r!==void 0){let a;r.session_id?a=r.session_id:n?.projectName?a=(await this.readProject({projectName:n?.projectName})).id:n?.projectId?a=n?.projectId:a=(await this.readProject({projectName:Ge("PROJECT")||"default"})).id;const s=await this._getTenantId();return`${this.getHostUrl()}/o/${s}/projects/p/${a}/r/${r.id}?poll=true`}else if(e!==void 0){const a=await this.readRun(e);if(!a.app_path)throw new Error(`Run ${e} has no app_path`);return`${this.getHostUrl()}${a.app_path}`}else throw new Error("Must provide either runId or run")}async _loadChildRuns(e){const r=await Tp(this.listRuns({isRoot:!1,projectId:e.session_id,traceId:e.trace_id})),n={},a={};r.sort((s,i)=>(s?.dotted_order??"").localeCompare(i?.dotted_order??""));for(const s of r){if(s.parent_run_id===null||s.parent_run_id===void 0)throw new Error(`Child run ${s.id} has no parent`);s.dotted_order?.startsWith(e.dotted_order??"")&&s.id!==e.id&&(s.parent_run_id in n||(n[s.parent_run_id]=[]),n[s.parent_run_id].push(s),a[s.id]=s)}e.child_runs=n[e.id]||[];for(const s in n)s!==e.id&&(a[s].child_runs=n[s]);return e}async*listRuns(e){const{projectId:r,projectName:n,parentRunId:a,traceId:s,referenceExampleId:i,startTime:o,executionOrder:c,isRoot:u,runType:l,error:d,id:h,query:p,filter:g,traceFilter:y,treeFilter:v,limit:b,select:S,order:E}=e;let k=[];if(r&&(k=Array.isArray(r)?r:[r]),n){const _=Array.isArray(n)?n:[n],ge=await Promise.all(_.map(ye=>this.readProject({projectName:ye}).then(oe=>oe.id)));k.push(...ge)}const C=["app_path","completion_cost","completion_tokens","dotted_order","end_time","error","events","extra","feedback_stats","first_token_time","id","inputs","name","outputs","parent_run_id","parent_run_ids","prompt_cost","prompt_tokens","reference_example_id","run_type","session_id","start_time","status","tags","total_cost","total_tokens","trace_id"],F={session:k.length?k:null,run_type:l,reference_example:i,query:p,filter:g,trace_filter:y,tree_filter:v,execution_order:c,parent_run:a,start_time:o?o.toISOString():null,error:d,id:h,limit:b,trace:s,select:S||C,is_root:u,order:E};F.select.includes("child_run_ids")&&Es("Deprecated: 'child_run_ids' in the listRuns select parameter is deprecated and will be removed in a future version.");let W=0;for await(const _ of this._getCursorPaginatedList("/runs/query",F))if(b){if(W>=b)break;if(_.length+W>b){yield*_.slice(0,b-W);break}W+=_.length,yield*_}else yield*_}async*listGroupRuns(e){const{projectId:r,projectName:n,groupBy:a,filter:s,startTime:i,endTime:o,limit:c,offset:u}=e,d={session_id:r||(await this.readProject({projectName:n})).id,group_by:a,filter:s,start_time:i?i.toISOString():null,end_time:o?o.toISOString():null,limit:Number(c)||100};let h=Number(u)||0;const p="/runs/group",g=`${this.apiUrl}${p}`;for(;;){const y={...d,offset:h},v=Object.fromEntries(Object.entries(y).filter(([F,W])=>W!==void 0)),b=JSON.stringify(v),E=await(await this.caller.call(async()=>{const F=await this._fetch(g,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:b});return await G(F,`Failed to fetch ${p}`),F})).json(),{groups:k,total:C}=E;if(k.length===0)break;for(const F of k)yield F;if(h+=k.length,h>=C)break}}async getRunStats({id:e,trace:r,parentRun:n,runType:a,projectNames:s,projectIds:i,referenceExampleIds:o,startTime:c,endTime:u,error:l,query:d,filter:h,traceFilter:p,treeFilter:g,isRoot:y,dataSourceType:v}){let b=i||[];s&&(b=[...i||[],...await Promise.all(s.map(W=>this.readProject({projectName:W}).then(_=>_.id)))]);const E=Object.fromEntries(Object.entries({id:e,trace:r,parent_run:n,run_type:a,session:b,reference_example:o,start_time:c,end_time:u,error:l,query:d,filter:h,trace_filter:p,tree_filter:g,is_root:y,data_source_type:v}).filter(([W,_])=>_!==void 0)),k=JSON.stringify(E);return await(await this.caller.call(async()=>{const W=await this._fetch(`${this.apiUrl}/runs/stats`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:k});return await G(W,"get run stats"),W})).json()}async shareRun(e,{shareId:r}={}){const n={run_id:e,share_token:r||De()};re(e);const a=JSON.stringify(n),i=await(await this.caller.call(async()=>{const o=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:"PUT",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await G(o,"share run"),o})).json();if(i===null||!("share_token"in i))throw new Error("Invalid response from server");return`${this.getHostUrl()}/public/${i.share_token}/r`}async unshareRun(e){re(e),await this.caller.call(async()=>{const r=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await G(r,"unshare run",!0),r})}async readRunSharedLink(e){re(e);const n=await(await this.caller.call(async()=>{const a=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await G(a,"read run shared link"),a})).json();if(!(n===null||!("share_token"in n)))return`${this.getHostUrl()}/public/${n.share_token}/r`}async listSharedRuns(e,{runIds:r}={}){const n=new URLSearchParams({share_token:e});if(r!==void 0)for(const i of r)n.append("id",i);return re(e),await(await this.caller.call(async()=>{const i=await this._fetch(`${this.apiUrl}/public/${e}/runs${n}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await G(i,"list shared runs"),i})).json()}async readDatasetSharedSchema(e,r){if(!e&&!r)throw new Error("Either datasetId or datasetName must be given");e||(e=(await this.readDataset({datasetName:r})).id),re(e);const a=await(await this.caller.call(async()=>{const s=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await G(s,"read dataset shared schema"),s})).json();return a.url=`${this.getHostUrl()}/public/${a.share_token}/d`,a}async shareDataset(e,r){if(!e&&!r)throw new Error("Either datasetId or datasetName must be given");e||(e=(await this.readDataset({datasetName:r})).id);const n={dataset_id:e};re(e);const a=JSON.stringify(n),i=await(await this.caller.call(async()=>{const o=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:"PUT",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await G(o,"share dataset"),o})).json();return i.url=`${this.getHostUrl()}/public/${i.share_token}/d`,i}async unshareDataset(e){re(e),await this.caller.call(async()=>{const r=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await G(r,"unshare dataset",!0),r})}async readSharedDataset(e){return re(e),await(await this.caller.call(async()=>{const a=await this._fetch(`${this.apiUrl}/public/${e}/datasets`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await G(a,"read shared dataset"),a})).json()}async listSharedExamples(e,r){const n={};r?.exampleIds&&(n.id=r.exampleIds);const a=new URLSearchParams;Object.entries(n).forEach(([o,c])=>{Array.isArray(c)?c.forEach(u=>a.append(o,u)):a.append(o,c)});const s=await this.caller.call(async()=>{const o=await this._fetch(`${this.apiUrl}/public/${e}/examples?${a.toString()}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await G(o,"list shared examples"),o}),i=await s.json();if(!s.ok)throw"detail"in i?new Error(`Failed to list shared examples.
|
|
37
|
-
Status: ${s.status}
|
|
38
|
-
Message: ${Array.isArray(i.detail)?i.detail.join(`
|
|
39
|
-
`):"Unspecified error"}`):new Error(`Failed to list shared examples: ${s.status} ${s.statusText}`);return i.map(o=>({...o,_hostUrl:this.getHostUrl()}))}async createProject({projectName:e,description:r=null,metadata:n=null,upsert:a=!1,projectExtra:s=null,referenceDatasetId:i=null}){const o=a?"?upsert=true":"",c=`${this.apiUrl}/sessions${o}`,u=s||{};n&&(u.metadata=n);const l={name:e,extra:u,description:r};i!==null&&(l.reference_dataset_id=i);const d=JSON.stringify(l);return await(await this.caller.call(async()=>{const g=await this._fetch(c,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:d});return await G(g,"create project"),g})).json()}async updateProject(e,{name:r=null,description:n=null,metadata:a=null,projectExtra:s=null,endTime:i=null}){const o=`${this.apiUrl}/sessions/${e}`;let c=s;a&&(c={...c||{},metadata:a});const u=JSON.stringify({name:r,extra:c,description:n,end_time:i?new Date(i).toISOString():null});return await(await this.caller.call(async()=>{const h=await this._fetch(o,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:u});return await G(h,"update project"),h})).json()}async hasProject({projectId:e,projectName:r}){let n="/sessions";const a=new URLSearchParams;if(e!==void 0&&r!==void 0)throw new Error("Must provide either projectName or projectId, not both");if(e!==void 0)re(e),n+=`/${e}`;else if(r!==void 0)a.append("name",r);else throw new Error("Must provide projectName or projectId");const s=await this.caller.call(async()=>{const i=await this._fetch(`${this.apiUrl}${n}?${a}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await G(i,"has project"),i});try{const i=await s.json();return s.ok?Array.isArray(i)?i.length>0:!0:!1}catch{return!1}}async readProject({projectId:e,projectName:r,includeStats:n}){let a="/sessions";const s=new URLSearchParams;if(e!==void 0&&r!==void 0)throw new Error("Must provide either projectName or projectId, not both");if(e!==void 0)re(e),a+=`/${e}`;else if(r!==void 0)s.append("name",r);else throw new Error("Must provide projectName or projectId");n!==void 0&&s.append("include_stats",n.toString());const i=await this._get(a,s);let o;if(Array.isArray(i)){if(i.length===0)throw new Error(`Project[id=${e}, name=${r}] not found`);o=i[0]}else o=i;return o}async getProjectUrl({projectId:e,projectName:r}){if(e===void 0&&r===void 0)throw new Error("Must provide either projectName or projectId");const n=await this.readProject({projectId:e,projectName:r}),a=await this._getTenantId();return`${this.getHostUrl()}/o/${a}/projects/p/${n.id}`}async getDatasetUrl({datasetId:e,datasetName:r}){if(e===void 0&&r===void 0)throw new Error("Must provide either datasetName or datasetId");const n=await this.readDataset({datasetId:e,datasetName:r}),a=await this._getTenantId();return`${this.getHostUrl()}/o/${a}/datasets/${n.id}`}async _getTenantId(){if(this._tenantId!==null)return this._tenantId;const e=new URLSearchParams({limit:"1"});for await(const r of this._getPaginated("/sessions",e))return this._tenantId=r[0].tenant_id,r[0].tenant_id;throw new Error("No projects found to resolve tenant.")}async*listProjects({projectIds:e,name:r,nameContains:n,referenceDatasetId:a,referenceDatasetName:s,includeStats:i,datasetVersion:o,referenceFree:c,metadata:u}={}){const l=new URLSearchParams;if(e!==void 0)for(const d of e)l.append("id",d);if(r!==void 0&&l.append("name",r),n!==void 0&&l.append("name_contains",n),a!==void 0)l.append("reference_dataset",a);else if(s!==void 0){const d=await this.readDataset({datasetName:s});l.append("reference_dataset",d.id)}i!==void 0&&l.append("include_stats",i.toString()),o!==void 0&&l.append("dataset_version",o),c!==void 0&&l.append("reference_free",c.toString()),u!==void 0&&l.append("metadata",JSON.stringify(u));for await(const d of this._getPaginated("/sessions",l))yield*d}async deleteProject({projectId:e,projectName:r}){let n;if(e===void 0&&r===void 0)throw new Error("Must provide projectName or projectId");if(e!==void 0&&r!==void 0)throw new Error("Must provide either projectName or projectId, not both");e===void 0?n=(await this.readProject({projectName:r})).id:n=e,re(n),await this.caller.call(async()=>{const a=await this._fetch(`${this.apiUrl}/sessions/${n}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await G(a,`delete session ${n} (${r})`,!0),a})}async uploadCsv({csvFile:e,fileName:r,inputKeys:n,outputKeys:a,description:s,dataType:i,name:o}){const c=`${this.apiUrl}/datasets/upload`,u=new FormData;return u.append("file",e,r),n.forEach(h=>{u.append("input_keys",h)}),a.forEach(h=>{u.append("output_keys",h)}),s&&u.append("description",s),i&&u.append("data_type",i),o&&u.append("name",o),await(await this.caller.call(async()=>{const h=await this._fetch(c,{method:"POST",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:u});return await G(h,"upload CSV"),h})).json()}async createDataset(e,{description:r,dataType:n,inputsSchema:a,outputsSchema:s,metadata:i}={}){const o={name:e,description:r,extra:i?{metadata:i}:void 0};n&&(o.data_type=n),a&&(o.inputs_schema_definition=a),s&&(o.outputs_schema_definition=s);const c=JSON.stringify(o);return await(await this.caller.call(async()=>{const d=await this._fetch(`${this.apiUrl}/datasets`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await G(d,"create dataset"),d})).json()}async readDataset({datasetId:e,datasetName:r}){let n="/datasets";const a=new URLSearchParams({limit:"1"});if(e&&r)throw new Error("Must provide either datasetName or datasetId, not both");if(e)re(e),n+=`/${e}`;else if(r)a.append("name",r);else throw new Error("Must provide datasetName or datasetId");const s=await this._get(n,a);let i;if(Array.isArray(s)){if(s.length===0)throw new Error(`Dataset[id=${e}, name=${r}] not found`);i=s[0]}else i=s;return i}async hasDataset({datasetId:e,datasetName:r}){try{return await this.readDataset({datasetId:e,datasetName:r}),!0}catch(n){if(n instanceof Error&&n.message.toLocaleLowerCase().includes("not found"))return!1;throw n}}async diffDatasetVersions({datasetId:e,datasetName:r,fromVersion:n,toVersion:a}){let s=e;if(s===void 0&&r===void 0)throw new Error("Must provide either datasetName or datasetId");if(s!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");s===void 0&&(s=(await this.readDataset({datasetName:r})).id);const i=new URLSearchParams({from_version:typeof n=="string"?n:n.toISOString(),to_version:typeof a=="string"?a:a.toISOString()});return await this._get(`/datasets/${s}/versions/diff`,i)}async readDatasetOpenaiFinetuning({datasetId:e,datasetName:r}){const n="/datasets";if(e===void 0)if(r!==void 0)e=(await this.readDataset({datasetName:r})).id;else throw new Error("Must provide either datasetName or datasetId");return(await(await this._getResponse(`${n}/${e}/openai_ft`)).text()).trim().split(`
|
|
40
|
-
`).map(o=>JSON.parse(o))}async*listDatasets({limit:e=100,offset:r=0,datasetIds:n,datasetName:a,datasetNameContains:s,metadata:i}={}){const o="/datasets",c=new URLSearchParams({limit:e.toString(),offset:r.toString()});if(n!==void 0)for(const u of n)c.append("id",u);a!==void 0&&c.append("name",a),s!==void 0&&c.append("name_contains",s),i!==void 0&&c.append("metadata",JSON.stringify(i));for await(const u of this._getPaginated(o,c))yield*u}async updateDataset(e){const{datasetId:r,datasetName:n,...a}=e;if(!r&&!n)throw new Error("Must provide either datasetName or datasetId");const s=r??(await this.readDataset({datasetName:n})).id;re(s);const i=JSON.stringify(a);return await(await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/datasets/${s}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await G(c,"update dataset"),c})).json()}async updateDatasetTag(e){const{datasetId:r,datasetName:n,asOf:a,tag:s}=e;if(!r&&!n)throw new Error("Must provide either datasetName or datasetId");const i=r??(await this.readDataset({datasetName:n})).id;re(i);const o=JSON.stringify({as_of:typeof a=="string"?a:a.toISOString(),tag:s});await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/datasets/${i}/tags`,{method:"PUT",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await G(c,"update dataset tags",!0),c})}async deleteDataset({datasetId:e,datasetName:r}){let n="/datasets",a=e;if(e!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");if(r!==void 0&&(a=(await this.readDataset({datasetName:r})).id),a!==void 0)re(a),n+=`/${a}`;else throw new Error("Must provide datasetName or datasetId");await this.caller.call(async()=>{const s=await this._fetch(this.apiUrl+n,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await G(s,`delete ${n}`,!0),s})}async indexDataset({datasetId:e,datasetName:r,tag:n}){let a=e;if(!a&&!r)throw new Error("Must provide either datasetName or datasetId");if(a&&r)throw new Error("Must provide either datasetName or datasetId, not both");a||(a=(await this.readDataset({datasetName:r})).id),re(a);const i=JSON.stringify({tag:n});await(await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/datasets/${a}/index`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await G(c,"index dataset"),c})).json()}async similarExamples(e,r,n,{filter:a}={}){const s={limit:n,inputs:e};a!==void 0&&(s.filter=a),re(r);const i=JSON.stringify(s);return(await(await this.caller.call(async()=>{const u=await this._fetch(`${this.apiUrl}/datasets/${r}/search`,{headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,method:"POST",body:i});return await G(u,"fetch similar examples"),u})).json()).examples}async createExample(e,r,n){if(mc(e)&&(r!==void 0||n!==void 0))throw new Error("Cannot provide outputs or options when using ExampleCreate object");let a=r?n?.datasetId:e.dataset_id;const s=r?n?.datasetName:e.dataset_name;if(a===void 0&&s===void 0)throw new Error("Must provide either datasetName or datasetId");if(a!==void 0&&s!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");a===void 0&&(a=(await this.readDataset({datasetName:s})).id);const i=(r?n?.createdAt:e.created_at)||new Date;let o;mc(e)?o=e:o={inputs:e,outputs:r,created_at:i?.toISOString(),id:n?.exampleId,metadata:n?.metadata,split:n?.split,source_run_id:n?.sourceRunId,use_source_run_io:n?.useSourceRunIO,use_source_run_attachments:n?.useSourceRunAttachments,attachments:n?.attachments};const c=await this._uploadExamplesMultipart(a,[o]);return await this.readExample(c.example_ids?.[0]??De())}async createExamples(e){if(Array.isArray(e)){if(e.length===0)return[];const S=e;let E=S[0].dataset_id;const k=S[0].dataset_name;if(E===void 0&&k===void 0)throw new Error("Must provide either datasetName or datasetId");if(E!==void 0&&k!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");E===void 0&&(E=(await this.readDataset({datasetName:k})).id);const C=await this._uploadExamplesMultipart(E,S);return await Promise.all(C.example_ids.map(W=>this.readExample(W)))}const{inputs:r,outputs:n,metadata:a,splits:s,sourceRunIds:i,useSourceRunIOs:o,useSourceRunAttachments:c,attachments:u,exampleIds:l,datasetId:d,datasetName:h}=e;if(r===void 0)throw new Error("Must provide inputs when using legacy parameters");let p=d;const g=h;if(p===void 0&&g===void 0)throw new Error("Must provide either datasetName or datasetId");if(p!==void 0&&g!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");p===void 0&&(p=(await this.readDataset({datasetName:g})).id);const y=r.map((S,E)=>({dataset_id:p,inputs:S,outputs:n?.[E],metadata:a?.[E],split:s?.[E],id:l?.[E],attachments:u?.[E],source_run_id:i?.[E],use_source_run_io:o?.[E],use_source_run_attachments:c?.[E]})),v=await this._uploadExamplesMultipart(p,y);return await Promise.all(v.example_ids.map(S=>this.readExample(S)))}async createLLMExample(e,r,n){return this.createExample({input:e},{output:r},n)}async createChatExample(e,r,n){const a=e.map(i=>_o(i)?yo(i):i),s=_o(r)?yo(r):r;return this.createExample({input:a},{output:s},n)}async readExample(e){re(e);const r=`/examples/${e}`,n=await this._get(r),{attachment_urls:a,...s}=n,i=s;return a&&(i.attachments=Object.entries(a).reduce((o,[c,u])=>(o[c.slice(11)]={presigned_url:u.presigned_url,mime_type:u.mime_type},o),{})),i}async*listExamples({datasetId:e,datasetName:r,exampleIds:n,asOf:a,splits:s,inlineS3Urls:i,metadata:o,limit:c,offset:u,filter:l,includeAttachments:d}={}){let h;if(e!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");if(e!==void 0)h=e;else if(r!==void 0)h=(await this.readDataset({datasetName:r})).id;else throw new Error("Must provide a datasetName or datasetId");const p=new URLSearchParams({dataset:h}),g=a?typeof a=="string"?a:a?.toISOString():void 0;g&&p.append("as_of",g);const y=i??!0;if(p.append("inline_s3_urls",y.toString()),n!==void 0)for(const b of n)p.append("id",b);if(s!==void 0)for(const b of s)p.append("splits",b);if(o!==void 0){const b=JSON.stringify(o);p.append("metadata",b)}c!==void 0&&p.append("limit",c.toString()),u!==void 0&&p.append("offset",u.toString()),l!==void 0&&p.append("filter",l),d===!0&&["attachment_urls","outputs","metadata"].forEach(b=>p.append("select",b));let v=0;for await(const b of this._getPaginated("/examples",p)){for(const S of b){const{attachment_urls:E,...k}=S,C=k;E&&(C.attachments=Object.entries(E).reduce((F,[W,_])=>(F[W.slice(11)]={presigned_url:_.presigned_url,mime_type:_.mime_type||void 0},F),{})),yield C,v++}if(c!==void 0&&v>=c)break}}async deleteExample(e){re(e);const r=`/examples/${e}`;await this.caller.call(async()=>{const n=await this._fetch(this.apiUrl+r,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await G(n,`delete ${r}`,!0),n})}async updateExample(e,r){let n;r?n=e:n=e.id,re(n);let a;r?a={id:n,...r}:a=e;let s;return a.dataset_id!==void 0?s=a.dataset_id:s=(await this.readExample(n)).dataset_id,this._updateExamplesMultipart(s,[a])}async updateExamples(e){let r;return e[0].dataset_id===void 0?r=(await this.readExample(e[0].id)).dataset_id:r=e[0].dataset_id,this._updateExamplesMultipart(r,e)}async readDatasetVersion({datasetId:e,datasetName:r,asOf:n,tag:a}){let s;if(e?s=e:s=(await this.readDataset({datasetName:r})).id,re(s),n&&a||!n&&!a)throw new Error("Exactly one of asOf and tag must be specified.");const i=new URLSearchParams;return n!==void 0&&i.append("as_of",typeof n=="string"?n:n.toISOString()),a!==void 0&&i.append("tag",a),await(await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/datasets/${s}/version?${i.toString()}`,{method:"GET",headers:{...this.headers},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await G(c,"read dataset version"),c})).json()}async listDatasetSplits({datasetId:e,datasetName:r,asOf:n}){let a;if(e===void 0&&r===void 0)throw new Error("Must provide dataset name or ID");if(e!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");e===void 0?a=(await this.readDataset({datasetName:r})).id:a=e,re(a);const s=new URLSearchParams,i=n?typeof n=="string"?n:n?.toISOString():void 0;return i&&s.append("as_of",i),await this._get(`/datasets/${a}/splits`,s)}async updateDatasetSplits({datasetId:e,datasetName:r,splitName:n,exampleIds:a,remove:s=!1}){let i;if(e===void 0&&r===void 0)throw new Error("Must provide dataset name or ID");if(e!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");e===void 0?i=(await this.readDataset({datasetName:r})).id:i=e,re(i);const o={split_name:n,examples:a.map(u=>(re(u),u)),remove:s},c=JSON.stringify(o);await this.caller.call(async()=>{const u=await this._fetch(`${this.apiUrl}/datasets/${i}/splits`,{method:"PUT",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await G(u,"update dataset splits",!0),u})}async evaluateRun(e,r,{sourceInfo:n,loadChildRuns:a,referenceExample:s}={loadChildRuns:!1}){Es("This method is deprecated and will be removed in future LangSmith versions, use `evaluate` from `langsmith/evaluation` instead.");let i;if(typeof e=="string")i=await this.readRun(e,{loadChildRuns:a});else if(typeof e=="object"&&"id"in e)i=e;else throw new Error(`Invalid run type: ${typeof e}`);i.reference_example_id!==null&&i.reference_example_id!==void 0&&(s=await this.readExample(i.reference_example_id));const o=await r.evaluateRun(i,s),[c,u]=await this._logEvaluationFeedback(o,i,n);return u[0]}async createFeedback(e,r,{score:n,value:a,correction:s,comment:i,sourceInfo:o,feedbackSourceType:c="api",sourceRunId:u,feedbackId:l,feedbackConfig:d,projectId:h,comparativeExperimentId:p}){if(!e&&!h)throw new Error("One of runId or projectId must be provided");if(e&&h)throw new Error("Only one of runId or projectId can be provided");const g={type:c??"api",metadata:o??{}};u!==void 0&&g?.metadata!==void 0&&!g.metadata.__run&&(g.metadata.__run={run_id:u}),g?.metadata!==void 0&&g.metadata.__run?.run_id!==void 0&&re(g.metadata.__run.run_id);const y={id:l??De(),run_id:e,key:r,score:fc(n),value:a,correction:s,comment:i,feedback_source:g,comparative_experiment_id:p,feedbackConfig:d,session_id:h},v=JSON.stringify(y),b=`${this.apiUrl}/feedback`;return await this.caller.call(async()=>{const S=await this._fetch(b,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:v});return await G(S,"create feedback",!0),S}),y}async updateFeedback(e,{score:r,value:n,correction:a,comment:s}){const i={};r!=null&&(i.score=fc(r)),n!=null&&(i.value=n),a!=null&&(i.correction=a),s!=null&&(i.comment=s),re(e);const o=JSON.stringify(i);await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/feedback/${e}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await G(c,"update feedback",!0),c})}async readFeedback(e){re(e);const r=`/feedback/${e}`;return await this._get(r)}async deleteFeedback(e){re(e);const r=`/feedback/${e}`;await this.caller.call(async()=>{const n=await this._fetch(this.apiUrl+r,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await G(n,`delete ${r}`,!0),n})}async*listFeedback({runIds:e,feedbackKeys:r,feedbackSourceTypes:n}={}){const a=new URLSearchParams;if(e)for(const s of e)re(s),a.append("run",s);if(r)for(const s of r)a.append("key",s);if(n)for(const s of n)a.append("source",s);for await(const s of this._getPaginated("/feedback",a))yield*s}async createPresignedFeedbackToken(e,r,{expiration:n,feedbackConfig:a}={}){const s={run_id:e,feedback_key:r,feedback_config:a};n?typeof n=="string"?s.expires_at=n:(n?.hours||n?.minutes||n?.days)&&(s.expires_in=n):s.expires_in={hours:3};const i=JSON.stringify(s);return await(await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/feedback/tokens`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await G(c,"create presigned feedback token"),c})).json()}async createComparativeExperiment({name:e,experimentIds:r,referenceDatasetId:n,createdAt:a,description:s,metadata:i,id:o}){if(r.length===0)throw new Error("At least one experiment is required");if(n||(n=(await this.readProject({projectId:r[0]})).reference_dataset_id),!n==null)throw new Error("A reference dataset is required");const c={id:o,name:e,experiment_ids:r,reference_dataset_id:n,description:s,created_at:(a??new Date)?.toISOString(),extra:{}};i&&(c.extra.metadata=i);const u=JSON.stringify(c);return(await this.caller.call(async()=>{const d=await this._fetch(`${this.apiUrl}/datasets/comparative`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:u});return await G(d,"create comparative experiment"),d})).json()}async*listPresignedFeedbackTokens(e){re(e);const r=new URLSearchParams({run_id:e});for await(const n of this._getPaginated("/feedback/tokens",r))yield*n}_selectEvalResults(e){let r;return"results"in e?r=e.results:Array.isArray(e)?r=e:r=[e],r}async _logEvaluationFeedback(e,r,n){const a=this._selectEvalResults(e),s=[];for(const i of a){let o=n||{};i.evaluatorInfo&&(o={...i.evaluatorInfo,...o});let c=null;i.targetRunId?c=i.targetRunId:r&&(c=r.id),s.push(await this.createFeedback(c,i.key,{score:i.score,value:i.value,comment:i.comment,correction:i.correction,sourceInfo:o,sourceRunId:i.sourceRunId,feedbackConfig:i.feedbackConfig,feedbackSourceType:"model"}))}return[a,s]}async logEvaluationFeedback(e,r,n){const[a]=await this._logEvaluationFeedback(e,r,n);return a}async*listAnnotationQueues(e={}){const{queueIds:r,name:n,nameContains:a,limit:s}=e,i=new URLSearchParams;r&&r.forEach((c,u)=>{re(c,`queueIds[${u}]`),i.append("ids",c)}),n&&i.append("name",n),a&&i.append("name_contains",a),i.append("limit",(s!==void 0?Math.min(s,100):100).toString());let o=0;for await(const c of this._getPaginated("/annotation-queues",i))if(yield*c,o++,s!==void 0&&o>=s)break}async createAnnotationQueue(e){const{name:r,description:n,queueId:a,rubricInstructions:s}=e,i={name:r,description:n,id:a||De(),rubric_instructions:s},o=JSON.stringify(Object.fromEntries(Object.entries(i).filter(([u,l])=>l!==void 0)));return(await this.caller.call(async()=>{const u=await this._fetch(`${this.apiUrl}/annotation-queues`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await G(u,"create annotation queue"),u})).json()}async readAnnotationQueue(e){return(await this.caller.call(async()=>{const n=await this._fetch(`${this.apiUrl}/annotation-queues/${re(e,"queueId")}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await G(n,"read annotation queue"),n})).json()}async updateAnnotationQueue(e,r){const{name:n,description:a,rubricInstructions:s}=r,i=JSON.stringify({name:n,description:a,rubric_instructions:s});await this.caller.call(async()=>{const o=await this._fetch(`${this.apiUrl}/annotation-queues/${re(e,"queueId")}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await G(o,"update annotation queue",!0),o})}async deleteAnnotationQueue(e){await this.caller.call(async()=>{const r=await this._fetch(`${this.apiUrl}/annotation-queues/${re(e,"queueId")}`,{method:"DELETE",headers:{...this.headers,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await G(r,"delete annotation queue",!0),r})}async addRunsToAnnotationQueue(e,r){const n=JSON.stringify(r.map((a,s)=>re(a,`runIds[${s}]`).toString()));await this.caller.call(async()=>{const a=await this._fetch(`${this.apiUrl}/annotation-queues/${re(e,"queueId")}/runs`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:n});return await G(a,"add runs to annotation queue",!0),a})}async getRunFromAnnotationQueue(e,r){const n=`/annotation-queues/${re(e,"queueId")}/run`;return(await this.caller.call(async()=>{const s=await this._fetch(`${this.apiUrl}${n}/${r}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await G(s,"get run from annotation queue"),s})).json()}async deleteRunFromAnnotationQueue(e,r){await this.caller.call(async()=>{const n=await this._fetch(`${this.apiUrl}/annotation-queues/${re(e,"queueId")}/runs/${re(r,"queueRunId")}`,{method:"DELETE",headers:{...this.headers,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await G(n,"delete run from annotation queue",!0),n})}async getSizeFromAnnotationQueue(e){return(await this.caller.call(async()=>{const n=await this._fetch(`${this.apiUrl}/annotation-queues/${re(e,"queueId")}/size`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await G(n,"get size from annotation queue"),n})).json()}async _currentTenantIsOwner(e){const r=await this._getSettings();return e=="-"||r.tenant_handle===e}async _ownerConflictError(e,r){const n=await this._getSettings();return new Error(`Cannot ${e} for another tenant.
|
|
41
|
-
|
|
42
|
-
Current tenant: ${n.tenant_handle}
|
|
43
|
-
|
|
44
|
-
Requested tenant: ${r}`)}async _getLatestCommitHash(e){const n=await(await this.caller.call(async()=>{const a=await this._fetch(`${this.apiUrl}/commits/${e}/?limit=1&offset=0`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await G(a,"get latest commit hash"),a})).json();if(n.commits.length!==0)return n.commits[0].commit_hash}async _likeOrUnlikePrompt(e,r){const[n,a,s]=Ot(e),i=JSON.stringify({like:r});return(await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/likes/${n}/${a}`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await G(c,`${r?"like":"unlike"} prompt`),c})).json()}async _getPromptUrl(e){const[r,n,a]=Ot(e);if(await this._currentTenantIsOwner(r)){const s=await this._getSettings();return a!=="latest"?`${this.getHostUrl()}/prompts/${n}/${a.substring(0,8)}?organizationId=${s.id}`:`${this.getHostUrl()}/prompts/${n}?organizationId=${s.id}`}else return a!=="latest"?`${this.getHostUrl()}/hub/${r}/${n}/${a.substring(0,8)}`:`${this.getHostUrl()}/hub/${r}/${n}`}async promptExists(e){return!!await this.getPrompt(e)}async likePrompt(e){return this._likeOrUnlikePrompt(e,!0)}async unlikePrompt(e){return this._likeOrUnlikePrompt(e,!1)}async*listCommits(e){for await(const r of this._getPaginated(`/commits/${e}/`,new URLSearchParams,n=>n.commits))yield*r}async*listPrompts(e){const r=new URLSearchParams;r.append("sort_field",e?.sortField??"updated_at"),r.append("sort_direction","desc"),r.append("is_archived",(!!e?.isArchived).toString()),e?.isPublic!==void 0&&r.append("is_public",e.isPublic.toString()),e?.query&&r.append("query",e.query);for await(const n of this._getPaginated("/repos",r,a=>a.repos))yield*n}async getPrompt(e){const[r,n,a]=Ot(e),i=await(await this.caller.call(async()=>{const o=await this._fetch(`${this.apiUrl}/repos/${r}/${n}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return o?.status===404?null:(await G(o,"get prompt"),o)}))?.json();return i?.repo?i.repo:null}async createPrompt(e,r){const n=await this._getSettings();if(r?.isPublic&&!n.tenant_handle)throw new Error(`Cannot create a public prompt without first
|
|
45
|
-
|
|
46
|
-
creating a LangChain Hub handle.
|
|
47
|
-
You can add a handle by creating a public prompt at:
|
|
48
|
-
|
|
49
|
-
https://smith.langchain.com/prompts`);const[a,s,i]=Ot(e);if(!await this._currentTenantIsOwner(a))throw await this._ownerConflictError("create a prompt",a);const o={repo_handle:s,...r?.description&&{description:r.description},...r?.readme&&{readme:r.readme},...r?.tags&&{tags:r.tags},is_public:!!r?.isPublic},c=JSON.stringify(o),u=await this.caller.call(async()=>{const d=await this._fetch(`${this.apiUrl}/repos/`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await G(d,"create prompt"),d}),{repo:l}=await u.json();return l}async createCommit(e,r,n){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");const[a,s,i]=Ot(e),o=n?.parentCommitHash==="latest"||!n?.parentCommitHash?await this._getLatestCommitHash(`${a}/${s}`):n?.parentCommitHash,c={manifest:JSON.parse(JSON.stringify(r)),parent_commit:o},u=JSON.stringify(c),d=await(await this.caller.call(async()=>{const h=await this._fetch(`${this.apiUrl}/commits/${a}/${s}`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:u});return await G(h,"create commit"),h})).json();return this._getPromptUrl(`${a}/${s}${d.commit_hash?`:${d.commit_hash}`:""}`)}async updateExamplesMultipart(e,r=[]){return this._updateExamplesMultipart(e,r)}async _updateExamplesMultipart(e,r=[]){if(!await this._getDatasetExamplesMultiPartSupport())throw new Error("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version.");const n=new FormData;for(const i of r){const o=i.id,c={...i.metadata&&{metadata:i.metadata},...i.split&&{split:i.split}},u=Ve(c,`Serializing body for example with id: ${o}`),l=new Blob([u],{type:"application/json"});if(n.append(o,l),i.inputs){const d=Ve(i.inputs,`Serializing inputs for example with id: ${o}`),h=new Blob([d],{type:"application/json"});n.append(`${o}.inputs`,h)}if(i.outputs){const d=Ve(i.outputs,`Serializing outputs whle updating example with id: ${o}`),h=new Blob([d],{type:"application/json"});n.append(`${o}.outputs`,h)}if(i.attachments)for(const[d,h]of Object.entries(i.attachments)){let p,g;Array.isArray(h)?[p,g]=h:(p=h.mimeType,g=h.data);const y=new Blob([g],{type:`${p}; length=${g.byteLength}`});n.append(`${o}.attachment.${d}`,y)}if(i.attachments_operations){const d=Ve(i.attachments_operations,`Serializing attachments while updating example with id: ${o}`),h=new Blob([d],{type:"application/json"});n.append(`${o}.attachments_operations`,h)}}const a=e??r[0]?.dataset_id;return(await this.caller.call(async()=>{const i=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${a}/examples`)}`,{method:"PATCH",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:n});return await G(i,"update examples"),i})).json()}async uploadExamplesMultipart(e,r=[]){return this._uploadExamplesMultipart(e,r)}async _uploadExamplesMultipart(e,r=[]){if(!await this._getDatasetExamplesMultiPartSupport())throw new Error("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version.");const n=new FormData;for(const s of r){const i=(s.id??De()).toString(),o={created_at:s.created_at,...s.metadata&&{metadata:s.metadata},...s.split&&{split:s.split},...s.source_run_id&&{source_run_id:s.source_run_id},...s.use_source_run_io&&{use_source_run_io:s.use_source_run_io},...s.use_source_run_attachments&&{use_source_run_attachments:s.use_source_run_attachments}},c=Ve(o,`Serializing body for uploaded example with id: ${i}`),u=new Blob([c],{type:"application/json"});if(n.append(i,u),s.inputs){const l=Ve(s.inputs,`Serializing inputs for uploaded example with id: ${i}`),d=new Blob([l],{type:"application/json"});n.append(`${i}.inputs`,d)}if(s.outputs){const l=Ve(s.outputs,`Serializing outputs for uploaded example with id: ${i}`),d=new Blob([l],{type:"application/json"});n.append(`${i}.outputs`,d)}if(s.attachments)for(const[l,d]of Object.entries(s.attachments)){let h,p;Array.isArray(d)?[h,p]=d:(h=d.mimeType,p=d.data);const g=new Blob([p],{type:`${h}; length=${p.byteLength}`});n.append(`${i}.attachment.${l}`,g)}}return(await this.caller.call(async()=>{const s=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${e}/examples`)}`,{method:"POST",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:n});return await G(s,"upload examples"),s})).json()}async updatePrompt(e,r){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");const[n,a]=Ot(e);if(!await this._currentTenantIsOwner(n))throw await this._ownerConflictError("update a prompt",n);const s={};if(r?.description!==void 0&&(s.description=r.description),r?.readme!==void 0&&(s.readme=r.readme),r?.tags!==void 0&&(s.tags=r.tags),r?.isPublic!==void 0&&(s.is_public=r.isPublic),r?.isArchived!==void 0&&(s.is_archived=r.isArchived),Object.keys(s).length===0)throw new Error("No valid update options provided");const i=JSON.stringify(s);return(await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/repos/${n}/${a}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await G(c,"update prompt"),c})).json()}async deletePrompt(e){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");const[r,n,a]=Ot(e);if(!await this._currentTenantIsOwner(r))throw await this._ownerConflictError("delete a prompt",r);return(await this.caller.call(async()=>{const i=await this._fetch(`${this.apiUrl}/repos/${r}/${n}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await G(i,"delete prompt"),i})).json()}async pullPromptCommit(e,r){const[n,a,s]=Ot(e),o=await(await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/commits/${n}/${a}/${s}${r?.includeModel?"?include_model=true":""}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await G(c,"pull prompt commit"),c})).json();return{owner:n,repo:a,commit_hash:o.commit_hash,manifest:o.manifest,examples:o.examples}}async _pullPrompt(e,r){const n=await this.pullPromptCommit(e,{includeModel:r?.includeModel});return JSON.stringify(n.manifest)}async pushPrompt(e,r){return await this.promptExists(e)?r&&Object.keys(r).some(a=>a!=="object")&&await this.updatePrompt(e,{description:r?.description,readme:r?.readme,tags:r?.tags,isPublic:r?.isPublic}):await this.createPrompt(e,{description:r?.description,readme:r?.readme,tags:r?.tags,isPublic:r?.isPublic}),r?.object?await this.createCommit(e,r?.object,{parentCommitHash:r?.parentCommitHash}):await this._getPromptUrl(e)}async clonePublicDataset(e,r={}){const{sourceApiUrl:n=this.apiUrl,datasetName:a}=r,[s,i]=this.parseTokenOrUrl(e,n),o=new Dr({apiUrl:s,apiKey:"placeholder"}),c=await o.readSharedDataset(i),u=a||c.name;try{if(await this.hasDataset({datasetId:u})){console.log(`Dataset ${u} already exists in your tenant. Skipping.`);return}}catch{}const l=await o.listSharedExamples(i),d=await this.createDataset(u,{description:c.description,dataType:c.data_type||"kv",inputsSchema:c.inputs_schema_definition??void 0,outputsSchema:c.outputs_schema_definition??void 0});try{await this.createExamples({inputs:l.map(h=>h.inputs),outputs:l.flatMap(h=>h.outputs?[h.outputs]:[]),datasetId:d.id})}catch(h){throw console.error(`An error occurred while creating dataset ${u}. You should delete it manually.`),h}}parseTokenOrUrl(e,r,n=2,a="dataset"){try{return re(e),[r,e]}catch{}try{const i=new URL(e).pathname.split("/").filter(o=>o!=="");if(i.length>=n){const o=i[i.length-n];return[r,o]}else throw new Error(`Invalid public ${a} URL: ${e}`)}catch{throw new Error(`Invalid public ${a} URL or token: ${e}`)}}async awaitPendingTraceBatches(){if(this.manualFlushMode)return console.warn("[WARNING]: When tracing in manual flush mode, you must call `await client.flush()` manually to submit trace batches."),Promise.resolve();await Promise.all([...this.autoBatchQueue.items.map(({itemPromise:e})=>e),this.batchIngestCaller.queue.onIdle()]),this.langSmithToOTELTranslator!==void 0&&await Sf()?.DEFAULT_LANGSMITH_SPAN_PROCESSOR?.forceFlush()}}function mc(t){return"dataset_id"in t||"dataset_name"in t}const kp=t=>!!["TRACING_V2","TRACING"].find(r=>Ge(r)==="true"),Qa=Symbol.for("lc:context_variables");function Rp(t){return t.replace(/[-:.]/g,"")}function Ru(t,e,r=1){const n=r.toFixed(0).slice(0,3).padStart(3,"0"),a=`${new Date(t).toISOString().slice(0,-1)}${n}Z`;return{dottedOrder:Rp(a)+e,microsecondPrecisionDatestring:a}}class bn{constructor(e,r,n,a){Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"project_name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"replicas",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.metadata=e,this.tags=r,this.project_name=n,this.replicas=a}static fromHeader(e){const r=e.split(",");let n={},a=[],s,i;for(const o of r){const[c,u]=o.split("="),l=decodeURIComponent(u);c==="langsmith-metadata"?n=JSON.parse(l):c==="langsmith-tags"?a=l.split(","):c==="langsmith-project"?s=l:c==="langsmith-replicas"&&(i=JSON.parse(l))}return new bn(n,a,s,i)}toHeader(){const e=[];return this.metadata&&Object.keys(this.metadata).length>0&&e.push(`langsmith-metadata=${encodeURIComponent(JSON.stringify(this.metadata))}`),this.tags&&this.tags.length>0&&e.push(`langsmith-tags=${encodeURIComponent(this.tags.join(","))}`),this.project_name&&e.push(`langsmith-project=${encodeURIComponent(this.project_name)}`),e.join(",")}}class qe{constructor(e){if(Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"run_type",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"project_name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"parent_run",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"parent_run_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"child_runs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"start_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"end_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"extra",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"error",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"serialized",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"inputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"outputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"reference_example_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"events",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"trace_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"dotted_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tracingEnabled",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"execution_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"child_execution_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"attachments",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"replicas",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_serialized_start_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Cp(e)){Object.assign(this,{...e});return}const r=qe.getDefaultConfig(),{metadata:n,...a}=e,s=a.client??qe.getSharedClient(),i={...n,...a?.extra?.metadata};if(a.extra={...a.extra,metadata:i},"id"in a&&a.id==null&&delete a.id,Object.assign(this,{...r,...a,client:s}),this.trace_id||(this.parent_run?this.trace_id=this.parent_run.trace_id??this.id:this.trace_id=this.id),this.replicas=Lp(this.replicas),this.execution_order??=1,this.child_execution_order??=1,!this.dotted_order){const{dottedOrder:o,microsecondPrecisionDatestring:c}=Ru(this.start_time,this.id,this.execution_order);this.parent_run?this.dotted_order=this.parent_run.dotted_order+"."+o:this.dotted_order=o,this._serialized_start_time=c}}set metadata(e){this.extra={...this.extra,metadata:{...this.extra?.metadata,...e}}}get metadata(){return this.extra?.metadata}static getDefaultConfig(){return{id:De(),run_type:"chain",project_name:gu(),child_runs:[],api_url:yt("LANGCHAIN_ENDPOINT")??"http://localhost:1984",api_key:yt("LANGCHAIN_API_KEY"),caller_options:{},start_time:Date.now(),serialized:{},inputs:{},extra:{}}}static getSharedClient(){return qe.sharedClient||(qe.sharedClient=new Dr),qe.sharedClient}createChild(e){const r=this.child_execution_order+1,n=new qe({...e,parent_run:this,project_name:this.project_name,replicas:this.replicas,client:this.client,tracingEnabled:this.tracingEnabled,execution_order:r,child_execution_order:r});Qa in this&&(n[Qa]=this[Qa]);const a=Symbol.for("lc:child_config"),s=e.extra?.[a]??this.extra[a];if($p(s)){const c={...s},u=Np(c.callbacks)?c.callbacks.copy?.():void 0;u&&(Object.assign(u,{_parentRunId:n.id}),u.handlers?.find(Cu)?.updateFromRunTree?.(n),c.callbacks=u),n.extra[a]=c}const i=new Set;let o=this;for(;o!=null&&!i.has(o.id);)i.add(o.id),o.child_execution_order=Math.max(o.child_execution_order,r),o=o.parent_run;return this.child_runs.push(n),n}async end(e,r,n=Date.now(),a){this.outputs=this.outputs??e,this.error=this.error??r,this.end_time=this.end_time??n,a&&Object.keys(a).length>0&&(this.extra=this.extra?{...this.extra,metadata:{...this.extra.metadata,...a}}:{metadata:a})}_convertToCreate(e,r,n=!0){const a=e.extra??{};if(a?.runtime?.library===void 0&&(a.runtime||(a.runtime={}),r))for(const[o,c]of Object.entries(r))a.runtime[o]||(a.runtime[o]=c);let s,i;return n?(i=e.parent_run?.id??e.parent_run_id,s=[]):(s=e.child_runs.map(o=>this._convertToCreate(o,r,n)),i=void 0),{id:e.id,name:e.name,start_time:e._serialized_start_time??e.start_time,end_time:e.end_time,run_type:e.run_type,reference_example_id:e.reference_example_id,extra:a,serialized:e.serialized,error:e.error,inputs:e.inputs,outputs:e.outputs,session_name:e.project_name,child_runs:s,parent_run_id:i,trace_id:e.trace_id,dotted_order:e.dotted_order,tags:e.tags,attachments:e.attachments,events:e.events}}_remapForProject(e,r,n=!0){const a=this._convertToCreate(this,r,n);if(e===this.project_name)return a;const s=d=>Xi(`${d}:${e}`,Xi.DNS),i=s(a.id),o=a.trace_id?s(a.trace_id):void 0,c=a.parent_run_id?s(a.parent_run_id):void 0;let u;if(a.dotted_order){const d=Pp(a.dotted_order),h=[];for(let g=0;g<d.length-1;g++){const[y,v]=d[g],b=s(v);h.push(y.toISOString().replace(/[-:]/g,"").replace(".","")+b)}const[p]=d[d.length-1];h.push(p.toISOString().replace(/[-:]/g,"").replace(".","")+i),u=h.join(".")}else u=void 0;return{...a,id:i,trace_id:o,parent_run_id:c,dotted_order:u,session_name:e}}async postRun(e=!0){try{const r=wu();if(this.replicas&&this.replicas.length>0)for(const{projectName:n,apiKey:a,apiUrl:s,workspaceId:i}of this.replicas){const o=this._remapForProject(n??this.project_name,r,!0);await this.client.createRun(o,{apiKey:a,apiUrl:s,workspaceId:i})}else{const n=this._convertToCreate(this,r,e);await this.client.createRun(n)}if(!e){Es("Posting with excludeChildRuns=false is deprecated and will be removed in a future version.");for(const n of this.child_runs)await n.postRun(!1)}}catch(r){console.error(`Error in postRun for run ${this.id}:`,r)}}async patchRun(e){if(this.replicas&&this.replicas.length>0)for(const{projectName:r,apiKey:n,apiUrl:a,workspaceId:s,updates:i}of this.replicas){const o=this._remapForProject(r??this.project_name),c={id:o.id,outputs:o.outputs,error:o.error,parent_run_id:o.parent_run_id,session_name:o.session_name,reference_example_id:o.reference_example_id,end_time:o.end_time,dotted_order:o.dotted_order,trace_id:o.trace_id,events:o.events,tags:o.tags,extra:o.extra,attachments:this.attachments,...i};e?.excludeInputs||(c.inputs=o.inputs),await this.client.updateRun(o.id,c,{apiKey:n,apiUrl:a,workspaceId:s})}else try{const r={end_time:this.end_time,error:this.error,outputs:this.outputs,parent_run_id:this.parent_run?.id??this.parent_run_id,reference_example_id:this.reference_example_id,extra:this.extra,events:this.events,dotted_order:this.dotted_order,trace_id:this.trace_id,tags:this.tags,attachments:this.attachments,session_name:this.project_name};e?.excludeInputs||(r.inputs=this.inputs),await this.client.updateRun(this.id,r)}catch(r){console.error(`Error in patchRun for run ${this.id}`,r)}}toJSON(){return this._convertToCreate(this,void 0,!1)}addEvent(e){this.events||(this.events=[]),typeof e=="string"?this.events.push({name:"event",time:new Date().toISOString(),message:e}):this.events.push({...e,time:e.time??new Date().toISOString()})}static fromRunnableConfig(e,r){const n=e?.callbacks;let a,s,i,o=kp();if(n){const u=n?.getParentRunId?.()??"",l=n?.handlers?.find(d=>d?.name=="langchain_tracer");a=l?.getRun?.(u),s=l?.projectName,i=l?.client,o=o||!!l}return a?new qe({name:a.name,id:a.id,trace_id:a.trace_id,dotted_order:a.dotted_order,client:i,tracingEnabled:o,project_name:s,tags:[...new Set((a?.tags??[]).concat(e?.tags??[]))],extra:{metadata:{...a?.extra?.metadata,...e?.metadata}}}).createChild(r):new qe({...r,client:i,tracingEnabled:o,project_name:s})}static fromDottedOrder(e){return this.fromHeaders({"langsmith-trace":e})}static fromHeaders(e,r){const n="get"in e&&typeof e.get=="function"?{"langsmith-trace":e.get("langsmith-trace"),baggage:e.get("baggage")}:e,a=n["langsmith-trace"];if(!a||typeof a!="string")return;const s=a.trim(),i=s.split(".").map(u=>{const[l,d]=u.split("Z");return{strTime:l,time:Date.parse(l+"Z"),uuid:d}}),o=i[0].uuid,c={...r,name:r?.name??"parent",run_type:r?.run_type??"chain",start_time:r?.start_time??Date.now(),id:i.at(-1)?.uuid,trace_id:o,dotted_order:s};if(n.baggage&&typeof n.baggage=="string"){const u=bn.fromHeader(n.baggage);c.metadata=u.metadata,c.tags=u.tags,c.project_name=u.project_name,c.replicas=u.replicas}return new qe(c)}toHeaders(e){const r={"langsmith-trace":this.dotted_order,baggage:new bn(this.extra?.metadata,this.tags,this.project_name,this.replicas).toHeader()};if(e)for(const[n,a]of Object.entries(r))e.set(n,a);return r}}Object.defineProperty(qe,"sharedClient",{enumerable:!0,configurable:!0,writable:!0,value:null});function Cp(t){return t!=null&&typeof t.createChild=="function"&&typeof t.postRun=="function"}function Cu(t){return typeof t=="object"&&t!=null&&typeof t.name=="string"&&t.name==="langchain_tracer"}function gc(t){return Array.isArray(t)&&t.some(e=>Cu(e))}function Np(t){return typeof t=="object"&&t!=null&&Array.isArray(t.handlers)}function $p(t){return t!=null&&typeof t.callbacks=="object"&&(gc(t.callbacks?.handlers)||gc(t.callbacks))}function Pp(t){return t.split(".").map(r=>{const n=r.slice(0,-36),a=r.slice(-36),s=parseInt(n.slice(0,4)),i=parseInt(n.slice(4,6))-1,o=parseInt(n.slice(6,8)),c=parseInt(n.slice(9,11)),u=parseInt(n.slice(11,13)),l=parseInt(n.slice(13,15)),d=parseInt(n.slice(15,21));return[new Date(s,i,o,c,u,l,d/1e3),a]})}function Mp(){const t=yt("LANGSMITH_RUNS_ENDPOINTS");if(!t)return[];try{const e=JSON.parse(t);if(Array.isArray(e)){const r=[];for(const n of e){if(typeof n!="object"||n===null){console.warn(`Invalid item type in LANGSMITH_RUNS_ENDPOINTS: expected object, got ${typeof n}`);continue}if(typeof n.api_url!="string"){console.warn(`Invalid api_url type in LANGSMITH_RUNS_ENDPOINTS: expected string, got ${typeof n.api_url}`);continue}if(typeof n.api_key!="string"){console.warn(`Invalid api_key type in LANGSMITH_RUNS_ENDPOINTS: expected string, got ${typeof n.api_key}`);continue}r.push({apiUrl:n.api_url.replace(/\/$/,""),apiKey:n.api_key})}return r}else if(typeof e=="object"&&e!==null){jp(e);const r=[];for(const[n,a]of Object.entries(e)){const s=n.replace(/\/$/,"");if(typeof a=="string")r.push({apiUrl:s,apiKey:a});else{console.warn(`Invalid value type in LANGSMITH_RUNS_ENDPOINTS for URL ${n}: expected string, got ${typeof a}`);continue}}return r}else return console.warn(`Invalid LANGSMITH_RUNS_ENDPOINTS – must be valid JSON array of objects with api_url and api_key properties, or object mapping url->apiKey, got ${typeof e}`),[]}catch(e){if(mp(e))throw e;return console.warn("Invalid LANGSMITH_RUNS_ENDPOINTS – must be valid JSON array of objects with api_url and api_key properties, or object mapping url->apiKey"),[]}}function Lp(t){return t?t.map(e=>Array.isArray(e)?{projectName:e[0],updates:e[1]}:e):Mp()}function jp(t){if(Object.keys(t).length>0&&Ge("ENDPOINT"))throw new pp}var Dp={};pe(Dp,{BaseTracer:()=>vr,isBaseTracer:()=>rr});const Up=t=>{if(t)return t.events=t.events??[],t.child_runs=t.child_runs??[],t};function Ss(t,e){if(t)return new qe({...t,start_time:t._serialized_start_time??t.start_time,parent_run:Ss(e),child_runs:t.child_runs.map(r=>Ss(r)).filter(r=>r!==void 0),extra:{...t.extra,runtime:du()},tracingEnabled:!1})}function es(t,e){return t&&!Array.isArray(t)&&typeof t=="object"?t:{[e]:t}}function rr(t){return typeof t._addRunToRunMap=="function"}var vr=class extends Gr{runMap=new Map;runTreeMap=new Map;usesRunTreeMap=!1;constructor(t){super(...arguments)}copy(){return this}getRunById(t){if(t!==void 0)return this.usesRunTreeMap?Up(this.runTreeMap.get(t)):this.runMap.get(t)}stringifyError(t){return t instanceof Error?t.message+(t?.stack?`
|
|
50
|
-
|
|
51
|
-
${t.stack}`:""):typeof t=="string"?t:`${t}`}_addChildRun(t,e){t.child_runs.push(e)}_addRunToRunMap(t){const{dottedOrder:e,microsecondPrecisionDatestring:r}=Ru(new Date(t.start_time).getTime(),t.id,t.execution_order),n={...t},a=this.getRunById(n.parent_run_id);if(n.parent_run_id!==void 0?a&&(this._addChildRun(a,n),a.child_execution_order=Math.max(a.child_execution_order,n.child_execution_order),n.trace_id=a.trace_id,a.dotted_order!==void 0&&(n.dotted_order=[a.dotted_order,e].join("."),n._serialized_start_time=r)):(n.trace_id=n.id,n.dotted_order=e,n._serialized_start_time=r),this.usesRunTreeMap){const s=Ss(n,a);s!==void 0&&this.runTreeMap.set(n.id,s)}else this.runMap.set(n.id,n);return n}async _endTrace(t){const e=t.parent_run_id!==void 0&&this.getRunById(t.parent_run_id);e?e.child_execution_order=Math.max(e.child_execution_order,t.child_execution_order):await this.persistRun(t),await this.onRunUpdate?.(t),this.usesRunTreeMap?this.runTreeMap.delete(t.id):this.runMap.delete(t.id)}_getExecutionOrder(t){const e=t!==void 0&&this.getRunById(t);return e?e.child_execution_order+1:1}_createRunForLLMStart(t,e,r,n,a,s,i,o){const c=this._getExecutionOrder(n),u=Date.now(),l=i?{...a,metadata:i}:a,d={id:r,name:o??t.id[t.id.length-1],parent_run_id:n,start_time:u,serialized:t,events:[{name:"start",time:new Date(u).toISOString()}],inputs:{prompts:e},execution_order:c,child_runs:[],child_execution_order:c,run_type:"llm",extra:l??{},tags:s||[]};return this._addRunToRunMap(d)}async handleLLMStart(t,e,r,n,a,s,i,o){const c=this.getRunById(r)??this._createRunForLLMStart(t,e,r,n,a,s,i,o);return await this.onRunCreate?.(c),await this.onLLMStart?.(c),c}_createRunForChatModelStart(t,e,r,n,a,s,i,o){const c=this._getExecutionOrder(n),u=Date.now(),l=i?{...a,metadata:i}:a,d={id:r,name:o??t.id[t.id.length-1],parent_run_id:n,start_time:u,serialized:t,events:[{name:"start",time:new Date(u).toISOString()}],inputs:{messages:e},execution_order:c,child_runs:[],child_execution_order:c,run_type:"llm",extra:l??{},tags:s||[]};return this._addRunToRunMap(d)}async handleChatModelStart(t,e,r,n,a,s,i,o){const c=this.getRunById(r)??this._createRunForChatModelStart(t,e,r,n,a,s,i,o);return await this.onRunCreate?.(c),await this.onLLMStart?.(c),c}async handleLLMEnd(t,e,r,n,a){const s=this.getRunById(e);if(!s||s?.run_type!=="llm")throw new Error("No LLM run to end.");return s.end_time=Date.now(),s.outputs=t,s.events.push({name:"end",time:new Date(s.end_time).toISOString()}),s.extra={...s.extra,...a},await this.onLLMEnd?.(s),await this._endTrace(s),s}async handleLLMError(t,e,r,n,a){const s=this.getRunById(e);if(!s||s?.run_type!=="llm")throw new Error("No LLM run to end.");return s.end_time=Date.now(),s.error=this.stringifyError(t),s.events.push({name:"error",time:new Date(s.end_time).toISOString()}),s.extra={...s.extra,...a},await this.onLLMError?.(s),await this._endTrace(s),s}_createRunForChainStart(t,e,r,n,a,s,i,o){const c=this._getExecutionOrder(n),u=Date.now(),l={id:r,name:o??t.id[t.id.length-1],parent_run_id:n,start_time:u,serialized:t,events:[{name:"start",time:new Date(u).toISOString()}],inputs:e,execution_order:c,child_execution_order:c,run_type:i??"chain",child_runs:[],extra:s?{metadata:s}:{},tags:a||[]};return this._addRunToRunMap(l)}async handleChainStart(t,e,r,n,a,s,i,o){const c=this.getRunById(r)??this._createRunForChainStart(t,e,r,n,a,s,i,o);return await this.onRunCreate?.(c),await this.onChainStart?.(c),c}async handleChainEnd(t,e,r,n,a){const s=this.getRunById(e);if(!s)throw new Error("No chain run to end.");return s.end_time=Date.now(),s.outputs=es(t,"output"),s.events.push({name:"end",time:new Date(s.end_time).toISOString()}),a?.inputs!==void 0&&(s.inputs=es(a.inputs,"input")),await this.onChainEnd?.(s),await this._endTrace(s),s}async handleChainError(t,e,r,n,a){const s=this.getRunById(e);if(!s)throw new Error("No chain run to end.");return s.end_time=Date.now(),s.error=this.stringifyError(t),s.events.push({name:"error",time:new Date(s.end_time).toISOString()}),a?.inputs!==void 0&&(s.inputs=es(a.inputs,"input")),await this.onChainError?.(s),await this._endTrace(s),s}_createRunForToolStart(t,e,r,n,a,s,i){const o=this._getExecutionOrder(n),c=Date.now(),u={id:r,name:i??t.id[t.id.length-1],parent_run_id:n,start_time:c,serialized:t,events:[{name:"start",time:new Date(c).toISOString()}],inputs:{input:e},execution_order:o,child_execution_order:o,run_type:"tool",child_runs:[],extra:s?{metadata:s}:{},tags:a||[]};return this._addRunToRunMap(u)}async handleToolStart(t,e,r,n,a,s,i){const o=this.getRunById(r)??this._createRunForToolStart(t,e,r,n,a,s,i);return await this.onRunCreate?.(o),await this.onToolStart?.(o),o}async handleToolEnd(t,e){const r=this.getRunById(e);if(!r||r?.run_type!=="tool")throw new Error("No tool run to end");return r.end_time=Date.now(),r.outputs={output:t},r.events.push({name:"end",time:new Date(r.end_time).toISOString()}),await this.onToolEnd?.(r),await this._endTrace(r),r}async handleToolError(t,e){const r=this.getRunById(e);if(!r||r?.run_type!=="tool")throw new Error("No tool run to end");return r.end_time=Date.now(),r.error=this.stringifyError(t),r.events.push({name:"error",time:new Date(r.end_time).toISOString()}),await this.onToolError?.(r),await this._endTrace(r),r}async handleAgentAction(t,e){const r=this.getRunById(e);if(!r||r?.run_type!=="chain")return;const n=r;n.actions=n.actions||[],n.actions.push(t),n.events.push({name:"agent_action",time:new Date().toISOString(),kwargs:{action:t}}),await this.onAgentAction?.(r)}async handleAgentEnd(t,e){const r=this.getRunById(e);!r||r?.run_type!=="chain"||(r.events.push({name:"agent_end",time:new Date().toISOString(),kwargs:{action:t}}),await this.onAgentEnd?.(r))}_createRunForRetrieverStart(t,e,r,n,a,s,i){const o=this._getExecutionOrder(n),c=Date.now(),u={id:r,name:i??t.id[t.id.length-1],parent_run_id:n,start_time:c,serialized:t,events:[{name:"start",time:new Date(c).toISOString()}],inputs:{query:e},execution_order:o,child_execution_order:o,run_type:"retriever",child_runs:[],extra:s?{metadata:s}:{},tags:a||[]};return this._addRunToRunMap(u)}async handleRetrieverStart(t,e,r,n,a,s,i){const o=this.getRunById(r)??this._createRunForRetrieverStart(t,e,r,n,a,s,i);return await this.onRunCreate?.(o),await this.onRetrieverStart?.(o),o}async handleRetrieverEnd(t,e){const r=this.getRunById(e);if(!r||r?.run_type!=="retriever")throw new Error("No retriever run to end");return r.end_time=Date.now(),r.outputs={documents:t},r.events.push({name:"end",time:new Date(r.end_time).toISOString()}),await this.onRetrieverEnd?.(r),await this._endTrace(r),r}async handleRetrieverError(t,e){const r=this.getRunById(e);if(!r||r?.run_type!=="retriever")throw new Error("No retriever run to end");return r.end_time=Date.now(),r.error=this.stringifyError(t),r.events.push({name:"error",time:new Date(r.end_time).toISOString()}),await this.onRetrieverError?.(r),await this._endTrace(r),r}async handleText(t,e){const r=this.getRunById(e);!r||r?.run_type!=="chain"||(r.events.push({name:"text",time:new Date().toISOString(),kwargs:{text:t}}),await this.onText?.(r))}async handleLLMNewToken(t,e,r,n,a,s){const i=this.getRunById(r);if(!i||i?.run_type!=="llm")throw new Error('Invalid "runId" provided to "handleLLMNewToken" callback.');return i.events.push({name:"new_token",time:new Date().toISOString(),kwargs:{token:t,idx:e,chunk:s?.chunk}}),await this.onLLMNewToken?.(i,t,{chunk:s?.chunk}),i}},un={exports:{}};un.exports;var _c;function Fp(){return _c||(_c=1,(function(t){const r=(s=0)=>i=>`\x1B[${38+s};5;${i}m`,n=(s=0)=>(i,o,c)=>`\x1B[${38+s};2;${i};${o};${c}m`;function a(){const s=new Map,i={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};i.color.gray=i.color.blackBright,i.bgColor.bgGray=i.bgColor.bgBlackBright,i.color.grey=i.color.blackBright,i.bgColor.bgGrey=i.bgColor.bgBlackBright;for(const[o,c]of Object.entries(i)){for(const[u,l]of Object.entries(c))i[u]={open:`\x1B[${l[0]}m`,close:`\x1B[${l[1]}m`},c[u]=i[u],s.set(l[0],l[1]);Object.defineProperty(i,o,{value:c,enumerable:!1})}return Object.defineProperty(i,"codes",{value:s,enumerable:!1}),i.color.close="\x1B[39m",i.bgColor.close="\x1B[49m",i.color.ansi256=r(),i.color.ansi16m=n(),i.bgColor.ansi256=r(10),i.bgColor.ansi16m=n(10),Object.defineProperties(i,{rgbToAnsi256:{value:(o,c,u)=>o===c&&c===u?o<8?16:o>248?231:Math.round((o-8)/247*24)+232:16+36*Math.round(o/255*5)+6*Math.round(c/255*5)+Math.round(u/255*5),enumerable:!1},hexToRgb:{value:o=>{const c=/(?<colorString>[a-f\d]{6}|[a-f\d]{3})/i.exec(o.toString(16));if(!c)return[0,0,0];let{colorString:u}=c.groups;u.length===3&&(u=u.split("").map(d=>d+d).join(""));const l=Number.parseInt(u,16);return[l>>16&255,l>>8&255,l&255]},enumerable:!1},hexToAnsi256:{value:o=>i.rgbToAnsi256(...i.hexToRgb(o)),enumerable:!1}}),i}Object.defineProperty(t,"exports",{enumerable:!0,get:a})})(un)),un.exports}var Bp=Fp();const Nu=gr(Bp);var zp={};pe(zp,{ConsoleCallbackHandler:()=>Is});function Le(t,e){return`${t.open}${e}${t.close}`}function Ye(t,e){try{return JSON.stringify(t,null,2)}catch{return e}}function yc(t){return typeof t=="string"?t.trim():t==null?t:Ye(t,t.toString())}function kt(t){if(!t.end_time)return"";const e=t.end_time-t.start_time;return e<1e3?`${e}ms`:`${(e/1e3).toFixed(2)}s`}const{color:ze}=Nu;var Is=class extends vr{name="console_callback_handler";persistRun(t){return Promise.resolve()}getParents(t){const e=[];let r=t;for(;r.parent_run_id;){const n=this.runMap.get(r.parent_run_id);if(n)e.push(n),r=n;else break}return e}getBreadcrumbs(t){const r=[...this.getParents(t).reverse(),t].map((n,a,s)=>{const i=`${n.execution_order}:${n.run_type}:${n.name}`;return a===s.length-1?Le(Nu.bold,i):i}).join(" > ");return Le(ze.grey,r)}onChainStart(t){const e=this.getBreadcrumbs(t);console.log(`${Le(ze.green,"[chain/start]")} [${e}] Entering Chain run with input: ${Ye(t.inputs,"[inputs]")}`)}onChainEnd(t){const e=this.getBreadcrumbs(t);console.log(`${Le(ze.cyan,"[chain/end]")} [${e}] [${kt(t)}] Exiting Chain run with output: ${Ye(t.outputs,"[outputs]")}`)}onChainError(t){const e=this.getBreadcrumbs(t);console.log(`${Le(ze.red,"[chain/error]")} [${e}] [${kt(t)}] Chain run errored with error: ${Ye(t.error,"[error]")}`)}onLLMStart(t){const e=this.getBreadcrumbs(t),r="prompts"in t.inputs?{prompts:t.inputs.prompts.map(n=>n.trim())}:t.inputs;console.log(`${Le(ze.green,"[llm/start]")} [${e}] Entering LLM run with input: ${Ye(r,"[inputs]")}`)}onLLMEnd(t){const e=this.getBreadcrumbs(t);console.log(`${Le(ze.cyan,"[llm/end]")} [${e}] [${kt(t)}] Exiting LLM run with output: ${Ye(t.outputs,"[response]")}`)}onLLMError(t){const e=this.getBreadcrumbs(t);console.log(`${Le(ze.red,"[llm/error]")} [${e}] [${kt(t)}] LLM run errored with error: ${Ye(t.error,"[error]")}`)}onToolStart(t){const e=this.getBreadcrumbs(t);console.log(`${Le(ze.green,"[tool/start]")} [${e}] Entering Tool run with input: "${yc(t.inputs.input)}"`)}onToolEnd(t){const e=this.getBreadcrumbs(t);console.log(`${Le(ze.cyan,"[tool/end]")} [${e}] [${kt(t)}] Exiting Tool run with output: "${yc(t.outputs?.output)}"`)}onToolError(t){const e=this.getBreadcrumbs(t);console.log(`${Le(ze.red,"[tool/error]")} [${e}] [${kt(t)}] Tool run errored with error: ${Ye(t.error,"[error]")}`)}onRetrieverStart(t){const e=this.getBreadcrumbs(t);console.log(`${Le(ze.green,"[retriever/start]")} [${e}] Entering Retriever run with input: ${Ye(t.inputs,"[inputs]")}`)}onRetrieverEnd(t){const e=this.getBreadcrumbs(t);console.log(`${Le(ze.cyan,"[retriever/end]")} [${e}] [${kt(t)}] Exiting Retriever run with output: ${Ye(t.outputs,"[outputs]")}`)}onRetrieverError(t){const e=this.getBreadcrumbs(t);console.log(`${Le(ze.red,"[retriever/error]")} [${e}] [${kt(t)}] Retriever run errored with error: ${Ye(t.error,"[error]")}`)}onAgentAction(t){const e=t,r=this.getBreadcrumbs(t);console.log(`${Le(ze.blue,"[agent/action]")} [${r}] Agent selected action: ${Ye(e.actions[e.actions.length-1],"[action]")}`)}};let ts;const $u=()=>{if(ts===void 0){const t=$t("LANGCHAIN_CALLBACKS_BACKGROUND")==="false"?{blockOnRootRunFinalization:!0}:{};ts=new Dr(t)}return ts};let qp=class{getStore(){}run(e,r){return r()}};const rs=Symbol.for("ls:tracing_async_local_storage"),Gp=new qp;let Hp=class{getInstance(){return globalThis[rs]??Gp}initializeGlobalInstance(e){globalThis[rs]===void 0&&(globalThis[rs]=e)}};const Zp=new Hp;function Vp(t=!1){const e=Zp.getInstance().getStore();if(!t&&e===void 0)throw new Error(`Could not get the current run tree.
|
|
52
|
-
|
|
53
|
-
Please make sure you are calling this method within a traceable function and that tracing is enabled.`);return e}function fi(t){return typeof t=="function"&&"langsmith:traceable"in t}var Wp={};pe(Wp,{LangChainTracer:()=>ln});var ln=class Pu extends vr{name="langchain_tracer";projectName;exampleId;client;replicas;usesRunTreeMap=!0;constructor(e={}){super(e);const{exampleId:r,projectName:n,client:a,replicas:s}=e;this.projectName=n??gu(),this.replicas=s,this.exampleId=r,this.client=a??$u();const i=Pu.getTraceableRunTree();i&&this.updateFromRunTree(i)}async persistRun(e){}async onRunCreate(e){await this.getRunTreeWithTracingConfig(e.id)?.postRun()}async onRunUpdate(e){await this.getRunTreeWithTracingConfig(e.id)?.patchRun()}getRun(e){return this.runTreeMap.get(e)}updateFromRunTree(e){this.runTreeMap.set(e.id,e);let r=e;const n=new Set;for(;r.parent_run&&!(n.has(r.id)||(n.add(r.id),!r.parent_run));)r=r.parent_run;n.clear();const a=[r];for(;a.length>0;){const s=a.shift();!s||n.has(s.id)||(n.add(s.id),this.runTreeMap.set(s.id,s),s.child_runs&&a.push(...s.child_runs))}this.client=e.client??this.client,this.replicas=e.replicas??this.replicas,this.projectName=e.project_name??this.projectName,this.exampleId=e.reference_example_id??this.exampleId}getRunTreeWithTracingConfig(e){const r=this.runTreeMap.get(e);if(r)return new qe({...r,client:this.client,project_name:this.projectName,replicas:this.replicas,reference_example_id:this.exampleId,tracingEnabled:!0})}static getTraceableRunTree(){try{return Vp(!0)}catch{return}}};let zt;function Jp(){const t="default"in Tt?Tt.default:Tt;return new t({autoStart:!0,concurrency:1})}function Kp(){return typeof zt>"u"&&(zt=Jp()),zt}async function Oe(t,e){if(e===!0){const r=jr();r!==void 0?await r.run(void 0,async()=>t()):await t()}else zt=Kp(),zt.add(async()=>{const r=jr();r!==void 0?await r.run(void 0,async()=>t()):await t()})}async function Yp(){const t=$u();await Promise.allSettled([typeof zt<"u"?zt.onIdle():Promise.resolve(),t.awaitPendingTraceBatches()])}var Xp={};pe(Xp,{awaitAllCallbacks:()=>Yp,consumeCallback:()=>Oe});const Qp=t=>!!["LANGSMITH_TRACING_V2","LANGCHAIN_TRACING_V2","LANGSMITH_TRACING","LANGCHAIN_TRACING"].find(r=>$t(r)==="true");function Mu(t){const e=jr();return e===void 0?void 0:e.getStore()?.[kr]?.[t]}const em=Symbol("lc:configure_hooks"),tm=()=>Mu(em)||[];var rm={};pe(rm,{BaseCallbackManager:()=>Lu,BaseRunManager:()=>Zr,CallbackManager:()=>mt,CallbackManagerForChainRun:()=>Du,CallbackManagerForLLMRun:()=>xs,CallbackManagerForRetrieverRun:()=>ju,CallbackManagerForToolRun:()=>Uu,ensureHandler:()=>Ur,parseCallbackConfigArg:()=>nm});function nm(t){return t?Array.isArray(t)||"name"in t?{callbacks:t}:t:{}}var Lu=class{setHandler(t){return this.setHandlers([t])}},Zr=class{constructor(t,e,r,n,a,s,i,o){this.runId=t,this.handlers=e,this.inheritableHandlers=r,this.tags=n,this.inheritableTags=a,this.metadata=s,this.inheritableMetadata=i,this._parentRunId=o}get parentRunId(){return this._parentRunId}async handleText(t){await Promise.all(this.handlers.map(e=>Oe(async()=>{try{await e.handleText?.(t,this.runId,this._parentRunId,this.tags)}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleText: ${r}`),e.raiseError)throw r}},e.awaitHandlers)))}async handleCustomEvent(t,e,r,n,a){await Promise.all(this.handlers.map(s=>Oe(async()=>{try{await s.handleCustomEvent?.(t,e,this.runId,this.tags,this.metadata)}catch(i){if((s.raiseError?console.error:console.warn)(`Error in handler ${s.constructor.name}, handleCustomEvent: ${i}`),s.raiseError)throw i}},s.awaitHandlers)))}},ju=class extends Zr{getChild(t){const e=new mt(this.runId);return e.setHandlers(this.inheritableHandlers),e.addTags(this.inheritableTags),e.addMetadata(this.inheritableMetadata),t&&e.addTags([t],!1),e}async handleRetrieverEnd(t){await Promise.all(this.handlers.map(e=>Oe(async()=>{if(!e.ignoreRetriever)try{await e.handleRetrieverEnd?.(t,this.runId,this._parentRunId,this.tags)}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleRetriever`),e.raiseError)throw r}},e.awaitHandlers)))}async handleRetrieverError(t){await Promise.all(this.handlers.map(e=>Oe(async()=>{if(!e.ignoreRetriever)try{await e.handleRetrieverError?.(t,this.runId,this._parentRunId,this.tags)}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleRetrieverError: ${r}`),e.raiseError)throw t}},e.awaitHandlers)))}},xs=class extends Zr{async handleLLMNewToken(t,e,r,n,a,s){await Promise.all(this.handlers.map(i=>Oe(async()=>{if(!i.ignoreLLM)try{await i.handleLLMNewToken?.(t,e??{prompt:0,completion:0},this.runId,this._parentRunId,this.tags,s)}catch(o){if((i.raiseError?console.error:console.warn)(`Error in handler ${i.constructor.name}, handleLLMNewToken: ${o}`),i.raiseError)throw o}},i.awaitHandlers)))}async handleLLMError(t,e,r,n,a){await Promise.all(this.handlers.map(s=>Oe(async()=>{if(!s.ignoreLLM)try{await s.handleLLMError?.(t,this.runId,this._parentRunId,this.tags,a)}catch(i){if((s.raiseError?console.error:console.warn)(`Error in handler ${s.constructor.name}, handleLLMError: ${i}`),s.raiseError)throw i}},s.awaitHandlers)))}async handleLLMEnd(t,e,r,n,a){await Promise.all(this.handlers.map(s=>Oe(async()=>{if(!s.ignoreLLM)try{await s.handleLLMEnd?.(t,this.runId,this._parentRunId,this.tags,a)}catch(i){if((s.raiseError?console.error:console.warn)(`Error in handler ${s.constructor.name}, handleLLMEnd: ${i}`),s.raiseError)throw i}},s.awaitHandlers)))}},Du=class extends Zr{getChild(t){const e=new mt(this.runId);return e.setHandlers(this.inheritableHandlers),e.addTags(this.inheritableTags),e.addMetadata(this.inheritableMetadata),t&&e.addTags([t],!1),e}async handleChainError(t,e,r,n,a){await Promise.all(this.handlers.map(s=>Oe(async()=>{if(!s.ignoreChain)try{await s.handleChainError?.(t,this.runId,this._parentRunId,this.tags,a)}catch(i){if((s.raiseError?console.error:console.warn)(`Error in handler ${s.constructor.name}, handleChainError: ${i}`),s.raiseError)throw i}},s.awaitHandlers)))}async handleChainEnd(t,e,r,n,a){await Promise.all(this.handlers.map(s=>Oe(async()=>{if(!s.ignoreChain)try{await s.handleChainEnd?.(t,this.runId,this._parentRunId,this.tags,a)}catch(i){if((s.raiseError?console.error:console.warn)(`Error in handler ${s.constructor.name}, handleChainEnd: ${i}`),s.raiseError)throw i}},s.awaitHandlers)))}async handleAgentAction(t){await Promise.all(this.handlers.map(e=>Oe(async()=>{if(!e.ignoreAgent)try{await e.handleAgentAction?.(t,this.runId,this._parentRunId,this.tags)}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleAgentAction: ${r}`),e.raiseError)throw r}},e.awaitHandlers)))}async handleAgentEnd(t){await Promise.all(this.handlers.map(e=>Oe(async()=>{if(!e.ignoreAgent)try{await e.handleAgentEnd?.(t,this.runId,this._parentRunId,this.tags)}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleAgentEnd: ${r}`),e.raiseError)throw r}},e.awaitHandlers)))}},Uu=class extends Zr{getChild(t){const e=new mt(this.runId);return e.setHandlers(this.inheritableHandlers),e.addTags(this.inheritableTags),e.addMetadata(this.inheritableMetadata),t&&e.addTags([t],!1),e}async handleToolError(t){await Promise.all(this.handlers.map(e=>Oe(async()=>{if(!e.ignoreAgent)try{await e.handleToolError?.(t,this.runId,this._parentRunId,this.tags)}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleToolError: ${r}`),e.raiseError)throw r}},e.awaitHandlers)))}async handleToolEnd(t){await Promise.all(this.handlers.map(e=>Oe(async()=>{if(!e.ignoreAgent)try{await e.handleToolEnd?.(t,this.runId,this._parentRunId,this.tags)}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleToolEnd: ${r}`),e.raiseError)throw r}},e.awaitHandlers)))}},mt=class Ir extends Lu{handlers=[];inheritableHandlers=[];tags=[];inheritableTags=[];metadata={};inheritableMetadata={};name="callback_manager";_parentRunId;constructor(e,r){super(),this.handlers=r?.handlers??this.handlers,this.inheritableHandlers=r?.inheritableHandlers??this.inheritableHandlers,this.tags=r?.tags??this.tags,this.inheritableTags=r?.inheritableTags??this.inheritableTags,this.metadata=r?.metadata??this.metadata,this.inheritableMetadata=r?.inheritableMetadata??this.inheritableMetadata,this._parentRunId=e}getParentRunId(){return this._parentRunId}async handleLLMStart(e,r,n=void 0,a=void 0,s=void 0,i=void 0,o=void 0,c=void 0){return Promise.all(r.map(async(u,l)=>{const d=l===0&&n?n:De();return await Promise.all(this.handlers.map(h=>{if(!h.ignoreLLM)return rr(h)&&h._createRunForLLMStart(e,[u],d,this._parentRunId,s,this.tags,this.metadata,c),Oe(async()=>{try{await h.handleLLMStart?.(e,[u],d,this._parentRunId,s,this.tags,this.metadata,c)}catch(p){if((h.raiseError?console.error:console.warn)(`Error in handler ${h.constructor.name}, handleLLMStart: ${p}`),h.raiseError)throw p}},h.awaitHandlers)})),new xs(d,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChatModelStart(e,r,n=void 0,a=void 0,s=void 0,i=void 0,o=void 0,c=void 0){return Promise.all(r.map(async(u,l)=>{const d=l===0&&n?n:De();return await Promise.all(this.handlers.map(h=>{if(!h.ignoreLLM)return rr(h)&&h._createRunForChatModelStart(e,[u],d,this._parentRunId,s,this.tags,this.metadata,c),Oe(async()=>{try{if(h.handleChatModelStart)await h.handleChatModelStart?.(e,[u],d,this._parentRunId,s,this.tags,this.metadata,c);else if(h.handleLLMStart){const p=ai(u);await h.handleLLMStart?.(e,[p],d,this._parentRunId,s,this.tags,this.metadata,c)}}catch(p){if((h.raiseError?console.error:console.warn)(`Error in handler ${h.constructor.name}, handleLLMStart: ${p}`),h.raiseError)throw p}},h.awaitHandlers)})),new xs(d,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChainStart(e,r,n=De(),a=void 0,s=void 0,i=void 0,o=void 0){return await Promise.all(this.handlers.map(c=>{if(!c.ignoreChain)return rr(c)&&c._createRunForChainStart(e,r,n,this._parentRunId,this.tags,this.metadata,a,o),Oe(async()=>{try{await c.handleChainStart?.(e,r,n,this._parentRunId,this.tags,this.metadata,a,o)}catch(u){if((c.raiseError?console.error:console.warn)(`Error in handler ${c.constructor.name}, handleChainStart: ${u}`),c.raiseError)throw u}},c.awaitHandlers)})),new Du(n,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleToolStart(e,r,n=De(),a=void 0,s=void 0,i=void 0,o=void 0){return await Promise.all(this.handlers.map(c=>{if(!c.ignoreAgent)return rr(c)&&c._createRunForToolStart(e,r,n,this._parentRunId,this.tags,this.metadata,o),Oe(async()=>{try{await c.handleToolStart?.(e,r,n,this._parentRunId,this.tags,this.metadata,o)}catch(u){if((c.raiseError?console.error:console.warn)(`Error in handler ${c.constructor.name}, handleToolStart: ${u}`),c.raiseError)throw u}},c.awaitHandlers)})),new Uu(n,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleRetrieverStart(e,r,n=De(),a=void 0,s=void 0,i=void 0,o=void 0){return await Promise.all(this.handlers.map(c=>{if(!c.ignoreRetriever)return rr(c)&&c._createRunForRetrieverStart(e,r,n,this._parentRunId,this.tags,this.metadata,o),Oe(async()=>{try{await c.handleRetrieverStart?.(e,r,n,this._parentRunId,this.tags,this.metadata,o)}catch(u){if((c.raiseError?console.error:console.warn)(`Error in handler ${c.constructor.name}, handleRetrieverStart: ${u}`),c.raiseError)throw u}},c.awaitHandlers)})),new ju(n,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleCustomEvent(e,r,n,a,s){await Promise.all(this.handlers.map(i=>Oe(async()=>{if(!i.ignoreCustomEvent)try{await i.handleCustomEvent?.(e,r,n,this.tags,this.metadata)}catch(o){if((i.raiseError?console.error:console.warn)(`Error in handler ${i.constructor.name}, handleCustomEvent: ${o}`),i.raiseError)throw o}},i.awaitHandlers)))}addHandler(e,r=!0){this.handlers.push(e),r&&this.inheritableHandlers.push(e)}removeHandler(e){this.handlers=this.handlers.filter(r=>r!==e),this.inheritableHandlers=this.inheritableHandlers.filter(r=>r!==e)}setHandlers(e,r=!0){this.handlers=[],this.inheritableHandlers=[];for(const n of e)this.addHandler(n,r)}addTags(e,r=!0){this.removeTags(e),this.tags.push(...e),r&&this.inheritableTags.push(...e)}removeTags(e){this.tags=this.tags.filter(r=>!e.includes(r)),this.inheritableTags=this.inheritableTags.filter(r=>!e.includes(r))}addMetadata(e,r=!0){this.metadata={...this.metadata,...e},r&&(this.inheritableMetadata={...this.inheritableMetadata,...e})}removeMetadata(e){for(const r of Object.keys(e))delete this.metadata[r],delete this.inheritableMetadata[r]}copy(e=[],r=!0){const n=new Ir(this._parentRunId);for(const a of this.handlers){const s=this.inheritableHandlers.includes(a);n.addHandler(a,s)}for(const a of this.tags){const s=this.inheritableTags.includes(a);n.addTags([a],s)}for(const a of Object.keys(this.metadata)){const s=Object.keys(this.inheritableMetadata).includes(a);n.addMetadata({[a]:this.metadata[a]},s)}for(const a of e)n.handlers.filter(s=>s.name==="console_callback_handler").some(s=>s.name===a.name)||n.addHandler(a,r);return n}static fromHandlers(e){class r extends Gr{name=De();constructor(){super(),Object.assign(this,e)}}const n=new this;return n.addHandler(new r),n}static configure(e,r,n,a,s,i,o){return this._configureSync(e,r,n,a,s,i,o)}static _configureSync(e,r,n,a,s,i,o){let c;(e||r)&&(Array.isArray(e)||!e?(c=new Ir,c.setHandlers(e?.map(Ur)??[],!0)):c=e,c=c.copy(Array.isArray(r)?r.map(Ur):r?.handlers,!1));const u=$t("LANGCHAIN_VERBOSE")==="true"||o?.verbose,l=ln.getTraceableRunTree()?.tracingEnabled||Qp(),d=l||($t("LANGCHAIN_TRACING")??!1);if(u||d){if(c||(c=new Ir),u&&!c.handlers.some(h=>h.name===Is.prototype.name)){const h=new Is;c.addHandler(h,!0)}if(d&&!c.handlers.some(h=>h.name==="langchain_tracer")&&l){const h=new ln;c.addHandler(h,!0)}if(l){const h=ln.getTraceableRunTree();h&&c._parentRunId===void 0&&(c._parentRunId=h.id,c.handlers.find(g=>g.name==="langchain_tracer")?.updateFromRunTree(h))}}for(const{contextVar:h,inheritable:p=!0,handlerClass:g,envVar:y}of tm()){const v=y&&$t(y)==="true"&&g;let b;const S=h!==void 0?Mu(h):void 0;S&&pu(S)?b=S:v&&(b=new g({})),b!==void 0&&(c||(c=new Ir),c.handlers.some(E=>E.name===b.name)||c.addHandler(b,p))}return(n||a)&&c&&(c.addTags(n??[]),c.addTags(a??[],!1)),(s||i)&&c&&(c.addMetadata(s??{}),c.addMetadata(i??{},!1)),c}};function Ur(t){return"name"in t?t:Gr.fromMethods(t)}var Fu=class{getStore(){}run(t,e){return e()}enterWith(t){}};const am=new Fu,vc=Symbol.for("lc:child_config");var sm=class{getInstance(){return jr()??am}getRunnableConfig(){return this.getInstance().getStore()?.extra?.[vc]}runWithConfig(t,e,r){const n=mt._configureSync(t?.callbacks,void 0,t?.tags,void 0,t?.metadata),a=this.getInstance(),s=a.getStore(),i=n?.getParentRunId(),o=n?.handlers?.find(u=>u?.name==="langchain_tracer");let c;return o&&i?c=o.getRunTreeWithTracingConfig(i):r||(c=new qe({name:"<runnable_lambda>",tracingEnabled:!1})),c&&(c.extra={...c.extra,[vc]:t}),s!==void 0&&s[kr]!==void 0&&(c===void 0&&(c={}),c[kr]=s[kr]),a.run(c,e)}initializeGlobalInstance(t){jr()===void 0&&_h(t)}};const It=new sm;var im={};pe(im,{AsyncLocalStorageProviderSingleton:()=>It,MockAsyncLocalStorage:()=>Fu,_CONTEXT_VARIABLES_KEY:()=>kr});const ns=25;async function Je(t){return mt._configureSync(t?.callbacks,void 0,t?.tags,void 0,t?.metadata)}function As(...t){const e={};for(const r of t.filter(n=>!!n))for(const n of Object.keys(r))if(n==="metadata")e[n]={...e[n],...r[n]};else if(n==="tags"){const a=e[n]??[];e[n]=[...new Set(a.concat(r[n]??[]))]}else if(n==="configurable")e[n]={...e[n],...r[n]};else if(n==="timeout")e.timeout===void 0?e.timeout=r.timeout:r.timeout!==void 0&&(e.timeout=Math.min(e.timeout,r.timeout));else if(n==="signal")e.signal===void 0?e.signal=r.signal:r.signal!==void 0&&("any"in AbortSignal?e.signal=AbortSignal.any([e.signal,r.signal]):e.signal=r.signal);else if(n==="callbacks"){const a=e.callbacks,s=r.callbacks;if(Array.isArray(s))if(!a)e.callbacks=s;else if(Array.isArray(a))e.callbacks=a.concat(s);else{const i=a.copy();for(const o of s)i.addHandler(Ur(o),!0);e.callbacks=i}else if(s)if(!a)e.callbacks=s;else if(Array.isArray(a)){const i=s.copy();for(const o of a)i.addHandler(Ur(o),!0);e.callbacks=i}else e.callbacks=new mt(s._parentRunId,{handlers:a.handlers.concat(s.handlers),inheritableHandlers:a.inheritableHandlers.concat(s.inheritableHandlers),tags:Array.from(new Set(a.tags.concat(s.tags))),inheritableTags:Array.from(new Set(a.inheritableTags.concat(s.inheritableTags))),metadata:{...a.metadata,...s.metadata}})}else{const a=n;e[a]=r[a]??e[a]}return e}const om=new Set(["string","number","boolean"]);function de(t){const e=It.getRunnableConfig();let r={tags:[],metadata:{},recursionLimit:25,runId:void 0};if(e){const{runId:n,runName:a,...s}=e;r=Object.entries(s).reduce((i,[o,c])=>(c!==void 0&&(i[o]=c),i),r)}if(t&&(r=Object.entries(t).reduce((n,[a,s])=>(s!==void 0&&(n[a]=s),n),r)),r?.configurable)for(const n of Object.keys(r.configurable))om.has(typeof r.configurable[n])&&!r.metadata?.[n]&&(r.metadata||(r.metadata={}),r.metadata[n]=r.configurable[n]);if(r.timeout!==void 0){if(r.timeout<=0)throw new Error("Timeout must be a positive number");const n=AbortSignal.timeout(r.timeout);r.signal!==void 0?"any"in AbortSignal&&(r.signal=AbortSignal.any([r.signal,n])):r.signal=n,delete r.timeout}return r}function we(t={},{callbacks:e,maxConcurrency:r,recursionLimit:n,runName:a,configurable:s,runId:i}={}){const o=de(t);return e!==void 0&&(delete o.runName,o.callbacks=e),n!==void 0&&(o.recursionLimit=n),r!==void 0&&(o.maxConcurrency=r),a!==void 0&&(o.runName=a),s!==void 0&&(o.configurable={...o.configurable,...s}),i!==void 0&&delete o.runId,o}function Vt(t){return t?{configurable:t.configurable,recursionLimit:t.recursionLimit,callbacks:t.callbacks,tags:t.tags,metadata:t.metadata,maxConcurrency:t.maxConcurrency,timeout:t.timeout,signal:t.signal}:void 0}async function Dt(t,e){if(e===void 0)return t;let r;return Promise.race([t.catch(n=>{if(!e?.aborted)throw n}),new Promise((n,a)=>{r=()=>{a(En(e))},e.addEventListener("abort",r),e.aborted&&a(En(e))})]).finally(()=>e.removeEventListener("abort",r))}function En(t){return t?.reason instanceof Error?t.reason:typeof t?.reason=="string"?new Error(t.reason):new Error("Aborted")}var cm={};pe(cm,{AsyncGeneratorWithSetup:()=>Xt,IterableReadableStream:()=>ot,atee:()=>pi,concat:()=>Wt,pipeGeneratorWithSetup:()=>Bu});var ot=class Os extends ReadableStream{reader;ensureReader(){this.reader||(this.reader=this.getReader())}async next(){this.ensureReader();try{const e=await this.reader.read();return e.done?(this.reader.releaseLock(),{done:!0,value:void 0}):{done:!1,value:e.value}}catch(e){throw this.reader.releaseLock(),e}}async return(){if(this.ensureReader(),this.locked){const e=this.reader.cancel();this.reader.releaseLock(),await e}return{done:!0,value:void 0}}async throw(e){if(this.ensureReader(),this.locked){const r=this.reader.cancel();this.reader.releaseLock(),await r}throw e}[Symbol.asyncIterator](){return this}async[Symbol.asyncDispose](){await this.return()}static fromReadableStream(e){const r=e.getReader();return new Os({start(n){return a();function a(){return r.read().then(({done:s,value:i})=>{if(s){n.close();return}return n.enqueue(i),a()})}},cancel(){r.releaseLock()}})}static fromAsyncGenerator(e){return new Os({async pull(r){const{value:n,done:a}=await e.next();a&&r.close(),r.enqueue(n)},async cancel(r){await e.return(r)}})}};function pi(t,e=2){const r=Array.from({length:e},()=>[]);return r.map(async function*(a){for(;;)if(a.length===0){const s=await t.next();for(const i of r)i.push(s)}else{if(a[0].done)return;yield a.shift().value}})}function Wt(t,e){if(Array.isArray(t)&&Array.isArray(e))return t.concat(e);if(typeof t=="string"&&typeof e=="string")return t+e;if(typeof t=="number"&&typeof e=="number")return t+e;if("concat"in t&&typeof t.concat=="function")return t.concat(e);if(typeof t=="object"&&typeof e=="object"){const r={...t};for(const[n,a]of Object.entries(e))n in r&&!Array.isArray(r[n])?r[n]=Wt(r[n],a):r[n]=a;return r}else throw new Error(`Cannot concat ${typeof t} and ${typeof e}`)}var Xt=class{generator;setup;config;signal;firstResult;firstResultUsed=!1;constructor(t){this.generator=t.generator,this.config=t.config,this.signal=t.signal??this.config?.signal,this.setup=new Promise((e,r)=>{It.runWithConfig(Vt(t.config),async()=>{this.firstResult=t.generator.next(),t.startSetup?this.firstResult.then(t.startSetup).then(e,r):this.firstResult.then(n=>e(void 0),r)},!0)})}async next(...t){return this.signal?.throwIfAborted(),this.firstResultUsed?It.runWithConfig(Vt(this.config),this.signal?async()=>Dt(this.generator.next(...t),this.signal):async()=>this.generator.next(...t),!0):(this.firstResultUsed=!0,this.firstResult)}async return(t){return this.generator.return(t)}async throw(t){return this.generator.throw(t)}[Symbol.asyncIterator](){return this}async[Symbol.asyncDispose](){await this.return()}};async function Bu(t,e,r,n,...a){const s=new Xt({generator:e,startSetup:r,signal:n}),i=await s.setup;return{output:t(s,i,...a),setup:i}}const um=Object.prototype.hasOwnProperty;function ks(t,e){return um.call(t,e)}function Rs(t){if(Array.isArray(t)){const r=new Array(t.length);for(let n=0;n<r.length;n++)r[n]=""+n;return r}if(Object.keys)return Object.keys(t);let e=[];for(let r in t)ks(t,r)&&e.push(r);return e}function st(t){switch(typeof t){case"object":return JSON.parse(JSON.stringify(t));case"undefined":return null;default:return t}}function Cs(t){let e=0;const r=t.length;let n;for(;e<r;){if(n=t.charCodeAt(e),n>=48&&n<=57){e++;continue}return!1}return!0}function er(t){return t.indexOf("/")===-1&&t.indexOf("~")===-1?t:t.replace(/~/g,"~0").replace(/\//g,"~1")}function lm(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}function Ns(t){if(t===void 0)return!0;if(t){if(Array.isArray(t)){for(let r=0,n=t.length;r<n;r++)if(Ns(t[r]))return!0}else if(typeof t=="object"){const r=Rs(t),n=r.length;for(var e=0;e<n;e++)if(Ns(t[r[e]]))return!0}}return!1}function wc(t,e){const r=[t];for(const n in e){const a=typeof e[n]=="object"?JSON.stringify(e[n],null,2):e[n];typeof a<"u"&&r.push(`${n}: ${a}`)}return r.join(`
|
|
54
|
-
`)}var dm=class extends Error{constructor(t,e,r,n,a){super(wc(t,{name:e,index:r,operation:n,tree:a})),this.name=e,this.index=r,this.operation=n,this.tree=a,Object.setPrototypeOf(this,new.target.prototype),this.message=wc(t,{name:e,index:r,operation:n,tree:a})}},zu={};pe(zu,{JsonPatchError:()=>Ee,_areEquals:()=>Fr,applyOperation:()=>qt,applyPatch:()=>pr,applyReducer:()=>pm,deepClone:()=>hm,getValueByPointer:()=>Tn,validate:()=>qu,validator:()=>Sn});const Ee=dm,hm=st,ar={add:function(t,e,r){return t[e]=this.value,{newDocument:r}},remove:function(t,e,r){var n=t[e];return delete t[e],{newDocument:r,removed:n}},replace:function(t,e,r){var n=t[e];return t[e]=this.value,{newDocument:r,removed:n}},move:function(t,e,r){let n=Tn(r,this.path);n&&(n=st(n));const a=qt(r,{op:"remove",path:this.from}).removed;return qt(r,{op:"add",path:this.path,value:a}),{newDocument:r,removed:n}},copy:function(t,e,r){const n=Tn(r,this.from);return qt(r,{op:"add",path:this.path,value:st(n)}),{newDocument:r}},test:function(t,e,r){return{newDocument:r,test:Fr(t[e],this.value)}},_get:function(t,e,r){return this.value=t[e],{newDocument:r}}};var fm={add:function(t,e,r){return Cs(e)?t.splice(e,0,this.value):t[e]=this.value,{newDocument:r,index:e}},remove:function(t,e,r){var n=t.splice(e,1);return{newDocument:r,removed:n[0]}},replace:function(t,e,r){var n=t[e];return t[e]=this.value,{newDocument:r,removed:n}},move:ar.move,copy:ar.copy,test:ar.test,_get:ar._get};function Tn(t,e){if(e=="")return t;var r={op:"_get",path:e};return qt(t,r),r.value}function qt(t,e,r=!1,n=!0,a=!0,s=0){if(r&&(typeof r=="function"?r(e,0,t,e.path):Sn(e,0)),e.path===""){let i={newDocument:t};if(e.op==="add")return i.newDocument=e.value,i;if(e.op==="replace")return i.newDocument=e.value,i.removed=t,i;if(e.op==="move"||e.op==="copy")return i.newDocument=Tn(t,e.from),e.op==="move"&&(i.removed=t),i;if(e.op==="test"){if(i.test=Fr(t,e.value),i.test===!1)throw new Ee("Test operation failed","TEST_OPERATION_FAILED",s,e,t);return i.newDocument=t,i}else{if(e.op==="remove")return i.removed=t,i.newDocument=null,i;if(e.op==="_get")return e.value=t,i;if(r)throw new Ee("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",s,e,t);return i}}else{n||(t=st(t));const o=(e.path||"").split("/");let c=t,u=1,l=o.length,d,h,p;for(typeof r=="function"?p=r:p=Sn;;){if(h=o[u],h&&h.indexOf("~")!=-1&&(h=lm(h)),a&&(h=="__proto__"||h=="prototype"&&u>0&&o[u-1]=="constructor"))throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(r&&d===void 0&&(c[h]===void 0?d=o.slice(0,u).join("/"):u==l-1&&(d=e.path),d!==void 0&&p(e,0,t,d)),u++,Array.isArray(c)){if(h==="-")h=c.length;else{if(r&&!Cs(h))throw new Ee("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",s,e,t);Cs(h)&&(h=~~h)}if(u>=l){if(r&&e.op==="add"&&h>c.length)throw new Ee("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",s,e,t);const g=fm[e.op].call(e,c,h,t);if(g.test===!1)throw new Ee("Test operation failed","TEST_OPERATION_FAILED",s,e,t);return g}}else if(u>=l){const g=ar[e.op].call(e,c,h,t);if(g.test===!1)throw new Ee("Test operation failed","TEST_OPERATION_FAILED",s,e,t);return g}if(c=c[h],r&&u<l&&(!c||typeof c!="object"))throw new Ee("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",s,e,t)}}}function pr(t,e,r,n=!0,a=!0){if(r&&!Array.isArray(e))throw new Ee("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");n||(t=st(t));const s=new Array(e.length);for(let i=0,o=e.length;i<o;i++)s[i]=qt(t,e[i],r,!0,a,i),t=s[i].newDocument;return s.newDocument=t,s}function pm(t,e,r){const n=qt(t,e);if(n.test===!1)throw new Ee("Test operation failed","TEST_OPERATION_FAILED",r,e,t);return n.newDocument}function Sn(t,e,r,n){if(typeof t!="object"||t===null||Array.isArray(t))throw new Ee("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,t,r);if(ar[t.op]){if(typeof t.path!="string")throw new Ee("Operation `path` property is not a string","OPERATION_PATH_INVALID",e,t,r);if(t.path.indexOf("/")!==0&&t.path.length>0)throw new Ee('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",e,t,r);if((t.op==="move"||t.op==="copy")&&typeof t.from!="string")throw new Ee("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",e,t,r);if((t.op==="add"||t.op==="replace"||t.op==="test")&&t.value===void 0)throw new Ee("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",e,t,r);if((t.op==="add"||t.op==="replace"||t.op==="test")&&Ns(t.value))throw new Ee("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",e,t,r);if(r){if(t.op=="add"){var a=t.path.split("/").length,s=n.split("/").length;if(a!==s+1&&a!==s)throw new Ee("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",e,t,r)}else if(t.op==="replace"||t.op==="remove"||t.op==="_get"){if(t.path!==n)throw new Ee("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",e,t,r)}else if(t.op==="move"||t.op==="copy"){var i={op:"_get",path:t.from,value:void 0},o=qu([i],r);if(o&&o.name==="OPERATION_PATH_UNRESOLVABLE")throw new Ee("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",e,t,r)}}}else throw new Ee("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",e,t,r)}function qu(t,e,r){try{if(!Array.isArray(t))throw new Ee("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)pr(st(e),st(t),r||!0);else{r=r||Sn;for(var n=0;n<t.length;n++)r(t[n],n,e,void 0)}}catch(a){if(a instanceof Ee)return a;throw a}}function Fr(t,e){if(t===e)return!0;if(t&&e&&typeof t=="object"&&typeof e=="object"){var r=Array.isArray(t),n=Array.isArray(e),a,s,i;if(r&&n){if(s=t.length,s!=e.length)return!1;for(a=s;a--!==0;)if(!Fr(t[a],e[a]))return!1;return!0}if(r!=n)return!1;var o=Object.keys(t);if(s=o.length,s!==Object.keys(e).length)return!1;for(a=s;a--!==0;)if(!e.hasOwnProperty(o[a]))return!1;for(a=s;a--!==0;)if(i=o[a],!Fr(t[i],e[i]))return!1;return!0}return t!==t&&e!==e}function Gu(t,e,r,n,a){if(e!==t){typeof e.toJSON=="function"&&(e=e.toJSON());for(var s=Rs(e),i=Rs(t),o=!1,c=i.length-1;c>=0;c--){var u=i[c],l=t[u];if(ks(e,u)&&!(e[u]===void 0&&l!==void 0&&Array.isArray(e)===!1)){var d=e[u];typeof l=="object"&&l!=null&&typeof d=="object"&&d!=null&&Array.isArray(l)===Array.isArray(d)?Gu(l,d,r,n+"/"+er(u),a):l!==d&&(a&&r.push({op:"test",path:n+"/"+er(u),value:st(l)}),r.push({op:"replace",path:n+"/"+er(u),value:st(d)}))}else Array.isArray(t)===Array.isArray(e)?(a&&r.push({op:"test",path:n+"/"+er(u),value:st(l)}),r.push({op:"remove",path:n+"/"+er(u)}),o=!0):(a&&r.push({op:"test",path:n,value:t}),r.push({op:"replace",path:n,value:e}))}if(!(!o&&s.length==i.length))for(var c=0;c<s.length;c++){var u=s[c];!ks(t,u)&&e[u]!==void 0&&r.push({op:"add",path:n+"/"+er(u),value:st(e[u])})}}}function mi(t,e,r=!1){var n=[];return Gu(t,e,n,"",r),n}({...zu});var mm={};pe(mm,{LogStreamCallbackHandler:()=>Ps,RunLog:()=>gi,RunLogPatch:()=>wt,isLogStreamHandler:()=>Hu});var wt=class{ops;constructor(t){this.ops=t.ops??[]}concat(t){const e=this.ops.concat(t.ops),r=pr({},e);return new gi({ops:e,state:r[r.length-1].newDocument})}},gi=class $s extends wt{state;constructor(e){super(e),this.state=e.state}concat(e){const r=this.ops.concat(e.ops),n=pr(this.state,e.ops);return new $s({ops:r,state:n[n.length-1].newDocument})}static fromRunLogPatch(e){const r=pr({},e.ops);return new $s({ops:e.ops,state:r[r.length-1].newDocument})}};const Hu=t=>t.name==="log_stream_tracer";async function bc(t,e){if(e==="original")throw new Error("Do not assign inputs with original schema drop the key for now. When inputs are added to streamLog they should be added with standardized schema for streaming events.");const{inputs:r}=t;if(["retriever","llm","prompt"].includes(t.run_type))return r;if(!(Object.keys(r).length===1&&r?.input===""))return r.input}async function Ec(t,e){const{outputs:r}=t;return e==="original"||["retriever","llm","prompt"].includes(t.run_type)?r:r!==void 0&&Object.keys(r).length===1&&r?.output!==void 0?r.output:r}function gm(t){return t!==void 0&&t.message!==void 0}var Ps=class extends vr{autoClose=!0;includeNames;includeTypes;includeTags;excludeNames;excludeTypes;excludeTags;_schemaFormat="original";rootId;keyMapByRunId={};counterMapByRunName={};transformStream;writer;receiveStream;name="log_stream_tracer";lc_prefer_streaming=!0;constructor(t){super({_awaitHandler:!0,...t}),this.autoClose=t?.autoClose??!0,this.includeNames=t?.includeNames,this.includeTypes=t?.includeTypes,this.includeTags=t?.includeTags,this.excludeNames=t?.excludeNames,this.excludeTypes=t?.excludeTypes,this.excludeTags=t?.excludeTags,this._schemaFormat=t?._schemaFormat??this._schemaFormat,this.transformStream=new TransformStream,this.writer=this.transformStream.writable.getWriter(),this.receiveStream=ot.fromReadableStream(this.transformStream.readable)}[Symbol.asyncIterator](){return this.receiveStream}async persistRun(t){}_includeRun(t){if(t.id===this.rootId)return!1;const e=t.tags??[];let r=this.includeNames===void 0&&this.includeTags===void 0&&this.includeTypes===void 0;return this.includeNames!==void 0&&(r=r||this.includeNames.includes(t.name)),this.includeTypes!==void 0&&(r=r||this.includeTypes.includes(t.run_type)),this.includeTags!==void 0&&(r=r||e.find(n=>this.includeTags?.includes(n))!==void 0),this.excludeNames!==void 0&&(r=r&&!this.excludeNames.includes(t.name)),this.excludeTypes!==void 0&&(r=r&&!this.excludeTypes.includes(t.run_type)),this.excludeTags!==void 0&&(r=r&&e.every(n=>!this.excludeTags?.includes(n))),r}async*tapOutputIterable(t,e){for await(const r of e){if(t!==this.rootId){const n=this.keyMapByRunId[t];n&&await this.writer.write(new wt({ops:[{op:"add",path:`/logs/${n}/streamed_output/-`,value:r}]}))}yield r}}async onRunCreate(t){if(this.rootId===void 0&&(this.rootId=t.id,await this.writer.write(new wt({ops:[{op:"replace",path:"",value:{id:t.id,name:t.name,type:t.run_type,streamed_output:[],final_output:void 0,logs:{}}}]}))),!this._includeRun(t))return;this.counterMapByRunName[t.name]===void 0&&(this.counterMapByRunName[t.name]=0),this.counterMapByRunName[t.name]+=1;const e=this.counterMapByRunName[t.name];this.keyMapByRunId[t.id]=e===1?t.name:`${t.name}:${e}`;const r={id:t.id,name:t.name,type:t.run_type,tags:t.tags??[],metadata:t.extra?.metadata??{},start_time:new Date(t.start_time).toISOString(),streamed_output:[],streamed_output_str:[],final_output:void 0,end_time:void 0};this._schemaFormat==="streaming_events"&&(r.inputs=await bc(t,this._schemaFormat)),await this.writer.write(new wt({ops:[{op:"add",path:`/logs/${this.keyMapByRunId[t.id]}`,value:r}]}))}async onRunUpdate(t){try{const e=this.keyMapByRunId[t.id];if(e===void 0)return;const r=[];this._schemaFormat==="streaming_events"&&r.push({op:"replace",path:`/logs/${e}/inputs`,value:await bc(t,this._schemaFormat)}),r.push({op:"add",path:`/logs/${e}/final_output`,value:await Ec(t,this._schemaFormat)}),t.end_time!==void 0&&r.push({op:"add",path:`/logs/${e}/end_time`,value:new Date(t.end_time).toISOString()});const n=new wt({ops:r});await this.writer.write(n)}finally{if(t.id===this.rootId){const e=new wt({ops:[{op:"replace",path:"/final_output",value:await Ec(t,this._schemaFormat)}]});await this.writer.write(e),this.autoClose&&await this.writer.close()}}}async onLLMNewToken(t,e,r){const n=this.keyMapByRunId[t.id];if(n===void 0)return;const a=t.inputs.messages!==void 0;let s;a?gm(r?.chunk)?s=r?.chunk:s=new Yt({id:`run-${t.id}`,content:e}):s=e;const i=new wt({ops:[{op:"add",path:`/logs/${n}/streamed_output_str/-`,value:e},{op:"add",path:`/logs/${n}/streamed_output/-`,value:s}]});await this.writer.write(i)}},_m={};pe(_m,{ChatGenerationChunk:()=>Ls,GenerationChunk:()=>Br,RUN_KEY:()=>Ms});const Ms="__run";var Br=class Zu{text;generationInfo;constructor(e){this.text=e.text,this.generationInfo=e.generationInfo}concat(e){return new Zu({text:this.text+e.text,generationInfo:{...this.generationInfo,...e.generationInfo}})}},Ls=class Vu extends Br{message;constructor(e){super(e),this.message=e.message}concat(e){return new Vu({text:this.text+e.text,generationInfo:{...this.generationInfo,...e.generationInfo},message:this.message.concat(e.message)})}};function sn({name:t,serialized:e}){return t!==void 0?t:e?.name!==void 0?e.name:e?.id!==void 0&&Array.isArray(e?.id)?e.id[e.id.length-1]:"Unnamed"}const ym=t=>t.name==="event_stream_tracer";var vm=class extends vr{autoClose=!0;includeNames;includeTypes;includeTags;excludeNames;excludeTypes;excludeTags;runInfoMap=new Map;tappedPromises=new Map;transformStream;writer;receiveStream;name="event_stream_tracer";lc_prefer_streaming=!0;constructor(t){super({_awaitHandler:!0,...t}),this.autoClose=t?.autoClose??!0,this.includeNames=t?.includeNames,this.includeTypes=t?.includeTypes,this.includeTags=t?.includeTags,this.excludeNames=t?.excludeNames,this.excludeTypes=t?.excludeTypes,this.excludeTags=t?.excludeTags,this.transformStream=new TransformStream,this.writer=this.transformStream.writable.getWriter(),this.receiveStream=ot.fromReadableStream(this.transformStream.readable)}[Symbol.asyncIterator](){return this.receiveStream}async persistRun(t){}_includeRun(t){const e=t.tags??[];let r=this.includeNames===void 0&&this.includeTags===void 0&&this.includeTypes===void 0;return this.includeNames!==void 0&&(r=r||this.includeNames.includes(t.name)),this.includeTypes!==void 0&&(r=r||this.includeTypes.includes(t.runType)),this.includeTags!==void 0&&(r=r||e.find(n=>this.includeTags?.includes(n))!==void 0),this.excludeNames!==void 0&&(r=r&&!this.excludeNames.includes(t.name)),this.excludeTypes!==void 0&&(r=r&&!this.excludeTypes.includes(t.runType)),this.excludeTags!==void 0&&(r=r&&e.every(n=>!this.excludeTags?.includes(n))),r}async*tapOutputIterable(t,e){const r=await e.next();if(r.done)return;const n=this.runInfoMap.get(t);if(n===void 0){yield r.value;return}function a(i,o){return i==="llm"&&typeof o=="string"?new Br({text:o}):o}let s=this.tappedPromises.get(t);if(s===void 0){let i;s=new Promise(o=>{i=o}),this.tappedPromises.set(t,s);try{const o={event:`on_${n.runType}_stream`,run_id:t,name:n.name,tags:n.tags,metadata:n.metadata,data:{}};await this.send({...o,data:{chunk:a(n.runType,r.value)}},n),yield r.value;for await(const c of e)n.runType!=="tool"&&n.runType!=="retriever"&&await this.send({...o,data:{chunk:a(n.runType,c)}},n),yield c}finally{i?.()}}else{yield r.value;for await(const i of e)yield i}}async send(t,e){this._includeRun(e)&&await this.writer.write(t)}async sendEndEvent(t,e){const r=this.tappedPromises.get(t.run_id);r!==void 0?r.then(()=>{this.send(t,e)}):await this.send(t,e)}async onLLMStart(t){const e=sn(t),r=t.inputs.messages!==void 0?"chat_model":"llm",n={tags:t.tags??[],metadata:t.extra?.metadata??{},name:e,runType:r,inputs:t.inputs};this.runInfoMap.set(t.id,n);const a=`on_${r}_start`;await this.send({event:a,data:{input:t.inputs},name:e,tags:t.tags??[],run_id:t.id,metadata:t.extra?.metadata??{}},n)}async onLLMNewToken(t,e,r){const n=this.runInfoMap.get(t.id);let a,s;if(n===void 0)throw new Error(`onLLMNewToken: Run ID ${t.id} not found in run map.`);if(this.runInfoMap.size!==1){if(n.runType==="chat_model")s="on_chat_model_stream",r?.chunk===void 0?a=new Yt({content:e,id:`run-${t.id}`}):a=r.chunk.message;else if(n.runType==="llm")s="on_llm_stream",r?.chunk===void 0?a=new Br({text:e}):a=r.chunk;else throw new Error(`Unexpected run type ${n.runType}`);await this.send({event:s,data:{chunk:a},run_id:t.id,name:n.name,tags:n.tags,metadata:n.metadata},n)}}async onLLMEnd(t){const e=this.runInfoMap.get(t.id);this.runInfoMap.delete(t.id);let r;if(e===void 0)throw new Error(`onLLMEnd: Run ID ${t.id} not found in run map.`);const n=t.outputs?.generations;let a;if(e.runType==="chat_model"){for(const s of n??[]){if(a!==void 0)break;a=s[0]?.message}r="on_chat_model_end"}else if(e.runType==="llm")a={generations:n?.map(s=>s.map(i=>({text:i.text,generationInfo:i.generationInfo}))),llmOutput:t.outputs?.llmOutput??{}},r="on_llm_end";else throw new Error(`onLLMEnd: Unexpected run type: ${e.runType}`);await this.sendEndEvent({event:r,data:{output:a,input:e.inputs},run_id:t.id,name:e.name,tags:e.tags,metadata:e.metadata},e)}async onChainStart(t){const e=sn(t),r=t.run_type??"chain",n={tags:t.tags??[],metadata:t.extra?.metadata??{},name:e,runType:t.run_type};let a={};t.inputs.input===""&&Object.keys(t.inputs).length===1?(a={},n.inputs={}):t.inputs.input!==void 0?(a.input=t.inputs.input,n.inputs=t.inputs.input):(a.input=t.inputs,n.inputs=t.inputs),this.runInfoMap.set(t.id,n),await this.send({event:`on_${r}_start`,data:a,name:e,tags:t.tags??[],run_id:t.id,metadata:t.extra?.metadata??{}},n)}async onChainEnd(t){const e=this.runInfoMap.get(t.id);if(this.runInfoMap.delete(t.id),e===void 0)throw new Error(`onChainEnd: Run ID ${t.id} not found in run map.`);const r=`on_${t.run_type}_end`,n=t.inputs??e.inputs??{},s={output:t.outputs?.output??t.outputs,input:n};n.input&&Object.keys(n).length===1&&(s.input=n.input,e.inputs=n.input),await this.sendEndEvent({event:r,data:s,run_id:t.id,name:e.name,tags:e.tags,metadata:e.metadata??{}},e)}async onToolStart(t){const e=sn(t),r={tags:t.tags??[],metadata:t.extra?.metadata??{},name:e,runType:"tool",inputs:t.inputs??{}};this.runInfoMap.set(t.id,r),await this.send({event:"on_tool_start",data:{input:t.inputs??{}},name:e,run_id:t.id,tags:t.tags??[],metadata:t.extra?.metadata??{}},r)}async onToolEnd(t){const e=this.runInfoMap.get(t.id);if(this.runInfoMap.delete(t.id),e===void 0)throw new Error(`onToolEnd: Run ID ${t.id} not found in run map.`);if(e.inputs===void 0)throw new Error(`onToolEnd: Run ID ${t.id} is a tool call, and is expected to have traced inputs.`);const r=t.outputs?.output===void 0?t.outputs:t.outputs.output;await this.sendEndEvent({event:"on_tool_end",data:{output:r,input:e.inputs},run_id:t.id,name:e.name,tags:e.tags,metadata:e.metadata},e)}async onRetrieverStart(t){const e=sn(t),n={tags:t.tags??[],metadata:t.extra?.metadata??{},name:e,runType:"retriever",inputs:{query:t.inputs.query}};this.runInfoMap.set(t.id,n),await this.send({event:"on_retriever_start",data:{input:{query:t.inputs.query}},name:e,tags:t.tags??[],run_id:t.id,metadata:t.extra?.metadata??{}},n)}async onRetrieverEnd(t){const e=this.runInfoMap.get(t.id);if(this.runInfoMap.delete(t.id),e===void 0)throw new Error(`onRetrieverEnd: Run ID ${t.id} not found in run map.`);await this.sendEndEvent({event:"on_retriever_end",data:{output:t.outputs?.documents??t.outputs,input:e.inputs},run_id:t.id,name:e.name,tags:e.tags,metadata:e.metadata},e)}async handleCustomEvent(t,e,r){const n=this.runInfoMap.get(r);if(n===void 0)throw new Error(`handleCustomEvent: Run ID ${r} not found in run map.`);await this.send({event:"on_custom_event",run_id:r,name:t,tags:n.tags,metadata:n.metadata,data:e},n)}async finish(){const t=[...this.tappedPromises.values()];Promise.all(t).finally(()=>{this.writer.close()})}},wm={};pe(wm,{AsyncCaller:()=>Fn});const bm=[400,401,402,403,404,405,406,407,409],Em=t=>{if(t.message.startsWith("Cancel")||t.message.startsWith("AbortError")||t.name==="AbortError"||t?.code==="ECONNABORTED")throw t;const e=t?.response?.status??t?.status;if(e&&bm.includes(+e))throw t;if(t?.error?.code==="insufficient_quota"){const r=new Error(t?.message);throw r.name="InsufficientQuotaError",r}};var Fn=class{maxConcurrency;maxRetries;onFailedAttempt;queue;constructor(t){this.maxConcurrency=t.maxConcurrency??1/0,this.maxRetries=t.maxRetries??6,this.onFailedAttempt=t.onFailedAttempt??Em;const e="default"in Tt?Tt.default:Tt;this.queue=new e({concurrency:this.maxConcurrency})}call(t,...e){return this.queue.add(()=>vn(()=>t(...e).catch(r=>{throw r instanceof Error?r:new Error(r)}),{onFailedAttempt:this.onFailedAttempt,retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0})}callWithOptions(t,e,...r){if(t.signal){let n;return Promise.race([this.call(e,...r),new Promise((a,s)=>{n=()=>{s(En(t.signal))},t.signal?.addEventListener("abort",n)})]).finally(()=>{t.signal&&n&&t.signal.removeEventListener("abort",n)})}return this.call(e,...r)}fetch(...t){return this.call(()=>fetch(...t).then(e=>e.ok?e:Promise.reject(e)))}},Wu=class extends vr{name="RootListenersTracer";rootId;config;argOnStart;argOnEnd;argOnError;constructor({config:t,onStart:e,onEnd:r,onError:n}){super({_awaitHandler:!0}),this.config=t,this.argOnStart=e,this.argOnEnd=r,this.argOnError=n}persistRun(t){return Promise.resolve()}async onRunCreate(t){this.rootId||(this.rootId=t.id,this.argOnStart&&await this.argOnStart(t,this.config))}async onRunUpdate(t){t.id===this.rootId&&(t.error?this.argOnError&&await this.argOnError(t,this.config):this.argOnEnd&&await this.argOnEnd(t,this.config))}};function _i(t){return t?t.lc_runnable:!1}var Tm=class{includeNames;includeTypes;includeTags;excludeNames;excludeTypes;excludeTags;constructor(t){this.includeNames=t.includeNames,this.includeTypes=t.includeTypes,this.includeTags=t.includeTags,this.excludeNames=t.excludeNames,this.excludeTypes=t.excludeTypes,this.excludeTags=t.excludeTags}includeEvent(t,e){let r=this.includeNames===void 0&&this.includeTypes===void 0&&this.includeTags===void 0;const n=t.tags??[];return this.includeNames!==void 0&&(r=r||this.includeNames.includes(t.name)),this.includeTypes!==void 0&&(r=r||this.includeTypes.includes(e)),this.includeTags!==void 0&&(r=r||n.some(a=>this.includeTags?.includes(a))),this.excludeNames!==void 0&&(r=r&&!this.excludeNames.includes(t.name)),this.excludeTypes!==void 0&&(r=r&&!this.excludeTypes.includes(e)),this.excludeTags!==void 0&&(r=r&&n.every(a=>!this.excludeTags?.includes(a))),r}};function Ie(t){if(typeof t!="object"||t===null)return!1;const e=t;if(!("_zod"in e))return!1;const r=e._zod;return typeof r=="object"&&r!==null&&"def"in r}function Re(t){if(typeof t!="object"||t===null)return!1;const e=t;if(!("_def"in e)||"_zod"in e)return!1;const r=e._def;return typeof r=="object"&&r!=null&&"typeName"in r}function Sm(t){return Ie(t)&&console.warn("[WARNING] Attempting to use Zod 4 schema in a context where Zod 3 schema is expected. This may cause unexpected behavior."),Re(t)}function Vr(t){return!t||typeof t!="object"||Array.isArray(t)?!1:!!(Ie(t)||Re(t))}function Ju(t){return typeof t=="object"&&t!==null&&"_def"in t&&typeof t._def=="object"&&t._def!==null&&"typeName"in t._def&&t._def.typeName==="ZodLiteral"}function Ku(t){return Ie(t)?typeof t=="object"&&t!==null&&"_zod"in t&&typeof t._zod=="object"&&t._zod!==null&&"def"in t._zod&&typeof t._zod.def=="object"&&t._zod.def!==null&&"type"in t._zod.def&&t._zod.def.type==="literal":!1}function Im(t){return!!(Ju(t)||Ku(t))}async function xm(t,e){if(Ie(t))try{return{success:!0,data:await Pc(t,e)}}catch(r){return{success:!1,error:r}}if(Re(t))return await t.safeParseAsync(e);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}async function yi(t,e){if(Ie(t))return await Pc(t,e);if(Re(t))return await t.parseAsync(e);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function Am(t,e){if(Ie(t))try{return{success:!0,data:Hs(t,e)}}catch(r){return{success:!1,error:r}}if(Re(t))return t.safeParse(e);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function Om(t,e){if(Ie(t))return Hs(t,e);if(Re(t))return t.parse(e);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function vi(t){if(Ie(t))return We.get(t)?.description;if(Re(t)||"description"in t&&typeof t.description=="string")return t.description}function km(t){if(!Vr(t))return!1;if(Re(t)){const e=t._def;if(e.typeName==="ZodObject"){const r=t;return!r.shape||Object.keys(r.shape).length===0}if(e.typeName==="ZodRecord")return!0}if(Ie(t)){const e=t._zod.def;if(e.type==="object"){const r=t;return!r.shape||Object.keys(r.shape).length===0}if(e.type==="record")return!0}return typeof t=="object"&&t!==null&&!("shape"in t)}function Yu(t){return Vr(t)?Re(t)?t._def.typeName==="ZodString":Ie(t)?t._zod.def.type==="string":!1:!1}function wi(t){return typeof t=="object"&&t!==null&&"_def"in t&&typeof t._def=="object"&&t._def!==null&&"typeName"in t._def&&t._def.typeName==="ZodObject"}function gt(t){return Ie(t)?typeof t=="object"&&t!==null&&"_zod"in t&&typeof t._zod=="object"&&t._zod!==null&&"def"in t._zod&&typeof t._zod.def=="object"&&t._zod.def!==null&&"type"in t._zod.def&&t._zod.def.type==="object":!1}function Bn(t){return Ie(t)?typeof t=="object"&&t!==null&&"_zod"in t&&typeof t._zod=="object"&&t._zod!==null&&"def"in t._zod&&typeof t._zod.def=="object"&&t._zod.def!==null&&"type"in t._zod.def&&t._zod.def.type==="array":!1}function Rm(t){return!!(wi(t)||gt(t))}function js(t){if(Re(t))return t.shape;if(Ie(t))return t._zod.def.shape;throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function Cm(t,e){if(Re(t))return t.extend(e);if(Ie(t))return Fl(t,e);throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function Nm(t){if(Re(t))return t.partial();if(Ie(t))return Bl(Mc,t,void 0);throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function In(t,e=!1){if(Re(t))return t.strict();if(gt(t)){const r=t._zod.def.shape;if(e)for(const[s,i]of Object.entries(t._zod.def.shape)){if(gt(i)){const c=In(i,e);r[s]=c}else if(Bn(i)){let c=i._zod.def.element;gt(c)&&(c=In(c,e)),r[s]=Zt(i,{...i._zod.def,element:c})}else r[s]=i;const o=We.get(i);o&&We.add(r[s],o)}const n=Zt(t,{...t._zod.def,shape:r,catchall:Dl(Ul)}),a=We.get(t);return a&&We.add(n,a),n}throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function Ds(t,e=!1){if(wi(t))return t.passthrough();if(gt(t)){const r=t._zod.def.shape;if(e)for(const[s,i]of Object.entries(t._zod.def.shape)){if(gt(i)){const c=Ds(i,e);r[s]=c}else if(Bn(i)){let c=i._zod.def.element;gt(c)&&(c=Ds(c,e)),r[s]=Zt(i,{...i._zod.def,element:c})}else r[s]=i;const o=We.get(i);o&&We.add(r[s],o)}const n=Zt(t,{...t._zod.def,shape:r,catchall:zl(ql)}),a=We.get(t);return a&&We.add(n,a),n}throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function $m(t){if(Re(t))try{const e=t.parse(void 0);return()=>e}catch{return}if(Ie(t))try{const e=Hs(t,void 0);return()=>e}catch{return}}function Pm(t){return Re(t)&&"typeName"in t._def&&t._def.typeName==="ZodEffects"}function Mm(t){return Ie(t)&&t._zod.def.type==="pipe"}function sr(t,e=!1){if(Re(t))return Pm(t)?sr(t._def.schema,e):t;if(Ie(t)){let r=t;if(Mm(t)&&(r=sr(t._zod.def.in,e)),e){if(gt(r)){const a=r._zod.def.shape;for(const[s,i]of Object.entries(r._zod.def.shape))a[s]=sr(i,e);r=Zt(r,{...r._zod.def,shape:a})}else if(Bn(r)){const a=sr(r._zod.def.element,e);r=Zt(r,{...r._zod.def,element:a})}}const n=We.get(t);return n&&We.add(r,n),r}throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function Lm(t,e){if(Re(t)){const r=js(t),n={};for(const[a,s]of Object.entries(r))e(a,s)?n[a]=s.optional():n[a]=s;return t.extend(n)}if(Ie(t)){const r=js(t),n={...t._zod.def.shape};for(const[i,o]of Object.entries(r))e(i,o)&&(n[i]=new Mc({type:"optional",innerType:o}));const a=Zt(t,{...t._zod.def,shape:n}),s=We.get(t);return s&&We.add(a,s),a}throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function as(t){return t.replace(/[^a-zA-Z-_0-9]/g,"_")}const jm=["*","_","`"];function Dm(t){let e="";for(const[r,n]of Object.entries(t))e+=` classDef ${r} ${n};
|
|
55
|
-
`;return e}function Um(t,e,r){const{firstNode:n,lastNode:a,nodeColors:s,withStyles:i=!0,curveStyle:o="linear",wrapLabelNWords:c=9}=r??{};let u=i?`%%{init: {'flowchart': {'curve': '${o}'}}}%%
|
|
56
|
-
graph TD;
|
|
57
|
-
`:`graph TD;
|
|
58
|
-
`;if(i){const p="default",g={[p]:"{0}({1})"};n!==void 0&&(g[n]="{0}([{1}]):::first"),a!==void 0&&(g[a]="{0}([{1}]):::last");for(const[y,v]of Object.entries(t)){const b=v.name.split(":").pop()??"";let E=jm.some(C=>b.startsWith(C)&&b.endsWith(C))?`<p>${b}</p>`:b;Object.keys(v.metadata??{}).length&&(E+=`<hr/><small><em>${Object.entries(v.metadata??{}).map(([C,F])=>`${C} = ${F}`).join(`
|
|
59
|
-
`)}</em></small>`);const k=(g[y]??g[p]).replace("{0}",as(y)).replace("{1}",E);u+=` ${k}
|
|
60
|
-
`}}const l={};for(const p of e){const g=p.source.split(":"),y=p.target.split(":"),v=g.filter((b,S)=>b===y[S]).join(":");l[v]||(l[v]=[]),l[v].push(p)}const d=new Set;function h(p,g){const y=p.length===1&&p[0].source===p[0].target;if(g&&!y){const v=g.split(":").pop();if(d.has(v))throw new Error(`Found duplicate subgraph '${v}' -- this likely means that you're reusing a subgraph node with the same name. Please adjust your graph to have subgraph nodes with unique names.`);d.add(v),u+=` subgraph ${v}
|
|
61
|
-
`}for(const v of p){const{source:b,target:S,data:E,conditional:k}=v;let C="";if(E!==void 0){let F=E;const W=F.split(" ");W.length>c&&(F=Array.from({length:Math.ceil(W.length/c)},(_,ge)=>W.slice(ge*c,(ge+1)*c).join(" ")).join(" <br> ")),C=k?` -. ${F} .-> `:` -- ${F} --> `}else C=k?" -.-> ":" --> ";u+=` ${as(b)}${C}${as(S)};
|
|
62
|
-
`}for(const v in l)v.startsWith(`${g}:`)&&v!==g&&h(l[v],v);g&&!y&&(u+=` end
|
|
63
|
-
`)}h(l[""]??[],"");for(const p in l)!p.includes(":")&&p!==""&&h(l[p],p);return i&&(u+=Dm(s??{})),u}async function Fm(t,e){let r=e?.backgroundColor??"white";const n=e?.imageType??"png",a=btoa(t);r!==void 0&&(/^#(?:[0-9a-fA-F]{3}){1,2}$/.test(r)||(r=`!${r}`));const s=`https://mermaid.ink/img/${a}?bgColor=${r}&type=${n}`,i=await fetch(s);if(!i.ok)throw new Error(["Failed to render the graph using the Mermaid.INK API.",`Status code: ${i.status}`,`Status text: ${i.statusText}`].join(`
|
|
64
|
-
`));return await i.blob()}const Bm=Symbol("Let zodToJsonSchema decide on which parser to use"),zm={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},qm=t=>({...zm,...t}),Gm=t=>{const e=qm(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([n,a])=>[a._def,{def:a._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}},Xu=(t,e)=>{let r=0;for(;r<t.length&&r<e.length&&t[r]===e[r];r++);return[(t.length-r).toString(),...e.slice(r)].join("/")};function Ze(t){if(t.target!=="openAi")return{};const e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?Xu(e,t.currentPath):e.join("/")}}function Qu(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function fe(t,e,r,n,a){t[e]=r,Qu(t,e,n,a)}function Hm(t,e){const r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==x.ZodAny&&(r.items=he(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&fe(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&fe(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(fe(r,"minItems",t.exactLength.value,t.exactLength.message,e),fe(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}function Zm(t,e){const r={type:"integer",format:"int64"};if(!t.checks)return r;for(const n of t.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?fe(r,"minimum",n.value,n.message,e):fe(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),fe(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?fe(r,"maximum",n.value,n.message,e):fe(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),fe(r,"maximum",n.value,n.message,e));break;case"multipleOf":fe(r,"multipleOf",n.value,n.message,e);break}return r}function Vm(){return{type:"boolean"}}function el(t,e){return he(t.type._def,e)}const Wm=(t,e)=>he(t.innerType._def,e);function tl(t,e,r){const n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map(a=>tl(t,e,a))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return Jm(t,e)}}const Jm=(t,e)=>{const r={type:"integer",format:"unix-time"};if(e.target==="openApi3")return r;for(const n of t.checks)switch(n.kind){case"min":fe(r,"minimum",n.value,n.message,e);break;case"max":fe(r,"maximum",n.value,n.message,e);break}return r};function Km(t,e){return{...he(t.innerType._def,e),default:t.defaultValue()}}function Ym(t,e){return e.effectStrategy==="input"?he(t.schema._def,e):Ze(e)}function Xm(t){return{type:"string",enum:Array.from(t.values)}}const Qm=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function eg(t,e){const r=[he(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),he(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(s=>!!s);let n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0;const a=[];return r.forEach(s=>{if(Qm(s))a.push(...s.allOf),s.unevaluatedProperties===void 0&&(n=void 0);else{let i=s;if("additionalProperties"in s&&s.additionalProperties===!1){const{additionalProperties:o,...c}=s;i=c}else n=void 0;a.push(i)}}),a.length?{allOf:a,...n}:void 0}function tg(t,e){const r=typeof t.value;return r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:r==="bigint"?"integer":r,enum:[t.value]}:{type:r==="bigint"?"integer":r,const:t.value}}let ss;const et={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(ss===void 0&&(ss=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),ss),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function rl(t,e){const r={type:"string"};if(t.checks)for(const n of t.checks)switch(n.kind){case"min":fe(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":fe(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"email":switch(e.emailStrategy){case"format:email":tt(r,"email",n.message,e);break;case"format:idn-email":tt(r,"idn-email",n.message,e);break;case"pattern:zod":je(r,et.email,n.message,e);break}break;case"url":tt(r,"uri",n.message,e);break;case"uuid":tt(r,"uuid",n.message,e);break;case"regex":je(r,n.regex,n.message,e);break;case"cuid":je(r,et.cuid,n.message,e);break;case"cuid2":je(r,et.cuid2,n.message,e);break;case"startsWith":je(r,RegExp(`^${is(n.value,e)}`),n.message,e);break;case"endsWith":je(r,RegExp(`${is(n.value,e)}$`),n.message,e);break;case"datetime":tt(r,"date-time",n.message,e);break;case"date":tt(r,"date",n.message,e);break;case"time":tt(r,"time",n.message,e);break;case"duration":tt(r,"duration",n.message,e);break;case"length":fe(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),fe(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":je(r,RegExp(is(n.value,e)),n.message,e);break;case"ip":n.version!=="v6"&&tt(r,"ipv4",n.message,e),n.version!=="v4"&&tt(r,"ipv6",n.message,e);break;case"base64url":je(r,et.base64url,n.message,e);break;case"jwt":je(r,et.jwt,n.message,e);break;case"cidr":n.version!=="v6"&&je(r,et.ipv4Cidr,n.message,e),n.version!=="v4"&&je(r,et.ipv6Cidr,n.message,e);break;case"emoji":je(r,et.emoji(),n.message,e);break;case"ulid":je(r,et.ulid,n.message,e);break;case"base64":switch(e.base64Strategy){case"format:binary":tt(r,"binary",n.message,e);break;case"contentEncoding:base64":fe(r,"contentEncoding","base64",n.message,e);break;case"pattern:zod":je(r,et.base64,n.message,e);break}break;case"nanoid":je(r,et.nanoid,n.message,e);break}return r}function is(t,e){return e.patternStrategy==="escape"?ng(t):t}const rg=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function ng(t){let e="";for(let r=0;r<t.length;r++)rg.has(t[r])||(e+="\\"),e+=t[r];return e}function tt(t,e,r,n){t.format||t.anyOf?.some(a=>a.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&n.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...r&&n.errorMessages&&{errorMessage:{format:r}}})):fe(t,"format",e,r,n)}function je(t,e,r,n){t.pattern||t.allOf?.some(a=>a.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&n.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:Tc(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):fe(t,"pattern",Tc(e,n),r,n)}function Tc(t,e){if(!e.applyRegexFlags||!t.flags)return t.source;const r={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},n=r.i?t.source.toLowerCase():t.source;let a="",s=!1,i=!1,o=!1;for(let c=0;c<n.length;c++){if(s){a+=n[c],s=!1;continue}if(r.i){if(i){if(n[c].match(/[a-z]/)){o?(a+=n[c],a+=`${n[c-2]}-${n[c]}`.toUpperCase(),o=!1):n[c+1]==="-"&&n[c+2]?.match(/[a-z]/)?(a+=n[c],o=!0):a+=`${n[c]}${n[c].toUpperCase()}`;continue}}else if(n[c].match(/[a-z]/)){a+=`[${n[c]}${n[c].toUpperCase()}]`;continue}}if(r.m){if(n[c]==="^"){a+=`(^|(?<=[\r
|
|
65
|
-
]))`;continue}else if(n[c]==="$"){a+=`($|(?=[\r
|
|
66
|
-
]))`;continue}}if(r.s&&n[c]==="."){a+=i?`${n[c]}\r
|
|
67
|
-
`:`[${n[c]}\r
|
|
68
|
-
]`;continue}a+=n[c],n[c]==="\\"?s=!0:i&&n[c]==="]"?i=!1:!i&&n[c]==="["&&(i=!0)}try{new RegExp(a)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return a}function nl(t,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&t.keyType?._def.typeName===x.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,a)=>({...n,[a]:he(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",a]})??Ze(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};const r={type:"object",additionalProperties:he(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===x.ZodString&&t.keyType._def.checks?.length){const{type:n,...a}=rl(t.keyType._def,e);return{...r,propertyNames:a}}else{if(t.keyType?._def.typeName===x.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===x.ZodBranded&&t.keyType._def.type._def.typeName===x.ZodString&&t.keyType._def.type._def.checks?.length){const{type:n,...a}=el(t.keyType._def,e);return{...r,propertyNames:a}}}return r}function ag(t,e){if(e.mapStrategy==="record")return nl(t,e);const r=he(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||Ze(e),n=he(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||Ze(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function sg(t){const e=t.values,n=Object.keys(t.values).filter(s=>typeof e[e[s]]!="number").map(s=>e[s]),a=Array.from(new Set(n.map(s=>typeof s)));return{type:a.length===1?a[0]==="string"?"string":"number":["string","number"],enum:n}}function ig(t){return t.target==="openAi"?void 0:{not:Ze({...t,currentPath:[...t.currentPath,"not"]})}}function og(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}const xn={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function cg(t,e){if(e.target==="openApi3")return Sc(t,e);const r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in xn&&(!n._def.checks||!n._def.checks.length))){const n=r.reduce((a,s)=>{const i=xn[s._def.typeName];return i&&!a.includes(i)?[...a,i]:a},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){const n=r.reduce((a,s)=>{const i=typeof s._def.value;switch(i){case"string":case"number":case"boolean":return[...a,i];case"bigint":return[...a,"integer"];case"object":return s._def.value===null?[...a,"null"]:a;case"symbol":case"undefined":case"function":default:return a}},[]);if(n.length===r.length){const a=n.filter((s,i,o)=>o.indexOf(s)===i);return{type:a.length>1?a:a[0],enum:r.reduce((s,i)=>s.includes(i._def.value)?s:[...s,i._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,a)=>[...n,...a._def.values.filter(s=>!n.includes(s))],[])};return Sc(t,e)}const Sc=(t,e)=>{const r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,a)=>he(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${a}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function ug(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"?{type:xn[t.innerType._def.typeName],nullable:!0}:{type:[xn[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){const n=he(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}const r=he(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function lg(t,e){const r={type:"number"};if(!t.checks)return r;for(const n of t.checks)switch(n.kind){case"int":r.type="integer",Qu(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?fe(r,"minimum",n.value,n.message,e):fe(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),fe(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?fe(r,"maximum",n.value,n.message,e):fe(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),fe(r,"maximum",n.value,n.message,e));break;case"multipleOf":fe(r,"multipleOf",n.value,n.message,e);break}return r}function dg(t,e){const r=e.target==="openAi",n={type:"object",properties:{}},a=[],s=t.shape();for(const o in s){let c=s[o];if(c===void 0||c._def===void 0)continue;let u=fg(c);u&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),u=!1);const l=he(c._def,{...e,currentPath:[...e.currentPath,"properties",o],propertyPath:[...e.currentPath,"properties",o]});l!==void 0&&(n.properties[o]=l,u||a.push(o))}a.length&&(n.required=a);const i=hg(t,e);return i!==void 0&&(n.additionalProperties=i),n}function hg(t,e){if(t.catchall._def.typeName!=="ZodNever")return he(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function fg(t){try{return t.isOptional()}catch{return!0}}const pg=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return he(t.innerType._def,e);const r=he(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:Ze(e)},r]}:Ze(e)},mg=(t,e)=>{if(e.pipeStrategy==="input")return he(t.in._def,e);if(e.pipeStrategy==="output")return he(t.out._def,e);const r=he(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=he(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(a=>a!==void 0)}};function gg(t,e){return he(t.type._def,e)}function _g(t,e){const n={type:"array",uniqueItems:!0,items:he(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&fe(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&fe(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}function yg(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>he(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:he(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>he(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function vg(t){return{not:Ze(t)}}function wg(t){return Ze(t)}const bg=(t,e)=>he(t.innerType._def,e),Eg=(t,e,r)=>{switch(e){case x.ZodString:return rl(t,r);case x.ZodNumber:return lg(t,r);case x.ZodObject:return dg(t,r);case x.ZodBigInt:return Zm(t,r);case x.ZodBoolean:return Vm();case x.ZodDate:return tl(t,r);case x.ZodUndefined:return vg(r);case x.ZodNull:return og(r);case x.ZodArray:return Hm(t,r);case x.ZodUnion:case x.ZodDiscriminatedUnion:return cg(t,r);case x.ZodIntersection:return eg(t,r);case x.ZodTuple:return yg(t,r);case x.ZodRecord:return nl(t,r);case x.ZodLiteral:return tg(t,r);case x.ZodEnum:return Xm(t);case x.ZodNativeEnum:return sg(t);case x.ZodNullable:return ug(t,r);case x.ZodOptional:return pg(t,r);case x.ZodMap:return ag(t,r);case x.ZodSet:return _g(t,r);case x.ZodLazy:return()=>t.getter()._def;case x.ZodPromise:return gg(t,r);case x.ZodNaN:case x.ZodNever:return ig(r);case x.ZodEffects:return Ym(t,r);case x.ZodAny:return Ze(r);case x.ZodUnknown:return wg(r);case x.ZodDefault:return Km(t,r);case x.ZodBranded:return el(t,r);case x.ZodReadonly:return bg(t,r);case x.ZodCatch:return Wm(t,r);case x.ZodPipeline:return mg(t,r);case x.ZodFunction:case x.ZodVoid:case x.ZodSymbol:return;default:return(n=>{})()}};function he(t,e,r=!1){const n=e.seen.get(t);if(e.override){const o=e.override?.(t,e,n,r);if(o!==Bm)return o}if(n&&!r){const o=Tg(n,e);if(o!==void 0)return o}const a={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,a);const s=Eg(t,t.typeName,e),i=typeof s=="function"?he(s(),e):s;if(i&&Sg(t,e,i),e.postProcess){const o=e.postProcess(i,t,e);return a.jsonSchema=i,o}return a.jsonSchema=i,i}const Tg=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:Xu(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((r,n)=>e.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),Ze(e)):e.$refStrategy==="seen"?Ze(e):void 0}},Sg=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r),Ig=(t,e)=>{const r=Gm(e);let n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((o,[c,u])=>({...o,[c]:he(u._def,{...r,currentPath:[...r.basePath,r.definitionPath,c]},!0)??Ze(r)}),{}):void 0;const a=typeof e=="string"?e:e?.name,s=he(t._def,r,!1)??Ze(r);r.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[r.openAiAnyTypeName]||(n[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));const i=a===void 0?n?{...s,[r.definitionPath]:n}:s:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,a].join("/"),[r.definitionPath]:{...n,[a]:s}};return r.target==="jsonSchema7"?i.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(i.$schema="https://json-schema.org/draft/2019-09/schema#"),r.target==="openAi"&&("anyOf"in i||"oneOf"in i||"allOf"in i||"type"in i&&Array.isArray(i.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),i};function Gt(t,e){const r=typeof t;if(r!==typeof e)return!1;if(Array.isArray(t)){if(!Array.isArray(e))return!1;const n=t.length;if(n!==e.length)return!1;for(let a=0;a<n;a++)if(!Gt(t[a],e[a]))return!1;return!0}if(r==="object"){if(!t||!e)return t===e;const n=Object.keys(t),a=Object.keys(e);if(n.length!==a.length)return!1;for(const i of n)if(!Gt(t[i],e[i]))return!1;return!0}return t===e}function nt(t){return encodeURI(xg(t))}function xg(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}const Ag={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},Og={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},kg={id:!0,$id:!0,$ref:!0,$schema:!0,$anchor:!0,$vocabulary:!0,$comment:!0,default:!0,enum:!0,const:!0,required:!0,type:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};let Rg=typeof self<"u"&&self.location&&self.location.origin!=="null"?new URL(self.location.origin+self.location.pathname+location.search):new URL("https://github.com/cfworker");function Ct(t,e=Object.create(null),r=Rg,n=""){if(t&&typeof t=="object"&&!Array.isArray(t)){const s=t.$id||t.id;if(s){const i=new URL(s,r.href);i.hash.length>1?e[i.href]=t:(i.hash="",n===""?r=i:Ct(t,e,r))}}else if(t!==!0&&t!==!1)return e;const a=r.href+(n?"#"+n:"");if(e[a]!==void 0)throw new Error(`Duplicate schema URI "${a}".`);if(e[a]=t,t===!0||t===!1)return e;if(t.__absolute_uri__===void 0&&Object.defineProperty(t,"__absolute_uri__",{enumerable:!1,value:a}),t.$ref&&t.__absolute_ref__===void 0){const s=new URL(t.$ref,r.href);s.hash=s.hash,Object.defineProperty(t,"__absolute_ref__",{enumerable:!1,value:s.href})}if(t.$recursiveRef&&t.__absolute_recursive_ref__===void 0){const s=new URL(t.$recursiveRef,r.href);s.hash=s.hash,Object.defineProperty(t,"__absolute_recursive_ref__",{enumerable:!1,value:s.href})}if(t.$anchor){const s=new URL("#"+t.$anchor,r.href);e[s.href]=t}for(let s in t){if(kg[s])continue;const i=`${n}/${nt(s)}`,o=t[s];if(Array.isArray(o)){if(Ag[s]){const c=o.length;for(let u=0;u<c;u++)Ct(o[u],e,r,`${i}/${u}`)}}else if(Og[s])for(let c in o)Ct(o[c],e,r,`${i}/${nt(c)}`);else Ct(o,e,r,i)}return e}const Cg=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,Ng=[0,31,28,31,30,31,30,31,31,30,31,30,31],$g=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,Pg=/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,Mg=/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,Lg=/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,jg=/^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,Dg=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,Ug=/^(?:\/(?:[^~/]|~0|~1)*)*$/,Fg=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,Bg=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,zg=t=>{if(t[0]==='"')return!1;const[e,r,...n]=t.split("@");return!e||!r||n.length!==0||e.length>64||r.length>253||e[0]==="."||e.endsWith(".")||e.includes("..")||!/^[a-z0-9.-]+$/i.test(r)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(e)?!1:r.split(".").every(a=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(a))},qg=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,Gg=/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,Hg=t=>t.length>1&&t.length<80&&(/^P\d+([.,]\d+)?W$/.test(t)||/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(t)&&/^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(t));function ht(t){return t.test.bind(t)}const Ic={date:al,time:sl.bind(void 0,!1),"date-time":Wg,duration:Hg,uri:Yg,"uri-reference":ht(Mg),"uri-template":ht(Lg),url:ht(jg),email:zg,hostname:ht(Pg),ipv4:ht(qg),ipv6:ht(Gg),regex:Qg,uuid:ht(Dg),"json-pointer":ht(Ug),"json-pointer-uri-fragment":ht(Fg),"relative-json-pointer":ht(Bg)};function Zg(t){return t%4===0&&(t%100!==0||t%400===0)}function al(t){const e=t.match(Cg);if(!e)return!1;const r=+e[1],n=+e[2],a=+e[3];return n>=1&&n<=12&&a>=1&&a<=(n==2&&Zg(r)?29:Ng[n])}function sl(t,e){const r=e.match($g);if(!r)return!1;const n=+r[1],a=+r[2],s=+r[3],i=!!r[5];return(n<=23&&a<=59&&s<=59||n==23&&a==59&&s==60)&&(!t||i)}const Vg=/t|\s/i;function Wg(t){const e=t.split(Vg);return e.length==2&&al(e[0])&&sl(!0,e[1])}const Jg=/\/|:/,Kg=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function Yg(t){return Jg.test(t)&&Kg.test(t)}const Xg=/[^\\]\\Z/;function Qg(t){if(Xg.test(t))return!1;try{return new RegExp(t,"u"),!0}catch{return!1}}function e_(t){let e=0,r=t.length,n=0,a;for(;n<r;)e++,a=t.charCodeAt(n++),a>=55296&&a<=56319&&n<r&&(a=t.charCodeAt(n),(a&64512)==56320&&n++);return e}function ve(t,e,r="2019-09",n=Ct(e),a=!0,s=null,i="#",o="#",c=Object.create(null)){if(e===!0)return{valid:!0,errors:[]};if(e===!1)return{valid:!1,errors:[{instanceLocation:i,keyword:"false",keywordLocation:i,error:"False boolean schema."}]};const u=typeof t;let l;switch(u){case"boolean":case"number":case"string":l=u;break;case"object":t===null?l="null":Array.isArray(t)?l="array":l="object";break;default:throw new Error(`Instances of "${u}" type are not supported.`)}const{$ref:d,$recursiveRef:h,$recursiveAnchor:p,type:g,const:y,enum:v,required:b,not:S,anyOf:E,allOf:k,oneOf:C,if:F,then:W,else:_,format:ge,properties:ye,patternProperties:oe,additionalProperties:Ne,unevaluatedProperties:vt,minProperties:R,maxProperties:A,propertyNames:O,dependentRequired:B,dependentSchemas:q,dependencies:U,prefixItems:V,items:ae,additionalItems:ee,unevaluatedItems:le,contains:Te,minContains:ce,maxContains:m,minItems:f,maxItems:T,uniqueItems:w,minimum:se,maximum:me,exclusiveMinimum:_e,exclusiveMaximum:xe,multipleOf:$e,minLength:Qe,maxLength:be,pattern:Ke,__absolute_ref__:Qt,__absolute_recursive_ref__:Kr}=e,P=[];if(p===!0&&s===null&&(s=e),h==="#"){const J=s===null?n[Kr]:s,H=`${o}/$recursiveRef`,Q=ve(t,s===null?e:s,r,n,a,J,i,H,c);Q.valid||P.push({instanceLocation:i,keyword:"$recursiveRef",keywordLocation:H,error:"A subschema had errors."},...Q.errors)}if(d!==void 0){const H=n[Qt||d];if(H===void 0){let N=`Unresolved $ref "${d}".`;throw Qt&&Qt!==d&&(N+=` Absolute URI "${Qt}".`),N+=`
|
|
69
|
-
Known schemas:
|
|
70
|
-
- ${Object.keys(n).join(`
|
|
71
|
-
- `)}`,new Error(N)}const Q=`${o}/$ref`,j=ve(t,H,r,n,a,s,i,Q,c);if(j.valid||P.push({instanceLocation:i,keyword:"$ref",keywordLocation:Q,error:"A subschema had errors."},...j.errors),r==="4"||r==="7")return{valid:P.length===0,errors:P}}if(Array.isArray(g)){let J=g.length,H=!1;for(let Q=0;Q<J;Q++)if(l===g[Q]||g[Q]==="integer"&&l==="number"&&t%1===0&&t===t){H=!0;break}H||P.push({instanceLocation:i,keyword:"type",keywordLocation:`${o}/type`,error:`Instance type "${l}" is invalid. Expected "${g.join('", "')}".`})}else g==="integer"?(l!=="number"||t%1||t!==t)&&P.push({instanceLocation:i,keyword:"type",keywordLocation:`${o}/type`,error:`Instance type "${l}" is invalid. Expected "${g}".`}):g!==void 0&&l!==g&&P.push({instanceLocation:i,keyword:"type",keywordLocation:`${o}/type`,error:`Instance type "${l}" is invalid. Expected "${g}".`});if(y!==void 0&&(l==="object"||l==="array"?Gt(t,y)||P.push({instanceLocation:i,keyword:"const",keywordLocation:`${o}/const`,error:`Instance does not match ${JSON.stringify(y)}.`}):t!==y&&P.push({instanceLocation:i,keyword:"const",keywordLocation:`${o}/const`,error:`Instance does not match ${JSON.stringify(y)}.`})),v!==void 0&&(l==="object"||l==="array"?v.some(J=>Gt(t,J))||P.push({instanceLocation:i,keyword:"enum",keywordLocation:`${o}/enum`,error:`Instance does not match any of ${JSON.stringify(v)}.`}):v.some(J=>t===J)||P.push({instanceLocation:i,keyword:"enum",keywordLocation:`${o}/enum`,error:`Instance does not match any of ${JSON.stringify(v)}.`})),S!==void 0){const J=`${o}/not`;ve(t,S,r,n,a,s,i,J).valid&&P.push({instanceLocation:i,keyword:"not",keywordLocation:J,error:'Instance matched "not" schema.'})}let Ft=[];if(E!==void 0){const J=`${o}/anyOf`,H=P.length;let Q=!1;for(let j=0;j<E.length;j++){const N=E[j],Y=Object.create(c),K=ve(t,N,r,n,a,p===!0?s:null,i,`${J}/${j}`,Y);P.push(...K.errors),Q=Q||K.valid,K.valid&&Ft.push(Y)}Q?P.length=H:P.splice(H,0,{instanceLocation:i,keyword:"anyOf",keywordLocation:J,error:"Instance does not match any subschemas."})}if(k!==void 0){const J=`${o}/allOf`,H=P.length;let Q=!0;for(let j=0;j<k.length;j++){const N=k[j],Y=Object.create(c),K=ve(t,N,r,n,a,p===!0?s:null,i,`${J}/${j}`,Y);P.push(...K.errors),Q=Q&&K.valid,K.valid&&Ft.push(Y)}Q?P.length=H:P.splice(H,0,{instanceLocation:i,keyword:"allOf",keywordLocation:J,error:"Instance does not match every subschema."})}if(C!==void 0){const J=`${o}/oneOf`,H=P.length,Q=C.filter((j,N)=>{const Y=Object.create(c),K=ve(t,j,r,n,a,p===!0?s:null,i,`${J}/${N}`,Y);return P.push(...K.errors),K.valid&&Ft.push(Y),K.valid}).length;Q===1?P.length=H:P.splice(H,0,{instanceLocation:i,keyword:"oneOf",keywordLocation:J,error:`Instance does not match exactly one subschema (${Q} matches).`})}if((l==="object"||l==="array")&&Object.assign(c,...Ft),F!==void 0){const J=`${o}/if`;if(ve(t,F,r,n,a,s,i,J,c).valid){if(W!==void 0){const Q=ve(t,W,r,n,a,s,i,`${o}/then`,c);Q.valid||P.push({instanceLocation:i,keyword:"if",keywordLocation:J,error:'Instance does not match "then" schema.'},...Q.errors)}}else if(_!==void 0){const Q=ve(t,_,r,n,a,s,i,`${o}/else`,c);Q.valid||P.push({instanceLocation:i,keyword:"if",keywordLocation:J,error:'Instance does not match "else" schema.'},...Q.errors)}}if(l==="object"){if(b!==void 0)for(const j of b)j in t||P.push({instanceLocation:i,keyword:"required",keywordLocation:`${o}/required`,error:`Instance does not have required property "${j}".`});const J=Object.keys(t);if(R!==void 0&&J.length<R&&P.push({instanceLocation:i,keyword:"minProperties",keywordLocation:`${o}/minProperties`,error:`Instance does not have at least ${R} properties.`}),A!==void 0&&J.length>A&&P.push({instanceLocation:i,keyword:"maxProperties",keywordLocation:`${o}/maxProperties`,error:`Instance does not have at least ${A} properties.`}),O!==void 0){const j=`${o}/propertyNames`;for(const N in t){const Y=`${i}/${nt(N)}`,K=ve(N,O,r,n,a,s,Y,j);K.valid||P.push({instanceLocation:i,keyword:"propertyNames",keywordLocation:j,error:`Property name "${N}" does not match schema.`},...K.errors)}}if(B!==void 0){const j=`${o}/dependantRequired`;for(const N in B)if(N in t){const Y=B[N];for(const K of Y)K in t||P.push({instanceLocation:i,keyword:"dependentRequired",keywordLocation:j,error:`Instance has "${N}" but does not have "${K}".`})}}if(q!==void 0)for(const j in q){const N=`${o}/dependentSchemas`;if(j in t){const Y=ve(t,q[j],r,n,a,s,i,`${N}/${nt(j)}`,c);Y.valid||P.push({instanceLocation:i,keyword:"dependentSchemas",keywordLocation:N,error:`Instance has "${j}" but does not match dependant schema.`},...Y.errors)}}if(U!==void 0){const j=`${o}/dependencies`;for(const N in U)if(N in t){const Y=U[N];if(Array.isArray(Y))for(const K of Y)K in t||P.push({instanceLocation:i,keyword:"dependencies",keywordLocation:j,error:`Instance has "${N}" but does not have "${K}".`});else{const K=ve(t,Y,r,n,a,s,i,`${j}/${nt(N)}`);K.valid||P.push({instanceLocation:i,keyword:"dependencies",keywordLocation:j,error:`Instance has "${N}" but does not match dependant schema.`},...K.errors)}}}const H=Object.create(null);let Q=!1;if(ye!==void 0){const j=`${o}/properties`;for(const N in ye){if(!(N in t))continue;const Y=`${i}/${nt(N)}`,K=ve(t[N],ye[N],r,n,a,s,Y,`${j}/${nt(N)}`);if(K.valid)c[N]=H[N]=!0;else if(Q=a,P.push({instanceLocation:i,keyword:"properties",keywordLocation:j,error:`Property "${N}" does not match schema.`},...K.errors),Q)break}}if(!Q&&oe!==void 0){const j=`${o}/patternProperties`;for(const N in oe){const Y=new RegExp(N,"u"),K=oe[N];for(const Be in t){if(!Y.test(Be))continue;const Ai=`${i}/${nt(Be)}`,Oi=ve(t[Be],K,r,n,a,s,Ai,`${j}/${nt(N)}`);Oi.valid?c[Be]=H[Be]=!0:(Q=a,P.push({instanceLocation:i,keyword:"patternProperties",keywordLocation:j,error:`Property "${Be}" matches pattern "${N}" but does not match associated schema.`},...Oi.errors))}}}if(!Q&&Ne!==void 0){const j=`${o}/additionalProperties`;for(const N in t){if(H[N])continue;const Y=`${i}/${nt(N)}`,K=ve(t[N],Ne,r,n,a,s,Y,j);K.valid?c[N]=!0:(Q=a,P.push({instanceLocation:i,keyword:"additionalProperties",keywordLocation:j,error:`Property "${N}" does not match additional properties schema.`},...K.errors))}}else if(!Q&&vt!==void 0){const j=`${o}/unevaluatedProperties`;for(const N in t)if(!c[N]){const Y=`${i}/${nt(N)}`,K=ve(t[N],vt,r,n,a,s,Y,j);K.valid?c[N]=!0:P.push({instanceLocation:i,keyword:"unevaluatedProperties",keywordLocation:j,error:`Property "${N}" does not match unevaluated properties schema.`},...K.errors)}}}else if(l==="array"){T!==void 0&&t.length>T&&P.push({instanceLocation:i,keyword:"maxItems",keywordLocation:`${o}/maxItems`,error:`Array has too many items (${t.length} > ${T}).`}),f!==void 0&&t.length<f&&P.push({instanceLocation:i,keyword:"minItems",keywordLocation:`${o}/minItems`,error:`Array has too few items (${t.length} < ${f}).`});const J=t.length;let H=0,Q=!1;if(V!==void 0){const j=`${o}/prefixItems`,N=Math.min(V.length,J);for(;H<N;H++){const Y=ve(t[H],V[H],r,n,a,s,`${i}/${H}`,`${j}/${H}`);if(c[H]=!0,!Y.valid&&(Q=a,P.push({instanceLocation:i,keyword:"prefixItems",keywordLocation:j,error:"Items did not match schema."},...Y.errors),Q))break}}if(ae!==void 0){const j=`${o}/items`;if(Array.isArray(ae)){const N=Math.min(ae.length,J);for(;H<N;H++){const Y=ve(t[H],ae[H],r,n,a,s,`${i}/${H}`,`${j}/${H}`);if(c[H]=!0,!Y.valid&&(Q=a,P.push({instanceLocation:i,keyword:"items",keywordLocation:j,error:"Items did not match schema."},...Y.errors),Q))break}}else for(;H<J;H++){const N=ve(t[H],ae,r,n,a,s,`${i}/${H}`,j);if(c[H]=!0,!N.valid&&(Q=a,P.push({instanceLocation:i,keyword:"items",keywordLocation:j,error:"Items did not match schema."},...N.errors),Q))break}if(!Q&&ee!==void 0){const N=`${o}/additionalItems`;for(;H<J;H++){const Y=ve(t[H],ee,r,n,a,s,`${i}/${H}`,N);c[H]=!0,Y.valid||(Q=a,P.push({instanceLocation:i,keyword:"additionalItems",keywordLocation:N,error:"Items did not match additional items schema."},...Y.errors))}}}if(Te!==void 0)if(J===0&&ce===void 0)P.push({instanceLocation:i,keyword:"contains",keywordLocation:`${o}/contains`,error:"Array is empty. It must contain at least one item matching the schema."});else if(ce!==void 0&&J<ce)P.push({instanceLocation:i,keyword:"minContains",keywordLocation:`${o}/minContains`,error:`Array has less items (${J}) than minContains (${ce}).`});else{const j=`${o}/contains`,N=P.length;let Y=0;for(let K=0;K<J;K++){const Be=ve(t[K],Te,r,n,a,s,`${i}/${K}`,j);Be.valid?(c[K]=!0,Y++):P.push(...Be.errors)}Y>=(ce||0)&&(P.length=N),ce===void 0&&m===void 0&&Y===0?P.splice(N,0,{instanceLocation:i,keyword:"contains",keywordLocation:j,error:"Array does not contain item matching schema."}):ce!==void 0&&Y<ce?P.push({instanceLocation:i,keyword:"minContains",keywordLocation:`${o}/minContains`,error:`Array must contain at least ${ce} items matching schema. Only ${Y} items were found.`}):m!==void 0&&Y>m&&P.push({instanceLocation:i,keyword:"maxContains",keywordLocation:`${o}/maxContains`,error:`Array may contain at most ${m} items matching schema. ${Y} items were found.`})}if(!Q&&le!==void 0){const j=`${o}/unevaluatedItems`;for(H;H<J;H++){if(c[H])continue;const N=ve(t[H],le,r,n,a,s,`${i}/${H}`,j);c[H]=!0,N.valid||P.push({instanceLocation:i,keyword:"unevaluatedItems",keywordLocation:j,error:"Items did not match unevaluated items schema."},...N.errors)}}if(w)for(let j=0;j<J;j++){const N=t[j],Y=typeof N=="object"&&N!==null;for(let K=0;K<J;K++){if(j===K)continue;const Be=t[K];(N===Be||Y&&(typeof Be=="object"&&Be!==null)&&Gt(N,Be))&&(P.push({instanceLocation:i,keyword:"uniqueItems",keywordLocation:`${o}/uniqueItems`,error:`Duplicate items at indexes ${j} and ${K}.`}),j=Number.MAX_SAFE_INTEGER,K=Number.MAX_SAFE_INTEGER)}}}else if(l==="number"){if(r==="4"?(se!==void 0&&(_e===!0&&t<=se||t<se)&&P.push({instanceLocation:i,keyword:"minimum",keywordLocation:`${o}/minimum`,error:`${t} is less than ${_e?"or equal to ":""} ${se}.`}),me!==void 0&&(xe===!0&&t>=me||t>me)&&P.push({instanceLocation:i,keyword:"maximum",keywordLocation:`${o}/maximum`,error:`${t} is greater than ${xe?"or equal to ":""} ${me}.`})):(se!==void 0&&t<se&&P.push({instanceLocation:i,keyword:"minimum",keywordLocation:`${o}/minimum`,error:`${t} is less than ${se}.`}),me!==void 0&&t>me&&P.push({instanceLocation:i,keyword:"maximum",keywordLocation:`${o}/maximum`,error:`${t} is greater than ${me}.`}),_e!==void 0&&t<=_e&&P.push({instanceLocation:i,keyword:"exclusiveMinimum",keywordLocation:`${o}/exclusiveMinimum`,error:`${t} is less than ${_e}.`}),xe!==void 0&&t>=xe&&P.push({instanceLocation:i,keyword:"exclusiveMaximum",keywordLocation:`${o}/exclusiveMaximum`,error:`${t} is greater than or equal to ${xe}.`})),$e!==void 0){const J=t%$e;Math.abs(0-J)>=11920929e-14&&Math.abs($e-J)>=11920929e-14&&P.push({instanceLocation:i,keyword:"multipleOf",keywordLocation:`${o}/multipleOf`,error:`${t} is not a multiple of ${$e}.`})}}else if(l==="string"){const J=Qe===void 0&&be===void 0?0:e_(t);Qe!==void 0&&J<Qe&&P.push({instanceLocation:i,keyword:"minLength",keywordLocation:`${o}/minLength`,error:`String is too short (${J} < ${Qe}).`}),be!==void 0&&J>be&&P.push({instanceLocation:i,keyword:"maxLength",keywordLocation:`${o}/maxLength`,error:`String is too long (${J} > ${be}).`}),Ke!==void 0&&!new RegExp(Ke,"u").test(t)&&P.push({instanceLocation:i,keyword:"pattern",keywordLocation:`${o}/pattern`,error:"String does not match pattern."}),ge!==void 0&&Ic[ge]&&!Ic[ge](t)&&P.push({instanceLocation:i,keyword:"format",keywordLocation:`${o}/format`,error:`String does not match format "${ge}".`})}return{valid:P.length===0,errors:P}}class t_{schema;draft;shortCircuit;lookup;constructor(e,r="2019-09",n=!0){this.schema=e,this.draft=r,this.shortCircuit=n,this.lookup=Ct(e)}validate(e){return ve(e,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(e,r){r&&(e={...e,$id:r}),Ct(e,this.lookup)}}var r_={};pe(r_,{Validator:()=>t_,deepCompareStrict:()=>Gt,toJsonSchema:()=>wr,validatesOnlyStrings:()=>dn});function wr(t){if(Ie(t)){const e=sr(t,!0);if(gt(e)){const r=In(e,!0);return ki(r)}else return ki(t)}return Re(t)?Ig(t):t}function dn(t){if(!t||typeof t!="object"||Object.keys(t).length===0||Array.isArray(t))return!1;if("type"in t)return typeof t.type=="string"?t.type==="string":Array.isArray(t.type)?t.type.every(e=>e==="string"):!1;if("enum"in t)return Array.isArray(t.enum)&&t.enum.length>0&&t.enum.every(e=>typeof e=="string");if("const"in t)return typeof t.const=="string";if("allOf"in t&&Array.isArray(t.allOf))return t.allOf.some(e=>dn(e));if("anyOf"in t&&Array.isArray(t.anyOf)||"oneOf"in t&&Array.isArray(t.oneOf)){const e="anyOf"in t?t.anyOf:t.oneOf;return e.length>0&&e.every(r=>dn(r))}if("not"in t)return!1;if("$ref"in t&&typeof t.$ref=="string"){const e=t.$ref,r=Ct(t);return r[e]?dn(r[e]):!1}return!1}var n_={};pe(n_,{Graph:()=>bi});function a_(t,e){if(t!==void 0&&!Rr(t))return t;if(_i(e))try{let r=e.getName();return r=r.startsWith("Runnable")?r.slice(8):r,r}catch{return e.getName()}else return e.name??"UnknownSchema"}function s_(t){return _i(t.data)?{type:"runnable",data:{id:t.data.lc_id,name:t.data.getName()}}:{type:"schema",data:{...wr(t.data.schema),title:t.data.name}}}var bi=class il{nodes={};edges=[];constructor(e){this.nodes=e?.nodes??this.nodes,this.edges=e?.edges??this.edges}toJSON(){const e={};return Object.values(this.nodes).forEach((r,n)=>{e[r.id]=Rr(r.id)?n:r.id}),{nodes:Object.values(this.nodes).map(r=>({id:e[r.id],...s_(r)})),edges:this.edges.map(r=>{const n={source:e[r.source],target:e[r.target]};return typeof r.data<"u"&&(n.data=r.data),typeof r.conditional<"u"&&(n.conditional=r.conditional),n})}}addNode(e,r,n){if(r!==void 0&&this.nodes[r]!==void 0)throw new Error(`Node with id ${r} already exists`);const a=r??De(),s={id:a,data:e,name:a_(r,e),metadata:n};return this.nodes[a]=s,s}removeNode(e){delete this.nodes[e.id],this.edges=this.edges.filter(r=>r.source!==e.id&&r.target!==e.id)}addEdge(e,r,n,a){if(this.nodes[e.id]===void 0)throw new Error(`Source node ${e.id} not in graph`);if(this.nodes[r.id]===void 0)throw new Error(`Target node ${r.id} not in graph`);const s={source:e.id,target:r.id,data:n,conditional:a};return this.edges.push(s),s}firstNode(){return xc(this)}lastNode(){return Ac(this)}extend(e,r=""){let n=r;Object.values(e.nodes).map(u=>u.id).every(Rr)&&(n="");const s=u=>n?`${n}:${u}`:u;Object.entries(e.nodes).forEach(([u,l])=>{this.nodes[s(u)]={...l,id:s(u)}});const i=e.edges.map(u=>({...u,source:s(u.source),target:s(u.target)}));this.edges=[...this.edges,...i];const o=e.firstNode(),c=e.lastNode();return[o?{id:s(o.id),data:o.data}:void 0,c?{id:s(c.id),data:c.data}:void 0]}trimFirstNode(){const e=this.firstNode();e&&xc(this,[e.id])&&this.removeNode(e)}trimLastNode(){const e=this.lastNode();e&&Ac(this,[e.id])&&this.removeNode(e)}reid(){const e=Object.fromEntries(Object.values(this.nodes).map(a=>[a.id,a.name])),r=new Map;Object.values(e).forEach(a=>{r.set(a,(r.get(a)||0)+1)});const n=a=>{const s=e[a];return Rr(a)&&r.get(s)===1?s:a};return new il({nodes:Object.fromEntries(Object.entries(this.nodes).map(([a,s])=>[n(a),{...s,id:n(a)}])),edges:this.edges.map(a=>({...a,source:n(a.source),target:n(a.target)}))})}drawMermaid(e){const{withStyles:r,curveStyle:n,nodeColors:a={default:"fill:#f2f0ff,line-height:1.2",first:"fill-opacity:0",last:"fill:#bfb6fc"},wrapLabelNWords:s}=e??{},i=this.reid(),o=i.firstNode(),c=i.lastNode();return Um(i.nodes,i.edges,{firstNode:o?.id,lastNode:c?.id,withStyles:r,curveStyle:n,nodeColors:a,wrapLabelNWords:s})}async drawMermaidPng(e){const r=this.drawMermaid(e);return Fm(r,{backgroundColor:e?.backgroundColor})}};function xc(t,e=[]){const r=new Set(t.edges.filter(a=>!e.includes(a.source)).map(a=>a.target)),n=[];for(const a of Object.values(t.nodes))!e.includes(a.id)&&!r.has(a.id)&&n.push(a);return n.length===1?n[0]:void 0}function Ac(t,e=[]){const r=new Set(t.edges.filter(a=>!e.includes(a.target)).map(a=>a.source)),n=[];for(const a of Object.values(t.nodes))!e.includes(a.id)&&!r.has(a.id)&&n.push(a);return n.length===1?n[0]:void 0}function i_(t){const e=new TextEncoder,r=new ReadableStream({async start(n){for await(const a of t)n.enqueue(e.encode(`event: data
|
|
72
|
-
data: ${JSON.stringify(a)}
|
|
73
|
-
|
|
74
|
-
`));n.enqueue(e.encode(`event: end
|
|
75
|
-
|
|
76
|
-
`)),n.close()}});return ot.fromReadableStream(r)}function Oc(t){return typeof t=="object"&&t!==null&&typeof t[Symbol.iterator]=="function"&&typeof t.next=="function"}const o_=t=>t!=null&&typeof t=="object"&&"next"in t&&typeof t.next=="function";function Us(t){return typeof t=="object"&&t!==null&&typeof t[Symbol.asyncIterator]=="function"}function*kc(t,e){for(;;){const{value:r,done:n}=It.runWithConfig(Vt(t),e.next.bind(e),!0);if(n)break;yield r}}async function*Fs(t,e){const r=e[Symbol.asyncIterator]();for(;;){const{value:n,done:a}=await It.runWithConfig(Vt(t),r.next.bind(e),!0);if(a)break;yield n}}function ke(t,e){return t&&!Array.isArray(t)&&!(t instanceof Date)&&typeof t=="object"?t:{[e]:t}}var Se=class extends hr{lc_runnable=!0;name;getName(t){const e=this.name??this.constructor.lc_name()??this.constructor.name;return t?`${e}${t}`:e}withRetry(t){return new Ei({bound:this,kwargs:{},config:{},maxAttemptNumber:t?.stopAfterAttempt,...t})}withConfig(t){return new mr({bound:this,config:t,kwargs:{}})}withFallbacks(t){const e=Array.isArray(t)?t:t.fallbacks;return new hl({runnable:this,fallbacks:e})}_getOptionsList(t,e=0){if(Array.isArray(t)&&t.length!==e)throw new Error(`Passed "options" must be an array with the same length as the inputs, but got ${t.length} options for ${e} inputs`);if(Array.isArray(t))return t.map(de);if(e>1&&!Array.isArray(t)&&t.runId){console.warn("Provided runId will be used only for the first element of the batch.");const r=Object.fromEntries(Object.entries(t).filter(([n])=>n!=="runId"));return Array.from({length:e},(n,a)=>de(a===0?t:r))}return Array.from({length:e},()=>de(t))}async batch(t,e,r){const n=this._getOptionsList(e??{},t.length),a=n[0]?.maxConcurrency??r?.maxConcurrency,s=new Fn({maxConcurrency:a,onFailedAttempt:o=>{throw o}}),i=t.map((o,c)=>s.call(async()=>{try{return await this.invoke(o,n[c])}catch(u){if(r?.returnExceptions)return u;throw u}}));return Promise.all(i)}async*_streamIterator(t,e){yield this.invoke(t,e)}async stream(t,e){const r=de(e),n=new Xt({generator:this._streamIterator(t,r),config:r});return await n.setup,ot.fromAsyncGenerator(n)}_separateRunnableConfigFromCallOptions(t){let e;t===void 0?e=de(t):e=de({callbacks:t.callbacks,tags:t.tags,metadata:t.metadata,runName:t.runName,configurable:t.configurable,recursionLimit:t.recursionLimit,maxConcurrency:t.maxConcurrency,runId:t.runId,timeout:t.timeout,signal:t.signal});const r={...t};return delete r.callbacks,delete r.tags,delete r.metadata,delete r.runName,delete r.configurable,delete r.recursionLimit,delete r.maxConcurrency,delete r.runId,delete r.timeout,delete r.signal,[e,r]}async _callWithConfig(t,e,r){const n=de(r),s=await(await Je(n))?.handleChainStart(this.toJSON(),ke(e,"input"),n.runId,n?.runType,void 0,void 0,n?.runName??this.getName());delete n.runId;let i;try{const o=t.call(this,e,n,s);i=await Dt(o,r?.signal)}catch(o){throw await s?.handleChainError(o),o}return await s?.handleChainEnd(ke(i,"output")),i}async _batchWithConfig(t,e,r,n){const a=this._getOptionsList(r??{},e.length),s=await Promise.all(a.map(Je)),i=await Promise.all(s.map(async(c,u)=>{const l=await c?.handleChainStart(this.toJSON(),ke(e[u],"input"),a[u].runId,a[u].runType,void 0,void 0,a[u].runName??this.getName());return delete a[u].runId,l}));let o;try{const c=t.call(this,e,a,i,n);o=await Dt(c,a?.[0]?.signal)}catch(c){throw await Promise.all(i.map(u=>u?.handleChainError(c))),c}return await Promise.all(i.map(c=>c?.handleChainEnd(ke(o,"output")))),o}_concatOutputChunks(t,e){return Wt(t,e)}async*_transformStreamWithConfig(t,e,r){let n,a=!0,s,i=!0;const o=de(r),c=await Je(o),u=this;async function*l(){for await(const h of t){if(a)if(n===void 0)n=h;else try{n=u._concatOutputChunks(n,h)}catch{n=void 0,a=!1}yield h}}let d;try{const h=await Bu(e.bind(this),l(),async()=>c?.handleChainStart(this.toJSON(),{input:""},o.runId,o.runType,void 0,void 0,o.runName??this.getName()),r?.signal,o);delete o.runId,d=h.setup;const p=d?.handlers.find(ym);let g=h.output;p!==void 0&&d!==void 0&&(g=p.tapOutputIterable(d.runId,g));const y=d?.handlers.find(Hu);y!==void 0&&d!==void 0&&(g=y.tapOutputIterable(d.runId,g));for await(const v of g)if(yield v,i)if(s===void 0)s=v;else try{s=this._concatOutputChunks(s,v)}catch{s=void 0,i=!1}}catch(h){throw await d?.handleChainError(h,void 0,void 0,void 0,{inputs:ke(n,"input")}),h}await d?.handleChainEnd(s??{},void 0,void 0,void 0,{inputs:ke(n,"input")})}getGraph(t){const e=new bi,r=e.addNode({name:`${this.getName()}Input`,schema:zi()}),n=e.addNode(this),a=e.addNode({name:`${this.getName()}Output`,schema:zi()});return e.addEdge(r,n),e.addEdge(n,a),e}pipe(t){return new zn({first:this,last:it(t)})}pick(t){return this.pipe(new fl(t))}assign(t){return this.pipe(new Ti(new br({steps:t})))}async*transform(t,e){let r;for await(const n of t)r===void 0?r=n:r=this._concatOutputChunks(r,n);yield*this._streamIterator(r,de(e))}async*streamLog(t,e,r){const n=new Ps({...r,autoClose:!1,_schemaFormat:"original"}),a=de(e);yield*this._streamLog(t,n,a)}async*_streamLog(t,e,r){const{callbacks:n}=r;if(n===void 0)r.callbacks=[e];else if(Array.isArray(n))r.callbacks=n.concat([e]);else{const o=n.copy();o.addHandler(e,!0),r.callbacks=o}const a=this.stream(t,r);async function s(){try{const o=await a;for await(const c of o){const u=new wt({ops:[{op:"add",path:"/streamed_output/-",value:c}]});await e.writer.write(u)}}finally{await e.writer.close()}}const i=s();try{for await(const o of e)yield o}finally{await i}}streamEvents(t,e,r){let n;if(e.version==="v1")n=this._streamEventsV1(t,e,r);else if(e.version==="v2")n=this._streamEventsV2(t,e,r);else throw new Error('Only versions "v1" and "v2" of the schema are currently supported.');return e.encoding==="text/event-stream"?i_(n):ot.fromAsyncGenerator(n)}async*_streamEventsV2(t,e,r){const n=new vm({...r,autoClose:!1}),a=de(e),s=a.runId??De();a.runId=s;const i=a.callbacks;if(i===void 0)a.callbacks=[n];else if(Array.isArray(i))a.callbacks=i.concat(n);else{const p=i.copy();p.addHandler(n,!0),a.callbacks=p}const o=new AbortController,c=this;async function u(){let p,g=null;try{e?.signal?"any"in AbortSignal?p=AbortSignal.any([o.signal,e.signal]):(p=e.signal,g=()=>{o.abort()},e.signal.addEventListener("abort",g,{once:!0})):p=o.signal;const y=await c.stream(t,{...a,signal:p}),v=n.tapOutputIterable(s,y);for await(const b of v)if(o.signal.aborted)break}finally{await n.finish(),p&&g&&p.removeEventListener("abort",g)}}const l=u();let d=!1,h;try{for await(const p of n){if(!d){p.data.input=t,d=!0,h=p.run_id,yield p;continue}p.run_id===h&&p.event.endsWith("_end")&&p.data?.input&&delete p.data.input,yield p}}finally{o.abort(),await l}}async*_streamEventsV1(t,e,r){let n,a=!1;const s=de(e),i=s.tags??[],o=s.metadata??{},c=s.runName??this.getName(),u=new Ps({...r,autoClose:!1,_schemaFormat:"streaming_events"}),l=new Tm({...r}),d=this._streamLog(t,u,s);for await(const p of d){if(n?n=n.concat(p):n=gi.fromRunLogPatch(p),n.state===void 0)throw new Error('Internal error: "streamEvents" state is missing. Please open a bug report.');if(!a){a=!0;const b={...n.state},S={run_id:b.id,event:`on_${b.type}_start`,name:c,tags:i,metadata:o,data:{input:t}};l.includeEvent(S,b.type)&&(yield S)}const g=p.ops.filter(b=>b.path.startsWith("/logs/")).map(b=>b.path.split("/")[2]),y=[...new Set(g)];for(const b of y){let S,E={};const k=n.state.logs[b];if(k.end_time===void 0?k.streamed_output.length>0?S="stream":S="start":S="end",S==="start")k.inputs!==void 0&&(E.input=k.inputs);else if(S==="end")k.inputs!==void 0&&(E.input=k.inputs),E.output=k.final_output;else if(S==="stream"){const C=k.streamed_output.length;if(C!==1)throw new Error(`Expected exactly one chunk of streamed output, got ${C} instead. Encountered in: "${k.name}"`);E={chunk:k.streamed_output[0]},k.streamed_output=[]}yield{event:`on_${k.type}_${S}`,name:k.name,run_id:k.id,tags:k.tags,metadata:k.metadata,data:E}}const{state:v}=n;if(v.streamed_output.length>0){const b=v.streamed_output.length;if(b!==1)throw new Error(`Expected exactly one chunk of streamed output, got ${b} instead. Encountered in: "${v.name}"`);const S={chunk:v.streamed_output[0]};v.streamed_output=[];const E={event:`on_${v.type}_stream`,run_id:v.id,tags:i,metadata:o,name:c,data:S};l.includeEvent(E,v.type)&&(yield E)}}const h=n?.state;if(h!==void 0){const p={event:`on_${h.type}_end`,name:c,run_id:h.id,tags:i,metadata:o,data:{output:h.final_output}};l.includeEvent(p,h.type)&&(yield p)}}static isRunnable(t){return _i(t)}withListeners({onStart:t,onEnd:e,onError:r}){return new mr({bound:this,config:{},configFactories:[n=>({callbacks:[new Wu({config:n,onStart:t,onEnd:e,onError:r})]})]})}asTool(t){return h_(this,t)}},mr=class ol extends Se{static lc_name(){return"RunnableBinding"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;bound;config;kwargs;configFactories;constructor(e){super(e),this.bound=e.bound,this.kwargs=e.kwargs,this.config=e.config,this.configFactories=e.configFactories}getName(e){return this.bound.getName(e)}async _mergeConfig(...e){const r=As(this.config,...e);return As(r,...this.configFactories?await Promise.all(this.configFactories.map(async n=>await n(r))):[])}withConfig(e){return new this.constructor({bound:this.bound,kwargs:this.kwargs,config:{...this.config,...e}})}withRetry(e){return new Ei({bound:this.bound,kwargs:this.kwargs,config:this.config,maxAttemptNumber:e?.stopAfterAttempt,...e})}async invoke(e,r){return this.bound.invoke(e,await this._mergeConfig(r,this.kwargs))}async batch(e,r,n){const a=Array.isArray(r)?await Promise.all(r.map(async s=>this._mergeConfig(de(s),this.kwargs))):await this._mergeConfig(de(r),this.kwargs);return this.bound.batch(e,a,n)}_concatOutputChunks(e,r){return this.bound._concatOutputChunks(e,r)}async*_streamIterator(e,r){yield*this.bound._streamIterator(e,await this._mergeConfig(de(r),this.kwargs))}async stream(e,r){return this.bound.stream(e,await this._mergeConfig(de(r),this.kwargs))}async*transform(e,r){yield*this.bound.transform(e,await this._mergeConfig(de(r),this.kwargs))}streamEvents(e,r,n){const a=this,s=async function*(){yield*a.bound.streamEvents(e,{...await a._mergeConfig(de(r),a.kwargs),version:r.version},n)};return ot.fromAsyncGenerator(s())}static isRunnableBinding(e){return e.bound&&Se.isRunnable(e.bound)}withListeners({onStart:e,onEnd:r,onError:n}){return new ol({bound:this.bound,kwargs:this.kwargs,config:this.config,configFactories:[a=>({callbacks:[new Wu({config:a,onStart:e,onEnd:r,onError:n})]})]})}},c_=class cl extends Se{static lc_name(){return"RunnableEach"}lc_serializable=!0;lc_namespace=["langchain_core","runnables"];bound;constructor(e){super(e),this.bound=e.bound}async invoke(e,r){return this._callWithConfig(this._invoke.bind(this),e,r)}async _invoke(e,r,n){return this.bound.batch(e,we(r,{callbacks:n?.getChild()}))}withListeners({onStart:e,onEnd:r,onError:n}){return new cl({bound:this.bound.withListeners({onStart:e,onEnd:r,onError:n})})}},Ei=class extends mr{static lc_name(){return"RunnableRetry"}lc_namespace=["langchain_core","runnables"];maxAttemptNumber=3;onFailedAttempt=()=>{};constructor(t){super(t),this.maxAttemptNumber=t.maxAttemptNumber??this.maxAttemptNumber,this.onFailedAttempt=t.onFailedAttempt??this.onFailedAttempt}_patchConfigForRetry(t,e,r){const n=t>1?`retry:attempt:${t}`:void 0;return we(e,{callbacks:r?.getChild(n)})}async _invoke(t,e,r){return vn(n=>super.invoke(t,this._patchConfigForRetry(n,e,r)),{onFailedAttempt:n=>this.onFailedAttempt(n,t),retries:Math.max(this.maxAttemptNumber-1,0),randomize:!0})}async invoke(t,e){return this._callWithConfig(this._invoke.bind(this),t,e)}async _batch(t,e,r,n){const a={};try{await vn(async s=>{const i=t.map((d,h)=>h).filter(d=>a[d.toString()]===void 0||a[d.toString()]instanceof Error),o=i.map(d=>t[d]),c=i.map(d=>this._patchConfigForRetry(s,e?.[d],r?.[d])),u=await super.batch(o,c,{...n,returnExceptions:!0});let l;for(let d=0;d<u.length;d+=1){const h=u[d],p=i[d];h instanceof Error&&l===void 0&&(l=h,l.input=o[d]),a[p.toString()]=h}if(l)throw l;return u},{onFailedAttempt:s=>this.onFailedAttempt(s,s.input),retries:Math.max(this.maxAttemptNumber-1,0),randomize:!0})}catch(s){if(n?.returnExceptions!==!0)throw s}return Object.keys(a).sort((s,i)=>parseInt(s,10)-parseInt(i,10)).map(s=>a[parseInt(s,10)])}async batch(t,e,r){return this._batchWithConfig(this._batch.bind(this),t,e,r)}},zn=class xr extends Se{static lc_name(){return"RunnableSequence"}first;middle=[];last;omitSequenceTags=!1;lc_serializable=!0;lc_namespace=["langchain_core","runnables"];constructor(e){super(e),this.first=e.first,this.middle=e.middle??this.middle,this.last=e.last,this.name=e.name,this.omitSequenceTags=e.omitSequenceTags??this.omitSequenceTags}get steps(){return[this.first,...this.middle,this.last]}async invoke(e,r){const n=de(r),s=await(await Je(n))?.handleChainStart(this.toJSON(),ke(e,"input"),n.runId,void 0,void 0,void 0,n?.runName);delete n.runId;let i=e,o;try{const c=[this.first,...this.middle];for(let u=0;u<c.length;u+=1){const d=c[u].invoke(i,we(n,{callbacks:s?.getChild(this.omitSequenceTags?void 0:`seq:step:${u+1}`)}));i=await Dt(d,r?.signal)}if(r?.signal?.aborted)throw En(r.signal);o=await this.last.invoke(i,we(n,{callbacks:s?.getChild(this.omitSequenceTags?void 0:`seq:step:${this.steps.length}`)}))}catch(c){throw await s?.handleChainError(c),c}return await s?.handleChainEnd(ke(o,"output")),o}async batch(e,r,n){const a=this._getOptionsList(r??{},e.length),s=await Promise.all(a.map(Je)),i=await Promise.all(s.map(async(c,u)=>{const l=await c?.handleChainStart(this.toJSON(),ke(e[u],"input"),a[u].runId,void 0,void 0,void 0,a[u].runName);return delete a[u].runId,l}));let o=e;try{for(let c=0;c<this.steps.length;c+=1){const l=this.steps[c].batch(o,i.map((d,h)=>{const p=d?.getChild(this.omitSequenceTags?void 0:`seq:step:${c+1}`);return we(a[h],{callbacks:p})}),n);o=await Dt(l,a[0]?.signal)}}catch(c){throw await Promise.all(i.map(u=>u?.handleChainError(c))),c}return await Promise.all(i.map(c=>c?.handleChainEnd(ke(o,"output")))),o}_concatOutputChunks(e,r){return this.last._concatOutputChunks(e,r)}async*_streamIterator(e,r){const n=await Je(r),{runId:a,...s}=r??{},i=await n?.handleChainStart(this.toJSON(),ke(e,"input"),a,void 0,void 0,void 0,s?.runName),o=[this.first,...this.middle,this.last];let c=!0,u;async function*l(){yield e}try{let d=o[0].transform(l(),we(s,{callbacks:i?.getChild(this.omitSequenceTags?void 0:"seq:step:1")}));for(let h=1;h<o.length;h+=1)d=await o[h].transform(d,we(s,{callbacks:i?.getChild(this.omitSequenceTags?void 0:`seq:step:${h+1}`)}));for await(const h of d)if(r?.signal?.throwIfAborted(),yield h,c)if(u===void 0)u=h;else try{u=this._concatOutputChunks(u,h)}catch{u=void 0,c=!1}}catch(d){throw await i?.handleChainError(d),d}await i?.handleChainEnd(ke(u,"output"))}getGraph(e){const r=new bi;let n=null;return this.steps.forEach((a,s)=>{const i=a.getGraph(e);s!==0&&i.trimFirstNode(),s!==this.steps.length-1&&i.trimLastNode(),r.extend(i);const o=i.firstNode();if(!o)throw new Error(`Runnable ${a} has no first node`);n&&r.addEdge(n,o),n=i.lastNode()}),r}pipe(e){return xr.isRunnableSequence(e)?new xr({first:this.first,middle:this.middle.concat([this.last,e.first,...e.middle]),last:e.last,name:this.name??e.name}):new xr({first:this.first,middle:[...this.middle,this.last],last:it(e),name:this.name})}static isRunnableSequence(e){return Array.isArray(e.middle)&&Se.isRunnable(e)}static from([e,...r],n){let a={};return typeof n=="string"?a.name=n:n!==void 0&&(a=n),new xr({...a,first:it(e),middle:r.slice(0,-1).map(it),last:it(r[r.length-1])})}},br=class ul extends Se{static lc_name(){return"RunnableMap"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;steps;getStepsKeys(){return Object.keys(this.steps)}constructor(e){super(e),this.steps={};for(const[r,n]of Object.entries(e.steps))this.steps[r]=it(n)}static from(e){return new ul({steps:e})}async invoke(e,r){const n=de(r),s=await(await Je(n))?.handleChainStart(this.toJSON(),{input:e},n.runId,void 0,void 0,void 0,n?.runName);delete n.runId;const i={};try{const o=Object.entries(this.steps).map(async([c,u])=>{i[c]=await u.invoke(e,we(n,{callbacks:s?.getChild(`map:key:${c}`)}))});await Dt(Promise.all(o),r?.signal)}catch(o){throw await s?.handleChainError(o),o}return await s?.handleChainEnd(i),i}async*_transform(e,r,n){const a={...this.steps},s=pi(e,Object.keys(a).length),i=new Map(Object.entries(a).map(([o,c],u)=>{const l=c.transform(s[u],we(n,{callbacks:r?.getChild(`map:key:${o}`)}));return[o,l.next().then(d=>({key:o,gen:l,result:d}))]}));for(;i.size;){const o=Promise.race(i.values()),{key:c,result:u,gen:l}=await Dt(o,n?.signal);i.delete(c),u.done||(yield{[c]:u.value},i.set(c,l.next().then(d=>({key:c,gen:l,result:d}))))}}transform(e,r){return this._transformStreamWithConfig(e,this._transform.bind(this),r)}async stream(e,r){async function*n(){yield e}const a=de(r),s=new Xt({generator:this.transform(n(),a),config:a});return await s.setup,ot.fromAsyncGenerator(s)}},u_=class ll extends Se{lc_serializable=!1;lc_namespace=["langchain_core","runnables"];func;constructor(e){if(super(e),!fi(e.func))throw new Error("RunnableTraceable requires a function that is wrapped in traceable higher-order function");this.func=e.func}async invoke(e,r){const[n]=this._getOptionsList(r??{},1),a=await Je(n),s=this.func(we(n,{callbacks:a}),e);return Dt(s,n?.signal)}async*_streamIterator(e,r){const[n]=this._getOptionsList(r??{},1),a=await this.invoke(e,r);if(Us(a)){for await(const s of a)n?.signal?.throwIfAborted(),yield s;return}if(o_(a)){for(;;){n?.signal?.throwIfAborted();const s=a.next();if(s.done)break;yield s.value}return}yield a}static from(e){return new ll({func:e})}};function l_(t){if(fi(t))throw new Error("RunnableLambda requires a function that is not wrapped in traceable higher-order function. This shouldn't happen.")}var Ut=class dl extends Se{static lc_name(){return"RunnableLambda"}lc_namespace=["langchain_core","runnables"];func;constructor(e){if(fi(e.func))return u_.from(e.func);super(e),l_(e.func),this.func=e.func}static from(e){return new dl({func:e})}async _invoke(e,r,n){return new Promise((a,s)=>{const i=we(r,{callbacks:n?.getChild(),recursionLimit:(r?.recursionLimit??ns)-1});It.runWithConfig(Vt(i),async()=>{try{let o=await this.func(e,{...i});if(o&&Se.isRunnable(o)){if(r?.recursionLimit===0)throw new Error("Recursion limit reached.");o=await o.invoke(e,{...i,recursionLimit:(i.recursionLimit??ns)-1})}else if(Us(o)){let c;for await(const u of Fs(i,o))if(r?.signal?.throwIfAborted(),c===void 0)c=u;else try{c=this._concatOutputChunks(c,u)}catch{c=u}o=c}else if(Oc(o)){let c;for(const u of kc(i,o))if(r?.signal?.throwIfAborted(),c===void 0)c=u;else try{c=this._concatOutputChunks(c,u)}catch{c=u}o=c}a(o)}catch(o){s(o)}})})}async invoke(e,r){return this._callWithConfig(this._invoke.bind(this),e,r)}async*_transform(e,r,n){let a;for await(const o of e)if(a===void 0)a=o;else try{a=this._concatOutputChunks(a,o)}catch{a=o}const s=we(n,{callbacks:r?.getChild(),recursionLimit:(n?.recursionLimit??ns)-1}),i=await new Promise((o,c)=>{It.runWithConfig(Vt(s),async()=>{try{const u=await this.func(a,{...s,config:s});o(u)}catch(u){c(u)}})});if(i&&Se.isRunnable(i)){if(n?.recursionLimit===0)throw new Error("Recursion limit reached.");const o=await i.stream(a,s);for await(const c of o)yield c}else if(Us(i))for await(const o of Fs(s,i))n?.signal?.throwIfAborted(),yield o;else if(Oc(i))for(const o of kc(s,i))n?.signal?.throwIfAborted(),yield o;else yield i}transform(e,r){return this._transformStreamWithConfig(e,this._transform.bind(this),r)}async stream(e,r){async function*n(){yield e}const a=de(r),s=new Xt({generator:this.transform(n(),a),config:a});return await s.setup,ot.fromAsyncGenerator(s)}},d_=class extends br{},hl=class extends Se{static lc_name(){return"RunnableWithFallbacks"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;runnable;fallbacks;constructor(t){super(t),this.runnable=t.runnable,this.fallbacks=t.fallbacks}*runnables(){yield this.runnable;for(const t of this.fallbacks)yield t}async invoke(t,e){const r=de(e),n=await Je(r),{runId:a,...s}=r,i=await n?.handleChainStart(this.toJSON(),ke(t,"input"),a,void 0,void 0,void 0,s?.runName),o=we(s,{callbacks:i?.getChild()});return await It.runWithConfig(o,async()=>{let u;for(const l of this.runnables()){r?.signal?.throwIfAborted();try{const d=await l.invoke(t,o);return await i?.handleChainEnd(ke(d,"output")),d}catch(d){u===void 0&&(u=d)}}throw u===void 0?new Error("No error stored at end of fallback."):(await i?.handleChainError(u),u)})}async*_streamIterator(t,e){const r=de(e),n=await Je(r),{runId:a,...s}=r,i=await n?.handleChainStart(this.toJSON(),ke(t,"input"),a,void 0,void 0,void 0,s?.runName);let o,c;for(const l of this.runnables()){r?.signal?.throwIfAborted();const d=we(s,{callbacks:i?.getChild()});try{const h=await l.stream(t,d);c=Fs(d,h);break}catch(h){o===void 0&&(o=h)}}if(c===void 0){const l=o??new Error("No error stored at end of fallback.");throw await i?.handleChainError(l),l}let u;try{for await(const l of c){yield l;try{u=u===void 0?u:this._concatOutputChunks(u,l)}catch{u=void 0}}}catch(l){throw await i?.handleChainError(l),l}await i?.handleChainEnd(ke(u,"output"))}async batch(t,e,r){if(r?.returnExceptions)throw new Error("Not implemented.");const n=this._getOptionsList(e??{},t.length),a=await Promise.all(n.map(o=>Je(o))),s=await Promise.all(a.map(async(o,c)=>{const u=await o?.handleChainStart(this.toJSON(),ke(t[c],"input"),n[c].runId,void 0,void 0,void 0,n[c].runName);return delete n[c].runId,u}));let i;for(const o of this.runnables()){n[0].signal?.throwIfAborted();try{const c=await o.batch(t,s.map((u,l)=>we(n[l],{callbacks:u?.getChild()})),r);return await Promise.all(s.map((u,l)=>u?.handleChainEnd(ke(c[l],"output")))),c}catch(c){i===void 0&&(i=c)}}throw i?(await Promise.all(s.map(o=>o?.handleChainError(i))),i):new Error("No error stored at end of fallbacks.")}};function it(t){if(typeof t=="function")return new Ut({func:t});if(Se.isRunnable(t))return t;if(!Array.isArray(t)&&typeof t=="object"){const e={};for(const[r,n]of Object.entries(t))e[r]=it(n);return new br({steps:e})}else throw new Error(`Expected a Runnable, function or object.
|
|
77
|
-
Instead got an unsupported type.`)}var Ti=class extends Se{static lc_name(){return"RunnableAssign"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;mapper;constructor(t){t instanceof br&&(t={mapper:t}),super(t),this.mapper=t.mapper}async invoke(t,e){const r=await this.mapper.invoke(t,e);return{...t,...r}}async*_transform(t,e,r){const n=this.mapper.getStepsKeys(),[a,s]=pi(t),i=this.mapper.transform(s,we(r,{callbacks:e?.getChild()})),o=i.next();for await(const c of a){if(typeof c!="object"||Array.isArray(c))throw new Error(`RunnableAssign can only be used with objects as input, got ${typeof c}`);const u=Object.fromEntries(Object.entries(c).filter(([l])=>!n.includes(l)));Object.keys(u).length>0&&(yield u)}yield(await o).value;for await(const c of i)yield c}transform(t,e){return this._transformStreamWithConfig(t,this._transform.bind(this),e)}async stream(t,e){async function*r(){yield t}const n=de(e),a=new Xt({generator:this.transform(r(),n),config:n});return await a.setup,ot.fromAsyncGenerator(a)}},fl=class extends Se{static lc_name(){return"RunnablePick"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;keys;constructor(t){(typeof t=="string"||Array.isArray(t))&&(t={keys:t}),super(t),this.keys=t.keys}async _pick(t){if(typeof this.keys=="string")return t[this.keys];{const e=this.keys.map(r=>[r,t[r]]).filter(r=>r[1]!==void 0);return e.length===0?void 0:Object.fromEntries(e)}}async invoke(t,e){return this._callWithConfig(this._pick.bind(this),t,e)}async*_transform(t){for await(const e of t){const r=await this._pick(e);r!==void 0&&(yield r)}}transform(t,e){return this._transformStreamWithConfig(t,this._transform.bind(this),e)}async stream(t,e){async function*r(){yield t}const n=de(e),a=new Xt({generator:this.transform(r(),n),config:n});return await a.setup,ot.fromAsyncGenerator(a)}},Bs=class extends mr{name;description;schema;constructor(t){const e=zn.from([Ut.from(async r=>{let n;if(au(r))try{n=await yi(this.schema,r.args)}catch{throw new lh("Received tool input did not match expected schema",JSON.stringify(r.args))}else n=r;return n}).withConfig({runName:`${t.name}:parse_input`}),t.bound]).withConfig({runName:t.name});super({bound:e,config:t.config??{}}),this.name=t.name,this.description=t.description,this.schema=t.schema}static lc_name(){return"RunnableToolLike"}};function h_(t,e){const r=e.name??t.getName(),n=e.description??vi(e.schema);return Yu(e.schema)?new Bs({name:r,description:n,schema:Ws({input:Vs()}).transform(a=>a.input),bound:t}):new Bs({name:r,description:n,schema:e.schema,bound:t})}const An=(t,e)=>{const r=[...new Set(e?.map(a=>{if(typeof a=="string")return a;const s=new a({});if(!("getType"in s)||typeof s.getType!="function")throw new Error("Invalid type provided.");return s.getType()}))],n=t.getType();return r.some(a=>a===n)};function f_(t,e){return Array.isArray(t)?Rc(t,e):Ut.from(r=>Rc(r,t))}function Rc(t,e={}){const{includeNames:r,excludeNames:n,includeTypes:a,excludeTypes:s,includeIds:i,excludeIds:o}=e,c=[];for(const u of t)if(!(n&&u.name&&n.includes(u.name))){{if(s&&An(u,s))continue;if(o&&u.id&&o.includes(u.id))continue}a||i||r?(r&&u.name&&r.some(l=>l===u.name)||a&&An(u,a)||i&&u.id&&i.some(l=>l===u.id))&&c.push(u):c.push(u)}return c}function p_(t){return Array.isArray(t)?Cc(t):Ut.from(Cc)}function Cc(t){if(!t.length)return[];const e=[];for(const r of t){const n=r,a=e.pop();if(!a)e.push(n);else if(n.getType()==="tool"||n.getType()!==a.getType())e.push(a,n);else{const s=yn(a),i=yn(n),o=s.concat(i);typeof s.content=="string"&&typeof i.content=="string"&&(o.content=`${s.content}
|
|
78
|
-
${i.content}`),e.push(__(o))}}return e}function m_(t,e){if(Array.isArray(t)){const r=t;if(!e)throw new Error("Options parameter is required when providing messages.");return Nc(r,e)}else{const r=t;return Ut.from(n=>Nc(n,r)).withConfig({runName:"trim_messages"})}}async function Nc(t,e){const{maxTokens:r,tokenCounter:n,strategy:a="last",allowPartial:s=!1,endOn:i,startOn:o,includeSystem:c=!1,textSplitter:u}=e;if(o&&a==="first")throw new Error("`startOn` should only be specified if `strategy` is 'last'.");if(c&&a==="first")throw new Error("`includeSystem` should only be specified if `strategy` is 'last'.");let l;"getNumTokens"in n?l=async h=>(await Promise.all(h.map(g=>n.getNumTokens(g.content)))).reduce((g,y)=>g+y,0):l=async h=>n(h);let d=ml;if(u&&("splitText"in u?d=u.splitText:d=async h=>u(h)),a==="first")return pl(t,{maxTokens:r,tokenCounter:l,textSplitter:d,partialStrategy:s?"first":void 0,endOn:i});if(a==="last")return g_(t,{maxTokens:r,tokenCounter:l,textSplitter:d,allowPartial:s,includeSystem:c,startOn:o,endOn:i});throw new Error(`Unrecognized strategy: '${a}'. Must be one of 'first' or 'last'.`)}async function pl(t,e){const{maxTokens:r,tokenCounter:n,textSplitter:a,partialStrategy:s,endOn:i}=e;let o=[...t],c=0;for(let u=0;u<o.length;u+=1){const l=u>0?o.slice(0,-u):o;if(await n(l)<=r){c=o.length-u;break}}if(c<o.length&&s){let u=!1;if(Array.isArray(o[c].content)){const l=o[c];if(typeof l.content=="string")throw new Error("Expected content to be an array.");const d=l.content.length,h=s==="last"?[...l.content].reverse():l.content;for(let p=1;p<=d;p+=1){const g=s==="first"?h.slice(0,p):h.slice(-p),y=Object.fromEntries(Object.entries(l).filter(([S])=>S!=="type"&&!S.startsWith("lc_"))),v=Si(l.getType(),{...y,content:g}),b=[...o.slice(0,c),v];if(await n(b)<=r)o=b,c+=1,u=!0;else break}u&&s==="last"&&(l.content=[...h].reverse())}if(!u){const l=o[c];let d;if(Array.isArray(l.content)&&l.content.some(h=>typeof h=="string"||h.type==="text")?d=l.content.find(p=>p.type==="text"&&p.text)?.text:typeof l.content=="string"&&(d=l.content),d){const h=await a(d),p=h.length;s==="last"&&h.reverse();for(let g=0;g<p-1;g+=1)if(h.pop(),l.content=h.join(""),await n([...o.slice(0,c),l])<=r){s==="last"&&(l.content=[...h].reverse().join("")),o=[...o.slice(0,c),l],c+=1;break}}}}if(i){const u=Array.isArray(i)?i:[i];for(;c>0&&!An(o[c-1],u);)c-=1}return o.slice(0,c)}async function g_(t,e){const{allowPartial:r=!1,includeSystem:n=!1,endOn:a,startOn:s,...i}=e;let o=t.map(l=>{const d=Object.fromEntries(Object.entries(l).filter(([h])=>h!=="type"&&!h.startsWith("lc_")));return Si(l.getType(),d,ei(l))});if(a){const l=Array.isArray(a)?a:[a];for(;o.length>0&&!An(o[o.length-1],l);)o=o.slice(0,-1)}const c=n&&o[0]?.getType()==="system";let u=c?o.slice(0,1).concat(o.slice(1).reverse()):o.reverse();return u=await pl(u,{...i,partialStrategy:r?"last":void 0,endOn:s}),c?[u[0],...u.slice(1).reverse()]:u.reverse()}const $c={human:{message:At,messageChunk:$n},ai:{message:Lt,messageChunk:Yt},system:{message:jt,messageChunk:fr},developer:{message:jt,messageChunk:fr},tool:{message:_r,messageChunk:kn},function:{message:Cn,messageChunk:Nn},generic:{message:qr,messageChunk:Rn},remove:{message:_n,messageChunk:_n}};function Si(t,e,r){let n,a;switch(t){case"human":r?n=new $n(e):a=new At(e);break;case"ai":if(r){let s={...e};"tool_calls"in s&&(s={...s,tool_call_chunks:s.tool_calls?.map(i=>({...i,type:"tool_call_chunk",index:void 0,args:JSON.stringify(i.args)}))}),n=new Yt(s)}else a=new Lt(e);break;case"system":r?n=new fr(e):a=new jt(e);break;case"developer":r?n=new fr({...e,additional_kwargs:{...e.additional_kwargs,__openai_role__:"developer"}}):a=new jt({...e,additional_kwargs:{...e.additional_kwargs,__openai_role__:"developer"}});break;case"tool":if("tool_call_id"in e)r?n=new kn(e):a=new _r(e);else throw new Error("Can not convert ToolMessage to ToolMessageChunk if 'tool_call_id' field is not defined.");break;case"function":if(r)n=new Nn(e);else{if(!e.name)throw new Error("FunctionMessage must have a 'name' field");a=new Cn(e)}break;case"generic":if("role"in e)r?n=new Rn(e):a=new qr(e);else throw new Error("Can not convert ChatMessage to ChatMessageChunk if 'role' field is not defined.");break;default:throw new Error(`Unrecognized message type ${t}`)}if(r&&n)return n;if(a)return a;throw new Error(`Unrecognized message type ${t}`)}function __(t){const e=t.getType();let r;const n=Object.fromEntries(Object.entries(t).filter(([a])=>!["type","tool_call_chunks"].includes(a)&&!a.startsWith("lc_")));if(e in $c&&(r=Si(e,n)),!r)throw new Error(`Unrecognized message chunk class ${e}. Supported classes are ${Object.keys($c)}`);return r}function ml(t){const e=t.split(`
|
|
79
|
-
`);return Promise.resolve([...e.slice(0,-1).map(r=>`${r}
|
|
80
|
-
`),e[e.length-1]])}const y_=["tool_call","tool_call_chunk","invalid_tool_call","server_tool_call","server_tool_call_chunk","server_tool_call_result"],v_=["image","video","audio","text-plain","file"],w_=["text","reasoning",...y_,...v_];var b_={};pe(b_,{AIMessage:()=>Lt,AIMessageChunk:()=>Yt,BaseMessage:()=>xt,BaseMessageChunk:()=>Kt,ChatMessage:()=>qr,ChatMessageChunk:()=>Rn,FunctionMessage:()=>Cn,FunctionMessageChunk:()=>Nn,HumanMessage:()=>At,HumanMessageChunk:()=>$n,KNOWN_BLOCK_TYPES:()=>w_,RemoveMessage:()=>_n,SystemMessage:()=>jt,SystemMessageChunk:()=>fr,ToolMessage:()=>_r,ToolMessageChunk:()=>kn,_isMessageFieldWithRole:()=>Vc,_mergeDicts:()=>Me,_mergeLists:()=>zr,_mergeObj:()=>Zc,_mergeStatus:()=>Hc,coerceMessageLikeToMessage:()=>Or,convertToChunk:()=>yn,convertToOpenAIImageBlock:()=>Fc,convertToProviderContentBlock:()=>vd,defaultTextSplitter:()=>ml,defaultToolCallParser:()=>ti,filterMessages:()=>f_,getBufferString:()=>ai,iife:()=>dh,isAIMessage:()=>tu,isAIMessageChunk:()=>ws,isBase64ContentBlock:()=>Ks,isBaseMessage:()=>Et,isBaseMessageChunk:()=>ei,isChatMessage:()=>rh,isChatMessageChunk:()=>nh,isDataContentBlock:()=>Mt,isDirectToolOutput:()=>Yc,isFunctionMessage:()=>ah,isFunctionMessageChunk:()=>sh,isHumanMessage:()=>ih,isHumanMessageChunk:()=>oh,isIDContentBlock:()=>Uc,isMessage:()=>Bc,isOpenAIToolCallArray:()=>Zd,isPlainTextContentBlock:()=>_d,isSystemMessage:()=>ch,isSystemMessageChunk:()=>uh,isToolMessage:()=>Xc,isToolMessageChunk:()=>Qc,isURLContentBlock:()=>Js,mapChatMessagesToStoredMessages:()=>gh,mapStoredMessageToChatMessage:()=>si,mapStoredMessagesToChatMessages:()=>mh,mergeContent:()=>Jt,mergeMessageRuns:()=>p_,mergeResponseMetadata:()=>Wc,mergeUsageMetadata:()=>Kc,parseBase64DataUrl:()=>ys,parseMimeType:()=>yd,trimMessages:()=>m_});var E_={};pe(E_,{extendInteropZodObject:()=>Cm,getInteropZodDefaultGetter:()=>$m,getInteropZodObjectShape:()=>js,getSchemaDescription:()=>vi,interopParse:()=>Om,interopParseAsync:()=>yi,interopSafeParse:()=>Am,interopSafeParseAsync:()=>xm,interopZodObjectMakeFieldsOptional:()=>Lm,interopZodObjectPartial:()=>Nm,interopZodObjectPassthrough:()=>Ds,interopZodObjectStrict:()=>In,interopZodTransformInputSchema:()=>sr,isInteropZodLiteral:()=>Im,isInteropZodObject:()=>Rm,isInteropZodSchema:()=>Vr,isShapelessZodSchema:()=>km,isSimpleStringZodSchema:()=>Yu,isZodArrayV4:()=>Bn,isZodLiteralV3:()=>Ju,isZodLiteralV4:()=>Ku,isZodObjectV3:()=>wi,isZodObjectV4:()=>gt,isZodSchema:()=>Sm,isZodSchemaV3:()=>Re,isZodSchemaV4:()=>Ie});function gl(t){return t!==void 0&&Array.isArray(t.lc_namespace)}function _l(t){return t!==void 0&&Se.isRunnable(t)&&"lc_name"in t.constructor&&typeof t.constructor.lc_name=="function"&&t.constructor.lc_name()==="RunnableToolLike"}function yl(t){return!!t&&typeof t=="object"&&"name"in t&&"schema"in t&&(Vr(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 vl(t){return yl(t)||_l(t)||gl(t)}var T_={};pe(T_,{convertToOpenAIFunction:()=>wl,convertToOpenAITool:()=>S_,isLangChainTool:()=>vl,isRunnableToolLike:()=>_l,isStructuredTool:()=>gl,isStructuredToolParams:()=>yl});function wl(t,e){const r=typeof e=="number"?void 0:e;return{name:t.name,description:t.description,parameters:wr(t.schema),...r?.strict!==void 0?{strict:r.strict}:{}}}function S_(t,e){const r=typeof e=="number"?void 0:e;let n;return vl(t)?n={type:"function",function:wl(t)}:n=t,r?.strict!==void 0&&(n.function.strict=r.strict),n}var I_={};pe(I_,{BasePromptValue:()=>qn,ChatPromptValue:()=>El,ImagePromptValue:()=>x_,StringPromptValue:()=>bl});var qn=class extends hr{},bl=class extends qn{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 At(this.value)]}},El=class extends qn{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 ai(this.messages)}toChatMessages(){return this.messages}},x_=class extends qn{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 At({content:[{type:"image_url",image_url:{detail:this.imageUrl.detail,url:this.imageUrl.url}}]})]}},D="0123456789abcdef".split(""),A_=[-2147483648,8388608,32768,128],rt=[24,16,8,0],on=[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],Ce=[];function ct(t,e){e?(Ce[0]=Ce[16]=Ce[1]=Ce[2]=Ce[3]=Ce[4]=Ce[5]=Ce[6]=Ce[7]=Ce[8]=Ce[9]=Ce[10]=Ce[11]=Ce[12]=Ce[13]=Ce[14]=Ce[15]=0,this.blocks=Ce):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}ct.prototype.update=function(t){if(!this.finalized){var e,r=typeof t;if(r!=="string"){if(r==="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);e=!0}for(var n,a=0,s,i=t.length,o=this.blocks;a<i;){if(this.hashed&&(this.hashed=!1,o[0]=this.block,this.block=o[16]=o[1]=o[2]=o[3]=o[4]=o[5]=o[6]=o[7]=o[8]=o[9]=o[10]=o[11]=o[12]=o[13]=o[14]=o[15]=0),e)for(s=this.start;a<i&&s<64;++a)o[s>>>2]|=t[a]<<rt[s++&3];else for(s=this.start;a<i&&s<64;++a)n=t.charCodeAt(a),n<128?o[s>>>2]|=n<<rt[s++&3]:n<2048?(o[s>>>2]|=(192|n>>>6)<<rt[s++&3],o[s>>>2]|=(128|n&63)<<rt[s++&3]):n<55296||n>=57344?(o[s>>>2]|=(224|n>>>12)<<rt[s++&3],o[s>>>2]|=(128|n>>>6&63)<<rt[s++&3],o[s>>>2]|=(128|n&63)<<rt[s++&3]):(n=65536+((n&1023)<<10|t.charCodeAt(++a)&1023),o[s>>>2]|=(240|n>>>18)<<rt[s++&3],o[s>>>2]|=(128|n>>>12&63)<<rt[s++&3],o[s>>>2]|=(128|n>>>6&63)<<rt[s++&3],o[s>>>2]|=(128|n&63)<<rt[s++&3]);this.lastByteIndex=s,this.bytes+=s-this.start,s>=64?(this.block=o[16],this.start=s-64,this.hash(),this.hashed=!0):this.start=s}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296<<0,this.bytes=this.bytes%4294967296),this}};ct.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var t=this.blocks,e=this.lastByteIndex;t[16]=this.block,t[e>>>2]|=A_[e&3],this.block=t[16],e>=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()}};ct.prototype.hash=function(){var t=this.h0,e=this.h1,r=this.h2,n=this.h3,a=this.h4,s=this.h5,i=this.h6,o=this.h7,c=this.blocks,u,l,d,h,p,g,y,v,b,S,E;for(u=16;u<64;++u)p=c[u-15],l=(p>>>7|p<<25)^(p>>>18|p<<14)^p>>>3,p=c[u-2],d=(p>>>17|p<<15)^(p>>>19|p<<13)^p>>>10,c[u]=c[u-16]+l+c[u-7]+d<<0;for(E=e&r,u=0;u<64;u+=4)this.first?(this.is224?(v=300032,p=c[0]-1413257819,o=p-150054599<<0,n=p+24177077<<0):(v=704751109,p=c[0]-210244248,o=p-1521486534<<0,n=p+143694565<<0),this.first=!1):(l=(t>>>2|t<<30)^(t>>>13|t<<19)^(t>>>22|t<<10),d=(a>>>6|a<<26)^(a>>>11|a<<21)^(a>>>25|a<<7),v=t&e,h=v^t&r^E,y=a&s^~a&i,p=o+d+y+on[u]+c[u],g=l+h,o=n+p<<0,n=p+g<<0),l=(n>>>2|n<<30)^(n>>>13|n<<19)^(n>>>22|n<<10),d=(o>>>6|o<<26)^(o>>>11|o<<21)^(o>>>25|o<<7),b=n&t,h=b^n&e^v,y=i&o^~i&a,p=s+d+y+on[u+1]+c[u+1],g=l+h,i=r+p<<0,r=p+g<<0,l=(r>>>2|r<<30)^(r>>>13|r<<19)^(r>>>22|r<<10),d=(i>>>6|i<<26)^(i>>>11|i<<21)^(i>>>25|i<<7),S=r&n,h=S^r&t^b,y=s&i^~s&o,p=a+d+y+on[u+2]+c[u+2],g=l+h,s=e+p<<0,e=p+g<<0,l=(e>>>2|e<<30)^(e>>>13|e<<19)^(e>>>22|e<<10),d=(s>>>6|s<<26)^(s>>>11|s<<21)^(s>>>25|s<<7),E=e&r,h=E^e&n^S,y=s&i^~s&o,p=a+d+y+on[u+3]+c[u+3],g=l+h,a=t+p<<0,t=p+g<<0,this.chromeBugWorkAround=!0;this.h0=this.h0+t<<0,this.h1=this.h1+e<<0,this.h2=this.h2+r<<0,this.h3=this.h3+n<<0,this.h4=this.h4+a<<0,this.h5=this.h5+s<<0,this.h6=this.h6+i<<0,this.h7=this.h7+o<<0};ct.prototype.hex=function(){this.finalize();var t=this.h0,e=this.h1,r=this.h2,n=this.h3,a=this.h4,s=this.h5,i=this.h6,o=this.h7,c=D[t>>>28&15]+D[t>>>24&15]+D[t>>>20&15]+D[t>>>16&15]+D[t>>>12&15]+D[t>>>8&15]+D[t>>>4&15]+D[t&15]+D[e>>>28&15]+D[e>>>24&15]+D[e>>>20&15]+D[e>>>16&15]+D[e>>>12&15]+D[e>>>8&15]+D[e>>>4&15]+D[e&15]+D[r>>>28&15]+D[r>>>24&15]+D[r>>>20&15]+D[r>>>16&15]+D[r>>>12&15]+D[r>>>8&15]+D[r>>>4&15]+D[r&15]+D[n>>>28&15]+D[n>>>24&15]+D[n>>>20&15]+D[n>>>16&15]+D[n>>>12&15]+D[n>>>8&15]+D[n>>>4&15]+D[n&15]+D[a>>>28&15]+D[a>>>24&15]+D[a>>>20&15]+D[a>>>16&15]+D[a>>>12&15]+D[a>>>8&15]+D[a>>>4&15]+D[a&15]+D[s>>>28&15]+D[s>>>24&15]+D[s>>>20&15]+D[s>>>16&15]+D[s>>>12&15]+D[s>>>8&15]+D[s>>>4&15]+D[s&15]+D[i>>>28&15]+D[i>>>24&15]+D[i>>>20&15]+D[i>>>16&15]+D[i>>>12&15]+D[i>>>8&15]+D[i>>>4&15]+D[i&15];return this.is224||(c+=D[o>>>28&15]+D[o>>>24&15]+D[o>>>20&15]+D[o>>>16&15]+D[o>>>12&15]+D[o>>>8&15]+D[o>>>4&15]+D[o&15]),c};ct.prototype.toString=ct.prototype.hex;ct.prototype.digest=function(){this.finalize();var t=this.h0,e=this.h1,r=this.h2,n=this.h3,a=this.h4,s=this.h5,i=this.h6,o=this.h7,c=[t>>>24&255,t>>>16&255,t>>>8&255,t&255,e>>>24&255,e>>>16&255,e>>>8&255,e&255,r>>>24&255,r>>>16&255,r>>>8&255,r&255,n>>>24&255,n>>>16&255,n>>>8&255,n&255,a>>>24&255,a>>>16&255,a>>>8&255,a&255,s>>>24&255,s>>>16&255,s>>>8&255,s&255,i>>>24&255,i>>>16&255,i>>>8&255,i&255];return this.is224||c.push(o>>>24&255,o>>>16&255,o>>>8&255,o&255),c};ct.prototype.array=ct.prototype.digest;ct.prototype.arrayBuffer=function(){this.finalize();var t=new ArrayBuffer(this.is224?28:32),e=new DataView(t);return e.setUint32(0,this.h0),e.setUint32(4,this.h1),e.setUint32(8,this.h2),e.setUint32(12,this.h3),e.setUint32(16,this.h4),e.setUint32(20,this.h5),e.setUint32(24,this.h6),this.is224||e.setUint32(28,this.h7),t};const Tl=(...t)=>new ct(!1,!0).update(t.join("")).hex();var O_={};pe(O_,{sha256:()=>Tl});var k_={};pe(k_,{BaseCache:()=>Il,InMemoryCache:()=>xl,defaultHashKeyEncoder:()=>Sl,deserializeStoredGeneration:()=>R_,serializeGeneration:()=>C_});const Sl=(...t)=>Tl(t.join("_"));function R_(t){return t.message!==void 0?{text:t.text,message:si(t.message)}:{text:t.text}}function C_(t){const e={text:t.text};return t.message!==void 0&&(e.message=t.message.toDict()),e}var Il=class{keyEncoder=Sl;makeDefaultKeyEncoder(t){this.keyEncoder=t}};const N_=new Map;var xl=class Al extends Il{cache;constructor(e){super(),this.cache=e??new Map}lookup(e,r){return Promise.resolve(this.cache.get(this.keyEncoder(e,r))??null)}async update(e,r,n){this.cache.set(this.keyEncoder(e,r),n)}static global(){return new Al(N_)}},$_=Gl();const P_=gr($_);var M_=Object.defineProperty,L_=(t,e,r)=>e in t?M_(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,j_=(t,e,r)=>(L_(t,e+"",r),r);function D_(t,e){let r=Array.from({length:t.length},(n,a)=>({start:a,end:a+1}));for(;r.length>1;){let n=null;for(let a=0;a<r.length-1;a++){const s=t.slice(r[a].start,r[a+1].end),i=e.get(s.join(","));i!=null&&(n==null||i<n[0])&&(n=[i,a])}if(n!=null){const a=n[1];r[a]={start:r[a].start,end:r[a+1].end},r.splice(a+1,1)}else break}return r}function U_(t,e){return t.length===1?[e.get(t.join(","))]:D_(t,e).map(r=>e.get(t.slice(r.start,r.end).join(","))).filter(r=>r!=null)}function F_(t){return t.replace(/[\\^$*+?.()|[\]{}]/g,"\\$&")}var zs=class{specialTokens;inverseSpecialTokens;patStr;textEncoder=new TextEncoder;textDecoder=new TextDecoder("utf-8");rankMap=new Map;textMap=new Map;constructor(t,e){this.patStr=t.pat_str;const r=t.bpe_ranks.split(`
|
|
81
|
-
`).filter(Boolean).reduce((n,a)=>{const[s,i,...o]=a.split(" "),c=Number.parseInt(i,10);return o.forEach((u,l)=>n[u]=c+l),n},{});for(const[n,a]of Object.entries(r)){const s=P_.toByteArray(n);this.rankMap.set(s.join(","),a),this.textMap.set(a,s)}this.specialTokens={...t.special_tokens,...e},this.inverseSpecialTokens=Object.entries(this.specialTokens).reduce((n,[a,s])=>(n[s]=this.textEncoder.encode(a),n),{})}encode(t,e=[],r="all"){const n=new RegExp(this.patStr,"ug"),a=zs.specialTokenRegex(Object.keys(this.specialTokens)),s=[],i=new Set(e==="all"?Object.keys(this.specialTokens):e),o=new Set(r==="all"?Object.keys(this.specialTokens).filter(u=>!i.has(u)):r);if(o.size>0){const u=zs.specialTokenRegex([...o]),l=t.match(u);if(l!=null)throw new Error(`The text contains a special token that is not allowed: ${l[0]}`)}let c=0;for(;;){let u=null,l=c;for(;a.lastIndex=l,u=a.exec(t),!(u==null||i.has(u[0]));)l=u.index+1;const d=u?.index??t.length;for(const p of t.substring(c,d).matchAll(n)){const g=this.textEncoder.encode(p[0]),y=this.rankMap.get(g.join(","));if(y!=null){s.push(y);continue}s.push(...U_(g,this.rankMap))}if(u==null)break;let h=this.specialTokens[u[0]];s.push(h),c=u.index+u[0].length}return s}decode(t){const e=[];let r=0;for(let s=0;s<t.length;++s){const i=t[s],o=this.textMap.get(i)??this.inverseSpecialTokens[i];o!=null&&(e.push(o),r+=o.length)}const n=new Uint8Array(r);let a=0;for(const s of e)n.set(s,a),a+=s.length;return this.textDecoder.decode(n)}},Ol=zs;j_(Ol,"specialTokenRegex",t=>new RegExp(t.map(e=>F_(e)).join("|"),"g"));function B_(t){switch(t){case"gpt2":return"gpt2";case"code-cushman-001":case"code-cushman-002":case"code-davinci-001":case"code-davinci-002":case"cushman-codex":case"davinci-codex":case"davinci-002":case"text-davinci-002":case"text-davinci-003":return"p50k_base";case"code-davinci-edit-001":case"text-davinci-edit-001":return"p50k_edit";case"ada":case"babbage":case"babbage-002":case"code-search-ada-code-001":case"code-search-babbage-code-001":case"curie":case"davinci":case"text-ada-001":case"text-babbage-001":case"text-curie-001":case"text-davinci-001":case"text-search-ada-doc-001":case"text-search-babbage-doc-001":case"text-search-curie-doc-001":case"text-search-davinci-doc-001":case"text-similarity-ada-001":case"text-similarity-babbage-001":case"text-similarity-curie-001":case"text-similarity-davinci-001":return"r50k_base";case"gpt-3.5-turbo-instruct-0914":case"gpt-3.5-turbo-instruct":case"gpt-3.5-turbo-16k-0613":case"gpt-3.5-turbo-16k":case"gpt-3.5-turbo-0613":case"gpt-3.5-turbo-0301":case"gpt-3.5-turbo":case"gpt-4-32k-0613":case"gpt-4-32k-0314":case"gpt-4-32k":case"gpt-4-0613":case"gpt-4-0314":case"gpt-4":case"gpt-3.5-turbo-1106":case"gpt-35-turbo":case"gpt-4-1106-preview":case"gpt-4-vision-preview":case"gpt-3.5-turbo-0125":case"gpt-4-turbo":case"gpt-4-turbo-2024-04-09":case"gpt-4-turbo-preview":case"gpt-4-0125-preview":case"text-embedding-ada-002":case"text-embedding-3-small":case"text-embedding-3-large":return"cl100k_base";case"gpt-4o":case"gpt-4o-2024-05-13":case"gpt-4o-2024-08-06":case"gpt-4o-2024-11-20":case"gpt-4o-mini-2024-07-18":case"gpt-4o-mini":case"gpt-4o-search-preview":case"gpt-4o-search-preview-2025-03-11":case"gpt-4o-mini-search-preview":case"gpt-4o-mini-search-preview-2025-03-11":case"gpt-4o-audio-preview":case"gpt-4o-audio-preview-2024-12-17":case"gpt-4o-audio-preview-2024-10-01":case"gpt-4o-mini-audio-preview":case"gpt-4o-mini-audio-preview-2024-12-17":case"o1":case"o1-2024-12-17":case"o1-mini":case"o1-mini-2024-09-12":case"o1-preview":case"o1-preview-2024-09-12":case"o1-pro":case"o1-pro-2025-03-19":case"o3":case"o3-2025-04-16":case"o3-mini":case"o3-mini-2025-01-31":case"o4-mini":case"o4-mini-2025-04-16":case"chatgpt-4o-latest":case"gpt-4o-realtime":case"gpt-4o-realtime-preview-2024-10-01":case"gpt-4o-realtime-preview-2024-12-17":case"gpt-4o-mini-realtime-preview":case"gpt-4o-mini-realtime-preview-2024-12-17":case"gpt-4.1":case"gpt-4.1-2025-04-14":case"gpt-4.1-mini":case"gpt-4.1-mini-2025-04-14":case"gpt-4.1-nano":case"gpt-4.1-nano-2025-04-14":case"gpt-4.5-preview":case"gpt-4.5-preview-2025-02-27":case"gpt-5":case"gpt-5-2025-08-07":case"gpt-5-nano":case"gpt-5-nano-2025-08-07":case"gpt-5-mini":case"gpt-5-mini-2025-08-07":case"gpt-5-chat-latest":return"o200k_base";default:throw new Error("Unknown model")}}var z_={};pe(z_,{encodingForModel:()=>Ii,getEncoding:()=>kl});const cn={},q_=new Fn({});async function kl(t){return t in cn||(cn[t]=q_.fetch(`https://tiktoken.pages.dev/js/${t}.json`).then(e=>e.json()).then(e=>new Ol(e)).catch(e=>{throw delete cn[t],e})),await cn[t]}async function Ii(t){return kl(B_(t))}var G_={};pe(G_,{BaseLangChain:()=>Cl,BaseLanguageModel:()=>Nl,calculateMaxTokens:()=>V_,getEmbeddingContextSize:()=>H_,getModelContextSize:()=>Rl,getModelNameForTiktoken:()=>Gn,isOpenAITool:()=>Z_});const Gn=t=>t.startsWith("gpt-5")?"gpt-5":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,H_=t=>{switch(t){case"text-embedding-ada-002":return 8191;default:return 2046}},Rl=t=>{switch(Gn(t)){case"gpt-5":case"gpt-5-turbo":case"gpt-5-turbo-preview":return 4e5;case"gpt-4o":case"gpt-4o-mini":case"gpt-4o-2024-05-13":case"gpt-4o-2024-08-06":return 128e3;case"gpt-4-turbo":case"gpt-4-turbo-preview":case"gpt-4-turbo-2024-04-09":case"gpt-4-0125-preview":case"gpt-4-1106-preview":return 128e3;case"gpt-4-32k":case"gpt-4-32k-0314":case"gpt-4-32k-0613":return 32768;case"gpt-4":case"gpt-4-0314":case"gpt-4-0613":return 8192;case"gpt-3.5-turbo-16k":case"gpt-3.5-turbo-16k-0613":return 16384;case"gpt-3.5-turbo":case"gpt-3.5-turbo-0301":case"gpt-3.5-turbo-0613":case"gpt-3.5-turbo-1106":case"gpt-3.5-turbo-0125":return 4096;case"text-davinci-003":case"text-davinci-002":return 4097;case"text-davinci-001":return 2049;case"text-curie-001":case"text-babbage-001":case"text-ada-001":return 2048;case"code-davinci-002":case"code-davinci-001":return 8e3;case"code-cushman-001":return 2048;case"claude-3-5-sonnet-20241022":case"claude-3-5-sonnet-20240620":case"claude-3-opus-20240229":case"claude-3-sonnet-20240229":case"claude-3-haiku-20240307":case"claude-2.1":return 2e5;case"claude-2.0":case"claude-instant-1.2":return 1e5;case"gemini-1.5-pro":case"gemini-1.5-pro-latest":case"gemini-1.5-flash":case"gemini-1.5-flash-latest":return 1e6;case"gemini-pro":case"gemini-pro-vision":return 32768;default:return 4097}};function Z_(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 V_=async({prompt:t,modelName:e})=>{let r;try{r=(await Ii(Gn(e))).encode(t).length}catch{console.warn("Failed to calculate number of tokens, falling back to approximate count"),r=Math.ceil(t.length/4)}return Rl(e)-r},W_=()=>!1;var Cl=class extends Se{verbose;callbacks;tags;metadata;get lc_attributes(){return{callbacks:void 0,verbose:void 0}}constructor(t){super(t),this.verbose=t.verbose??W_(),this.callbacks=t.callbacks,this.tags=t.tags??[],this.metadata=t.metadata??{}}},Nl=class extends Cl{get callKeys(){return["stop","timeout","signal","tags","metadata","callbacks"]}caller;cache;constructor({callbacks:t,callbackManager:e,...r}){const{cache:n,...a}=r;super({callbacks:t??e,...a}),typeof n=="object"?this.cache=n:n?this.cache=xl.global():this.cache=void 0,this.caller=new Fn(r??{})}_encoding;async getNumTokens(t){let e;typeof t=="string"?e=t:e=t.map(n=>typeof n=="string"?n:n.type==="text"&&"text"in n?n.text:"").join("");let r=Math.ceil(e.length/4);if(!this._encoding)try{this._encoding=await Ii("modelName"in this?Gn(this.modelName):"gpt2")}catch(n){console.warn("Failed to calculate number of tokens, falling back to approximate count",n)}if(this._encoding)try{r=this._encoding.encode(e).length}catch(n){console.warn("Failed to calculate number of tokens, falling back to approximate count",n)}return r}static _convertInputToPromptValue(t){return typeof t=="string"?new bl(t):Array.isArray(t)?new El(t.map(Or)):t}_identifyingParams(){return{}}_getSerializedCacheKeyParametersForCall({config:t,...e}){const r={...this._identifyingParams(),...e,_type:this._llmType(),_model:this._modelType()};return Object.entries(r).filter(([s,i])=>i!==void 0).map(([s,i])=>`${s}:${JSON.stringify(i)}`).sort().join(",")}serialize(){return{...this._identifyingParams(),_type:this._llmType(),_model:this._modelType()}}static async deserialize(t){throw new Error("Use .toJSON() instead")}},On=class extends Se{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,e){const r=de(e);return this.func&&await this.func(t,r),this._callWithConfig(n=>Promise.resolve(n),t,r)}async*transform(t,e){const r=de(e);let n,a=!0;for await(const s of this._transformStreamWithConfig(t,i=>i,r))if(yield s,a)if(n===void 0)n=s;else try{n=Wt(n,s)}catch{n=void 0,a=!1}this.func&&n!==void 0&&await this.func(n,r)}static assign(t){return new Ti(new br({steps:t}))}};const J_=t=>t();function os(t){const e=t.constructor;return new e({...t,content:t.contentBlocks,response_metadata:{...t.response_metadata,output_version:"v1"}})}var K_={};pe(K_,{BaseChatModel:()=>$l,SimpleChatModel:()=>Y_});function cs(t){const e=[];for(const r of t){let n=r;if(Array.isArray(r.content))for(let a=0;a<r.content.length;a++){const s=r.content[a];(Js(s)||Ks(s))&&n===r&&(n=new r.constructor({...n,content:[...r.content.slice(0,a),Fc(s),...r.content.slice(a+1)]}))}e.push(n)}return e}var $l=class Bt extends Nl{lc_namespace=["langchain","chat_models",this._llmType()];disableStreaming=!1;outputVersion;get callKeys(){return[...super.callKeys,"outputVersion"]}constructor(e){super(e),this.outputVersion=J_(()=>{const r=e.outputVersion??$t("LC_OUTPUT_VERSION");return r&&["v0","v1"].includes(r)?r:"v0"})}_separateRunnableConfigFromCallOptionsCompat(e){const[r,n]=super._separateRunnableConfigFromCallOptions(e);return n.signal=r.signal,[r,n]}async invoke(e,r){const n=Bt._convertInputToPromptValue(e);return(await this.generatePrompt([n],r,r?.callbacks)).generations[0][0].message}async*_streamResponseChunks(e,r,n){throw new Error("Not implemented.")}async*_streamIterator(e,r){if(this._streamResponseChunks===Bt.prototype._streamResponseChunks||this.disableStreaming)yield this.invoke(e,r);else{const a=Bt._convertInputToPromptValue(e).toChatMessages(),[s,i]=this._separateRunnableConfigFromCallOptionsCompat(r),o={...s.metadata,...this.getLsParams(i)},c=await mt.configure(s.callbacks,this.callbacks,s.tags,this.tags,o,this.metadata,{verbose:this.verbose}),u={options:i,invocation_params:this?.invocationParams(i),batch_size:1},l=i.outputVersion??this.outputVersion,d=await c?.handleChatModelStart(this.toJSON(),[cs(a)],s.runId,void 0,u,void 0,void 0,s.runName);let h,p;try{for await(const g of this._streamResponseChunks(a,i,d?.[0])){if(g.message.id==null){const y=d?.at(0)?.runId;y!=null&&g.message._updateId(`run-${y}`)}g.message.response_metadata={...g.generationInfo,...g.message.response_metadata},l==="v1"?yield os(g.message):yield g.message,h?h=h.concat(g):h=g,ws(g.message)&&g.message.usage_metadata!==void 0&&(p={tokenUsage:{promptTokens:g.message.usage_metadata.input_tokens,completionTokens:g.message.usage_metadata.output_tokens,totalTokens:g.message.usage_metadata.total_tokens}})}}catch(g){throw await Promise.all((d??[]).map(y=>y?.handleLLMError(g))),g}await Promise.all((d??[]).map(g=>g?.handleLLMEnd({generations:[[h]],llmOutput:p})))}}getLsParams(e){const r=this.getName().startsWith("Chat")?this.getName().replace("Chat",""):this.getName();return{ls_model_type:"chat",ls_stop:e.stop,ls_provider:r}}async _generateUncached(e,r,n,a){const s=e.map(h=>h.map(Or));let i;if(a!==void 0&&a.length===s.length)i=a;else{const h={...n.metadata,...this.getLsParams(r)},p=await mt.configure(n.callbacks,this.callbacks,n.tags,this.tags,h,this.metadata,{verbose:this.verbose}),g={options:r,invocation_params:this?.invocationParams(r),batch_size:1};i=await p?.handleChatModelStart(this.toJSON(),s.map(cs),n.runId,void 0,g,void 0,void 0,n.runName)}const o=r.outputVersion??this.outputVersion,c=[],u=[];if(!!i?.[0].handlers.find(fu)&&!this.disableStreaming&&s.length===1&&this._streamResponseChunks!==Bt.prototype._streamResponseChunks)try{const h=await this._streamResponseChunks(s[0],r,i?.[0]);let p,g;for await(const y of h){if(y.message.id==null){const v=i?.at(0)?.runId;v!=null&&y.message._updateId(`run-${v}`)}p===void 0?p=y:p=Wt(p,y),ws(y.message)&&y.message.usage_metadata!==void 0&&(g={tokenUsage:{promptTokens:y.message.usage_metadata.input_tokens,completionTokens:y.message.usage_metadata.output_tokens,totalTokens:y.message.usage_metadata.total_tokens}})}if(p===void 0)throw new Error("Received empty response from chat model call.");c.push([p]),await i?.[0].handleLLMEnd({generations:c,llmOutput:g})}catch(h){throw await i?.[0].handleLLMError(h),h}else{const h=await Promise.allSettled(s.map(async(p,g)=>{const y=await this._generate(p,{...r,promptIndex:g},i?.[g]);if(o==="v1")for(const v of y.generations)v.message=os(v.message);return y}));await Promise.all(h.map(async(p,g)=>{if(p.status==="fulfilled"){const y=p.value;for(const v of y.generations){if(v.message.id==null){const b=i?.at(0)?.runId;b!=null&&v.message._updateId(`run-${b}`)}v.message.response_metadata={...v.generationInfo,...v.message.response_metadata}}return y.generations.length===1&&(y.generations[0].message.response_metadata={...y.llmOutput,...y.generations[0].message.response_metadata}),c[g]=y.generations,u[g]=y.llmOutput,i?.[g]?.handleLLMEnd({generations:[y.generations],llmOutput:y.llmOutput})}else return await i?.[g]?.handleLLMError(p.reason),Promise.reject(p.reason)}))}const d={generations:c,llmOutput:u.length?this._combineLLMOutput?.(...u):void 0};return Object.defineProperty(d,Ms,{value:i?{runIds:i?.map(h=>h.runId)}:void 0,configurable:!0}),d}async _generateCached({messages:e,cache:r,llmStringKey:n,parsedOptions:a,handledOptions:s}){const i=e.map(b=>b.map(Or)),o={...s.metadata,...this.getLsParams(a)},c=await mt.configure(s.callbacks,this.callbacks,s.tags,this.tags,o,this.metadata,{verbose:this.verbose}),u={options:a,invocation_params:this?.invocationParams(a),batch_size:1},l=await c?.handleChatModelStart(this.toJSON(),i.map(cs),s.runId,void 0,u,void 0,void 0,s.runName),d=[],p=(await Promise.allSettled(i.map(async(b,S)=>{const E=Bt._convertInputToPromptValue(b).toString(),k=await r.lookup(E,n);return k==null&&d.push(S),k}))).map((b,S)=>({result:b,runManager:l?.[S]})).filter(({result:b})=>b.status==="fulfilled"&&b.value!=null||b.status==="rejected"),g=a.outputVersion??this.outputVersion,y=[];await Promise.all(p.map(async({result:b,runManager:S},E)=>{if(b.status==="fulfilled"){const k=b.value;return y[E]=k.map(C=>("message"in C&&Et(C.message)&&tu(C.message)&&(C.message.usage_metadata={input_tokens:0,output_tokens:0,total_tokens:0},g==="v1"&&(C.message=os(C.message))),C.generationInfo={...C.generationInfo,tokenUsage:{}},C)),k.length&&await S?.handleLLMNewToken(k[0].text),S?.handleLLMEnd({generations:[k]},void 0,void 0,void 0,{cached:!0})}else return await S?.handleLLMError(b.reason,void 0,void 0,void 0,{cached:!0}),Promise.reject(b.reason)}));const v={generations:y,missingPromptIndices:d,startedRunManagers:l};return Object.defineProperty(v,Ms,{value:l?{runIds:l?.map(b=>b.runId)}:void 0,configurable:!0}),v}async generate(e,r,n){let a;Array.isArray(r)?a={stop:r}:a=r;const s=e.map(g=>g.map(Or)),[i,o]=this._separateRunnableConfigFromCallOptionsCompat(a);if(i.callbacks=i.callbacks??n,!this.cache)return this._generateUncached(s,o,i);const{cache:c}=this,u=this._getSerializedCacheKeyParametersForCall(o),{generations:l,missingPromptIndices:d,startedRunManagers:h}=await this._generateCached({messages:s,cache:c,llmStringKey:u,parsedOptions:o,handledOptions:i});let p={};if(d.length>0){const g=await this._generateUncached(d.map(y=>s[y]),o,i,h!==void 0?d.map(y=>h?.[y]):void 0);await Promise.all(g.generations.map(async(y,v)=>{const b=d[v];l[b]=y;const S=Bt._convertInputToPromptValue(s[b]).toString();return c.update(S,u,y)})),p=g.llmOutput??{}}return{generations:l,llmOutput:p}}invocationParams(e){return{}}_modelType(){return"base_chat_model"}async generatePrompt(e,r,n){const a=e.map(s=>s.toChatMessages());return this.generate(a,r,n)}withStructuredOutput(e,r){if(typeof this.bindTools!="function")throw new Error('Chat model must implement ".bindTools()" to use withStructuredOutput.');if(r?.strict)throw new Error('"strict" mode is not supported for this model by default.');const n=e,a=r?.name,s=vi(n)??"A function available to call.",i=r?.method,o=r?.includeRaw;if(i==="jsonMode")throw new Error('Base withStructuredOutput implementation only supports "functionCalling" as a method.');let c=a??"extract",u;Vr(n)?u=[{type:"function",function:{name:c,description:s,parameters:wr(n)}}]:("name"in n&&(c=n.name),u=[{type:"function",function:{name:c,description:s,parameters:n}}]);const l=this.bindTools(u),d=Ut.from(y=>{if(!Yt.isInstance(y))throw new Error("Input is not an AIMessageChunk.");if(!y.tool_calls||y.tool_calls.length===0)throw new Error("No tool calls found in the response.");const v=y.tool_calls.find(b=>b.name===c);if(!v)throw new Error(`No tool call found with name ${c}.`);return v.args});if(!o)return l.pipe(d).withConfig({runName:"StructuredOutput"});const h=On.assign({parsed:(y,v)=>d.invoke(y.raw,v)}),p=On.assign({parsed:()=>null}),g=h.withFallbacks({fallbacks:[p]});return zn.from([{raw:l},g]).withConfig({runName:"StructuredOutputRunnable"})}},Y_=class extends $l{async _generate(t,e,r){const n=await this._call(t,e,r),a=new Lt(n);if(typeof a.content!="string")throw new Error("Cannot generate with a simple chat model when output is not a string.");return{generations:[{text:a.content,message:a}]}}},X_=class extends Se{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,e){const{key:r,input:n}=t,a=this.runnables[r];if(a===void 0)throw new Error(`No runnable associated with key "${r}".`);return a.invoke(n,de(e))}async batch(t,e,r){const n=t.map(d=>d.key),a=t.map(d=>d.input);if(n.find(d=>this.runnables[d]===void 0)!==void 0)throw new Error("One or more keys do not have a corresponding runnable.");const i=n.map(d=>this.runnables[d]),o=this._getOptionsList(e??{},t.length),c=o[0]?.maxConcurrency??r?.maxConcurrency,u=c&&c>0?c:t.length,l=[];for(let d=0;d<a.length;d+=u){const h=a.slice(d,d+u).map((g,y)=>i[y].invoke(g,o[y])),p=await Promise.all(h);l.push(p)}return l.flat()}async stream(t,e){const{key:r,input:n}=t,a=this.runnables[r];if(a===void 0)throw new Error(`No runnable associated with key "${r}".`);return a.stream(n,e)}},Q_=class extends Se{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 r=t.slice(0,-1).map(([a,s])=>[it(a),it(s)]),n=it(t[t.length-1]);return new this({branches:r,default:n})}async _invoke(t,e,r){let n;for(let a=0;a<this.branches.length;a+=1){const[s,i]=this.branches[a];if(await s.invoke(t,we(e,{callbacks:r?.getChild(`condition:${a+1}`)}))){n=await i.invoke(t,we(e,{callbacks:r?.getChild(`branch:${a+1}`)}));break}}return n||(n=await this.default.invoke(t,we(e,{callbacks:r?.getChild("branch:default")}))),n}async invoke(t,e={}){return this._callWithConfig(this._invoke,t,e)}async*_streamIterator(t,e){const n=await(await Je(e))?.handleChainStart(this.toJSON(),ke(t,"input"),e?.runId,void 0,void 0,void 0,e?.runName);let a,s=!0,i;try{for(let o=0;o<this.branches.length;o+=1){const[c,u]=this.branches[o];if(await c.invoke(t,we(e,{callbacks:n?.getChild(`condition:${o+1}`)}))){i=await u.stream(t,we(e,{callbacks:n?.getChild(`branch:${o+1}`)}));for await(const d of i)if(yield d,s)if(a===void 0)a=d;else try{a=Wt(a,d)}catch{a=void 0,s=!1}break}}if(i===void 0){i=await this.default.stream(t,we(e,{callbacks:n?.getChild("branch:default")}));for await(const o of i)if(yield o,s)if(a===void 0)a=o;else try{a=Wt(a,o)}catch{a=void 0,s=!1}}}catch(o){throw await n?.handleChainError(o),o}await n?.handleChainEnd(a??{})}},ey=class extends mr{runnable;inputMessagesKey;outputMessagesKey;historyMessagesKey;getMessageHistory;constructor(t){let e=Ut.from((s,i)=>this._enterHistory(s,i??{})).withConfig({runName:"loadHistory"});const r=t.historyMessagesKey??t.inputMessagesKey;r&&(e=On.assign({[r]:e}).withConfig({runName:"insertHistory"}));const n=e.pipe(t.runnable.withListeners({onEnd:(s,i)=>this._exitHistory(s,i??{})})).withConfig({runName:"RunnableWithMessageHistory"}),a=t.config??{};super({...t,config:a,bound:n}),this.runnable=t.runnable,this.getMessageHistory=t.getMessageHistory,this.inputMessagesKey=t.inputMessagesKey,this.outputMessagesKey=t.outputMessagesKey,this.historyMessagesKey=t.historyMessagesKey}_getInputMessages(t){let e;if(typeof t=="object"&&!Array.isArray(t)&&!Et(t)){let r;this.inputMessagesKey?r=this.inputMessagesKey:Object.keys(t).length===1?r=Object.keys(t)[0]:r="input",Array.isArray(t[r])&&Array.isArray(t[r][0])?e=t[r][0]:e=t[r]}else e=t;if(typeof e=="string")return[new At(e)];if(Array.isArray(e))return e;if(Et(e))return[e];throw new Error(`Expected a string, BaseMessage, or array of BaseMessages.
|
|
82
|
-
Got ${JSON.stringify(e,null,2)}`)}_getOutputMessages(t){let e;if(!Array.isArray(t)&&!Et(t)&&typeof t!="string"){let r;this.outputMessagesKey!==void 0?r=this.outputMessagesKey:Object.keys(t).length===1?r=Object.keys(t)[0]:r="output",t.generations!==void 0?e=t.generations[0][0].message:e=t[r]}else e=t;if(typeof e=="string")return[new Lt(e)];if(Array.isArray(e))return e;if(Et(e))return[e];throw new Error(`Expected a string, BaseMessage, or array of BaseMessages. Received: ${JSON.stringify(e,null,2)}`)}async _enterHistory(t,e){const n=await(e?.configurable?.messageHistory).getMessages();return this.historyMessagesKey===void 0?n.concat(this._getInputMessages(t)):n}async _exitHistory(t,e){const r=e.configurable?.messageHistory;let n;Array.isArray(t.inputs)&&Array.isArray(t.inputs[0])?n=t.inputs[0]:n=t.inputs;let a=this._getInputMessages(n);if(this.historyMessagesKey===void 0){const o=await r.getMessages();a=a.slice(o.length)}const s=t.outputs;if(!s)throw new Error(`Output values from 'Run' undefined. Run: ${JSON.stringify(t,null,2)}`);const i=this._getOutputMessages(s);await r.addMessages([...a,...i])}async _mergeConfig(...t){const e=await super._mergeConfig(...t);if(!e.configurable||!e.configurable.sessionId){const n={[this.inputMessagesKey??"input"]:"foo"},a={configurable:{sessionId:"123"}};throw new Error(`sessionId is required. Pass it in as part of the config argument to .invoke() or .stream()
|
|
83
|
-
eg. chain.invoke(${JSON.stringify(n)}, ${JSON.stringify(a)})`)}const{sessionId:r}=e.configurable;return e.configurable.messageHistory=await this.getMessageHistory(r),e}},ty={};pe(ty,{RouterRunnable:()=>X_,Runnable:()=>Se,RunnableAssign:()=>Ti,RunnableBinding:()=>mr,RunnableBranch:()=>Q_,RunnableEach:()=>c_,RunnableLambda:()=>Ut,RunnableMap:()=>br,RunnableParallel:()=>d_,RunnablePassthrough:()=>On,RunnablePick:()=>fl,RunnableRetry:()=>Ei,RunnableSequence:()=>zn,RunnableToolLike:()=>Bs,RunnableWithFallbacks:()=>hl,RunnableWithMessageHistory:()=>ey,_coerceToRunnable:()=>it,ensureConfig:()=>de,getCallbackManagerForConfig:()=>Je,mergeConfigs:()=>As,patchConfig:()=>we,pickRunnableConfigKeys:()=>Vt});var Pl=class extends Se{parseResultWithPrompt(t,e,r){return this.parseResult(t,r)}_baseMessageToString(t){return typeof t.content=="string"?t.content:this._baseMessageContentToString(t.content)}_baseMessageContentToString(t){return JSON.stringify(t)}async invoke(t,e){return typeof t=="string"?this._callWithConfig(async(r,n)=>this.parseResult([{text:r}],n?.callbacks),t,{...e,runType:"parser"}):this._callWithConfig(async(r,n)=>this.parseResult([{message:r,text:this._baseMessageToString(r)}],n?.callbacks),t,{...e,runType:"parser"})}},Hn=class extends Pl{parseResult(t,e){return this.parse(t[0].text,e)}async parseWithPrompt(t,e,r){return this.parse(t,r)}_type(){throw new Error("_type not implemented")}},Ht=class extends Error{llmOutput;observation;sendToLLM;constructor(t,e,r,n=!1){if(super(t),this.llmOutput=e,this.observation=r,this.sendToLLM=n,n&&(r===void 0||e===void 0))throw new Error("Arguments 'observation' & 'llmOutput' are required if 'sendToLlm' is true");nu(this,"OUTPUT_PARSING_FAILURE")}},Wr=class extends Hn{async*_transform(t){for await(const e of t)typeof e=="string"?yield this.parseResult([{text:e}]):yield this.parseResult([{message:e,text:this._baseMessageToString(e)}])}async*transform(t,e){yield*this._transformStreamWithConfig(t,this._transform.bind(this),{...e,runType:"parser"})}},xi=class extends Wr{diff=!1;constructor(t){super(t),this.diff=t?.diff??this.diff}async*_transform(t){let e,r;for await(const n of t){if(typeof n!="string"&&typeof n.content!="string")throw new Error("Cannot handle non-string output.");let a;if(ei(n)){if(typeof n.content!="string")throw new Error("Cannot handle non-string message output.");a=new Ls({message:n,text:n.content})}else if(Et(n)){if(typeof n.content!="string")throw new Error("Cannot handle non-string message output.");a=new Ls({message:yn(n),text:n.content})}else a=new Br({text:n});r===void 0?r=a:r=r.concat(a);const s=await this.parsePartialResult([r]);s!=null&&!Gt(s,e)&&(this.diff?yield this._diff(e,s):yield s,e=s)}}getFormatInstructions(){return""}},ry=class extends Wr{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""}},Jr=class extends Wr{re;async*_transform(t){let e="";for await(const r of t)if(typeof r=="string"?e+=r:e+=r.content,this.re){const n=[...e.matchAll(this.re)];if(n.length>1){let a=0;for(const s of n.slice(0,-1))yield[s[1]],a+=(s.index??0)+s[0].length;e=e.slice(a)}}else{const n=await this.parse(e);if(n.length>1){for(const a of n.slice(0,-1))yield[a];e=n[n.length-1]}}for(const r of await this.parse(e))yield[r]}},ny=class extends Jr{static lc_name(){return"CommaSeparatedListOutputParser"}lc_namespace=["langchain_core","output_parsers","list"];lc_serializable=!0;async parse(t){try{return t.trim().split(",").map(e=>e.trim())}catch{throw new Ht(`Could not parse output: ${t}`,t)}}getFormatInstructions(){return"Your response should be a list of comma separated values, eg: `foo, bar, baz`"}},ay=class extends Jr{lc_namespace=["langchain_core","output_parsers","list"];length;separator;constructor({length:t,separator:e}){super(...arguments),this.length=t,this.separator=e||","}async parse(t){try{const e=t.trim().split(this.separator).map(r=>r.trim());if(this.length!==void 0&&e.length!==this.length)throw new Ht(`Incorrect number of items. Expected ${this.length}, got ${e.length}.`);return e}catch(e){throw Object.getPrototypeOf(e)===Ht.prototype?e:new Ht(`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\`)`}},sy=class extends Jr{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:
|
|
84
|
-
|
|
85
|
-
1. foo
|
|
86
|
-
|
|
87
|
-
2. bar
|
|
88
|
-
|
|
89
|
-
3. baz`}re=/\d+\.\s([^\n]+)/g;async parse(t){return[...t.matchAll(this.re)??[]].map(e=>e[1])}},iy=class extends Jr{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:
|
|
90
|
-
|
|
91
|
-
1. foo
|
|
92
|
-
|
|
93
|
-
2. bar
|
|
94
|
-
|
|
95
|
-
3. baz`}re=/^\s*[-*]\s([^\n]+)$/gm;async parse(t){return[...t.matchAll(this.re)??[]].map(e=>e[1])}},oy=class extends Wr{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((e,r)=>e+this._messageContentToString(r),"")}},Ml=class extends Hn{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 e=Ws(Object.fromEntries(Object.entries(t).map(([r,n])=>[r,Vs().describe(n)])));return new this(e)}getFormatInstructions(){return`You must format your output as a JSON value that adheres to a given "JSON Schema" instance.
|
|
96
|
-
|
|
97
|
-
"JSON Schema" is a declarative language that allows you to annotate and validate JSON documents.
|
|
98
|
-
|
|
99
|
-
For example, the example "JSON Schema" instance {{"properties": {{"foo": {{"description": "a list of test words", "type": "array", "items": {{"type": "string"}}}}}}, "required": ["foo"]}}
|
|
100
|
-
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.
|
|
101
|
-
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.
|
|
102
|
-
|
|
103
|
-
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!
|
|
104
|
-
|
|
105
|
-
Here is the JSON Schema instance your output must adhere to. Include the enclosing markdown codeblock:
|
|
106
|
-
\`\`\`json
|
|
107
|
-
${JSON.stringify(wr(this.schema))}
|
|
108
|
-
\`\`\`
|
|
109
|
-
`}async parse(t){try{const e=t.trim(),n=(e.match(/^```(?:json)?\s*([\s\S]*?)```/)?.[1]||e.match(/```json\s*([\s\S]*?)```/)?.[1]||e).replace(/"([^"\\]*(\\.[^"\\]*)*)"/g,(a,s)=>`"${s.replace(/\n/g,"\\n")}"`).replace(/\n/g,"");return await yi(this.schema,JSON.parse(n))}catch(e){throw new Ht(`Failed to parse. Text: "${t}". Error: ${e}`,t)}}},Ll=class extends Ml{static lc_name(){return"JsonMarkdownStructuredOutputParser"}getFormatInstructions(t){const e=t?.interpolationDepth??1;if(e<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:
|
|
110
|
-
\`\`\`json
|
|
111
|
-
${this._schemaToInstruction(wr(this.schema)).replaceAll("{","{".repeat(e)).replaceAll("}","}".repeat(e))}
|
|
112
|
-
\`\`\``}_schemaToInstruction(t,e=2){const r=t;if("type"in r){let n=!1,a;if(Array.isArray(r.type)){const o=r.type.findIndex(c=>c==="null");o!==-1&&(n=!0,r.type.splice(o,1)),a=r.type.join(" | ")}else a=r.type;if(r.type==="object"&&r.properties){const o=r.description?` // ${r.description}`:"";return`{
|
|
113
|
-
${Object.entries(r.properties).map(([u,l])=>{const d=r.required?.includes(u)?"":" (optional)";return`${" ".repeat(e)}"${u}": ${this._schemaToInstruction(l,e+2)}${d}`}).join(`
|
|
114
|
-
`)}
|
|
115
|
-
${" ".repeat(e-2)}}${o}`}if(r.type==="array"&&r.items){const o=r.description?` // ${r.description}`:"";return`array[
|
|
116
|
-
${" ".repeat(e)}${this._schemaToInstruction(r.items,e+2)}
|
|
117
|
-
${" ".repeat(e-2)}] ${o}`}const s=n?" (nullable)":"",i=r.description?` // ${r.description}`:"";return`${a}${i}${s}`}if("anyOf"in r)return r.anyOf.map(n=>this._schemaToInstruction(n,e)).join(`
|
|
118
|
-
${" ".repeat(e-2)}`);throw new Error("unsupported schema type")}static fromZodSchema(t){return new this(t)}static fromNamesAndDescriptions(t){const e=Ws(Object.fromEntries(Object.entries(t).map(([r,n])=>[r,Vs().describe(n)])));return new this(e)}},cy=class extends Hn{structuredInputParser;constructor({inputSchema:t}){super(...arguments),this.structuredInputParser=new Ll(t)}async parse(t){let e;try{e=await this.structuredInputParser.parse(t)}catch(r){throw new Ht(`Failed to parse. Text: "${t}". Error: ${r}`,t)}return this.outputProcessor(e)}getFormatInstructions(){return this.structuredInputParser.getFormatInstructions()}},uy={};pe(uy,{applyPatch:()=>pr,compare:()=>mi});var ly=class extends xi{static lc_name(){return"JsonOutputParser"}lc_namespace=["langchain_core","output_parsers"];lc_serializable=!0;_concatOutputChunks(t,e){return this.diff?super._concatOutputChunks(t,e):e}_diff(t,e){if(e)return t?mi(t,e):[{op:"replace",path:"",value:e}]}async parsePartialResult(t){return vs(t[0].text)}async parse(t){return vs(t,JSON.parse)}getFormatInstructions(){return""}};const dy=function(){const t={};t.parser=function(m,f){return new r(m,f)},t.SAXParser=r,t.SAXStream=u,t.createStream=c,t.MAX_BUFFER_LENGTH=64*1024;const e=["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 r(m,f){if(!(this instanceof r))return new r(m,f);var T=this;a(T),T.q=T.c="",T.bufferCheckPosition=t.MAX_BUFFER_LENGTH,T.opt=f||{},T.opt.lowercase=T.opt.lowercase||T.opt.lowercasetags,T.looseCase=T.opt.lowercase?"toLowerCase":"toUpperCase",T.tags=[],T.closed=T.closedRoot=T.sawRoot=!1,T.tag=T.error=null,T.strict=!!m,T.noscript=!!(m||T.opt.noscript),T.state=_.BEGIN,T.strictEntities=T.opt.strictEntities,T.ENTITIES=T.strictEntities?Object.create(t.XML_ENTITIES):Object.create(t.ENTITIES),T.attribList=[],T.opt.xmlns&&(T.ns=Object.create(g)),T.trackPosition=T.opt.position!==!1,T.trackPosition&&(T.position=T.line=T.column=0),ye(T,"onready")}Object.create||(Object.create=function(m){function f(){}f.prototype=m;var T=new f;return T}),Object.keys||(Object.keys=function(m){var f=[];for(var T in m)m.hasOwnProperty(T)&&f.push(T);return f});function n(m){for(var f=Math.max(t.MAX_BUFFER_LENGTH,10),T=0,w=0,se=e.length;w<se;w++){var me=m[e[w]].length;if(me>f)switch(e[w]){case"textNode":Ne(m);break;case"cdata":oe(m,"oncdata",m.cdata),m.cdata="";break;case"script":oe(m,"onscript",m.script),m.script="";break;default:R(m,"Max buffer length exceeded: "+e[w])}T=Math.max(T,me)}var _e=t.MAX_BUFFER_LENGTH-T;m.bufferCheckPosition=_e+m.position}function a(m){for(var f=0,T=e.length;f<T;f++)m[e[f]]=""}function s(m){Ne(m),m.cdata!==""&&(oe(m,"oncdata",m.cdata),m.cdata=""),m.script!==""&&(oe(m,"onscript",m.script),m.script="")}r.prototype={end:function(){A(this)},write:ce,resume:function(){return this.error=null,this},close:function(){return this.write(null)},flush:function(){s(this)}};var i=ReadableStream;i||(i=function(){});var o=t.EVENTS.filter(function(m){return m!=="error"&&m!=="end"});function c(m,f){return new u(m,f)}function u(m,f){if(!(this instanceof u))return new u(m,f);i.apply(this),this._parser=new r(m,f),this.writable=!0,this.readable=!0;var T=this;this._parser.onend=function(){T.emit("end")},this._parser.onerror=function(w){T.emit("error",w),T._parser.error=null},this._decoder=null,o.forEach(function(w){Object.defineProperty(T,"on"+w,{get:function(){return T._parser["on"+w]},set:function(se){if(!se)return T.removeAllListeners(w),T._parser["on"+w]=se,se;T.on(w,se)},enumerable:!0,configurable:!1})})}u.prototype=Object.create(i.prototype,{constructor:{value:u}}),u.prototype.write=function(m){return this._parser.write(m.toString()),this.emit("data",m),!0},u.prototype.end=function(m){return m&&m.length&&this.write(m),this._parser.end(),!0},u.prototype.on=function(m,f){var T=this;return!T._parser["on"+m]&&o.indexOf(m)!==-1&&(T._parser["on"+m]=function(){var w=arguments.length===1?[arguments[0]]:Array.apply(null,arguments);w.splice(0,0,m),T.emit.apply(T,w)}),i.prototype.on.call(T,m,f)};var l="[CDATA[",d="DOCTYPE",h="http://www.w3.org/XML/1998/namespace",p="http://www.w3.org/2000/xmlns/",g={xml:h,xmlns:p},y=/[:_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-]/,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]/,S=/[#:_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 E(m){return m===" "||m===`
|
|
119
|
-
`||m==="\r"||m===" "}function k(m){return m==='"'||m==="'"}function C(m){return m===">"||E(m)}function F(m,f){return m.test(f)}function W(m,f){return!F(m,f)}var _=0;t.STATE={BEGIN:_++,BEGIN_WHITESPACE:_++,TEXT:_++,TEXT_ENTITY:_++,OPEN_WAKA:_++,SGML_DECL:_++,SGML_DECL_QUOTED:_++,DOCTYPE:_++,DOCTYPE_QUOTED:_++,DOCTYPE_DTD:_++,DOCTYPE_DTD_QUOTED:_++,COMMENT_STARTING:_++,COMMENT:_++,COMMENT_ENDING:_++,COMMENT_ENDED:_++,CDATA:_++,CDATA_ENDING:_++,CDATA_ENDING_2:_++,PROC_INST:_++,PROC_INST_BODY:_++,PROC_INST_ENDING:_++,OPEN_TAG:_++,OPEN_TAG_SLASH:_++,ATTRIB:_++,ATTRIB_NAME:_++,ATTRIB_NAME_SAW_WHITE:_++,ATTRIB_VALUE:_++,ATTRIB_VALUE_QUOTED:_++,ATTRIB_VALUE_CLOSED:_++,ATTRIB_VALUE_UNQUOTED:_++,ATTRIB_VALUE_ENTITY_Q:_++,ATTRIB_VALUE_ENTITY_U:_++,CLOSE_TAG:_++,CLOSE_TAG_SAW_WHITE:_++,SCRIPT:_++,SCRIPT_ENDING:_++},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(m){var f=t.ENTITIES[m],T=typeof f=="number"?String.fromCharCode(f):f;t.ENTITIES[m]=T});for(var ge in t.STATE)t.STATE[t.STATE[ge]]=ge;_=t.STATE;function ye(m,f,T){m[f]&&m[f](T)}function oe(m,f,T){m.textNode&&Ne(m),ye(m,f,T)}function Ne(m){m.textNode=vt(m.opt,m.textNode),m.textNode&&ye(m,"ontext",m.textNode),m.textNode=""}function vt(m,f){return m.trim&&(f=f.trim()),m.normalize&&(f=f.replace(/\s+/g," ")),f}function R(m,f){return Ne(m),m.trackPosition&&(f+=`
|
|
120
|
-
Line: `+m.line+`
|
|
121
|
-
Column: `+m.column+`
|
|
122
|
-
Char: `+m.c),f=new Error(f),m.error=f,ye(m,"onerror",f),m}function A(m){return m.sawRoot&&!m.closedRoot&&O(m,"Unclosed root tag"),m.state!==_.BEGIN&&m.state!==_.BEGIN_WHITESPACE&&m.state!==_.TEXT&&R(m,"Unexpected end"),Ne(m),m.c="",m.closed=!0,ye(m,"onend"),r.call(m,m.strict,m.opt),m}function O(m,f){if(typeof m!="object"||!(m instanceof r))throw new Error("bad call to strictFail");m.strict&&R(m,f)}function B(m){m.strict||(m.tagName=m.tagName[m.looseCase]());var f=m.tags[m.tags.length-1]||m,T=m.tag={name:m.tagName,attributes:{}};m.opt.xmlns&&(T.ns=f.ns),m.attribList.length=0,oe(m,"onopentagstart",T)}function q(m,f){var T=m.indexOf(":"),w=T<0?["",m]:m.split(":"),se=w[0],me=w[1];return f&&m==="xmlns"&&(se="xmlns",me=""),{prefix:se,local:me}}function U(m){if(m.strict||(m.attribName=m.attribName[m.looseCase]()),m.attribList.indexOf(m.attribName)!==-1||m.tag.attributes.hasOwnProperty(m.attribName)){m.attribName=m.attribValue="";return}if(m.opt.xmlns){var f=q(m.attribName,!0),T=f.prefix,w=f.local;if(T==="xmlns")if(w==="xml"&&m.attribValue!==h)O(m,"xml: prefix must be bound to "+h+`
|
|
123
|
-
Actual: `+m.attribValue);else if(w==="xmlns"&&m.attribValue!==p)O(m,"xmlns: prefix must be bound to "+p+`
|
|
124
|
-
Actual: `+m.attribValue);else{var se=m.tag,me=m.tags[m.tags.length-1]||m;se.ns===me.ns&&(se.ns=Object.create(me.ns)),se.ns[w]=m.attribValue}m.attribList.push([m.attribName,m.attribValue])}else m.tag.attributes[m.attribName]=m.attribValue,oe(m,"onattribute",{name:m.attribName,value:m.attribValue});m.attribName=m.attribValue=""}function V(m,f){if(m.opt.xmlns){var T=m.tag,w=q(m.tagName);T.prefix=w.prefix,T.local=w.local,T.uri=T.ns[w.prefix]||"",T.prefix&&!T.uri&&(O(m,"Unbound namespace prefix: "+JSON.stringify(m.tagName)),T.uri=w.prefix);var se=m.tags[m.tags.length-1]||m;T.ns&&se.ns!==T.ns&&Object.keys(T.ns).forEach(function(Ft){oe(m,"onopennamespace",{prefix:Ft,uri:T.ns[Ft]})});for(var me=0,_e=m.attribList.length;me<_e;me++){var xe=m.attribList[me],$e=xe[0],Qe=xe[1],be=q($e,!0),Ke=be.prefix,Qt=be.local,Kr=Ke===""?"":T.ns[Ke]||"",P={name:$e,value:Qe,prefix:Ke,local:Qt,uri:Kr};Ke&&Ke!=="xmlns"&&!Kr&&(O(m,"Unbound namespace prefix: "+JSON.stringify(Ke)),P.uri=Ke),m.tag.attributes[$e]=P,oe(m,"onattribute",P)}m.attribList.length=0}m.tag.isSelfClosing=!!f,m.sawRoot=!0,m.tags.push(m.tag),oe(m,"onopentag",m.tag),f||(!m.noscript&&m.tagName.toLowerCase()==="script"?m.state=_.SCRIPT:m.state=_.TEXT,m.tag=null,m.tagName=""),m.attribName=m.attribValue="",m.attribList.length=0}function ae(m){if(!m.tagName){O(m,"Weird empty close tag."),m.textNode+="</>",m.state=_.TEXT;return}if(m.script){if(m.tagName!=="script"){m.script+="</"+m.tagName+">",m.tagName="",m.state=_.SCRIPT;return}oe(m,"onscript",m.script),m.script=""}var f=m.tags.length,T=m.tagName;m.strict||(T=T[m.looseCase]());for(var w=T;f--;){var se=m.tags[f];if(se.name!==w)O(m,"Unexpected close tag");else break}if(f<0){O(m,"Unmatched closing tag: "+m.tagName),m.textNode+="</"+m.tagName+">",m.state=_.TEXT;return}m.tagName=T;for(var me=m.tags.length;me-- >f;){var _e=m.tag=m.tags.pop();m.tagName=m.tag.name,oe(m,"onclosetag",m.tagName);var xe={};for(var $e in _e.ns)xe[$e]=_e.ns[$e];var Qe=m.tags[m.tags.length-1]||m;m.opt.xmlns&&_e.ns!==Qe.ns&&Object.keys(_e.ns).forEach(function(be){var Ke=_e.ns[be];oe(m,"onclosenamespace",{prefix:be,uri:Ke})})}f===0&&(m.closedRoot=!0),m.tagName=m.attribValue=m.attribName="",m.attribList.length=0,m.state=_.TEXT}function ee(m){var f=m.entity,T=f.toLowerCase(),w,se="";return m.ENTITIES[f]?m.ENTITIES[f]:m.ENTITIES[T]?m.ENTITIES[T]:(f=T,f.charAt(0)==="#"&&(f.charAt(1)==="x"?(f=f.slice(2),w=parseInt(f,16),se=w.toString(16)):(f=f.slice(1),w=parseInt(f,10),se=w.toString(10))),f=f.replace(/^0+/,""),isNaN(w)||se.toLowerCase()!==f?(O(m,"Invalid character entity"),"&"+m.entity+";"):String.fromCodePoint(w))}function le(m,f){f==="<"?(m.state=_.OPEN_WAKA,m.startTagPosition=m.position):E(f)||(O(m,"Non-whitespace before first tag."),m.textNode=f,m.state=_.TEXT)}function Te(m,f){var T="";return f<m.length&&(T=m.charAt(f)),T}function ce(m){var f=this;if(this.error)throw this.error;if(f.closed)return R(f,"Cannot write after close. Assign an onready handler.");if(m===null)return A(f);typeof m=="object"&&(m=m.toString());for(var T=0,w="";w=Te(m,T++),f.c=w,!!w;)switch(f.trackPosition&&(f.position++,w===`
|
|
125
|
-
`?(f.line++,f.column=0):f.column++),f.state){case _.BEGIN:if(f.state=_.BEGIN_WHITESPACE,w==="\uFEFF")continue;le(f,w);continue;case _.BEGIN_WHITESPACE:le(f,w);continue;case _.TEXT:if(f.sawRoot&&!f.closedRoot){for(var se=T-1;w&&w!=="<"&&w!=="&";)w=Te(m,T++),w&&f.trackPosition&&(f.position++,w===`
|
|
126
|
-
`?(f.line++,f.column=0):f.column++);f.textNode+=m.substring(se,T-1)}w==="<"&&!(f.sawRoot&&f.closedRoot&&!f.strict)?(f.state=_.OPEN_WAKA,f.startTagPosition=f.position):(!E(w)&&(!f.sawRoot||f.closedRoot)&&O(f,"Text data outside of root node."),w==="&"?f.state=_.TEXT_ENTITY:f.textNode+=w);continue;case _.SCRIPT:w==="<"?f.state=_.SCRIPT_ENDING:f.script+=w;continue;case _.SCRIPT_ENDING:w==="/"?f.state=_.CLOSE_TAG:(f.script+="<"+w,f.state=_.SCRIPT);continue;case _.OPEN_WAKA:if(w==="!")f.state=_.SGML_DECL,f.sgmlDecl="";else if(!E(w))if(F(y,w))f.state=_.OPEN_TAG,f.tagName=w;else if(w==="/")f.state=_.CLOSE_TAG,f.tagName="";else if(w==="?")f.state=_.PROC_INST,f.procInstName=f.procInstBody="";else{if(O(f,"Unencoded <"),f.startTagPosition+1<f.position){var me=f.position-f.startTagPosition;w=new Array(me).join(" ")+w}f.textNode+="<"+w,f.state=_.TEXT}continue;case _.SGML_DECL:(f.sgmlDecl+w).toUpperCase()===l?(oe(f,"onopencdata"),f.state=_.CDATA,f.sgmlDecl="",f.cdata=""):f.sgmlDecl+w==="--"?(f.state=_.COMMENT,f.comment="",f.sgmlDecl=""):(f.sgmlDecl+w).toUpperCase()===d?(f.state=_.DOCTYPE,(f.doctype||f.sawRoot)&&O(f,"Inappropriately located doctype declaration"),f.doctype="",f.sgmlDecl=""):w===">"?(oe(f,"onsgmldeclaration",f.sgmlDecl),f.sgmlDecl="",f.state=_.TEXT):(k(w)&&(f.state=_.SGML_DECL_QUOTED),f.sgmlDecl+=w);continue;case _.SGML_DECL_QUOTED:w===f.q&&(f.state=_.SGML_DECL,f.q=""),f.sgmlDecl+=w;continue;case _.DOCTYPE:w===">"?(f.state=_.TEXT,oe(f,"ondoctype",f.doctype),f.doctype=!0):(f.doctype+=w,w==="["?f.state=_.DOCTYPE_DTD:k(w)&&(f.state=_.DOCTYPE_QUOTED,f.q=w));continue;case _.DOCTYPE_QUOTED:f.doctype+=w,w===f.q&&(f.q="",f.state=_.DOCTYPE);continue;case _.DOCTYPE_DTD:f.doctype+=w,w==="]"?f.state=_.DOCTYPE:k(w)&&(f.state=_.DOCTYPE_DTD_QUOTED,f.q=w);continue;case _.DOCTYPE_DTD_QUOTED:f.doctype+=w,w===f.q&&(f.state=_.DOCTYPE_DTD,f.q="");continue;case _.COMMENT:w==="-"?f.state=_.COMMENT_ENDING:f.comment+=w;continue;case _.COMMENT_ENDING:w==="-"?(f.state=_.COMMENT_ENDED,f.comment=vt(f.opt,f.comment),f.comment&&oe(f,"oncomment",f.comment),f.comment=""):(f.comment+="-"+w,f.state=_.COMMENT);continue;case _.COMMENT_ENDED:w!==">"?(O(f,"Malformed comment"),f.comment+="--"+w,f.state=_.COMMENT):f.state=_.TEXT;continue;case _.CDATA:w==="]"?f.state=_.CDATA_ENDING:f.cdata+=w;continue;case _.CDATA_ENDING:w==="]"?f.state=_.CDATA_ENDING_2:(f.cdata+="]"+w,f.state=_.CDATA);continue;case _.CDATA_ENDING_2:w===">"?(f.cdata&&oe(f,"oncdata",f.cdata),oe(f,"onclosecdata"),f.cdata="",f.state=_.TEXT):w==="]"?f.cdata+="]":(f.cdata+="]]"+w,f.state=_.CDATA);continue;case _.PROC_INST:w==="?"?f.state=_.PROC_INST_ENDING:E(w)?f.state=_.PROC_INST_BODY:f.procInstName+=w;continue;case _.PROC_INST_BODY:if(!f.procInstBody&&E(w))continue;w==="?"?f.state=_.PROC_INST_ENDING:f.procInstBody+=w;continue;case _.PROC_INST_ENDING:w===">"?(oe(f,"onprocessinginstruction",{name:f.procInstName,body:f.procInstBody}),f.procInstName=f.procInstBody="",f.state=_.TEXT):(f.procInstBody+="?"+w,f.state=_.PROC_INST_BODY);continue;case _.OPEN_TAG:F(v,w)?f.tagName+=w:(B(f),w===">"?V(f):w==="/"?f.state=_.OPEN_TAG_SLASH:(E(w)||O(f,"Invalid character in tag name"),f.state=_.ATTRIB));continue;case _.OPEN_TAG_SLASH:w===">"?(V(f,!0),ae(f)):(O(f,"Forward-slash in opening tag not followed by >"),f.state=_.ATTRIB);continue;case _.ATTRIB:if(E(w))continue;w===">"?V(f):w==="/"?f.state=_.OPEN_TAG_SLASH:F(y,w)?(f.attribName=w,f.attribValue="",f.state=_.ATTRIB_NAME):O(f,"Invalid attribute name");continue;case _.ATTRIB_NAME:w==="="?f.state=_.ATTRIB_VALUE:w===">"?(O(f,"Attribute without value"),f.attribValue=f.attribName,U(f),V(f)):E(w)?f.state=_.ATTRIB_NAME_SAW_WHITE:F(v,w)?f.attribName+=w:O(f,"Invalid attribute name");continue;case _.ATTRIB_NAME_SAW_WHITE:if(w==="=")f.state=_.ATTRIB_VALUE;else{if(E(w))continue;O(f,"Attribute without value"),f.tag.attributes[f.attribName]="",f.attribValue="",oe(f,"onattribute",{name:f.attribName,value:""}),f.attribName="",w===">"?V(f):F(y,w)?(f.attribName=w,f.state=_.ATTRIB_NAME):(O(f,"Invalid attribute name"),f.state=_.ATTRIB)}continue;case _.ATTRIB_VALUE:if(E(w))continue;k(w)?(f.q=w,f.state=_.ATTRIB_VALUE_QUOTED):(O(f,"Unquoted attribute value"),f.state=_.ATTRIB_VALUE_UNQUOTED,f.attribValue=w);continue;case _.ATTRIB_VALUE_QUOTED:if(w!==f.q){w==="&"?f.state=_.ATTRIB_VALUE_ENTITY_Q:f.attribValue+=w;continue}U(f),f.q="",f.state=_.ATTRIB_VALUE_CLOSED;continue;case _.ATTRIB_VALUE_CLOSED:E(w)?f.state=_.ATTRIB:w===">"?V(f):w==="/"?f.state=_.OPEN_TAG_SLASH:F(y,w)?(O(f,"No whitespace between attributes"),f.attribName=w,f.attribValue="",f.state=_.ATTRIB_NAME):O(f,"Invalid attribute name");continue;case _.ATTRIB_VALUE_UNQUOTED:if(!C(w)){w==="&"?f.state=_.ATTRIB_VALUE_ENTITY_U:f.attribValue+=w;continue}U(f),w===">"?V(f):f.state=_.ATTRIB;continue;case _.CLOSE_TAG:if(f.tagName)w===">"?ae(f):F(v,w)?f.tagName+=w:f.script?(f.script+="</"+f.tagName,f.tagName="",f.state=_.SCRIPT):(E(w)||O(f,"Invalid tagname in closing tag"),f.state=_.CLOSE_TAG_SAW_WHITE);else{if(E(w))continue;W(y,w)?f.script?(f.script+="</"+w,f.state=_.SCRIPT):O(f,"Invalid tagname in closing tag."):f.tagName=w}continue;case _.CLOSE_TAG_SAW_WHITE:if(E(w))continue;w===">"?ae(f):O(f,"Invalid characters in closing tag");continue;case _.TEXT_ENTITY:case _.ATTRIB_VALUE_ENTITY_Q:case _.ATTRIB_VALUE_ENTITY_U:var _e,xe;switch(f.state){case _.TEXT_ENTITY:_e=_.TEXT,xe="textNode";break;case _.ATTRIB_VALUE_ENTITY_Q:_e=_.ATTRIB_VALUE_QUOTED,xe="attribValue";break;case _.ATTRIB_VALUE_ENTITY_U:_e=_.ATTRIB_VALUE_UNQUOTED,xe="attribValue";break}if(w===";")if(f.opt.unparsedEntities){var $e=ee(f);f.entity="",f.state=_e,f.write($e)}else f[xe]+=ee(f),f.entity="",f.state=_e;else F(f.entity.length?S:b,w)?f.entity+=w:(O(f,"Invalid character in entity name"),f[xe]+="&"+f.entity+w,f.entity="",f.state=_e);continue;default:throw new Error(f,"Unknown state: "+f.state)}return f.position>=f.bufferCheckPosition&&n(f),f}return String.fromCodePoint||(function(){var m=String.fromCharCode,f=Math.floor,T=function(){var w=16384,se=[],me,_e,xe=-1,$e=arguments.length;if(!$e)return"";for(var Qe="";++xe<$e;){var be=Number(arguments[xe]);if(!isFinite(be)||be<0||be>1114111||f(be)!==be)throw RangeError("Invalid code point: "+be);be<=65535?se.push(be):(be-=65536,me=(be>>10)+55296,_e=be%1024+56320,se.push(me,_e)),(xe+1===$e||se.length>w)&&(Qe+=m.apply(null,se),se.length=0)}return Qe};Object.defineProperty?Object.defineProperty(String,"fromCodePoint",{value:T,configurable:!0,writable:!0}):String.fromCodePoint=T})(),t},hy=dy(),qs=`The output should be formatted as a XML file.
|
|
127
|
-
1. Output should conform to the tags below.
|
|
128
|
-
2. If tags are not given, make them on your own.
|
|
129
|
-
3. Remember to always open and close all the tags.
|
|
130
|
-
|
|
131
|
-
As an example, for the tags ["foo", "bar", "baz"]:
|
|
132
|
-
1. String "<foo>
|
|
133
|
-
<bar>
|
|
134
|
-
<baz></baz>
|
|
135
|
-
</bar>
|
|
136
|
-
</foo>" is a well-formatted instance of the schema.
|
|
137
|
-
2. String "<foo>
|
|
138
|
-
<bar>
|
|
139
|
-
</foo>" is a badly-formatted instance.
|
|
140
|
-
3. String "<foo>
|
|
141
|
-
<tag>
|
|
142
|
-
</tag>
|
|
143
|
-
</foo>" is a badly-formatted instance.
|
|
144
|
-
|
|
145
|
-
Here are the output tags:
|
|
146
|
-
\`\`\`
|
|
147
|
-
{tags}
|
|
148
|
-
\`\`\``;var fy=class extends xi{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,e){if(e)return t?mi(t,e):[{op:"replace",path:"",value:e}]}async parsePartialResult(t){return Gs(t[0].text)}async parse(t){return Gs(t)}getFormatInstructions(){return!!(this.tags&&this.tags.length>0)?qs.replace("{tags}",this.tags?.join(", ")??""):qs}};const py=t=>t.split(`
|
|
149
|
-
`).map(e=>e.replace(/^\s+/,"")).join(`
|
|
150
|
-
`).trim(),jl=t=>{if(Object.keys(t).length===0)return{};const e={};return t.children.length>0?(e[t.name]=t.children.map(jl),e):(e[t.name]=t.text??void 0,e)};function Gs(t){const e=py(t),r=hy.parser(!0);let n={};const a=[];r.onopentag=o=>{const c={name:o.name,attributes:o.attributes,children:[],text:"",isSelfClosing:o.isSelfClosing};a.length>0?a[a.length-1].children.push(c):n=c,o.isSelfClosing||a.push(c)},r.onclosetag=()=>{if(a.length>0){const o=a.pop();a.length===0&&o&&(n=o)}},r.ontext=o=>{if(a.length>0){const c=a[a.length-1];c.text+=o}},r.onattribute=o=>{if(a.length>0){const c=a[a.length-1];c.attributes[o.name]=o.value}};const s=/```(xml)?(.*)```/s.exec(e),i=s?s[2]:e;return r.write(i).close(),n&&n.name==="?xml"&&(n=n.children[0]),jl(n)}var my={};pe(my,{AsymmetricStructuredOutputParser:()=>cy,BaseCumulativeTransformOutputParser:()=>xi,BaseLLMOutputParser:()=>Pl,BaseOutputParser:()=>Hn,BaseTransformOutputParser:()=>Wr,BytesOutputParser:()=>ry,CommaSeparatedListOutputParser:()=>ny,CustomListOutputParser:()=>ay,JsonMarkdownStructuredOutputParser:()=>Ll,JsonOutputParser:()=>ly,ListOutputParser:()=>Jr,MarkdownListOutputParser:()=>iy,NumberedListOutputParser:()=>sy,OutputParserException:()=>Ht,StringOutputParser:()=>oy,StructuredOutputParser:()=>Ml,XMLOutputParser:()=>fy,XML_FORMAT_INSTRUCTIONS:()=>qs,parseJsonMarkdown:()=>vs,parsePartialJson:()=>ri,parseXMLMarkdown:()=>Gs});export{zn as $,Fn as A,xi as B,mt as C,It as D,Vt as E,En as F,Br as G,wr as H,Et as I,Lt as J,Ls as K,Yt as L,qr as M,Xc as N,Ht as O,Z_ as P,Mt as Q,Ms as R,vd as S,lh as T,ys as U,Pl as V,$l as W,$t as X,ly as Y,On as Z,pe as _,tu as a,rm as a$,At as a0,S_ as a1,x as a2,Re as a3,Ie as a4,Ml as a5,vi as a6,Ut as a7,$n as a8,fr as a9,vr as aA,Hn as aB,E_ as aC,z_ as aD,cm as aE,r_ as aF,uy as aG,O_ as aH,T_ as aI,vh as aJ,wm as aK,Wp as aL,mm as aM,zp as aN,Dp as aO,im as aP,n_ as aQ,ty as aR,I_ as aS,_m as aT,my as aU,Jd as aV,b_ as aW,Od as aX,K_ as aY,G_ as aZ,Xp as a_,Nn as aa,kn as ab,Rn as ac,yd as ad,dh as ae,Th as af,hu as ag,bh as ah,mr as ai,Xt as aj,ot as ak,Rm as al,t_ as am,Xi as an,hr as ao,Se as ap,Dr as aq,Tl as ar,mi as as,bl as at,nu as au,x_ as av,jt as aw,Or as ax,xt as ay,El as az,Nl as b,Ch as b0,k_ as b1,Ys as b2,Ad as b3,ky as b4,it as b5,Gr as b6,ei as b7,Je as b8,bi as b9,f_ as bA,Kt as bB,Rr as ba,$m as bb,js as bc,Cm as bd,Nm as be,Om as bf,De as bg,md as bh,ie as bi,Ty as bj,xy as bk,by as bl,zi as bm,Lm as bn,Iy as bo,Ey as bp,vy as bq,Oy as br,Am as bs,_n as bt,Rl as bu,m_ as bv,Ay as bw,Sy as bx,wy as by,yy as bz,fu as c,Wt as d,nm as e,Cl as f,de as g,au as h,xm as i,Vr as j,yi as k,Ry as l,As as m,Yc as n,_r as o,ri as p,yl as q,gl as r,_l as s,vl as t,Ws as u,ve as v,Vs as w,Yu as x,dn as y,we as z};
|