@mcp-use/inspector 0.4.13-canary.0 → 0.4.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/client/assets/{chunk-VL2OQCWN-D5zTMCrV.js → chunk-VL2OQCWN-C61KfPSl.js} +2 -2
- package/dist/client/assets/embeddings-BIo-kwlO.js +1 -0
- package/dist/client/assets/{index-D2syF8VP.js → index-BLLgp4UX.js} +4 -4
- package/dist/client/assets/index-Cva-hqGs.js +4 -0
- package/dist/client/assets/{index-jpgFjbgb.js → index-D1RB_-JK.js} +3 -3
- package/dist/client/assets/{index-B1m6hcte.js → index-dXj4eNzX.js} +1 -1
- package/dist/client/assets/{index-q-FFFyxK.js → index-g0U2Uz9F.js} +6 -6
- package/dist/client/assets/{index-X8eKTn1y.js → index-gQstsvsJ.js} +4 -4
- package/dist/client/assets/index-jQGzGE29.js +150 -0
- package/dist/client/assets/{langfuse-C4HKZ3NL-DxYt-pQv.js → langfuse-C4HKZ3NL-ComM_afA.js} +45 -45
- package/dist/client/assets/{winston-PkVSuyBJ.js → winston-B9dQmIAy.js} +1 -1
- package/dist/client/index.html +2 -2
- package/package.json +2 -2
- package/dist/client/assets/embeddings-T3ulhIAT.js +0 -1
- package/dist/client/assets/index-BgTUJ2nU.js +0 -81
- package/dist/client/assets/index-D8wSHXf0.js +0 -70
- package/dist/client/assets/index-DOTQn2XV.js +0 -4
|
@@ -1,81 +0,0 @@
|
|
|
1
|
-
import{s as Fr,v as G,P as ue,p as lt,a as Sn,b as ha,c as Q,e as pa,f as Ee,_ as Br,$ as zr,h as Hr,i as Gr,j as fa,k as sn,l as Zr,m as qr,t as En,d as Jr,V as Vr,n as Wr,o as st}from"./chunk-VL2OQCWN-D5zTMCrV.js";import{Z as T,a as Tn,o as Kr,s as Qr}from"./index-D2syF8VP.js";var Yr=Object.defineProperty,D=(e,t)=>{for(var n in t)Yr(e,n,{get:t[n],enumerable:!0})};function ge(e){return typeof e=="object"&&e!==null&&"type"in e&&typeof e.type=="string"&&"source_type"in e&&(e.source_type==="url"||e.source_type==="base64"||e.source_type==="text"||e.source_type==="id")}function ma(e){return ge(e)&&e.source_type==="url"&&"url"in e&&typeof e.url=="string"}function ga(e){return ge(e)&&e.source_type==="base64"&&"data"in e&&typeof e.data=="string"}function Xr(e){return ge(e)&&e.source_type==="text"&&"text"in e&&typeof e.text=="string"}function _a(e){return ge(e)&&e.source_type==="id"&&"id"in e&&typeof e.id=="string"}function ei(e){if(ge(e)){if(e.source_type==="url")return{type:"image_url",image_url:{url:e.url}};if(e.source_type==="base64"){if(!e.mime_type)throw new Error("mime_type key is required for base64 data.");return{type:"image_url",image_url:{url:`data:${e.mime_type};base64,${e.data}`}}}}throw new Error("Unsupported source type. Only 'url' and 'base64' are supported.")}function ti(e){const t=e.split(";")[0].split("/");if(t.length!==2)throw new Error(`Invalid mime type: "${e}" - does not match type/subtype format.`);const n=t[0].trim(),a=t[1].trim();if(n===""||a==="")throw new Error(`Invalid mime type: "${e}" - type or subtype is empty.`);const r={};for(const i of e.split(";").slice(1)){const s=i.split("=");if(s.length!==2)throw new Error(`Invalid parameter syntax in mime type: "${e}".`);const o=s[0].trim(),c=s[1].trim();if(o==="")throw new Error(`Invalid parameter syntax in mime type: "${e}".`);r[o]=c}return{type:n,subtype:a,parameters:r}}function Ht({dataUrl:e,asTypedArray:t=!1}){const n=e.match(/^data:(\w+\/\w+);base64,([A-Za-z0-9+/]+=*)$/);let a;if(n){a=n[1].toLowerCase();const r=t?Uint8Array.from(atob(n[2]),i=>i.charCodeAt(0)):n[2];return{mime_type:a,data:r}}}function ni(e,t){if(e.type==="text"){if(!t.fromStandardTextBlock)throw new Error(`Converter for ${t.providerName} does not implement \`fromStandardTextBlock\` method.`);return t.fromStandardTextBlock(e)}if(e.type==="image"){if(!t.fromStandardImageBlock)throw new Error(`Converter for ${t.providerName} does not implement \`fromStandardImageBlock\` method.`);return t.fromStandardImageBlock(e)}if(e.type==="audio"){if(!t.fromStandardAudioBlock)throw new Error(`Converter for ${t.providerName} does not implement \`fromStandardAudioBlock\` method.`);return t.fromStandardAudioBlock(e)}if(e.type==="file"){if(!t.fromStandardFileBlock)throw new Error(`Converter for ${t.providerName} does not implement \`fromStandardFileBlock\` method.`);return t.fromStandardFileBlock(e)}throw new Error(`Unable to convert content block type '${e.type}' to provider-specific format: not recognized.`)}function ya(e){return typeof e=="object"&&e!==null&&"type"in e&&"content"in e&&(typeof e.content=="string"||Array.isArray(e.content))}function ai(e,t){return t?.[e]||Fr(e)}function ri(e,t,n){const a={};for(const r in e)Object.hasOwn(e,r)&&(a[t(r,n)]=e[r]);return a}var ii={};D(ii,{Serializable:()=>Ge,get_lc_unique_name:()=>on});function An(e){return Array.isArray(e)?[...e]:{...e}}function si(e,t){const n=An(e);for(const[a,r]of Object.entries(t)){const[i,...s]=a.split(".").reverse();let o=n;for(const c of s.reverse()){if(o[c]===void 0)break;o[c]=An(o[c]),o=o[c]}o[i]!==void 0&&(o[i]={lc:1,type:"secret",id:[r]})}return n}function on(e){const t=Object.getPrototypeOf(e);return typeof e.lc_name=="function"&&(typeof t.lc_name!="function"||e.lc_name()!==t.lc_name())?e.lc_name():e.name}var Ge=class wa{lc_serializable=!1;lc_kwargs;static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,on(this.constructor)]}get lc_secrets(){}get lc_attributes(){}get lc_aliases(){}get lc_serializable_keys(){}constructor(t,...n){this.lc_serializable_keys!==void 0?this.lc_kwargs=Object.fromEntries(Object.entries(t||{}).filter(([a])=>this.lc_serializable_keys?.includes(a))):this.lc_kwargs=t??{}}toJSON(){if(!this.lc_serializable)return this.toJSONNotImplemented();if(this.lc_kwargs instanceof wa||typeof this.lc_kwargs!="object"||Array.isArray(this.lc_kwargs))return this.toJSONNotImplemented();const t={},n={},a=Object.keys(this.lc_kwargs).reduce((r,i)=>(r[i]=i in this?this[i]:this.lc_kwargs[i],r),{});for(let r=Object.getPrototypeOf(this);r;r=Object.getPrototypeOf(r))Object.assign(t,Reflect.get(r,"lc_aliases",this)),Object.assign(n,Reflect.get(r,"lc_secrets",this)),Object.assign(a,Reflect.get(r,"lc_attributes",this));return Object.keys(n).forEach(r=>{let i=this,s=a;const[o,...c]=r.split(".").reverse();for(const l of c.reverse()){if(!(l in i)||i[l]===void 0)return;(!(l in s)||s[l]===void 0)&&(typeof i[l]=="object"&&i[l]!=null?s[l]={}:Array.isArray(i[l])&&(s[l]=[])),i=i[l],s=s[l]}o in i&&i[o]!==void 0&&(s[o]=s[o]||i[o])}),{lc:1,type:"constructor",id:this.lc_id,kwargs:ri(Object.keys(n).length?si(a,n):a,ai,t)}}toJSONNotImplemented(){return{lc:1,type:"not_implemented",id:this.lc_id}}};function w(e,t){return b(e)&&e.type===t}function b(e){return typeof e=="object"&&e!==null}function se(e){return Array.isArray(e)}function m(e){return typeof e=="string"}function ne(e){return typeof e=="number"}function cn(e){return e instanceof Uint8Array}function In(e){try{return JSON.parse(e)}catch{return}}const Ze=e=>e();function oi(e){if(e.type==="char_location"&&m(e.document_title)&&ne(e.start_char_index)&&ne(e.end_char_index)&&m(e.cited_text)){const{document_title:t,start_char_index:n,end_char_index:a,cited_text:r,...i}=e;return{...i,type:"citation",source:"char",title:t??void 0,startIndex:n,endIndex:a,citedText:r}}if(e.type==="page_location"&&m(e.document_title)&&ne(e.start_page_number)&&ne(e.end_page_number)&&m(e.cited_text)){const{document_title:t,start_page_number:n,end_page_number:a,cited_text:r,...i}=e;return{...i,type:"citation",source:"page",title:t??void 0,startIndex:n,endIndex:a,citedText:r}}if(e.type==="content_block_location"&&m(e.document_title)&&ne(e.start_block_index)&&ne(e.end_block_index)&&m(e.cited_text)){const{document_title:t,start_block_index:n,end_block_index:a,cited_text:r,...i}=e;return{...i,type:"citation",source:"block",title:t??void 0,startIndex:n,endIndex:a,citedText:r}}if(e.type==="web_search_result_location"&&m(e.url)&&m(e.title)&&m(e.encrypted_index)&&m(e.cited_text)){const{url:t,title:n,encrypted_index:a,cited_text:r,...i}=e;return{...i,type:"citation",source:"url",url:t,title:n,startIndex:Number(a),endIndex:Number(a),citedText:r}}if(e.type==="search_result_location"&&m(e.source)&&m(e.title)&&ne(e.start_block_index)&&ne(e.end_block_index)&&m(e.cited_text)){const{source:t,title:n,start_block_index:a,end_block_index:r,cited_text:i,...s}=e;return{...s,type:"citation",source:"search",url:t,title:n??void 0,startIndex:a,endIndex:r,citedText:i}}}function va(e){if(w(e,"document")&&b(e.source)&&"type"in e.source){if(e.source.type==="base64"&&m(e.source.media_type)&&m(e.source.data))return{type:"file",mimeType:e.source.media_type,data:e.source.data};if(e.source.type==="url"&&m(e.source.url))return{type:"file",url:e.source.url};if(e.source.type==="file"&&m(e.source.file_id))return{type:"file",fileId:e.source.file_id};if(e.source.type==="text"&&m(e.source.data))return{type:"file",mimeType:String(e.source.media_type??"text/plain"),data:e.source.data}}else if(w(e,"image")&&b(e.source)&&"type"in e.source){if(e.source.type==="base64"&&m(e.source.media_type)&&m(e.source.data))return{type:"image",mimeType:e.source.media_type,data:e.source.data};if(e.source.type==="url"&&m(e.source.url))return{type:"image",url:e.source.url};if(e.source.type==="file"&&m(e.source.file_id))return{type:"image",fileId:e.source.file_id}}}function ci(e){function*t(){for(const n of e){const a=va(n);a?yield a:yield n}}return Array.from(t())}function On(e){function*t(){const n=typeof e.content=="string"?[{type:"text",text:e.content}]:e.content;for(const a of n){if(w(a,"text")&&m(a.text)){const{text:r,citations:i,...s}=a;if(se(i)&&i.length){const o=i.reduce((c,l)=>{const u=oi(l);return u?[...c,u]:c},[]);yield{...s,type:"text",text:r,annotations:o};continue}else{yield{...s,type:"text",text:r};continue}}else if(w(a,"thinking")&&m(a.thinking)){const{thinking:r,signature:i,...s}=a;yield{...s,type:"reasoning",reasoning:r,signature:i};continue}else if(w(a,"redacted_thinking")){yield{type:"non_standard",value:a};continue}else if(w(a,"tool_use")&&m(a.name)&&m(a.id)){yield{type:"tool_call",id:a.id,name:a.name,args:a.input};continue}else if(w(a,"input_json_delta")){if(ui(e)&&e.tool_call_chunks?.length){const r=e.tool_call_chunks[0];yield{type:"tool_call_chunk",id:r.id,name:r.name,args:r.args,index:r.index};continue}}else if(w(a,"server_tool_use")&&m(a.name)&&m(a.id)){const{name:r,id:i}=a;if(r==="web_search"){const s=Ze(()=>{if(typeof a.input=="string")return a.input;if(b(a.input)&&m(a.input.query))return a.input.query;if(m(a.partial_json)){const o=In(a.partial_json);if(o?.query)return o.query}return""});yield{id:i,type:"server_tool_call",name:"web_search",args:{query:s}};continue}else if(a.name==="code_execution"){const s=Ze(()=>{if(typeof a.input=="string")return a.input;if(b(a.input)&&m(a.input.code))return a.input.code;if(m(a.partial_json)){const o=In(a.partial_json);if(o?.code)return o.code}return""});yield{id:i,type:"server_tool_call",name:"code_execution",args:{code:s}};continue}}else if(w(a,"web_search_tool_result")&&m(a.tool_use_id)&&se(a.content)){const{content:r,tool_use_id:i}=a,s=r.reduce((o,c)=>w(c,"web_search_result")?[...o,c.url]:o,[]);yield{type:"server_tool_call_result",name:"web_search",toolCallId:i,status:"success",output:{urls:s}};continue}else if(w(a,"code_execution_tool_result")&&m(a.tool_use_id)&&b(a.content)){yield{type:"server_tool_call_result",name:"code_execution",toolCallId:a.tool_use_id,status:"success",output:a.content};continue}else if(w(a,"mcp_tool_use")){yield{id:a.id,type:"server_tool_call",name:"mcp_tool_use",args:a.input};continue}else if(w(a,"mcp_tool_result")&&m(a.tool_use_id)&&b(a.content)){yield{type:"server_tool_call_result",name:"mcp_tool_use",toolCallId:a.tool_use_id,status:"success",output:a.content};continue}else if(w(a,"container_upload")){yield{type:"server_tool_call",name:"container_upload",args:a.input};continue}else if(w(a,"search_result")){yield{id:a.id,type:"non_standard",value:a};continue}else if(w(a,"tool_result")){yield{id:a.id,type:"non_standard",value:a};continue}else{const r=va(a);if(r){yield r;continue}}yield{type:"non_standard",value:a}}}return Array.from(t())}const li={translateContent:On,translateContentChunk:On};function ui(e){return typeof e?._getType=="function"&&typeof e.concat=="function"&&e._getType()==="ai"}function di(e){return ma(e)?{type:e.type,mimeType:e.mime_type,url:e.url,metadata:e.metadata}:ga(e)?{type:e.type,mimeType:e.mime_type??"application/octet-stream",data:e.data,metadata:e.metadata}:_a(e)?{type:e.type,mimeType:e.mime_type,fileId:e.id,metadata:e.metadata}:e}function hi(e){return e.map(di)}function pi(e){return!!(w(e,"image_url")&&b(e.image_url)||w(e,"input_audio")&&b(e.input_audio)||w(e,"file")&&b(e.file))}function fi(e){if(w(e,"image_url")&&b(e.image_url)&&m(e.image_url.url)){const t=Ht({dataUrl:e.image_url.url});return t?{type:"image",mimeType:t.mime_type,data:t.data}:{type:"image",url:e.image_url.url}}else{if(w(e,"input_audio")&&b(e.input_audio)&&m(e.input_audio.data)&&m(e.input_audio.format))return{type:"audio",data:e.input_audio.data,mimeType:`audio/${e.input_audio.format}`};if(w(e,"file")&&b(e.file)&&m(e.file.data)){const t=Ht({dataUrl:e.file.data});if(t)return{type:"file",data:t.data,mimeType:t.mime_type};if(m(e.file.file_id))return{type:"file",fileId:e.file.file_id}}}return e}function mi(e){const t=[];typeof e.content=="string"?t.push({type:"text",text:e.content}):t.push(...ln(e.content));for(const n of e.tool_calls??[])t.push({type:"tool_call",id:n.id,name:n.name,args:n.args});return t}function gi(e){const t=[];typeof e.content=="string"?t.push({type:"text",text:e.content}):t.push(...ln(e.content));for(const n of e.tool_calls??[])t.push({type:"tool_call",id:n.id,name:n.name,args:n.args});return t}function ln(e){const t=[];for(const n of e)pi(n)?t.push(fi(n)):t.push(n);return t}function _i(e){if(e.type==="url_citation"){const{url:t,title:n,start_index:a,end_index:r}=e;return{type:"citation",url:t,title:n,startIndex:a,endIndex:r}}if(e.type==="file_citation"){const{file_id:t,filename:n,index:a}=e;return{type:"citation",title:n,startIndex:a,endIndex:a,fileId:t}}return e}function ba(e){function*t(){b(e.additional_kwargs?.reasoning)&&se(e.additional_kwargs.reasoning.summary)&&(yield{type:"reasoning",reasoning:e.additional_kwargs.reasoning.summary.reduce((r,i)=>b(i)&&m(i.text)?`${r}${i.text}`:r,"")});const n=typeof e.content=="string"?[{type:"text",text:e.content}]:e.content;for(const a of n)if(w(a,"text")){const{text:r,annotations:i,...s}=a;Array.isArray(i)?yield{...s,type:"text",text:String(r),annotations:i.map(_i)}:yield{...s,type:"text",text:String(r)}}for(const a of e.tool_calls??[])yield{type:"tool_call",id:a.id,name:a.name,args:a.args};if(b(e.additional_kwargs)&&se(e.additional_kwargs.tool_outputs))for(const a of e.additional_kwargs.tool_outputs){if(w(a,"web_search_call")){yield{id:a.id,type:"server_tool_call",name:"web_search",args:{query:a.query}};continue}else if(w(a,"file_search_call")){yield{id:a.id,type:"server_tool_call",name:"file_search",args:{query:a.query}};continue}else if(w(a,"computer_call")){yield{type:"non_standard",value:a};continue}else if(w(a,"code_interpreter_call")){if(m(a.code)&&(yield{id:a.id,type:"server_tool_call",name:"code_interpreter",args:{code:a.code}}),se(a.outputs)){const r=Ze(()=>{if(a.status!=="in_progress"){if(a.status==="completed")return 0;if(a.status==="incomplete")return 127;if(a.status!=="interpreting"&&a.status==="failed")return 1}});for(const i of a.outputs)if(w(i,"logs")){yield{type:"server_tool_call_result",toolCallId:a.id??"",status:"success",output:{type:"code_interpreter_output",returnCode:r??0,stderr:[0,void 0].includes(r)?void 0:String(i.logs),stdout:[0,void 0].includes(r)?String(i.logs):void 0}};continue}}continue}else if(w(a,"mcp_call")){yield{id:a.id,type:"server_tool_call",name:"mcp_call",args:a.input};continue}else if(w(a,"mcp_list_tools")){yield{id:a.id,type:"server_tool_call",name:"mcp_list_tools",args:a.input};continue}else if(w(a,"mcp_approval_request")){yield{type:"non_standard",value:a};continue}else if(w(a,"image_generation_call")){yield{type:"non_standard",value:a};continue}b(a)&&(yield{type:"non_standard",value:a})}}return Array.from(t())}function yi(e){function*t(){yield*ba(e);for(const n of e.tool_call_chunks??[])yield{type:"tool_call_chunk",id:n.id,name:n.name,args:n.args}}return Array.from(t())}const wi={translateContent:e=>typeof e.content=="string"?mi(e):ba(e),translateContentChunk:e=>typeof e.content=="string"?gi(e):yi(e)};function vi(e,t="pretty"){return t==="pretty"?bi(e):JSON.stringify(e)}function bi(e){const t=[],n=` ${e.type.charAt(0).toUpperCase()+e.type.slice(1)} Message `,a=Math.floor((80-n.length)/2),r="=".repeat(a),i=n.length%2===0?r:`${r}=`;if(t.push(`${r}${n}${i}`),e.type==="ai"){const s=e;if(s.tool_calls&&s.tool_calls.length>0){t.push("Tool Calls:");for(const o of s.tool_calls){t.push(` ${o.name} (${o.id})`),t.push(` Call ID: ${o.id}`),t.push(" Args:");for(const[c,l]of Object.entries(o.args))t.push(` ${c}: ${l}`)}}}if(e.type==="tool"){const s=e;s.name&&t.push(`Name: ${s.name}`)}return typeof e.content=="string"&&e.content.trim()&&(t.length>1&&t.push(""),t.push(e.content)),t.join(`
|
|
2
|
-
`)}const Ot=Symbol.for("langchain.message");function Ae(e,t){return typeof e=="string"?e===""?t:typeof t=="string"?e+t:Array.isArray(t)&&t.some(n=>ge(n))?[{type:"text",source_type:"text",text:e},...t]:[{type:"text",text:e},...t]:Array.isArray(t)?Qe(e,t)??[...e,...t]:t===""?e:Array.isArray(e)&&e.some(n=>ge(n))?[...e,{type:"file",source_type:"text",text:t}]:[...e,{type:"text",text:t}]}function Sa(e,t){return e==="error"||t==="error"?"error":"success"}function Si(e,t){function n(a,r){if(typeof a!="object"||a===null||a===void 0)return a;if(r>=t)return Array.isArray(a)?"[Array]":"[Object]";if(Array.isArray(a))return a.map(s=>n(s,r+1));const i={};for(const s of Object.keys(a))i[s]=n(a[s],r+1);return i}return JSON.stringify(n(e,0),null,2)}var pe=class extends Ge{lc_namespace=["langchain_core","messages"];lc_serializable=!0;get lc_aliases(){return{additional_kwargs:"additional_kwargs",response_metadata:"response_metadata"}}[Ot]=!0;id;name;content;additional_kwargs;response_metadata;_getType(){return this.type}getType(){return this._getType()}constructor(e){const t=typeof e=="string"||Array.isArray(e)?{content:e}:e;t.additional_kwargs||(t.additional_kwargs={}),t.response_metadata||(t.response_metadata={}),super(t),this.name=t.name,t.content===void 0&&t.contentBlocks!==void 0?(this.content=t.contentBlocks,this.response_metadata={output_version:"v1",...t.response_metadata}):t.content!==void 0?(this.content=t.content??[],this.response_metadata=t.response_metadata):(this.content=[],this.response_metadata=t.response_metadata),this.additional_kwargs=t.additional_kwargs,this.id=t.id}get text(){return typeof this.content=="string"?this.content:Array.isArray(this.content)?this.content.map(e=>typeof e=="string"?e:e.type==="text"?e.text:"").join(""):""}get contentBlocks(){const e=typeof this.content=="string"?[{type:"text",text:this.content}]:this.content;return[hi,ln,ci].reduce((a,r)=>r(a),e)}toDict(){return{type:this.getType(),data:this.toJSON().kwargs}}static lc_name(){return"BaseMessage"}get _printableFields(){return{id:this.id,content:this.content,name:this.name,additional_kwargs:this.additional_kwargs,response_metadata:this.response_metadata}}static isInstance(e){return typeof e=="object"&&e!==null&&Ot in e&&e[Ot]===!0&&ya(e)}_updateId(e){this.id=e,this.lc_kwargs.id=e}get[Symbol.toStringTag](){return this.constructor.lc_name()}[Symbol.for("nodejs.util.inspect.custom")](e){if(e===null)return this;const t=Si(this._printableFields,Math.max(4,e));return`${this.constructor.lc_name()} ${t}`}toFormattedString(e="pretty"){return vi(this,e)}};function Ei(e){return Array.isArray(e)&&e.every(t=>typeof t.index=="number")}function B(e={},t={}){const n={...e};for(const[a,r]of Object.entries(t))if(n[a]==null)n[a]=r;else{if(r==null)continue;if(typeof n[a]!=typeof r||Array.isArray(n[a])!==Array.isArray(r))throw new Error(`field[${a}] already exists in the message chunk, but with a different type.`);if(typeof n[a]=="string"){if(a==="type")continue;["id","name","output_version","model_provider"].includes(a)?n[a]=r:n[a]+=r}else if(typeof n[a]=="object"&&!Array.isArray(n[a]))n[a]=B(n[a],r);else if(Array.isArray(n[a]))n[a]=Qe(n[a],r);else{if(n[a]===r)continue;console.warn(`field[${a}] already exists in this message chunk and value has unsupported type.`)}}return n}function Qe(e,t){if(!(e===void 0&&t===void 0)){if(e===void 0||t===void 0)return e||t;{const n=[...e];for(const a of t)if(typeof a=="object"&&a!==null&&"index"in a&&typeof a.index=="number"){const r=n.findIndex(i=>{const s=typeof i=="object",o="index"in i&&i.index===a.index,c="id"in i&&"id"in a&&i?.id===a?.id,l=!("id"in i)||!i?.id||!("id"in a)||!a?.id;return s&&o&&(c||l)});r!==-1&&typeof n[r]=="object"&&n[r]!==null?n[r]=B(n[r],a):n.push(a)}else{if(typeof a=="object"&&a!==null&&"text"in a&&a.text==="")continue;n.push(a)}return n}}}function Ea(e,t){if(!e&&!t)throw new Error("Cannot merge two undefined objects.");if(!e||!t)return e||t;if(typeof e!=typeof t)throw new Error(`Cannot merge objects of different types.
|
|
3
|
-
Left ${typeof e}
|
|
4
|
-
Right ${typeof t}`);if(typeof e=="string"&&typeof t=="string")return e+t;if(Array.isArray(e)&&Array.isArray(t))return Qe(e,t);if(typeof e=="object"&&typeof t=="object")return B(e,t);if(e===t)return e;throw new Error(`Can not merge objects of different types.
|
|
5
|
-
Left ${e}
|
|
6
|
-
Right ${t}`)}var Ie=class extends pe{static isInstance(e){return super.isInstance(e)&&"concat"in e&&typeof e.concat=="function"}};function Ta(e){return typeof e.role=="string"}function un(e){return typeof e?._getType=="function"}function Aa(e){return un(e)&&typeof e.concat=="function"}function Ia(e,t){return B(e??{},t??{})}function Oa(e,t){const n={};return(e?.audio!==void 0||t?.audio!==void 0)&&(n.audio=(e?.audio??0)+(t?.audio??0)),(e?.image!==void 0||t?.image!==void 0)&&(n.image=(e?.image??0)+(t?.image??0)),(e?.video!==void 0||t?.video!==void 0)&&(n.video=(e?.video??0)+(t?.video??0)),(e?.document!==void 0||t?.document!==void 0)&&(n.document=(e?.document??0)+(t?.document??0)),(e?.text!==void 0||t?.text!==void 0)&&(n.text=(e?.text??0)+(t?.text??0)),n}function Ti(e,t){const n={...Oa(e,t)};return(e?.cache_read!==void 0||t?.cache_read!==void 0)&&(n.cache_read=(e?.cache_read??0)+(t?.cache_read??0)),(e?.cache_creation!==void 0||t?.cache_creation!==void 0)&&(n.cache_creation=(e?.cache_creation??0)+(t?.cache_creation??0)),n}function Ai(e,t){const n={...Oa(e,t)};return(e?.reasoning!==void 0||t?.reasoning!==void 0)&&(n.reasoning=(e?.reasoning??0)+(t?.reasoning??0)),n}function Ca(e,t){return{input_tokens:(e?.input_tokens??0)+(t?.input_tokens??0),output_tokens:(e?.output_tokens??0)+(t?.output_tokens??0),total_tokens:(e?.total_tokens??0)+(t?.total_tokens??0),input_token_details:Ti(e?.input_token_details,t?.input_token_details),output_token_details:Ai(e?.output_token_details,t?.output_token_details)}}var Ii={};D(Ii,{ToolMessage:()=>Me,ToolMessageChunk:()=>vt,defaultToolCallParser:()=>dn,isDirectToolOutput:()=>xa,isToolMessage:()=>ka,isToolMessageChunk:()=>Ra});function xa(e){return e!=null&&typeof e=="object"&&"lc_direct_tool_output"in e&&e.lc_direct_tool_output===!0}var Me=class extends pe{static lc_name(){return"ToolMessage"}get lc_aliases(){return{tool_call_id:"tool_call_id"}}lc_direct_tool_output=!0;type="tool";status;tool_call_id;metadata;artifact;constructor(e,t,n){const a=typeof e=="string"||Array.isArray(e)?{content:e,name:n,tool_call_id:t}:e;super(a),this.tool_call_id=a.tool_call_id,this.artifact=a.artifact,this.status=a.status,this.metadata=a.metadata}static isInstance(e){return super.isInstance(e)&&e.type==="tool"}get _printableFields(){return{...super._printableFields,tool_call_id:this.tool_call_id,artifact:this.artifact}}},vt=class extends Ie{type="tool";tool_call_id;status;artifact;constructor(e){super(e),this.tool_call_id=e.tool_call_id,this.artifact=e.artifact,this.status=e.status}static lc_name(){return"ToolMessageChunk"}concat(e){const t=this.constructor;return new t({content:Ae(this.content,e.content),additional_kwargs:B(this.additional_kwargs,e.additional_kwargs),response_metadata:B(this.response_metadata,e.response_metadata),artifact:Ea(this.artifact,e.artifact),tool_call_id:this.tool_call_id,id:this.id??e.id,status:Sa(this.status,e.status)})}get _printableFields(){return{...super._printableFields,tool_call_id:this.tool_call_id,artifact:this.artifact}}};function dn(e){const t=[],n=[];for(const a of e)if(a.function){const r=a.function.name;try{const i=JSON.parse(a.function.arguments);t.push({name:r||"",args:i||{},id:a.id})}catch{n.push({name:r,args:a.function.arguments,id:a.id,error:"Malformed args."})}}else continue;return[t,n]}function ka(e){return typeof e=="object"&&e!==null&&"getType"in e&&typeof e.getType=="function"&&e.getType()==="tool"}function Ra(e){return e._getType()==="tool"}function Pl(e,t=Na){e=e.trim();const n=e.indexOf("```");if(n===-1)return t(e);let a=e.substring(n+3);a.startsWith(`json
|
|
7
|
-
`)?a=a.substring(5):a.startsWith("json")?a=a.substring(4):a.startsWith(`
|
|
8
|
-
`)&&(a=a.substring(1));const r=a.indexOf("```");let i=a;return r!==-1&&(i=a.substring(0,r)),t(i.trim())}function Na(e){if(typeof e>"u")return null;try{return JSON.parse(e)}catch{}let t="";const n=[];let a=!1,r=!1;for(let i of e){if(a)i==='"'&&!r?a=!1:i===`
|
|
9
|
-
`&&!r?i="\\n":i==="\\"?r=!r:r=!1;else if(i==='"')a=!0,r=!1;else if(i==="{")n.push("}");else if(i==="[")n.push("]");else if(i==="}"||i==="]")if(n&&n[n.length-1]===i)n.pop();else return null;t+=i}a&&(t+='"');for(let i=n.length-1;i>=0;i-=1)t+=n[i];try{return JSON.parse(t)}catch{return null}}function hn(e){switch(e){case"csv":return"text/csv";case"doc":return"application/vnd.openxmlformats-officedocument.wordprocessingml.document";case"docx":return"application/vnd.openxmlformats-officedocument.wordprocessingml.document";case"html":return"text/html";case"md":return"text/markdown";case"pdf":return"application/pdf";case"txt":return"text/plain";case"xls":return"application/vnd.ms-excel";case"xlsx":return"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";case"gif":return"image/gif";case"jpeg":return"image/jpeg";case"jpg":return"image/jpeg";case"png":return"image/png";case"webp":return"image/webp";case"flv":return"video/flv";case"mkv":return"video/mkv";case"mov":return"video/mov";case"mp4":return"video/mp4";case"mpeg":return"video/mpeg";case"mpg":return"video/mpg";case"three_gp":return"video/three_gp";case"webm":return"video/webm";case"wmv":return"video/wmv";default:return"application/octet-stream"}}function Oi(e){if(b(e.document)&&b(e.document.source)){const t=b(e.document)&&m(e.document.format)?e.document.format:"",n=hn(t);if(b(e.document.source)){if(b(e.document.source.s3Location)&&m(e.document.source.s3Location.uri))return{type:"file",mimeType:n,fileId:e.document.source.s3Location.uri};if(cn(e.document.source.bytes))return{type:"file",mimeType:n,data:e.document.source.bytes};if(m(e.document.source.text))return{type:"file",mimeType:n,data:Buffer.from(e.document.source.text).toString("base64")};if(se(e.document.source.content)){const a=e.document.source.content.reduce((r,i)=>b(i)&&m(i.text)?r+i.text:r,"");return{type:"file",mimeType:n,data:a}}}}return{type:"non_standard",value:e}}function Ci(e){if(w(e,"image")&&b(e.image)){const t=b(e.image)&&m(e.image.format)?e.image.format:"",n=hn(t);if(b(e.image.source)){if(b(e.image.source.s3Location)&&m(e.image.source.s3Location.uri))return{type:"image",mimeType:n,fileId:e.image.source.s3Location.uri};if(cn(e.image.source.bytes))return{type:"image",mimeType:n,data:e.image.source.bytes}}}return{type:"non_standard",value:e}}function xi(e){if(w(e,"video")&&b(e.video)){const t=b(e.video)&&m(e.video.format)?e.video.format:"",n=hn(t);if(b(e.video.source)){if(b(e.video.source.s3Location)&&m(e.video.source.s3Location.uri))return{type:"video",mimeType:n,fileId:e.video.source.s3Location.uri};if(cn(e.video.source.bytes))return{type:"video",mimeType:n,data:e.video.source.bytes}}}return{type:"non_standard",value:e}}function Cn(e){function*t(){const n=typeof e.content=="string"?[{type:"text",text:e.content}]:e.content;for(const a of n){if(w(a,"cache_point")){yield{type:"non_standard",value:a};continue}else if(w(a,"citations_content")&&b(a.citationsContent)){const r=se(a.citationsContent.content)?a.citationsContent.content.reduce((s,o)=>b(o)&&m(o.text)?s+o.text:s,""):"",i=se(a.citationsContent.citations)?a.citationsContent.citations.reduce((s,o)=>{if(b(o)){const c=se(o.sourceContent)?o.sourceContent.reduce((u,h)=>b(h)&&m(h.text)?u+h.text:u,""):"",l=Ze(()=>{if(b(o.location)){const u=o.location.documentChar||o.location.documentPage||o.location.documentChunk;if(b(u))return{source:ne(u.documentIndex)?u.documentIndex.toString():void 0,startIndex:ne(u.start)?u.start:void 0,endIndex:ne(u.end)?u.end:void 0}}return{}});s.push({type:"citation",citedText:c,...l})}return s},[]):[];yield{type:"text",text:r,annotations:i};continue}else if(w(a,"document")&&b(a.document)){yield Oi(a);continue}else if(w(a,"guard_content")){yield{type:"non_standard",value:a};continue}else if(w(a,"image")&&b(a.image)){yield Ci(a);continue}else if(w(a,"reasoning_content")&&m(a.reasoningText)){yield{type:"reasoning",reasoning:a.reasoningText};continue}else if(w(a,"text")&&m(a.text)){yield{type:"text",text:a.text};continue}else if(w(a,"tool_result")){yield{type:"non_standard",value:a};continue}else{if(w(a,"tool_call"))continue;if(w(a,"video")&&b(a.video)){yield xi(a);continue}}yield{type:"non_standard",value:a}}}return Array.from(t())}const ki={translateContent:Cn,translateContentChunk:Cn};function xn(e){function*t(){const n=typeof e.content=="string"?[{type:"text",text:e.content}]:e.content;for(const a of n){if(w(a,"text")&&m(a.text)){yield{type:"text",text:a.text};continue}else if(w(a,"inlineData")&&b(a.inlineData)&&m(a.inlineData.mimeType)&&m(a.inlineData.data)){yield{type:"file",mimeType:a.inlineData.mimeType,data:a.inlineData.data};continue}else if(w(a,"functionCall")&&b(a.functionCall)&&m(a.functionCall.name)&&b(a.functionCall.args)){yield{type:"tool_call",id:e.id,name:a.functionCall.name,args:a.functionCall.args};continue}else if(w(a,"functionResponse")){yield{type:"non_standard",value:a};continue}else if(w(a,"fileData")&&b(a.fileData)&&m(a.fileData.mimeType)&&m(a.fileData.fileUri)){yield{type:"file",mimeType:a.fileData.mimeType,fileId:a.fileData.fileUri};continue}else if(w(a,"executableCode")){yield{type:"non_standard",value:a};continue}else if(w(a,"codeExecutionResult")){yield{type:"non_standard",value:a};continue}yield{type:"non_standard",value:a}}}return Array.from(t())}const Ri={translateContent:xn,translateContentChunk:xn};function kn(e){function*t(){const n=typeof e.content=="string"?[{type:"text",text:e.content}]:e.content;for(const a of n){if(w(a,"reasoning")&&m(a.reasoning)){const r=Ze(()=>{const i=n.indexOf(a);if(se(e.additional_kwargs?.signatures)&&i>=0)return e.additional_kwargs.signatures.at(i)});m(r)?yield{type:"reasoning",reasoning:a.reasoning,signature:r}:yield{type:"reasoning",reasoning:a.reasoning};continue}else if(w(a,"text")&&m(a.text)){yield{type:"text",text:a.text};continue}else if(w(a,"image_url")){if(m(a.image_url))if(a.image_url.startsWith("data:")){const r=/^data:([^;]+);base64,(.+)$/,i=a.image_url.match(r);i?yield{type:"image",data:i[2],mimeType:i[1]}:yield{type:"image",url:a.image_url}}else yield{type:"image",url:a.image_url};continue}else if(w(a,"media")&&m(a.mimeType)&&m(a.data)){yield{type:"file",mimeType:a.mimeType,data:a.data};continue}yield{type:"non_standard",value:a}}}return Array.from(t())}const Ni={translateContent:kn,translateContentChunk:kn};globalThis.lc_block_translators_registry??=new Map([["anthropic",li],["bedrock-converse",ki],["google-genai",Ri],["google-vertexai",Ni],["openai",wi]]);function Pa(e){return globalThis.lc_block_translators_registry.get(e)}var Ne=class extends pe{type="ai";tool_calls=[];invalid_tool_calls=[];usage_metadata;get lc_aliases(){return{...super.lc_aliases,tool_calls:"tool_calls",invalid_tool_calls:"invalid_tool_calls"}}constructor(e){let t;if(typeof e=="string"||Array.isArray(e))t={content:e,tool_calls:[],invalid_tool_calls:[],additional_kwargs:{}};else{t=e;const n=t.additional_kwargs?.tool_calls,a=t.tool_calls;n!=null&&n.length>0&&(a===void 0||a.length===0)&&console.warn(["New LangChain packages are available that more efficiently handle",`tool calling.
|
|
10
|
-
|
|
11
|
-
Please upgrade your packages to versions that set`,"message tool calls. e.g., `pnpm install @langchain/anthropic`,","pnpm install @langchain/openai`, etc."].join(" "));try{if(n!=null&&a===void 0){const[r,i]=dn(n);t.tool_calls=r??[],t.invalid_tool_calls=i??[]}else t.tool_calls=t.tool_calls??[],t.invalid_tool_calls=t.invalid_tool_calls??[]}catch{t.tool_calls=[],t.invalid_tool_calls=[]}if(t.response_metadata!==void 0&&"output_version"in t.response_metadata&&t.response_metadata.output_version==="v1"&&(t.contentBlocks=t.content,t.content=void 0),t.contentBlocks!==void 0){t.contentBlocks.push(...t.tool_calls.map(i=>({type:"tool_call",id:i.id,name:i.name,args:i.args})));const r=t.contentBlocks.filter(i=>i.type==="tool_call").filter(i=>!t.tool_calls?.some(s=>s.id===i.id&&s.name===i.name));r.length>0&&(t.tool_calls=r.map(i=>({type:"tool_call",id:i.id,name:i.name,args:i.args})))}}super(t),typeof t!="string"&&(this.tool_calls=t.tool_calls??this.tool_calls,this.invalid_tool_calls=t.invalid_tool_calls??this.invalid_tool_calls),this.usage_metadata=t.usage_metadata}static lc_name(){return"AIMessage"}get contentBlocks(){if(this.response_metadata&&"output_version"in this.response_metadata&&this.response_metadata.output_version==="v1")return this.content;if(this.response_metadata&&"model_provider"in this.response_metadata&&typeof this.response_metadata.model_provider=="string"){const t=Pa(this.response_metadata.model_provider);if(t)return t.translateContent(this)}const e=super.contentBlocks;if(this.tool_calls){const t=this.tool_calls.filter(n=>!e.some(a=>a.id===n.id&&a.name===n.name));e.push(...t.map(n=>({...n,type:"tool_call",id:n.id,name:n.name,args:n.args})))}return e}get _printableFields(){return{...super._printableFields,tool_calls:this.tool_calls,invalid_tool_calls:this.invalid_tool_calls,usage_metadata:this.usage_metadata}}static isInstance(e){return super.isInstance(e)&&e.type==="ai"}};function Pi(e){return e._getType()==="ai"}function $i(e){return e._getType()==="ai"}var Le=class extends Ie{type="ai";tool_calls=[];invalid_tool_calls=[];tool_call_chunks=[];usage_metadata;constructor(e){let t;if(typeof e=="string"||Array.isArray(e))t={content:e,tool_calls:[],invalid_tool_calls:[],tool_call_chunks:[]};else if(e.tool_call_chunks===void 0||e.tool_call_chunks.length===0)t={...e,tool_calls:e.tool_calls??[],invalid_tool_calls:[],tool_call_chunks:[],usage_metadata:e.usage_metadata!==void 0?e.usage_metadata:void 0};else{const a=(e.tool_call_chunks??[]).reduce((s,o)=>{const c=s.findIndex(([l])=>"id"in o&&o.id&&"index"in o&&o.index!==void 0?o.id===l.id&&o.index===l.index:"id"in o&&o.id?o.id===l.id:"index"in o&&o.index!==void 0?o.index===l.index:!1);return c!==-1?s[c].push(o):s.push([o]),s},[]),r=[],i=[];for(const s of a){let o=null;const c=s[0]?.name??"",l=s.map(d=>d.args||"").join(""),u=l.length?l:"{}",h=s[0]?.id;try{if(o=Na(u),!h||o===null||typeof o!="object"||Array.isArray(o))throw new Error("Malformed tool call chunk args.");r.push({name:c,args:o,id:h,type:"tool_call"})}catch{i.push({name:c,args:u,id:h,error:"Malformed args.",type:"invalid_tool_call"})}}t={...e,tool_calls:r,invalid_tool_calls:i,usage_metadata:e.usage_metadata!==void 0?e.usage_metadata:void 0}}super(t),this.tool_call_chunks=t.tool_call_chunks??this.tool_call_chunks,this.tool_calls=t.tool_calls??this.tool_calls,this.invalid_tool_calls=t.invalid_tool_calls??this.invalid_tool_calls,this.usage_metadata=t.usage_metadata}get lc_aliases(){return{...super.lc_aliases,tool_calls:"tool_calls",invalid_tool_calls:"invalid_tool_calls",tool_call_chunks:"tool_call_chunks"}}static lc_name(){return"AIMessageChunk"}get contentBlocks(){if(this.response_metadata&&"output_version"in this.response_metadata&&this.response_metadata.output_version==="v1")return this.content;if(this.response_metadata&&"model_provider"in this.response_metadata&&typeof this.response_metadata.model_provider=="string"){const t=Pa(this.response_metadata.model_provider);if(t)return t.translateContent(this)}const e=super.contentBlocks;if(this.tool_calls&&typeof this.content!="string"){const t=this.content.filter(n=>n.type==="tool_call").map(n=>n.id);for(const n of this.tool_calls)n.id&&!t.includes(n.id)&&e.push({...n,type:"tool_call",id:n.id,name:n.name,args:n.args})}return e}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(e){const t={content:Ae(this.content,e.content),additional_kwargs:B(this.additional_kwargs,e.additional_kwargs),response_metadata:Ia(this.response_metadata,e.response_metadata),tool_call_chunks:[],id:this.id??e.id};if(this.tool_call_chunks!==void 0||e.tool_call_chunks!==void 0){const a=Qe(this.tool_call_chunks,e.tool_call_chunks);a!==void 0&&a.length>0&&(t.tool_call_chunks=a)}(this.usage_metadata!==void 0||e.usage_metadata!==void 0)&&(t.usage_metadata=Ca(this.usage_metadata,e.usage_metadata));const n=this.constructor;return new n(t)}static isInstance(e){return super.isInstance(e)&&e.type==="ai"}},Ye=class $a extends pe{static lc_name(){return"ChatMessage"}type="generic";role;static _chatMessageClass(){return $a}constructor(t,n){(typeof t=="string"||Array.isArray(t))&&(t={content:t,role:n}),super(t),this.role=t.role}static isInstance(t){return super.isInstance(t)&&t.type==="generic"}get _printableFields(){return{...super._printableFields,role:this.role}}},bt=class extends Ie{static lc_name(){return"ChatMessageChunk"}type="generic";role;constructor(e,t){(typeof e=="string"||Array.isArray(e))&&(e={content:e,role:t}),super(e),this.role=e.role}concat(e){const t=this.constructor;return new t({content:Ae(this.content,e.content),additional_kwargs:B(this.additional_kwargs,e.additional_kwargs),response_metadata:B(this.response_metadata,e.response_metadata),role:this.role,id:this.id??e.id})}static isInstance(e){return super.isInstance(e)&&e.type==="generic"}get _printableFields(){return{...super._printableFields,role:this.role}}};function Mi(e){return e._getType()==="generic"}function Li(e){return e._getType()==="generic"}var St=class extends pe{static lc_name(){return"FunctionMessage"}type="function";name;constructor(e){super(e),this.name=e.name}},Et=class extends Ie{static lc_name(){return"FunctionMessageChunk"}type="function";concat(e){const t=this.constructor;return new t({content:Ae(this.content,e.content),additional_kwargs:B(this.additional_kwargs,e.additional_kwargs),response_metadata:B(this.response_metadata,e.response_metadata),name:this.name??"",id:this.id??e.id})}};function ji(e){return e._getType()==="function"}function Di(e){return e._getType()==="function"}var je=class extends pe{static lc_name(){return"HumanMessage"}type="human";constructor(e){super(e)}static isInstance(e){return super.isInstance(e)&&e.type==="human"}},Tt=class extends Ie{static lc_name(){return"HumanMessageChunk"}type="human";constructor(e){super(e)}concat(e){const t=this.constructor;return new t({content:Ae(this.content,e.content),additional_kwargs:B(this.additional_kwargs,e.additional_kwargs),response_metadata:B(this.response_metadata,e.response_metadata),id:this.id??e.id})}static isInstance(e){return super.isInstance(e)&&e.type==="human"}};function Ui(e){return e.getType()==="human"}function Fi(e){return e.getType()==="human"}var _e=class extends pe{static lc_name(){return"SystemMessage"}type="system";constructor(e){super(e)}static isInstance(e){return super.isInstance(e)&&e.type==="system"}},Pe=class extends Ie{static lc_name(){return"SystemMessageChunk"}type="system";constructor(e){super(e)}concat(e){const t=this.constructor;return new t({content:Ae(this.content,e.content),additional_kwargs:B(this.additional_kwargs,e.additional_kwargs),response_metadata:B(this.response_metadata,e.response_metadata),id:this.id??e.id})}static isInstance(e){return super.isInstance(e)&&e.type==="system"}};function Bi(e){return e._getType()==="system"}function zi(e){return e._getType()==="system"}var ut=class extends pe{type="remove";id;constructor(e){super({...e,content:[]}),this.id=e.id}get _printableFields(){return{...super._printableFields,id:this.id}}static isInstance(e){return super.isInstance(e)&&e.type==="remove"}};function Hi(e,t){return e.lc_error_code=t,e.message=`${e.message}
|
|
12
|
-
|
|
13
|
-
Troubleshooting URL: https://js.langchain.com/docs/troubleshooting/errors/${t}/
|
|
14
|
-
`,e}function Ma(e){return!!(e&&typeof e=="object"&&"type"in e&&e.type==="tool_call")}function $l(e){return!!(e&&typeof e=="object"&&"toolCall"in e&&e.toolCall!=null&&typeof e.toolCall=="object"&&"id"in e.toolCall&&typeof e.toolCall.id=="string")}var Gi=class extends Error{output;constructor(e,t){super(e),this.output=t}};const Zi=e=>e();function qi(e){return Ma(e)?e:typeof e.id=="string"&&e.type==="function"&&typeof e.function=="object"&&e.function!==null&&"arguments"in e.function&&typeof e.function.arguments=="string"&&"name"in e.function&&typeof e.function.name=="string"?{id:e.id,args:JSON.parse(e.function.arguments),name:e.function.name,type:"tool_call"}:e}function Ji(e){return typeof e=="object"&&e!=null&&e.lc===1&&Array.isArray(e.id)&&e.kwargs!=null&&typeof e.kwargs=="object"}function Ct(e){let t,n;if(Ji(e)){const a=e.id.at(-1);a==="HumanMessage"||a==="HumanMessageChunk"?t="user":a==="AIMessage"||a==="AIMessageChunk"?t="assistant":a==="SystemMessage"||a==="SystemMessageChunk"?t="system":a==="FunctionMessage"||a==="FunctionMessageChunk"?t="function":a==="ToolMessage"||a==="ToolMessageChunk"?t="tool":t="unknown",n=e.kwargs}else{const{type:a,...r}=e;t=a,n=r}if(t==="human"||t==="user")return new je(n);if(t==="ai"||t==="assistant"){const{tool_calls:a,...r}=n;if(!Array.isArray(a))return new Ne(n);const i=a.map(qi);return new Ne({...r,tool_calls:i})}else{if(t==="system")return new _e(n);if(t==="developer")return new _e({...n,additional_kwargs:{...n.additional_kwargs,__openai_role__:"developer"}});if(t==="tool"&&"tool_call_id"in n)return new Me({...n,content:n.content,tool_call_id:n.tool_call_id,name:n.name});if(t==="remove"&&"id"in n&&typeof n.id=="string")return new ut({...n,id:n.id});throw Hi(new Error(`Unable to coerce message from array: only human, AI, system, developer, or tool message coercion is currently supported.
|
|
15
|
-
|
|
16
|
-
Received: ${JSON.stringify(e,null,2)}`),"MESSAGE_COERCION_FAILURE")}}function Vi(e){if(typeof e=="string")return new je(e);if(un(e))return e;if(Array.isArray(e)){const[t,n]=e;return Ct({type:t,content:n})}else if(Ta(e)){const{role:t,...n}=e;return Ct({...n,type:t})}else return Ct(e)}function La(e,t="Human",n="AI"){const a=[];for(const r of e){let i;if(r._getType()==="human")i=t;else if(r._getType()==="ai")i=n;else if(r._getType()==="system")i="System";else if(r._getType()==="tool")i="Tool";else if(r._getType()==="generic")i=r.role;else throw new Error(`Got unsupported message type: ${r._getType()}`);const s=r.name?`${r.name}, `:"",o=typeof r.content=="string"?r.content:JSON.stringify(r.content,null,2);a.push(`${i}: ${s}${o}`)}return a.join(`
|
|
17
|
-
`)}function Wi(e){if(e.data!==void 0)return e;{const t=e;return{type:t.type,data:{content:t.text,role:t.role,name:void 0,tool_call_id:void 0}}}}function ja(e){const t=Wi(e);switch(t.type){case"human":return new je(t.data);case"ai":return new Ne(t.data);case"system":return new _e(t.data);case"function":if(t.data.name===void 0)throw new Error("Name must be defined for function messages");return new St(t.data);case"tool":if(t.data.tool_call_id===void 0)throw new Error("Tool call ID must be defined for tool messages");return new Me(t.data);case"generic":if(t.data.role===void 0)throw new Error("Role must be defined for chat messages");return new Ye(t.data);default:throw new Error(`Got unexpected type: ${t.type}`)}}function Ki(e){return e.map(ja)}function Qi(e){return e.map(t=>t.toDict())}function Gt(e){const t=e._getType();if(t==="human")return new Tt({...e});if(t==="ai"){let n={...e};return"tool_calls"in n&&(n={...n,tool_call_chunks:n.tool_calls?.map(a=>({...a,type:"tool_call_chunk",index:void 0,args:JSON.stringify(a.args)}))}),new Le({...n})}else{if(t==="system")return new Pe({...e});if(t==="function")return new Et({...e});if(Ye.isInstance(e))return new bt({...e});throw new Error("Unknown message type.")}}const Da=Symbol.for("ls:tracing_async_local_storage"),He=Symbol.for("lc:context_variables"),Yi=e=>{globalThis[Da]=e},qe=()=>globalThis[Da];var Xi={},es={};D(es,{getEnv:()=>Ha,getEnvironmentVariable:()=>ve,getRuntimeEnvironment:()=>Ga,isBrowser:()=>Ua,isDeno:()=>At,isJsDom:()=>Ba,isNode:()=>za,isWebWorker:()=>Fa});const Ua=()=>typeof window<"u"&&typeof window.document<"u",Fa=()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope",Ba=()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),At=()=>typeof Deno<"u",za=()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!At(),Ha=()=>{let e;return Ua()?e="browser":za()?e="node":Fa()?e="webworker":Ba()?e="jsdom":At()?e="deno":e="other",e};let xt;function Ga(){return xt===void 0&&(xt={library:"langchain-js",runtime:Ha()}),xt}function ve(e){try{return typeof process<"u"?Xi?.[e]:At()?Deno?.env.get(e):void 0}catch{return}}var ts={};D(ts,{BaseCallbackHandler:()=>Xe,callbackHandlerPrefersStreaming:()=>as,isBaseCallbackHandler:()=>Za});var ns=class{};function as(e){return"lc_prefer_streaming"in e&&e.lc_prefer_streaming}var Xe=class extends ns{lc_serializable=!1;get lc_namespace(){return["langchain_core","callbacks",this.name]}get lc_secrets(){}get lc_attributes(){}get lc_aliases(){}get lc_serializable_keys(){}static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,on(this.constructor)]}lc_kwargs;ignoreLLM=!1;ignoreChain=!1;ignoreAgent=!1;ignoreRetriever=!1;ignoreCustomEvent=!1;raiseError=!1;awaitHandlers=ve("LANGCHAIN_CALLBACKS_BACKGROUND")==="false";constructor(e){super(),this.lc_kwargs=e||{},e&&(this.ignoreLLM=e.ignoreLLM??this.ignoreLLM,this.ignoreChain=e.ignoreChain??this.ignoreChain,this.ignoreAgent=e.ignoreAgent??this.ignoreAgent,this.ignoreRetriever=e.ignoreRetriever??this.ignoreRetriever,this.ignoreCustomEvent=e.ignoreCustomEvent??this.ignoreCustomEvent,this.raiseError=e.raiseError??this.raiseError,this.awaitHandlers=this.raiseError||(e._awaitHandler??this.awaitHandlers))}copy(){return new this.constructor(this)}toJSON(){return Ge.prototype.toJSON.call(this)}toJSONNotImplemented(){return Ge.prototype.toJSONNotImplemented.call(this)}static fromMethods(e){class t extends Xe{name=G();constructor(){super(),Object.assign(this,e)}}return new t}};const Za=e=>{const t=e;return t!==void 0&&typeof t.copy=="function"&&typeof t.name=="string"&&typeof t.awaitHandlers=="boolean"},rs="gen_ai.operation.name",is="gen_ai.system",Rn="gen_ai.request.model",ss="gen_ai.response.model",Nn="gen_ai.usage.input_tokens",Pn="gen_ai.usage.output_tokens",$n="gen_ai.usage.total_tokens",os="gen_ai.request.max_tokens",cs="gen_ai.request.temperature",ls="gen_ai.request.top_p",us="gen_ai.request.frequency_penalty",ds="gen_ai.request.presence_penalty",hs="gen_ai.response.finish_reasons",ps="gen_ai.prompt",fs="gen_ai.completion",ms="gen_ai.request.extra_query",gs="gen_ai.request.extra_body",_s="gen_ai.serialized.name",ys="gen_ai.serialized.signature",ws="gen_ai.serialized.doc",vs="gen_ai.response.id",bs="gen_ai.response.service_tier",Ss="gen_ai.response.system_fingerprint",Es="gen_ai.usage.input_token_details",Ts="gen_ai.usage.output_token_details",As="langsmith.trace.session_id",Is="langsmith.trace.session_name",Os="langsmith.span.kind",Cs="langsmith.trace.name",xs="langsmith.metadata",Mn="langsmith.span.tags",ks="langsmith.request.streaming",Rs="langsmith.request.headers",Ns=(...e)=>fetch(...e),qa=Symbol.for("ls:fetch_implementation"),Ps=()=>{const e=globalThis[qa];return e?typeof e=="function"&&"Headers"in e&&"Request"in e&&"Response"in e:!1},$s=e=>async(...t)=>{if(e||J("DEBUG")==="true"){const[a,r]=t;console.log(`→ ${r?.method||"GET"} ${a}`)}const n=await(globalThis[qa]??Ns)(...t);return(e||J("DEBUG")==="true")&&console.log(`← ${n.status} ${n.statusText} ${n.url}`),n},Ja=()=>J("PROJECT")??oe("LANGCHAIN_SESSION")??"default",Va="0.3.75";var Zt={};let ie;const Ms=()=>typeof window<"u"&&typeof window.document<"u",Ls=()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope",js=()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),Wa=()=>typeof Deno<"u",Ds=()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!Wa(),Ka=()=>ie||(typeof Bun<"u"?ie="bun":Ms()?ie="browser":Ds()?ie="node":Ls()?ie="webworker":js()?ie="jsdom":Wa()?ie="deno":ie="other",ie);let kt;function Qa(){if(kt===void 0){const e=Ka(),t=Fs();kt={library:"langsmith",runtime:e,sdk:"langsmith-js",sdk_version:Va,...t}}return kt}function Ya(){const e=Us(),t={},n=["LANGCHAIN_API_KEY","LANGCHAIN_ENDPOINT","LANGCHAIN_TRACING_V2","LANGCHAIN_PROJECT","LANGCHAIN_SESSION","LANGSMITH_API_KEY","LANGSMITH_ENDPOINT","LANGSMITH_TRACING_V2","LANGSMITH_PROJECT","LANGSMITH_SESSION"];for(const[a,r]of Object.entries(e))typeof r=="string"&&!n.includes(a)&&!a.toLowerCase().includes("key")&&!a.toLowerCase().includes("secret")&&!a.toLowerCase().includes("token")&&(a==="LANGCHAIN_REVISION_ID"?t.revision_id=r:t[a]=r);return t}function Us(){const e={};try{if(typeof process<"u"&&Zt)for(const[t,n]of Object.entries(Zt))(t.startsWith("LANGCHAIN_")||t.startsWith("LANGSMITH_"))&&n!=null&&((t.toLowerCase().includes("key")||t.toLowerCase().includes("secret")||t.toLowerCase().includes("token"))&&typeof n=="string"?e[t]=n.slice(0,2)+"*".repeat(n.length-4)+n.slice(-2):e[t]=n)}catch{}return e}function oe(e){try{return typeof process<"u"?Zt?.[e]:void 0}catch{return}}function J(e){return oe(`LANGSMITH_${e}`)||oe(`LANGCHAIN_${e}`)}let Rt;function Fs(){if(Rt!==void 0)return Rt;const e=["VERCEL_GIT_COMMIT_SHA","NEXT_PUBLIC_VERCEL_GIT_COMMIT_SHA","COMMIT_REF","RENDER_GIT_COMMIT","CI_COMMIT_SHA","CIRCLE_SHA1","CF_PAGES_COMMIT_SHA","REACT_APP_GIT_SHA","SOURCE_VERSION","GITHUB_SHA","TRAVIS_COMMIT","GIT_COMMIT","BUILD_VCS_NUMBER","bamboo_planRepository_revision","Build.SourceVersion","BITBUCKET_COMMIT","DRONE_COMMIT_SHA","SEMAPHORE_GIT_SHA","BUILDKITE_COMMIT"],t={};for(const n of e){const a=oe(n);a!==void 0&&(t[n]=a)}return Rt=t,t}function Xa(){return oe("OTEL_ENABLED")==="true"||J("OTEL_ENABLED")==="true"}class Bs{constructor(){Object.defineProperty(this,"hasWarned",{enumerable:!0,configurable:!0,writable:!0,value:!1})}startActiveSpan(t,...n){!this.hasWarned&&Xa()&&(console.warn('You have enabled OTEL export via the `OTEL_ENABLED` or `LANGSMITH_OTEL_ENABLED` environment variable, but have not initialized the required OTEL instances. Please add:\n```\nimport { initializeOTEL } from "langsmith/experimental/otel/setup";\ninitializeOTEL();\n```\nat the beginning of your code.'),this.hasWarned=!0);let a;if(n.length===1&&typeof n[0]=="function"?a=n[0]:n.length===2&&typeof n[1]=="function"?a=n[1]:n.length===3&&typeof n[2]=="function"&&(a=n[2]),typeof a=="function")return a()}}class zs{constructor(){Object.defineProperty(this,"mockTracer",{enumerable:!0,configurable:!0,writable:!0,value:new Bs})}getTracer(t,n){return this.mockTracer}getActiveSpan(){}setSpan(t,n){return t}getSpan(t){}setSpanContext(t,n){return t}getTracerProvider(){}setGlobalTracerProvider(t){return!1}}class Hs{active(){return{}}with(t,n){return n()}}const Nt=Symbol.for("ls:otel_trace"),Pt=Symbol.for("ls:otel_context"),Ln=Symbol.for("ls:otel_get_default_otlp_tracer_provider"),Gs=new zs,Zs=new Hs;class qs{getTraceInstance(){return globalThis[Nt]??Gs}getContextInstance(){return globalThis[Pt]??Zs}initializeGlobalInstances(t){globalThis[Nt]===void 0&&(globalThis[Nt]=t.trace),globalThis[Pt]===void 0&&(globalThis[Pt]=t.context)}setDefaultOTLPTracerComponents(t){globalThis[Ln]=t}getDefaultOTLPTracerComponents(){return globalThis[Ln]??void 0}}const pn=new qs;function er(){return pn.getTraceInstance()}function Js(){return pn.getContextInstance()}function Vs(){return pn.getDefaultOTLPTracerComponents()}const Ws={llm:"chat",tool:"execute_tool",retriever:"embeddings",embedding:"embeddings",prompt:"chat"};function Ks(e){return Ws[e]||e}class Qs{constructor(){Object.defineProperty(this,"spans",{enumerable:!0,configurable:!0,writable:!0,value:new Map})}exportBatch(t,n){for(const a of t)try{if(!a.run)continue;if(a.operation==="post"){const r=this.createSpanForRun(a,a.run,n.get(a.id));r&&!a.run.end_time&&this.spans.set(a.id,r)}else this.updateSpanForRun(a,a.run)}catch(r){console.error(`Error processing operation ${a.id}:`,r)}}createSpanForRun(t,n,a){const r=a&&er().getSpan(a);if(r)try{return this.finishSpanSetup(r,n,t)}catch(i){console.error(`Failed to create span for run ${t.id}:`,i);return}}finishSpanSetup(t,n,a){return this.setSpanAttributes(t,n,a),n.error?(t.setStatus({code:2}),t.recordException(new Error(n.error))):t.setStatus({code:1}),n.end_time&&t.end(new Date(n.end_time)),t}updateSpanForRun(t,n){try{const a=this.spans.get(t.id);if(!a){console.debug(`No span found for run ${t.id} during update`);return}this.setSpanAttributes(a,n,t),n.error?(a.setStatus({code:2}),a.recordException(new Error(n.error))):a.setStatus({code:1});const r=n.end_time;r&&(a.end(new Date(r)),this.spans.delete(t.id))}catch(a){console.error(`Failed to update span for run ${t.id}:`,a)}}extractModelName(t){if(t.extra?.metadata){const n=t.extra.metadata;if(n.ls_model_name)return n.ls_model_name;if(n.invocation_params){const a=n.invocation_params;if(a.model)return a.model;if(a.model_name)return a.model_name}}}setSpanAttributes(t,n,a){if("run_type"in n&&n.run_type){t.setAttribute(Os,n.run_type);const o=Ks(n.run_type||"chain");t.setAttribute(rs,o)}"name"in n&&n.name&&t.setAttribute(Cs,n.name),"session_id"in n&&n.session_id&&t.setAttribute(As,n.session_id),"session_name"in n&&n.session_name&&t.setAttribute(Is,n.session_name),this.setGenAiSystem(t,n);const r=this.extractModelName(n);r&&t.setAttribute(Rn,r),"prompt_tokens"in n&&typeof n.prompt_tokens=="number"&&t.setAttribute(Nn,n.prompt_tokens),"completion_tokens"in n&&typeof n.completion_tokens=="number"&&t.setAttribute(Pn,n.completion_tokens),"total_tokens"in n&&typeof n.total_tokens=="number"&&t.setAttribute($n,n.total_tokens),this.setInvocationParameters(t,n);const i=n.extra?.metadata||{};for(const[o,c]of Object.entries(i))c!=null&&t.setAttribute(`${xs}.${o}`,String(c));const s=n.tags;if(s&&Array.isArray(s)?t.setAttribute(Mn,s.join(", ")):s&&t.setAttribute(Mn,String(s)),"serialized"in n&&typeof n.serialized=="object"){const o=n.serialized;o.name&&t.setAttribute(_s,String(o.name)),o.signature&&t.setAttribute(ys,String(o.signature)),o.doc&&t.setAttribute(ws,String(o.doc))}this.setIOAttributes(t,a)}setGenAiSystem(t,n){let a="langchain";const r=this.extractModelName(n);if(r){const i=r.toLowerCase();i.includes("anthropic")||i.startsWith("claude")?a="anthropic":i.includes("bedrock")?a="aws.bedrock":i.includes("azure")&&i.includes("openai")?a="az.ai.openai":i.includes("azure")&&i.includes("inference")?a="az.ai.inference":i.includes("cohere")?a="cohere":i.includes("deepseek")?a="deepseek":i.includes("gemini")?a="gemini":i.includes("groq")?a="groq":i.includes("watson")||i.includes("ibm")?a="ibm.watsonx.ai":i.includes("mistral")?a="mistral_ai":i.includes("gpt")||i.includes("openai")?a="openai":i.includes("perplexity")||i.includes("sonar")?a="perplexity":i.includes("vertex")?a="vertex_ai":(i.includes("xai")||i.includes("grok"))&&(a="xai")}t.setAttribute(is,a)}setInvocationParameters(t,n){if(!n.extra?.metadata?.invocation_params)return;const a=n.extra.metadata.invocation_params;a.max_tokens!==void 0&&t.setAttribute(os,a.max_tokens),a.temperature!==void 0&&t.setAttribute(cs,a.temperature),a.top_p!==void 0&&t.setAttribute(ls,a.top_p),a.frequency_penalty!==void 0&&t.setAttribute(us,a.frequency_penalty),a.presence_penalty!==void 0&&t.setAttribute(ds,a.presence_penalty)}setIOAttributes(t,n){if(n.run.inputs)try{const a=n.run.inputs;typeof a=="object"&&a!==null&&(a.model&&Array.isArray(a.messages)&&t.setAttribute(Rn,a.model),a.stream!==void 0&&t.setAttribute(ks,a.stream),a.extra_headers&&t.setAttribute(Rs,JSON.stringify(a.extra_headers)),a.extra_query&&t.setAttribute(ms,JSON.stringify(a.extra_query)),a.extra_body&&t.setAttribute(gs,JSON.stringify(a.extra_body))),t.setAttribute(ps,JSON.stringify(a))}catch(a){console.debug(`Failed to process inputs for run ${n.id}`,a)}if(n.run.outputs)try{const a=n.run.outputs,r=this.getUnifiedRunTokens(a);if(r&&(t.setAttribute(Nn,r[0]),t.setAttribute(Pn,r[1]),t.setAttribute($n,r[0]+r[1])),a&&typeof a=="object"){if(a.model&&t.setAttribute(ss,String(a.model)),a.id&&t.setAttribute(vs,a.id),a.choices&&Array.isArray(a.choices)){const i=a.choices.map(s=>s.finish_reason).filter(s=>s).map(String);i.length>0&&t.setAttribute(hs,i.join(", "))}if(a.service_tier&&t.setAttribute(bs,a.service_tier),a.system_fingerprint&&t.setAttribute(Ss,a.system_fingerprint),a.usage_metadata&&typeof a.usage_metadata=="object"){const i=a.usage_metadata;i.input_token_details&&t.setAttribute(Es,JSON.stringify(i.input_token_details)),i.output_token_details&&t.setAttribute(Ts,JSON.stringify(i.output_token_details))}}t.setAttribute(fs,JSON.stringify(a))}catch(a){console.debug(`Failed to process outputs for run ${n.id}`,a)}}getUnifiedRunTokens(t){if(!t)return null;let n=this.extractUnifiedRunTokens(t.usage_metadata);if(n)return n;const a=Object.keys(t);for(const s of a){const o=t[s];if(!(!o||typeof o!="object")&&(n=this.extractUnifiedRunTokens(o.usage_metadata),n||o.lc===1&&o.kwargs&&typeof o.kwargs=="object"&&(n=this.extractUnifiedRunTokens(o.kwargs.usage_metadata),n)))return n}const r=t.generations||[];if(!Array.isArray(r))return null;const i=Array.isArray(r[0])?r.flat():r;for(const s of i)if(typeof s=="object"&&s.message&&typeof s.message=="object"&&s.message.kwargs&&typeof s.message.kwargs=="object"&&(n=this.extractUnifiedRunTokens(s.message.kwargs.usage_metadata),n))return n;return null}extractUnifiedRunTokens(t){return!t||typeof t!="object"||typeof t.input_tokens!="number"||typeof t.output_tokens!="number"?null:[t.input_tokens,t.output_tokens]}}const Ys=[429,500,502,503,504];let jn=class{constructor(t){Object.defineProperty(this,"maxConcurrency",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"maxRetries",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"queue",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onFailedResponseHook",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxConcurrency=t.maxConcurrency??1/0,this.maxRetries=t.maxRetries??6,"default"in ue?this.queue=new ue.default({concurrency:this.maxConcurrency}):this.queue=new ue({concurrency:this.maxConcurrency}),this.onFailedResponseHook=t?.onFailedResponseHook}call(t,...n){const a=this.onFailedResponseHook;return this.queue.add(()=>lt(()=>t(...n).catch(r=>{throw r instanceof Error?r:new Error(r)}),{async onFailedAttempt(r){if(r.message.startsWith("Cancel")||r.message.startsWith("TimeoutError")||r.name==="TimeoutError"||r.message.startsWith("AbortError")||r?.code==="ECONNABORTED")throw r;const i=r?.response;if(a&&await a(i))return;const s=i?.status??r?.status;if(s&&!Ys.includes(+s))throw r},retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0})}callWithOptions(t,n,...a){return t.signal?Promise.race([this.call(n,...a),new Promise((r,i)=>{t.signal?.addEventListener("abort",()=>{i(new Error("AbortError"))})})]):this.call(n,...a)}};function Dn(e){return typeof e?._getType=="function"}function Un(e){const t={type:e._getType(),data:{content:e.content}};return e?.additional_kwargs&&Object.keys(e.additional_kwargs).length>0&&(t.data.additional_kwargs={...e.additional_kwargs}),t}const Xs=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function S(e,t){if(!Xs.test(e)){const n=t!==void 0?`Invalid UUID for ${t}: ${e}`:`Invalid UUID: ${e}`;throw new Error(n)}return e}const Fn={};function qt(e){Fn[e]||(console.warn(e),Fn[e]=!0)}function fe(e){if(!e||e.split("/").length>2||e.startsWith("/")||e.endsWith("/")||e.split(":").length>2)throw new Error(`Invalid identifier format: ${e}`);const[t,n]=e.split(":"),a=n||"latest";if(t.includes("/")){const[r,i]=t.split("/",2);if(!r||!i)throw new Error(`Invalid identifier format: ${e}`);return[r,i,a]}else{if(!t)throw new Error(`Invalid identifier format: ${e}`);return["-",t,a]}}class eo extends Error{constructor(t){super(t),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="LangSmithConflictError",this.status=409}}async function _(e,t,n){let a;if(e.ok){n&&(a=await e.text());return}if(e.status===403)try{(await e.json())?.error==="org_scoped_key_requires_workspace"&&(a="This API key is org-scoped and requires workspace specification. Please provide 'workspaceId' parameter, or set LANGSMITH_WORKSPACE_ID environment variable.")}catch{const o=new Error(`${e.status} ${e.statusText}`);throw o.status=e?.status,o}if(a===void 0)try{a=await e.text()}catch{a=""}const r=`Failed to ${t}. Received status [${e.status}]: ${e.statusText}. Message: ${a}`;if(e.status===409)throw new eo(r);const i=new Error(r);throw i.status=e.status,i}const tr="ERR_CONFLICTING_ENDPOINTS";class to extends Error{constructor(){super("You cannot provide both LANGSMITH_ENDPOINT / LANGCHAIN_ENDPOINT and LANGSMITH_RUNS_ENDPOINTS."),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:tr}),this.name="ConflictingEndpointsError"}}function no(e){return typeof e=="object"&&e!==null&&e.code===tr}var Bn="[...]",ao={result:"[Circular]"},dt=[],ke=[];const ro=new TextEncoder;function io(){return{depthLimit:Number.MAX_SAFE_INTEGER,edgesLimit:Number.MAX_SAFE_INTEGER}}function at(e){return ro.encode(e)}function nr(e){if(e&&typeof e=="object"&&e!==null){if(e instanceof Map)return Object.fromEntries(e);if(e instanceof Set)return Array.from(e);if(e instanceof Date)return e.toISOString();if(e instanceof RegExp)return e.toString();if(e instanceof Error)return{name:e.name,message:e.message}}else if(typeof e=="bigint")return e.toString();return e}function so(e){return function(t,n){return nr(n)}}function K(e,t,n,a,r){try{const i=JSON.stringify(e,so(n),a);return at(i)}catch(i){if(!i.message?.includes("Converting circular structure to JSON"))return console.warn(`[WARNING]: LangSmith received unserializable value.${t?`
|
|
18
|
-
Context: ${t}`:""}`),at("[Unserializable]");J("SUPPRESS_CIRCULAR_JSON_WARNINGS")!=="true"&&console.warn(`[WARNING]: LangSmith received circular JSON. This will decrease tracer performance. ${t?`
|
|
19
|
-
Context: ${t}`:""}`),typeof r>"u"&&(r=io()),Jt(e,"",0,[],void 0,0,r);let s;try{ke.length===0?s=JSON.stringify(e,n,a):s=JSON.stringify(e,oo(n),a)}catch{return at("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;dt.length!==0;){const o=dt.pop();o.length===4?Object.defineProperty(o[0],o[1],o[3]):o[0][o[1]]=o[2]}}return at(s)}}function $t(e,t,n,a){var r=Object.getOwnPropertyDescriptor(a,n);r.get!==void 0?r.configurable?(Object.defineProperty(a,n,{value:e}),dt.push([a,n,t,r])):ke.push([t,n,e]):(a[n]=e,dt.push([a,n,t]))}function Jt(e,t,n,a,r,i,s){i+=1;var o;if(typeof e=="object"&&e!==null){for(o=0;o<a.length;o++)if(a[o]===e){$t(ao,e,t,r);return}if(typeof s.depthLimit<"u"&&i>s.depthLimit){$t(Bn,e,t,r);return}if(typeof s.edgesLimit<"u"&&n+1>s.edgesLimit){$t(Bn,e,t,r);return}if(a.push(e),Array.isArray(e))for(o=0;o<e.length;o++)Jt(e[o],o,o,a,e,i,s);else{e=nr(e);var c=Object.keys(e);for(o=0;o<c.length;o++){var l=c[o];Jt(e[l],l,o,a,e,i,s)}}a.pop()}}function oo(e){return e=typeof e<"u"?e:function(t,n){return n},function(t,n){if(ke.length>0)for(var a=0;a<ke.length;a++){var r=ke[a];if(r[1]===t&&r[0]===n){n=r[2],ke.splice(a,1);break}}return e.call(this,t,n)}}function zn(e,t){const n=Qa(),a=t??Ya(),r=e.extra??{},i=r.metadata;return e.extra={...r,runtime:{...n,...r?.runtime},metadata:{...a,...a.revision_id||"revision_id"in e&&e.revision_id?{revision_id:("revision_id"in e?e.revision_id:void 0)??a.revision_id}:{},...i}},e}const co=e=>{const t=e?.toString()??J("TRACING_SAMPLING_RATE");if(t===void 0)return;const n=parseFloat(t);if(n<0||n>1)throw new Error(`LANGSMITH_TRACING_SAMPLING_RATE must be between 0 and 1 if set. Got: ${n}`);return n},lo=e=>{const n=e.replace("http://","").replace("https://","").split("/")[0].split(":")[0];return n==="localhost"||n==="127.0.0.1"||n==="::1"};async function uo(e){const t=[];for await(const n of e)t.push(n);return t}function rt(e){if(e!==void 0)return e.trim().replace(/^"(.*)"$/,"$1").replace(/^'(.*)'$/,"$1")}const ho=async e=>{if(e?.status===429){const t=parseInt(e.headers.get("retry-after")??"10",10)*1e3;if(t>0)return await new Promise(n=>setTimeout(n,t)),!0}return!1};function Hn(e){return typeof e=="number"?Number(e.toFixed(4)):e}class po{constructor(){Object.defineProperty(this,"items",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"sizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:0})}peek(){return this.items[0]}push(t){let n;const a=new Promise(i=>{n=i}),r=K(t.item,`Serializing run with id: ${t.item.id}`).length;return this.items.push({action:t.action,payload:t.item,otelContext:t.otelContext,apiKey:t.apiKey,apiUrl:t.apiUrl,itemPromiseResolve:n,itemPromise:a,size:r}),this.sizeBytes+=r,a}pop({upToSizeBytes:t,upToSize:n}){if(t<1)throw new Error("Number of bytes to pop off may not be less than 1.");const a=[];let r=0;for(;r+(this.peek()?.size??0)<t&&this.items.length>0&&a.length<n;){const i=this.items.shift();i&&(a.push(i),r+=i.size,this.sizeBytes-=i.size)}if(a.length===0&&this.items.length>0){const i=this.items.shift();a.push(i),r+=i.size,this.sizeBytes-=i.size}return[a.map(i=>({action:i.action,item:i.payload,otelContext:i.otelContext,apiKey:i.apiKey,apiUrl:i.apiUrl})),()=>a.forEach(i=>i.itemPromiseResolve())]}}const fo=24*1024*1024,mo=1e4,go=100,Gn="https://api.smith.langchain.com";class Je{get _fetch(){return this.fetchImplementation||$s(this.debug)}constructor(t={}){Object.defineProperty(this,"apiKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"apiUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"webUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"workspaceId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"caller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"batchIngestCaller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"timeout_ms",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_tenantId",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"hideInputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"hideOutputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tracingSampleRate",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"filteredPostUuids",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"autoBatchTracing",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"autoBatchQueue",{enumerable:!0,configurable:!0,writable:!0,value:new po}),Object.defineProperty(this,"autoBatchTimeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"autoBatchAggregationDelayMs",{enumerable:!0,configurable:!0,writable:!0,value:250}),Object.defineProperty(this,"batchSizeBytesLimit",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"batchSizeLimit",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"fetchOptions",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"settings",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"blockOnRootRunFinalization",{enumerable:!0,configurable:!0,writable:!0,value:oe("LANGSMITH_TRACING_BACKGROUND")==="false"}),Object.defineProperty(this,"traceBatchConcurrency",{enumerable:!0,configurable:!0,writable:!0,value:5}),Object.defineProperty(this,"_serverInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_getServerInfoPromise",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"manualFlushMode",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"langSmithToOTELTranslator",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"fetchImplementation",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cachedLSEnvVarsForMetadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"multipartStreamingDisabled",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"debug",{enumerable:!0,configurable:!0,writable:!0,value:oe("LANGSMITH_DEBUG")==="true"});const n=Je.getDefaultClientConfig();if(this.tracingSampleRate=co(t.tracingSamplingRate),this.apiUrl=rt(t.apiUrl??n.apiUrl)??"",this.apiUrl.endsWith("/")&&(this.apiUrl=this.apiUrl.slice(0,-1)),this.apiKey=rt(t.apiKey??n.apiKey),this.webUrl=rt(t.webUrl??n.webUrl),this.webUrl?.endsWith("/")&&(this.webUrl=this.webUrl.slice(0,-1)),this.workspaceId=rt(t.workspaceId??J("WORKSPACE_ID")),this.timeout_ms=t.timeout_ms??9e4,this.caller=new jn({...t.callerOptions??{},maxRetries:4,debug:t.debug??this.debug}),this.traceBatchConcurrency=t.traceBatchConcurrency??this.traceBatchConcurrency,this.traceBatchConcurrency<1)throw new Error("Trace batch concurrency must be positive.");this.debug=t.debug??this.debug,this.fetchImplementation=t.fetchImplementation,this.batchIngestCaller=new jn({maxRetries:2,maxConcurrency:this.traceBatchConcurrency,...t.callerOptions??{},onFailedResponseHook:ho,debug:t.debug??this.debug}),this.hideInputs=t.hideInputs??t.anonymizer??n.hideInputs,this.hideOutputs=t.hideOutputs??t.anonymizer??n.hideOutputs,this.autoBatchTracing=t.autoBatchTracing??this.autoBatchTracing,this.blockOnRootRunFinalization=t.blockOnRootRunFinalization??this.blockOnRootRunFinalization,this.batchSizeBytesLimit=t.batchSizeBytesLimit,this.batchSizeLimit=t.batchSizeLimit,this.fetchOptions=t.fetchOptions||{},this.manualFlushMode=t.manualFlushMode??this.manualFlushMode,Xa()&&(this.langSmithToOTELTranslator=new Qs),this.cachedLSEnvVarsForMetadata=Ya()}static getDefaultClientConfig(){const t=J("API_KEY"),n=J("ENDPOINT")??Gn,a=J("HIDE_INPUTS")==="true",r=J("HIDE_OUTPUTS")==="true";return{apiUrl:n,apiKey:t,webUrl:void 0,hideInputs:a,hideOutputs:r}}getHostUrl(){return this.webUrl?this.webUrl:lo(this.apiUrl)?(this.webUrl="http://localhost:3000",this.webUrl):this.apiUrl.endsWith("/api/v1")?(this.webUrl=this.apiUrl.replace("/api/v1",""),this.webUrl):this.apiUrl.includes("/api")&&!this.apiUrl.split(".",1)[0].endsWith("api")?(this.webUrl=this.apiUrl.replace("/api",""),this.webUrl):this.apiUrl.split(".",1)[0].includes("dev")?(this.webUrl="https://dev.smith.langchain.com",this.webUrl):this.apiUrl.split(".",1)[0].includes("eu")?(this.webUrl="https://eu.smith.langchain.com",this.webUrl):this.apiUrl.split(".",1)[0].includes("beta")?(this.webUrl="https://beta.smith.langchain.com",this.webUrl):(this.webUrl="https://smith.langchain.com",this.webUrl)}get headers(){const t={"User-Agent":`langsmith-js/${Va}`};return this.apiKey&&(t["x-api-key"]=`${this.apiKey}`),this.workspaceId&&(t["x-tenant-id"]=this.workspaceId),t}_getPlatformEndpointPath(t){return this.apiUrl.slice(-3)!=="/v1"&&this.apiUrl.slice(-4)!=="/v1/"?`/v1/platform/${t}`:`/platform/${t}`}async processInputs(t){return this.hideInputs===!1?t:this.hideInputs===!0?{}:typeof this.hideInputs=="function"?this.hideInputs(t):t}async processOutputs(t){return this.hideOutputs===!1?t:this.hideOutputs===!0?{}:typeof this.hideOutputs=="function"?this.hideOutputs(t):t}async prepareRunCreateOrUpdateInputs(t){const n={...t};return n.inputs!==void 0&&(n.inputs=await this.processInputs(n.inputs)),n.outputs!==void 0&&(n.outputs=await this.processOutputs(n.outputs)),n}async _getResponse(t,n){const a=n?.toString()??"",r=`${this.apiUrl}${t}?${a}`;return await this.caller.call(async()=>{const s=await this._fetch(r,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await _(s,`fetch ${t}`),s})}async _get(t,n){return(await this._getResponse(t,n)).json()}async*_getPaginated(t,n=new URLSearchParams,a){let r=Number(n.get("offset"))||0;const i=Number(n.get("limit"))||100;for(;;){n.set("offset",String(r)),n.set("limit",String(i));const s=`${this.apiUrl}${t}?${n}`,o=await this.caller.call(async()=>{const l=await this._fetch(s,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await _(l,`fetch ${t}`),l}),c=a?a(await o.json()):await o.json();if(c.length===0||(yield c,c.length<i))break;r+=c.length}}async*_getCursorPaginatedList(t,n=null,a="POST",r="runs"){const i=n?{...n}:{};for(;;){const s=JSON.stringify(i),c=await(await this.caller.call(async()=>{const u=await this._fetch(`${this.apiUrl}${t}`,{method:a,headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await _(u,`fetch ${t}`),u})).json();if(!c||!c[r])break;yield c[r];const l=c.cursors;if(!l||!l.next)break;i.cursor=l.next}}_shouldSample(){return this.tracingSampleRate===void 0?!0:Math.random()<this.tracingSampleRate}_filterForSampling(t,n=!1){if(this.tracingSampleRate===void 0)return t;if(n){const a=[];for(const r of t)this.filteredPostUuids.has(r.trace_id)?r.id===r.trace_id&&this.filteredPostUuids.delete(r.trace_id):a.push(r);return a}else{const a=[];for(const r of t){const i=r.trace_id??r.id;this.filteredPostUuids.has(i)||(r.id===i?this._shouldSample()?a.push(r):this.filteredPostUuids.add(i):a.push(r))}return a}}async _getBatchSizeLimitBytes(){const t=await this._ensureServerInfo();return this.batchSizeBytesLimit??t.batch_ingest_config?.size_limit_bytes??fo}async _getBatchSizeLimit(){const t=await this._ensureServerInfo();return this.batchSizeLimit??t.batch_ingest_config?.size_limit??go}async _getDatasetExamplesMultiPartSupport(){return(await this._ensureServerInfo()).instance_flags?.dataset_examples_multipart_enabled??!1}drainAutoBatchQueue({batchSizeLimitBytes:t,batchSizeLimit:n}){const a=[];for(;this.autoBatchQueue.items.length>0;){const[r,i]=this.autoBatchQueue.pop({upToSizeBytes:t,upToSize:n});if(!r.length){i();break}const s=r.reduce((l,u)=>{const h=u.apiUrl??this.apiUrl,d=u.apiKey??this.apiKey,f=u.apiKey===this.apiKey&&u.apiUrl===this.apiUrl?"default":`${h}|${d}`;return l[f]||(l[f]=[]),l[f].push(u),l},{}),o=[];for(const[l,u]of Object.entries(s)){const h=this._processBatch(u,{apiUrl:l==="default"?void 0:l.split("|")[0],apiKey:l==="default"?void 0:l.split("|")[1]});o.push(h)}const c=Promise.all(o).finally(i);a.push(c)}return Promise.all(a)}async _processBatch(t,n){if(t.length)try{if(this.langSmithToOTELTranslator!==void 0)this._sendBatchToOTELTranslator(t);else{const a={runCreates:t.filter(i=>i.action==="create").map(i=>i.item),runUpdates:t.filter(i=>i.action==="update").map(i=>i.item)},r=await this._ensureServerInfo();if(r?.batch_ingest_config?.use_multipart_endpoint){const i=r?.instance_flags?.gzip_body_enabled;await this.multipartIngestRuns(a,{...n,useGzip:i})}else await this.batchIngestRuns(a,n)}}catch(a){console.error("Error exporting batch:",a)}}_sendBatchToOTELTranslator(t){if(this.langSmithToOTELTranslator!==void 0){const n=new Map,a=[];for(const r of t)r.item.id&&r.otelContext&&(n.set(r.item.id,r.otelContext),r.action==="create"?a.push({operation:"post",id:r.item.id,trace_id:r.item.trace_id??r.item.id,run:r.item}):a.push({operation:"patch",id:r.item.id,trace_id:r.item.trace_id??r.item.id,run:r.item}));this.langSmithToOTELTranslator.exportBatch(a,n)}}async processRunOperation(t){clearTimeout(this.autoBatchTimeout),this.autoBatchTimeout=void 0,t.item=zn(t.item,this.cachedLSEnvVarsForMetadata);const n=this.autoBatchQueue.push(t);if(this.manualFlushMode)return n;const a=await this._getBatchSizeLimitBytes(),r=await this._getBatchSizeLimit();return(this.autoBatchQueue.sizeBytes>a||this.autoBatchQueue.items.length>r)&&this.drainAutoBatchQueue({batchSizeLimitBytes:a,batchSizeLimit:r}),this.autoBatchQueue.items.length>0&&(this.autoBatchTimeout=setTimeout(()=>{this.autoBatchTimeout=void 0,this.drainAutoBatchQueue({batchSizeLimitBytes:a,batchSizeLimit:r})},this.autoBatchAggregationDelayMs)),n}async _getServerInfo(){const n=await(await this.caller.call(async()=>{const a=await this._fetch(`${this.apiUrl}/info`,{method:"GET",headers:{Accept:"application/json"},signal:AbortSignal.timeout(mo),...this.fetchOptions});return await _(a,"get server info"),a})).json();return this.debug&&console.log(`
|
|
20
|
-
=== LangSmith Server Configuration ===
|
|
21
|
-
`+JSON.stringify(n,null,2)+`
|
|
22
|
-
`),n}async _ensureServerInfo(){return this._getServerInfoPromise===void 0&&(this._getServerInfoPromise=(async()=>{if(this._serverInfo===void 0)try{this._serverInfo=await this._getServerInfo()}catch(t){console.warn(`[LANGSMITH]: Failed to fetch info on supported operations. Falling back to batch operations and default limits. Info: ${t.status??"Unspecified status code"} ${t.message}`)}return this._serverInfo??{}})()),this._getServerInfoPromise.then(t=>(this._serverInfo===void 0&&(this._getServerInfoPromise=void 0),t))}async _getSettings(){return this.settings||(this.settings=this._get("/settings")),await this.settings}async flush(){const t=await this._getBatchSizeLimitBytes(),n=await this._getBatchSizeLimit();await this.drainAutoBatchQueue({batchSizeLimitBytes:t,batchSizeLimit:n})}_cloneCurrentOTELContext(){const t=er(),n=Js();if(this.langSmithToOTELTranslator!==void 0){const a=t.getActiveSpan();if(a)return t.setSpan(n.active(),a)}}async createRun(t,n){if(!this._filterForSampling([t]).length)return;const a={...this.headers,"Content-Type":"application/json"},r=t.project_name;delete t.project_name;const i=await this.prepareRunCreateOrUpdateInputs({session_name:r,...t,start_time:t.start_time??Date.now()});if(this.autoBatchTracing&&i.trace_id!==void 0&&i.dotted_order!==void 0){const c=this._cloneCurrentOTELContext();this.processRunOperation({action:"create",item:i,otelContext:c,apiKey:n?.apiKey,apiUrl:n?.apiUrl}).catch(console.error);return}const s=zn(i,this.cachedLSEnvVarsForMetadata);n?.apiKey!==void 0&&(a["x-api-key"]=n.apiKey),n?.workspaceId!==void 0&&(a["x-tenant-id"]=n.workspaceId);const o=K(s,`Creating run with id: ${s.id}`);await this.caller.call(async()=>{const c=await this._fetch(`${n?.apiUrl??this.apiUrl}/runs`,{method:"POST",headers:a,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await _(c,"create run",!0),c})}async batchIngestRuns({runCreates:t,runUpdates:n},a){if(t===void 0&&n===void 0)return;let r=await Promise.all(t?.map(c=>this.prepareRunCreateOrUpdateInputs(c))??[]),i=await Promise.all(n?.map(c=>this.prepareRunCreateOrUpdateInputs(c))??[]);if(r.length>0&&i.length>0){const c=r.reduce((u,h)=>(h.id&&(u[h.id]=h),u),{}),l=[];for(const u of i)u.id!==void 0&&c[u.id]?c[u.id]={...c[u.id],...u}:l.push(u);r=Object.values(c),i=l}const s={post:r,patch:i};if(!s.post.length&&!s.patch.length)return;const o={post:[],patch:[]};for(const c of["post","patch"]){const l=c,u=s[l].reverse();let h=u.pop();for(;h!==void 0;)o[l].push(h),h=u.pop()}if(o.post.length>0||o.patch.length>0){const c=o.post.map(l=>l.id).concat(o.patch.map(l=>l.id)).join(",");await this._postBatchIngestRuns(K(o,`Ingesting runs with ids: ${c}`),a)}}async _postBatchIngestRuns(t,n){const a={...this.headers,"Content-Type":"application/json",Accept:"application/json"};n?.apiKey!==void 0&&(a["x-api-key"]=n.apiKey),await this.batchIngestCaller.call(async()=>{const r=await this._fetch(`${n?.apiUrl??this.apiUrl}/runs/batch`,{method:"POST",headers:a,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:t});return await _(r,"batch create run",!0),r})}async multipartIngestRuns({runCreates:t,runUpdates:n},a){if(t===void 0&&n===void 0)return;const r={};let i=[];for(const h of t??[]){const d=await this.prepareRunCreateOrUpdateInputs(h);d.id!==void 0&&d.attachments!==void 0&&(r[d.id]=d.attachments),delete d.attachments,i.push(d)}let s=[];for(const h of n??[])s.push(await this.prepareRunCreateOrUpdateInputs(h));if(i.find(h=>h.trace_id===void 0||h.dotted_order===void 0)!==void 0)throw new Error('Multipart ingest requires "trace_id" and "dotted_order" to be set when creating a run');if(s.find(h=>h.trace_id===void 0||h.dotted_order===void 0)!==void 0)throw new Error('Multipart ingest requires "trace_id" and "dotted_order" to be set when updating a run');if(i.length>0&&s.length>0){const h=i.reduce((p,f)=>(f.id&&(p[f.id]=f),p),{}),d=[];for(const p of s)p.id!==void 0&&h[p.id]?h[p.id]={...h[p.id],...p}:d.push(p);i=Object.values(h),s=d}if(i.length===0&&s.length===0)return;const l=[],u=[];for(const[h,d]of[["post",i],["patch",s]])for(const p of d){const{inputs:f,outputs:A,events:y,extra:g,error:v,serialized:E,attachments:I,...O}=p,N={inputs:f,outputs:A,events:y,extra:g,error:v,serialized:E},R=K(O,`Serializing for multipart ingestion of run with id: ${O.id}`);u.push({name:`${h}.${O.id}`,payload:new Blob([R],{type:`application/json; length=${R.length}`})});for(const[$,Y]of Object.entries(N)){if(Y===void 0)continue;const ce=K(Y,`Serializing ${$} for multipart ingestion of run with id: ${O.id}`);u.push({name:`${h}.${O.id}.${$}`,payload:new Blob([ce],{type:`application/json; length=${ce.length}`})})}if(O.id!==void 0){const $=r[O.id];if($){delete r[O.id];for(const[Y,ce]of Object.entries($)){let Ue,nt;if(Array.isArray(ce)?[Ue,nt]=ce:(Ue=ce.mimeType,nt=ce.data),Y.includes(".")){console.warn(`Skipping attachment '${Y}' for run ${O.id}: Invalid attachment name. Attachment names must not contain periods ('.'). Please rename the attachment and try again.`);continue}u.push({name:`attachment.${O.id}.${Y}`,payload:new Blob([nt],{type:`${Ue}; length=${nt.byteLength}`})})}}}l.push(`trace=${O.trace_id},id=${O.id}`)}await this._sendMultipartRequest(u,l.join("; "),a)}async _createNodeFetchBody(t,n){const a=[];for(const s of t)a.push(new Blob([`--${n}\r
|
|
23
|
-
`])),a.push(new Blob([`Content-Disposition: form-data; name="${s.name}"\r
|
|
24
|
-
`,`Content-Type: ${s.payload.type}\r
|
|
25
|
-
\r
|
|
26
|
-
`])),a.push(s.payload),a.push(new Blob([`\r
|
|
27
|
-
`]));return a.push(new Blob([`--${n}--\r
|
|
28
|
-
`])),await new Blob(a).arrayBuffer()}async _createMultipartStream(t,n){const a=new TextEncoder;return new ReadableStream({async start(i){const s=async o=>{typeof o=="string"?i.enqueue(a.encode(o)):i.enqueue(o)};for(const o of t){await s(`--${n}\r
|
|
29
|
-
`),await s(`Content-Disposition: form-data; name="${o.name}"\r
|
|
30
|
-
`),await s(`Content-Type: ${o.payload.type}\r
|
|
31
|
-
\r
|
|
32
|
-
`);const l=o.payload.stream().getReader();try{let u;for(;!(u=await l.read()).done;)i.enqueue(u.value)}finally{l.releaseLock()}await s(`\r
|
|
33
|
-
`)}await s(`--${n}--\r
|
|
34
|
-
`),i.close()}})}async _sendMultipartRequest(t,n,a){const r="----LangSmithFormBoundary"+Math.random().toString(36).slice(2),i=Ps(),s=()=>this._createNodeFetchBody(t,r),o=()=>this._createMultipartStream(t,r),c=async l=>this.batchIngestCaller.call(async()=>{const u=await l(),h={...this.headers,"Content-Type":`multipart/form-data; boundary=${r}`};a?.apiKey!==void 0&&(h["x-api-key"]=a.apiKey);let d=u;a?.useGzip&&typeof u=="object"&&"pipeThrough"in u&&(d=u.pipeThrough(new CompressionStream("gzip")),h["Content-Encoding"]="gzip");const p=await this._fetch(`${a?.apiUrl??this.apiUrl}/runs/multipart`,{method:"POST",headers:h,body:d,duplex:"half",signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await _(p,"Failed to send multipart request",!0),p});try{let l,u=!1;!i&&!this.multipartStreamingDisabled&&Ka()!=="bun"?(u=!0,l=await c(o)):l=await c(s),(!this.multipartStreamingDisabled||u)&&l.status===422&&(a?.apiUrl??this.apiUrl)!==Gn&&(console.warn(`Streaming multipart upload to ${a?.apiUrl??this.apiUrl}/runs/multipart failed. This usually means the host does not support chunked uploads. Retrying with a buffered upload for operation "${n}".`),this.multipartStreamingDisabled=!0,l=await c(s))}catch(l){console.warn(`${l.message.trim()}
|
|
35
|
-
|
|
36
|
-
Context: ${n}`)}}async updateRun(t,n,a){S(t),n.inputs&&(n.inputs=await this.processInputs(n.inputs)),n.outputs&&(n.outputs=await this.processOutputs(n.outputs));const r={...n,id:t};if(!this._filterForSampling([r],!0).length)return;if(this.autoBatchTracing&&r.trace_id!==void 0&&r.dotted_order!==void 0){const o=this._cloneCurrentOTELContext();if(n.end_time!==void 0&&r.parent_run_id===void 0&&this.blockOnRootRunFinalization&&!this.manualFlushMode){await this.processRunOperation({action:"update",item:r,otelContext:o,apiKey:a?.apiKey,apiUrl:a?.apiUrl}).catch(console.error);return}else this.processRunOperation({action:"update",item:r,otelContext:o,apiKey:a?.apiKey,apiUrl:a?.apiUrl}).catch(console.error);return}const i={...this.headers,"Content-Type":"application/json"};a?.apiKey!==void 0&&(i["x-api-key"]=a.apiKey),a?.workspaceId!==void 0&&(i["x-tenant-id"]=a.workspaceId);const s=K(n,`Serializing payload to update run with id: ${t}`);await this.caller.call(async()=>{const o=await this._fetch(`${a?.apiUrl??this.apiUrl}/runs/${t}`,{method:"PATCH",headers:i,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await _(o,"update run",!0),o})}async readRun(t,{loadChildRuns:n}={loadChildRuns:!1}){S(t);let a=await this._get(`/runs/${t}`);return n&&(a=await this._loadChildRuns(a)),a}async getRunUrl({runId:t,run:n,projectOpts:a}){if(n!==void 0){let r;n.session_id?r=n.session_id:a?.projectName?r=(await this.readProject({projectName:a?.projectName})).id:a?.projectId?r=a?.projectId:r=(await this.readProject({projectName:J("PROJECT")||"default"})).id;const i=await this._getTenantId();return`${this.getHostUrl()}/o/${i}/projects/p/${r}/r/${n.id}?poll=true`}else if(t!==void 0){const r=await this.readRun(t);if(!r.app_path)throw new Error(`Run ${t} has no app_path`);return`${this.getHostUrl()}${r.app_path}`}else throw new Error("Must provide either runId or run")}async _loadChildRuns(t){const n=await uo(this.listRuns({isRoot:!1,projectId:t.session_id,traceId:t.trace_id})),a={},r={};n.sort((i,s)=>(i?.dotted_order??"").localeCompare(s?.dotted_order??""));for(const i of n){if(i.parent_run_id===null||i.parent_run_id===void 0)throw new Error(`Child run ${i.id} has no parent`);i.dotted_order?.startsWith(t.dotted_order??"")&&i.id!==t.id&&(i.parent_run_id in a||(a[i.parent_run_id]=[]),a[i.parent_run_id].push(i),r[i.id]=i)}t.child_runs=a[t.id]||[];for(const i in a)i!==t.id&&(r[i].child_runs=a[i]);return t}async*listRuns(t){const{projectId:n,projectName:a,parentRunId:r,traceId:i,referenceExampleId:s,startTime:o,executionOrder:c,isRoot:l,runType:u,error:h,id:d,query:p,filter:f,traceFilter:A,treeFilter:y,limit:g,select:v,order:E}=t;let I=[];if(n&&(I=Array.isArray(n)?n:[n]),a){const $=Array.isArray(a)?a:[a],Y=await Promise.all($.map(ce=>this.readProject({projectName:ce}).then(Ue=>Ue.id)));I.push(...Y)}const O=["app_path","completion_cost","completion_tokens","dotted_order","end_time","error","events","extra","feedback_stats","first_token_time","id","inputs","name","outputs","parent_run_id","parent_run_ids","prompt_cost","prompt_tokens","reference_example_id","run_type","session_id","start_time","status","tags","total_cost","total_tokens","trace_id"],N={session:I.length?I:null,run_type:u,reference_example:s,query:p,filter:f,trace_filter:A,tree_filter:y,execution_order:c,parent_run:r,start_time:o?o.toISOString():null,error:h,id:d,limit:g,trace:i,select:v||O,is_root:l,order:E};N.select.includes("child_run_ids")&&qt("Deprecated: 'child_run_ids' in the listRuns select parameter is deprecated and will be removed in a future version.");let R=0;for await(const $ of this._getCursorPaginatedList("/runs/query",N))if(g){if(R>=g)break;if($.length+R>g){yield*$.slice(0,g-R);break}R+=$.length,yield*$}else yield*$}async*listGroupRuns(t){const{projectId:n,projectName:a,groupBy:r,filter:i,startTime:s,endTime:o,limit:c,offset:l}=t,h={session_id:n||(await this.readProject({projectName:a})).id,group_by:r,filter:i,start_time:s?s.toISOString():null,end_time:o?o.toISOString():null,limit:Number(c)||100};let d=Number(l)||0;const p="/runs/group",f=`${this.apiUrl}${p}`;for(;;){const A={...h,offset:d},y=Object.fromEntries(Object.entries(A).filter(([N,R])=>R!==void 0)),g=JSON.stringify(y),E=await(await this.caller.call(async()=>{const N=await this._fetch(f,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:g});return await _(N,`Failed to fetch ${p}`),N})).json(),{groups:I,total:O}=E;if(I.length===0)break;for(const N of I)yield N;if(d+=I.length,d>=O)break}}async getRunStats({id:t,trace:n,parentRun:a,runType:r,projectNames:i,projectIds:s,referenceExampleIds:o,startTime:c,endTime:l,error:u,query:h,filter:d,traceFilter:p,treeFilter:f,isRoot:A,dataSourceType:y}){let g=s||[];i&&(g=[...s||[],...await Promise.all(i.map(R=>this.readProject({projectName:R}).then($=>$.id)))]);const E=Object.fromEntries(Object.entries({id:t,trace:n,parent_run:a,run_type:r,session:g,reference_example:o,start_time:c,end_time:l,error:u,query:h,filter:d,trace_filter:p,tree_filter:f,is_root:A,data_source_type:y}).filter(([R,$])=>$!==void 0)),I=JSON.stringify(E);return await(await this.caller.call(async()=>{const R=await this._fetch(`${this.apiUrl}/runs/stats`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:I});return await _(R,"get run stats"),R})).json()}async shareRun(t,{shareId:n}={}){const a={run_id:t,share_token:n||G()};S(t);const r=JSON.stringify(a),s=await(await this.caller.call(async()=>{const o=await this._fetch(`${this.apiUrl}/runs/${t}/share`,{method:"PUT",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:r});return await _(o,"share run"),o})).json();if(s===null||!("share_token"in s))throw new Error("Invalid response from server");return`${this.getHostUrl()}/public/${s.share_token}/r`}async unshareRun(t){S(t),await this.caller.call(async()=>{const n=await this._fetch(`${this.apiUrl}/runs/${t}/share`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await _(n,"unshare run",!0),n})}async readRunSharedLink(t){S(t);const a=await(await this.caller.call(async()=>{const r=await this._fetch(`${this.apiUrl}/runs/${t}/share`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await _(r,"read run shared link"),r})).json();if(!(a===null||!("share_token"in a)))return`${this.getHostUrl()}/public/${a.share_token}/r`}async listSharedRuns(t,{runIds:n}={}){const a=new URLSearchParams({share_token:t});if(n!==void 0)for(const s of n)a.append("id",s);return S(t),await(await this.caller.call(async()=>{const s=await this._fetch(`${this.apiUrl}/public/${t}/runs${a}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await _(s,"list shared runs"),s})).json()}async readDatasetSharedSchema(t,n){if(!t&&!n)throw new Error("Either datasetId or datasetName must be given");t||(t=(await this.readDataset({datasetName:n})).id),S(t);const r=await(await this.caller.call(async()=>{const i=await this._fetch(`${this.apiUrl}/datasets/${t}/share`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await _(i,"read dataset shared schema"),i})).json();return r.url=`${this.getHostUrl()}/public/${r.share_token}/d`,r}async shareDataset(t,n){if(!t&&!n)throw new Error("Either datasetId or datasetName must be given");t||(t=(await this.readDataset({datasetName:n})).id);const a={dataset_id:t};S(t);const r=JSON.stringify(a),s=await(await this.caller.call(async()=>{const o=await this._fetch(`${this.apiUrl}/datasets/${t}/share`,{method:"PUT",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:r});return await _(o,"share dataset"),o})).json();return s.url=`${this.getHostUrl()}/public/${s.share_token}/d`,s}async unshareDataset(t){S(t),await this.caller.call(async()=>{const n=await this._fetch(`${this.apiUrl}/datasets/${t}/share`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await _(n,"unshare dataset",!0),n})}async readSharedDataset(t){return S(t),await(await this.caller.call(async()=>{const r=await this._fetch(`${this.apiUrl}/public/${t}/datasets`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await _(r,"read shared dataset"),r})).json()}async listSharedExamples(t,n){const a={};n?.exampleIds&&(a.id=n.exampleIds);const r=new URLSearchParams;Object.entries(a).forEach(([o,c])=>{Array.isArray(c)?c.forEach(l=>r.append(o,l)):r.append(o,c)});const i=await this.caller.call(async()=>{const o=await this._fetch(`${this.apiUrl}/public/${t}/examples?${r.toString()}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await _(o,"list shared examples"),o}),s=await i.json();if(!i.ok)throw"detail"in s?new Error(`Failed to list shared examples.
|
|
37
|
-
Status: ${i.status}
|
|
38
|
-
Message: ${Array.isArray(s.detail)?s.detail.join(`
|
|
39
|
-
`):"Unspecified error"}`):new Error(`Failed to list shared examples: ${i.status} ${i.statusText}`);return s.map(o=>({...o,_hostUrl:this.getHostUrl()}))}async createProject({projectName:t,description:n=null,metadata:a=null,upsert:r=!1,projectExtra:i=null,referenceDatasetId:s=null}){const o=r?"?upsert=true":"",c=`${this.apiUrl}/sessions${o}`,l=i||{};a&&(l.metadata=a);const u={name:t,extra:l,description:n};s!==null&&(u.reference_dataset_id=s);const h=JSON.stringify(u);return await(await this.caller.call(async()=>{const f=await this._fetch(c,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:h});return await _(f,"create project"),f})).json()}async updateProject(t,{name:n=null,description:a=null,metadata:r=null,projectExtra:i=null,endTime:s=null}){const o=`${this.apiUrl}/sessions/${t}`;let c=i;r&&(c={...c||{},metadata:r});const l=JSON.stringify({name:n,extra:c,description:a,end_time:s?new Date(s).toISOString():null});return await(await this.caller.call(async()=>{const d=await this._fetch(o,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:l});return await _(d,"update project"),d})).json()}async hasProject({projectId:t,projectName:n}){let a="/sessions";const r=new URLSearchParams;if(t!==void 0&&n!==void 0)throw new Error("Must provide either projectName or projectId, not both");if(t!==void 0)S(t),a+=`/${t}`;else if(n!==void 0)r.append("name",n);else throw new Error("Must provide projectName or projectId");const i=await this.caller.call(async()=>{const s=await this._fetch(`${this.apiUrl}${a}?${r}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await _(s,"has project"),s});try{const s=await i.json();return i.ok?Array.isArray(s)?s.length>0:!0:!1}catch{return!1}}async readProject({projectId:t,projectName:n,includeStats:a}){let r="/sessions";const i=new URLSearchParams;if(t!==void 0&&n!==void 0)throw new Error("Must provide either projectName or projectId, not both");if(t!==void 0)S(t),r+=`/${t}`;else if(n!==void 0)i.append("name",n);else throw new Error("Must provide projectName or projectId");a!==void 0&&i.append("include_stats",a.toString());const s=await this._get(r,i);let o;if(Array.isArray(s)){if(s.length===0)throw new Error(`Project[id=${t}, name=${n}] not found`);o=s[0]}else o=s;return o}async getProjectUrl({projectId:t,projectName:n}){if(t===void 0&&n===void 0)throw new Error("Must provide either projectName or projectId");const a=await this.readProject({projectId:t,projectName:n}),r=await this._getTenantId();return`${this.getHostUrl()}/o/${r}/projects/p/${a.id}`}async getDatasetUrl({datasetId:t,datasetName:n}){if(t===void 0&&n===void 0)throw new Error("Must provide either datasetName or datasetId");const a=await this.readDataset({datasetId:t,datasetName:n}),r=await this._getTenantId();return`${this.getHostUrl()}/o/${r}/datasets/${a.id}`}async _getTenantId(){if(this._tenantId!==null)return this._tenantId;const t=new URLSearchParams({limit:"1"});for await(const n of this._getPaginated("/sessions",t))return this._tenantId=n[0].tenant_id,n[0].tenant_id;throw new Error("No projects found to resolve tenant.")}async*listProjects({projectIds:t,name:n,nameContains:a,referenceDatasetId:r,referenceDatasetName:i,includeStats:s,datasetVersion:o,referenceFree:c,metadata:l}={}){const u=new URLSearchParams;if(t!==void 0)for(const h of t)u.append("id",h);if(n!==void 0&&u.append("name",n),a!==void 0&&u.append("name_contains",a),r!==void 0)u.append("reference_dataset",r);else if(i!==void 0){const h=await this.readDataset({datasetName:i});u.append("reference_dataset",h.id)}s!==void 0&&u.append("include_stats",s.toString()),o!==void 0&&u.append("dataset_version",o),c!==void 0&&u.append("reference_free",c.toString()),l!==void 0&&u.append("metadata",JSON.stringify(l));for await(const h of this._getPaginated("/sessions",u))yield*h}async deleteProject({projectId:t,projectName:n}){let a;if(t===void 0&&n===void 0)throw new Error("Must provide projectName or projectId");if(t!==void 0&&n!==void 0)throw new Error("Must provide either projectName or projectId, not both");t===void 0?a=(await this.readProject({projectName:n})).id:a=t,S(a),await this.caller.call(async()=>{const r=await this._fetch(`${this.apiUrl}/sessions/${a}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await _(r,`delete session ${a} (${n})`,!0),r})}async uploadCsv({csvFile:t,fileName:n,inputKeys:a,outputKeys:r,description:i,dataType:s,name:o}){const c=`${this.apiUrl}/datasets/upload`,l=new FormData;return l.append("file",t,n),a.forEach(d=>{l.append("input_keys",d)}),r.forEach(d=>{l.append("output_keys",d)}),i&&l.append("description",i),s&&l.append("data_type",s),o&&l.append("name",o),await(await this.caller.call(async()=>{const d=await this._fetch(c,{method:"POST",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:l});return await _(d,"upload CSV"),d})).json()}async createDataset(t,{description:n,dataType:a,inputsSchema:r,outputsSchema:i,metadata:s}={}){const o={name:t,description:n,extra:s?{metadata:s}:void 0};a&&(o.data_type=a),r&&(o.inputs_schema_definition=r),i&&(o.outputs_schema_definition=i);const c=JSON.stringify(o);return await(await this.caller.call(async()=>{const h=await this._fetch(`${this.apiUrl}/datasets`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await _(h,"create dataset"),h})).json()}async readDataset({datasetId:t,datasetName:n}){let a="/datasets";const r=new URLSearchParams({limit:"1"});if(t&&n)throw new Error("Must provide either datasetName or datasetId, not both");if(t)S(t),a+=`/${t}`;else if(n)r.append("name",n);else throw new Error("Must provide datasetName or datasetId");const i=await this._get(a,r);let s;if(Array.isArray(i)){if(i.length===0)throw new Error(`Dataset[id=${t}, name=${n}] not found`);s=i[0]}else s=i;return s}async hasDataset({datasetId:t,datasetName:n}){try{return await this.readDataset({datasetId:t,datasetName:n}),!0}catch(a){if(a instanceof Error&&a.message.toLocaleLowerCase().includes("not found"))return!1;throw a}}async diffDatasetVersions({datasetId:t,datasetName:n,fromVersion:a,toVersion:r}){let i=t;if(i===void 0&&n===void 0)throw new Error("Must provide either datasetName or datasetId");if(i!==void 0&&n!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");i===void 0&&(i=(await this.readDataset({datasetName:n})).id);const s=new URLSearchParams({from_version:typeof a=="string"?a:a.toISOString(),to_version:typeof r=="string"?r:r.toISOString()});return await this._get(`/datasets/${i}/versions/diff`,s)}async readDatasetOpenaiFinetuning({datasetId:t,datasetName:n}){const a="/datasets";if(t===void 0)if(n!==void 0)t=(await this.readDataset({datasetName:n})).id;else throw new Error("Must provide either datasetName or datasetId");return(await(await this._getResponse(`${a}/${t}/openai_ft`)).text()).trim().split(`
|
|
40
|
-
`).map(o=>JSON.parse(o))}async*listDatasets({limit:t=100,offset:n=0,datasetIds:a,datasetName:r,datasetNameContains:i,metadata:s}={}){const o="/datasets",c=new URLSearchParams({limit:t.toString(),offset:n.toString()});if(a!==void 0)for(const l of a)c.append("id",l);r!==void 0&&c.append("name",r),i!==void 0&&c.append("name_contains",i),s!==void 0&&c.append("metadata",JSON.stringify(s));for await(const l of this._getPaginated(o,c))yield*l}async updateDataset(t){const{datasetId:n,datasetName:a,...r}=t;if(!n&&!a)throw new Error("Must provide either datasetName or datasetId");const i=n??(await this.readDataset({datasetName:a})).id;S(i);const s=JSON.stringify(r);return await(await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/datasets/${i}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await _(c,"update dataset"),c})).json()}async updateDatasetTag(t){const{datasetId:n,datasetName:a,asOf:r,tag:i}=t;if(!n&&!a)throw new Error("Must provide either datasetName or datasetId");const s=n??(await this.readDataset({datasetName:a})).id;S(s);const o=JSON.stringify({as_of:typeof r=="string"?r:r.toISOString(),tag:i});await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/datasets/${s}/tags`,{method:"PUT",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await _(c,"update dataset tags",!0),c})}async deleteDataset({datasetId:t,datasetName:n}){let a="/datasets",r=t;if(t!==void 0&&n!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");if(n!==void 0&&(r=(await this.readDataset({datasetName:n})).id),r!==void 0)S(r),a+=`/${r}`;else throw new Error("Must provide datasetName or datasetId");await this.caller.call(async()=>{const i=await this._fetch(this.apiUrl+a,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await _(i,`delete ${a}`,!0),i})}async indexDataset({datasetId:t,datasetName:n,tag:a}){let r=t;if(!r&&!n)throw new Error("Must provide either datasetName or datasetId");if(r&&n)throw new Error("Must provide either datasetName or datasetId, not both");r||(r=(await this.readDataset({datasetName:n})).id),S(r);const s=JSON.stringify({tag:a});await(await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/datasets/${r}/index`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await _(c,"index dataset"),c})).json()}async similarExamples(t,n,a,{filter:r}={}){const i={limit:a,inputs:t};r!==void 0&&(i.filter=r),S(n);const s=JSON.stringify(i);return(await(await this.caller.call(async()=>{const l=await this._fetch(`${this.apiUrl}/datasets/${n}/search`,{headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,method:"POST",body:s});return await _(l,"fetch similar examples"),l})).json()).examples}async createExample(t,n,a){if(Zn(t)&&(n!==void 0||a!==void 0))throw new Error("Cannot provide outputs or options when using ExampleCreate object");let r=n?a?.datasetId:t.dataset_id;const i=n?a?.datasetName:t.dataset_name;if(r===void 0&&i===void 0)throw new Error("Must provide either datasetName or datasetId");if(r!==void 0&&i!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");r===void 0&&(r=(await this.readDataset({datasetName:i})).id);const s=(n?a?.createdAt:t.created_at)||new Date;let o;Zn(t)?o=t:o={inputs:t,outputs:n,created_at:s?.toISOString(),id:a?.exampleId,metadata:a?.metadata,split:a?.split,source_run_id:a?.sourceRunId,use_source_run_io:a?.useSourceRunIO,use_source_run_attachments:a?.useSourceRunAttachments,attachments:a?.attachments};const c=await this._uploadExamplesMultipart(r,[o]);return await this.readExample(c.example_ids?.[0]??G())}async createExamples(t){if(Array.isArray(t)){if(t.length===0)return[];const v=t;let E=v[0].dataset_id;const I=v[0].dataset_name;if(E===void 0&&I===void 0)throw new Error("Must provide either datasetName or datasetId");if(E!==void 0&&I!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");E===void 0&&(E=(await this.readDataset({datasetName:I})).id);const O=await this._uploadExamplesMultipart(E,v);return await Promise.all(O.example_ids.map(R=>this.readExample(R)))}const{inputs:n,outputs:a,metadata:r,splits:i,sourceRunIds:s,useSourceRunIOs:o,useSourceRunAttachments:c,attachments:l,exampleIds:u,datasetId:h,datasetName:d}=t;if(n===void 0)throw new Error("Must provide inputs when using legacy parameters");let p=h;const f=d;if(p===void 0&&f===void 0)throw new Error("Must provide either datasetName or datasetId");if(p!==void 0&&f!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");p===void 0&&(p=(await this.readDataset({datasetName:f})).id);const A=n.map((v,E)=>({dataset_id:p,inputs:v,outputs:a?.[E],metadata:r?.[E],split:i?.[E],id:u?.[E],attachments:l?.[E],source_run_id:s?.[E],use_source_run_io:o?.[E],use_source_run_attachments:c?.[E]})),y=await this._uploadExamplesMultipart(p,A);return await Promise.all(y.example_ids.map(v=>this.readExample(v)))}async createLLMExample(t,n,a){return this.createExample({input:t},{output:n},a)}async createChatExample(t,n,a){const r=t.map(s=>Dn(s)?Un(s):s),i=Dn(n)?Un(n):n;return this.createExample({input:r},{output:i},a)}async readExample(t){S(t);const n=`/examples/${t}`,a=await this._get(n),{attachment_urls:r,...i}=a,s=i;return r&&(s.attachments=Object.entries(r).reduce((o,[c,l])=>(o[c.slice(11)]={presigned_url:l.presigned_url,mime_type:l.mime_type},o),{})),s}async*listExamples({datasetId:t,datasetName:n,exampleIds:a,asOf:r,splits:i,inlineS3Urls:s,metadata:o,limit:c,offset:l,filter:u,includeAttachments:h}={}){let d;if(t!==void 0&&n!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");if(t!==void 0)d=t;else if(n!==void 0)d=(await this.readDataset({datasetName:n})).id;else throw new Error("Must provide a datasetName or datasetId");const p=new URLSearchParams({dataset:d}),f=r?typeof r=="string"?r:r?.toISOString():void 0;f&&p.append("as_of",f);const A=s??!0;if(p.append("inline_s3_urls",A.toString()),a!==void 0)for(const g of a)p.append("id",g);if(i!==void 0)for(const g of i)p.append("splits",g);if(o!==void 0){const g=JSON.stringify(o);p.append("metadata",g)}c!==void 0&&p.append("limit",c.toString()),l!==void 0&&p.append("offset",l.toString()),u!==void 0&&p.append("filter",u),h===!0&&["attachment_urls","outputs","metadata"].forEach(g=>p.append("select",g));let y=0;for await(const g of this._getPaginated("/examples",p)){for(const v of g){const{attachment_urls:E,...I}=v,O=I;E&&(O.attachments=Object.entries(E).reduce((N,[R,$])=>(N[R.slice(11)]={presigned_url:$.presigned_url,mime_type:$.mime_type||void 0},N),{})),yield O,y++}if(c!==void 0&&y>=c)break}}async deleteExample(t){S(t);const n=`/examples/${t}`;await this.caller.call(async()=>{const a=await this._fetch(this.apiUrl+n,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await _(a,`delete ${n}`,!0),a})}async updateExample(t,n){let a;n?a=t:a=t.id,S(a);let r;n?r={id:a,...n}:r=t;let i;return r.dataset_id!==void 0?i=r.dataset_id:i=(await this.readExample(a)).dataset_id,this._updateExamplesMultipart(i,[r])}async updateExamples(t){let n;return t[0].dataset_id===void 0?n=(await this.readExample(t[0].id)).dataset_id:n=t[0].dataset_id,this._updateExamplesMultipart(n,t)}async readDatasetVersion({datasetId:t,datasetName:n,asOf:a,tag:r}){let i;if(t?i=t:i=(await this.readDataset({datasetName:n})).id,S(i),a&&r||!a&&!r)throw new Error("Exactly one of asOf and tag must be specified.");const s=new URLSearchParams;return a!==void 0&&s.append("as_of",typeof a=="string"?a:a.toISOString()),r!==void 0&&s.append("tag",r),await(await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/datasets/${i}/version?${s.toString()}`,{method:"GET",headers:{...this.headers},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await _(c,"read dataset version"),c})).json()}async listDatasetSplits({datasetId:t,datasetName:n,asOf:a}){let r;if(t===void 0&&n===void 0)throw new Error("Must provide dataset name or ID");if(t!==void 0&&n!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");t===void 0?r=(await this.readDataset({datasetName:n})).id:r=t,S(r);const i=new URLSearchParams,s=a?typeof a=="string"?a:a?.toISOString():void 0;return s&&i.append("as_of",s),await this._get(`/datasets/${r}/splits`,i)}async updateDatasetSplits({datasetId:t,datasetName:n,splitName:a,exampleIds:r,remove:i=!1}){let s;if(t===void 0&&n===void 0)throw new Error("Must provide dataset name or ID");if(t!==void 0&&n!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");t===void 0?s=(await this.readDataset({datasetName:n})).id:s=t,S(s);const o={split_name:a,examples:r.map(l=>(S(l),l)),remove:i},c=JSON.stringify(o);await this.caller.call(async()=>{const l=await this._fetch(`${this.apiUrl}/datasets/${s}/splits`,{method:"PUT",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await _(l,"update dataset splits",!0),l})}async evaluateRun(t,n,{sourceInfo:a,loadChildRuns:r,referenceExample:i}={loadChildRuns:!1}){qt("This method is deprecated and will be removed in future LangSmith versions, use `evaluate` from `langsmith/evaluation` instead.");let s;if(typeof t=="string")s=await this.readRun(t,{loadChildRuns:r});else if(typeof t=="object"&&"id"in t)s=t;else throw new Error(`Invalid run type: ${typeof t}`);s.reference_example_id!==null&&s.reference_example_id!==void 0&&(i=await this.readExample(s.reference_example_id));const o=await n.evaluateRun(s,i),[c,l]=await this._logEvaluationFeedback(o,s,a);return l[0]}async createFeedback(t,n,{score:a,value:r,correction:i,comment:s,sourceInfo:o,feedbackSourceType:c="api",sourceRunId:l,feedbackId:u,feedbackConfig:h,projectId:d,comparativeExperimentId:p}){if(!t&&!d)throw new Error("One of runId or projectId must be provided");if(t&&d)throw new Error("Only one of runId or projectId can be provided");const f={type:c??"api",metadata:o??{}};l!==void 0&&f?.metadata!==void 0&&!f.metadata.__run&&(f.metadata.__run={run_id:l}),f?.metadata!==void 0&&f.metadata.__run?.run_id!==void 0&&S(f.metadata.__run.run_id);const A={id:u??G(),run_id:t,key:n,score:Hn(a),value:r,correction:i,comment:s,feedback_source:f,comparative_experiment_id:p,feedbackConfig:h,session_id:d},y=JSON.stringify(A),g=`${this.apiUrl}/feedback`;return await this.caller.call(async()=>{const v=await this._fetch(g,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:y});return await _(v,"create feedback",!0),v}),A}async updateFeedback(t,{score:n,value:a,correction:r,comment:i}){const s={};n!=null&&(s.score=Hn(n)),a!=null&&(s.value=a),r!=null&&(s.correction=r),i!=null&&(s.comment=i),S(t);const o=JSON.stringify(s);await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/feedback/${t}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await _(c,"update feedback",!0),c})}async readFeedback(t){S(t);const n=`/feedback/${t}`;return await this._get(n)}async deleteFeedback(t){S(t);const n=`/feedback/${t}`;await this.caller.call(async()=>{const a=await this._fetch(this.apiUrl+n,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await _(a,`delete ${n}`,!0),a})}async*listFeedback({runIds:t,feedbackKeys:n,feedbackSourceTypes:a}={}){const r=new URLSearchParams;if(t)for(const i of t)S(i),r.append("run",i);if(n)for(const i of n)r.append("key",i);if(a)for(const i of a)r.append("source",i);for await(const i of this._getPaginated("/feedback",r))yield*i}async createPresignedFeedbackToken(t,n,{expiration:a,feedbackConfig:r}={}){const i={run_id:t,feedback_key:n,feedback_config:r};a?typeof a=="string"?i.expires_at=a:(a?.hours||a?.minutes||a?.days)&&(i.expires_in=a):i.expires_in={hours:3};const s=JSON.stringify(i);return await(await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/feedback/tokens`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await _(c,"create presigned feedback token"),c})).json()}async createComparativeExperiment({name:t,experimentIds:n,referenceDatasetId:a,createdAt:r,description:i,metadata:s,id:o}){if(n.length===0)throw new Error("At least one experiment is required");if(a||(a=(await this.readProject({projectId:n[0]})).reference_dataset_id),!a==null)throw new Error("A reference dataset is required");const c={id:o,name:t,experiment_ids:n,reference_dataset_id:a,description:i,created_at:(r??new Date)?.toISOString(),extra:{}};s&&(c.extra.metadata=s);const l=JSON.stringify(c);return(await this.caller.call(async()=>{const h=await this._fetch(`${this.apiUrl}/datasets/comparative`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:l});return await _(h,"create comparative experiment"),h})).json()}async*listPresignedFeedbackTokens(t){S(t);const n=new URLSearchParams({run_id:t});for await(const a of this._getPaginated("/feedback/tokens",n))yield*a}_selectEvalResults(t){let n;return"results"in t?n=t.results:Array.isArray(t)?n=t:n=[t],n}async _logEvaluationFeedback(t,n,a){const r=this._selectEvalResults(t),i=[];for(const s of r){let o=a||{};s.evaluatorInfo&&(o={...s.evaluatorInfo,...o});let c=null;s.targetRunId?c=s.targetRunId:n&&(c=n.id),i.push(await this.createFeedback(c,s.key,{score:s.score,value:s.value,comment:s.comment,correction:s.correction,sourceInfo:o,sourceRunId:s.sourceRunId,feedbackConfig:s.feedbackConfig,feedbackSourceType:"model"}))}return[r,i]}async logEvaluationFeedback(t,n,a){const[r]=await this._logEvaluationFeedback(t,n,a);return r}async*listAnnotationQueues(t={}){const{queueIds:n,name:a,nameContains:r,limit:i}=t,s=new URLSearchParams;n&&n.forEach((c,l)=>{S(c,`queueIds[${l}]`),s.append("ids",c)}),a&&s.append("name",a),r&&s.append("name_contains",r),s.append("limit",(i!==void 0?Math.min(i,100):100).toString());let o=0;for await(const c of this._getPaginated("/annotation-queues",s))if(yield*c,o++,i!==void 0&&o>=i)break}async createAnnotationQueue(t){const{name:n,description:a,queueId:r,rubricInstructions:i}=t,s={name:n,description:a,id:r||G(),rubric_instructions:i},o=JSON.stringify(Object.fromEntries(Object.entries(s).filter(([l,u])=>u!==void 0)));return(await this.caller.call(async()=>{const l=await this._fetch(`${this.apiUrl}/annotation-queues`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await _(l,"create annotation queue"),l})).json()}async readAnnotationQueue(t){return(await this.caller.call(async()=>{const a=await this._fetch(`${this.apiUrl}/annotation-queues/${S(t,"queueId")}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await _(a,"read annotation queue"),a})).json()}async updateAnnotationQueue(t,n){const{name:a,description:r,rubricInstructions:i}=n,s=JSON.stringify({name:a,description:r,rubric_instructions:i});await this.caller.call(async()=>{const o=await this._fetch(`${this.apiUrl}/annotation-queues/${S(t,"queueId")}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await _(o,"update annotation queue",!0),o})}async deleteAnnotationQueue(t){await this.caller.call(async()=>{const n=await this._fetch(`${this.apiUrl}/annotation-queues/${S(t,"queueId")}`,{method:"DELETE",headers:{...this.headers,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await _(n,"delete annotation queue",!0),n})}async addRunsToAnnotationQueue(t,n){const a=JSON.stringify(n.map((r,i)=>S(r,`runIds[${i}]`).toString()));await this.caller.call(async()=>{const r=await this._fetch(`${this.apiUrl}/annotation-queues/${S(t,"queueId")}/runs`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await _(r,"add runs to annotation queue",!0),r})}async getRunFromAnnotationQueue(t,n){const a=`/annotation-queues/${S(t,"queueId")}/run`;return(await this.caller.call(async()=>{const i=await this._fetch(`${this.apiUrl}${a}/${n}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await _(i,"get run from annotation queue"),i})).json()}async deleteRunFromAnnotationQueue(t,n){await this.caller.call(async()=>{const a=await this._fetch(`${this.apiUrl}/annotation-queues/${S(t,"queueId")}/runs/${S(n,"queueRunId")}`,{method:"DELETE",headers:{...this.headers,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await _(a,"delete run from annotation queue",!0),a})}async getSizeFromAnnotationQueue(t){return(await this.caller.call(async()=>{const a=await this._fetch(`${this.apiUrl}/annotation-queues/${S(t,"queueId")}/size`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await _(a,"get size from annotation queue"),a})).json()}async _currentTenantIsOwner(t){const n=await this._getSettings();return t=="-"||n.tenant_handle===t}async _ownerConflictError(t,n){const a=await this._getSettings();return new Error(`Cannot ${t} for another tenant.
|
|
41
|
-
|
|
42
|
-
Current tenant: ${a.tenant_handle}
|
|
43
|
-
|
|
44
|
-
Requested tenant: ${n}`)}async _getLatestCommitHash(t){const a=await(await this.caller.call(async()=>{const r=await this._fetch(`${this.apiUrl}/commits/${t}/?limit=1&offset=0`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await _(r,"get latest commit hash"),r})).json();if(a.commits.length!==0)return a.commits[0].commit_hash}async _likeOrUnlikePrompt(t,n){const[a,r,i]=fe(t),s=JSON.stringify({like:n});return(await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/likes/${a}/${r}`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await _(c,`${n?"like":"unlike"} prompt`),c})).json()}async _getPromptUrl(t){const[n,a,r]=fe(t);if(await this._currentTenantIsOwner(n)){const i=await this._getSettings();return r!=="latest"?`${this.getHostUrl()}/prompts/${a}/${r.substring(0,8)}?organizationId=${i.id}`:`${this.getHostUrl()}/prompts/${a}?organizationId=${i.id}`}else return r!=="latest"?`${this.getHostUrl()}/hub/${n}/${a}/${r.substring(0,8)}`:`${this.getHostUrl()}/hub/${n}/${a}`}async promptExists(t){return!!await this.getPrompt(t)}async likePrompt(t){return this._likeOrUnlikePrompt(t,!0)}async unlikePrompt(t){return this._likeOrUnlikePrompt(t,!1)}async*listCommits(t){for await(const n of this._getPaginated(`/commits/${t}/`,new URLSearchParams,a=>a.commits))yield*n}async*listPrompts(t){const n=new URLSearchParams;n.append("sort_field",t?.sortField??"updated_at"),n.append("sort_direction","desc"),n.append("is_archived",(!!t?.isArchived).toString()),t?.isPublic!==void 0&&n.append("is_public",t.isPublic.toString()),t?.query&&n.append("query",t.query);for await(const a of this._getPaginated("/repos",n,r=>r.repos))yield*a}async getPrompt(t){const[n,a,r]=fe(t),s=await(await this.caller.call(async()=>{const o=await this._fetch(`${this.apiUrl}/repos/${n}/${a}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return o?.status===404?null:(await _(o,"get prompt"),o)}))?.json();return s?.repo?s.repo:null}async createPrompt(t,n){const a=await this._getSettings();if(n?.isPublic&&!a.tenant_handle)throw new Error(`Cannot create a public prompt without first
|
|
45
|
-
|
|
46
|
-
creating a LangChain Hub handle.
|
|
47
|
-
You can add a handle by creating a public prompt at:
|
|
48
|
-
|
|
49
|
-
https://smith.langchain.com/prompts`);const[r,i,s]=fe(t);if(!await this._currentTenantIsOwner(r))throw await this._ownerConflictError("create a prompt",r);const o={repo_handle:i,...n?.description&&{description:n.description},...n?.readme&&{readme:n.readme},...n?.tags&&{tags:n.tags},is_public:!!n?.isPublic},c=JSON.stringify(o),l=await this.caller.call(async()=>{const h=await this._fetch(`${this.apiUrl}/repos/`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await _(h,"create prompt"),h}),{repo:u}=await l.json();return u}async createCommit(t,n,a){if(!await this.promptExists(t))throw new Error("Prompt does not exist, you must create it first.");const[r,i,s]=fe(t),o=a?.parentCommitHash==="latest"||!a?.parentCommitHash?await this._getLatestCommitHash(`${r}/${i}`):a?.parentCommitHash,c={manifest:JSON.parse(JSON.stringify(n)),parent_commit:o},l=JSON.stringify(c),h=await(await this.caller.call(async()=>{const d=await this._fetch(`${this.apiUrl}/commits/${r}/${i}`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:l});return await _(d,"create commit"),d})).json();return this._getPromptUrl(`${r}/${i}${h.commit_hash?`:${h.commit_hash}`:""}`)}async updateExamplesMultipart(t,n=[]){return this._updateExamplesMultipart(t,n)}async _updateExamplesMultipart(t,n=[]){if(!await this._getDatasetExamplesMultiPartSupport())throw new Error("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version.");const a=new FormData;for(const s of n){const o=s.id,c={...s.metadata&&{metadata:s.metadata},...s.split&&{split:s.split}},l=K(c,`Serializing body for example with id: ${o}`),u=new Blob([l],{type:"application/json"});if(a.append(o,u),s.inputs){const h=K(s.inputs,`Serializing inputs for example with id: ${o}`),d=new Blob([h],{type:"application/json"});a.append(`${o}.inputs`,d)}if(s.outputs){const h=K(s.outputs,`Serializing outputs whle updating example with id: ${o}`),d=new Blob([h],{type:"application/json"});a.append(`${o}.outputs`,d)}if(s.attachments)for(const[h,d]of Object.entries(s.attachments)){let p,f;Array.isArray(d)?[p,f]=d:(p=d.mimeType,f=d.data);const A=new Blob([f],{type:`${p}; length=${f.byteLength}`});a.append(`${o}.attachment.${h}`,A)}if(s.attachments_operations){const h=K(s.attachments_operations,`Serializing attachments while updating example with id: ${o}`),d=new Blob([h],{type:"application/json"});a.append(`${o}.attachments_operations`,d)}}const r=t??n[0]?.dataset_id;return(await this.caller.call(async()=>{const s=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${r}/examples`)}`,{method:"PATCH",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await _(s,"update examples"),s})).json()}async uploadExamplesMultipart(t,n=[]){return this._uploadExamplesMultipart(t,n)}async _uploadExamplesMultipart(t,n=[]){if(!await this._getDatasetExamplesMultiPartSupport())throw new Error("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version.");const a=new FormData;for(const i of n){const s=(i.id??G()).toString(),o={created_at:i.created_at,...i.metadata&&{metadata:i.metadata},...i.split&&{split:i.split},...i.source_run_id&&{source_run_id:i.source_run_id},...i.use_source_run_io&&{use_source_run_io:i.use_source_run_io},...i.use_source_run_attachments&&{use_source_run_attachments:i.use_source_run_attachments}},c=K(o,`Serializing body for uploaded example with id: ${s}`),l=new Blob([c],{type:"application/json"});if(a.append(s,l),i.inputs){const u=K(i.inputs,`Serializing inputs for uploaded example with id: ${s}`),h=new Blob([u],{type:"application/json"});a.append(`${s}.inputs`,h)}if(i.outputs){const u=K(i.outputs,`Serializing outputs for uploaded example with id: ${s}`),h=new Blob([u],{type:"application/json"});a.append(`${s}.outputs`,h)}if(i.attachments)for(const[u,h]of Object.entries(i.attachments)){let d,p;Array.isArray(h)?[d,p]=h:(d=h.mimeType,p=h.data);const f=new Blob([p],{type:`${d}; length=${p.byteLength}`});a.append(`${s}.attachment.${u}`,f)}}return(await this.caller.call(async()=>{const i=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${t}/examples`)}`,{method:"POST",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await _(i,"upload examples"),i})).json()}async updatePrompt(t,n){if(!await this.promptExists(t))throw new Error("Prompt does not exist, you must create it first.");const[a,r]=fe(t);if(!await this._currentTenantIsOwner(a))throw await this._ownerConflictError("update a prompt",a);const i={};if(n?.description!==void 0&&(i.description=n.description),n?.readme!==void 0&&(i.readme=n.readme),n?.tags!==void 0&&(i.tags=n.tags),n?.isPublic!==void 0&&(i.is_public=n.isPublic),n?.isArchived!==void 0&&(i.is_archived=n.isArchived),Object.keys(i).length===0)throw new Error("No valid update options provided");const s=JSON.stringify(i);return(await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/repos/${a}/${r}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await _(c,"update prompt"),c})).json()}async deletePrompt(t){if(!await this.promptExists(t))throw new Error("Prompt does not exist, you must create it first.");const[n,a,r]=fe(t);if(!await this._currentTenantIsOwner(n))throw await this._ownerConflictError("delete a prompt",n);return(await this.caller.call(async()=>{const s=await this._fetch(`${this.apiUrl}/repos/${n}/${a}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await _(s,"delete prompt"),s})).json()}async pullPromptCommit(t,n){const[a,r,i]=fe(t),o=await(await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/commits/${a}/${r}/${i}${n?.includeModel?"?include_model=true":""}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await _(c,"pull prompt commit"),c})).json();return{owner:a,repo:r,commit_hash:o.commit_hash,manifest:o.manifest,examples:o.examples}}async _pullPrompt(t,n){const a=await this.pullPromptCommit(t,{includeModel:n?.includeModel});return JSON.stringify(a.manifest)}async pushPrompt(t,n){return await this.promptExists(t)?n&&Object.keys(n).some(r=>r!=="object")&&await this.updatePrompt(t,{description:n?.description,readme:n?.readme,tags:n?.tags,isPublic:n?.isPublic}):await this.createPrompt(t,{description:n?.description,readme:n?.readme,tags:n?.tags,isPublic:n?.isPublic}),n?.object?await this.createCommit(t,n?.object,{parentCommitHash:n?.parentCommitHash}):await this._getPromptUrl(t)}async clonePublicDataset(t,n={}){const{sourceApiUrl:a=this.apiUrl,datasetName:r}=n,[i,s]=this.parseTokenOrUrl(t,a),o=new Je({apiUrl:i,apiKey:"placeholder"}),c=await o.readSharedDataset(s),l=r||c.name;try{if(await this.hasDataset({datasetId:l})){console.log(`Dataset ${l} already exists in your tenant. Skipping.`);return}}catch{}const u=await o.listSharedExamples(s),h=await this.createDataset(l,{description:c.description,dataType:c.data_type||"kv",inputsSchema:c.inputs_schema_definition??void 0,outputsSchema:c.outputs_schema_definition??void 0});try{await this.createExamples({inputs:u.map(d=>d.inputs),outputs:u.flatMap(d=>d.outputs?[d.outputs]:[]),datasetId:h.id})}catch(d){throw console.error(`An error occurred while creating dataset ${l}. You should delete it manually.`),d}}parseTokenOrUrl(t,n,a=2,r="dataset"){try{return S(t),[n,t]}catch{}try{const s=new URL(t).pathname.split("/").filter(o=>o!=="");if(s.length>=a){const o=s[s.length-a];return[n,o]}else throw new Error(`Invalid public ${r} URL: ${t}`)}catch{throw new Error(`Invalid public ${r} URL or token: ${t}`)}}async awaitPendingTraceBatches(){if(this.manualFlushMode)return console.warn("[WARNING]: When tracing in manual flush mode, you must call `await client.flush()` manually to submit trace batches."),Promise.resolve();await Promise.all([...this.autoBatchQueue.items.map(({itemPromise:t})=>t),this.batchIngestCaller.queue.onIdle()]),this.langSmithToOTELTranslator!==void 0&&await Vs()?.DEFAULT_LANGSMITH_SPAN_PROCESSOR?.forceFlush()}}function Zn(e){return"dataset_id"in e||"dataset_name"in e}const _o=e=>!!["TRACING_V2","TRACING"].find(n=>J(n)==="true"),Mt=Symbol.for("lc:context_variables");function yo(e){return e.replace(/[-:.]/g,"")}function ar(e,t,n=1){const a=n.toFixed(0).slice(0,3).padStart(3,"0"),r=`${new Date(e).toISOString().slice(0,-1)}${a}Z`;return{dottedOrder:yo(r)+t,microsecondPrecisionDatestring:r}}class ht{constructor(t,n,a,r){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=t,this.tags=n,this.project_name=a,this.replicas=r}static fromHeader(t){const n=t.split(",");let a={},r=[],i,s;for(const o of n){const[c,l]=o.split("="),u=decodeURIComponent(l);c==="langsmith-metadata"?a=JSON.parse(u):c==="langsmith-tags"?r=u.split(","):c==="langsmith-project"?i=u:c==="langsmith-replicas"&&(s=JSON.parse(u))}return new ht(a,r,i,s)}toHeader(){const t=[];return this.metadata&&Object.keys(this.metadata).length>0&&t.push(`langsmith-metadata=${encodeURIComponent(JSON.stringify(this.metadata))}`),this.tags&&this.tags.length>0&&t.push(`langsmith-tags=${encodeURIComponent(this.tags.join(","))}`),this.project_name&&t.push(`langsmith-project=${encodeURIComponent(this.project_name)}`),t.join(",")}}class q{constructor(t){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}),wo(t)){Object.assign(this,{...t});return}const n=q.getDefaultConfig(),{metadata:a,...r}=t,i=r.client??q.getSharedClient(),s={...a,...r?.extra?.metadata};if(r.extra={...r.extra,metadata:s},Object.assign(this,{...n,...r,client:i}),this.trace_id||(this.parent_run?this.trace_id=this.parent_run.trace_id??this.id:this.trace_id=this.id),this.replicas=To(this.replicas),this.execution_order??=1,this.child_execution_order??=1,!this.dotted_order){const{dottedOrder:o,microsecondPrecisionDatestring:c}=ar(this.start_time,this.id,this.execution_order);this.parent_run?this.dotted_order=this.parent_run.dotted_order+"."+o:this.dotted_order=o,this._serialized_start_time=c}}set metadata(t){this.extra={...this.extra,metadata:{...this.extra?.metadata,...t}}}get metadata(){return this.extra?.metadata}static getDefaultConfig(){return{id:G(),run_type:"chain",project_name:Ja(),child_runs:[],api_url:oe("LANGCHAIN_ENDPOINT")??"http://localhost:1984",api_key:oe("LANGCHAIN_API_KEY"),caller_options:{},start_time:Date.now(),serialized:{},inputs:{},extra:{}}}static getSharedClient(){return q.sharedClient||(q.sharedClient=new Je),q.sharedClient}createChild(t){const n=this.child_execution_order+1,a=new q({...t,parent_run:this,project_name:this.project_name,replicas:this.replicas,client:this.client,tracingEnabled:this.tracingEnabled,execution_order:n,child_execution_order:n});Mt in this&&(a[Mt]=this[Mt]);const r=Symbol.for("lc:child_config"),i=t.extra?.[r]??this.extra[r];if(bo(i)){const c={...i},l=vo(c.callbacks)?c.callbacks.copy?.():void 0;l&&(Object.assign(l,{_parentRunId:a.id}),l.handlers?.find(rr)?.updateFromRunTree?.(a),c.callbacks=l),a.extra[r]=c}const s=new Set;let o=this;for(;o!=null&&!s.has(o.id);)s.add(o.id),o.child_execution_order=Math.max(o.child_execution_order,n),o=o.parent_run;return this.child_runs.push(a),a}async end(t,n,a=Date.now(),r){this.outputs=this.outputs??t,this.error=this.error??n,this.end_time=this.end_time??a,r&&Object.keys(r).length>0&&(this.extra=this.extra?{...this.extra,metadata:{...this.extra.metadata,...r}}:{metadata:r})}_convertToCreate(t,n,a=!0){const r=t.extra??{};if(r?.runtime?.library===void 0&&(r.runtime||(r.runtime={}),n))for(const[o,c]of Object.entries(n))r.runtime[o]||(r.runtime[o]=c);let i,s;return a?(s=t.parent_run?.id??t.parent_run_id,i=[]):(i=t.child_runs.map(o=>this._convertToCreate(o,n,a)),s=void 0),{id:t.id,name:t.name,start_time:t._serialized_start_time??t.start_time,end_time:t.end_time,run_type:t.run_type,reference_example_id:t.reference_example_id,extra:r,serialized:t.serialized,error:t.error,inputs:t.inputs,outputs:t.outputs,session_name:t.project_name,child_runs:i,parent_run_id:s,trace_id:t.trace_id,dotted_order:t.dotted_order,tags:t.tags,attachments:t.attachments,events:t.events}}_remapForProject(t,n,a=!0){const r=this._convertToCreate(this,n,a);if(t===this.project_name)return r;const i=h=>Sn(`${h}:${t}`,Sn.DNS),s=i(r.id),o=r.trace_id?i(r.trace_id):void 0,c=r.parent_run_id?i(r.parent_run_id):void 0;let l;if(r.dotted_order){const h=So(r.dotted_order),d=[];for(let f=0;f<h.length-1;f++){const[A,y]=h[f],g=i(y);d.push(A.toISOString().replace(/[-:]/g,"").replace(".","")+g)}const[p]=h[h.length-1];d.push(p.toISOString().replace(/[-:]/g,"").replace(".","")+s),l=d.join(".")}else l=void 0;return{...r,id:s,trace_id:o,parent_run_id:c,dotted_order:l,session_name:t}}async postRun(t=!0){try{const n=Qa();if(this.replicas&&this.replicas.length>0)for(const{projectName:a,apiKey:r,apiUrl:i,workspaceId:s}of this.replicas){const o=this._remapForProject(a??this.project_name,n,!0);await this.client.createRun(o,{apiKey:r,apiUrl:i,workspaceId:s})}else{const a=this._convertToCreate(this,n,t);await this.client.createRun(a)}if(!t){qt("Posting with excludeChildRuns=false is deprecated and will be removed in a future version.");for(const a of this.child_runs)await a.postRun(!1)}}catch(n){console.error(`Error in postRun for run ${this.id}:`,n)}}async patchRun(t){if(this.replicas&&this.replicas.length>0)for(const{projectName:n,apiKey:a,apiUrl:r,workspaceId:i,updates:s}of this.replicas){const o=this._remapForProject(n??this.project_name),c={id:o.id,outputs:o.outputs,error:o.error,parent_run_id:o.parent_run_id,session_name:o.session_name,reference_example_id:o.reference_example_id,end_time:o.end_time,dotted_order:o.dotted_order,trace_id:o.trace_id,events:o.events,tags:o.tags,extra:o.extra,attachments:this.attachments,...s};t?.excludeInputs||(c.inputs=o.inputs),await this.client.updateRun(o.id,c,{apiKey:a,apiUrl:r,workspaceId:i})}else try{const n={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};t?.excludeInputs||(n.inputs=this.inputs),await this.client.updateRun(this.id,n)}catch(n){console.error(`Error in patchRun for run ${this.id}`,n)}}toJSON(){return this._convertToCreate(this,void 0,!1)}addEvent(t){this.events||(this.events=[]),typeof t=="string"?this.events.push({name:"event",time:new Date().toISOString(),message:t}):this.events.push({...t,time:t.time??new Date().toISOString()})}static fromRunnableConfig(t,n){const a=t?.callbacks;let r,i,s,o=_o();if(a){const l=a?.getParentRunId?.()??"",u=a?.handlers?.find(h=>h?.name=="langchain_tracer");r=u?.getRun?.(l),i=u?.projectName,s=u?.client,o=o||!!u}return r?new q({name:r.name,id:r.id,trace_id:r.trace_id,dotted_order:r.dotted_order,client:s,tracingEnabled:o,project_name:i,tags:[...new Set((r?.tags??[]).concat(t?.tags??[]))],extra:{metadata:{...r?.extra?.metadata,...t?.metadata}}}).createChild(n):new q({...n,client:s,tracingEnabled:o,project_name:i})}static fromDottedOrder(t){return this.fromHeaders({"langsmith-trace":t})}static fromHeaders(t,n){const a="get"in t&&typeof t.get=="function"?{"langsmith-trace":t.get("langsmith-trace"),baggage:t.get("baggage")}:t,r=a["langsmith-trace"];if(!r||typeof r!="string")return;const i=r.trim(),s=i.split(".").map(l=>{const[u,h]=l.split("Z");return{strTime:u,time:Date.parse(u+"Z"),uuid:h}}),o=s[0].uuid,c={...n,name:n?.name??"parent",run_type:n?.run_type??"chain",start_time:n?.start_time??Date.now(),id:s.at(-1)?.uuid,trace_id:o,dotted_order:i};if(a.baggage&&typeof a.baggage=="string"){const l=ht.fromHeader(a.baggage);c.metadata=l.metadata,c.tags=l.tags,c.project_name=l.project_name,c.replicas=l.replicas}return new q(c)}toHeaders(t){const n={"langsmith-trace":this.dotted_order,baggage:new ht(this.extra?.metadata,this.tags,this.project_name,this.replicas).toHeader()};if(t)for(const[a,r]of Object.entries(n))t.set(a,r);return n}}Object.defineProperty(q,"sharedClient",{enumerable:!0,configurable:!0,writable:!0,value:null});function wo(e){return e!=null&&typeof e.createChild=="function"&&typeof e.postRun=="function"}function rr(e){return typeof e=="object"&&e!=null&&typeof e.name=="string"&&e.name==="langchain_tracer"}function qn(e){return Array.isArray(e)&&e.some(t=>rr(t))}function vo(e){return typeof e=="object"&&e!=null&&Array.isArray(e.handlers)}function bo(e){return e!=null&&typeof e.callbacks=="object"&&(qn(e.callbacks?.handlers)||qn(e.callbacks))}function So(e){return e.split(".").map(n=>{const a=n.slice(0,-36),r=n.slice(-36),i=parseInt(a.slice(0,4)),s=parseInt(a.slice(4,6))-1,o=parseInt(a.slice(6,8)),c=parseInt(a.slice(9,11)),l=parseInt(a.slice(11,13)),u=parseInt(a.slice(13,15)),h=parseInt(a.slice(15,21));return[new Date(i,s,o,c,l,u,h/1e3),r]})}function Eo(){const e=oe("LANGSMITH_RUNS_ENDPOINTS");if(!e)return[];try{const t=JSON.parse(e);if(Array.isArray(t)){const n=[];for(const a of t){if(typeof a!="object"||a===null){console.warn(`Invalid item type in LANGSMITH_RUNS_ENDPOINTS: expected object, got ${typeof a}`);continue}if(typeof a.api_url!="string"){console.warn(`Invalid api_url type in LANGSMITH_RUNS_ENDPOINTS: expected string, got ${typeof a.api_url}`);continue}if(typeof a.api_key!="string"){console.warn(`Invalid api_key type in LANGSMITH_RUNS_ENDPOINTS: expected string, got ${typeof a.api_key}`);continue}n.push({apiUrl:a.api_url.replace(/\/$/,""),apiKey:a.api_key})}return n}else if(typeof t=="object"&&t!==null){Ao(t);const n=[];for(const[a,r]of Object.entries(t)){const i=a.replace(/\/$/,"");if(typeof r=="string")n.push({apiUrl:i,apiKey:r});else{console.warn(`Invalid value type in LANGSMITH_RUNS_ENDPOINTS for URL ${a}: expected string, got ${typeof r}`);continue}}return n}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 t}`),[]}catch(t){if(no(t))throw t;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 To(e){return e?e.map(t=>Array.isArray(t)?{projectName:t[0],updates:t[1]}:t):Eo()}function Ao(e){if(Object.keys(e).length>0&&J("ENDPOINT"))throw new to}var Io={};D(Io,{BaseTracer:()=>De,isBaseTracer:()=>xe});const Oo=e=>{if(e)return e.events=e.events??[],e.child_runs=e.child_runs??[],e};function Vt(e,t){if(e)return new q({...e,start_time:e._serialized_start_time??e.start_time,parent_run:Vt(t),child_runs:e.child_runs.map(n=>Vt(n)).filter(n=>n!==void 0),extra:{...e.extra,runtime:Ga()},tracingEnabled:!1})}function Lt(e,t){return e&&!Array.isArray(e)&&typeof e=="object"?e:{[t]:e}}function xe(e){return typeof e._addRunToRunMap=="function"}var De=class extends Xe{runMap=new Map;runTreeMap=new Map;usesRunTreeMap=!1;constructor(e){super(...arguments)}copy(){return this}getRunById(e){if(e!==void 0)return this.usesRunTreeMap?Oo(this.runTreeMap.get(e)):this.runMap.get(e)}stringifyError(e){return e instanceof Error?e.message+(e?.stack?`
|
|
50
|
-
|
|
51
|
-
${e.stack}`:""):typeof e=="string"?e:`${e}`}_addChildRun(e,t){e.child_runs.push(t)}_addRunToRunMap(e){const{dottedOrder:t,microsecondPrecisionDatestring:n}=ar(new Date(e.start_time).getTime(),e.id,e.execution_order),a={...e},r=this.getRunById(a.parent_run_id);if(a.parent_run_id!==void 0?r&&(this._addChildRun(r,a),r.child_execution_order=Math.max(r.child_execution_order,a.child_execution_order),a.trace_id=r.trace_id,r.dotted_order!==void 0&&(a.dotted_order=[r.dotted_order,t].join("."),a._serialized_start_time=n)):(a.trace_id=a.id,a.dotted_order=t,a._serialized_start_time=n),this.usesRunTreeMap){const i=Vt(a,r);i!==void 0&&this.runTreeMap.set(a.id,i)}else this.runMap.set(a.id,a);return a}async _endTrace(e){const t=e.parent_run_id!==void 0&&this.getRunById(e.parent_run_id);t?t.child_execution_order=Math.max(t.child_execution_order,e.child_execution_order):await this.persistRun(e),await this.onRunUpdate?.(e),this.usesRunTreeMap?this.runTreeMap.delete(e.id):this.runMap.delete(e.id)}_getExecutionOrder(e){const t=e!==void 0&&this.getRunById(e);return t?t.child_execution_order+1:1}_createRunForLLMStart(e,t,n,a,r,i,s,o){const c=this._getExecutionOrder(a),l=Date.now(),u=s?{...r,metadata:s}:r,h={id:n,name:o??e.id[e.id.length-1],parent_run_id:a,start_time:l,serialized:e,events:[{name:"start",time:new Date(l).toISOString()}],inputs:{prompts:t},execution_order:c,child_runs:[],child_execution_order:c,run_type:"llm",extra:u??{},tags:i||[]};return this._addRunToRunMap(h)}async handleLLMStart(e,t,n,a,r,i,s,o){const c=this.getRunById(n)??this._createRunForLLMStart(e,t,n,a,r,i,s,o);return await this.onRunCreate?.(c),await this.onLLMStart?.(c),c}_createRunForChatModelStart(e,t,n,a,r,i,s,o){const c=this._getExecutionOrder(a),l=Date.now(),u=s?{...r,metadata:s}:r,h={id:n,name:o??e.id[e.id.length-1],parent_run_id:a,start_time:l,serialized:e,events:[{name:"start",time:new Date(l).toISOString()}],inputs:{messages:t},execution_order:c,child_runs:[],child_execution_order:c,run_type:"llm",extra:u??{},tags:i||[]};return this._addRunToRunMap(h)}async handleChatModelStart(e,t,n,a,r,i,s,o){const c=this.getRunById(n)??this._createRunForChatModelStart(e,t,n,a,r,i,s,o);return await this.onRunCreate?.(c),await this.onLLMStart?.(c),c}async handleLLMEnd(e,t,n,a,r){const i=this.getRunById(t);if(!i||i?.run_type!=="llm")throw new Error("No LLM run to end.");return i.end_time=Date.now(),i.outputs=e,i.events.push({name:"end",time:new Date(i.end_time).toISOString()}),i.extra={...i.extra,...r},await this.onLLMEnd?.(i),await this._endTrace(i),i}async handleLLMError(e,t,n,a,r){const i=this.getRunById(t);if(!i||i?.run_type!=="llm")throw new Error("No LLM run to end.");return i.end_time=Date.now(),i.error=this.stringifyError(e),i.events.push({name:"error",time:new Date(i.end_time).toISOString()}),i.extra={...i.extra,...r},await this.onLLMError?.(i),await this._endTrace(i),i}_createRunForChainStart(e,t,n,a,r,i,s,o){const c=this._getExecutionOrder(a),l=Date.now(),u={id:n,name:o??e.id[e.id.length-1],parent_run_id:a,start_time:l,serialized:e,events:[{name:"start",time:new Date(l).toISOString()}],inputs:t,execution_order:c,child_execution_order:c,run_type:s??"chain",child_runs:[],extra:i?{metadata:i}:{},tags:r||[]};return this._addRunToRunMap(u)}async handleChainStart(e,t,n,a,r,i,s,o){const c=this.getRunById(n)??this._createRunForChainStart(e,t,n,a,r,i,s,o);return await this.onRunCreate?.(c),await this.onChainStart?.(c),c}async handleChainEnd(e,t,n,a,r){const i=this.getRunById(t);if(!i)throw new Error("No chain run to end.");return i.end_time=Date.now(),i.outputs=Lt(e,"output"),i.events.push({name:"end",time:new Date(i.end_time).toISOString()}),r?.inputs!==void 0&&(i.inputs=Lt(r.inputs,"input")),await this.onChainEnd?.(i),await this._endTrace(i),i}async handleChainError(e,t,n,a,r){const i=this.getRunById(t);if(!i)throw new Error("No chain run to end.");return i.end_time=Date.now(),i.error=this.stringifyError(e),i.events.push({name:"error",time:new Date(i.end_time).toISOString()}),r?.inputs!==void 0&&(i.inputs=Lt(r.inputs,"input")),await this.onChainError?.(i),await this._endTrace(i),i}_createRunForToolStart(e,t,n,a,r,i,s){const o=this._getExecutionOrder(a),c=Date.now(),l={id:n,name:s??e.id[e.id.length-1],parent_run_id:a,start_time:c,serialized:e,events:[{name:"start",time:new Date(c).toISOString()}],inputs:{input:t},execution_order:o,child_execution_order:o,run_type:"tool",child_runs:[],extra:i?{metadata:i}:{},tags:r||[]};return this._addRunToRunMap(l)}async handleToolStart(e,t,n,a,r,i,s){const o=this.getRunById(n)??this._createRunForToolStart(e,t,n,a,r,i,s);return await this.onRunCreate?.(o),await this.onToolStart?.(o),o}async handleToolEnd(e,t){const n=this.getRunById(t);if(!n||n?.run_type!=="tool")throw new Error("No tool run to end");return n.end_time=Date.now(),n.outputs={output:e},n.events.push({name:"end",time:new Date(n.end_time).toISOString()}),await this.onToolEnd?.(n),await this._endTrace(n),n}async handleToolError(e,t){const n=this.getRunById(t);if(!n||n?.run_type!=="tool")throw new Error("No tool run to end");return n.end_time=Date.now(),n.error=this.stringifyError(e),n.events.push({name:"error",time:new Date(n.end_time).toISOString()}),await this.onToolError?.(n),await this._endTrace(n),n}async handleAgentAction(e,t){const n=this.getRunById(t);if(!n||n?.run_type!=="chain")return;const a=n;a.actions=a.actions||[],a.actions.push(e),a.events.push({name:"agent_action",time:new Date().toISOString(),kwargs:{action:e}}),await this.onAgentAction?.(n)}async handleAgentEnd(e,t){const n=this.getRunById(t);!n||n?.run_type!=="chain"||(n.events.push({name:"agent_end",time:new Date().toISOString(),kwargs:{action:e}}),await this.onAgentEnd?.(n))}_createRunForRetrieverStart(e,t,n,a,r,i,s){const o=this._getExecutionOrder(a),c=Date.now(),l={id:n,name:s??e.id[e.id.length-1],parent_run_id:a,start_time:c,serialized:e,events:[{name:"start",time:new Date(c).toISOString()}],inputs:{query:t},execution_order:o,child_execution_order:o,run_type:"retriever",child_runs:[],extra:i?{metadata:i}:{},tags:r||[]};return this._addRunToRunMap(l)}async handleRetrieverStart(e,t,n,a,r,i,s){const o=this.getRunById(n)??this._createRunForRetrieverStart(e,t,n,a,r,i,s);return await this.onRunCreate?.(o),await this.onRetrieverStart?.(o),o}async handleRetrieverEnd(e,t){const n=this.getRunById(t);if(!n||n?.run_type!=="retriever")throw new Error("No retriever run to end");return n.end_time=Date.now(),n.outputs={documents:e},n.events.push({name:"end",time:new Date(n.end_time).toISOString()}),await this.onRetrieverEnd?.(n),await this._endTrace(n),n}async handleRetrieverError(e,t){const n=this.getRunById(t);if(!n||n?.run_type!=="retriever")throw new Error("No retriever run to end");return n.end_time=Date.now(),n.error=this.stringifyError(e),n.events.push({name:"error",time:new Date(n.end_time).toISOString()}),await this.onRetrieverError?.(n),await this._endTrace(n),n}async handleText(e,t){const n=this.getRunById(t);!n||n?.run_type!=="chain"||(n.events.push({name:"text",time:new Date().toISOString(),kwargs:{text:e}}),await this.onText?.(n))}async handleLLMNewToken(e,t,n,a,r,i){const s=this.getRunById(n);if(!s||s?.run_type!=="llm")throw new Error('Invalid "runId" provided to "handleLLMNewToken" callback.');return s.events.push({name:"new_token",time:new Date().toISOString(),kwargs:{token:e,idx:t,chunk:i?.chunk}}),await this.onLLMNewToken?.(s,e,{chunk:i?.chunk}),s}},Co={};D(Co,{ConsoleCallbackHandler:()=>Wt});function z(e,t){return`${e.open}${t}${e.close}`}function X(e,t){try{return JSON.stringify(e,null,2)}catch{return t}}function Jn(e){return typeof e=="string"?e.trim():e==null?e:X(e,e.toString())}function me(e){if(!e.end_time)return"";const t=e.end_time-e.start_time;return t<1e3?`${t}ms`:`${(t/1e3).toFixed(2)}s`}const{color:Z}=ha;var Wt=class extends De{name="console_callback_handler";persistRun(e){return Promise.resolve()}getParents(e){const t=[];let n=e;for(;n.parent_run_id;){const a=this.runMap.get(n.parent_run_id);if(a)t.push(a),n=a;else break}return t}getBreadcrumbs(e){const n=[...this.getParents(e).reverse(),e].map((a,r,i)=>{const s=`${a.execution_order}:${a.run_type}:${a.name}`;return r===i.length-1?z(ha.bold,s):s}).join(" > ");return z(Z.grey,n)}onChainStart(e){const t=this.getBreadcrumbs(e);console.log(`${z(Z.green,"[chain/start]")} [${t}] Entering Chain run with input: ${X(e.inputs,"[inputs]")}`)}onChainEnd(e){const t=this.getBreadcrumbs(e);console.log(`${z(Z.cyan,"[chain/end]")} [${t}] [${me(e)}] Exiting Chain run with output: ${X(e.outputs,"[outputs]")}`)}onChainError(e){const t=this.getBreadcrumbs(e);console.log(`${z(Z.red,"[chain/error]")} [${t}] [${me(e)}] Chain run errored with error: ${X(e.error,"[error]")}`)}onLLMStart(e){const t=this.getBreadcrumbs(e),n="prompts"in e.inputs?{prompts:e.inputs.prompts.map(a=>a.trim())}:e.inputs;console.log(`${z(Z.green,"[llm/start]")} [${t}] Entering LLM run with input: ${X(n,"[inputs]")}`)}onLLMEnd(e){const t=this.getBreadcrumbs(e);console.log(`${z(Z.cyan,"[llm/end]")} [${t}] [${me(e)}] Exiting LLM run with output: ${X(e.outputs,"[response]")}`)}onLLMError(e){const t=this.getBreadcrumbs(e);console.log(`${z(Z.red,"[llm/error]")} [${t}] [${me(e)}] LLM run errored with error: ${X(e.error,"[error]")}`)}onToolStart(e){const t=this.getBreadcrumbs(e);console.log(`${z(Z.green,"[tool/start]")} [${t}] Entering Tool run with input: "${Jn(e.inputs.input)}"`)}onToolEnd(e){const t=this.getBreadcrumbs(e);console.log(`${z(Z.cyan,"[tool/end]")} [${t}] [${me(e)}] Exiting Tool run with output: "${Jn(e.outputs?.output)}"`)}onToolError(e){const t=this.getBreadcrumbs(e);console.log(`${z(Z.red,"[tool/error]")} [${t}] [${me(e)}] Tool run errored with error: ${X(e.error,"[error]")}`)}onRetrieverStart(e){const t=this.getBreadcrumbs(e);console.log(`${z(Z.green,"[retriever/start]")} [${t}] Entering Retriever run with input: ${X(e.inputs,"[inputs]")}`)}onRetrieverEnd(e){const t=this.getBreadcrumbs(e);console.log(`${z(Z.cyan,"[retriever/end]")} [${t}] [${me(e)}] Exiting Retriever run with output: ${X(e.outputs,"[outputs]")}`)}onRetrieverError(e){const t=this.getBreadcrumbs(e);console.log(`${z(Z.red,"[retriever/error]")} [${t}] [${me(e)}] Retriever run errored with error: ${X(e.error,"[error]")}`)}onAgentAction(e){const t=e,n=this.getBreadcrumbs(e);console.log(`${z(Z.blue,"[agent/action]")} [${n}] Agent selected action: ${X(t.actions[t.actions.length-1],"[action]")}`)}};let jt;const ir=()=>{if(jt===void 0){const e=ve("LANGCHAIN_CALLBACKS_BACKGROUND")==="false"?{blockOnRootRunFinalization:!0}:{};jt=new Je(e)}return jt};let xo=class{getStore(){}run(t,n){return n()}};const Dt=Symbol.for("ls:tracing_async_local_storage"),ko=new xo;let Ro=class{getInstance(){return globalThis[Dt]??ko}initializeGlobalInstance(t){globalThis[Dt]===void 0&&(globalThis[Dt]=t)}};const No=new Ro;function Po(e=!1){const t=No.getInstance().getStore();if(!e&&t===void 0)throw new Error(`Could not get the current run tree.
|
|
52
|
-
|
|
53
|
-
Please make sure you are calling this method within a traceable function and that tracing is enabled.`);return t}function fn(e){return typeof e=="function"&&"langsmith:traceable"in e}var $o={};D($o,{LangChainTracer:()=>ot});var ot=class sr extends De{name="langchain_tracer";projectName;exampleId;client;replicas;usesRunTreeMap=!0;constructor(t={}){super(t);const{exampleId:n,projectName:a,client:r,replicas:i}=t;this.projectName=a??Ja(),this.replicas=i,this.exampleId=n,this.client=r??ir();const s=sr.getTraceableRunTree();s&&this.updateFromRunTree(s)}async persistRun(t){}async onRunCreate(t){await this.getRunTreeWithTracingConfig(t.id)?.postRun()}async onRunUpdate(t){await this.getRunTreeWithTracingConfig(t.id)?.patchRun()}getRun(t){return this.runTreeMap.get(t)}updateFromRunTree(t){this.runTreeMap.set(t.id,t);let n=t;const a=new Set;for(;n.parent_run&&!(a.has(n.id)||(a.add(n.id),!n.parent_run));)n=n.parent_run;a.clear();const r=[n];for(;r.length>0;){const i=r.shift();!i||a.has(i.id)||(a.add(i.id),this.runTreeMap.set(i.id,i),i.child_runs&&r.push(...i.child_runs))}this.client=t.client??this.client,this.replicas=t.replicas??this.replicas,this.projectName=t.project_name??this.projectName,this.exampleId=t.reference_example_id??this.exampleId}getRunTreeWithTracingConfig(t){const n=this.runTreeMap.get(t);if(n)return new q({...n,client:this.client,project_name:this.projectName,replicas:this.replicas,reference_example_id:this.exampleId,tracingEnabled:!0})}static getTraceableRunTree(){try{return Po(!0)}catch{return}}};let be;function Mo(){const e="default"in ue?ue.default:ue;return new e({autoStart:!0,concurrency:1})}function Lo(){return typeof be>"u"&&(be=Mo()),be}async function M(e,t){if(t===!0){const n=qe();n!==void 0?await n.run(void 0,async()=>e()):await e()}else be=Lo(),be.add(async()=>{const n=qe();n!==void 0?await n.run(void 0,async()=>e()):await e()})}async function jo(){const e=ir();await Promise.allSettled([typeof be<"u"?be.onIdle():Promise.resolve(),e.awaitPendingTraceBatches()])}var Do={};D(Do,{awaitAllCallbacks:()=>jo,consumeCallback:()=>M});const Uo=e=>!!["LANGSMITH_TRACING_V2","LANGCHAIN_TRACING_V2","LANGSMITH_TRACING","LANGCHAIN_TRACING"].find(n=>ve(n)==="true");function or(e){const t=qe();return t===void 0?void 0:t.getStore()?.[He]?.[e]}const Fo=Symbol("lc:configure_hooks"),Bo=()=>or(Fo)||[];var zo={};D(zo,{BaseCallbackManager:()=>cr,BaseRunManager:()=>et,CallbackManager:()=>Oe,CallbackManagerForChainRun:()=>ur,CallbackManagerForLLMRun:()=>Kt,CallbackManagerForRetrieverRun:()=>lr,CallbackManagerForToolRun:()=>dr,ensureHandler:()=>Ve,parseCallbackConfigArg:()=>Ho});function Ho(e){return e?Array.isArray(e)||"name"in e?{callbacks:e}:e:{}}var cr=class{setHandler(e){return this.setHandlers([e])}},et=class{constructor(e,t,n,a,r,i,s,o){this.runId=e,this.handlers=t,this.inheritableHandlers=n,this.tags=a,this.inheritableTags=r,this.metadata=i,this.inheritableMetadata=s,this._parentRunId=o}get parentRunId(){return this._parentRunId}async handleText(e){await Promise.all(this.handlers.map(t=>M(async()=>{try{await t.handleText?.(e,this.runId,this._parentRunId,this.tags)}catch(n){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleText: ${n}`),t.raiseError)throw n}},t.awaitHandlers)))}async handleCustomEvent(e,t,n,a,r){await Promise.all(this.handlers.map(i=>M(async()=>{try{await i.handleCustomEvent?.(e,t,this.runId,this.tags,this.metadata)}catch(s){if((i.raiseError?console.error:console.warn)(`Error in handler ${i.constructor.name}, handleCustomEvent: ${s}`),i.raiseError)throw s}},i.awaitHandlers)))}},lr=class extends et{getChild(e){const t=new Oe(this.runId);return t.setHandlers(this.inheritableHandlers),t.addTags(this.inheritableTags),t.addMetadata(this.inheritableMetadata),e&&t.addTags([e],!1),t}async handleRetrieverEnd(e){await Promise.all(this.handlers.map(t=>M(async()=>{if(!t.ignoreRetriever)try{await t.handleRetrieverEnd?.(e,this.runId,this._parentRunId,this.tags)}catch(n){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleRetriever`),t.raiseError)throw n}},t.awaitHandlers)))}async handleRetrieverError(e){await Promise.all(this.handlers.map(t=>M(async()=>{if(!t.ignoreRetriever)try{await t.handleRetrieverError?.(e,this.runId,this._parentRunId,this.tags)}catch(n){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleRetrieverError: ${n}`),t.raiseError)throw e}},t.awaitHandlers)))}},Kt=class extends et{async handleLLMNewToken(e,t,n,a,r,i){await Promise.all(this.handlers.map(s=>M(async()=>{if(!s.ignoreLLM)try{await s.handleLLMNewToken?.(e,t??{prompt:0,completion:0},this.runId,this._parentRunId,this.tags,i)}catch(o){if((s.raiseError?console.error:console.warn)(`Error in handler ${s.constructor.name}, handleLLMNewToken: ${o}`),s.raiseError)throw o}},s.awaitHandlers)))}async handleLLMError(e,t,n,a,r){await Promise.all(this.handlers.map(i=>M(async()=>{if(!i.ignoreLLM)try{await i.handleLLMError?.(e,this.runId,this._parentRunId,this.tags,r)}catch(s){if((i.raiseError?console.error:console.warn)(`Error in handler ${i.constructor.name}, handleLLMError: ${s}`),i.raiseError)throw s}},i.awaitHandlers)))}async handleLLMEnd(e,t,n,a,r){await Promise.all(this.handlers.map(i=>M(async()=>{if(!i.ignoreLLM)try{await i.handleLLMEnd?.(e,this.runId,this._parentRunId,this.tags,r)}catch(s){if((i.raiseError?console.error:console.warn)(`Error in handler ${i.constructor.name}, handleLLMEnd: ${s}`),i.raiseError)throw s}},i.awaitHandlers)))}},ur=class extends et{getChild(e){const t=new Oe(this.runId);return t.setHandlers(this.inheritableHandlers),t.addTags(this.inheritableTags),t.addMetadata(this.inheritableMetadata),e&&t.addTags([e],!1),t}async handleChainError(e,t,n,a,r){await Promise.all(this.handlers.map(i=>M(async()=>{if(!i.ignoreChain)try{await i.handleChainError?.(e,this.runId,this._parentRunId,this.tags,r)}catch(s){if((i.raiseError?console.error:console.warn)(`Error in handler ${i.constructor.name}, handleChainError: ${s}`),i.raiseError)throw s}},i.awaitHandlers)))}async handleChainEnd(e,t,n,a,r){await Promise.all(this.handlers.map(i=>M(async()=>{if(!i.ignoreChain)try{await i.handleChainEnd?.(e,this.runId,this._parentRunId,this.tags,r)}catch(s){if((i.raiseError?console.error:console.warn)(`Error in handler ${i.constructor.name}, handleChainEnd: ${s}`),i.raiseError)throw s}},i.awaitHandlers)))}async handleAgentAction(e){await Promise.all(this.handlers.map(t=>M(async()=>{if(!t.ignoreAgent)try{await t.handleAgentAction?.(e,this.runId,this._parentRunId,this.tags)}catch(n){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleAgentAction: ${n}`),t.raiseError)throw n}},t.awaitHandlers)))}async handleAgentEnd(e){await Promise.all(this.handlers.map(t=>M(async()=>{if(!t.ignoreAgent)try{await t.handleAgentEnd?.(e,this.runId,this._parentRunId,this.tags)}catch(n){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleAgentEnd: ${n}`),t.raiseError)throw n}},t.awaitHandlers)))}},dr=class extends et{getChild(e){const t=new Oe(this.runId);return t.setHandlers(this.inheritableHandlers),t.addTags(this.inheritableTags),t.addMetadata(this.inheritableMetadata),e&&t.addTags([e],!1),t}async handleToolError(e){await Promise.all(this.handlers.map(t=>M(async()=>{if(!t.ignoreAgent)try{await t.handleToolError?.(e,this.runId,this._parentRunId,this.tags)}catch(n){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleToolError: ${n}`),t.raiseError)throw n}},t.awaitHandlers)))}async handleToolEnd(e){await Promise.all(this.handlers.map(t=>M(async()=>{if(!t.ignoreAgent)try{await t.handleToolEnd?.(e,this.runId,this._parentRunId,this.tags)}catch(n){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleToolEnd: ${n}`),t.raiseError)throw n}},t.awaitHandlers)))}},Oe=class Fe extends cr{handlers=[];inheritableHandlers=[];tags=[];inheritableTags=[];metadata={};inheritableMetadata={};name="callback_manager";_parentRunId;constructor(t,n){super(),this.handlers=n?.handlers??this.handlers,this.inheritableHandlers=n?.inheritableHandlers??this.inheritableHandlers,this.tags=n?.tags??this.tags,this.inheritableTags=n?.inheritableTags??this.inheritableTags,this.metadata=n?.metadata??this.metadata,this.inheritableMetadata=n?.inheritableMetadata??this.inheritableMetadata,this._parentRunId=t}getParentRunId(){return this._parentRunId}async handleLLMStart(t,n,a=void 0,r=void 0,i=void 0,s=void 0,o=void 0,c=void 0){return Promise.all(n.map(async(l,u)=>{const h=u===0&&a?a:G();return await Promise.all(this.handlers.map(d=>{if(!d.ignoreLLM)return xe(d)&&d._createRunForLLMStart(t,[l],h,this._parentRunId,i,this.tags,this.metadata,c),M(async()=>{try{await d.handleLLMStart?.(t,[l],h,this._parentRunId,i,this.tags,this.metadata,c)}catch(p){if((d.raiseError?console.error:console.warn)(`Error in handler ${d.constructor.name}, handleLLMStart: ${p}`),d.raiseError)throw p}},d.awaitHandlers)})),new Kt(h,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChatModelStart(t,n,a=void 0,r=void 0,i=void 0,s=void 0,o=void 0,c=void 0){return Promise.all(n.map(async(l,u)=>{const h=u===0&&a?a:G();return await Promise.all(this.handlers.map(d=>{if(!d.ignoreLLM)return xe(d)&&d._createRunForChatModelStart(t,[l],h,this._parentRunId,i,this.tags,this.metadata,c),M(async()=>{try{if(d.handleChatModelStart)await d.handleChatModelStart?.(t,[l],h,this._parentRunId,i,this.tags,this.metadata,c);else if(d.handleLLMStart){const p=La(l);await d.handleLLMStart?.(t,[p],h,this._parentRunId,i,this.tags,this.metadata,c)}}catch(p){if((d.raiseError?console.error:console.warn)(`Error in handler ${d.constructor.name}, handleLLMStart: ${p}`),d.raiseError)throw p}},d.awaitHandlers)})),new Kt(h,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChainStart(t,n,a=G(),r=void 0,i=void 0,s=void 0,o=void 0){return await Promise.all(this.handlers.map(c=>{if(!c.ignoreChain)return xe(c)&&c._createRunForChainStart(t,n,a,this._parentRunId,this.tags,this.metadata,r,o),M(async()=>{try{await c.handleChainStart?.(t,n,a,this._parentRunId,this.tags,this.metadata,r,o)}catch(l){if((c.raiseError?console.error:console.warn)(`Error in handler ${c.constructor.name}, handleChainStart: ${l}`),c.raiseError)throw l}},c.awaitHandlers)})),new ur(a,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleToolStart(t,n,a=G(),r=void 0,i=void 0,s=void 0,o=void 0){return await Promise.all(this.handlers.map(c=>{if(!c.ignoreAgent)return xe(c)&&c._createRunForToolStart(t,n,a,this._parentRunId,this.tags,this.metadata,o),M(async()=>{try{await c.handleToolStart?.(t,n,a,this._parentRunId,this.tags,this.metadata,o)}catch(l){if((c.raiseError?console.error:console.warn)(`Error in handler ${c.constructor.name}, handleToolStart: ${l}`),c.raiseError)throw l}},c.awaitHandlers)})),new dr(a,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleRetrieverStart(t,n,a=G(),r=void 0,i=void 0,s=void 0,o=void 0){return await Promise.all(this.handlers.map(c=>{if(!c.ignoreRetriever)return xe(c)&&c._createRunForRetrieverStart(t,n,a,this._parentRunId,this.tags,this.metadata,o),M(async()=>{try{await c.handleRetrieverStart?.(t,n,a,this._parentRunId,this.tags,this.metadata,o)}catch(l){if((c.raiseError?console.error:console.warn)(`Error in handler ${c.constructor.name}, handleRetrieverStart: ${l}`),c.raiseError)throw l}},c.awaitHandlers)})),new lr(a,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleCustomEvent(t,n,a,r,i){await Promise.all(this.handlers.map(s=>M(async()=>{if(!s.ignoreCustomEvent)try{await s.handleCustomEvent?.(t,n,a,this.tags,this.metadata)}catch(o){if((s.raiseError?console.error:console.warn)(`Error in handler ${s.constructor.name}, handleCustomEvent: ${o}`),s.raiseError)throw o}},s.awaitHandlers)))}addHandler(t,n=!0){this.handlers.push(t),n&&this.inheritableHandlers.push(t)}removeHandler(t){this.handlers=this.handlers.filter(n=>n!==t),this.inheritableHandlers=this.inheritableHandlers.filter(n=>n!==t)}setHandlers(t,n=!0){this.handlers=[],this.inheritableHandlers=[];for(const a of t)this.addHandler(a,n)}addTags(t,n=!0){this.removeTags(t),this.tags.push(...t),n&&this.inheritableTags.push(...t)}removeTags(t){this.tags=this.tags.filter(n=>!t.includes(n)),this.inheritableTags=this.inheritableTags.filter(n=>!t.includes(n))}addMetadata(t,n=!0){this.metadata={...this.metadata,...t},n&&(this.inheritableMetadata={...this.inheritableMetadata,...t})}removeMetadata(t){for(const n of Object.keys(t))delete this.metadata[n],delete this.inheritableMetadata[n]}copy(t=[],n=!0){const a=new Fe(this._parentRunId);for(const r of this.handlers){const i=this.inheritableHandlers.includes(r);a.addHandler(r,i)}for(const r of this.tags){const i=this.inheritableTags.includes(r);a.addTags([r],i)}for(const r of Object.keys(this.metadata)){const i=Object.keys(this.inheritableMetadata).includes(r);a.addMetadata({[r]:this.metadata[r]},i)}for(const r of t)a.handlers.filter(i=>i.name==="console_callback_handler").some(i=>i.name===r.name)||a.addHandler(r,n);return a}static fromHandlers(t){class n extends Xe{name=G();constructor(){super(),Object.assign(this,t)}}const a=new this;return a.addHandler(new n),a}static configure(t,n,a,r,i,s,o){return this._configureSync(t,n,a,r,i,s,o)}static _configureSync(t,n,a,r,i,s,o){let c;(t||n)&&(Array.isArray(t)||!t?(c=new Fe,c.setHandlers(t?.map(Ve)??[],!0)):c=t,c=c.copy(Array.isArray(n)?n.map(Ve):n?.handlers,!1));const l=ve("LANGCHAIN_VERBOSE")==="true"||o?.verbose,u=ot.getTraceableRunTree()?.tracingEnabled||Uo(),h=u||(ve("LANGCHAIN_TRACING")??!1);if(l||h){if(c||(c=new Fe),l&&!c.handlers.some(d=>d.name===Wt.prototype.name)){const d=new Wt;c.addHandler(d,!0)}if(h&&!c.handlers.some(d=>d.name==="langchain_tracer")&&u){const d=new ot;c.addHandler(d,!0)}if(u){const d=ot.getTraceableRunTree();d&&c._parentRunId===void 0&&(c._parentRunId=d.id,c.handlers.find(f=>f.name==="langchain_tracer")?.updateFromRunTree(d))}}for(const{contextVar:d,inheritable:p=!0,handlerClass:f,envVar:A}of Bo()){const y=A&&ve(A)==="true"&&f;let g;const v=d!==void 0?or(d):void 0;v&&Za(v)?g=v:y&&(g=new f({})),g!==void 0&&(c||(c=new Fe),c.handlers.some(E=>E.name===g.name)||c.addHandler(g,p))}return(a||r)&&c&&(c.addTags(a??[]),c.addTags(r??[],!1)),(i||s)&&c&&(c.addMetadata(i??{}),c.addMetadata(s??{},!1)),c}};function Ve(e){return"name"in e?e:Xe.fromMethods(e)}var hr=class{getStore(){}run(e,t){return t()}enterWith(e){}};const Go=new hr,Vn=Symbol.for("lc:child_config");var Zo=class{getInstance(){return qe()??Go}getRunnableConfig(){return this.getInstance().getStore()?.extra?.[Vn]}runWithConfig(e,t,n){const a=Oe._configureSync(e?.callbacks,void 0,e?.tags,void 0,e?.metadata),r=this.getInstance(),i=r.getStore(),s=a?.getParentRunId(),o=a?.handlers?.find(l=>l?.name==="langchain_tracer");let c;return o&&s?c=o.getRunTreeWithTracingConfig(s):n||(c=new q({name:"<runnable_lambda>",tracingEnabled:!1})),c&&(c.extra={...c.extra,[Vn]:e}),i!==void 0&&i[He]!==void 0&&(c===void 0&&(c={}),c[He]=i[He]),r.run(c,t)}initializeGlobalInstance(e){qe()===void 0&&Yi(e)}};const he=new Zo;var qo={};D(qo,{AsyncLocalStorageProviderSingleton:()=>he,MockAsyncLocalStorage:()=>hr,_CONTEXT_VARIABLES_KEY:()=>He});const Ut=25;async function ae(e){return Oe._configureSync(e?.callbacks,void 0,e?.tags,void 0,e?.metadata)}function Wn(...e){const t={};for(const n of e.filter(a=>!!a))for(const a of Object.keys(n))if(a==="metadata")t[a]={...t[a],...n[a]};else if(a==="tags"){const r=t[a]??[];t[a]=[...new Set(r.concat(n[a]??[]))]}else if(a==="configurable")t[a]={...t[a],...n[a]};else if(a==="timeout")t.timeout===void 0?t.timeout=n.timeout:n.timeout!==void 0&&(t.timeout=Math.min(t.timeout,n.timeout));else if(a==="signal")t.signal===void 0?t.signal=n.signal:n.signal!==void 0&&("any"in AbortSignal?t.signal=AbortSignal.any([t.signal,n.signal]):t.signal=n.signal);else if(a==="callbacks"){const r=t.callbacks,i=n.callbacks;if(Array.isArray(i))if(!r)t.callbacks=i;else if(Array.isArray(r))t.callbacks=r.concat(i);else{const s=r.copy();for(const o of i)s.addHandler(Ve(o),!0);t.callbacks=s}else if(i)if(!r)t.callbacks=i;else if(Array.isArray(r)){const s=i.copy();for(const o of r)s.addHandler(Ve(o),!0);t.callbacks=s}else t.callbacks=new Oe(i._parentRunId,{handlers:r.handlers.concat(i.handlers),inheritableHandlers:r.inheritableHandlers.concat(i.inheritableHandlers),tags:Array.from(new Set(r.tags.concat(i.tags))),inheritableTags:Array.from(new Set(r.inheritableTags.concat(i.inheritableTags))),metadata:{...r.metadata,...i.metadata}})}else{const r=a;t[r]=n[r]??t[r]}return t}const Jo=new Set(["string","number","boolean"]);function k(e){const t=he.getRunnableConfig();let n={tags:[],metadata:{},recursionLimit:25,runId:void 0};if(t){const{runId:a,runName:r,...i}=t;n=Object.entries(i).reduce((s,[o,c])=>(c!==void 0&&(s[o]=c),s),n)}if(e&&(n=Object.entries(e).reduce((a,[r,i])=>(i!==void 0&&(a[r]=i),a),n)),n?.configurable)for(const a of Object.keys(n.configurable))Jo.has(typeof n.configurable[a])&&!n.metadata?.[a]&&(n.metadata||(n.metadata={}),n.metadata[a]=n.configurable[a]);if(n.timeout!==void 0){if(n.timeout<=0)throw new Error("Timeout must be a positive number");const a=AbortSignal.timeout(n.timeout);n.signal!==void 0?"any"in AbortSignal&&(n.signal=AbortSignal.any([n.signal,a])):n.signal=a,delete n.timeout}return n}function F(e={},{callbacks:t,maxConcurrency:n,recursionLimit:a,runName:r,configurable:i,runId:s}={}){const o=k(e);return t!==void 0&&(delete o.runName,o.callbacks=t),a!==void 0&&(o.recursionLimit=a),n!==void 0&&(o.maxConcurrency=n),r!==void 0&&(o.runName=r),i!==void 0&&(o.configurable={...o.configurable,...i}),s!==void 0&&delete o.runId,o}function $e(e){return e?{configurable:e.configurable,recursionLimit:e.recursionLimit,callbacks:e.callbacks,tags:e.tags,metadata:e.metadata,maxConcurrency:e.maxConcurrency,timeout:e.timeout,signal:e.signal}:void 0}async function ye(e,t){if(t===void 0)return e;let n;return Promise.race([e.catch(a=>{if(!t?.aborted)throw a}),new Promise((a,r)=>{n=()=>{r(pt(t))},t.addEventListener("abort",n),t.aborted&&r(pt(t))})]).finally(()=>t.removeEventListener("abort",n))}function pt(e){return e?.reason instanceof Error?e.reason:typeof e?.reason=="string"?new Error(e.reason):new Error("Aborted")}var Vo={};D(Vo,{AsyncGeneratorWithSetup:()=>Ce,IterableReadableStream:()=>re,atee:()=>mn,concat:()=>gn,pipeGeneratorWithSetup:()=>pr});var re=class Qt extends ReadableStream{reader;ensureReader(){this.reader||(this.reader=this.getReader())}async next(){this.ensureReader();try{const t=await this.reader.read();return t.done?(this.reader.releaseLock(),{done:!0,value:void 0}):{done:!1,value:t.value}}catch(t){throw this.reader.releaseLock(),t}}async return(){if(this.ensureReader(),this.locked){const t=this.reader.cancel();this.reader.releaseLock(),await t}return{done:!0,value:void 0}}async throw(t){if(this.ensureReader(),this.locked){const n=this.reader.cancel();this.reader.releaseLock(),await n}throw t}[Symbol.asyncIterator](){return this}async[Symbol.asyncDispose](){await this.return()}static fromReadableStream(t){const n=t.getReader();return new Qt({start(a){return r();function r(){return n.read().then(({done:i,value:s})=>{if(i){a.close();return}return a.enqueue(s),r()})}},cancel(){n.releaseLock()}})}static fromAsyncGenerator(t){return new Qt({async pull(n){const{value:a,done:r}=await t.next();r&&n.close(),n.enqueue(a)},async cancel(n){await t.return(n)}})}};function mn(e,t=2){const n=Array.from({length:t},()=>[]);return n.map(async function*(r){for(;;)if(r.length===0){const i=await e.next();for(const s of n)s.push(i)}else{if(r[0].done)return;yield r.shift().value}})}function gn(e,t){if(Array.isArray(e)&&Array.isArray(t))return e.concat(t);if(typeof e=="string"&&typeof t=="string")return e+t;if(typeof e=="number"&&typeof t=="number")return e+t;if("concat"in e&&typeof e.concat=="function")return e.concat(t);if(typeof e=="object"&&typeof t=="object"){const n={...e};for(const[a,r]of Object.entries(t))a in n&&!Array.isArray(n[a])?n[a]=gn(n[a],r):n[a]=r;return n}else throw new Error(`Cannot concat ${typeof e} and ${typeof t}`)}var Ce=class{generator;setup;config;signal;firstResult;firstResultUsed=!1;constructor(e){this.generator=e.generator,this.config=e.config,this.signal=e.signal??this.config?.signal,this.setup=new Promise((t,n)=>{he.runWithConfig($e(e.config),async()=>{this.firstResult=e.generator.next(),e.startSetup?this.firstResult.then(e.startSetup).then(t,n):this.firstResult.then(a=>t(void 0),n)},!0)})}async next(...e){return this.signal?.throwIfAborted(),this.firstResultUsed?he.runWithConfig($e(this.config),this.signal?async()=>ye(this.generator.next(...e),this.signal):async()=>this.generator.next(...e),!0):(this.firstResultUsed=!0,this.firstResult)}async return(e){return this.generator.return(e)}async throw(e){return this.generator.throw(e)}[Symbol.asyncIterator](){return this}async[Symbol.asyncDispose](){await this.return()}};async function pr(e,t,n,a,...r){const i=new Ce({generator:t,startSetup:n,signal:a}),s=await i.setup;return{output:e(i,s,...r),setup:s}}/*!
|
|
54
|
-
* https://github.com/Starcounter-Jack/JSON-Patch
|
|
55
|
-
* (c) 2017-2022 Joachim Wester
|
|
56
|
-
* MIT licensed
|
|
57
|
-
*/const Wo=Object.prototype.hasOwnProperty;function Ko(e,t){return Wo.call(e,t)}function Qo(e){if(Array.isArray(e)){const n=new Array(e.length);for(let a=0;a<n.length;a++)n[a]=""+a;return n}if(Object.keys)return Object.keys(e);let t=[];for(let n in e)Ko(e,n)&&t.push(n);return t}function Te(e){switch(typeof e){case"object":return JSON.parse(JSON.stringify(e));case"undefined":return null;default:return e}}function Yt(e){let t=0;const n=e.length;let a;for(;t<n;){if(a=e.charCodeAt(t),a>=48&&a<=57){t++;continue}return!1}return!0}function Dl(e){return e.indexOf("/")===-1&&e.indexOf("~")===-1?e:e.replace(/~/g,"~0").replace(/\//g,"~1")}function Yo(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function Xt(e){if(e===void 0)return!0;if(e){if(Array.isArray(e)){for(let n=0,a=e.length;n<a;n++)if(Xt(e[n]))return!0}else if(typeof e=="object"){const n=Qo(e),a=n.length;for(var t=0;t<a;t++)if(Xt(e[n[t]]))return!0}}return!1}function Kn(e,t){const n=[e];for(const a in t){const r=typeof t[a]=="object"?JSON.stringify(t[a],null,2):t[a];typeof r<"u"&&n.push(`${a}: ${r}`)}return n.join(`
|
|
58
|
-
`)}var Xo=class extends Error{constructor(e,t,n,a,r){super(Kn(e,{name:t,index:n,operation:a,tree:r})),this.name=t,this.index=n,this.operation=a,this.tree=r,Object.setPrototypeOf(this,new.target.prototype),this.message=Kn(e,{name:t,index:n,operation:a,tree:r})}},fr={};D(fr,{JsonPatchError:()=>P,_areEquals:()=>Ke,applyOperation:()=>Se,applyPatch:()=>We,applyReducer:()=>nc,deepClone:()=>ec,getValueByPointer:()=>ft,validate:()=>mr,validator:()=>mt});const P=Xo,ec=Te,Re={add:function(e,t,n){return e[t]=this.value,{newDocument:n}},remove:function(e,t,n){var a=e[t];return delete e[t],{newDocument:n,removed:a}},replace:function(e,t,n){var a=e[t];return e[t]=this.value,{newDocument:n,removed:a}},move:function(e,t,n){let a=ft(n,this.path);a&&(a=Te(a));const r=Se(n,{op:"remove",path:this.from}).removed;return Se(n,{op:"add",path:this.path,value:r}),{newDocument:n,removed:a}},copy:function(e,t,n){const a=ft(n,this.from);return Se(n,{op:"add",path:this.path,value:Te(a)}),{newDocument:n}},test:function(e,t,n){return{newDocument:n,test:Ke(e[t],this.value)}},_get:function(e,t,n){return this.value=e[t],{newDocument:n}}};var tc={add:function(e,t,n){return Yt(t)?e.splice(t,0,this.value):e[t]=this.value,{newDocument:n,index:t}},remove:function(e,t,n){var a=e.splice(t,1);return{newDocument:n,removed:a[0]}},replace:function(e,t,n){var a=e[t];return e[t]=this.value,{newDocument:n,removed:a}},move:Re.move,copy:Re.copy,test:Re.test,_get:Re._get};function ft(e,t){if(t=="")return e;var n={op:"_get",path:t};return Se(e,n),n.value}function Se(e,t,n=!1,a=!0,r=!0,i=0){if(n&&(typeof n=="function"?n(t,0,e,t.path):mt(t,0)),t.path===""){let s={newDocument:e};if(t.op==="add")return s.newDocument=t.value,s;if(t.op==="replace")return s.newDocument=t.value,s.removed=e,s;if(t.op==="move"||t.op==="copy")return s.newDocument=ft(e,t.from),t.op==="move"&&(s.removed=e),s;if(t.op==="test"){if(s.test=Ke(e,t.value),s.test===!1)throw new P("Test operation failed","TEST_OPERATION_FAILED",i,t,e);return s.newDocument=e,s}else{if(t.op==="remove")return s.removed=e,s.newDocument=null,s;if(t.op==="_get")return t.value=e,s;if(n)throw new P("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",i,t,e);return s}}else{a||(e=Te(e));const o=(t.path||"").split("/");let c=e,l=1,u=o.length,h,d,p;for(typeof n=="function"?p=n:p=mt;;){if(d=o[l],d&&d.indexOf("~")!=-1&&(d=Yo(d)),r&&(d=="__proto__"||d=="prototype"&&l>0&&o[l-1]=="constructor"))throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(n&&h===void 0&&(c[d]===void 0?h=o.slice(0,l).join("/"):l==u-1&&(h=t.path),h!==void 0&&p(t,0,e,h)),l++,Array.isArray(c)){if(d==="-")d=c.length;else{if(n&&!Yt(d))throw new P("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",i,t,e);Yt(d)&&(d=~~d)}if(l>=u){if(n&&t.op==="add"&&d>c.length)throw new P("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",i,t,e);const f=tc[t.op].call(t,c,d,e);if(f.test===!1)throw new P("Test operation failed","TEST_OPERATION_FAILED",i,t,e);return f}}else if(l>=u){const f=Re[t.op].call(t,c,d,e);if(f.test===!1)throw new P("Test operation failed","TEST_OPERATION_FAILED",i,t,e);return f}if(c=c[d],n&&l<u&&(!c||typeof c!="object"))throw new P("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",i,t,e)}}}function We(e,t,n,a=!0,r=!0){if(n&&!Array.isArray(t))throw new P("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");a||(e=Te(e));const i=new Array(t.length);for(let s=0,o=t.length;s<o;s++)i[s]=Se(e,t[s],n,!0,r,s),e=i[s].newDocument;return i.newDocument=e,i}function nc(e,t,n){const a=Se(e,t);if(a.test===!1)throw new P("Test operation failed","TEST_OPERATION_FAILED",n,t,e);return a.newDocument}function mt(e,t,n,a){if(typeof e!="object"||e===null||Array.isArray(e))throw new P("Operation is not an object","OPERATION_NOT_AN_OBJECT",t,e,n);if(Re[e.op]){if(typeof e.path!="string")throw new P("Operation `path` property is not a string","OPERATION_PATH_INVALID",t,e,n);if(e.path.indexOf("/")!==0&&e.path.length>0)throw new P('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",t,e,n);if((e.op==="move"||e.op==="copy")&&typeof e.from!="string")throw new P("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",t,e,n);if((e.op==="add"||e.op==="replace"||e.op==="test")&&e.value===void 0)throw new P("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",t,e,n);if((e.op==="add"||e.op==="replace"||e.op==="test")&&Xt(e.value))throw new P("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",t,e,n);if(n){if(e.op=="add"){var r=e.path.split("/").length,i=a.split("/").length;if(r!==i+1&&r!==i)throw new P("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",t,e,n)}else if(e.op==="replace"||e.op==="remove"||e.op==="_get"){if(e.path!==a)throw new P("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",t,e,n)}else if(e.op==="move"||e.op==="copy"){var s={op:"_get",path:e.from,value:void 0},o=mr([s],n);if(o&&o.name==="OPERATION_PATH_UNRESOLVABLE")throw new P("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",t,e,n)}}}else throw new P("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",t,e,n)}function mr(e,t,n){try{if(!Array.isArray(e))throw new P("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(t)We(Te(t),Te(e),n||!0);else{n=n||mt;for(var a=0;a<e.length;a++)n(e[a],a,t,void 0)}}catch(r){if(r instanceof P)return r;throw r}}function Ke(e,t){if(e===t)return!0;if(e&&t&&typeof e=="object"&&typeof t=="object"){var n=Array.isArray(e),a=Array.isArray(t),r,i,s;if(n&&a){if(i=e.length,i!=t.length)return!1;for(r=i;r--!==0;)if(!Ke(e[r],t[r]))return!1;return!0}if(n!=a)return!1;var o=Object.keys(e);if(i=o.length,i!==Object.keys(t).length)return!1;for(r=i;r--!==0;)if(!t.hasOwnProperty(o[r]))return!1;for(r=i;r--!==0;)if(s=o[r],!Ke(e[s],t[s]))return!1;return!0}return e!==e&&t!==t}({...fr});var ac={};D(ac,{LogStreamCallbackHandler:()=>tn,RunLog:()=>_n,RunLogPatch:()=>le,isLogStreamHandler:()=>gr});var le=class{ops;constructor(e){this.ops=e.ops??[]}concat(e){const t=this.ops.concat(e.ops),n=We({},t);return new _n({ops:t,state:n[n.length-1].newDocument})}},_n=class en extends le{state;constructor(t){super(t),this.state=t.state}concat(t){const n=this.ops.concat(t.ops),a=We(this.state,t.ops);return new en({ops:n,state:a[a.length-1].newDocument})}static fromRunLogPatch(t){const n=We({},t.ops);return new en({ops:t.ops,state:n[n.length-1].newDocument})}};const gr=e=>e.name==="log_stream_tracer";async function Qn(e,t){if(t==="original")throw new Error("Do not assign inputs with original schema drop the key for now. When inputs are added to streamLog they should be added with standardized schema for streaming events.");const{inputs:n}=e;if(["retriever","llm","prompt"].includes(e.run_type))return n;if(!(Object.keys(n).length===1&&n?.input===""))return n.input}async function Yn(e,t){const{outputs:n}=e;return t==="original"||["retriever","llm","prompt"].includes(e.run_type)?n:n!==void 0&&Object.keys(n).length===1&&n?.output!==void 0?n.output:n}function rc(e){return e!==void 0&&e.message!==void 0}var tn=class extends De{autoClose=!0;includeNames;includeTypes;includeTags;excludeNames;excludeTypes;excludeTags;_schemaFormat="original";rootId;keyMapByRunId={};counterMapByRunName={};transformStream;writer;receiveStream;name="log_stream_tracer";lc_prefer_streaming=!0;constructor(e){super({_awaitHandler:!0,...e}),this.autoClose=e?.autoClose??!0,this.includeNames=e?.includeNames,this.includeTypes=e?.includeTypes,this.includeTags=e?.includeTags,this.excludeNames=e?.excludeNames,this.excludeTypes=e?.excludeTypes,this.excludeTags=e?.excludeTags,this._schemaFormat=e?._schemaFormat??this._schemaFormat,this.transformStream=new TransformStream,this.writer=this.transformStream.writable.getWriter(),this.receiveStream=re.fromReadableStream(this.transformStream.readable)}[Symbol.asyncIterator](){return this.receiveStream}async persistRun(e){}_includeRun(e){if(e.id===this.rootId)return!1;const t=e.tags??[];let n=this.includeNames===void 0&&this.includeTags===void 0&&this.includeTypes===void 0;return this.includeNames!==void 0&&(n=n||this.includeNames.includes(e.name)),this.includeTypes!==void 0&&(n=n||this.includeTypes.includes(e.run_type)),this.includeTags!==void 0&&(n=n||t.find(a=>this.includeTags?.includes(a))!==void 0),this.excludeNames!==void 0&&(n=n&&!this.excludeNames.includes(e.name)),this.excludeTypes!==void 0&&(n=n&&!this.excludeTypes.includes(e.run_type)),this.excludeTags!==void 0&&(n=n&&t.every(a=>!this.excludeTags?.includes(a))),n}async*tapOutputIterable(e,t){for await(const n of t){if(e!==this.rootId){const a=this.keyMapByRunId[e];a&&await this.writer.write(new le({ops:[{op:"add",path:`/logs/${a}/streamed_output/-`,value:n}]}))}yield n}}async onRunCreate(e){if(this.rootId===void 0&&(this.rootId=e.id,await this.writer.write(new le({ops:[{op:"replace",path:"",value:{id:e.id,name:e.name,type:e.run_type,streamed_output:[],final_output:void 0,logs:{}}}]}))),!this._includeRun(e))return;this.counterMapByRunName[e.name]===void 0&&(this.counterMapByRunName[e.name]=0),this.counterMapByRunName[e.name]+=1;const t=this.counterMapByRunName[e.name];this.keyMapByRunId[e.id]=t===1?e.name:`${e.name}:${t}`;const n={id:e.id,name:e.name,type:e.run_type,tags:e.tags??[],metadata:e.extra?.metadata??{},start_time:new Date(e.start_time).toISOString(),streamed_output:[],streamed_output_str:[],final_output:void 0,end_time:void 0};this._schemaFormat==="streaming_events"&&(n.inputs=await Qn(e,this._schemaFormat)),await this.writer.write(new le({ops:[{op:"add",path:`/logs/${this.keyMapByRunId[e.id]}`,value:n}]}))}async onRunUpdate(e){try{const t=this.keyMapByRunId[e.id];if(t===void 0)return;const n=[];this._schemaFormat==="streaming_events"&&n.push({op:"replace",path:`/logs/${t}/inputs`,value:await Qn(e,this._schemaFormat)}),n.push({op:"add",path:`/logs/${t}/final_output`,value:await Yn(e,this._schemaFormat)}),e.end_time!==void 0&&n.push({op:"add",path:`/logs/${t}/end_time`,value:new Date(e.end_time).toISOString()});const a=new le({ops:n});await this.writer.write(a)}finally{if(e.id===this.rootId){const t=new le({ops:[{op:"replace",path:"/final_output",value:await Yn(e,this._schemaFormat)}]});await this.writer.write(t),this.autoClose&&await this.writer.close()}}}async onLLMNewToken(e,t,n){const a=this.keyMapByRunId[e.id];if(a===void 0)return;const r=e.inputs.messages!==void 0;let i;r?rc(n?.chunk)?i=n?.chunk:i=new Le({id:`run-${e.id}`,content:t}):i=t;const s=new le({ops:[{op:"add",path:`/logs/${a}/streamed_output_str/-`,value:t},{op:"add",path:`/logs/${a}/streamed_output/-`,value:i}]});await this.writer.write(s)}},ic={};D(ic,{ChatGenerationChunk:()=>oc,GenerationChunk:()=>gt,RUN_KEY:()=>sc});const sc="__run";var gt=class _r{text;generationInfo;constructor(t){this.text=t.text,this.generationInfo=t.generationInfo}concat(t){return new _r({text:this.text+t.text,generationInfo:{...this.generationInfo,...t.generationInfo}})}},oc=class yr extends gt{message;constructor(t){super(t),this.message=t.message}concat(t){return new yr({text:this.text+t.text,generationInfo:{...this.generationInfo,...t.generationInfo},message:this.message.concat(t.message)})}};function it({name:e,serialized:t}){return e!==void 0?e:t?.name!==void 0?t.name:t?.id!==void 0&&Array.isArray(t?.id)?t.id[t.id.length-1]:"Unnamed"}const cc=e=>e.name==="event_stream_tracer";var lc=class extends De{autoClose=!0;includeNames;includeTypes;includeTags;excludeNames;excludeTypes;excludeTags;runInfoMap=new Map;tappedPromises=new Map;transformStream;writer;receiveStream;name="event_stream_tracer";lc_prefer_streaming=!0;constructor(e){super({_awaitHandler:!0,...e}),this.autoClose=e?.autoClose??!0,this.includeNames=e?.includeNames,this.includeTypes=e?.includeTypes,this.includeTags=e?.includeTags,this.excludeNames=e?.excludeNames,this.excludeTypes=e?.excludeTypes,this.excludeTags=e?.excludeTags,this.transformStream=new TransformStream,this.writer=this.transformStream.writable.getWriter(),this.receiveStream=re.fromReadableStream(this.transformStream.readable)}[Symbol.asyncIterator](){return this.receiveStream}async persistRun(e){}_includeRun(e){const t=e.tags??[];let n=this.includeNames===void 0&&this.includeTags===void 0&&this.includeTypes===void 0;return this.includeNames!==void 0&&(n=n||this.includeNames.includes(e.name)),this.includeTypes!==void 0&&(n=n||this.includeTypes.includes(e.runType)),this.includeTags!==void 0&&(n=n||t.find(a=>this.includeTags?.includes(a))!==void 0),this.excludeNames!==void 0&&(n=n&&!this.excludeNames.includes(e.name)),this.excludeTypes!==void 0&&(n=n&&!this.excludeTypes.includes(e.runType)),this.excludeTags!==void 0&&(n=n&&t.every(a=>!this.excludeTags?.includes(a))),n}async*tapOutputIterable(e,t){const n=await t.next();if(n.done)return;const a=this.runInfoMap.get(e);if(a===void 0){yield n.value;return}function r(s,o){return s==="llm"&&typeof o=="string"?new gt({text:o}):o}let i=this.tappedPromises.get(e);if(i===void 0){let s;i=new Promise(o=>{s=o}),this.tappedPromises.set(e,i);try{const o={event:`on_${a.runType}_stream`,run_id:e,name:a.name,tags:a.tags,metadata:a.metadata,data:{}};await this.send({...o,data:{chunk:r(a.runType,n.value)}},a),yield n.value;for await(const c of t)a.runType!=="tool"&&a.runType!=="retriever"&&await this.send({...o,data:{chunk:r(a.runType,c)}},a),yield c}finally{s?.()}}else{yield n.value;for await(const s of t)yield s}}async send(e,t){this._includeRun(t)&&await this.writer.write(e)}async sendEndEvent(e,t){const n=this.tappedPromises.get(e.run_id);n!==void 0?n.then(()=>{this.send(e,t)}):await this.send(e,t)}async onLLMStart(e){const t=it(e),n=e.inputs.messages!==void 0?"chat_model":"llm",a={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:n,inputs:e.inputs};this.runInfoMap.set(e.id,a);const r=`on_${n}_start`;await this.send({event:r,data:{input:e.inputs},name:t,tags:e.tags??[],run_id:e.id,metadata:e.extra?.metadata??{}},a)}async onLLMNewToken(e,t,n){const a=this.runInfoMap.get(e.id);let r,i;if(a===void 0)throw new Error(`onLLMNewToken: Run ID ${e.id} not found in run map.`);if(this.runInfoMap.size!==1){if(a.runType==="chat_model")i="on_chat_model_stream",n?.chunk===void 0?r=new Le({content:t,id:`run-${e.id}`}):r=n.chunk.message;else if(a.runType==="llm")i="on_llm_stream",n?.chunk===void 0?r=new gt({text:t}):r=n.chunk;else throw new Error(`Unexpected run type ${a.runType}`);await this.send({event:i,data:{chunk:r},run_id:e.id,name:a.name,tags:a.tags,metadata:a.metadata},a)}}async onLLMEnd(e){const t=this.runInfoMap.get(e.id);this.runInfoMap.delete(e.id);let n;if(t===void 0)throw new Error(`onLLMEnd: Run ID ${e.id} not found in run map.`);const a=e.outputs?.generations;let r;if(t.runType==="chat_model"){for(const i of a??[]){if(r!==void 0)break;r=i[0]?.message}n="on_chat_model_end"}else if(t.runType==="llm")r={generations:a?.map(i=>i.map(s=>({text:s.text,generationInfo:s.generationInfo}))),llmOutput:e.outputs?.llmOutput??{}},n="on_llm_end";else throw new Error(`onLLMEnd: Unexpected run type: ${t.runType}`);await this.sendEndEvent({event:n,data:{output:r,input:t.inputs},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async onChainStart(e){const t=it(e),n=e.run_type??"chain",a={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:e.run_type};let r={};e.inputs.input===""&&Object.keys(e.inputs).length===1?(r={},a.inputs={}):e.inputs.input!==void 0?(r.input=e.inputs.input,a.inputs=e.inputs.input):(r.input=e.inputs,a.inputs=e.inputs),this.runInfoMap.set(e.id,a),await this.send({event:`on_${n}_start`,data:r,name:t,tags:e.tags??[],run_id:e.id,metadata:e.extra?.metadata??{}},a)}async onChainEnd(e){const t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),t===void 0)throw new Error(`onChainEnd: Run ID ${e.id} not found in run map.`);const n=`on_${e.run_type}_end`,a=e.inputs??t.inputs??{},i={output:e.outputs?.output??e.outputs,input:a};a.input&&Object.keys(a).length===1&&(i.input=a.input,t.inputs=a.input),await this.sendEndEvent({event:n,data:i,run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata??{}},t)}async onToolStart(e){const t=it(e),n={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:"tool",inputs:e.inputs??{}};this.runInfoMap.set(e.id,n),await this.send({event:"on_tool_start",data:{input:e.inputs??{}},name:t,run_id:e.id,tags:e.tags??[],metadata:e.extra?.metadata??{}},n)}async onToolEnd(e){const t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),t===void 0)throw new Error(`onToolEnd: Run ID ${e.id} not found in run map.`);if(t.inputs===void 0)throw new Error(`onToolEnd: Run ID ${e.id} is a tool call, and is expected to have traced inputs.`);const n=e.outputs?.output===void 0?e.outputs:e.outputs.output;await this.sendEndEvent({event:"on_tool_end",data:{output:n,input:t.inputs},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async onRetrieverStart(e){const t=it(e),a={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:"retriever",inputs:{query:e.inputs.query}};this.runInfoMap.set(e.id,a),await this.send({event:"on_retriever_start",data:{input:{query:e.inputs.query}},name:t,tags:e.tags??[],run_id:e.id,metadata:e.extra?.metadata??{}},a)}async onRetrieverEnd(e){const t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),t===void 0)throw new Error(`onRetrieverEnd: Run ID ${e.id} not found in run map.`);await this.sendEndEvent({event:"on_retriever_end",data:{output:e.outputs?.documents??e.outputs,input:t.inputs},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async handleCustomEvent(e,t,n){const a=this.runInfoMap.get(n);if(a===void 0)throw new Error(`handleCustomEvent: Run ID ${n} not found in run map.`);await this.send({event:"on_custom_event",run_id:n,name:e,tags:a.tags,metadata:a.metadata,data:t},a)}async finish(){const e=[...this.tappedPromises.values()];Promise.all(e).finally(()=>{this.writer.close()})}},uc={};D(uc,{AsyncCaller:()=>wr});const dc=[400,401,402,403,404,405,406,407,409],hc=e=>{if(e.message.startsWith("Cancel")||e.message.startsWith("AbortError")||e.name==="AbortError"||e?.code==="ECONNABORTED")throw e;const t=e?.response?.status??e?.status;if(t&&dc.includes(+t))throw e;if(e?.error?.code==="insufficient_quota"){const n=new Error(e?.message);throw n.name="InsufficientQuotaError",n}};var wr=class{maxConcurrency;maxRetries;onFailedAttempt;queue;constructor(e){this.maxConcurrency=e.maxConcurrency??1/0,this.maxRetries=e.maxRetries??6,this.onFailedAttempt=e.onFailedAttempt??hc;const t="default"in ue?ue.default:ue;this.queue=new t({concurrency:this.maxConcurrency})}call(e,...t){return this.queue.add(()=>lt(()=>e(...t).catch(n=>{throw n instanceof Error?n:new Error(n)}),{onFailedAttempt:this.onFailedAttempt,retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0})}callWithOptions(e,t,...n){return e.signal?Promise.race([this.call(t,...n),new Promise((a,r)=>{e.signal?.addEventListener("abort",()=>{r(pt(e.signal))})})]):this.call(t,...n)}fetch(...e){return this.call(()=>fetch(...e).then(t=>t.ok?t:Promise.reject(t)))}},vr=class extends De{name="RootListenersTracer";rootId;config;argOnStart;argOnEnd;argOnError;constructor({config:e,onStart:t,onEnd:n,onError:a}){super({_awaitHandler:!0}),this.config=e,this.argOnStart=t,this.argOnEnd=n,this.argOnError=a}persistRun(e){return Promise.resolve()}async onRunCreate(e){this.rootId||(this.rootId=e.id,this.argOnStart&&await this.argOnStart(e,this.config))}async onRunUpdate(e){e.id===this.rootId&&(e.error?this.argOnError&&await this.argOnError(e,this.config):this.argOnEnd&&await this.argOnEnd(e,this.config))}};function yn(e){return e?e.lc_runnable:!1}var pc=class{includeNames;includeTypes;includeTags;excludeNames;excludeTypes;excludeTags;constructor(e){this.includeNames=e.includeNames,this.includeTypes=e.includeTypes,this.includeTags=e.includeTags,this.excludeNames=e.excludeNames,this.excludeTypes=e.excludeTypes,this.excludeTags=e.excludeTags}includeEvent(e,t){let n=this.includeNames===void 0&&this.includeTypes===void 0&&this.includeTags===void 0;const a=e.tags??[];return this.includeNames!==void 0&&(n=n||this.includeNames.includes(e.name)),this.includeTypes!==void 0&&(n=n||this.includeTypes.includes(t)),this.includeTags!==void 0&&(n=n||a.some(r=>this.includeTags?.includes(r))),this.excludeNames!==void 0&&(n=n&&!this.excludeNames.includes(e.name)),this.excludeTypes!==void 0&&(n=n&&!this.excludeTypes.includes(t)),this.excludeTags!==void 0&&(n=n&&a.every(r=>!this.excludeTags?.includes(r))),n}};function L(e){if(typeof e!="object"||e===null)return!1;const t=e;if(!("_zod"in t))return!1;const n=t._zod;return typeof n=="object"&&n!==null&&"def"in n}function U(e){if(typeof e!="object"||e===null)return!1;const t=e;if(!("_def"in t)||"_zod"in t)return!1;const n=t._def;return typeof n=="object"&&n!=null&&"typeName"in n}function Ul(e){return L(e)&&console.warn("[WARNING] Attempting to use Zod 4 schema in a context where Zod 3 schema is expected. This may cause unexpected behavior."),U(e)}function br(e){return!e||typeof e!="object"||Array.isArray(e)?!1:!!(L(e)||U(e))}function fc(e){return typeof e=="object"&&e!==null&&"_def"in e&&typeof e._def=="object"&&e._def!==null&&"typeName"in e._def&&e._def.typeName==="ZodLiteral"}function mc(e){return L(e)?typeof e=="object"&&e!==null&&"_zod"in e&&typeof e._zod=="object"&&e._zod!==null&&"def"in e._zod&&typeof e._zod.def=="object"&&e._zod.def!==null&&"type"in e._zod.def&&e._zod.def.type==="literal":!1}function Fl(e){return!!(fc(e)||mc(e))}async function Bl(e,t){if(L(e))try{return{success:!0,data:await pa(e,t)}}catch(n){return{success:!1,error:n}}if(U(e))return await e.safeParseAsync(t);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}async function gc(e,t){if(L(e))return await pa(e,t);if(U(e))return await e.parseAsync(t);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function zl(e,t){if(L(e))try{return{success:!0,data:sn(e,t)}}catch(n){return{success:!1,error:n}}if(U(e))return e.safeParse(t);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function Hl(e,t){if(L(e))return sn(e,t);if(U(e))return e.parse(t);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function _c(e){if(L(e))return Q.get(e)?.description;if(U(e)||"description"in e&&typeof e.description=="string")return e.description}function Gl(e){if(!br(e))return!1;if(U(e)){const t=e._def;if(t.typeName==="ZodObject"){const n=e;return!n.shape||Object.keys(n.shape).length===0}if(t.typeName==="ZodRecord")return!0}if(L(e)){const t=e._zod.def;if(t.type==="object"){const n=e;return!n.shape||Object.keys(n.shape).length===0}if(t.type==="record")return!0}return typeof e=="object"&&e!==null&&!("shape"in e)}function yc(e){return br(e)?U(e)?e._def.typeName==="ZodString":L(e)?e._zod.def.type==="string":!1:!1}function Sr(e){return typeof e=="object"&&e!==null&&"_def"in e&&typeof e._def=="object"&&e._def!==null&&"typeName"in e._def&&e._def.typeName==="ZodObject"}function de(e){return L(e)?typeof e=="object"&&e!==null&&"_zod"in e&&typeof e._zod=="object"&&e._zod!==null&&"def"in e._zod&&typeof e._zod.def=="object"&&e._zod.def!==null&&"type"in e._zod.def&&e._zod.def.type==="object":!1}function wn(e){return L(e)?typeof e=="object"&&e!==null&&"_zod"in e&&typeof e._zod=="object"&&e._zod!==null&&"def"in e._zod&&typeof e._zod.def=="object"&&e._zod.def!==null&&"type"in e._zod.def&&e._zod.def.type==="array":!1}function Zl(e){return!!(Sr(e)||de(e))}function Xn(e){if(U(e))return e.shape;if(L(e))return e._zod.def.shape;throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function ql(e,t){if(U(e))return e.extend(t);if(L(e))return Zr(e,t);throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function Jl(e){if(U(e))return e.partial();if(L(e))return Gr(fa,e);throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function nn(e,t=!1){if(U(e))return e.strict();if(de(e)){const n=e._zod.def.shape;if(t)for(const[i,s]of Object.entries(e._zod.def.shape)){if(de(s)){const c=nn(s,t);n[i]=c}else if(wn(s)){let c=s._zod.def.element;de(c)&&(c=nn(c,t)),n[i]=Ee(s,{...s._zod.def,element:c})}else n[i]=s;const o=Q.get(s);o&&Q.add(n[i],o)}const a=Ee(e,{...e._zod.def,shape:n,catchall:Br(zr)}),r=Q.get(e);return r&&Q.add(a,r),a}throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function ea(e,t=!1){if(Sr(e))return e.passthrough();if(de(e)){const n=e._zod.def.shape;if(t)for(const[i,s]of Object.entries(e._zod.def.shape)){if(de(s)){const c=ea(s,t);n[i]=c}else if(wn(s)){let c=s._zod.def.element;de(c)&&(c=ea(c,t)),n[i]=Ee(s,{...s._zod.def,element:c})}else n[i]=s;const o=Q.get(s);o&&Q.add(n[i],o)}const a=Ee(e,{...e._zod.def,shape:n,catchall:Hr(qr)}),r=Q.get(e);return r&&Q.add(a,r),a}throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function Vl(e){if(U(e))try{const t=e.parse(void 0);return()=>t}catch{return}if(L(e))try{const t=sn(e,void 0);return()=>t}catch{return}}function wc(e){return U(e)&&"typeName"in e._def&&e._def.typeName==="ZodEffects"}function vc(e){return L(e)&&e._zod.def.type==="pipe"}function Be(e,t=!1){if(U(e))return wc(e)?Be(e._def.schema,t):e;if(L(e)){let n=e;if(vc(e)&&(n=Be(e._zod.def.in,t)),t){if(de(n)){const r=n._zod.def.shape;for(const[i,s]of Object.entries(n._zod.def.shape))r[i]=Be(s,t);n=Ee(n,{...n._zod.def,shape:r})}else if(wn(n)){const r=Be(n._zod.def.element,t);n=Ee(n,{...n._zod.def,element:r})}}const a=Q.get(e);return a&&Q.add(n,a),n}throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function Wl(e,t){if(U(e)){const n=Xn(e),a={};for(const[r,i]of Object.entries(n))t(r,i)?a[r]=i.optional():a[r]=i;return e.extend(a)}if(L(e)){const n=Xn(e),a={...e._zod.def.shape};for(const[s,o]of Object.entries(n))t(s,o)&&(a[s]=new fa({type:"optional",innerType:o}));const r=Ee(e,{...e._zod.def,shape:a}),i=Q.get(e);return i&&Q.add(r,i),r}throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function Ft(e){return e.replace(/[^a-zA-Z-_0-9]/g,"_")}const bc=["*","_","`"];function Sc(e){let t="";for(const[n,a]of Object.entries(e))t+=` classDef ${n} ${a};
|
|
59
|
-
`;return t}function Ec(e,t,n){const{firstNode:a,lastNode:r,nodeColors:i,withStyles:s=!0,curveStyle:o="linear",wrapLabelNWords:c=9}=n??{};let l=s?`%%{init: {'flowchart': {'curve': '${o}'}}}%%
|
|
60
|
-
graph TD;
|
|
61
|
-
`:`graph TD;
|
|
62
|
-
`;if(s){const p="default",f={[p]:"{0}({1})"};a!==void 0&&(f[a]="{0}([{1}]):::first"),r!==void 0&&(f[r]="{0}([{1}]):::last");for(const[A,y]of Object.entries(e)){const g=y.name.split(":").pop()??"";let E=bc.some(O=>g.startsWith(O)&&g.endsWith(O))?`<p>${g}</p>`:g;Object.keys(y.metadata??{}).length&&(E+=`<hr/><small><em>${Object.entries(y.metadata??{}).map(([O,N])=>`${O} = ${N}`).join(`
|
|
63
|
-
`)}</em></small>`);const I=(f[A]??f[p]).replace("{0}",Ft(A)).replace("{1}",E);l+=` ${I}
|
|
64
|
-
`}}const u={};for(const p of t){const f=p.source.split(":"),A=p.target.split(":"),y=f.filter((g,v)=>g===A[v]).join(":");u[y]||(u[y]=[]),u[y].push(p)}const h=new Set;function d(p,f){const A=p.length===1&&p[0].source===p[0].target;if(f&&!A){const y=f.split(":").pop();if(h.has(y))throw new Error(`Found duplicate subgraph '${y}' -- this likely means that you're reusing a subgraph node with the same name. Please adjust your graph to have subgraph nodes with unique names.`);h.add(y),l+=` subgraph ${y}
|
|
65
|
-
`}for(const y of p){const{source:g,target:v,data:E,conditional:I}=y;let O="";if(E!==void 0){let N=E;const R=N.split(" ");R.length>c&&(N=Array.from({length:Math.ceil(R.length/c)},($,Y)=>R.slice(Y*c,(Y+1)*c).join(" ")).join(" <br> ")),O=I?` -. ${N} .-> `:` -- ${N} --> `}else O=I?" -.-> ":" --> ";l+=` ${Ft(g)}${O}${Ft(v)};
|
|
66
|
-
`}for(const y in u)y.startsWith(`${f}:`)&&y!==f&&d(u[y],y);f&&!A&&(l+=` end
|
|
67
|
-
`)}d(u[""]??[],"");for(const p in u)!p.includes(":")&&p!==""&&d(u[p],p);return s&&(l+=Sc(i??{})),l}async function Tc(e,t){let n=t?.backgroundColor??"white";const a=t?.imageType??"png",r=btoa(e);n!==void 0&&(/^#(?:[0-9a-fA-F]{3}){1,2}$/.test(n)||(n=`!${n}`));const i=`https://mermaid.ink/img/${r}?bgColor=${n}&type=${a}`,s=await fetch(i);if(!s.ok)throw new Error(["Failed to render the graph using the Mermaid.INK API.",`Status code: ${s.status}`,`Status text: ${s.statusText}`].join(`
|
|
68
|
-
`));return await s.blob()}const Ac=Symbol("Let zodToJsonSchema decide on which parser to use"),Ic={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},Oc=e=>({...Ic,...e}),Cc=e=>{const t=Oc(e),n=t.name!==void 0?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,flags:{hasReferencedOpenAiAnyType:!1},currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([a,r])=>[r._def,{def:r._def,path:[...t.basePath,t.definitionPath,a],jsonSchema:void 0}]))}},Er=(e,t)=>{let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];n++);return[(e.length-n).toString(),...t.slice(n)].join("/")};function W(e){if(e.target!=="openAi")return{};const t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy==="relative"?Er(t,e.currentPath):t.join("/")}}function Tr(e,t,n,a){a?.errorMessages&&n&&(e.errorMessage={...e.errorMessage,[t]:n})}function x(e,t,n,a,r){e[t]=n,Tr(e,t,a,r)}function xc(e,t){const n={type:"array"};return e.type?._def&&e.type?._def?.typeName!==T.ZodAny&&(n.items=C(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&x(n,"minItems",e.minLength.value,e.minLength.message,t),e.maxLength&&x(n,"maxItems",e.maxLength.value,e.maxLength.message,t),e.exactLength&&(x(n,"minItems",e.exactLength.value,e.exactLength.message,t),x(n,"maxItems",e.exactLength.value,e.exactLength.message,t)),n}function kc(e,t){const n={type:"integer",format:"int64"};if(!e.checks)return n;for(const a of e.checks)switch(a.kind){case"min":t.target==="jsonSchema7"?a.inclusive?x(n,"minimum",a.value,a.message,t):x(n,"exclusiveMinimum",a.value,a.message,t):(a.inclusive||(n.exclusiveMinimum=!0),x(n,"minimum",a.value,a.message,t));break;case"max":t.target==="jsonSchema7"?a.inclusive?x(n,"maximum",a.value,a.message,t):x(n,"exclusiveMaximum",a.value,a.message,t):(a.inclusive||(n.exclusiveMaximum=!0),x(n,"maximum",a.value,a.message,t));break;case"multipleOf":x(n,"multipleOf",a.value,a.message,t);break}return n}function Rc(){return{type:"boolean"}}function Ar(e,t){return C(e.type._def,t)}const Nc=(e,t)=>C(e.innerType._def,t);function Ir(e,t,n){const a=n??t.dateStrategy;if(Array.isArray(a))return{anyOf:a.map(r=>Ir(e,t,r))};switch(a){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return Pc(e,t)}}const Pc=(e,t)=>{const n={type:"integer",format:"unix-time"};if(t.target==="openApi3")return n;for(const a of e.checks)switch(a.kind){case"min":x(n,"minimum",a.value,a.message,t);break;case"max":x(n,"maximum",a.value,a.message,t);break}return n};function $c(e,t){return{...C(e.innerType._def,t),default:e.defaultValue()}}function Mc(e,t){return t.effectStrategy==="input"?C(e.schema._def,t):W(t)}function Lc(e){return{type:"string",enum:Array.from(e.values)}}const jc=e=>"type"in e&&e.type==="string"?!1:"allOf"in e;function Dc(e,t){const n=[C(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),C(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(i=>!!i);let a=t.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0;const r=[];return n.forEach(i=>{if(jc(i))r.push(...i.allOf),i.unevaluatedProperties===void 0&&(a=void 0);else{let s=i;if("additionalProperties"in i&&i.additionalProperties===!1){const{additionalProperties:o,...c}=i;s=c}else a=void 0;r.push(s)}}),r.length?{allOf:r,...a}:void 0}function Uc(e,t){const n=typeof e.value;return n!=="bigint"&&n!=="number"&&n!=="boolean"&&n!=="string"?{type:Array.isArray(e.value)?"array":"object"}:t.target==="openApi3"?{type:n==="bigint"?"integer":n,enum:[e.value]}:{type:n==="bigint"?"integer":n,const:e.value}}let Bt;const ee={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(Bt===void 0&&(Bt=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Bt),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function Or(e,t){const n={type:"string"};if(e.checks)for(const a of e.checks)switch(a.kind){case"min":x(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,a.value):a.value,a.message,t);break;case"max":x(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,a.value):a.value,a.message,t);break;case"email":switch(t.emailStrategy){case"format:email":te(n,"email",a.message,t);break;case"format:idn-email":te(n,"idn-email",a.message,t);break;case"pattern:zod":H(n,ee.email,a.message,t);break}break;case"url":te(n,"uri",a.message,t);break;case"uuid":te(n,"uuid",a.message,t);break;case"regex":H(n,a.regex,a.message,t);break;case"cuid":H(n,ee.cuid,a.message,t);break;case"cuid2":H(n,ee.cuid2,a.message,t);break;case"startsWith":H(n,RegExp(`^${zt(a.value,t)}`),a.message,t);break;case"endsWith":H(n,RegExp(`${zt(a.value,t)}$`),a.message,t);break;case"datetime":te(n,"date-time",a.message,t);break;case"date":te(n,"date",a.message,t);break;case"time":te(n,"time",a.message,t);break;case"duration":te(n,"duration",a.message,t);break;case"length":x(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,a.value):a.value,a.message,t),x(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,a.value):a.value,a.message,t);break;case"includes":H(n,RegExp(zt(a.value,t)),a.message,t);break;case"ip":a.version!=="v6"&&te(n,"ipv4",a.message,t),a.version!=="v4"&&te(n,"ipv6",a.message,t);break;case"base64url":H(n,ee.base64url,a.message,t);break;case"jwt":H(n,ee.jwt,a.message,t);break;case"cidr":a.version!=="v6"&&H(n,ee.ipv4Cidr,a.message,t),a.version!=="v4"&&H(n,ee.ipv6Cidr,a.message,t);break;case"emoji":H(n,ee.emoji(),a.message,t);break;case"ulid":H(n,ee.ulid,a.message,t);break;case"base64":switch(t.base64Strategy){case"format:binary":te(n,"binary",a.message,t);break;case"contentEncoding:base64":x(n,"contentEncoding","base64",a.message,t);break;case"pattern:zod":H(n,ee.base64,a.message,t);break}break;case"nanoid":H(n,ee.nanoid,a.message,t);break}return n}function zt(e,t){return t.patternStrategy==="escape"?Bc(e):e}const Fc=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Bc(e){let t="";for(let n=0;n<e.length;n++)Fc.has(e[n])||(t+="\\"),t+=e[n];return t}function te(e,t,n,a){e.format||e.anyOf?.some(r=>r.format)?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&a.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.anyOf.push({format:t,...n&&a.errorMessages&&{errorMessage:{format:n}}})):x(e,"format",t,n,a)}function H(e,t,n,a){e.pattern||e.allOf?.some(r=>r.pattern)?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&a.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.allOf.push({pattern:ta(t,a),...n&&a.errorMessages&&{errorMessage:{pattern:n}}})):x(e,"pattern",ta(t,a),n,a)}function ta(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;const n={i:e.flags.includes("i"),m:e.flags.includes("m"),s:e.flags.includes("s")},a=n.i?e.source.toLowerCase():e.source;let r="",i=!1,s=!1,o=!1;for(let c=0;c<a.length;c++){if(i){r+=a[c],i=!1;continue}if(n.i){if(s){if(a[c].match(/[a-z]/)){o?(r+=a[c],r+=`${a[c-2]}-${a[c]}`.toUpperCase(),o=!1):a[c+1]==="-"&&a[c+2]?.match(/[a-z]/)?(r+=a[c],o=!0):r+=`${a[c]}${a[c].toUpperCase()}`;continue}}else if(a[c].match(/[a-z]/)){r+=`[${a[c]}${a[c].toUpperCase()}]`;continue}}if(n.m){if(a[c]==="^"){r+=`(^|(?<=[\r
|
|
69
|
-
]))`;continue}else if(a[c]==="$"){r+=`($|(?=[\r
|
|
70
|
-
]))`;continue}}if(n.s&&a[c]==="."){r+=s?`${a[c]}\r
|
|
71
|
-
`:`[${a[c]}\r
|
|
72
|
-
]`;continue}r+=a[c],a[c]==="\\"?i=!0:s&&a[c]==="]"?s=!1:!s&&a[c]==="["&&(s=!0)}try{new RegExp(r)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return r}function Cr(e,t){if(t.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),t.target==="openApi3"&&e.keyType?._def.typeName===T.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((a,r)=>({...a,[r]:C(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",r]})??W(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};const n={type:"object",additionalProperties:C(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if(t.target==="openApi3")return n;if(e.keyType?._def.typeName===T.ZodString&&e.keyType._def.checks?.length){const{type:a,...r}=Or(e.keyType._def,t);return{...n,propertyNames:r}}else{if(e.keyType?._def.typeName===T.ZodEnum)return{...n,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===T.ZodBranded&&e.keyType._def.type._def.typeName===T.ZodString&&e.keyType._def.type._def.checks?.length){const{type:a,...r}=Ar(e.keyType._def,t);return{...n,propertyNames:r}}}return n}function zc(e,t){if(t.mapStrategy==="record")return Cr(e,t);const n=C(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||W(t),a=C(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||W(t);return{type:"array",maxItems:125,items:{type:"array",items:[n,a],minItems:2,maxItems:2}}}function Hc(e){const t=e.values,a=Object.keys(e.values).filter(i=>typeof t[t[i]]!="number").map(i=>t[i]),r=Array.from(new Set(a.map(i=>typeof i)));return{type:r.length===1?r[0]==="string"?"string":"number":["string","number"],enum:a}}function Gc(e){return e.target==="openAi"?void 0:{not:W({...e,currentPath:[...e.currentPath,"not"]})}}function Zc(e){return e.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}const _t={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function qc(e,t){if(t.target==="openApi3")return na(e,t);const n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(a=>a._def.typeName in _t&&(!a._def.checks||!a._def.checks.length))){const a=n.reduce((r,i)=>{const s=_t[i._def.typeName];return s&&!r.includes(s)?[...r,s]:r},[]);return{type:a.length>1?a:a[0]}}else if(n.every(a=>a._def.typeName==="ZodLiteral"&&!a.description)){const a=n.reduce((r,i)=>{const s=typeof i._def.value;switch(s){case"string":case"number":case"boolean":return[...r,s];case"bigint":return[...r,"integer"];case"object":return i._def.value===null?[...r,"null"]:r;case"symbol":case"undefined":case"function":default:return r}},[]);if(a.length===n.length){const r=a.filter((i,s,o)=>o.indexOf(i)===s);return{type:r.length>1?r:r[0],enum:n.reduce((i,s)=>i.includes(s._def.value)?i:[...i,s._def.value],[])}}}else if(n.every(a=>a._def.typeName==="ZodEnum"))return{type:"string",enum:n.reduce((a,r)=>[...a,...r._def.values.filter(i=>!a.includes(i))],[])};return na(e,t)}const na=(e,t)=>{const n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((a,r)=>C(a._def,{...t,currentPath:[...t.currentPath,"anyOf",`${r}`]})).filter(a=>!!a&&(!t.strictUnions||typeof a=="object"&&Object.keys(a).length>0));return n.length?{anyOf:n}:void 0};function Jc(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return t.target==="openApi3"?{type:_t[e.innerType._def.typeName],nullable:!0}:{type:[_t[e.innerType._def.typeName],"null"]};if(t.target==="openApi3"){const a=C(e.innerType._def,{...t,currentPath:[...t.currentPath]});return a&&"$ref"in a?{allOf:[a],nullable:!0}:a&&{...a,nullable:!0}}const n=C(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}function Vc(e,t){const n={type:"number"};if(!e.checks)return n;for(const a of e.checks)switch(a.kind){case"int":n.type="integer",Tr(n,"type",a.message,t);break;case"min":t.target==="jsonSchema7"?a.inclusive?x(n,"minimum",a.value,a.message,t):x(n,"exclusiveMinimum",a.value,a.message,t):(a.inclusive||(n.exclusiveMinimum=!0),x(n,"minimum",a.value,a.message,t));break;case"max":t.target==="jsonSchema7"?a.inclusive?x(n,"maximum",a.value,a.message,t):x(n,"exclusiveMaximum",a.value,a.message,t):(a.inclusive||(n.exclusiveMaximum=!0),x(n,"maximum",a.value,a.message,t));break;case"multipleOf":x(n,"multipleOf",a.value,a.message,t);break}return n}function Wc(e,t){const n=t.target==="openAi",a={type:"object",properties:{}},r=[],i=e.shape();for(const o in i){let c=i[o];if(c===void 0||c._def===void 0)continue;let l=Qc(c);l&&n&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),l=!1);const u=C(c._def,{...t,currentPath:[...t.currentPath,"properties",o],propertyPath:[...t.currentPath,"properties",o]});u!==void 0&&(a.properties[o]=u,l||r.push(o))}r.length&&(a.required=r);const s=Kc(e,t);return s!==void 0&&(a.additionalProperties=s),a}function Kc(e,t){if(e.catchall._def.typeName!=="ZodNever")return C(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;case"strip":return t.removeAdditionalStrategy==="strict"?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function Qc(e){try{return e.isOptional()}catch{return!0}}const Yc=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return C(e.innerType._def,t);const n=C(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return n?{anyOf:[{not:W(t)},n]}:W(t)},Xc=(e,t)=>{if(t.pipeStrategy==="input")return C(e.in._def,t);if(t.pipeStrategy==="output")return C(e.out._def,t);const n=C(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),a=C(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",n?"1":"0"]});return{allOf:[n,a].filter(r=>r!==void 0)}};function el(e,t){return C(e.type._def,t)}function tl(e,t){const a={type:"array",uniqueItems:!0,items:C(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&x(a,"minItems",e.minSize.value,e.minSize.message,t),e.maxSize&&x(a,"maxItems",e.maxSize.value,e.maxSize.message,t),a}function nl(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((n,a)=>C(n._def,{...t,currentPath:[...t.currentPath,"items",`${a}`]})).reduce((n,a)=>a===void 0?n:[...n,a],[]),additionalItems:C(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((n,a)=>C(n._def,{...t,currentPath:[...t.currentPath,"items",`${a}`]})).reduce((n,a)=>a===void 0?n:[...n,a],[])}}function al(e){return{not:W(e)}}function rl(e){return W(e)}const il=(e,t)=>C(e.innerType._def,t),sl=(e,t,n)=>{switch(t){case T.ZodString:return Or(e,n);case T.ZodNumber:return Vc(e,n);case T.ZodObject:return Wc(e,n);case T.ZodBigInt:return kc(e,n);case T.ZodBoolean:return Rc();case T.ZodDate:return Ir(e,n);case T.ZodUndefined:return al(n);case T.ZodNull:return Zc(n);case T.ZodArray:return xc(e,n);case T.ZodUnion:case T.ZodDiscriminatedUnion:return qc(e,n);case T.ZodIntersection:return Dc(e,n);case T.ZodTuple:return nl(e,n);case T.ZodRecord:return Cr(e,n);case T.ZodLiteral:return Uc(e,n);case T.ZodEnum:return Lc(e);case T.ZodNativeEnum:return Hc(e);case T.ZodNullable:return Jc(e,n);case T.ZodOptional:return Yc(e,n);case T.ZodMap:return zc(e,n);case T.ZodSet:return tl(e,n);case T.ZodLazy:return()=>e.getter()._def;case T.ZodPromise:return el(e,n);case T.ZodNaN:case T.ZodNever:return Gc(n);case T.ZodEffects:return Mc(e,n);case T.ZodAny:return W(n);case T.ZodUnknown:return rl(n);case T.ZodDefault:return $c(e,n);case T.ZodBranded:return Ar(e,n);case T.ZodReadonly:return il(e,n);case T.ZodCatch:return Nc(e,n);case T.ZodPipeline:return Xc(e,n);case T.ZodFunction:case T.ZodVoid:case T.ZodSymbol:return;default:return(a=>{})()}};function C(e,t,n=!1){const a=t.seen.get(e);if(t.override){const o=t.override?.(e,t,a,n);if(o!==Ac)return o}if(a&&!n){const o=ol(a,t);if(o!==void 0)return o}const r={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,r);const i=sl(e,e.typeName,t),s=typeof i=="function"?C(i(),t):i;if(s&&cl(e,t,s),t.postProcess){const o=t.postProcess(s,e,t);return r.jsonSchema=s,o}return r.jsonSchema=s,s}const ol=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:Er(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every((n,a)=>t.currentPath[a]===n)?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),W(t)):t.$refStrategy==="seen"?W(t):void 0}},cl=(e,t,n)=>(e.description&&(n.description=e.description,t.markdownDescription&&(n.markdownDescription=e.description)),n),ll=(e,t)=>{const n=Cc(t);let a=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((o,[c,l])=>({...o,[c]:C(l._def,{...n,currentPath:[...n.basePath,n.definitionPath,c]},!0)??W(n)}),{}):void 0;const r=typeof t=="string"?t:t?.name,i=C(e._def,n,!1)??W(n);n.flags.hasReferencedOpenAiAnyType&&(a||(a={}),a[n.openAiAnyTypeName]||(a[n.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:n.$refStrategy==="relative"?"1":[...n.basePath,n.definitionPath,n.openAiAnyTypeName].join("/")}}));const s=r===void 0?a?{...i,[n.definitionPath]:a}:i:{$ref:[...n.$refStrategy==="relative"?[]:n.basePath,n.definitionPath,r].join("/"),[n.definitionPath]:{...a,[r]:i}};return n.target==="jsonSchema7"?s.$schema="http://json-schema.org/draft-07/schema#":(n.target==="jsonSchema2019-09"||n.target==="openAi")&&(s.$schema="https://json-schema.org/draft/2019-09/schema#"),n.target==="openAi"&&("anyOf"in s||"oneOf"in s||"allOf"in s||"type"in s&&Array.isArray(s.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),s};var ul={};D(ul,{Validator:()=>Vr,deepCompareStrict:()=>Jr,toJsonSchema:()=>xr,validatesOnlyStrings:()=>ct});function xr(e){if(L(e)){const t=Be(e,!0);if(de(t)){const n=nn(t,!0);return En(n)}else return En(e)}return U(e)?ll(e):e}function ct(e){if(!e||typeof e!="object"||Object.keys(e).length===0||Array.isArray(e))return!1;if("type"in e)return typeof e.type=="string"?e.type==="string":Array.isArray(e.type)?e.type.every(t=>t==="string"):!1;if("enum"in e)return Array.isArray(e.enum)&&e.enum.length>0&&e.enum.every(t=>typeof t=="string");if("const"in e)return typeof e.const=="string";if("allOf"in e&&Array.isArray(e.allOf))return e.allOf.some(t=>ct(t));if("anyOf"in e&&Array.isArray(e.anyOf)||"oneOf"in e&&Array.isArray(e.oneOf)){const t="anyOf"in e?e.anyOf:e.oneOf;return t.length>0&&t.every(n=>ct(n))}if("not"in e)return!1;if("$ref"in e&&typeof e.$ref=="string"){const t=e.$ref,n=Wr(e);return n[t]?ct(n[t]):!1}return!1}var dl={};D(dl,{Graph:()=>vn});function hl(e,t){if(e!==void 0&&!st(e))return e;if(yn(t))try{let n=t.getName();return n=n.startsWith("Runnable")?n.slice(8):n,n}catch{return t.getName()}else return t.name??"UnknownSchema"}function pl(e){return yn(e.data)?{type:"runnable",data:{id:e.data.lc_id,name:e.data.getName()}}:{type:"schema",data:{...xr(e.data.schema),title:e.data.name}}}var vn=class kr{nodes={};edges=[];constructor(t){this.nodes=t?.nodes??this.nodes,this.edges=t?.edges??this.edges}toJSON(){const t={};return Object.values(this.nodes).forEach((n,a)=>{t[n.id]=st(n.id)?a:n.id}),{nodes:Object.values(this.nodes).map(n=>({id:t[n.id],...pl(n)})),edges:this.edges.map(n=>{const a={source:t[n.source],target:t[n.target]};return typeof n.data<"u"&&(a.data=n.data),typeof n.conditional<"u"&&(a.conditional=n.conditional),a})}}addNode(t,n,a){if(n!==void 0&&this.nodes[n]!==void 0)throw new Error(`Node with id ${n} already exists`);const r=n??G(),i={id:r,data:t,name:hl(n,t),metadata:a};return this.nodes[r]=i,i}removeNode(t){delete this.nodes[t.id],this.edges=this.edges.filter(n=>n.source!==t.id&&n.target!==t.id)}addEdge(t,n,a,r){if(this.nodes[t.id]===void 0)throw new Error(`Source node ${t.id} not in graph`);if(this.nodes[n.id]===void 0)throw new Error(`Target node ${n.id} not in graph`);const i={source:t.id,target:n.id,data:a,conditional:r};return this.edges.push(i),i}firstNode(){return aa(this)}lastNode(){return ra(this)}extend(t,n=""){let a=n;Object.values(t.nodes).map(l=>l.id).every(st)&&(a="");const i=l=>a?`${a}:${l}`:l;Object.entries(t.nodes).forEach(([l,u])=>{this.nodes[i(l)]={...u,id:i(l)}});const s=t.edges.map(l=>({...l,source:i(l.source),target:i(l.target)}));this.edges=[...this.edges,...s];const o=t.firstNode(),c=t.lastNode();return[o?{id:i(o.id),data:o.data}:void 0,c?{id:i(c.id),data:c.data}:void 0]}trimFirstNode(){const t=this.firstNode();t&&aa(this,[t.id])&&this.removeNode(t)}trimLastNode(){const t=this.lastNode();t&&ra(this,[t.id])&&this.removeNode(t)}reid(){const t=Object.fromEntries(Object.values(this.nodes).map(r=>[r.id,r.name])),n=new Map;Object.values(t).forEach(r=>{n.set(r,(n.get(r)||0)+1)});const a=r=>{const i=t[r];return st(r)&&n.get(i)===1?i:r};return new kr({nodes:Object.fromEntries(Object.entries(this.nodes).map(([r,i])=>[a(r),{...i,id:a(r)}])),edges:this.edges.map(r=>({...r,source:a(r.source),target:a(r.target)}))})}drawMermaid(t){const{withStyles:n,curveStyle:a,nodeColors:r={default:"fill:#f2f0ff,line-height:1.2",first:"fill-opacity:0",last:"fill:#bfb6fc"},wrapLabelNWords:i}=t??{},s=this.reid(),o=s.firstNode(),c=s.lastNode();return Ec(s.nodes,s.edges,{firstNode:o?.id,lastNode:c?.id,withStyles:n,curveStyle:a,nodeColors:r,wrapLabelNWords:i})}async drawMermaidPng(t){const n=this.drawMermaid(t);return Tc(n,{backgroundColor:t?.backgroundColor})}};function aa(e,t=[]){const n=new Set(e.edges.filter(r=>!t.includes(r.source)).map(r=>r.target)),a=[];for(const r of Object.values(e.nodes))!t.includes(r.id)&&!n.has(r.id)&&a.push(r);return a.length===1?a[0]:void 0}function ra(e,t=[]){const n=new Set(e.edges.filter(r=>!t.includes(r.target)).map(r=>r.source)),a=[];for(const r of Object.values(e.nodes))!t.includes(r.id)&&!n.has(r.id)&&a.push(r);return a.length===1?a[0]:void 0}function fl(e){const t=new TextEncoder,n=new ReadableStream({async start(a){for await(const r of e)a.enqueue(t.encode(`event: data
|
|
73
|
-
data: ${JSON.stringify(r)}
|
|
74
|
-
|
|
75
|
-
`));a.enqueue(t.encode(`event: end
|
|
76
|
-
|
|
77
|
-
`)),a.close()}});return re.fromReadableStream(n)}function ia(e){return typeof e=="object"&&e!==null&&typeof e[Symbol.iterator]=="function"&&typeof e.next=="function"}const ml=e=>e!=null&&typeof e=="object"&&"next"in e&&typeof e.next=="function";function an(e){return typeof e=="object"&&e!==null&&typeof e[Symbol.asyncIterator]=="function"}function*sa(e,t){for(;;){const{value:n,done:a}=he.runWithConfig($e(e),t.next.bind(t),!0);if(a)break;yield n}}async function*rn(e,t){const n=t[Symbol.asyncIterator]();for(;;){const{value:a,done:r}=await he.runWithConfig($e(e),n.next.bind(t),!0);if(r)break;yield a}}function j(e,t){return e&&!Array.isArray(e)&&!(e instanceof Date)&&typeof e=="object"?e:{[t]:e}}var V=class extends Ge{lc_runnable=!0;name;getName(e){const t=this.name??this.constructor.lc_name()??this.constructor.name;return e?`${t}${e}`:t}withRetry(e){return new Pr({bound:this,kwargs:{},config:{},maxAttemptNumber:e?.stopAfterAttempt,...e})}withConfig(e){return new yt({bound:this,config:e,kwargs:{}})}withFallbacks(e){const t=Array.isArray(e)?e:e.fallbacks;return new yl({runnable:this,fallbacks:t})}_getOptionsList(e,t=0){if(Array.isArray(e)&&e.length!==t)throw new Error(`Passed "options" must be an array with the same length as the inputs, but got ${e.length} options for ${t} inputs`);if(Array.isArray(e))return e.map(k);if(t>1&&!Array.isArray(e)&&e.runId){console.warn("Provided runId will be used only for the first element of the batch.");const n=Object.fromEntries(Object.entries(e).filter(([a])=>a!=="runId"));return Array.from({length:t},(a,r)=>k(r===0?e:n))}return Array.from({length:t},()=>k(e))}async batch(e,t,n){const a=this._getOptionsList(t??{},e.length),r=a[0]?.maxConcurrency??n?.maxConcurrency,i=new wr({maxConcurrency:r,onFailedAttempt:o=>{throw o}}),s=e.map((o,c)=>i.call(async()=>{try{return await this.invoke(o,a[c])}catch(l){if(n?.returnExceptions)return l;throw l}}));return Promise.all(s)}async*_streamIterator(e,t){yield this.invoke(e,t)}async stream(e,t){const n=k(t),a=new Ce({generator:this._streamIterator(e,n),config:n});return await a.setup,re.fromAsyncGenerator(a)}_separateRunnableConfigFromCallOptions(e){let t;e===void 0?t=k(e):t=k({callbacks:e.callbacks,tags:e.tags,metadata:e.metadata,runName:e.runName,configurable:e.configurable,recursionLimit:e.recursionLimit,maxConcurrency:e.maxConcurrency,runId:e.runId,timeout:e.timeout,signal:e.signal});const n={...e};return delete n.callbacks,delete n.tags,delete n.metadata,delete n.runName,delete n.configurable,delete n.recursionLimit,delete n.maxConcurrency,delete n.runId,delete n.timeout,delete n.signal,[t,n]}async _callWithConfig(e,t,n){const a=k(n),i=await(await ae(a))?.handleChainStart(this.toJSON(),j(t,"input"),a.runId,a?.runType,void 0,void 0,a?.runName??this.getName());delete a.runId;let s;try{const o=e.call(this,t,a,i);s=await ye(o,n?.signal)}catch(o){throw await i?.handleChainError(o),o}return await i?.handleChainEnd(j(s,"output")),s}async _batchWithConfig(e,t,n,a){const r=this._getOptionsList(n??{},t.length),i=await Promise.all(r.map(ae)),s=await Promise.all(i.map(async(c,l)=>{const u=await c?.handleChainStart(this.toJSON(),j(t[l],"input"),r[l].runId,r[l].runType,void 0,void 0,r[l].runName??this.getName());return delete r[l].runId,u}));let o;try{const c=e.call(this,t,r,s,a);o=await ye(c,r?.[0]?.signal)}catch(c){throw await Promise.all(s.map(l=>l?.handleChainError(c))),c}return await Promise.all(s.map(c=>c?.handleChainEnd(j(o,"output")))),o}_concatOutputChunks(e,t){return gn(e,t)}async*_transformStreamWithConfig(e,t,n){let a,r=!0,i,s=!0;const o=k(n),c=await ae(o),l=this;async function*u(){for await(const d of e){if(r)if(a===void 0)a=d;else try{a=l._concatOutputChunks(a,d)}catch{a=void 0,r=!1}yield d}}let h;try{const d=await pr(t.bind(this),u(),async()=>c?.handleChainStart(this.toJSON(),{input:""},o.runId,o.runType,void 0,void 0,o.runName??this.getName()),n?.signal,o);delete o.runId,h=d.setup;const p=h?.handlers.find(cc);let f=d.output;p!==void 0&&h!==void 0&&(f=p.tapOutputIterable(h.runId,f));const A=h?.handlers.find(gr);A!==void 0&&h!==void 0&&(f=A.tapOutputIterable(h.runId,f));for await(const y of f)if(yield y,s)if(i===void 0)i=y;else try{i=this._concatOutputChunks(i,y)}catch{i=void 0,s=!1}}catch(d){throw await h?.handleChainError(d,void 0,void 0,void 0,{inputs:j(a,"input")}),d}await h?.handleChainEnd(i??{},void 0,void 0,void 0,{inputs:j(a,"input")})}getGraph(e){const t=new vn,n=t.addNode({name:`${this.getName()}Input`,schema:Tn()}),a=t.addNode(this),r=t.addNode({name:`${this.getName()}Output`,schema:Tn()});return t.addEdge(n,a),t.addEdge(a,r),t}pipe(e){return new $r({first:this,last:we(e)})}pick(e){return this.pipe(new vl(e))}assign(e){return this.pipe(new wl(new It({steps:e})))}async*transform(e,t){let n;for await(const a of e)n===void 0?n=a:n=this._concatOutputChunks(n,a);yield*this._streamIterator(n,k(t))}async*streamLog(e,t,n){const a=new tn({...n,autoClose:!1,_schemaFormat:"original"}),r=k(t);yield*this._streamLog(e,a,r)}async*_streamLog(e,t,n){const{callbacks:a}=n;if(a===void 0)n.callbacks=[t];else if(Array.isArray(a))n.callbacks=a.concat([t]);else{const o=a.copy();o.addHandler(t,!0),n.callbacks=o}const r=this.stream(e,n);async function i(){try{const o=await r;for await(const c of o){const l=new le({ops:[{op:"add",path:"/streamed_output/-",value:c}]});await t.writer.write(l)}}finally{await t.writer.close()}}const s=i();try{for await(const o of t)yield o}finally{await s}}streamEvents(e,t,n){let a;if(t.version==="v1")a=this._streamEventsV1(e,t,n);else if(t.version==="v2")a=this._streamEventsV2(e,t,n);else throw new Error('Only versions "v1" and "v2" of the schema are currently supported.');return t.encoding==="text/event-stream"?fl(a):re.fromAsyncGenerator(a)}async*_streamEventsV2(e,t,n){const a=new lc({...n,autoClose:!1}),r=k(t),i=r.runId??G();r.runId=i;const s=r.callbacks;if(s===void 0)r.callbacks=[a];else if(Array.isArray(s))r.callbacks=s.concat(a);else{const p=s.copy();p.addHandler(a,!0),r.callbacks=p}const o=new AbortController,c=this;async function l(){let p,f=null;try{t?.signal?"any"in AbortSignal?p=AbortSignal.any([o.signal,t.signal]):(p=t.signal,f=()=>{o.abort()},t.signal.addEventListener("abort",f,{once:!0})):p=o.signal;const A=await c.stream(e,{...r,signal:p}),y=a.tapOutputIterable(i,A);for await(const g of y)if(o.signal.aborted)break}finally{await a.finish(),p&&f&&p.removeEventListener("abort",f)}}const u=l();let h=!1,d;try{for await(const p of a){if(!h){p.data.input=e,h=!0,d=p.run_id,yield p;continue}p.run_id===d&&p.event.endsWith("_end")&&p.data?.input&&delete p.data.input,yield p}}finally{o.abort(),await u}}async*_streamEventsV1(e,t,n){let a,r=!1;const i=k(t),s=i.tags??[],o=i.metadata??{},c=i.runName??this.getName(),l=new tn({...n,autoClose:!1,_schemaFormat:"streaming_events"}),u=new pc({...n}),h=this._streamLog(e,l,i);for await(const p of h){if(a?a=a.concat(p):a=_n.fromRunLogPatch(p),a.state===void 0)throw new Error('Internal error: "streamEvents" state is missing. Please open a bug report.');if(!r){r=!0;const g={...a.state},v={run_id:g.id,event:`on_${g.type}_start`,name:c,tags:s,metadata:o,data:{input:e}};u.includeEvent(v,g.type)&&(yield v)}const f=p.ops.filter(g=>g.path.startsWith("/logs/")).map(g=>g.path.split("/")[2]),A=[...new Set(f)];for(const g of A){let v,E={};const I=a.state.logs[g];if(I.end_time===void 0?I.streamed_output.length>0?v="stream":v="start":v="end",v==="start")I.inputs!==void 0&&(E.input=I.inputs);else if(v==="end")I.inputs!==void 0&&(E.input=I.inputs),E.output=I.final_output;else if(v==="stream"){const O=I.streamed_output.length;if(O!==1)throw new Error(`Expected exactly one chunk of streamed output, got ${O} instead. Encountered in: "${I.name}"`);E={chunk:I.streamed_output[0]},I.streamed_output=[]}yield{event:`on_${I.type}_${v}`,name:I.name,run_id:I.id,tags:I.tags,metadata:I.metadata,data:E}}const{state:y}=a;if(y.streamed_output.length>0){const g=y.streamed_output.length;if(g!==1)throw new Error(`Expected exactly one chunk of streamed output, got ${g} instead. Encountered in: "${y.name}"`);const v={chunk:y.streamed_output[0]};y.streamed_output=[];const E={event:`on_${y.type}_stream`,run_id:y.id,tags:s,metadata:o,name:c,data:v};u.includeEvent(E,y.type)&&(yield E)}}const d=a?.state;if(d!==void 0){const p={event:`on_${d.type}_end`,name:c,run_id:d.id,tags:s,metadata:o,data:{output:d.final_output}};u.includeEvent(p,d.type)&&(yield p)}}static isRunnable(e){return yn(e)}withListeners({onStart:e,onEnd:t,onError:n}){return new yt({bound:this,config:{},configFactories:[a=>({callbacks:[new vr({config:a,onStart:e,onEnd:t,onError:n})]})]})}asTool(e){return bl(this,e)}},yt=class Rr extends V{static lc_name(){return"RunnableBinding"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;bound;config;kwargs;configFactories;constructor(t){super(t),this.bound=t.bound,this.kwargs=t.kwargs,this.config=t.config,this.configFactories=t.configFactories}getName(t){return this.bound.getName(t)}async _mergeConfig(...t){const n=Wn(this.config,...t);return Wn(n,...this.configFactories?await Promise.all(this.configFactories.map(async a=>await a(n))):[])}withConfig(t){return new this.constructor({bound:this.bound,kwargs:this.kwargs,config:{...this.config,...t}})}withRetry(t){return new Pr({bound:this.bound,kwargs:this.kwargs,config:this.config,maxAttemptNumber:t?.stopAfterAttempt,...t})}async invoke(t,n){return this.bound.invoke(t,await this._mergeConfig(n,this.kwargs))}async batch(t,n,a){const r=Array.isArray(n)?await Promise.all(n.map(async i=>this._mergeConfig(k(i),this.kwargs))):await this._mergeConfig(k(n),this.kwargs);return this.bound.batch(t,r,a)}_concatOutputChunks(t,n){return this.bound._concatOutputChunks(t,n)}async*_streamIterator(t,n){yield*this.bound._streamIterator(t,await this._mergeConfig(k(n),this.kwargs))}async stream(t,n){return this.bound.stream(t,await this._mergeConfig(k(n),this.kwargs))}async*transform(t,n){yield*this.bound.transform(t,await this._mergeConfig(k(n),this.kwargs))}streamEvents(t,n,a){const r=this,i=async function*(){yield*r.bound.streamEvents(t,{...await r._mergeConfig(k(n),r.kwargs),version:n.version},a)};return re.fromAsyncGenerator(i())}static isRunnableBinding(t){return t.bound&&V.isRunnable(t.bound)}withListeners({onStart:t,onEnd:n,onError:a}){return new Rr({bound:this.bound,kwargs:this.kwargs,config:this.config,configFactories:[r=>({callbacks:[new vr({config:r,onStart:t,onEnd:n,onError:a})]})]})}},Kl=class Nr extends V{static lc_name(){return"RunnableEach"}lc_serializable=!0;lc_namespace=["langchain_core","runnables"];bound;constructor(t){super(t),this.bound=t.bound}async invoke(t,n){return this._callWithConfig(this._invoke.bind(this),t,n)}async _invoke(t,n,a){return this.bound.batch(t,F(n,{callbacks:a?.getChild()}))}withListeners({onStart:t,onEnd:n,onError:a}){return new Nr({bound:this.bound.withListeners({onStart:t,onEnd:n,onError:a})})}},Pr=class extends yt{static lc_name(){return"RunnableRetry"}lc_namespace=["langchain_core","runnables"];maxAttemptNumber=3;onFailedAttempt=()=>{};constructor(e){super(e),this.maxAttemptNumber=e.maxAttemptNumber??this.maxAttemptNumber,this.onFailedAttempt=e.onFailedAttempt??this.onFailedAttempt}_patchConfigForRetry(e,t,n){const a=e>1?`retry:attempt:${e}`:void 0;return F(t,{callbacks:n?.getChild(a)})}async _invoke(e,t,n){return lt(a=>super.invoke(e,this._patchConfigForRetry(a,t,n)),{onFailedAttempt:a=>this.onFailedAttempt(a,e),retries:Math.max(this.maxAttemptNumber-1,0),randomize:!0})}async invoke(e,t){return this._callWithConfig(this._invoke.bind(this),e,t)}async _batch(e,t,n,a){const r={};try{await lt(async i=>{const s=e.map((h,d)=>d).filter(h=>r[h.toString()]===void 0||r[h.toString()]instanceof Error),o=s.map(h=>e[h]),c=s.map(h=>this._patchConfigForRetry(i,t?.[h],n?.[h])),l=await super.batch(o,c,{...a,returnExceptions:!0});let u;for(let h=0;h<l.length;h+=1){const d=l[h],p=s[h];d instanceof Error&&u===void 0&&(u=d,u.input=o[h]),r[p.toString()]=d}if(u)throw u;return l},{onFailedAttempt:i=>this.onFailedAttempt(i,i.input),retries:Math.max(this.maxAttemptNumber-1,0),randomize:!0})}catch(i){if(a?.returnExceptions!==!0)throw i}return Object.keys(r).sort((i,s)=>parseInt(i,10)-parseInt(s,10)).map(i=>r[parseInt(i,10)])}async batch(e,t,n){return this._batchWithConfig(this._batch.bind(this),e,t,n)}},$r=class ze extends V{static lc_name(){return"RunnableSequence"}first;middle=[];last;omitSequenceTags=!1;lc_serializable=!0;lc_namespace=["langchain_core","runnables"];constructor(t){super(t),this.first=t.first,this.middle=t.middle??this.middle,this.last=t.last,this.name=t.name,this.omitSequenceTags=t.omitSequenceTags??this.omitSequenceTags}get steps(){return[this.first,...this.middle,this.last]}async invoke(t,n){const a=k(n),i=await(await ae(a))?.handleChainStart(this.toJSON(),j(t,"input"),a.runId,void 0,void 0,void 0,a?.runName);delete a.runId;let s=t,o;try{const c=[this.first,...this.middle];for(let l=0;l<c.length;l+=1){const h=c[l].invoke(s,F(a,{callbacks:i?.getChild(this.omitSequenceTags?void 0:`seq:step:${l+1}`)}));s=await ye(h,n?.signal)}if(n?.signal?.aborted)throw pt(n.signal);o=await this.last.invoke(s,F(a,{callbacks:i?.getChild(this.omitSequenceTags?void 0:`seq:step:${this.steps.length}`)}))}catch(c){throw await i?.handleChainError(c),c}return await i?.handleChainEnd(j(o,"output")),o}async batch(t,n,a){const r=this._getOptionsList(n??{},t.length),i=await Promise.all(r.map(ae)),s=await Promise.all(i.map(async(c,l)=>{const u=await c?.handleChainStart(this.toJSON(),j(t[l],"input"),r[l].runId,void 0,void 0,void 0,r[l].runName);return delete r[l].runId,u}));let o=t;try{for(let c=0;c<this.steps.length;c+=1){const u=this.steps[c].batch(o,s.map((h,d)=>{const p=h?.getChild(this.omitSequenceTags?void 0:`seq:step:${c+1}`);return F(r[d],{callbacks:p})}),a);o=await ye(u,r[0]?.signal)}}catch(c){throw await Promise.all(s.map(l=>l?.handleChainError(c))),c}return await Promise.all(s.map(c=>c?.handleChainEnd(j(o,"output")))),o}_concatOutputChunks(t,n){return this.last._concatOutputChunks(t,n)}async*_streamIterator(t,n){const a=await ae(n),{runId:r,...i}=n??{},s=await a?.handleChainStart(this.toJSON(),j(t,"input"),r,void 0,void 0,void 0,i?.runName),o=[this.first,...this.middle,this.last];let c=!0,l;async function*u(){yield t}try{let h=o[0].transform(u(),F(i,{callbacks:s?.getChild(this.omitSequenceTags?void 0:"seq:step:1")}));for(let d=1;d<o.length;d+=1)h=await o[d].transform(h,F(i,{callbacks:s?.getChild(this.omitSequenceTags?void 0:`seq:step:${d+1}`)}));for await(const d of h)if(n?.signal?.throwIfAborted(),yield d,c)if(l===void 0)l=d;else try{l=this._concatOutputChunks(l,d)}catch{l=void 0,c=!1}}catch(h){throw await s?.handleChainError(h),h}await s?.handleChainEnd(j(l,"output"))}getGraph(t){const n=new vn;let a=null;return this.steps.forEach((r,i)=>{const s=r.getGraph(t);i!==0&&s.trimFirstNode(),i!==this.steps.length-1&&s.trimLastNode(),n.extend(s);const o=s.firstNode();if(!o)throw new Error(`Runnable ${r} has no first node`);a&&n.addEdge(a,o),a=s.lastNode()}),n}pipe(t){return ze.isRunnableSequence(t)?new ze({first:this.first,middle:this.middle.concat([this.last,t.first,...t.middle]),last:t.last,name:this.name??t.name}):new ze({first:this.first,middle:[...this.middle,this.last],last:we(t),name:this.name})}static isRunnableSequence(t){return Array.isArray(t.middle)&&V.isRunnable(t)}static from([t,...n],a){let r={};return typeof a=="string"?r.name=a:a!==void 0&&(r=a),new ze({...r,first:we(t),middle:n.slice(0,-1).map(we),last:we(n[n.length-1])})}},It=class Mr extends V{static lc_name(){return"RunnableMap"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;steps;getStepsKeys(){return Object.keys(this.steps)}constructor(t){super(t),this.steps={};for(const[n,a]of Object.entries(t.steps))this.steps[n]=we(a)}static from(t){return new Mr({steps:t})}async invoke(t,n){const a=k(n),i=await(await ae(a))?.handleChainStart(this.toJSON(),{input:t},a.runId,void 0,void 0,void 0,a?.runName);delete a.runId;const s={};try{const o=Object.entries(this.steps).map(async([c,l])=>{s[c]=await l.invoke(t,F(a,{callbacks:i?.getChild(`map:key:${c}`)}))});await ye(Promise.all(o),n?.signal)}catch(o){throw await i?.handleChainError(o),o}return await i?.handleChainEnd(s),s}async*_transform(t,n,a){const r={...this.steps},i=mn(t,Object.keys(r).length),s=new Map(Object.entries(r).map(([o,c],l)=>{const u=c.transform(i[l],F(a,{callbacks:n?.getChild(`map:key:${o}`)}));return[o,u.next().then(h=>({key:o,gen:u,result:h}))]}));for(;s.size;){const o=Promise.race(s.values()),{key:c,result:l,gen:u}=await ye(o,a?.signal);s.delete(c),l.done||(yield{[c]:l.value},s.set(c,u.next().then(h=>({key:c,gen:u,result:h}))))}}transform(t,n){return this._transformStreamWithConfig(t,this._transform.bind(this),n)}async stream(t,n){async function*a(){yield t}const r=k(n),i=new Ce({generator:this.transform(a(),r),config:r});return await i.setup,re.fromAsyncGenerator(i)}},gl=class Lr extends V{lc_serializable=!1;lc_namespace=["langchain_core","runnables"];func;constructor(t){if(super(t),!fn(t.func))throw new Error("RunnableTraceable requires a function that is wrapped in traceable higher-order function");this.func=t.func}async invoke(t,n){const[a]=this._getOptionsList(n??{},1),r=await ae(a),i=this.func(F(a,{callbacks:r}),t);return ye(i,a?.signal)}async*_streamIterator(t,n){const[a]=this._getOptionsList(n??{},1),r=await this.invoke(t,n);if(an(r)){for await(const i of r)a?.signal?.throwIfAborted(),yield i;return}if(ml(r)){for(;;){a?.signal?.throwIfAborted();const i=r.next();if(i.done)break;yield i.value}return}yield r}static from(t){return new Lr({func:t})}};function _l(e){if(fn(e))throw new Error("RunnableLambda requires a function that is not wrapped in traceable higher-order function. This shouldn't happen.")}var tt=class jr extends V{static lc_name(){return"RunnableLambda"}lc_namespace=["langchain_core","runnables"];func;constructor(t){if(fn(t.func))return gl.from(t.func);super(t),_l(t.func),this.func=t.func}static from(t){return new jr({func:t})}async _invoke(t,n,a){return new Promise((r,i)=>{const s=F(n,{callbacks:a?.getChild(),recursionLimit:(n?.recursionLimit??Ut)-1});he.runWithConfig($e(s),async()=>{try{let o=await this.func(t,{...s});if(o&&V.isRunnable(o)){if(n?.recursionLimit===0)throw new Error("Recursion limit reached.");o=await o.invoke(t,{...s,recursionLimit:(s.recursionLimit??Ut)-1})}else if(an(o)){let c;for await(const l of rn(s,o))if(n?.signal?.throwIfAborted(),c===void 0)c=l;else try{c=this._concatOutputChunks(c,l)}catch{c=l}o=c}else if(ia(o)){let c;for(const l of sa(s,o))if(n?.signal?.throwIfAborted(),c===void 0)c=l;else try{c=this._concatOutputChunks(c,l)}catch{c=l}o=c}r(o)}catch(o){i(o)}})})}async invoke(t,n){return this._callWithConfig(this._invoke.bind(this),t,n)}async*_transform(t,n,a){let r;for await(const o of t)if(r===void 0)r=o;else try{r=this._concatOutputChunks(r,o)}catch{r=o}const i=F(a,{callbacks:n?.getChild(),recursionLimit:(a?.recursionLimit??Ut)-1}),s=await new Promise((o,c)=>{he.runWithConfig($e(i),async()=>{try{const l=await this.func(r,{...i,config:i});o(l)}catch(l){c(l)}})});if(s&&V.isRunnable(s)){if(a?.recursionLimit===0)throw new Error("Recursion limit reached.");const o=await s.stream(r,i);for await(const c of o)yield c}else if(an(s))for await(const o of rn(i,s))a?.signal?.throwIfAborted(),yield o;else if(ia(s))for(const o of sa(i,s))a?.signal?.throwIfAborted(),yield o;else yield s}transform(t,n){return this._transformStreamWithConfig(t,this._transform.bind(this),n)}async stream(t,n){async function*a(){yield t}const r=k(n),i=new Ce({generator:this.transform(a(),r),config:r});return await i.setup,re.fromAsyncGenerator(i)}},Ql=class extends It{},yl=class extends V{static lc_name(){return"RunnableWithFallbacks"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;runnable;fallbacks;constructor(e){super(e),this.runnable=e.runnable,this.fallbacks=e.fallbacks}*runnables(){yield this.runnable;for(const e of this.fallbacks)yield e}async invoke(e,t){const n=k(t),a=await ae(n),{runId:r,...i}=n,s=await a?.handleChainStart(this.toJSON(),j(e,"input"),r,void 0,void 0,void 0,i?.runName),o=F(i,{callbacks:s?.getChild()});return await he.runWithConfig(o,async()=>{let l;for(const u of this.runnables()){n?.signal?.throwIfAborted();try{const h=await u.invoke(e,o);return await s?.handleChainEnd(j(h,"output")),h}catch(h){l===void 0&&(l=h)}}throw l===void 0?new Error("No error stored at end of fallback."):(await s?.handleChainError(l),l)})}async*_streamIterator(e,t){const n=k(t),a=await ae(n),{runId:r,...i}=n,s=await a?.handleChainStart(this.toJSON(),j(e,"input"),r,void 0,void 0,void 0,i?.runName);let o,c;for(const u of this.runnables()){n?.signal?.throwIfAborted();const h=F(i,{callbacks:s?.getChild()});try{const d=await u.stream(e,h);c=rn(h,d);break}catch(d){o===void 0&&(o=d)}}if(c===void 0){const u=o??new Error("No error stored at end of fallback.");throw await s?.handleChainError(u),u}let l;try{for await(const u of c){yield u;try{l=l===void 0?l:this._concatOutputChunks(l,u)}catch{l=void 0}}}catch(u){throw await s?.handleChainError(u),u}await s?.handleChainEnd(j(l,"output"))}async batch(e,t,n){if(n?.returnExceptions)throw new Error("Not implemented.");const a=this._getOptionsList(t??{},e.length),r=await Promise.all(a.map(o=>ae(o))),i=await Promise.all(r.map(async(o,c)=>{const l=await o?.handleChainStart(this.toJSON(),j(e[c],"input"),a[c].runId,void 0,void 0,void 0,a[c].runName);return delete a[c].runId,l}));let s;for(const o of this.runnables()){a[0].signal?.throwIfAborted();try{const c=await o.batch(e,i.map((l,u)=>F(a[u],{callbacks:l?.getChild()})),n);return await Promise.all(i.map((l,u)=>l?.handleChainEnd(j(c[u],"output")))),c}catch(c){s===void 0&&(s=c)}}throw s?(await Promise.all(i.map(o=>o?.handleChainError(s))),s):new Error("No error stored at end of fallbacks.")}};function we(e){if(typeof e=="function")return new tt({func:e});if(V.isRunnable(e))return e;if(!Array.isArray(e)&&typeof e=="object"){const t={};for(const[n,a]of Object.entries(e))t[n]=we(a);return new It({steps:t})}else throw new Error(`Expected a Runnable, function or object.
|
|
78
|
-
Instead got an unsupported type.`)}var wl=class extends V{static lc_name(){return"RunnableAssign"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;mapper;constructor(e){e instanceof It&&(e={mapper:e}),super(e),this.mapper=e.mapper}async invoke(e,t){const n=await this.mapper.invoke(e,t);return{...e,...n}}async*_transform(e,t,n){const a=this.mapper.getStepsKeys(),[r,i]=mn(e),s=this.mapper.transform(i,F(n,{callbacks:t?.getChild()})),o=s.next();for await(const c of r){if(typeof c!="object"||Array.isArray(c))throw new Error(`RunnableAssign can only be used with objects as input, got ${typeof c}`);const l=Object.fromEntries(Object.entries(c).filter(([u])=>!a.includes(u)));Object.keys(l).length>0&&(yield l)}yield(await o).value;for await(const c of s)yield c}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){async function*n(){yield e}const a=k(t),r=new Ce({generator:this.transform(n(),a),config:a});return await r.setup,re.fromAsyncGenerator(r)}},vl=class extends V{static lc_name(){return"RunnablePick"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;keys;constructor(e){(typeof e=="string"||Array.isArray(e))&&(e={keys:e}),super(e),this.keys=e.keys}async _pick(e){if(typeof this.keys=="string")return e[this.keys];{const t=this.keys.map(n=>[n,e[n]]).filter(n=>n[1]!==void 0);return t.length===0?void 0:Object.fromEntries(t)}}async invoke(e,t){return this._callWithConfig(this._pick.bind(this),e,t)}async*_transform(e){for await(const t of e){const n=await this._pick(t);n!==void 0&&(yield n)}}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){async function*n(){yield e}const a=k(t),r=new Ce({generator:this.transform(n(),a),config:a});return await r.setup,re.fromAsyncGenerator(r)}},oa=class extends yt{name;description;schema;constructor(e){const t=$r.from([tt.from(async n=>{let a;if(Ma(n))try{a=await gc(this.schema,n.args)}catch{throw new Gi("Received tool input did not match expected schema",JSON.stringify(n.args))}else a=n;return a}).withConfig({runName:`${e.name}:parse_input`}),e.bound]).withConfig({runName:e.name});super({bound:t,config:e.config??{}}),this.name=e.name,this.description=e.description,this.schema=e.schema}static lc_name(){return"RunnableToolLike"}};function bl(e,t){const n=t.name??e.getName(),a=t.description??_c(t.schema);return yc(t.schema)?new oa({name:n,description:a,schema:Kr({input:Qr()}).transform(r=>r.input),bound:e}):new oa({name:n,description:a,schema:t.schema,bound:e})}const wt=(e,t)=>{const n=[...new Set(t?.map(r=>{if(typeof r=="string")return r;const i=new r({});if(!("getType"in i)||typeof i.getType!="function")throw new Error("Invalid type provided.");return i.getType()}))],a=e.getType();return n.some(r=>r===a)};function Sl(e,t){return Array.isArray(e)?ca(e,t):tt.from(n=>ca(n,e))}function ca(e,t={}){const{includeNames:n,excludeNames:a,includeTypes:r,excludeTypes:i,includeIds:s,excludeIds:o}=t,c=[];for(const l of e)if(!(a&&l.name&&a.includes(l.name))){{if(i&&wt(l,i))continue;if(o&&l.id&&o.includes(l.id))continue}r||s||n?(n&&l.name&&n.some(u=>u===l.name)||r&&wt(l,r)||s&&l.id&&s.some(u=>u===l.id))&&c.push(l):c.push(l)}return c}function El(e){return Array.isArray(e)?la(e):tt.from(la)}function la(e){if(!e.length)return[];const t=[];for(const n of e){const a=n,r=t.pop();if(!r)t.push(a);else if(a.getType()==="tool"||a.getType()!==r.getType())t.push(r,a);else{const i=Gt(r),s=Gt(a),o=i.concat(s);typeof i.content=="string"&&typeof s.content=="string"&&(o.content=`${i.content}
|
|
79
|
-
${s.content}`),t.push(Il(o))}}return t}function Tl(e,t){if(Array.isArray(e)){const n=e;if(!t)throw new Error("Options parameter is required when providing messages.");return ua(n,t)}else{const n=e;return tt.from(a=>ua(a,n)).withConfig({runName:"trim_messages"})}}async function ua(e,t){const{maxTokens:n,tokenCounter:a,strategy:r="last",allowPartial:i=!1,endOn:s,startOn:o,includeSystem:c=!1,textSplitter:l}=t;if(o&&r==="first")throw new Error("`startOn` should only be specified if `strategy` is 'last'.");if(c&&r==="first")throw new Error("`includeSystem` should only be specified if `strategy` is 'last'.");let u;"getNumTokens"in a?u=async d=>(await Promise.all(d.map(f=>a.getNumTokens(f.content)))).reduce((f,A)=>f+A,0):u=async d=>a(d);let h=Ur;if(l&&("splitText"in l?h=l.splitText:h=async d=>l(d)),r==="first")return Dr(e,{maxTokens:n,tokenCounter:u,textSplitter:h,partialStrategy:i?"first":void 0,endOn:s});if(r==="last")return Al(e,{maxTokens:n,tokenCounter:u,textSplitter:h,allowPartial:i,includeSystem:c,startOn:o,endOn:s});throw new Error(`Unrecognized strategy: '${r}'. Must be one of 'first' or 'last'.`)}async function Dr(e,t){const{maxTokens:n,tokenCounter:a,textSplitter:r,partialStrategy:i,endOn:s}=t;let o=[...e],c=0;for(let l=0;l<o.length;l+=1){const u=l>0?o.slice(0,-l):o;if(await a(u)<=n){c=o.length-l;break}}if(c<o.length&&i){let l=!1;if(Array.isArray(o[c].content)){const u=o[c];if(typeof u.content=="string")throw new Error("Expected content to be an array.");const h=u.content.length,d=i==="last"?[...u.content].reverse():u.content;for(let p=1;p<=h;p+=1){const f=i==="first"?d.slice(0,p):d.slice(-p),A=Object.fromEntries(Object.entries(u).filter(([v])=>v!=="type"&&!v.startsWith("lc_"))),y=bn(u.getType(),{...A,content:f}),g=[...o.slice(0,c),y];if(await a(g)<=n)o=g,c+=1,l=!0;else break}l&&i==="last"&&(u.content=[...d].reverse())}if(!l){const u=o[c];let h;if(Array.isArray(u.content)&&u.content.some(d=>typeof d=="string"||d.type==="text")?h=u.content.find(p=>p.type==="text"&&p.text)?.text:typeof u.content=="string"&&(h=u.content),h){const d=await r(h),p=d.length;i==="last"&&d.reverse();for(let f=0;f<p-1;f+=1)if(d.pop(),u.content=d.join(""),await a([...o.slice(0,c),u])<=n){i==="last"&&(u.content=[...d].reverse().join("")),o=[...o.slice(0,c),u],c+=1;break}}}}if(s){const l=Array.isArray(s)?s:[s];for(;c>0&&!wt(o[c-1],l);)c-=1}return o.slice(0,c)}async function Al(e,t){const{allowPartial:n=!1,includeSystem:a=!1,endOn:r,startOn:i,...s}=t;let o=e.map(u=>{const h=Object.fromEntries(Object.entries(u).filter(([d])=>d!=="type"&&!d.startsWith("lc_")));return bn(u.getType(),h,Aa(u))});if(r){const u=Array.isArray(r)?r:[r];for(;o.length>0&&!wt(o[o.length-1],u);)o=o.slice(0,-1)}const c=a&&o[0]?.getType()==="system";let l=c?o.slice(0,1).concat(o.slice(1).reverse()):o.reverse();return l=await Dr(l,{...s,partialStrategy:n?"last":void 0,endOn:i}),c?[l[0],...l.slice(1).reverse()]:l.reverse()}const da={human:{message:je,messageChunk:Tt},ai:{message:Ne,messageChunk:Le},system:{message:_e,messageChunk:Pe},developer:{message:_e,messageChunk:Pe},tool:{message:Me,messageChunk:vt},function:{message:St,messageChunk:Et},generic:{message:Ye,messageChunk:bt},remove:{message:ut,messageChunk:ut}};function bn(e,t,n){let a,r;switch(e){case"human":n?a=new Tt(t):r=new je(t);break;case"ai":if(n){let i={...t};"tool_calls"in i&&(i={...i,tool_call_chunks:i.tool_calls?.map(s=>({...s,type:"tool_call_chunk",index:void 0,args:JSON.stringify(s.args)}))}),a=new Le(i)}else r=new Ne(t);break;case"system":n?a=new Pe(t):r=new _e(t);break;case"developer":n?a=new Pe({...t,additional_kwargs:{...t.additional_kwargs,__openai_role__:"developer"}}):r=new _e({...t,additional_kwargs:{...t.additional_kwargs,__openai_role__:"developer"}});break;case"tool":if("tool_call_id"in t)n?a=new vt(t):r=new Me(t);else throw new Error("Can not convert ToolMessage to ToolMessageChunk if 'tool_call_id' field is not defined.");break;case"function":if(n)a=new Et(t);else{if(!t.name)throw new Error("FunctionMessage must have a 'name' field");r=new St(t)}break;case"generic":if("role"in t)n?a=new bt(t):r=new Ye(t);else throw new Error("Can not convert ChatMessage to ChatMessageChunk if 'role' field is not defined.");break;default:throw new Error(`Unrecognized message type ${e}`)}if(n&&a)return a;if(r)return r;throw new Error(`Unrecognized message type ${e}`)}function Il(e){const t=e.getType();let n;const a=Object.fromEntries(Object.entries(e).filter(([r])=>!["type","tool_call_chunks"].includes(r)&&!r.startsWith("lc_")));if(t in da&&(n=bn(t,a)),!n)throw new Error(`Unrecognized message chunk class ${t}. Supported classes are ${Object.keys(da)}`);return n}function Ur(e){const t=e.split(`
|
|
80
|
-
`);return Promise.resolve([...t.slice(0,-1).map(n=>`${n}
|
|
81
|
-
`),t[t.length-1]])}const Ol=["tool_call","tool_call_chunk","invalid_tool_call","server_tool_call","server_tool_call_chunk","server_tool_call_result"],Cl=["image","video","audio","text-plain","file"],xl=["text","reasoning",...Ol,...Cl];var kl={};D(kl,{AIMessage:()=>Ne,AIMessageChunk:()=>Le,BaseMessage:()=>pe,BaseMessageChunk:()=>Ie,ChatMessage:()=>Ye,ChatMessageChunk:()=>bt,FunctionMessage:()=>St,FunctionMessageChunk:()=>Et,HumanMessage:()=>je,HumanMessageChunk:()=>Tt,KNOWN_BLOCK_TYPES:()=>xl,RemoveMessage:()=>ut,SystemMessage:()=>_e,SystemMessageChunk:()=>Pe,ToolMessage:()=>Me,ToolMessageChunk:()=>vt,_isMessageFieldWithRole:()=>Ta,_mergeDicts:()=>B,_mergeLists:()=>Qe,_mergeObj:()=>Ea,_mergeStatus:()=>Sa,coerceMessageLikeToMessage:()=>Vi,convertToChunk:()=>Gt,convertToOpenAIImageBlock:()=>ei,convertToProviderContentBlock:()=>ni,defaultTextSplitter:()=>Ur,defaultToolCallParser:()=>dn,filterMessages:()=>Sl,getBufferString:()=>La,iife:()=>Zi,isAIMessage:()=>Pi,isAIMessageChunk:()=>$i,isBase64ContentBlock:()=>ga,isBaseMessage:()=>un,isBaseMessageChunk:()=>Aa,isChatMessage:()=>Mi,isChatMessageChunk:()=>Li,isDataContentBlock:()=>ge,isDirectToolOutput:()=>xa,isFunctionMessage:()=>ji,isFunctionMessageChunk:()=>Di,isHumanMessage:()=>Ui,isHumanMessageChunk:()=>Fi,isIDContentBlock:()=>_a,isMessage:()=>ya,isOpenAIToolCallArray:()=>Ei,isPlainTextContentBlock:()=>Xr,isSystemMessage:()=>Bi,isSystemMessageChunk:()=>zi,isToolMessage:()=>ka,isToolMessageChunk:()=>Ra,isURLContentBlock:()=>ma,mapChatMessagesToStoredMessages:()=>Qi,mapStoredMessageToChatMessage:()=>ja,mapStoredMessagesToChatMessages:()=>Ki,mergeContent:()=>Ae,mergeMessageRuns:()=>El,mergeResponseMetadata:()=>Ia,mergeUsageMetadata:()=>Ca,parseBase64DataUrl:()=>Ht,parseMimeType:()=>ti,trimMessages:()=>Tl});export{Ge as $,Ne as A,Xe as B,Ye as C,yc as D,Gl as E,St as F,Zl as G,je as H,Fl as I,Be as J,nn as K,ea as L,Jl as M,Wl as N,zl as O,gc as P,Hl as Q,$r as R,_e as S,Me as T,_c as U,Xn as V,Vl as W,ql as X,V as Y,La as Z,D as _,pe as a,ja as a0,Vi as a1,k as a2,wl as a3,It as a4,gn as a5,Oe as a6,$i as a7,as as a8,sc as a9,Pe as aA,Et as aB,vt as aC,bt as aD,Gi as aE,Ma as aF,Ho as aG,$l as aH,ct as aI,he as aJ,pt as aK,xa as aL,tt as aa,ma as ab,ga as ac,ei as ad,we as ae,F as af,ae as ag,j as ah,yt as ai,$e as aj,Wn as ak,yl as al,oa as am,Pr as an,vl as ao,Ql as ap,Kl as aq,Hi as ar,Aa as as,Gt as at,gt as au,We as av,Pl as aw,Na as ax,ti as ay,Tt as az,Le as b,wr as c,un as d,oc as e,ka as f,Pi as g,ge as h,br as i,ni as j,Bl as k,ve as l,Qo as m,Ko as n,Dl as o,Ht as p,Te as q,L as r,U as s,xr as t,Ul as u,de as v,Sr as w,mc as x,fc as y,wn as z};
|