@elizaos/core 1.5.9 → 1.5.10-beta.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.
|
@@ -82,7 +82,7 @@ Message: ${Array.isArray(O.detail)?O.detail.join(`
|
|
|
82
82
|
https://smith.langchain.com/prompts`);let[_,P,O]=vK(q);if(!await this._currentTenantIsOwner(_))throw await this._ownerConflictError("create a prompt",_);let Y={repo_handle:P,...$?.description&&{description:$.description},...$?.readme&&{readme:$.readme},...$?.tags&&{tags:$.tags},is_public:!!$?.isPublic},H=JSON.stringify(Y),v=await this.caller.call(async()=>{let Z=await this._fetch(`${this.apiUrl}/repos/`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:H});return await q$(Z,"create prompt"),Z}),{repo:X}=await v.json();return X}async createCommit(q,$,K){if(!await this.promptExists(q))throw Error("Prompt does not exist, you must create it first.");let[_,P,O]=vK(q),Y=K?.parentCommitHash==="latest"||!K?.parentCommitHash?await this._getLatestCommitHash(`${_}/${P}`):K?.parentCommitHash,H={manifest:JSON.parse(JSON.stringify($)),parent_commit:Y},v=JSON.stringify(H),Z=await(await this.caller.call(async()=>{let k=await this._fetch(`${this.apiUrl}/commits/${_}/${P}`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:v});return await q$(k,"create commit"),k})).json();return this._getPromptUrl(`${_}/${P}${Z.commit_hash?`:${Z.commit_hash}`:""}`)}async updateExamplesMultipart(q,$=[]){return this._updateExamplesMultipart(q,$)}async _updateExamplesMultipart(q,$=[]){if(!await this._getDatasetExamplesMultiPartSupport())throw Error("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version.");let K=new FormData;for(let O of $){let Y=O.id,H={...O.metadata&&{metadata:O.metadata},...O.split&&{split:O.split}},v=U8(H,`Serializing body for example with id: ${Y}`),X=new Blob([v],{type:"application/json"});if(K.append(Y,X),O.inputs){let Z=U8(O.inputs,`Serializing inputs for example with id: ${Y}`),k=new Blob([Z],{type:"application/json"});K.append(`${Y}.inputs`,k)}if(O.outputs){let Z=U8(O.outputs,`Serializing outputs whle updating example with id: ${Y}`),k=new Blob([Z],{type:"application/json"});K.append(`${Y}.outputs`,k)}if(O.attachments)for(let[Z,k]of Object.entries(O.attachments)){let G,S;if(Array.isArray(k))[G,S]=k;else G=k.mimeType,S=k.data;let N=new Blob([S],{type:`${G}; length=${S.byteLength}`});K.append(`${Y}.attachment.${Z}`,N)}if(O.attachments_operations){let Z=U8(O.attachments_operations,`Serializing attachments while updating example with id: ${Y}`),k=new Blob([Z],{type:"application/json"});K.append(`${Y}.attachments_operations`,k)}}let _=q??$[0]?.dataset_id;return(await this.caller.call(async()=>{let O=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${_}/examples`)}`,{method:"PATCH",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:K});return await q$(O,"update examples"),O})).json()}async uploadExamplesMultipart(q,$=[]){return this._uploadExamplesMultipart(q,$)}async _uploadExamplesMultipart(q,$=[]){if(!await this._getDatasetExamplesMultiPartSupport())throw Error("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version.");let K=new FormData;for(let P of $){let O=(P.id??JK()).toString(),Y={created_at:P.created_at,...P.metadata&&{metadata:P.metadata},...P.split&&{split:P.split},...P.source_run_id&&{source_run_id:P.source_run_id},...P.use_source_run_io&&{use_source_run_io:P.use_source_run_io},...P.use_source_run_attachments&&{use_source_run_attachments:P.use_source_run_attachments}},H=U8(Y,`Serializing body for uploaded example with id: ${O}`),v=new Blob([H],{type:"application/json"});if(K.append(O,v),P.inputs){let X=U8(P.inputs,`Serializing inputs for uploaded example with id: ${O}`),Z=new Blob([X],{type:"application/json"});K.append(`${O}.inputs`,Z)}if(P.outputs){let X=U8(P.outputs,`Serializing outputs for uploaded example with id: ${O}`),Z=new Blob([X],{type:"application/json"});K.append(`${O}.outputs`,Z)}if(P.attachments)for(let[X,Z]of Object.entries(P.attachments)){let k,G;if(Array.isArray(Z))[k,G]=Z;else k=Z.mimeType,G=Z.data;let S=new Blob([G],{type:`${k}; length=${G.byteLength}`});K.append(`${O}.attachment.${X}`,S)}}return(await this.caller.call(async()=>{let P=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${q}/examples`)}`,{method:"POST",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:K});return await q$(P,"upload examples"),P})).json()}async updatePrompt(q,$){if(!await this.promptExists(q))throw Error("Prompt does not exist, you must create it first.");let[K,_]=vK(q);if(!await this._currentTenantIsOwner(K))throw await this._ownerConflictError("update a prompt",K);let P={};if($?.description!==void 0)P.description=$.description;if($?.readme!==void 0)P.readme=$.readme;if($?.tags!==void 0)P.tags=$.tags;if($?.isPublic!==void 0)P.is_public=$.isPublic;if($?.isArchived!==void 0)P.is_archived=$.isArchived;if(Object.keys(P).length===0)throw Error("No valid update options provided");let O=JSON.stringify(P);return(await this.caller.call(async()=>{let H=await this._fetch(`${this.apiUrl}/repos/${K}/${_}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:O});return await q$(H,"update prompt"),H})).json()}async deletePrompt(q){if(!await this.promptExists(q))throw Error("Prompt does not exist, you must create it first.");let[$,K,_]=vK(q);if(!await this._currentTenantIsOwner($))throw await this._ownerConflictError("delete a prompt",$);return(await this.caller.call(async()=>{let O=await this._fetch(`${this.apiUrl}/repos/${$}/${K}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await q$(O,"delete prompt"),O})).json()}async pullPromptCommit(q,$){let[K,_,P]=vK(q),Y=await(await this.caller.call(async()=>{let H=await this._fetch(`${this.apiUrl}/commits/${K}/${_}/${P}${$?.includeModel?"?include_model=true":""}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await q$(H,"pull prompt commit"),H})).json();return{owner:K,repo:_,commit_hash:Y.commit_hash,manifest:Y.manifest,examples:Y.examples}}async _pullPrompt(q,$){let K=await this.pullPromptCommit(q,{includeModel:$?.includeModel});return JSON.stringify(K.manifest)}async pushPrompt(q,$){if(await this.promptExists(q)){if($&&Object.keys($).some((_)=>_!=="object"))await this.updatePrompt(q,{description:$?.description,readme:$?.readme,tags:$?.tags,isPublic:$?.isPublic})}else await this.createPrompt(q,{description:$?.description,readme:$?.readme,tags:$?.tags,isPublic:$?.isPublic});if(!$?.object)return await this._getPromptUrl(q);return await this.createCommit(q,$?.object,{parentCommitHash:$?.parentCommitHash})}async clonePublicDataset(q,$={}){let{sourceApiUrl:K=this.apiUrl,datasetName:_}=$,[P,O]=this.parseTokenOrUrl(q,K),Y=new lK({apiUrl:P,apiKey:"placeholder"}),H=await Y.readSharedDataset(O),v=_||H.name;try{if(await this.hasDataset({datasetId:v})){console.log(`Dataset ${v} already exists in your tenant. Skipping.`);return}}catch(k){}let X=await Y.listSharedExamples(O),Z=await this.createDataset(v,{description:H.description,dataType:H.data_type||"kv",inputsSchema:H.inputs_schema_definition??void 0,outputsSchema:H.outputs_schema_definition??void 0});try{await this.createExamples({inputs:X.map((k)=>k.inputs),outputs:X.flatMap((k)=>k.outputs?[k.outputs]:[]),datasetId:Z.id})}catch(k){throw console.error(`An error occurred while creating dataset ${v}. You should delete it manually.`),k}}parseTokenOrUrl(q,$,K=2,_="dataset"){try{return W$(q),[$,q]}catch(P){}try{let O=new URL(q).pathname.split("/").filter((Y)=>Y!=="");if(O.length>=K){let Y=O[O.length-K];return[$,Y]}else throw Error(`Invalid public ${_} URL: ${q}`)}catch(P){throw Error(`Invalid public ${_} URL or token: ${q}`)}}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();if(await Promise.all([...this.autoBatchQueue.items.map(({itemPromise:q})=>q),this.batchIngestCaller.queue.onIdle()]),this.langSmithToOTELTranslator!==void 0)await LO()?.DEFAULT_LANGSMITH_SPAN_PROCESSOR?.forceFlush()}}function iH(q){return"dataset_id"in q||"dataset_name"in q}var FH=(q)=>{if(q!==void 0)return q;return!!["TRACING_V2","TRACING"].find((K)=>B$(K)==="true")};var m9=Symbol.for("lc:context_variables");function DM(q){return q.replace(/[-:.]/g,"")}function WY(q,$,K=1){let _=K.toFixed(0).slice(0,3).padStart(3,"0"),P=`${new Date(q).toISOString().slice(0,-1)}${_}Z`;return{dottedOrder:DM(P)+$,microsecondPrecisionDatestring:P}}class c9{constructor(q,$,K,_){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=q,this.tags=$,this.project_name=K,this.replicas=_}static fromHeader(q){let $=q.split(","),K={},_=[],P,O;for(let Y of $){let[H,v]=Y.split("="),X=decodeURIComponent(v);if(H==="langsmith-metadata")K=JSON.parse(X);else if(H==="langsmith-tags")_=X.split(",");else if(H==="langsmith-project")P=X;else if(H==="langsmith-replicas")O=JSON.parse(X)}return new c9(K,_,P,O)}toHeader(){let q=[];if(this.metadata&&Object.keys(this.metadata).length>0)q.push(`langsmith-metadata=${encodeURIComponent(JSON.stringify(this.metadata))}`);if(this.tags&&this.tags.length>0)q.push(`langsmith-tags=${encodeURIComponent(this.tags.join(","))}`);if(this.project_name)q.push(`langsmith-project=${encodeURIComponent(this.project_name)}`);return q.join(",")}}class H8{constructor(q){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}),QH(q)){Object.assign(this,{...q});return}let $=H8.getDefaultConfig(),{metadata:K,..._}=q,P=_.client??H8.getSharedClient(),O={...K,..._?.extra?.metadata};if(_.extra={..._.extra,metadata:O},Object.assign(this,{...$,..._,client:P}),!this.trace_id)if(this.parent_run)this.trace_id=this.parent_run.trace_id??this.id;else this.trace_id=this.id;if(this.replicas=yM(this.replicas),this.execution_order??=1,this.child_execution_order??=1,!this.dotted_order){let{dottedOrder:Y,microsecondPrecisionDatestring:H}=WY(this.start_time,this.id,this.execution_order);if(this.parent_run)this.dotted_order=this.parent_run.dotted_order+"."+Y;else this.dotted_order=Y;this._serialized_start_time=H}}set metadata(q){this.extra={...this.extra,metadata:{...this.extra?.metadata,...q}}}get metadata(){return this.extra?.metadata}static getDefaultConfig(){return{id:JK(),run_type:"chain",project_name:R7(),child_runs:[],api_url:_6("LANGCHAIN_ENDPOINT")??"http://localhost:1984",api_key:_6("LANGCHAIN_API_KEY"),caller_options:{},start_time:Date.now(),serialized:{},inputs:{},extra:{}}}static getSharedClient(){if(!H8.sharedClient)H8.sharedClient=new lK;return H8.sharedClient}createChild(q){let $=this.child_execution_order+1,K=new H8({...q,parent_run:this,project_name:this.project_name,replicas:this.replicas,client:this.client,tracingEnabled:this.tracingEnabled,execution_order:$,child_execution_order:$});if(m9 in this)K[m9]=this[m9];let _=Symbol.for("lc:child_config"),P=q.extra?.[_]??this.extra[_];if(LM(P)){let H={...P},v=IM(H.callbacks)?H.callbacks.copy?.():void 0;if(v)Object.assign(v,{_parentRunId:K.id}),v.handlers?.find(aH)?.updateFromRunTree?.(K),H.callbacks=v;K.extra[_]=H}let O=new Set,Y=this;while(Y!=null&&!O.has(Y.id))O.add(Y.id),Y.child_execution_order=Math.max(Y.child_execution_order,$),Y=Y.parent_run;return this.child_runs.push(K),K}async end(q,$,K=Date.now(),_){if(this.outputs=this.outputs??q,this.error=this.error??$,this.end_time=this.end_time??K,_&&Object.keys(_).length>0)this.extra=this.extra?{...this.extra,metadata:{...this.extra.metadata,..._}}:{metadata:_}}_convertToCreate(q,$,K=!0){let _=q.extra??{};if(_?.runtime?.library===void 0){if(!_.runtime)_.runtime={};if($){for(let[Y,H]of Object.entries($))if(!_.runtime[Y])_.runtime[Y]=H}}let P,O;if(!K)P=q.child_runs.map((Y)=>this._convertToCreate(Y,$,K)),O=void 0;else O=q.parent_run?.id??q.parent_run_id,P=[];return{id:q.id,name:q.name,start_time:q._serialized_start_time??q.start_time,end_time:q.end_time,run_type:q.run_type,reference_example_id:q.reference_example_id,extra:_,serialized:q.serialized,error:q.error,inputs:q.inputs,outputs:q.outputs,session_name:q.project_name,child_runs:P,parent_run_id:O,trace_id:q.trace_id,dotted_order:q.dotted_order,tags:q.tags,attachments:q.attachments,events:q.events}}_remapForProject(q,$,K=!0){let _=this._convertToCreate(this,$,K);if(q===this.project_name)return _;let P=(Z)=>{return z9(`${Z}:${q}`,z9.DNS)},O=P(_.id),Y=_.trace_id?P(_.trace_id):void 0,H=_.parent_run_id?P(_.parent_run_id):void 0,v;if(_.dotted_order){let Z=bM(_.dotted_order),k=[];for(let S=0;S<Z.length-1;S++){let[N,E]=Z[S],h=P(E);k.push(N.toISOString().replace(/[-:]/g,"").replace(".","")+h)}let[G]=Z[Z.length-1];k.push(G.toISOString().replace(/[-:]/g,"").replace(".","")+O),v=k.join(".")}else v=void 0;return{..._,id:O,trace_id:Y,parent_run_id:H,dotted_order:v,session_name:q}}async postRun(q=!0){try{let $=v9();if(this.replicas&&this.replicas.length>0)for(let{projectName:K,apiKey:_,apiUrl:P,workspaceId:O}of this.replicas){let Y=this._remapForProject(K??this.project_name,$,!0);await this.client.createRun(Y,{apiKey:_,apiUrl:P,workspaceId:O})}else{let K=this._convertToCreate(this,$,q);await this.client.createRun(K)}if(!q){V9("Posting with excludeChildRuns=false is deprecated and will be removed in a future version.");for(let K of this.child_runs)await K.postRun(!1)}}catch($){console.error(`Error in postRun for run ${this.id}:`,$)}}async patchRun(q){if(this.replicas&&this.replicas.length>0)for(let{projectName:$,apiKey:K,apiUrl:_,workspaceId:P,updates:O}of this.replicas){let Y=this._remapForProject($??this.project_name),H={id:Y.id,outputs:Y.outputs,error:Y.error,parent_run_id:Y.parent_run_id,session_name:Y.session_name,reference_example_id:Y.reference_example_id,end_time:Y.end_time,dotted_order:Y.dotted_order,trace_id:Y.trace_id,events:Y.events,tags:Y.tags,extra:Y.extra,attachments:this.attachments,...O};if(!q?.excludeInputs)H.inputs=Y.inputs;await this.client.updateRun(Y.id,H,{apiKey:K,apiUrl:_,workspaceId:P})}else try{let $={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};if(!q?.excludeInputs)$.inputs=this.inputs;await this.client.updateRun(this.id,$)}catch($){console.error(`Error in patchRun for run ${this.id}`,$)}}toJSON(){return this._convertToCreate(this,void 0,!1)}addEvent(q){if(!this.events)this.events=[];if(typeof q==="string")this.events.push({name:"event",time:new Date().toISOString(),message:q});else this.events.push({...q,time:q.time??new Date().toISOString()})}static fromRunnableConfig(q,$){let K=q?.callbacks,_,P,O,Y=FH();if(K){let v=K?.getParentRunId?.()??"",X=K?.handlers?.find((Z)=>Z?.name=="langchain_tracer");_=X?.getRun?.(v),P=X?.projectName,O=X?.client,Y=Y||!!X}if(!_)return new H8({...$,client:O,tracingEnabled:Y,project_name:P});return new H8({name:_.name,id:_.id,trace_id:_.trace_id,dotted_order:_.dotted_order,client:O,tracingEnabled:Y,project_name:P,tags:[...new Set((_?.tags??[]).concat(q?.tags??[]))],extra:{metadata:{..._?.extra?.metadata,...q?.metadata}}}).createChild($)}static fromDottedOrder(q){return this.fromHeaders({"langsmith-trace":q})}static fromHeaders(q,$){let K="get"in q&&typeof q.get==="function"?{"langsmith-trace":q.get("langsmith-trace"),baggage:q.get("baggage")}:q,_=K["langsmith-trace"];if(!_||typeof _!=="string")return;let P=_.trim(),O=P.split(".").map((v)=>{let[X,Z]=v.split("Z");return{strTime:X,time:Date.parse(X+"Z"),uuid:Z}}),Y=O[0].uuid,H={...$,name:$?.name??"parent",run_type:$?.run_type??"chain",start_time:$?.start_time??Date.now(),id:O.at(-1)?.uuid,trace_id:Y,dotted_order:P};if(K.baggage&&typeof K.baggage==="string"){let v=c9.fromHeader(K.baggage);H.metadata=v.metadata,H.tags=v.tags,H.project_name=v.project_name,H.replicas=v.replicas}return new H8(H)}toHeaders(q){let $={"langsmith-trace":this.dotted_order,baggage:new c9(this.extra?.metadata,this.tags,this.project_name,this.replicas).toHeader()};if(q)for(let[K,_]of Object.entries($))q.set(K,_);return $}}Object.defineProperty(H8,"sharedClient",{enumerable:!0,configurable:!0,writable:!0,value:null});function QH(q){return q!=null&&typeof q.createChild==="function"&&typeof q.postRun==="function"}function aH(q){return typeof q==="object"&&q!=null&&typeof q.name==="string"&&q.name==="langchain_tracer"}function tH(q){return Array.isArray(q)&&q.some(($)=>aH($))}function IM(q){return typeof q==="object"&&q!=null&&Array.isArray(q.handlers)}function LM(q){return q!=null&&typeof q.callbacks==="object"&&(tH(q.callbacks?.handlers)||tH(q.callbacks))}function bM(q){return q.split(".").map((K)=>{let _=K.slice(0,-36),P=K.slice(-36),O=parseInt(_.slice(0,4)),Y=parseInt(_.slice(4,6))-1,H=parseInt(_.slice(6,8)),v=parseInt(_.slice(9,11)),X=parseInt(_.slice(11,13)),Z=parseInt(_.slice(13,15)),k=parseInt(_.slice(15,21));return[new Date(O,Y,H,v,X,Z,k/1000),P]})}function gM(){let q=_6("LANGSMITH_RUNS_ENDPOINTS");if(!q)return[];try{let $=JSON.parse(q);if(Array.isArray($)){let K=[];for(let _ of $){if(typeof _!=="object"||_===null){console.warn(`Invalid item type in LANGSMITH_RUNS_ENDPOINTS: expected object, got ${typeof _}`);continue}if(typeof _.api_url!=="string"){console.warn(`Invalid api_url type in LANGSMITH_RUNS_ENDPOINTS: expected string, got ${typeof _.api_url}`);continue}if(typeof _.api_key!=="string"){console.warn(`Invalid api_key type in LANGSMITH_RUNS_ENDPOINTS: expected string, got ${typeof _.api_key}`);continue}K.push({apiUrl:_.api_url.replace(/\/$/,""),apiKey:_.api_key})}return K}else if(typeof $==="object"&&$!==null){pM($);let K=[];for(let[_,P]of Object.entries($)){let O=_.replace(/\/$/,"");if(typeof P==="string")K.push({apiUrl:O,apiKey:P});else{console.warn(`Invalid value type in LANGSMITH_RUNS_ENDPOINTS for URL ${_}: expected string, got ${typeof P}`);continue}}return K}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 $}`),[]}catch($){if(lH($))throw $;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 yM(q){if(q)return q.map(($)=>{if(Array.isArray($))return{projectName:$[0],updates:$[1]};return $});return gM()}function pM(q){if(Object.keys(q).length>0&&B$("ENDPOINT"))throw new YY}var Oz=K6(sH(),1),oM=K6(jz(),1);function Wz(q,$){return $?.[q]||Oz.default(q)}function Hz(q,$,K){let _={};for(let P in q)if(Object.hasOwn(q,P))_[$(P,K)]=q[P];return _}function zz(q){return Array.isArray(q)?[...q]:{...q}}function nM(q,$){let K=zz(q);for(let[_,P]of Object.entries($)){let[O,...Y]=_.split(".").reverse(),H=K;for(let v of Y.reverse()){if(H[v]===void 0)break;H[v]=zz(H[v]),H=H[v]}if(H[O]!==void 0)H[O]={lc:1,type:"secret",id:[P]}}return K}function zY(q){let $=Object.getPrototypeOf(q);if(typeof q.lc_name==="function"&&(typeof $.lc_name!=="function"||q.lc_name()!==$.lc_name()))return q.lc_name();else return q.name}class wK{static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,zY(this.constructor)]}get lc_secrets(){return}get lc_attributes(){return}get lc_aliases(){return}get lc_serializable_keys(){return}constructor(q,...$){if(Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"lc_kwargs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.lc_serializable_keys!==void 0)this.lc_kwargs=Object.fromEntries(Object.entries(q||{}).filter(([K])=>this.lc_serializable_keys?.includes(K)));else this.lc_kwargs=q??{}}toJSON(){if(!this.lc_serializable)return this.toJSONNotImplemented();if(this.lc_kwargs instanceof wK||typeof this.lc_kwargs!=="object"||Array.isArray(this.lc_kwargs))return this.toJSONNotImplemented();let q={},$={},K=Object.keys(this.lc_kwargs).reduce((_,P)=>{return _[P]=P in this?this[P]:this.lc_kwargs[P],_},{});for(let _=Object.getPrototypeOf(this);_;_=Object.getPrototypeOf(_))Object.assign(q,Reflect.get(_,"lc_aliases",this)),Object.assign($,Reflect.get(_,"lc_secrets",this)),Object.assign(K,Reflect.get(_,"lc_attributes",this));return Object.keys($).forEach((_)=>{let P=this,O=K,[Y,...H]=_.split(".").reverse();for(let v of H.reverse()){if(!(v in P)||P[v]===void 0)return;if(!(v in O)||O[v]===void 0){if(typeof P[v]==="object"&&P[v]!=null)O[v]={};else if(Array.isArray(P[v]))O[v]=[]}P=P[v],O=O[v]}if(Y in P&&P[Y]!==void 0)O[Y]=O[Y]||P[Y]}),{lc:1,type:"constructor",id:this.lc_id,kwargs:Hz(Object.keys($).length?nM(K,$):K,Wz,q)}}toJSONNotImplemented(){return{lc:1,type:"not_implemented",id:this.lc_id}}}var rM=()=>typeof window<"u"&&typeof window.document<"u",BM=()=>typeof globalThis==="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope",iM=()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),vY=()=>typeof Deno<"u",UM=()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!vY(),FM=()=>{let q;if(rM())q="browser";else if(UM())q="node";else if(BM())q="webworker";else if(iM())q="jsdom";else if(vY())q="deno";else q="other";return q},JY;function Jz(){if(JY===void 0)JY={library:"langchain-js",runtime:FM()};return JY}function n6(q){try{if(typeof process<"u")return process.env?.[q];else if(vY())return Deno?.env.get(q);else return}catch($){return}}class vz{}class f_ extends vz{get lc_namespace(){return["langchain_core","callbacks",this.name]}get lc_secrets(){return}get lc_attributes(){return}get lc_aliases(){return}get lc_serializable_keys(){return}static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,zY(this.constructor)]}constructor(q){super();if(Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"lc_kwargs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"ignoreLLM",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"ignoreChain",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"ignoreAgent",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"ignoreRetriever",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"ignoreCustomEvent",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"raiseError",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"awaitHandlers",{enumerable:!0,configurable:!0,writable:!0,value:n6("LANGCHAIN_CALLBACKS_BACKGROUND")==="false"}),this.lc_kwargs=q||{},q)this.ignoreLLM=q.ignoreLLM??this.ignoreLLM,this.ignoreChain=q.ignoreChain??this.ignoreChain,this.ignoreAgent=q.ignoreAgent??this.ignoreAgent,this.ignoreRetriever=q.ignoreRetriever??this.ignoreRetriever,this.ignoreCustomEvent=q.ignoreCustomEvent??this.ignoreCustomEvent,this.raiseError=q.raiseError??this.raiseError,this.awaitHandlers=this.raiseError||(q._awaitHandler??this.awaitHandlers)}copy(){return new this.constructor(this)}toJSON(){return wK.prototype.toJSON.call(this)}toJSONNotImplemented(){return wK.prototype.toJSONNotImplemented.call(this)}static fromMethods(q){class $ extends f_{constructor(){super();Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:B8()}),Object.assign(this,q)}}return new $}}var wz=(q)=>{let $=q;return $!==void 0&&typeof $.copy==="function"&&typeof $.name==="string"&&typeof $.awaitHandlers==="boolean"};var tM=(q)=>{if(!q)return;return q.events=q.events??[],q.child_runs=q.child_runs??[],q};function TY(q,$){if(!q)return;return new H8({...q,start_time:q._serialized_start_time??q.start_time,parent_run:TY($),child_runs:q.child_runs.map((K)=>TY(K)).filter((K)=>K!==void 0),extra:{...q.extra,runtime:Jz()},tracingEnabled:!1})}function wY(q,$){return q&&!Array.isArray(q)&&typeof q==="object"?q:{[$]:q}}function w4(q){return typeof q._addRunToRunMap==="function"}class R6 extends f_{constructor(q){super(...arguments);Object.defineProperty(this,"runMap",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"runTreeMap",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"usesRunTreeMap",{enumerable:!0,configurable:!0,writable:!0,value:!1})}copy(){return this}getRunById(q){if(q===void 0)return;return this.usesRunTreeMap?tM(this.runTreeMap.get(q)):this.runMap.get(q)}stringifyError(q){if(q instanceof Error)return q.message+(q?.stack?`
|
|
83
83
|
|
|
84
84
|
${q.stack}`:"");if(typeof q==="string")return q;return`${q}`}_addChildRun(q,$){q.child_runs.push($)}_addRunToRunMap(q){let{dottedOrder:$,microsecondPrecisionDatestring:K}=WY(new Date(q.start_time).getTime(),q.id,q.execution_order),_={...q},P=this.getRunById(_.parent_run_id);if(_.parent_run_id!==void 0){if(P){if(this._addChildRun(P,_),P.child_execution_order=Math.max(P.child_execution_order,_.child_execution_order),_.trace_id=P.trace_id,P.dotted_order!==void 0)_.dotted_order=[P.dotted_order,$].join("."),_._serialized_start_time=K}}else _.trace_id=_.id,_.dotted_order=$,_._serialized_start_time=K;if(this.usesRunTreeMap){let O=TY(_,P);if(O!==void 0)this.runTreeMap.set(_.id,O)}else this.runMap.set(_.id,_);return _}async _endTrace(q){let $=q.parent_run_id!==void 0&&this.getRunById(q.parent_run_id);if($)$.child_execution_order=Math.max($.child_execution_order,q.child_execution_order);else await this.persistRun(q);if(await this.onRunUpdate?.(q),this.usesRunTreeMap)this.runTreeMap.delete(q.id);else this.runMap.delete(q.id)}_getExecutionOrder(q){let $=q!==void 0&&this.getRunById(q);if(!$)return 1;return $.child_execution_order+1}_createRunForLLMStart(q,$,K,_,P,O,Y,H){let v=this._getExecutionOrder(_),X=Date.now(),Z=Y?{...P,metadata:Y}:P,k={id:K,name:H??q.id[q.id.length-1],parent_run_id:_,start_time:X,serialized:q,events:[{name:"start",time:new Date(X).toISOString()}],inputs:{prompts:$},execution_order:v,child_runs:[],child_execution_order:v,run_type:"llm",extra:Z??{},tags:O||[]};return this._addRunToRunMap(k)}async handleLLMStart(q,$,K,_,P,O,Y,H){let v=this.getRunById(K)??this._createRunForLLMStart(q,$,K,_,P,O,Y,H);return await this.onRunCreate?.(v),await this.onLLMStart?.(v),v}_createRunForChatModelStart(q,$,K,_,P,O,Y,H){let v=this._getExecutionOrder(_),X=Date.now(),Z=Y?{...P,metadata:Y}:P,k={id:K,name:H??q.id[q.id.length-1],parent_run_id:_,start_time:X,serialized:q,events:[{name:"start",time:new Date(X).toISOString()}],inputs:{messages:$},execution_order:v,child_runs:[],child_execution_order:v,run_type:"llm",extra:Z??{},tags:O||[]};return this._addRunToRunMap(k)}async handleChatModelStart(q,$,K,_,P,O,Y,H){let v=this.getRunById(K)??this._createRunForChatModelStart(q,$,K,_,P,O,Y,H);return await this.onRunCreate?.(v),await this.onLLMStart?.(v),v}async handleLLMEnd(q,$,K,_,P){let O=this.getRunById($);if(!O||O?.run_type!=="llm")throw Error("No LLM run to end.");return O.end_time=Date.now(),O.outputs=q,O.events.push({name:"end",time:new Date(O.end_time).toISOString()}),O.extra={...O.extra,...P},await this.onLLMEnd?.(O),await this._endTrace(O),O}async handleLLMError(q,$,K,_,P){let O=this.getRunById($);if(!O||O?.run_type!=="llm")throw Error("No LLM run to end.");return O.end_time=Date.now(),O.error=this.stringifyError(q),O.events.push({name:"error",time:new Date(O.end_time).toISOString()}),O.extra={...O.extra,...P},await this.onLLMError?.(O),await this._endTrace(O),O}_createRunForChainStart(q,$,K,_,P,O,Y,H){let v=this._getExecutionOrder(_),X=Date.now(),Z={id:K,name:H??q.id[q.id.length-1],parent_run_id:_,start_time:X,serialized:q,events:[{name:"start",time:new Date(X).toISOString()}],inputs:$,execution_order:v,child_execution_order:v,run_type:Y??"chain",child_runs:[],extra:O?{metadata:O}:{},tags:P||[]};return this._addRunToRunMap(Z)}async handleChainStart(q,$,K,_,P,O,Y,H){let v=this.getRunById(K)??this._createRunForChainStart(q,$,K,_,P,O,Y,H);return await this.onRunCreate?.(v),await this.onChainStart?.(v),v}async handleChainEnd(q,$,K,_,P){let O=this.getRunById($);if(!O)throw Error("No chain run to end.");if(O.end_time=Date.now(),O.outputs=wY(q,"output"),O.events.push({name:"end",time:new Date(O.end_time).toISOString()}),P?.inputs!==void 0)O.inputs=wY(P.inputs,"input");return await this.onChainEnd?.(O),await this._endTrace(O),O}async handleChainError(q,$,K,_,P){let O=this.getRunById($);if(!O)throw Error("No chain run to end.");if(O.end_time=Date.now(),O.error=this.stringifyError(q),O.events.push({name:"error",time:new Date(O.end_time).toISOString()}),P?.inputs!==void 0)O.inputs=wY(P.inputs,"input");return await this.onChainError?.(O),await this._endTrace(O),O}_createRunForToolStart(q,$,K,_,P,O,Y){let H=this._getExecutionOrder(_),v=Date.now(),X={id:K,name:Y??q.id[q.id.length-1],parent_run_id:_,start_time:v,serialized:q,events:[{name:"start",time:new Date(v).toISOString()}],inputs:{input:$},execution_order:H,child_execution_order:H,run_type:"tool",child_runs:[],extra:O?{metadata:O}:{},tags:P||[]};return this._addRunToRunMap(X)}async handleToolStart(q,$,K,_,P,O,Y){let H=this.getRunById(K)??this._createRunForToolStart(q,$,K,_,P,O,Y);return await this.onRunCreate?.(H),await this.onToolStart?.(H),H}async handleToolEnd(q,$){let K=this.getRunById($);if(!K||K?.run_type!=="tool")throw Error("No tool run to end");return K.end_time=Date.now(),K.outputs={output:q},K.events.push({name:"end",time:new Date(K.end_time).toISOString()}),await this.onToolEnd?.(K),await this._endTrace(K),K}async handleToolError(q,$){let K=this.getRunById($);if(!K||K?.run_type!=="tool")throw Error("No tool run to end");return K.end_time=Date.now(),K.error=this.stringifyError(q),K.events.push({name:"error",time:new Date(K.end_time).toISOString()}),await this.onToolError?.(K),await this._endTrace(K),K}async handleAgentAction(q,$){let K=this.getRunById($);if(!K||K?.run_type!=="chain")return;let _=K;_.actions=_.actions||[],_.actions.push(q),_.events.push({name:"agent_action",time:new Date().toISOString(),kwargs:{action:q}}),await this.onAgentAction?.(K)}async handleAgentEnd(q,$){let K=this.getRunById($);if(!K||K?.run_type!=="chain")return;K.events.push({name:"agent_end",time:new Date().toISOString(),kwargs:{action:q}}),await this.onAgentEnd?.(K)}_createRunForRetrieverStart(q,$,K,_,P,O,Y){let H=this._getExecutionOrder(_),v=Date.now(),X={id:K,name:Y??q.id[q.id.length-1],parent_run_id:_,start_time:v,serialized:q,events:[{name:"start",time:new Date(v).toISOString()}],inputs:{query:$},execution_order:H,child_execution_order:H,run_type:"retriever",child_runs:[],extra:O?{metadata:O}:{},tags:P||[]};return this._addRunToRunMap(X)}async handleRetrieverStart(q,$,K,_,P,O,Y){let H=this.getRunById(K)??this._createRunForRetrieverStart(q,$,K,_,P,O,Y);return await this.onRunCreate?.(H),await this.onRetrieverStart?.(H),H}async handleRetrieverEnd(q,$){let K=this.getRunById($);if(!K||K?.run_type!=="retriever")throw Error("No retriever run to end");return K.end_time=Date.now(),K.outputs={documents:q},K.events.push({name:"end",time:new Date(K.end_time).toISOString()}),await this.onRetrieverEnd?.(K),await this._endTrace(K),K}async handleRetrieverError(q,$){let K=this.getRunById($);if(!K||K?.run_type!=="retriever")throw Error("No retriever run to end");return K.end_time=Date.now(),K.error=this.stringifyError(q),K.events.push({name:"error",time:new Date(K.end_time).toISOString()}),await this.onRetrieverError?.(K),await this._endTrace(K),K}async handleText(q,$){let K=this.getRunById($);if(!K||K?.run_type!=="chain")return;K.events.push({name:"text",time:new Date().toISOString(),kwargs:{text:q}}),await this.onText?.(K)}async handleLLMNewToken(q,$,K,_,P,O){let Y=this.getRunById(K);if(!Y||Y?.run_type!=="llm")throw Error('Invalid "runId" provided to "handleLLMNewToken" callback.');return Y.events.push({name:"new_token",time:new Date().toISOString(),kwargs:{token:q,idx:$,chunk:O?.chunk}}),await this.onLLMNewToken?.(Y,q,{chunk:O?.chunk}),Y}}var XY=K6(Az(),1);function c8(q,$){return`${q.open}${$}${q.close}`}function w6(q,$){try{return JSON.stringify(q,null,2)}catch(K){return $}}function kz(q){if(typeof q==="string")return q.trim();if(q===null||q===void 0)return q;return w6(q,q.toString())}function dK(q){if(!q.end_time)return"";let $=q.end_time-q.start_time;if($<1000)return`${$}ms`;return`${($/1000).toFixed(2)}s`}var{color:F8}=XY.default;class l9 extends R6{constructor(){super(...arguments);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"console_callback_handler"})}persistRun(q){return Promise.resolve()}getParents(q){let $=[],K=q;while(K.parent_run_id){let _=this.runMap.get(K.parent_run_id);if(_)$.push(_),K=_;else break}return $}getBreadcrumbs(q){let K=[...this.getParents(q).reverse(),q].map((_,P,O)=>{let Y=`${_.execution_order}:${_.run_type}:${_.name}`;return P===O.length-1?c8(XY.default.bold,Y):Y}).join(" > ");return c8(F8.grey,K)}onChainStart(q){let $=this.getBreadcrumbs(q);console.log(`${c8(F8.green,"[chain/start]")} [${$}] Entering Chain run with input: ${w6(q.inputs,"[inputs]")}`)}onChainEnd(q){let $=this.getBreadcrumbs(q);console.log(`${c8(F8.cyan,"[chain/end]")} [${$}] [${dK(q)}] Exiting Chain run with output: ${w6(q.outputs,"[outputs]")}`)}onChainError(q){let $=this.getBreadcrumbs(q);console.log(`${c8(F8.red,"[chain/error]")} [${$}] [${dK(q)}] Chain run errored with error: ${w6(q.error,"[error]")}`)}onLLMStart(q){let $=this.getBreadcrumbs(q),K="prompts"in q.inputs?{prompts:q.inputs.prompts.map((_)=>_.trim())}:q.inputs;console.log(`${c8(F8.green,"[llm/start]")} [${$}] Entering LLM run with input: ${w6(K,"[inputs]")}`)}onLLMEnd(q){let $=this.getBreadcrumbs(q);console.log(`${c8(F8.cyan,"[llm/end]")} [${$}] [${dK(q)}] Exiting LLM run with output: ${w6(q.outputs,"[response]")}`)}onLLMError(q){let $=this.getBreadcrumbs(q);console.log(`${c8(F8.red,"[llm/error]")} [${$}] [${dK(q)}] LLM run errored with error: ${w6(q.error,"[error]")}`)}onToolStart(q){let $=this.getBreadcrumbs(q);console.log(`${c8(F8.green,"[tool/start]")} [${$}] Entering Tool run with input: "${kz(q.inputs.input)}"`)}onToolEnd(q){let $=this.getBreadcrumbs(q);console.log(`${c8(F8.cyan,"[tool/end]")} [${$}] [${dK(q)}] Exiting Tool run with output: "${kz(q.outputs?.output)}"`)}onToolError(q){let $=this.getBreadcrumbs(q);console.log(`${c8(F8.red,"[tool/error]")} [${$}] [${dK(q)}] Tool run errored with error: ${w6(q.error,"[error]")}`)}onRetrieverStart(q){let $=this.getBreadcrumbs(q);console.log(`${c8(F8.green,"[retriever/start]")} [${$}] Entering Retriever run with input: ${w6(q.inputs,"[inputs]")}`)}onRetrieverEnd(q){let $=this.getBreadcrumbs(q);console.log(`${c8(F8.cyan,"[retriever/end]")} [${$}] [${dK(q)}] Exiting Retriever run with output: ${w6(q.outputs,"[outputs]")}`)}onRetrieverError(q){let $=this.getBreadcrumbs(q);console.log(`${c8(F8.red,"[retriever/error]")} [${$}] [${dK(q)}] Retriever run errored with error: ${w6(q.error,"[error]")}`)}onAgentAction(q){let $=q,K=this.getBreadcrumbs(q);console.log(`${c8(F8.blue,"[agent/action]")} [${K}] Agent selected action: ${w6($.actions[$.actions.length-1],"[action]")}`)}}function fY(q){return!!(q&&typeof q==="object"&&("type"in q)&&q.type==="tool_call")}class AY extends Error{constructor(q,$){super(q);Object.defineProperty(this,"output",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.output=$}}function Gz(q){if(typeof q>"u")return null;try{return JSON.parse(q)}catch(O){}let $="",K=[],_=!1,P=!1;for(let O of q){if(_)if(O==='"'&&!P)_=!1;else if(O===`
|
|
85
|
-
`&&!P)O="\\n";else if(O==="\\")P=!P;else P=!1;else if(O==='"')_=!0,P=!1;else if(O==="{")K.push("}");else if(O==="[")K.push("]");else if(O==="}"||O==="]")if(K&&K[K.length-1]===O)K.pop();else return null;$+=O}if(_)$+='"';for(let O=K.length-1;O>=0;O-=1)$+=K[O];try{return JSON.parse($)}catch(O){return null}}function kY(q){return typeof q==="object"&&q!==null&&"type"in q&&typeof q.type==="string"&&"source_type"in q&&(q.source_type==="url"||q.source_type==="base64"||q.source_type==="text"||q.source_type==="id")}function A_(q,$){if(typeof q==="string"){if(q==="")return $;if(typeof $==="string")return q+$;else if(Array.isArray($)&&$.some((K)=>kY(K)))return[{type:"text",source_type:"text",text:q},...$];else return[{type:"text",text:q},...$]}else if(Array.isArray($))return d9(q,$)??[...q,...$];else if($==="")return q;else if(Array.isArray(q)&&q.some((K)=>kY(K)))return[...q,{type:"file",source_type:"text",text:$}];else return[...q,{type:"text",text:$}]}function aM(q,$){function K(_,P){if(typeof _!=="object"||_===null||_===void 0)return _;if(P>=$){if(Array.isArray(_))return"[Array]";return"[Object]"}if(Array.isArray(_))return _.map((Y)=>K(Y,P+1));let O={};for(let Y of Object.keys(_))O[Y]=K(_[Y],P+1);return O}return JSON.stringify(K(q,0),null,2)}class TK extends wK{get lc_aliases(){return{additional_kwargs:"additional_kwargs",response_metadata:"response_metadata"}}get text(){if(typeof this.content==="string")return this.content;if(!Array.isArray(this.content))return"";return this.content.map((q)=>{if(typeof q==="string")return q;if(q.type==="text")return q.text;return""}).join("")}getType(){return this._getType()}constructor(q,$){if(typeof q==="string")q={content:q,additional_kwargs:$,response_metadata:{}};if(!q.additional_kwargs)q.additional_kwargs={};if(!q.response_metadata)q.response_metadata={};super(q);Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","messages"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"content",{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,"additional_kwargs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"response_metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=q.name,this.content=q.content,this.additional_kwargs=q.additional_kwargs,this.response_metadata=q.response_metadata,this.id=q.id}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}}_updateId(q){this.id=q,this.lc_kwargs.id=q}get[Symbol.toStringTag](){return this.constructor.lc_name()}[Symbol.for("nodejs.util.inspect.custom")](q){if(q===null)return this;let $=aM(this._printableFields,Math.max(4,q));return`${this.constructor.lc_name()} ${$}`}}function r6(q,$){let K={...q};for(let[_,P]of Object.entries($))if(K[_]==null)K[_]=P;else if(P==null)continue;else if(typeof K[_]!==typeof P||Array.isArray(K[_])!==Array.isArray(P))throw Error(`field[${_}] already exists in the message chunk, but with a different type.`);else if(typeof K[_]==="string")if(_==="type")continue;else if(["id","output_version","model_provider"].includes(_))K[_]=P;else K[_]+=P;else if(typeof K[_]==="object"&&!Array.isArray(K[_]))K[_]=r6(K[_],P);else if(Array.isArray(K[_]))K[_]=d9(K[_],P);else if(K[_]===P)continue;else console.warn(`field[${_}] already exists in this message chunk and value has unsupported type.`);return K}function d9(q,$){if(q===void 0&&$===void 0)return;else if(q===void 0||$===void 0)return q||$;else{let K=[...q];for(let _ of $)if(typeof _==="object"&&_!==null&&"index"in _&&typeof _.index==="number"){let P=K.findIndex((O)=>
|
|
85
|
+
`&&!P)O="\\n";else if(O==="\\")P=!P;else P=!1;else if(O==='"')_=!0,P=!1;else if(O==="{")K.push("}");else if(O==="[")K.push("]");else if(O==="}"||O==="]")if(K&&K[K.length-1]===O)K.pop();else return null;$+=O}if(_)$+='"';for(let O=K.length-1;O>=0;O-=1)$+=K[O];try{return JSON.parse($)}catch(O){return null}}function kY(q){return typeof q==="object"&&q!==null&&"type"in q&&typeof q.type==="string"&&"source_type"in q&&(q.source_type==="url"||q.source_type==="base64"||q.source_type==="text"||q.source_type==="id")}function A_(q,$){if(typeof q==="string"){if(q==="")return $;if(typeof $==="string")return q+$;else if(Array.isArray($)&&$.some((K)=>kY(K)))return[{type:"text",source_type:"text",text:q},...$];else return[{type:"text",text:q},...$]}else if(Array.isArray($))return d9(q,$)??[...q,...$];else if($==="")return q;else if(Array.isArray(q)&&q.some((K)=>kY(K)))return[...q,{type:"file",source_type:"text",text:$}];else return[...q,{type:"text",text:$}]}function aM(q,$){function K(_,P){if(typeof _!=="object"||_===null||_===void 0)return _;if(P>=$){if(Array.isArray(_))return"[Array]";return"[Object]"}if(Array.isArray(_))return _.map((Y)=>K(Y,P+1));let O={};for(let Y of Object.keys(_))O[Y]=K(_[Y],P+1);return O}return JSON.stringify(K(q,0),null,2)}class TK extends wK{get lc_aliases(){return{additional_kwargs:"additional_kwargs",response_metadata:"response_metadata"}}get text(){if(typeof this.content==="string")return this.content;if(!Array.isArray(this.content))return"";return this.content.map((q)=>{if(typeof q==="string")return q;if(q.type==="text")return q.text;return""}).join("")}getType(){return this._getType()}constructor(q,$){if(typeof q==="string")q={content:q,additional_kwargs:$,response_metadata:{}};if(!q.additional_kwargs)q.additional_kwargs={};if(!q.response_metadata)q.response_metadata={};super(q);Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","messages"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"content",{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,"additional_kwargs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"response_metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=q.name,this.content=q.content,this.additional_kwargs=q.additional_kwargs,this.response_metadata=q.response_metadata,this.id=q.id}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}}_updateId(q){this.id=q,this.lc_kwargs.id=q}get[Symbol.toStringTag](){return this.constructor.lc_name()}[Symbol.for("nodejs.util.inspect.custom")](q){if(q===null)return this;let $=aM(this._printableFields,Math.max(4,q));return`${this.constructor.lc_name()} ${$}`}}function r6(q,$){let K={...q};for(let[_,P]of Object.entries($))if(K[_]==null)K[_]=P;else if(P==null)continue;else if(typeof K[_]!==typeof P||Array.isArray(K[_])!==Array.isArray(P))throw Error(`field[${_}] already exists in the message chunk, but with a different type.`);else if(typeof K[_]==="string")if(_==="type")continue;else if(["id","name","output_version","model_provider"].includes(_))K[_]=P;else K[_]+=P;else if(typeof K[_]==="object"&&!Array.isArray(K[_]))K[_]=r6(K[_],P);else if(Array.isArray(K[_]))K[_]=d9(K[_],P);else if(K[_]===P)continue;else console.warn(`field[${_}] already exists in this message chunk and value has unsupported type.`);return K}function d9(q,$){if(q===void 0&&$===void 0)return;else if(q===void 0||$===void 0)return q||$;else{let K=[...q];for(let _ of $)if(typeof _==="object"&&_!==null&&"index"in _&&typeof _.index==="number"){let P=K.findIndex((O)=>{let Y=typeof O==="object",H="index"in O&&O.index===_.index,v="id"in O&&"id"in _&&O?.id===_?.id,X=!("id"in O)||!O?.id||!("id"in _)||!_?.id;return Y&&H&&(v||X)});if(P!==-1&&typeof K[P]==="object"&&K[P]!==null)K[P]=r6(K[P],_);else K.push(_)}else if(typeof _==="object"&&_!==null&&"text"in _&&_.text==="")continue;else K.push(_);return K}}class oK extends TK{}class k_ extends oK{constructor(q){let $;if(typeof q==="string")$={content:q,tool_calls:[],invalid_tool_calls:[],tool_call_chunks:[]};else if(q.tool_call_chunks===void 0)$={...q,tool_calls:q.tool_calls??[],invalid_tool_calls:[],tool_call_chunks:[],usage_metadata:q.usage_metadata!==void 0?q.usage_metadata:void 0};else{let K=q.tool_call_chunks.reduce((O,Y)=>{let H=O.findIndex(([v])=>{if("id"in Y&&Y.id&&"index"in Y&&Y.index!==void 0)return Y.id===v.id&&Y.index===v.index;if("id"in Y&&Y.id)return Y.id===v.id;if("index"in Y&&Y.index!==void 0)return Y.index===v.index;return!1});if(H!==-1)O[H].push(Y);else O.push([Y]);return O},[]),_=[],P=[];for(let O of K){let Y={},H=O[0]?.name??"",v=O.map((k)=>k.args||"").join(""),X=v.length?v:"{}",Z=O[0]?.id;try{if(Y=Gz(X),!Z||Y===null||typeof Y!=="object"||Array.isArray(Y))throw Error("Malformed tool call chunk args.");_.push({name:H,args:Y,id:Z,type:"tool_call"})}catch(k){P.push({name:H,args:X,id:Z,error:"Malformed args.",type:"invalid_tool_call"})}}$={...q,tool_calls:_,invalid_tool_calls:P,usage_metadata:q.usage_metadata!==void 0?q.usage_metadata:void 0}}super($);Object.defineProperty(this,"tool_calls",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"invalid_tool_calls",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"tool_call_chunks",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"usage_metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.tool_call_chunks=$.tool_call_chunks??this.tool_call_chunks,this.tool_calls=$.tool_calls??this.tool_calls,this.invalid_tool_calls=$.invalid_tool_calls??this.invalid_tool_calls,this.usage_metadata=$.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"}_getType(){return"ai"}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(q){let $={content:A_(this.content,q.content),additional_kwargs:r6(this.additional_kwargs,q.additional_kwargs),response_metadata:r6(this.response_metadata,q.response_metadata),tool_call_chunks:[],id:this.id??q.id};if(this.tool_call_chunks!==void 0||q.tool_call_chunks!==void 0){let K=d9(this.tool_call_chunks,q.tool_call_chunks);if(K!==void 0&&K.length>0)$.tool_call_chunks=K}if(this.usage_metadata!==void 0||q.usage_metadata!==void 0){let K={...(this.usage_metadata?.input_token_details?.audio!==void 0||q.usage_metadata?.input_token_details?.audio!==void 0)&&{audio:(this.usage_metadata?.input_token_details?.audio??0)+(q.usage_metadata?.input_token_details?.audio??0)},...(this.usage_metadata?.input_token_details?.cache_read!==void 0||q.usage_metadata?.input_token_details?.cache_read!==void 0)&&{cache_read:(this.usage_metadata?.input_token_details?.cache_read??0)+(q.usage_metadata?.input_token_details?.cache_read??0)},...(this.usage_metadata?.input_token_details?.cache_creation!==void 0||q.usage_metadata?.input_token_details?.cache_creation!==void 0)&&{cache_creation:(this.usage_metadata?.input_token_details?.cache_creation??0)+(q.usage_metadata?.input_token_details?.cache_creation??0)}},_={...(this.usage_metadata?.output_token_details?.audio!==void 0||q.usage_metadata?.output_token_details?.audio!==void 0)&&{audio:(this.usage_metadata?.output_token_details?.audio??0)+(q.usage_metadata?.output_token_details?.audio??0)},...(this.usage_metadata?.output_token_details?.reasoning!==void 0||q.usage_metadata?.output_token_details?.reasoning!==void 0)&&{reasoning:(this.usage_metadata?.output_token_details?.reasoning??0)+(q.usage_metadata?.output_token_details?.reasoning??0)}},P=this.usage_metadata??{input_tokens:0,output_tokens:0,total_tokens:0},O=q.usage_metadata??{input_tokens:0,output_tokens:0,total_tokens:0},Y={input_tokens:P.input_tokens+O.input_tokens,output_tokens:P.output_tokens+O.output_tokens,total_tokens:P.total_tokens+O.total_tokens,...Object.keys(K).length>0&&{input_token_details:K},...Object.keys(_).length>0&&{output_token_details:_}};$.usage_metadata=Y}return new k_($)}}function Zz(q,$="Human",K="AI"){let _=[];for(let P of q){let O;if(P._getType()==="human")O=$;else if(P._getType()==="ai")O=K;else if(P._getType()==="system")O="System";else if(P._getType()==="function")O="Function";else if(P._getType()==="tool")O="Tool";else if(P._getType()==="generic")O=P.role;else throw Error(`Got unsupported message type: ${P._getType()}`);let Y=P.name?`${P.name}, `:"",H=typeof P.content==="string"?P.content:JSON.stringify(P.content,null,2);_.push(`${O}: ${Y}${H}`)}return _.join(`
|
|
86
86
|
`)}var GY,ZY=()=>{if(GY===void 0){let q=n6("LANGCHAIN_CALLBACKS_BACKGROUND")==="false"?{blockOnRootRunFinalization:!0}:{};GY=new lK(q)}return GY};class T4 extends R6{constructor(q={}){super(q);Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"langchain_tracer"}),Object.defineProperty(this,"projectName",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"exampleId",{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,"replicas",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"usesRunTreeMap",{enumerable:!0,configurable:!0,writable:!0,value:!0});let{exampleId:$,projectName:K,client:_,replicas:P}=q;this.projectName=K??R7(),this.replicas=P,this.exampleId=$,this.client=_??ZY();let O=T4.getTraceableRunTree();if(O)this.updateFromRunTree(O)}async persistRun(q){}async onRunCreate(q){await this.getRunTreeWithTracingConfig(q.id)?.postRun()}async onRunUpdate(q){await this.getRunTreeWithTracingConfig(q.id)?.patchRun()}getRun(q){return this.runTreeMap.get(q)}updateFromRunTree(q){this.runTreeMap.set(q.id,q);let $=q,K=new Set;while($.parent_run){if(K.has($.id))break;if(K.add($.id),!$.parent_run)break;$=$.parent_run}K.clear();let _=[$];while(_.length>0){let P=_.shift();if(!P||K.has(P.id))continue;if(K.add(P.id),this.runTreeMap.set(P.id,P),P.child_runs)_.push(...P.child_runs)}this.client=q.client??this.client,this.replicas=q.replicas??this.replicas,this.projectName=q.project_name??this.projectName,this.exampleId=q.reference_example_id??this.exampleId}getRunTreeWithTracingConfig(q){let $=this.runTreeMap.get(q);if(!$)return;return new H8({...$,client:this.client,project_name:this.projectName,replicas:this.replicas,reference_example_id:this.exampleId,tracingEnabled:!0})}static getTraceableRunTree(){try{return xj(!0)}catch{return}}}var o9=K6(k9(),1);var Vz=Symbol.for("ls:tracing_async_local_storage"),G_=Symbol.for("lc:context_variables"),Mz=(q)=>{globalThis[Vz]=q},nK=()=>{return globalThis[Vz]};var u7;function eM(){return new("default"in o9.default?o9.default.default:o9.default)({autoStart:!0,concurrency:1})}function sM(){if(typeof u7>"u")u7=eM();return u7}async function n$(q,$){if($===!0){let K=nK();if(K!==void 0)await K.run(void 0,async()=>q());else await q()}else u7=sM(),u7.add(async()=>{let K=nK();if(K!==void 0)await K.run(void 0,async()=>q());else await q()})}var Sz=(q)=>{if(q!==void 0)return q;return!!["LANGSMITH_TRACING_V2","LANGCHAIN_TRACING_V2","LANGSMITH_TRACING","LANGCHAIN_TRACING"].find((K)=>n6(K)==="true")};function VY(q){let $=nK();if($===void 0)return;return $.getStore()?.[G_]?.[q]}var qS=Symbol("lc:configure_hooks"),Cz=()=>VY(qS)||[];class Nz{setHandler(q){return this.setHandlers([q])}}class c7{constructor(q,$,K,_,P,O,Y,H){Object.defineProperty(this,"runId",{enumerable:!0,configurable:!0,writable:!0,value:q}),Object.defineProperty(this,"handlers",{enumerable:!0,configurable:!0,writable:!0,value:$}),Object.defineProperty(this,"inheritableHandlers",{enumerable:!0,configurable:!0,writable:!0,value:K}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:_}),Object.defineProperty(this,"inheritableTags",{enumerable:!0,configurable:!0,writable:!0,value:P}),Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:O}),Object.defineProperty(this,"inheritableMetadata",{enumerable:!0,configurable:!0,writable:!0,value:Y}),Object.defineProperty(this,"_parentRunId",{enumerable:!0,configurable:!0,writable:!0,value:H})}get parentRunId(){return this._parentRunId}async handleText(q){await Promise.all(this.handlers.map(($)=>n$(async()=>{try{await $.handleText?.(q,this.runId,this._parentRunId,this.tags)}catch(K){if(($.raiseError?console.error:console.warn)(`Error in handler ${$.constructor.name}, handleText: ${K}`),$.raiseError)throw K}},$.awaitHandlers)))}async handleCustomEvent(q,$,K,_,P){await Promise.all(this.handlers.map((O)=>n$(async()=>{try{await O.handleCustomEvent?.(q,$,this.runId,this.tags,this.metadata)}catch(Y){if((O.raiseError?console.error:console.warn)(`Error in handler ${O.constructor.name}, handleCustomEvent: ${Y}`),O.raiseError)throw Y}},O.awaitHandlers)))}}class Ez extends c7{getChild(q){let $=new P6(this.runId);if($.setHandlers(this.inheritableHandlers),$.addTags(this.inheritableTags),$.addMetadata(this.inheritableMetadata),q)$.addTags([q],!1);return $}async handleRetrieverEnd(q){await Promise.all(this.handlers.map(($)=>n$(async()=>{if(!$.ignoreRetriever)try{await $.handleRetrieverEnd?.(q,this.runId,this._parentRunId,this.tags)}catch(K){if(($.raiseError?console.error:console.warn)(`Error in handler ${$.constructor.name}, handleRetriever`),$.raiseError)throw K}},$.awaitHandlers)))}async handleRetrieverError(q){await Promise.all(this.handlers.map(($)=>n$(async()=>{if(!$.ignoreRetriever)try{await $.handleRetrieverError?.(q,this.runId,this._parentRunId,this.tags)}catch(K){if(($.raiseError?console.error:console.warn)(`Error in handler ${$.constructor.name}, handleRetrieverError: ${K}`),$.raiseError)throw q}},$.awaitHandlers)))}}class MY extends c7{async handleLLMNewToken(q,$,K,_,P,O){await Promise.all(this.handlers.map((Y)=>n$(async()=>{if(!Y.ignoreLLM)try{await Y.handleLLMNewToken?.(q,$??{prompt:0,completion:0},this.runId,this._parentRunId,this.tags,O)}catch(H){if((Y.raiseError?console.error:console.warn)(`Error in handler ${Y.constructor.name}, handleLLMNewToken: ${H}`),Y.raiseError)throw H}},Y.awaitHandlers)))}async handleLLMError(q,$,K,_,P){await Promise.all(this.handlers.map((O)=>n$(async()=>{if(!O.ignoreLLM)try{await O.handleLLMError?.(q,this.runId,this._parentRunId,this.tags,P)}catch(Y){if((O.raiseError?console.error:console.warn)(`Error in handler ${O.constructor.name}, handleLLMError: ${Y}`),O.raiseError)throw Y}},O.awaitHandlers)))}async handleLLMEnd(q,$,K,_,P){await Promise.all(this.handlers.map((O)=>n$(async()=>{if(!O.ignoreLLM)try{await O.handleLLMEnd?.(q,this.runId,this._parentRunId,this.tags,P)}catch(Y){if((O.raiseError?console.error:console.warn)(`Error in handler ${O.constructor.name}, handleLLMEnd: ${Y}`),O.raiseError)throw Y}},O.awaitHandlers)))}}class Rz extends c7{getChild(q){let $=new P6(this.runId);if($.setHandlers(this.inheritableHandlers),$.addTags(this.inheritableTags),$.addMetadata(this.inheritableMetadata),q)$.addTags([q],!1);return $}async handleChainError(q,$,K,_,P){await Promise.all(this.handlers.map((O)=>n$(async()=>{if(!O.ignoreChain)try{await O.handleChainError?.(q,this.runId,this._parentRunId,this.tags,P)}catch(Y){if((O.raiseError?console.error:console.warn)(`Error in handler ${O.constructor.name}, handleChainError: ${Y}`),O.raiseError)throw Y}},O.awaitHandlers)))}async handleChainEnd(q,$,K,_,P){await Promise.all(this.handlers.map((O)=>n$(async()=>{if(!O.ignoreChain)try{await O.handleChainEnd?.(q,this.runId,this._parentRunId,this.tags,P)}catch(Y){if((O.raiseError?console.error:console.warn)(`Error in handler ${O.constructor.name}, handleChainEnd: ${Y}`),O.raiseError)throw Y}},O.awaitHandlers)))}async handleAgentAction(q){await Promise.all(this.handlers.map(($)=>n$(async()=>{if(!$.ignoreAgent)try{await $.handleAgentAction?.(q,this.runId,this._parentRunId,this.tags)}catch(K){if(($.raiseError?console.error:console.warn)(`Error in handler ${$.constructor.name}, handleAgentAction: ${K}`),$.raiseError)throw K}},$.awaitHandlers)))}async handleAgentEnd(q){await Promise.all(this.handlers.map(($)=>n$(async()=>{if(!$.ignoreAgent)try{await $.handleAgentEnd?.(q,this.runId,this._parentRunId,this.tags)}catch(K){if(($.raiseError?console.error:console.warn)(`Error in handler ${$.constructor.name}, handleAgentEnd: ${K}`),$.raiseError)throw K}},$.awaitHandlers)))}}class hz extends c7{getChild(q){let $=new P6(this.runId);if($.setHandlers(this.inheritableHandlers),$.addTags(this.inheritableTags),$.addMetadata(this.inheritableMetadata),q)$.addTags([q],!1);return $}async handleToolError(q){await Promise.all(this.handlers.map(($)=>n$(async()=>{if(!$.ignoreAgent)try{await $.handleToolError?.(q,this.runId,this._parentRunId,this.tags)}catch(K){if(($.raiseError?console.error:console.warn)(`Error in handler ${$.constructor.name}, handleToolError: ${K}`),$.raiseError)throw K}},$.awaitHandlers)))}async handleToolEnd(q){await Promise.all(this.handlers.map(($)=>n$(async()=>{if(!$.ignoreAgent)try{await $.handleToolEnd?.(q,this.runId,this._parentRunId,this.tags)}catch(K){if(($.raiseError?console.error:console.warn)(`Error in handler ${$.constructor.name}, handleToolEnd: ${K}`),$.raiseError)throw K}},$.awaitHandlers)))}}class P6 extends Nz{constructor(q,$){super();Object.defineProperty(this,"handlers",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"inheritableHandlers",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"inheritableTags",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"inheritableMetadata",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"callback_manager"}),Object.defineProperty(this,"_parentRunId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.handlers=$?.handlers??this.handlers,this.inheritableHandlers=$?.inheritableHandlers??this.inheritableHandlers,this.tags=$?.tags??this.tags,this.inheritableTags=$?.inheritableTags??this.inheritableTags,this.metadata=$?.metadata??this.metadata,this.inheritableMetadata=$?.inheritableMetadata??this.inheritableMetadata,this._parentRunId=q}getParentRunId(){return this._parentRunId}async handleLLMStart(q,$,K=void 0,_=void 0,P=void 0,O=void 0,Y=void 0,H=void 0){return Promise.all($.map(async(v,X)=>{let Z=X===0&&K?K:B8();return await Promise.all(this.handlers.map((k)=>{if(k.ignoreLLM)return;if(w4(k))k._createRunForLLMStart(q,[v],Z,this._parentRunId,P,this.tags,this.metadata,H);return n$(async()=>{try{await k.handleLLMStart?.(q,[v],Z,this._parentRunId,P,this.tags,this.metadata,H)}catch(G){if((k.raiseError?console.error:console.warn)(`Error in handler ${k.constructor.name}, handleLLMStart: ${G}`),k.raiseError)throw G}},k.awaitHandlers)})),new MY(Z,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChatModelStart(q,$,K=void 0,_=void 0,P=void 0,O=void 0,Y=void 0,H=void 0){return Promise.all($.map(async(v,X)=>{let Z=X===0&&K?K:B8();return await Promise.all(this.handlers.map((k)=>{if(k.ignoreLLM)return;if(w4(k))k._createRunForChatModelStart(q,[v],Z,this._parentRunId,P,this.tags,this.metadata,H);return n$(async()=>{try{if(k.handleChatModelStart)await k.handleChatModelStart?.(q,[v],Z,this._parentRunId,P,this.tags,this.metadata,H);else if(k.handleLLMStart){let G=Zz(v);await k.handleLLMStart?.(q,[G],Z,this._parentRunId,P,this.tags,this.metadata,H)}}catch(G){if((k.raiseError?console.error:console.warn)(`Error in handler ${k.constructor.name}, handleLLMStart: ${G}`),k.raiseError)throw G}},k.awaitHandlers)})),new MY(Z,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChainStart(q,$,K=B8(),_=void 0,P=void 0,O=void 0,Y=void 0){return await Promise.all(this.handlers.map((H)=>{if(H.ignoreChain)return;if(w4(H))H._createRunForChainStart(q,$,K,this._parentRunId,this.tags,this.metadata,_,Y);return n$(async()=>{try{await H.handleChainStart?.(q,$,K,this._parentRunId,this.tags,this.metadata,_,Y)}catch(v){if((H.raiseError?console.error:console.warn)(`Error in handler ${H.constructor.name}, handleChainStart: ${v}`),H.raiseError)throw v}},H.awaitHandlers)})),new Rz(K,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleToolStart(q,$,K=B8(),_=void 0,P=void 0,O=void 0,Y=void 0){return await Promise.all(this.handlers.map((H)=>{if(H.ignoreAgent)return;if(w4(H))H._createRunForToolStart(q,$,K,this._parentRunId,this.tags,this.metadata,Y);return n$(async()=>{try{await H.handleToolStart?.(q,$,K,this._parentRunId,this.tags,this.metadata,Y)}catch(v){if((H.raiseError?console.error:console.warn)(`Error in handler ${H.constructor.name}, handleToolStart: ${v}`),H.raiseError)throw v}},H.awaitHandlers)})),new hz(K,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleRetrieverStart(q,$,K=B8(),_=void 0,P=void 0,O=void 0,Y=void 0){return await Promise.all(this.handlers.map((H)=>{if(H.ignoreRetriever)return;if(w4(H))H._createRunForRetrieverStart(q,$,K,this._parentRunId,this.tags,this.metadata,Y);return n$(async()=>{try{await H.handleRetrieverStart?.(q,$,K,this._parentRunId,this.tags,this.metadata,Y)}catch(v){if((H.raiseError?console.error:console.warn)(`Error in handler ${H.constructor.name}, handleRetrieverStart: ${v}`),H.raiseError)throw v}},H.awaitHandlers)})),new Ez(K,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleCustomEvent(q,$,K,_,P){await Promise.all(this.handlers.map((O)=>n$(async()=>{if(!O.ignoreCustomEvent)try{await O.handleCustomEvent?.(q,$,K,this.tags,this.metadata)}catch(Y){if((O.raiseError?console.error:console.warn)(`Error in handler ${O.constructor.name}, handleCustomEvent: ${Y}`),O.raiseError)throw Y}},O.awaitHandlers)))}addHandler(q,$=!0){if(this.handlers.push(q),$)this.inheritableHandlers.push(q)}removeHandler(q){this.handlers=this.handlers.filter(($)=>$!==q),this.inheritableHandlers=this.inheritableHandlers.filter(($)=>$!==q)}setHandlers(q,$=!0){this.handlers=[],this.inheritableHandlers=[];for(let K of q)this.addHandler(K,$)}addTags(q,$=!0){if(this.removeTags(q),this.tags.push(...q),$)this.inheritableTags.push(...q)}removeTags(q){this.tags=this.tags.filter(($)=>!q.includes($)),this.inheritableTags=this.inheritableTags.filter(($)=>!q.includes($))}addMetadata(q,$=!0){if(this.metadata={...this.metadata,...q},$)this.inheritableMetadata={...this.inheritableMetadata,...q}}removeMetadata(q){for(let $ of Object.keys(q))delete this.metadata[$],delete this.inheritableMetadata[$]}copy(q=[],$=!0){let K=new P6(this._parentRunId);for(let _ of this.handlers){let P=this.inheritableHandlers.includes(_);K.addHandler(_,P)}for(let _ of this.tags){let P=this.inheritableTags.includes(_);K.addTags([_],P)}for(let _ of Object.keys(this.metadata)){let P=Object.keys(this.inheritableMetadata).includes(_);K.addMetadata({[_]:this.metadata[_]},P)}for(let _ of q){if(K.handlers.filter((P)=>P.name==="console_callback_handler").some((P)=>P.name===_.name))continue;K.addHandler(_,$)}return K}static fromHandlers(q){class $ extends f_{constructor(){super();Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:B8()}),Object.assign(this,q)}}let K=new this;return K.addHandler(new $),K}static configure(q,$,K,_,P,O,Y){return this._configureSync(q,$,K,_,P,O,Y)}static _configureSync(q,$,K,_,P,O,Y){let H;if(q||$){if(Array.isArray(q)||!q)H=new P6,H.setHandlers(q?.map(m7)??[],!0);else H=q;H=H.copy(Array.isArray($)?$.map(m7):$?.handlers,!1)}let v=n6("LANGCHAIN_VERBOSE")==="true"||Y?.verbose,X=T4.getTraceableRunTree()?.tracingEnabled||Sz(),Z=X||(n6("LANGCHAIN_TRACING")??!1);if(v||Z){if(!H)H=new P6;if(v&&!H.handlers.some((k)=>k.name===l9.prototype.name)){let k=new l9;H.addHandler(k,!0)}if(Z&&!H.handlers.some((k)=>k.name==="langchain_tracer")){if(X){let k=new T4;H.addHandler(k,!0)}}if(X){let k=T4.getTraceableRunTree();if(k&&H._parentRunId===void 0)H._parentRunId=k.id,H.handlers.find((S)=>S.name==="langchain_tracer")?.updateFromRunTree(k)}}for(let{contextVar:k,inheritable:G=!0,handlerClass:S,envVar:N}of Cz()){let E=N&&n6(N)==="true"&&S,h,D=k!==void 0?VY(k):void 0;if(D&&wz(D))h=D;else if(E)h=new S({});if(h!==void 0){if(!H)H=new P6;if(!H.handlers.some((I)=>I.name===h.name))H.addHandler(h,G)}}if(K||_){if(H)H.addTags(K??[]),H.addTags(_??[],!1)}if(P||O){if(H)H.addMetadata(P??{}),H.addMetadata(O??{},!1)}return H}}function m7(q){if("name"in q)return q;return f_.fromMethods(q)}class SY{getStore(){return}run(q,$){return $()}enterWith(q){return}}var $S=new SY,Dz=Symbol.for("lc:child_config");class Iz{getInstance(){return nK()??$S}getRunnableConfig(){return this.getInstance().getStore()?.extra?.[Dz]}runWithConfig(q,$,K){let _=P6._configureSync(q?.callbacks,void 0,q?.tags,void 0,q?.metadata),P=this.getInstance(),O=P.getStore(),Y=_?.getParentRunId(),H=_?.handlers?.find((X)=>X?.name==="langchain_tracer"),v;if(H&&Y)v=H.getRunTreeWithTracingConfig(Y);else if(!K)v=new H8({name:"<runnable_lambda>",tracingEnabled:!1});if(v)v.extra={...v.extra,[Dz]:q};if(O!==void 0&&O[G_]!==void 0){if(v===void 0)v={};v[G_]=O[G_]}return P.run(v,$)}initializeGlobalInstance(q){if(nK()===void 0)Mz(q)}}var Y6=new Iz;var n9=25;async function T6(q){return P6._configureSync(q?.callbacks,void 0,q?.tags,void 0,q?.metadata)}function CY(...q){let $={};for(let K of q.filter((_)=>!!_))for(let _ of Object.keys(K))if(_==="metadata")$[_]={...$[_],...K[_]};else if(_==="tags"){let P=$[_]??[];$[_]=[...new Set(P.concat(K[_]??[]))]}else if(_==="configurable")$[_]={...$[_],...K[_]};else if(_==="timeout"){if($.timeout===void 0)$.timeout=K.timeout;else if(K.timeout!==void 0)$.timeout=Math.min($.timeout,K.timeout)}else if(_==="signal"){if($.signal===void 0)$.signal=K.signal;else if(K.signal!==void 0)if("any"in AbortSignal)$.signal=AbortSignal.any([$.signal,K.signal]);else $.signal=K.signal}else if(_==="callbacks"){let P=$.callbacks,O=K.callbacks;if(Array.isArray(O))if(!P)$.callbacks=O;else if(Array.isArray(P))$.callbacks=P.concat(O);else{let Y=P.copy();for(let H of O)Y.addHandler(m7(H),!0);$.callbacks=Y}else if(O)if(!P)$.callbacks=O;else if(Array.isArray(P)){let Y=O.copy();for(let H of P)Y.addHandler(m7(H),!0);$.callbacks=Y}else $.callbacks=new P6(O._parentRunId,{handlers:P.handlers.concat(O.handlers),inheritableHandlers:P.inheritableHandlers.concat(O.inheritableHandlers),tags:Array.from(new Set(P.tags.concat(O.tags))),inheritableTags:Array.from(new Set(P.inheritableTags.concat(O.inheritableTags))),metadata:{...P.metadata,...O.metadata}})}else{let P=_;$[P]=K[P]??$[P]}return $}var KS=new Set(["string","number","boolean"]);function D$(q){let $=Y6.getRunnableConfig(),K={tags:[],metadata:{},recursionLimit:25,runId:void 0};if($){let{runId:_,runName:P,...O}=$;K=Object.entries(O).reduce((Y,[H,v])=>{if(v!==void 0)Y[H]=v;return Y},K)}if(q)K=Object.entries(q).reduce((_,[P,O])=>{if(O!==void 0)_[P]=O;return _},K);if(K?.configurable){for(let _ of Object.keys(K.configurable))if(KS.has(typeof K.configurable[_])&&!K.metadata?.[_]){if(!K.metadata)K.metadata={};K.metadata[_]=K.configurable[_]}}if(K.timeout!==void 0){if(K.timeout<=0)throw Error("Timeout must be a positive number");let _=AbortSignal.timeout(K.timeout);if(K.signal!==void 0){if("any"in AbortSignal)K.signal=AbortSignal.any([K.signal,_])}else K.signal=_;delete K.timeout}return K}function M8(q={},{callbacks:$,maxConcurrency:K,recursionLimit:_,runName:P,configurable:O,runId:Y}={}){let H=D$(q);if($!==void 0)delete H.runName,H.callbacks=$;if(_!==void 0)H.recursionLimit=_;if(K!==void 0)H.maxConcurrency=K;if(P!==void 0)H.runName=P;if(O!==void 0)H.configurable={...H.configurable,...O};if(Y!==void 0)delete H.runId;return H}function XK(q){return q?{configurable:q.configurable,recursionLimit:q.recursionLimit,callbacks:q.callbacks,tags:q.tags,metadata:q.metadata,maxConcurrency:q.maxConcurrency,timeout:q.timeout,signal:q.signal}:void 0}async function B6(q,$){if($===void 0)return q;let K;return Promise.race([q.catch((_)=>{if(!$?.aborted)throw _;else return}),new Promise((_,P)=>{if(K=()=>{P(Error("Aborted"))},$.addEventListener("abort",K),$.aborted)P(Error("Aborted"))})]).finally(()=>$.removeEventListener("abort",K))}class S8 extends ReadableStream{constructor(){super(...arguments);Object.defineProperty(this,"reader",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}ensureReader(){if(!this.reader)this.reader=this.getReader()}async next(){this.ensureReader();try{let q=await this.reader.read();if(q.done)return this.reader.releaseLock(),{done:!0,value:void 0};else return{done:!1,value:q.value}}catch(q){throw this.reader.releaseLock(),q}}async return(){if(this.ensureReader(),this.locked){let q=this.reader.cancel();this.reader.releaseLock(),await q}return{done:!0,value:void 0}}async throw(q){if(this.ensureReader(),this.locked){let $=this.reader.cancel();this.reader.releaseLock(),await $}throw q}[Symbol.asyncIterator](){return this}async[Symbol.asyncDispose](){await this.return()}static fromReadableStream(q){let $=q.getReader();return new S8({start(K){return _();function _(){return $.read().then(({done:P,value:O})=>{if(P){K.close();return}return K.enqueue(O),_()})}},cancel(){$.releaseLock()}})}static fromAsyncGenerator(q){return new S8({async pull($){let{value:K,done:_}=await q.next();if(_)$.close();$.enqueue(K)},async cancel($){await q.return($)}})}}function NY(q,$=2){let K=Array.from({length:$},()=>[]);return K.map(async function*(P){while(!0)if(P.length===0){let O=await q.next();for(let Y of K)Y.push(O)}else if(P[0].done)return;else yield P.shift().value})}function EY(q,$){if(Array.isArray(q)&&Array.isArray($))return q.concat($);else if(typeof q==="string"&&typeof $==="string")return q+$;else if(typeof q==="number"&&typeof $==="number")return q+$;else if("concat"in q&&typeof q.concat==="function")return q.concat($);else if(typeof q==="object"&&typeof $==="object"){let K={...q};for(let[_,P]of Object.entries($))if(_ in K&&!Array.isArray(K[_]))K[_]=EY(K[_],P);else K[_]=P;return K}else throw Error(`Cannot concat ${typeof q} and ${typeof $}`)}class rK{constructor(q){Object.defineProperty(this,"generator",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"setup",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"config",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"signal",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"firstResult",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"firstResultUsed",{enumerable:!0,configurable:!0,writable:!0,value:!1}),this.generator=q.generator,this.config=q.config,this.signal=q.signal??this.config?.signal,this.setup=new Promise(($,K)=>{Y6.runWithConfig(XK(q.config),async()=>{if(this.firstResult=q.generator.next(),q.startSetup)this.firstResult.then(q.startSetup).then($,K);else this.firstResult.then((_)=>$(void 0),K)},!0)})}async next(...q){if(this.signal?.throwIfAborted(),!this.firstResultUsed)return this.firstResultUsed=!0,this.firstResult;return Y6.runWithConfig(XK(this.config),this.signal?async()=>{return B6(this.generator.next(...q),this.signal)}:async()=>{return this.generator.next(...q)},!0)}async return(q){return this.generator.return(q)}async throw(q){return this.generator.throw(q)}[Symbol.asyncIterator](){return this}async[Symbol.asyncDispose](){await this.return()}}async function Lz(q,$,K,_,...P){let O=new rK({generator:$,startSetup:K,signal:_}),Y=await O.setup;return{output:q(O,Y,...P),setup:Y}}class i6{constructor(q){Object.defineProperty(this,"ops",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.ops=q.ops??[]}concat(q){let $=this.ops.concat(q.ops),K=T_({},$);return new X4({ops:$,state:K[K.length-1].newDocument})}}class X4 extends i6{constructor(q){super(q);Object.defineProperty(this,"state",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.state=q.state}concat(q){let $=this.ops.concat(q.ops),K=T_(this.state,q.ops);return new X4({ops:$,state:K[K.length-1].newDocument})}static fromRunLogPatch(q){let $=T_({},q.ops);return new X4({ops:q.ops,state:$[$.length-1].newDocument})}}var yz=(q)=>q.name==="log_stream_tracer";async function bz(q,$){if($==="original")throw 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.");let{inputs:K}=q;if(["retriever","llm","prompt"].includes(q.run_type))return K;if(Object.keys(K).length===1&&K?.input==="")return;return K.input}async function gz(q,$){let{outputs:K}=q;if($==="original")return K;if(["retriever","llm","prompt"].includes(q.run_type))return K;if(K!==void 0&&Object.keys(K).length===1&&K?.output!==void 0)return K.output;return K}function _S(q){return q!==void 0&&q.message!==void 0}class r9 extends R6{constructor(q){super({_awaitHandler:!0,...q});Object.defineProperty(this,"autoClose",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"includeNames",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"includeTypes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"includeTags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeNames",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeTypes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeTags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_schemaFormat",{enumerable:!0,configurable:!0,writable:!0,value:"original"}),Object.defineProperty(this,"rootId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"keyMapByRunId",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"counterMapByRunName",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"transformStream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"writer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"receiveStream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"log_stream_tracer"}),Object.defineProperty(this,"lc_prefer_streaming",{enumerable:!0,configurable:!0,writable:!0,value:!0}),this.autoClose=q?.autoClose??!0,this.includeNames=q?.includeNames,this.includeTypes=q?.includeTypes,this.includeTags=q?.includeTags,this.excludeNames=q?.excludeNames,this.excludeTypes=q?.excludeTypes,this.excludeTags=q?.excludeTags,this._schemaFormat=q?._schemaFormat??this._schemaFormat,this.transformStream=new TransformStream,this.writer=this.transformStream.writable.getWriter(),this.receiveStream=S8.fromReadableStream(this.transformStream.readable)}[Symbol.asyncIterator](){return this.receiveStream}async persistRun(q){}_includeRun(q){if(q.id===this.rootId)return!1;let $=q.tags??[],K=this.includeNames===void 0&&this.includeTags===void 0&&this.includeTypes===void 0;if(this.includeNames!==void 0)K=K||this.includeNames.includes(q.name);if(this.includeTypes!==void 0)K=K||this.includeTypes.includes(q.run_type);if(this.includeTags!==void 0)K=K||$.find((_)=>this.includeTags?.includes(_))!==void 0;if(this.excludeNames!==void 0)K=K&&!this.excludeNames.includes(q.name);if(this.excludeTypes!==void 0)K=K&&!this.excludeTypes.includes(q.run_type);if(this.excludeTags!==void 0)K=K&&$.every((_)=>!this.excludeTags?.includes(_));return K}async*tapOutputIterable(q,$){for await(let K of $){if(q!==this.rootId){let _=this.keyMapByRunId[q];if(_)await this.writer.write(new i6({ops:[{op:"add",path:`/logs/${_}/streamed_output/-`,value:K}]}))}yield K}}async onRunCreate(q){if(this.rootId===void 0)this.rootId=q.id,await this.writer.write(new i6({ops:[{op:"replace",path:"",value:{id:q.id,name:q.name,type:q.run_type,streamed_output:[],final_output:void 0,logs:{}}}]}));if(!this._includeRun(q))return;if(this.counterMapByRunName[q.name]===void 0)this.counterMapByRunName[q.name]=0;this.counterMapByRunName[q.name]+=1;let $=this.counterMapByRunName[q.name];this.keyMapByRunId[q.id]=$===1?q.name:`${q.name}:${$}`;let K={id:q.id,name:q.name,type:q.run_type,tags:q.tags??[],metadata:q.extra?.metadata??{},start_time:new Date(q.start_time).toISOString(),streamed_output:[],streamed_output_str:[],final_output:void 0,end_time:void 0};if(this._schemaFormat==="streaming_events")K.inputs=await bz(q,this._schemaFormat);await this.writer.write(new i6({ops:[{op:"add",path:`/logs/${this.keyMapByRunId[q.id]}`,value:K}]}))}async onRunUpdate(q){try{let $=this.keyMapByRunId[q.id];if($===void 0)return;let K=[];if(this._schemaFormat==="streaming_events")K.push({op:"replace",path:`/logs/${$}/inputs`,value:await bz(q,this._schemaFormat)});if(K.push({op:"add",path:`/logs/${$}/final_output`,value:await gz(q,this._schemaFormat)}),q.end_time!==void 0)K.push({op:"add",path:`/logs/${$}/end_time`,value:new Date(q.end_time).toISOString()});let _=new i6({ops:K});await this.writer.write(_)}finally{if(q.id===this.rootId){let $=new i6({ops:[{op:"replace",path:"/final_output",value:await gz(q,this._schemaFormat)}]});if(await this.writer.write($),this.autoClose)await this.writer.close()}}}async onLLMNewToken(q,$,K){let _=this.keyMapByRunId[q.id];if(_===void 0)return;let P=q.inputs.messages!==void 0,O;if(P)if(_S(K?.chunk))O=K?.chunk;else O=new k_({id:`run-${q.id}`,content:$});else O=$;let Y=new i6({ops:[{op:"add",path:`/logs/${_}/streamed_output_str/-`,value:$},{op:"add",path:`/logs/${_}/streamed_output/-`,value:O}]});await this.writer.write(Y)}}class l7{constructor(q){Object.defineProperty(this,"text",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"generationInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.text=q.text,this.generationInfo=q.generationInfo}concat(q){return new l7({text:this.text+q.text,generationInfo:{...this.generationInfo,...q.generationInfo}})}}function B9({name:q,serialized:$}){if(q!==void 0)return q;if($?.name!==void 0)return $.name;else if($?.id!==void 0&&Array.isArray($?.id))return $.id[$.id.length-1];return"Unnamed"}var pz=(q)=>q.name==="event_stream_tracer";class RY extends R6{constructor(q){super({_awaitHandler:!0,...q});Object.defineProperty(this,"autoClose",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"includeNames",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"includeTypes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"includeTags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeNames",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeTypes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeTags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"runInfoMap",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"tappedPromises",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"transformStream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"writer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"receiveStream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"event_stream_tracer"}),Object.defineProperty(this,"lc_prefer_streaming",{enumerable:!0,configurable:!0,writable:!0,value:!0}),this.autoClose=q?.autoClose??!0,this.includeNames=q?.includeNames,this.includeTypes=q?.includeTypes,this.includeTags=q?.includeTags,this.excludeNames=q?.excludeNames,this.excludeTypes=q?.excludeTypes,this.excludeTags=q?.excludeTags,this.transformStream=new TransformStream,this.writer=this.transformStream.writable.getWriter(),this.receiveStream=S8.fromReadableStream(this.transformStream.readable)}[Symbol.asyncIterator](){return this.receiveStream}async persistRun(q){}_includeRun(q){let $=q.tags??[],K=this.includeNames===void 0&&this.includeTags===void 0&&this.includeTypes===void 0;if(this.includeNames!==void 0)K=K||this.includeNames.includes(q.name);if(this.includeTypes!==void 0)K=K||this.includeTypes.includes(q.runType);if(this.includeTags!==void 0)K=K||$.find((_)=>this.includeTags?.includes(_))!==void 0;if(this.excludeNames!==void 0)K=K&&!this.excludeNames.includes(q.name);if(this.excludeTypes!==void 0)K=K&&!this.excludeTypes.includes(q.runType);if(this.excludeTags!==void 0)K=K&&$.every((_)=>!this.excludeTags?.includes(_));return K}async*tapOutputIterable(q,$){let K=await $.next();if(K.done)return;let _=this.runInfoMap.get(q);if(_===void 0){yield K.value;return}function P(Y,H){if(Y==="llm"&&typeof H==="string")return new l7({text:H});return H}let O=this.tappedPromises.get(q);if(O===void 0){let Y;O=new Promise((H)=>{Y=H}),this.tappedPromises.set(q,O);try{let H={event:`on_${_.runType}_stream`,run_id:q,name:_.name,tags:_.tags,metadata:_.metadata,data:{}};await this.send({...H,data:{chunk:P(_.runType,K.value)}},_),yield K.value;for await(let v of $){if(_.runType!=="tool"&&_.runType!=="retriever")await this.send({...H,data:{chunk:P(_.runType,v)}},_);yield v}}finally{Y()}}else{yield K.value;for await(let Y of $)yield Y}}async send(q,$){if(this._includeRun($))await this.writer.write(q)}async sendEndEvent(q,$){let K=this.tappedPromises.get(q.run_id);if(K!==void 0)K.then(()=>{this.send(q,$)});else await this.send(q,$)}async onLLMStart(q){let $=B9(q),K=q.inputs.messages!==void 0?"chat_model":"llm",_={tags:q.tags??[],metadata:q.extra?.metadata??{},name:$,runType:K,inputs:q.inputs};this.runInfoMap.set(q.id,_);let P=`on_${K}_start`;await this.send({event:P,data:{input:q.inputs},name:$,tags:q.tags??[],run_id:q.id,metadata:q.extra?.metadata??{}},_)}async onLLMNewToken(q,$,K){let _=this.runInfoMap.get(q.id),P,O;if(_===void 0)throw Error(`onLLMNewToken: Run ID ${q.id} not found in run map.`);if(this.runInfoMap.size===1)return;if(_.runType==="chat_model")if(O="on_chat_model_stream",K?.chunk===void 0)P=new k_({content:$,id:`run-${q.id}`});else P=K.chunk.message;else if(_.runType==="llm")if(O="on_llm_stream",K?.chunk===void 0)P=new l7({text:$});else P=K.chunk;else throw Error(`Unexpected run type ${_.runType}`);await this.send({event:O,data:{chunk:P},run_id:q.id,name:_.name,tags:_.tags,metadata:_.metadata},_)}async onLLMEnd(q){let $=this.runInfoMap.get(q.id);this.runInfoMap.delete(q.id);let K;if($===void 0)throw Error(`onLLMEnd: Run ID ${q.id} not found in run map.`);let _=q.outputs?.generations,P;if($.runType==="chat_model"){for(let O of _??[]){if(P!==void 0)break;P=O[0]?.message}K="on_chat_model_end"}else if($.runType==="llm")P={generations:_?.map((O)=>{return O.map((Y)=>{return{text:Y.text,generationInfo:Y.generationInfo}})}),llmOutput:q.outputs?.llmOutput??{}},K="on_llm_end";else throw Error(`onLLMEnd: Unexpected run type: ${$.runType}`);await this.sendEndEvent({event:K,data:{output:P,input:$.inputs},run_id:q.id,name:$.name,tags:$.tags,metadata:$.metadata},$)}async onChainStart(q){let $=B9(q),K=q.run_type??"chain",_={tags:q.tags??[],metadata:q.extra?.metadata??{},name:$,runType:q.run_type},P={};if(q.inputs.input===""&&Object.keys(q.inputs).length===1)P={},_.inputs={};else if(q.inputs.input!==void 0)P.input=q.inputs.input,_.inputs=q.inputs.input;else P.input=q.inputs,_.inputs=q.inputs;this.runInfoMap.set(q.id,_),await this.send({event:`on_${K}_start`,data:P,name:$,tags:q.tags??[],run_id:q.id,metadata:q.extra?.metadata??{}},_)}async onChainEnd(q){let $=this.runInfoMap.get(q.id);if(this.runInfoMap.delete(q.id),$===void 0)throw Error(`onChainEnd: Run ID ${q.id} not found in run map.`);let K=`on_${q.run_type}_end`,_=q.inputs??$.inputs??{},O={output:q.outputs?.output??q.outputs,input:_};if(_.input&&Object.keys(_).length===1)O.input=_.input,$.inputs=_.input;await this.sendEndEvent({event:K,data:O,run_id:q.id,name:$.name,tags:$.tags,metadata:$.metadata??{}},$)}async onToolStart(q){let $=B9(q),K={tags:q.tags??[],metadata:q.extra?.metadata??{},name:$,runType:"tool",inputs:q.inputs??{}};this.runInfoMap.set(q.id,K),await this.send({event:"on_tool_start",data:{input:q.inputs??{}},name:$,run_id:q.id,tags:q.tags??[],metadata:q.extra?.metadata??{}},K)}async onToolEnd(q){let $=this.runInfoMap.get(q.id);if(this.runInfoMap.delete(q.id),$===void 0)throw Error(`onToolEnd: Run ID ${q.id} not found in run map.`);if($.inputs===void 0)throw Error(`onToolEnd: Run ID ${q.id} is a tool call, and is expected to have traced inputs.`);let K=q.outputs?.output===void 0?q.outputs:q.outputs.output;await this.sendEndEvent({event:"on_tool_end",data:{output:K,input:$.inputs},run_id:q.id,name:$.name,tags:$.tags,metadata:$.metadata},$)}async onRetrieverStart(q){let $=B9(q),K="retriever",_={tags:q.tags??[],metadata:q.extra?.metadata??{},name:$,runType:"retriever",inputs:{query:q.inputs.query}};this.runInfoMap.set(q.id,_),await this.send({event:"on_retriever_start",data:{input:{query:q.inputs.query}},name:$,tags:q.tags??[],run_id:q.id,metadata:q.extra?.metadata??{}},_)}async onRetrieverEnd(q){let $=this.runInfoMap.get(q.id);if(this.runInfoMap.delete(q.id),$===void 0)throw Error(`onRetrieverEnd: Run ID ${q.id} not found in run map.`);await this.sendEndEvent({event:"on_retriever_end",data:{output:q.outputs?.documents??q.outputs,input:$.inputs},run_id:q.id,name:$.name,tags:$.tags,metadata:$.metadata},$)}async handleCustomEvent(q,$,K){let _=this.runInfoMap.get(K);if(_===void 0)throw Error(`handleCustomEvent: Run ID ${K} not found in run map.`);await this.send({event:"on_custom_event",run_id:K,name:q,tags:_.tags,metadata:_.metadata,data:$},_)}async finish(){let q=[...this.tappedPromises.values()];Promise.all(q).finally(()=>{this.writer.close()})}}var xz=K6(q9(),1),i9=K6(k9(),1),PS=[400,401,402,403,404,405,406,407,409],YS=(q)=>{if(q.message.startsWith("Cancel")||q.message.startsWith("AbortError")||q.name==="AbortError")throw q;if(q?.code==="ECONNABORTED")throw q;let $=q?.response?.status??q?.status;if($&&PS.includes(+$))throw q;if(q?.error?.code==="insufficient_quota"){let K=Error(q?.message);throw K.name="InsufficientQuotaError",K}};class U9{constructor(q){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,"onFailedAttempt",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"queue",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxConcurrency=q.maxConcurrency??1/0,this.maxRetries=q.maxRetries??6,this.onFailedAttempt=q.onFailedAttempt??YS;let $="default"in i9.default?i9.default.default:i9.default;this.queue=new $({concurrency:this.maxConcurrency})}call(q,...$){return this.queue.add(()=>xz.default(()=>q(...$).catch((K)=>{if(K instanceof Error)throw K;else throw Error(K)}),{onFailedAttempt:this.onFailedAttempt,retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0})}callWithOptions(q,$,...K){if(q.signal)return Promise.race([this.call($,...K),new Promise((_,P)=>{q.signal?.addEventListener("abort",()=>{P(Error("AbortError"))})})]);return this.call($,...K)}fetch(...q){return this.call(()=>fetch(...q).then(($)=>$.ok?$:Promise.reject($)))}}class F9 extends R6{constructor({config:q,onStart:$,onEnd:K,onError:_}){super({_awaitHandler:!0});Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"RootListenersTracer"}),Object.defineProperty(this,"rootId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"config",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"argOnStart",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"argOnEnd",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"argOnError",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.config=q,this.argOnStart=$,this.argOnEnd=K,this.argOnError=_}persistRun(q){return Promise.resolve()}async onRunCreate(q){if(this.rootId)return;if(this.rootId=q.id,this.argOnStart)await this.argOnStart(q,this.config)}async onRunUpdate(q){if(q.id!==this.rootId)return;if(!q.error){if(this.argOnEnd)await this.argOnEnd(q,this.config)}else if(this.argOnError)await this.argOnError(q,this.config)}}function d7(q){return q?q.lc_runnable:!1}class hY{constructor(q){Object.defineProperty(this,"includeNames",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"includeTypes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"includeTags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeNames",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeTypes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeTags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.includeNames=q.includeNames,this.includeTypes=q.includeTypes,this.includeTags=q.includeTags,this.excludeNames=q.excludeNames,this.excludeTypes=q.excludeTypes,this.excludeTags=q.excludeTags}includeEvent(q,$){let K=this.includeNames===void 0&&this.includeTypes===void 0&&this.includeTags===void 0,_=q.tags??[];if(this.includeNames!==void 0)K=K||this.includeNames.includes(q.name);if(this.includeTypes!==void 0)K=K||this.includeTypes.includes($);if(this.includeTags!==void 0)K=K||_.some((P)=>this.includeTags?.includes(P));if(this.excludeNames!==void 0)K=K&&!this.excludeNames.includes(q.name);if(this.excludeTypes!==void 0)K=K&&!this.excludeTypes.includes($);if(this.excludeTags!==void 0)K=K&&_.every((P)=>!this.excludeTags?.includes(P));return K}}function DY(q){return q.replace(/[^a-zA-Z-_0-9]/g,"_")}var jS=["*","_","`"];function OS(q){let $="";for(let[K,_]of Object.entries(q))$+=` classDef ${K} ${_};
|
|
87
87
|
`;return $}function uz(q,$,K){let{firstNode:_,lastNode:P,nodeColors:O,withStyles:Y=!0,curveStyle:H="linear",wrapLabelNWords:v=9}=K??{},X=Y?`%%{init: {'flowchart': {'curve': '${H}'}}}%%
|
|
88
88
|
graph TD;
|
|
@@ -602,5 +602,5 @@ Data: ${JSON.stringify(K.metadata)}
|
|
|
602
602
|
`}`}).join(`
|
|
603
603
|
`)}var ia=!0,Ua=!1,Fa={check:async()=>({status:"not-applicable",environment:"browser"}),isHealthy:()=>!0};export{qL as validateUuid,wX as validateCharacter,ha as updateWorldSettings,df as unsaltWorldSettings,sy as unsaltSettingValue,MQ as truncateToCompleteSentence,CQ as trimTokens,hy as toString,pf as toHex,mP as stringToUuid,SQ as splitChunks,gy as slice,oQ as shouldRespondTemplate,KF as setEnv,Fa as serverHealth,qp as saltWorldSettings,ey as saltSettingValue,C3 as safeReplacer,WQ as recentLogs,xy as randomBytes,EQ as prewarmUuidCache,rQ as postCreationTemplate,HX as parseKeyValueXml,VQ as parseJSONObjectFromText,NQ as parseBooleanFromText,LQ as parseAndValidateCharacter,PX as normalizeJsonString,FQ as multiStepSummaryTemplate,UQ as multiStepDecisionTemplate,nQ as messageHandlerTemplate,U$ as logger,bQ as isValidCharacter,Ua as isNode,zp as isMessageMetadata,Hp as isFragmentMetadata,Tp as isFragmentMemory,Wp as isDocumentMetadata,wp as isDocumentMemory,Jp as isDescriptionMetadata,vp as isCustomMetadata,Dy as isBuffer,ia as isBrowser,Ia as initializeOnboarding,YF as initBrowserEnvironment,iQ as imageDescriptionTemplate,_F as hasEnv,Da as getWorldSettings,eQ as getUserServerRole,Mp as getTypedService,r_ as getSalt,ST as getNumberEnv,Np as getModelSpecificSettingKey,Xp as getMemoryText,hQ as getLocalServerUrl,Q4 as getEnvironment,q_ as getEnv,na as getEntityDetails,RQ as getContentTypeFromMimeType,PF as getBooleanEnv,Ry as fromString,Ey as fromHex,Ly as fromBytes,WX as formatTimestamp,GQ as formatPosts,ZQ as formatMessages,ra as formatEntities,cQ as formatActions,mQ as formatActionNames,sQ as findWorldsForOwner,oa as findEntityByName,yy as equals,La as encryptedCharacter,lf as encryptStringValue,mf as encryptObjectValues,OQ as elizaLogger,ZT as detectEnvironment,pa as defineService,ba as decryptedCharacter,J5 as decryptStringValue,J5 as decryptSecret,cf as decryptObjectValues,jQ as customLevels,jF as currentRuntime,n_ as createUniqueUuid,Qy as createSettingFromConfig,Sp as createServiceError,$p as createService,Op as createMessageMemory,uP as createLogger,Zp as createActionResult,by as concat,AQ as composePromptFromState,jX as composePrompt,uQ as composeActionExamples,Ra as clearSaltCache,vL as characterSchema,py as byteLength,BQ as booleanFooter,Yp as asUUID,Iy as alloc,kQ as addHeader,_Q as __loggerTestHooks,Rp as VECTOR_DIMS,qA as TeeType,sf as TEEMode,r$ as ServiceType,of as ServiceBuilder,I$ as Service,Fy as Semaphore,KA as SOCKET_MESSAGE_TYPE,Qf as Role,ef as PlatformPrefix,L8 as ModelType,Uf as MemoryType,X7 as MODEL_SETTINGS,Ff as KnowledgeScope,HA as IWebSearchService,_A as IWalletService,jA as IVideoService,WA as ITranscriptionService,$A as ITokenDataService,vA as IPostService,YA as IPdfService,JA as IMessageService,PA as ILpService,zA as IEmailService,OA as IBrowserService,Xj as EventType,MT as Environment,my as DatabaseAdapter,wj as ContentType,Tj as ChannelType,tf as CacheKeyPrefix,Y_ as BufferUtils,Wj as BM25,af as AgentStatus,ty as AgentRuntime};
|
|
604
604
|
|
|
605
|
-
//# debugId=
|
|
605
|
+
//# debugId=12259F2E8E00B0EB64756E2164756E21
|
|
606
606
|
//# sourceMappingURL=index.browser.js.map
|