@mcp-use/inspector 0.4.13 → 0.5.0-canary.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/dist/cli.js +1 -5
  2. package/dist/client/assets/{chunk-VL2OQCWN-C61KfPSl.js → chunk-VL2OQCWN-MBqdQwvw.js} +1 -1
  3. package/dist/client/assets/{embeddings-BIo-kwlO.js → embeddings-B5Be4aCe.js} +1 -1
  4. package/dist/client/assets/index-B_wEtYs8.js +40 -0
  5. package/dist/client/assets/index-Bn0J9w6n.js +1438 -0
  6. package/dist/client/assets/{index-dXj4eNzX.js → index-BrE2Q7Md.js} +1 -1
  7. package/dist/client/assets/index-Bx3FWJNp.css +1 -0
  8. package/dist/client/assets/{index-jQGzGE29.js → index-CiA4rdQm.js} +9 -13
  9. package/dist/client/assets/index-CjCfkF26.js +2 -0
  10. package/dist/client/assets/{index-D1RB_-JK.js → index-DyE3WIut.js} +1 -1
  11. package/dist/client/assets/{index-Cva-hqGs.js → index-poirZU-_.js} +1 -1
  12. package/dist/client/assets/langfuse-C4HKZ3NL-DD548jIo.js +562 -0
  13. package/dist/client/assets/{winston-B9dQmIAy.js → winston-vzZ2qSTo.js} +29 -34
  14. package/dist/client/index.html +3 -3
  15. package/dist/server/{chunk-TIYOH5C4.js → chunk-37X7HLUV.js} +1 -5
  16. package/dist/server/{chunk-ZFMPIRVB.js → chunk-5OMSQNKB.js} +1 -1
  17. package/dist/server/{chunk-YGCKPAWJ.js → chunk-UZO6G7KA.js} +3 -3
  18. package/dist/server/{chunk-76XNP4ZB.js → chunk-VOQ3DLXM.js} +1 -5
  19. package/dist/server/{chunk-222XA5JA.js → chunk-WYBXXYSP.js} +1 -1
  20. package/dist/server/cli.js +4 -4
  21. package/dist/server/index.js +5 -5
  22. package/dist/server/middleware.js +5 -5
  23. package/dist/server/server.js +4 -4
  24. package/dist/server/shared-routes.js +2 -2
  25. package/dist/server/shared-static.js +2 -2
  26. package/dist/server/shared-utils-browser.d.ts.map +1 -1
  27. package/dist/server/shared-utils-browser.js +1 -1
  28. package/dist/server/shared-utils.d.ts.map +1 -1
  29. package/dist/server/shared-utils.js +1 -1
  30. package/package.json +2 -2
  31. package/dist/client/assets/index-BLLgp4UX.js +0 -1734
  32. package/dist/client/assets/index-BrUPorMz.css +0 -1
  33. package/dist/client/assets/index-g0U2Uz9F.js +0 -40
  34. package/dist/client/assets/index-gQstsvsJ.js +0 -212
  35. package/dist/client/assets/langfuse-C4HKZ3NL-ComM_afA.js +0 -570
@@ -1,4 +1,4 @@
1
- import{s as Oi,v as se,P as Pe,p as Ht,a as Ga,b as Nr,g as he,c as kr,d as Ke,_ as Ci,$ as xi,e as Ni,f as ki,h as Rr,i as ca,j as Ri,k as Pi,t as Va,l as Pr,V as Mi,m as Li,n as Ut,o as $i,T as ji}from"./chunk-VL2OQCWN-C61KfPSl.js";import{Z as P,a as Za,o as la,s as ua}from"./index-BLLgp4UX.js";var Di=Object.defineProperty,F=(e,t)=>{for(var n in t)Di(e,n,{get:t[n],enumerable:!0})};function Ue(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 da(e){return Ue(e)&&e.source_type==="url"&&"url"in e&&typeof e.url=="string"}function ha(e){return Ue(e)&&e.source_type==="base64"&&"data"in e&&typeof e.data=="string"}function Fi(e){return Ue(e)&&e.source_type==="text"&&"text"in e&&typeof e.text=="string"}function Mr(e){return Ue(e)&&e.source_type==="id"&&"id"in e&&typeof e.id=="string"}function Lr(e){if(Ue(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 Ui(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 s of e.split(";").slice(1)){const i=s.split("=");if(i.length!==2)throw new Error(`Invalid parameter syntax in mime type: "${e}".`);const o=i[0].trim(),c=i[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 $n({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]),s=>s.charCodeAt(0)):n[2];return{mime_type:a,data:r}}}function Bi(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 $r(e){return typeof e=="object"&&e!==null&&"type"in e&&"content"in e&&(typeof e.content=="string"||Array.isArray(e.content))}function zi(e,t){return t?.[e]||Oi(e)}function Hi(e,t,n){const a={};for(const r in e)Object.hasOwn(e,r)&&(a[t(r,n)]=e[r]);return a}var Gi={};F(Gi,{Serializable:()=>lt,get_lc_unique_name:()=>pa});function qa(e){return Array.isArray(e)?[...e]:{...e}}function Vi(e,t){const n=qa(e);for(const[a,r]of Object.entries(t)){const[s,...i]=a.split(".").reverse();let o=n;for(const c of i.reverse()){if(o[c]===void 0)break;o[c]=qa(o[c]),o=o[c]}o[s]!==void 0&&(o[s]={lc:1,type:"secret",id:[r]})}return n}function pa(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 lt=class jr{lc_serializable=!1;lc_kwargs;static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,pa(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 jr||typeof this.lc_kwargs!="object"||Array.isArray(this.lc_kwargs))return this.toJSONNotImplemented();const t={},n={},a=Object.keys(this.lc_kwargs).reduce((r,s)=>(r[s]=s in this?this[s]:this.lc_kwargs[s],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 s=this,i=a;const[o,...c]=r.split(".").reverse();for(const l of c.reverse()){if(!(l in s)||s[l]===void 0)return;(!(l in i)||i[l]===void 0)&&(typeof s[l]=="object"&&s[l]!=null?i[l]={}:Array.isArray(s[l])&&(i[l]=[])),s=s[l],i=i[l]}o in s&&s[o]!==void 0&&(i[o]=i[o]||s[o])}),{lc:1,type:"constructor",id:this.lc_id,kwargs:Hi(Object.keys(n).length?Vi(a,n):a,zi,t)}}toJSONNotImplemented(){return{lc:1,type:"not_implemented",id:this.lc_id}}};function C(e,t){return k(e)&&e.type===t}function k(e){return typeof e=="object"&&e!==null}function Ie(e){return Array.isArray(e)}function S(e){return typeof e=="string"}function we(e){return typeof e=="number"}function fa(e){return e instanceof Uint8Array}function Ja(e){try{return JSON.parse(e)}catch{return}}const vt=e=>e();function Zi(e){if(e.type==="char_location"&&S(e.document_title)&&we(e.start_char_index)&&we(e.end_char_index)&&S(e.cited_text)){const{document_title:t,start_char_index:n,end_char_index:a,cited_text:r,...s}=e;return{...s,type:"citation",source:"char",title:t??void 0,startIndex:n,endIndex:a,citedText:r}}if(e.type==="page_location"&&S(e.document_title)&&we(e.start_page_number)&&we(e.end_page_number)&&S(e.cited_text)){const{document_title:t,start_page_number:n,end_page_number:a,cited_text:r,...s}=e;return{...s,type:"citation",source:"page",title:t??void 0,startIndex:n,endIndex:a,citedText:r}}if(e.type==="content_block_location"&&S(e.document_title)&&we(e.start_block_index)&&we(e.end_block_index)&&S(e.cited_text)){const{document_title:t,start_block_index:n,end_block_index:a,cited_text:r,...s}=e;return{...s,type:"citation",source:"block",title:t??void 0,startIndex:n,endIndex:a,citedText:r}}if(e.type==="web_search_result_location"&&S(e.url)&&S(e.title)&&S(e.encrypted_index)&&S(e.cited_text)){const{url:t,title:n,encrypted_index:a,cited_text:r,...s}=e;return{...s,type:"citation",source:"url",url:t,title:n,startIndex:Number(a),endIndex:Number(a),citedText:r}}if(e.type==="search_result_location"&&S(e.source)&&S(e.title)&&we(e.start_block_index)&&we(e.end_block_index)&&S(e.cited_text)){const{source:t,title:n,start_block_index:a,end_block_index:r,cited_text:s,...i}=e;return{...i,type:"citation",source:"search",url:t,title:n??void 0,startIndex:a,endIndex:r,citedText:s}}}function Dr(e){if(C(e,"document")&&k(e.source)&&"type"in e.source){if(e.source.type==="base64"&&S(e.source.media_type)&&S(e.source.data))return{type:"file",mimeType:e.source.media_type,data:e.source.data};if(e.source.type==="url"&&S(e.source.url))return{type:"file",url:e.source.url};if(e.source.type==="file"&&S(e.source.file_id))return{type:"file",fileId:e.source.file_id};if(e.source.type==="text"&&S(e.source.data))return{type:"file",mimeType:String(e.source.media_type??"text/plain"),data:e.source.data}}else if(C(e,"image")&&k(e.source)&&"type"in e.source){if(e.source.type==="base64"&&S(e.source.media_type)&&S(e.source.data))return{type:"image",mimeType:e.source.media_type,data:e.source.data};if(e.source.type==="url"&&S(e.source.url))return{type:"image",url:e.source.url};if(e.source.type==="file"&&S(e.source.file_id))return{type:"image",fileId:e.source.file_id}}}function qi(e){function*t(){for(const n of e){const a=Dr(n);a?yield a:yield n}}return Array.from(t())}function Wa(e){function*t(){const n=typeof e.content=="string"?[{type:"text",text:e.content}]:e.content;for(const a of n){if(C(a,"text")&&S(a.text)){const{text:r,citations:s,...i}=a;if(Ie(s)&&s.length){const o=s.reduce((c,l)=>{const d=Zi(l);return d?[...c,d]:c},[]);yield{...i,type:"text",text:r,annotations:o};continue}else{yield{...i,type:"text",text:r};continue}}else if(C(a,"thinking")&&S(a.thinking)){const{thinking:r,signature:s,...i}=a;yield{...i,type:"reasoning",reasoning:r,signature:s};continue}else if(C(a,"redacted_thinking")){yield{type:"non_standard",value:a};continue}else if(C(a,"tool_use")&&S(a.name)&&S(a.id)){yield{type:"tool_call",id:a.id,name:a.name,args:a.input};continue}else if(C(a,"input_json_delta")){if(Wi(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(C(a,"server_tool_use")&&S(a.name)&&S(a.id)){const{name:r,id:s}=a;if(r==="web_search"){const i=vt(()=>{if(typeof a.input=="string")return a.input;if(k(a.input)&&S(a.input.query))return a.input.query;if(S(a.partial_json)){const o=Ja(a.partial_json);if(o?.query)return o.query}return""});yield{id:s,type:"server_tool_call",name:"web_search",args:{query:i}};continue}else if(a.name==="code_execution"){const i=vt(()=>{if(typeof a.input=="string")return a.input;if(k(a.input)&&S(a.input.code))return a.input.code;if(S(a.partial_json)){const o=Ja(a.partial_json);if(o?.code)return o.code}return""});yield{id:s,type:"server_tool_call",name:"code_execution",args:{code:i}};continue}}else if(C(a,"web_search_tool_result")&&S(a.tool_use_id)&&Ie(a.content)){const{content:r,tool_use_id:s}=a,i=r.reduce((o,c)=>C(c,"web_search_result")?[...o,c.url]:o,[]);yield{type:"server_tool_call_result",name:"web_search",toolCallId:s,status:"success",output:{urls:i}};continue}else if(C(a,"code_execution_tool_result")&&S(a.tool_use_id)&&k(a.content)){yield{type:"server_tool_call_result",name:"code_execution",toolCallId:a.tool_use_id,status:"success",output:a.content};continue}else if(C(a,"mcp_tool_use")){yield{id:a.id,type:"server_tool_call",name:"mcp_tool_use",args:a.input};continue}else if(C(a,"mcp_tool_result")&&S(a.tool_use_id)&&k(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(C(a,"container_upload")){yield{type:"server_tool_call",name:"container_upload",args:a.input};continue}else if(C(a,"search_result")){yield{id:a.id,type:"non_standard",value:a};continue}else if(C(a,"tool_result")){yield{id:a.id,type:"non_standard",value:a};continue}else{const r=Dr(a);if(r){yield r;continue}}yield{type:"non_standard",value:a}}}return Array.from(t())}const Ji={translateContent:Wa,translateContentChunk:Wa};function Wi(e){return typeof e?._getType=="function"&&typeof e.concat=="function"&&e._getType()==="ai"}function Ki(e){return da(e)?{type:e.type,mimeType:e.mime_type,url:e.url,metadata:e.metadata}:ha(e)?{type:e.type,mimeType:e.mime_type??"application/octet-stream",data:e.data,metadata:e.metadata}:Mr(e)?{type:e.type,mimeType:e.mime_type,fileId:e.id,metadata:e.metadata}:e}function Yi(e){return e.map(Ki)}function Qi(e){return!!(C(e,"image_url")&&k(e.image_url)||C(e,"input_audio")&&k(e.input_audio)||C(e,"file")&&k(e.file))}function Xi(e){if(C(e,"image_url")&&k(e.image_url)&&S(e.image_url.url)){const t=$n({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(C(e,"input_audio")&&k(e.input_audio)&&S(e.input_audio.data)&&S(e.input_audio.format))return{type:"audio",data:e.input_audio.data,mimeType:`audio/${e.input_audio.format}`};if(C(e,"file")&&k(e.file)&&S(e.file.data)){const t=$n({dataUrl:e.file.data});if(t)return{type:"file",data:t.data,mimeType:t.mime_type};if(S(e.file.file_id))return{type:"file",fileId:e.file.file_id}}}return e}function eo(e){const t=[];typeof e.content=="string"?t.push({type:"text",text:e.content}):t.push(...ma(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 to(e){const t=[];typeof e.content=="string"?t.push({type:"text",text:e.content}):t.push(...ma(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 ma(e){const t=[];for(const n of e)Qi(n)?t.push(Xi(n)):t.push(n);return t}function no(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 Fr(e){function*t(){k(e.additional_kwargs?.reasoning)&&Ie(e.additional_kwargs.reasoning.summary)&&(yield{type:"reasoning",reasoning:e.additional_kwargs.reasoning.summary.reduce((r,s)=>k(s)&&S(s.text)?`${r}${s.text}`:r,"")});const n=typeof e.content=="string"?[{type:"text",text:e.content}]:e.content;for(const a of n)if(C(a,"text")){const{text:r,annotations:s,...i}=a;Array.isArray(s)?yield{...i,type:"text",text:String(r),annotations:s.map(no)}:yield{...i,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(k(e.additional_kwargs)&&Ie(e.additional_kwargs.tool_outputs))for(const a of e.additional_kwargs.tool_outputs){if(C(a,"web_search_call")){yield{id:a.id,type:"server_tool_call",name:"web_search",args:{query:a.query}};continue}else if(C(a,"file_search_call")){yield{id:a.id,type:"server_tool_call",name:"file_search",args:{query:a.query}};continue}else if(C(a,"computer_call")){yield{type:"non_standard",value:a};continue}else if(C(a,"code_interpreter_call")){if(S(a.code)&&(yield{id:a.id,type:"server_tool_call",name:"code_interpreter",args:{code:a.code}}),Ie(a.outputs)){const r=vt(()=>{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 s of a.outputs)if(C(s,"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(s.logs),stdout:[0,void 0].includes(r)?String(s.logs):void 0}};continue}}continue}else if(C(a,"mcp_call")){yield{id:a.id,type:"server_tool_call",name:"mcp_call",args:a.input};continue}else if(C(a,"mcp_list_tools")){yield{id:a.id,type:"server_tool_call",name:"mcp_list_tools",args:a.input};continue}else if(C(a,"mcp_approval_request")){yield{type:"non_standard",value:a};continue}else if(C(a,"image_generation_call")){yield{type:"non_standard",value:a};continue}k(a)&&(yield{type:"non_standard",value:a})}}return Array.from(t())}function ao(e){function*t(){yield*Fr(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 ro={translateContent:e=>typeof e.content=="string"?eo(e):Fr(e),translateContentChunk:e=>typeof e.content=="string"?to(e):ao(e)};function so(e,t="pretty"){return t==="pretty"?io(e):JSON.stringify(e)}function io(e){const t=[],n=` ${e.type.charAt(0).toUpperCase()+e.type.slice(1)} Message `,a=Math.floor((80-n.length)/2),r="=".repeat(a),s=n.length%2===0?r:`${r}=`;if(t.push(`${r}${n}${s}`),e.type==="ai"){const i=e;if(i.tool_calls&&i.tool_calls.length>0){t.push("Tool Calls:");for(const o of i.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 i=e;i.name&&t.push(`Name: ${i.name}`)}return typeof e.content=="string"&&e.content.trim()&&(t.length>1&&t.push(""),t.push(e.content)),t.join(`
1
+ import{s as Oi,v as se,P as Pe,p as Ht,a as Ga,b as Nr,g as he,c as kr,d as Ke,_ as Ci,$ as xi,e as Ni,f as ki,h as Rr,i as ca,j as Ri,k as Pi,t as Va,l as Pr,V as Mi,m as Li,n as Ut,o as $i,T as ji}from"./chunk-VL2OQCWN-MBqdQwvw.js";import{Z as P,a as Za,o as la,s as ua}from"./index-Bn0J9w6n.js";var Di=Object.defineProperty,F=(e,t)=>{for(var n in t)Di(e,n,{get:t[n],enumerable:!0})};function Ue(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 da(e){return Ue(e)&&e.source_type==="url"&&"url"in e&&typeof e.url=="string"}function ha(e){return Ue(e)&&e.source_type==="base64"&&"data"in e&&typeof e.data=="string"}function Fi(e){return Ue(e)&&e.source_type==="text"&&"text"in e&&typeof e.text=="string"}function Mr(e){return Ue(e)&&e.source_type==="id"&&"id"in e&&typeof e.id=="string"}function Lr(e){if(Ue(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 Ui(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 s of e.split(";").slice(1)){const i=s.split("=");if(i.length!==2)throw new Error(`Invalid parameter syntax in mime type: "${e}".`);const o=i[0].trim(),c=i[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 $n({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]),s=>s.charCodeAt(0)):n[2];return{mime_type:a,data:r}}}function Bi(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 $r(e){return typeof e=="object"&&e!==null&&"type"in e&&"content"in e&&(typeof e.content=="string"||Array.isArray(e.content))}function zi(e,t){return t?.[e]||Oi(e)}function Hi(e,t,n){const a={};for(const r in e)Object.hasOwn(e,r)&&(a[t(r,n)]=e[r]);return a}var Gi={};F(Gi,{Serializable:()=>lt,get_lc_unique_name:()=>pa});function qa(e){return Array.isArray(e)?[...e]:{...e}}function Vi(e,t){const n=qa(e);for(const[a,r]of Object.entries(t)){const[s,...i]=a.split(".").reverse();let o=n;for(const c of i.reverse()){if(o[c]===void 0)break;o[c]=qa(o[c]),o=o[c]}o[s]!==void 0&&(o[s]={lc:1,type:"secret",id:[r]})}return n}function pa(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 lt=class jr{lc_serializable=!1;lc_kwargs;static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,pa(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 jr||typeof this.lc_kwargs!="object"||Array.isArray(this.lc_kwargs))return this.toJSONNotImplemented();const t={},n={},a=Object.keys(this.lc_kwargs).reduce((r,s)=>(r[s]=s in this?this[s]:this.lc_kwargs[s],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 s=this,i=a;const[o,...c]=r.split(".").reverse();for(const l of c.reverse()){if(!(l in s)||s[l]===void 0)return;(!(l in i)||i[l]===void 0)&&(typeof s[l]=="object"&&s[l]!=null?i[l]={}:Array.isArray(s[l])&&(i[l]=[])),s=s[l],i=i[l]}o in s&&s[o]!==void 0&&(i[o]=i[o]||s[o])}),{lc:1,type:"constructor",id:this.lc_id,kwargs:Hi(Object.keys(n).length?Vi(a,n):a,zi,t)}}toJSONNotImplemented(){return{lc:1,type:"not_implemented",id:this.lc_id}}};function C(e,t){return k(e)&&e.type===t}function k(e){return typeof e=="object"&&e!==null}function Ie(e){return Array.isArray(e)}function S(e){return typeof e=="string"}function we(e){return typeof e=="number"}function fa(e){return e instanceof Uint8Array}function Ja(e){try{return JSON.parse(e)}catch{return}}const vt=e=>e();function Zi(e){if(e.type==="char_location"&&S(e.document_title)&&we(e.start_char_index)&&we(e.end_char_index)&&S(e.cited_text)){const{document_title:t,start_char_index:n,end_char_index:a,cited_text:r,...s}=e;return{...s,type:"citation",source:"char",title:t??void 0,startIndex:n,endIndex:a,citedText:r}}if(e.type==="page_location"&&S(e.document_title)&&we(e.start_page_number)&&we(e.end_page_number)&&S(e.cited_text)){const{document_title:t,start_page_number:n,end_page_number:a,cited_text:r,...s}=e;return{...s,type:"citation",source:"page",title:t??void 0,startIndex:n,endIndex:a,citedText:r}}if(e.type==="content_block_location"&&S(e.document_title)&&we(e.start_block_index)&&we(e.end_block_index)&&S(e.cited_text)){const{document_title:t,start_block_index:n,end_block_index:a,cited_text:r,...s}=e;return{...s,type:"citation",source:"block",title:t??void 0,startIndex:n,endIndex:a,citedText:r}}if(e.type==="web_search_result_location"&&S(e.url)&&S(e.title)&&S(e.encrypted_index)&&S(e.cited_text)){const{url:t,title:n,encrypted_index:a,cited_text:r,...s}=e;return{...s,type:"citation",source:"url",url:t,title:n,startIndex:Number(a),endIndex:Number(a),citedText:r}}if(e.type==="search_result_location"&&S(e.source)&&S(e.title)&&we(e.start_block_index)&&we(e.end_block_index)&&S(e.cited_text)){const{source:t,title:n,start_block_index:a,end_block_index:r,cited_text:s,...i}=e;return{...i,type:"citation",source:"search",url:t,title:n??void 0,startIndex:a,endIndex:r,citedText:s}}}function Dr(e){if(C(e,"document")&&k(e.source)&&"type"in e.source){if(e.source.type==="base64"&&S(e.source.media_type)&&S(e.source.data))return{type:"file",mimeType:e.source.media_type,data:e.source.data};if(e.source.type==="url"&&S(e.source.url))return{type:"file",url:e.source.url};if(e.source.type==="file"&&S(e.source.file_id))return{type:"file",fileId:e.source.file_id};if(e.source.type==="text"&&S(e.source.data))return{type:"file",mimeType:String(e.source.media_type??"text/plain"),data:e.source.data}}else if(C(e,"image")&&k(e.source)&&"type"in e.source){if(e.source.type==="base64"&&S(e.source.media_type)&&S(e.source.data))return{type:"image",mimeType:e.source.media_type,data:e.source.data};if(e.source.type==="url"&&S(e.source.url))return{type:"image",url:e.source.url};if(e.source.type==="file"&&S(e.source.file_id))return{type:"image",fileId:e.source.file_id}}}function qi(e){function*t(){for(const n of e){const a=Dr(n);a?yield a:yield n}}return Array.from(t())}function Wa(e){function*t(){const n=typeof e.content=="string"?[{type:"text",text:e.content}]:e.content;for(const a of n){if(C(a,"text")&&S(a.text)){const{text:r,citations:s,...i}=a;if(Ie(s)&&s.length){const o=s.reduce((c,l)=>{const d=Zi(l);return d?[...c,d]:c},[]);yield{...i,type:"text",text:r,annotations:o};continue}else{yield{...i,type:"text",text:r};continue}}else if(C(a,"thinking")&&S(a.thinking)){const{thinking:r,signature:s,...i}=a;yield{...i,type:"reasoning",reasoning:r,signature:s};continue}else if(C(a,"redacted_thinking")){yield{type:"non_standard",value:a};continue}else if(C(a,"tool_use")&&S(a.name)&&S(a.id)){yield{type:"tool_call",id:a.id,name:a.name,args:a.input};continue}else if(C(a,"input_json_delta")){if(Wi(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(C(a,"server_tool_use")&&S(a.name)&&S(a.id)){const{name:r,id:s}=a;if(r==="web_search"){const i=vt(()=>{if(typeof a.input=="string")return a.input;if(k(a.input)&&S(a.input.query))return a.input.query;if(S(a.partial_json)){const o=Ja(a.partial_json);if(o?.query)return o.query}return""});yield{id:s,type:"server_tool_call",name:"web_search",args:{query:i}};continue}else if(a.name==="code_execution"){const i=vt(()=>{if(typeof a.input=="string")return a.input;if(k(a.input)&&S(a.input.code))return a.input.code;if(S(a.partial_json)){const o=Ja(a.partial_json);if(o?.code)return o.code}return""});yield{id:s,type:"server_tool_call",name:"code_execution",args:{code:i}};continue}}else if(C(a,"web_search_tool_result")&&S(a.tool_use_id)&&Ie(a.content)){const{content:r,tool_use_id:s}=a,i=r.reduce((o,c)=>C(c,"web_search_result")?[...o,c.url]:o,[]);yield{type:"server_tool_call_result",name:"web_search",toolCallId:s,status:"success",output:{urls:i}};continue}else if(C(a,"code_execution_tool_result")&&S(a.tool_use_id)&&k(a.content)){yield{type:"server_tool_call_result",name:"code_execution",toolCallId:a.tool_use_id,status:"success",output:a.content};continue}else if(C(a,"mcp_tool_use")){yield{id:a.id,type:"server_tool_call",name:"mcp_tool_use",args:a.input};continue}else if(C(a,"mcp_tool_result")&&S(a.tool_use_id)&&k(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(C(a,"container_upload")){yield{type:"server_tool_call",name:"container_upload",args:a.input};continue}else if(C(a,"search_result")){yield{id:a.id,type:"non_standard",value:a};continue}else if(C(a,"tool_result")){yield{id:a.id,type:"non_standard",value:a};continue}else{const r=Dr(a);if(r){yield r;continue}}yield{type:"non_standard",value:a}}}return Array.from(t())}const Ji={translateContent:Wa,translateContentChunk:Wa};function Wi(e){return typeof e?._getType=="function"&&typeof e.concat=="function"&&e._getType()==="ai"}function Ki(e){return da(e)?{type:e.type,mimeType:e.mime_type,url:e.url,metadata:e.metadata}:ha(e)?{type:e.type,mimeType:e.mime_type??"application/octet-stream",data:e.data,metadata:e.metadata}:Mr(e)?{type:e.type,mimeType:e.mime_type,fileId:e.id,metadata:e.metadata}:e}function Yi(e){return e.map(Ki)}function Qi(e){return!!(C(e,"image_url")&&k(e.image_url)||C(e,"input_audio")&&k(e.input_audio)||C(e,"file")&&k(e.file))}function Xi(e){if(C(e,"image_url")&&k(e.image_url)&&S(e.image_url.url)){const t=$n({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(C(e,"input_audio")&&k(e.input_audio)&&S(e.input_audio.data)&&S(e.input_audio.format))return{type:"audio",data:e.input_audio.data,mimeType:`audio/${e.input_audio.format}`};if(C(e,"file")&&k(e.file)&&S(e.file.data)){const t=$n({dataUrl:e.file.data});if(t)return{type:"file",data:t.data,mimeType:t.mime_type};if(S(e.file.file_id))return{type:"file",fileId:e.file.file_id}}}return e}function eo(e){const t=[];typeof e.content=="string"?t.push({type:"text",text:e.content}):t.push(...ma(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 to(e){const t=[];typeof e.content=="string"?t.push({type:"text",text:e.content}):t.push(...ma(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 ma(e){const t=[];for(const n of e)Qi(n)?t.push(Xi(n)):t.push(n);return t}function no(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 Fr(e){function*t(){k(e.additional_kwargs?.reasoning)&&Ie(e.additional_kwargs.reasoning.summary)&&(yield{type:"reasoning",reasoning:e.additional_kwargs.reasoning.summary.reduce((r,s)=>k(s)&&S(s.text)?`${r}${s.text}`:r,"")});const n=typeof e.content=="string"?[{type:"text",text:e.content}]:e.content;for(const a of n)if(C(a,"text")){const{text:r,annotations:s,...i}=a;Array.isArray(s)?yield{...i,type:"text",text:String(r),annotations:s.map(no)}:yield{...i,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(k(e.additional_kwargs)&&Ie(e.additional_kwargs.tool_outputs))for(const a of e.additional_kwargs.tool_outputs){if(C(a,"web_search_call")){yield{id:a.id,type:"server_tool_call",name:"web_search",args:{query:a.query}};continue}else if(C(a,"file_search_call")){yield{id:a.id,type:"server_tool_call",name:"file_search",args:{query:a.query}};continue}else if(C(a,"computer_call")){yield{type:"non_standard",value:a};continue}else if(C(a,"code_interpreter_call")){if(S(a.code)&&(yield{id:a.id,type:"server_tool_call",name:"code_interpreter",args:{code:a.code}}),Ie(a.outputs)){const r=vt(()=>{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 s of a.outputs)if(C(s,"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(s.logs),stdout:[0,void 0].includes(r)?String(s.logs):void 0}};continue}}continue}else if(C(a,"mcp_call")){yield{id:a.id,type:"server_tool_call",name:"mcp_call",args:a.input};continue}else if(C(a,"mcp_list_tools")){yield{id:a.id,type:"server_tool_call",name:"mcp_list_tools",args:a.input};continue}else if(C(a,"mcp_approval_request")){yield{type:"non_standard",value:a};continue}else if(C(a,"image_generation_call")){yield{type:"non_standard",value:a};continue}k(a)&&(yield{type:"non_standard",value:a})}}return Array.from(t())}function ao(e){function*t(){yield*Fr(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 ro={translateContent:e=>typeof e.content=="string"?eo(e):Fr(e),translateContentChunk:e=>typeof e.content=="string"?to(e):ao(e)};function so(e,t="pretty"){return t==="pretty"?io(e):JSON.stringify(e)}function io(e){const t=[],n=` ${e.type.charAt(0).toUpperCase()+e.type.slice(1)} Message `,a=Math.floor((80-n.length)/2),r="=".repeat(a),s=n.length%2===0?r:`${r}=`;if(t.push(`${r}${n}${s}`),e.type==="ai"){const i=e;if(i.tool_calls&&i.tool_calls.length>0){t.push("Tool Calls:");for(const o of i.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 i=e;i.name&&t.push(`Name: ${i.name}`)}return typeof e.content=="string"&&e.content.trim()&&(t.length>1&&t.push(""),t.push(e.content)),t.join(`
2
2
  `)}const yn=Symbol.for("langchain.message");function Xe(e,t){return typeof e=="string"?e===""?t:typeof t=="string"?e+t:Array.isArray(t)&&t.some(n=>Ue(n))?[{type:"text",source_type:"text",text:e},...t]:[{type:"text",text:e},...t]:Array.isArray(t)?Ot(e,t)??[...e,...t]:t===""?e:Array.isArray(e)&&e.some(n=>Ue(n))?[...e,{type:"file",source_type:"text",text:t}]:[...e,{type:"text",text:t}]}function Ur(e,t){return e==="error"||t==="error"?"error":"success"}function oo(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(i=>n(i,r+1));const s={};for(const i of Object.keys(a))s[i]=n(a[i],r+1);return s}return JSON.stringify(n(e,0),null,2)}var Le=class extends lt{lc_namespace=["langchain_core","messages"];lc_serializable=!0;get lc_aliases(){return{additional_kwargs:"additional_kwargs",response_metadata:"response_metadata"}}[yn]=!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[Yi,ma,qi].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&&yn in e&&e[yn]===!0&&$r(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=oo(this._printableFields,Math.max(4,e));return`${this.constructor.lc_name()} ${t}`}toFormattedString(e="pretty"){return so(this,e)}};function co(e){return Array.isArray(e)&&e.every(t=>typeof t.index=="number")}function ee(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]=ee(n[a],r);else if(Array.isArray(n[a]))n[a]=Ot(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 Ot(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(s=>{const i=typeof s=="object",o="index"in s&&s.index===a.index,c="id"in s&&"id"in a&&s?.id===a?.id,l=!("id"in s)||!s?.id||!("id"in a)||!a?.id;return i&&o&&(c||l)});r!==-1&&typeof n[r]=="object"&&n[r]!==null?n[r]=ee(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 Br(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
3
  Left ${typeof e}
4
4
  Right ${typeof t}`);if(typeof e=="string"&&typeof t=="string")return e+t;if(Array.isArray(e)&&Array.isArray(t))return Ot(e,t);if(typeof e=="object"&&typeof t=="object")return ee(e,t);if(e===t)return e;throw new Error(`Can not merge objects of different types.
@@ -10,11 +10,11 @@ Right ${t}`)}var et=class extends Le{static isInstance(e){return super.isInstanc
10
10
 
11
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,s]=_a(n);t.tool_calls=r??[],t.invalid_tool_calls=s??[]}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(s=>({type:"tool_call",id:s.id,name:s.name,args:s.args})));const r=t.contentBlocks.filter(s=>s.type==="tool_call").filter(s=>!t.tool_calls?.some(i=>i.id===s.id&&i.name===s.name));r.length>0&&(t.tool_calls=r.map(s=>({type:"tool_call",id:s.id,name:s.name,args:s.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=Wr(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 Kr(e){return e._getType()==="ai"}function Dn(e){return e._getType()==="ai"}var tt=class extends et{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((i,o)=>{const c=i.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?i[c].push(o):i.push([o]),i},[]),r=[],s=[];for(const i of a){let o=null;const c=i[0]?.name??"",l=i.map(f=>f.args||"").join(""),d=l.length?l:"{}",p=i[0]?.id;try{if(o=ya(d),!p||o===null||typeof o!="object"||Array.isArray(o))throw new Error("Malformed tool call chunk args.");r.push({name:c,args:o,id:p,type:"tool_call"})}catch{s.push({name:c,args:d,id:p,error:"Malformed args.",type:"invalid_tool_call"})}}t={...e,tool_calls:r,invalid_tool_calls:s,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=Wr(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:Xe(this.content,e.content),additional_kwargs:ee(this.additional_kwargs,e.additional_kwargs),response_metadata:Hr(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=Ot(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=Vr(this.usage_metadata,e.usage_metadata));const n=this.constructor;return new n(t)}static isInstance(e){return super.isInstance(e)&&e.type==="ai"}},Ct=class Yr extends Le{static lc_name(){return"ChatMessage"}type="generic";role;static _chatMessageClass(){return Yr}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}}},nn=class extends et{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:Xe(this.content,e.content),additional_kwargs:ee(this.additional_kwargs,e.additional_kwargs),response_metadata:ee(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 wo(e){return e._getType()==="generic"}function bo(e){return e._getType()==="generic"}var an=class extends Le{static lc_name(){return"FunctionMessage"}type="function";name;constructor(e){super(e),this.name=e.name}},rn=class extends et{static lc_name(){return"FunctionMessageChunk"}type="function";concat(e){const t=this.constructor;return new t({content:Xe(this.content,e.content),additional_kwargs:ee(this.additional_kwargs,e.additional_kwargs),response_metadata:ee(this.response_metadata,e.response_metadata),name:this.name??"",id:this.id??e.id})}};function vo(e){return e._getType()==="function"}function To(e){return e._getType()==="function"}var $e=class extends Le{static lc_name(){return"HumanMessage"}type="human";constructor(e){super(e)}static isInstance(e){return super.isInstance(e)&&e.type==="human"}},sn=class extends et{static lc_name(){return"HumanMessageChunk"}type="human";constructor(e){super(e)}concat(e){const t=this.constructor;return new t({content:Xe(this.content,e.content),additional_kwargs:ee(this.additional_kwargs,e.additional_kwargs),response_metadata:ee(this.response_metadata,e.response_metadata),id:this.id??e.id})}static isInstance(e){return super.isInstance(e)&&e.type==="human"}};function Eo(e){return e.getType()==="human"}function So(e){return e.getType()==="human"}var ze=class extends Le{static lc_name(){return"SystemMessage"}type="system";constructor(e){super(e)}static isInstance(e){return super.isInstance(e)&&e.type==="system"}},ut=class extends et{static lc_name(){return"SystemMessageChunk"}type="system";constructor(e){super(e)}concat(e){const t=this.constructor;return new t({content:Xe(this.content,e.content),additional_kwargs:ee(this.additional_kwargs,e.additional_kwargs),response_metadata:ee(this.response_metadata,e.response_metadata),id:this.id??e.id})}static isInstance(e){return super.isInstance(e)&&e.type==="system"}};function Ao(e){return e._getType()==="system"}function Io(e){return e._getType()==="system"}var Gt=class extends Le{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 Qr(e,t){return e.lc_error_code=t,e.message=`${e.message}
12
12
 
13
- Troubleshooting URL: https://js.langchain.com/docs/troubleshooting/errors/${t}/
13
+ Troubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${t}/
14
14
  `,e}function Xr(e){return!!(e&&typeof e=="object"&&"type"in e&&e.type==="tool_call")}function Xd(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 Oo=class extends Error{output;constructor(e,t){super(e),this.output=t}};const Co=e=>e();function xo(e){return Xr(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 No(e){return typeof e=="object"&&e!=null&&e.lc===1&&Array.isArray(e.id)&&e.kwargs!=null&&typeof e.kwargs=="object"}function wn(e){let t,n;if(No(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 $e(n);if(t==="ai"||t==="assistant"){const{tool_calls:a,...r}=n;if(!Array.isArray(a))return new Be(n);const s=a.map(xo);return new Be({...r,tool_calls:s})}else{if(t==="system")return new ze(n);if(t==="developer")return new ze({...n,additional_kwargs:{...n.additional_kwargs,__openai_role__:"developer"}});if(t==="tool"&&"tool_call_id"in n)return new pt({...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 Gt({...n,id:n.id});throw Qr(new Error(`Unable to coerce message from array: only human, AI, system, developer, or tool message coercion is currently supported.
15
15
 
16
16
  Received: ${JSON.stringify(e,null,2)}`),"MESSAGE_COERCION_FAILURE")}}function wt(e){if(typeof e=="string")return new $e(e);if(Re(e))return e;if(Array.isArray(e)){const[t,n]=e;return wn({type:t,content:n})}else if(zr(e)){const{role:t,...n}=e;return wn({...n,type:t})}else return wn(e)}function ba(e,t="Human",n="AI"){const a=[];for(const r of e){let s;if(r._getType()==="human")s=t;else if(r._getType()==="ai")s=n;else if(r._getType()==="system")s="System";else if(r._getType()==="tool")s="Tool";else if(r._getType()==="generic")s=r.role;else throw new Error(`Got unsupported message type: ${r._getType()}`);const i=r.name?`${r.name}, `:"",o=typeof r.content=="string"?r.content:JSON.stringify(r.content,null,2);a.push(`${s}: ${i}${o}`)}return a.join(`
17
- `)}function ko(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 va(e){const t=ko(e);switch(t.type){case"human":return new $e(t.data);case"ai":return new Be(t.data);case"system":return new ze(t.data);case"function":if(t.data.name===void 0)throw new Error("Name must be defined for function messages");return new an(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 pt(t.data);case"generic":if(t.data.role===void 0)throw new Error("Role must be defined for chat messages");return new Ct(t.data);default:throw new Error(`Got unexpected type: ${t.type}`)}}function Ro(e){return e.map(va)}function Po(e){return e.map(t=>t.toDict())}function Vt(e){const t=e._getType();if(t==="human")return new sn({...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 tt({...n})}else{if(t==="system")return new ut({...e});if(t==="function")return new rn({...e});if(Ct.isInstance(e))return new nn({...e});throw new Error("Unknown message type.")}}const es=Symbol.for("ls:tracing_async_local_storage"),bt=Symbol.for("lc:context_variables"),Mo=e=>{globalThis[es]=e},Tt=()=>globalThis[es];var Lo={},$o={};F($o,{getEnv:()=>ss,getEnvironmentVariable:()=>Fe,getRuntimeEnvironment:()=>is,isBrowser:()=>ts,isDeno:()=>on,isJsDom:()=>as,isNode:()=>rs,isWebWorker:()=>ns});const ts=()=>typeof window<"u"&&typeof window.document<"u",ns=()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope",as=()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),on=()=>typeof Deno<"u",rs=()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!on(),ss=()=>{let e;return ts()?e="browser":rs()?e="node":ns()?e="webworker":as()?e="jsdom":on()?e="deno":e="other",e};let bn;function is(){return bn===void 0&&(bn={library:"langchain-js",runtime:ss()}),bn}function Fe(e){try{return typeof process<"u"?Lo?.[e]:on()?Deno?.env.get(e):void 0}catch{return}}var jo={};F(jo,{BaseCallbackHandler:()=>xt,callbackHandlerPrefersStreaming:()=>os,isBaseCallbackHandler:()=>cs});var Do=class{};function os(e){return"lc_prefer_streaming"in e&&e.lc_prefer_streaming}var xt=class extends Do{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,pa(this.constructor)]}lc_kwargs;ignoreLLM=!1;ignoreChain=!1;ignoreAgent=!1;ignoreRetriever=!1;ignoreCustomEvent=!1;raiseError=!1;awaitHandlers=Fe("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 lt.prototype.toJSON.call(this)}toJSONNotImplemented(){return lt.prototype.toJSONNotImplemented.call(this)}static fromMethods(e){class t extends xt{name=se();constructor(){super(),Object.assign(this,e)}}return new t}};const cs=e=>{const t=e;return t!==void 0&&typeof t.copy=="function"&&typeof t.name=="string"&&typeof t.awaitHandlers=="boolean"},Fo="gen_ai.operation.name",Uo="gen_ai.system",Xa="gen_ai.request.model",Bo="gen_ai.response.model",er="gen_ai.usage.input_tokens",tr="gen_ai.usage.output_tokens",nr="gen_ai.usage.total_tokens",zo="gen_ai.request.max_tokens",Ho="gen_ai.request.temperature",Go="gen_ai.request.top_p",Vo="gen_ai.request.frequency_penalty",Zo="gen_ai.request.presence_penalty",qo="gen_ai.response.finish_reasons",Jo="gen_ai.prompt",Wo="gen_ai.completion",Ko="gen_ai.request.extra_query",Yo="gen_ai.request.extra_body",Qo="gen_ai.serialized.name",Xo="gen_ai.serialized.signature",ec="gen_ai.serialized.doc",tc="gen_ai.response.id",nc="gen_ai.response.service_tier",ac="gen_ai.response.system_fingerprint",rc="gen_ai.usage.input_token_details",sc="gen_ai.usage.output_token_details",ic="langsmith.trace.session_id",oc="langsmith.trace.session_name",cc="langsmith.span.kind",lc="langsmith.trace.name",uc="langsmith.metadata",ar="langsmith.span.tags",dc="langsmith.request.streaming",hc="langsmith.request.headers",pc=(...e)=>fetch(...e),ls=Symbol.for("ls:fetch_implementation"),fc=()=>{const e=globalThis[ls];return e?typeof e=="function"&&"Headers"in e&&"Request"in e&&"Response"in e:!1},mc=e=>async(...t)=>{if(e||le("DEBUG")==="true"){const[a,r]=t;console.log(`→ ${r?.method||"GET"} ${a}`)}const n=await(globalThis[ls]??pc)(...t);return(e||le("DEBUG")==="true")&&console.log(`← ${n.status} ${n.statusText} ${n.url}`),n},us=()=>le("PROJECT")??xe("LANGCHAIN_SESSION")??"default",ds="0.3.75";var Fn={};let Ae;const gc=()=>typeof window<"u"&&typeof window.document<"u",_c=()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope",yc=()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),hs=()=>typeof Deno<"u",wc=()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!hs(),ps=()=>Ae||(typeof Bun<"u"?Ae="bun":gc()?Ae="browser":wc()?Ae="node":_c()?Ae="webworker":yc()?Ae="jsdom":hs()?Ae="deno":Ae="other",Ae);let vn;function fs(){if(vn===void 0){const e=ps(),t=vc();vn={library:"langsmith",runtime:e,sdk:"langsmith-js",sdk_version:ds,...t}}return vn}function ms(){const e=bc(),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 bc(){const e={};try{if(typeof process<"u"&&Fn)for(const[t,n]of Object.entries(Fn))(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 xe(e){try{return typeof process<"u"?Fn?.[e]:void 0}catch{return}}function le(e){return xe(`LANGSMITH_${e}`)||xe(`LANGCHAIN_${e}`)}let Tn;function vc(){if(Tn!==void 0)return Tn;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=xe(n);a!==void 0&&(t[n]=a)}return Tn=t,t}function gs(){return xe("OTEL_ENABLED")==="true"||le("OTEL_ENABLED")==="true"}class Tc{constructor(){Object.defineProperty(this,"hasWarned",{enumerable:!0,configurable:!0,writable:!0,value:!1})}startActiveSpan(t,...n){!this.hasWarned&&gs()&&(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 Ec{constructor(){Object.defineProperty(this,"mockTracer",{enumerable:!0,configurable:!0,writable:!0,value:new Tc})}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 Sc{active(){return{}}with(t,n){return n()}}const En=Symbol.for("ls:otel_trace"),Sn=Symbol.for("ls:otel_context"),rr=Symbol.for("ls:otel_get_default_otlp_tracer_provider"),Ac=new Ec,Ic=new Sc;class Oc{getTraceInstance(){return globalThis[En]??Ac}getContextInstance(){return globalThis[Sn]??Ic}initializeGlobalInstances(t){globalThis[En]===void 0&&(globalThis[En]=t.trace),globalThis[Sn]===void 0&&(globalThis[Sn]=t.context)}setDefaultOTLPTracerComponents(t){globalThis[rr]=t}getDefaultOTLPTracerComponents(){return globalThis[rr]??void 0}}const Ta=new Oc;function _s(){return Ta.getTraceInstance()}function Cc(){return Ta.getContextInstance()}function xc(){return Ta.getDefaultOTLPTracerComponents()}const Nc={llm:"chat",tool:"execute_tool",retriever:"embeddings",embedding:"embeddings",prompt:"chat"};function kc(e){return Nc[e]||e}class Rc{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&&_s().getSpan(a);if(r)try{return this.finishSpanSetup(r,n,t)}catch(s){console.error(`Failed to create span for run ${t.id}:`,s);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(cc,n.run_type);const o=kc(n.run_type||"chain");t.setAttribute(Fo,o)}"name"in n&&n.name&&t.setAttribute(lc,n.name),"session_id"in n&&n.session_id&&t.setAttribute(ic,n.session_id),"session_name"in n&&n.session_name&&t.setAttribute(oc,n.session_name),this.setGenAiSystem(t,n);const r=this.extractModelName(n);r&&t.setAttribute(Xa,r),"prompt_tokens"in n&&typeof n.prompt_tokens=="number"&&t.setAttribute(er,n.prompt_tokens),"completion_tokens"in n&&typeof n.completion_tokens=="number"&&t.setAttribute(tr,n.completion_tokens),"total_tokens"in n&&typeof n.total_tokens=="number"&&t.setAttribute(nr,n.total_tokens),this.setInvocationParameters(t,n);const s=n.extra?.metadata||{};for(const[o,c]of Object.entries(s))c!=null&&t.setAttribute(`${uc}.${o}`,String(c));const i=n.tags;if(i&&Array.isArray(i)?t.setAttribute(ar,i.join(", ")):i&&t.setAttribute(ar,String(i)),"serialized"in n&&typeof n.serialized=="object"){const o=n.serialized;o.name&&t.setAttribute(Qo,String(o.name)),o.signature&&t.setAttribute(Xo,String(o.signature)),o.doc&&t.setAttribute(ec,String(o.doc))}this.setIOAttributes(t,a)}setGenAiSystem(t,n){let a="langchain";const r=this.extractModelName(n);if(r){const s=r.toLowerCase();s.includes("anthropic")||s.startsWith("claude")?a="anthropic":s.includes("bedrock")?a="aws.bedrock":s.includes("azure")&&s.includes("openai")?a="az.ai.openai":s.includes("azure")&&s.includes("inference")?a="az.ai.inference":s.includes("cohere")?a="cohere":s.includes("deepseek")?a="deepseek":s.includes("gemini")?a="gemini":s.includes("groq")?a="groq":s.includes("watson")||s.includes("ibm")?a="ibm.watsonx.ai":s.includes("mistral")?a="mistral_ai":s.includes("gpt")||s.includes("openai")?a="openai":s.includes("perplexity")||s.includes("sonar")?a="perplexity":s.includes("vertex")?a="vertex_ai":(s.includes("xai")||s.includes("grok"))&&(a="xai")}t.setAttribute(Uo,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(zo,a.max_tokens),a.temperature!==void 0&&t.setAttribute(Ho,a.temperature),a.top_p!==void 0&&t.setAttribute(Go,a.top_p),a.frequency_penalty!==void 0&&t.setAttribute(Vo,a.frequency_penalty),a.presence_penalty!==void 0&&t.setAttribute(Zo,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(Xa,a.model),a.stream!==void 0&&t.setAttribute(dc,a.stream),a.extra_headers&&t.setAttribute(hc,JSON.stringify(a.extra_headers)),a.extra_query&&t.setAttribute(Ko,JSON.stringify(a.extra_query)),a.extra_body&&t.setAttribute(Yo,JSON.stringify(a.extra_body))),t.setAttribute(Jo,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(er,r[0]),t.setAttribute(tr,r[1]),t.setAttribute(nr,r[0]+r[1])),a&&typeof a=="object"){if(a.model&&t.setAttribute(Bo,String(a.model)),a.id&&t.setAttribute(tc,a.id),a.choices&&Array.isArray(a.choices)){const s=a.choices.map(i=>i.finish_reason).filter(i=>i).map(String);s.length>0&&t.setAttribute(qo,s.join(", "))}if(a.service_tier&&t.setAttribute(nc,a.service_tier),a.system_fingerprint&&t.setAttribute(ac,a.system_fingerprint),a.usage_metadata&&typeof a.usage_metadata=="object"){const s=a.usage_metadata;s.input_token_details&&t.setAttribute(rc,JSON.stringify(s.input_token_details)),s.output_token_details&&t.setAttribute(sc,JSON.stringify(s.output_token_details))}}t.setAttribute(Wo,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 i of a){const o=t[i];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 s=Array.isArray(r[0])?r.flat():r;for(const i of s)if(typeof i=="object"&&i.message&&typeof i.message=="object"&&i.message.kwargs&&typeof i.message.kwargs=="object"&&(n=this.extractUnifiedRunTokens(i.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 Pc=[429,500,502,503,504];let sr=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 Pe?this.queue=new Pe.default({concurrency:this.maxConcurrency}):this.queue=new Pe({concurrency:this.maxConcurrency}),this.onFailedResponseHook=t?.onFailedResponseHook}call(t,...n){const a=this.onFailedResponseHook;return this.queue.add(()=>Ht(()=>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 s=r?.response;if(a&&await a(s))return;const i=s?.status??r?.status;if(i&&!Pc.includes(+i))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,s)=>{t.signal?.addEventListener("abort",()=>{s(new Error("AbortError"))})})]):this.call(n,...a)}};function ir(e){return typeof e?._getType=="function"}function or(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 Mc=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function R(e,t){if(!Mc.test(e)){const n=t!==void 0?`Invalid UUID for ${t}: ${e}`:`Invalid UUID: ${e}`;throw new Error(n)}return e}const cr={};function Un(e){cr[e]||(console.warn(e),cr[e]=!0)}function je(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,s]=t.split("/",2);if(!r||!s)throw new Error(`Invalid identifier format: ${e}`);return[r,s,a]}else{if(!t)throw new Error(`Invalid identifier format: ${e}`);return["-",t,a]}}class Lc 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 O(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 Lc(r);const s=new Error(r);throw s.status=e.status,s}const ys="ERR_CONFLICTING_ENDPOINTS";class $c 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:ys}),this.name="ConflictingEndpointsError"}}function jc(e){return typeof e=="object"&&e!==null&&e.code===ys}var lr="[...]",Dc={result:"[Circular]"},Zt=[],it=[];const Fc=new TextEncoder;function Uc(){return{depthLimit:Number.MAX_SAFE_INTEGER,edgesLimit:Number.MAX_SAFE_INTEGER}}function Lt(e){return Fc.encode(e)}function ws(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 Bc(e){return function(t,n){return ws(n)}}function de(e,t,n,a,r){try{const s=JSON.stringify(e,Bc(n),a);return Lt(s)}catch(s){if(!s.message?.includes("Converting circular structure to JSON"))return console.warn(`[WARNING]: LangSmith received unserializable value.${t?`
17
+ `)}function ko(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 va(e){const t=ko(e);switch(t.type){case"human":return new $e(t.data);case"ai":return new Be(t.data);case"system":return new ze(t.data);case"function":if(t.data.name===void 0)throw new Error("Name must be defined for function messages");return new an(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 pt(t.data);case"generic":if(t.data.role===void 0)throw new Error("Role must be defined for chat messages");return new Ct(t.data);default:throw new Error(`Got unexpected type: ${t.type}`)}}function Ro(e){return e.map(va)}function Po(e){return e.map(t=>t.toDict())}function Vt(e){const t=e._getType();if(t==="human")return new sn({...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 tt({...n})}else{if(t==="system")return new ut({...e});if(t==="function")return new rn({...e});if(Ct.isInstance(e))return new nn({...e});throw new Error("Unknown message type.")}}const es=Symbol.for("ls:tracing_async_local_storage"),bt=Symbol.for("lc:context_variables"),Mo=e=>{globalThis[es]=e},Tt=()=>globalThis[es];var Lo={},$o={};F($o,{getEnv:()=>ss,getEnvironmentVariable:()=>Fe,getRuntimeEnvironment:()=>is,isBrowser:()=>ts,isDeno:()=>on,isJsDom:()=>as,isNode:()=>rs,isWebWorker:()=>ns});const ts=()=>typeof window<"u"&&typeof window.document<"u",ns=()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope",as=()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),on=()=>typeof Deno<"u",rs=()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!on(),ss=()=>{let e;return ts()?e="browser":rs()?e="node":ns()?e="webworker":as()?e="jsdom":on()?e="deno":e="other",e};let bn;function is(){return bn===void 0&&(bn={library:"langchain-js",runtime:ss()}),bn}function Fe(e){try{return typeof process<"u"?Lo?.[e]:on()?Deno?.env.get(e):void 0}catch{return}}var jo={};F(jo,{BaseCallbackHandler:()=>xt,callbackHandlerPrefersStreaming:()=>os,isBaseCallbackHandler:()=>cs});var Do=class{};function os(e){return"lc_prefer_streaming"in e&&e.lc_prefer_streaming}var xt=class extends Do{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,pa(this.constructor)]}lc_kwargs;ignoreLLM=!1;ignoreChain=!1;ignoreAgent=!1;ignoreRetriever=!1;ignoreCustomEvent=!1;raiseError=!1;awaitHandlers=Fe("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 lt.prototype.toJSON.call(this)}toJSONNotImplemented(){return lt.prototype.toJSONNotImplemented.call(this)}static fromMethods(e){class t extends xt{name=se();constructor(){super(),Object.assign(this,e)}}return new t}};const cs=e=>{const t=e;return t!==void 0&&typeof t.copy=="function"&&typeof t.name=="string"&&typeof t.awaitHandlers=="boolean"},Fo="gen_ai.operation.name",Uo="gen_ai.system",Xa="gen_ai.request.model",Bo="gen_ai.response.model",er="gen_ai.usage.input_tokens",tr="gen_ai.usage.output_tokens",nr="gen_ai.usage.total_tokens",zo="gen_ai.request.max_tokens",Ho="gen_ai.request.temperature",Go="gen_ai.request.top_p",Vo="gen_ai.request.frequency_penalty",Zo="gen_ai.request.presence_penalty",qo="gen_ai.response.finish_reasons",Jo="gen_ai.prompt",Wo="gen_ai.completion",Ko="gen_ai.request.extra_query",Yo="gen_ai.request.extra_body",Qo="gen_ai.serialized.name",Xo="gen_ai.serialized.signature",ec="gen_ai.serialized.doc",tc="gen_ai.response.id",nc="gen_ai.response.service_tier",ac="gen_ai.response.system_fingerprint",rc="gen_ai.usage.input_token_details",sc="gen_ai.usage.output_token_details",ic="langsmith.trace.session_id",oc="langsmith.trace.session_name",cc="langsmith.span.kind",lc="langsmith.trace.name",uc="langsmith.metadata",ar="langsmith.span.tags",dc="langsmith.request.streaming",hc="langsmith.request.headers",pc=(...e)=>fetch(...e),ls=Symbol.for("ls:fetch_implementation"),fc=()=>{const e=globalThis[ls];return e?typeof e=="function"&&"Headers"in e&&"Request"in e&&"Response"in e:!1},mc=e=>async(...t)=>{if(e||le("DEBUG")==="true"){const[a,r]=t;console.log(`→ ${r?.method||"GET"} ${a}`)}const n=await(globalThis[ls]??pc)(...t);return(e||le("DEBUG")==="true")&&console.log(`← ${n.status} ${n.statusText} ${n.url}`),n},us=()=>le("PROJECT")??xe("LANGCHAIN_SESSION")??"default",ds="0.3.79";var Fn={};let Ae;const gc=()=>typeof window<"u"&&typeof window.document<"u",_c=()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope",yc=()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),hs=()=>typeof Deno<"u",wc=()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!hs(),ps=()=>Ae||(typeof Bun<"u"?Ae="bun":gc()?Ae="browser":wc()?Ae="node":_c()?Ae="webworker":yc()?Ae="jsdom":hs()?Ae="deno":Ae="other",Ae);let vn;function fs(){if(vn===void 0){const e=ps(),t=vc();vn={library:"langsmith",runtime:e,sdk:"langsmith-js",sdk_version:ds,...t}}return vn}function ms(){const e=bc(),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 bc(){const e={};try{if(typeof process<"u"&&Fn)for(const[t,n]of Object.entries(Fn))(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 xe(e){try{return typeof process<"u"?Fn?.[e]:void 0}catch{return}}function le(e){return xe(`LANGSMITH_${e}`)||xe(`LANGCHAIN_${e}`)}let Tn;function vc(){if(Tn!==void 0)return Tn;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=xe(n);a!==void 0&&(t[n]=a)}return Tn=t,t}function gs(){return xe("OTEL_ENABLED")==="true"||le("OTEL_ENABLED")==="true"}class Tc{constructor(){Object.defineProperty(this,"hasWarned",{enumerable:!0,configurable:!0,writable:!0,value:!1})}startActiveSpan(t,...n){!this.hasWarned&&gs()&&(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 Ec{constructor(){Object.defineProperty(this,"mockTracer",{enumerable:!0,configurable:!0,writable:!0,value:new Tc})}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 Sc{active(){return{}}with(t,n){return n()}}const En=Symbol.for("ls:otel_trace"),Sn=Symbol.for("ls:otel_context"),rr=Symbol.for("ls:otel_get_default_otlp_tracer_provider"),Ac=new Ec,Ic=new Sc;class Oc{getTraceInstance(){return globalThis[En]??Ac}getContextInstance(){return globalThis[Sn]??Ic}initializeGlobalInstances(t){globalThis[En]===void 0&&(globalThis[En]=t.trace),globalThis[Sn]===void 0&&(globalThis[Sn]=t.context)}setDefaultOTLPTracerComponents(t){globalThis[rr]=t}getDefaultOTLPTracerComponents(){return globalThis[rr]??void 0}}const Ta=new Oc;function _s(){return Ta.getTraceInstance()}function Cc(){return Ta.getContextInstance()}function xc(){return Ta.getDefaultOTLPTracerComponents()}const Nc={llm:"chat",tool:"execute_tool",retriever:"embeddings",embedding:"embeddings",prompt:"chat"};function kc(e){return Nc[e]||e}class Rc{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&&_s().getSpan(a);if(r)try{return this.finishSpanSetup(r,n,t)}catch(s){console.error(`Failed to create span for run ${t.id}:`,s);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(cc,n.run_type);const o=kc(n.run_type||"chain");t.setAttribute(Fo,o)}"name"in n&&n.name&&t.setAttribute(lc,n.name),"session_id"in n&&n.session_id&&t.setAttribute(ic,n.session_id),"session_name"in n&&n.session_name&&t.setAttribute(oc,n.session_name),this.setGenAiSystem(t,n);const r=this.extractModelName(n);r&&t.setAttribute(Xa,r),"prompt_tokens"in n&&typeof n.prompt_tokens=="number"&&t.setAttribute(er,n.prompt_tokens),"completion_tokens"in n&&typeof n.completion_tokens=="number"&&t.setAttribute(tr,n.completion_tokens),"total_tokens"in n&&typeof n.total_tokens=="number"&&t.setAttribute(nr,n.total_tokens),this.setInvocationParameters(t,n);const s=n.extra?.metadata||{};for(const[o,c]of Object.entries(s))c!=null&&t.setAttribute(`${uc}.${o}`,String(c));const i=n.tags;if(i&&Array.isArray(i)?t.setAttribute(ar,i.join(", ")):i&&t.setAttribute(ar,String(i)),"serialized"in n&&typeof n.serialized=="object"){const o=n.serialized;o.name&&t.setAttribute(Qo,String(o.name)),o.signature&&t.setAttribute(Xo,String(o.signature)),o.doc&&t.setAttribute(ec,String(o.doc))}this.setIOAttributes(t,a)}setGenAiSystem(t,n){let a="langchain";const r=this.extractModelName(n);if(r){const s=r.toLowerCase();s.includes("anthropic")||s.startsWith("claude")?a="anthropic":s.includes("bedrock")?a="aws.bedrock":s.includes("azure")&&s.includes("openai")?a="az.ai.openai":s.includes("azure")&&s.includes("inference")?a="az.ai.inference":s.includes("cohere")?a="cohere":s.includes("deepseek")?a="deepseek":s.includes("gemini")?a="gemini":s.includes("groq")?a="groq":s.includes("watson")||s.includes("ibm")?a="ibm.watsonx.ai":s.includes("mistral")?a="mistral_ai":s.includes("gpt")||s.includes("openai")?a="openai":s.includes("perplexity")||s.includes("sonar")?a="perplexity":s.includes("vertex")?a="vertex_ai":(s.includes("xai")||s.includes("grok"))&&(a="xai")}t.setAttribute(Uo,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(zo,a.max_tokens),a.temperature!==void 0&&t.setAttribute(Ho,a.temperature),a.top_p!==void 0&&t.setAttribute(Go,a.top_p),a.frequency_penalty!==void 0&&t.setAttribute(Vo,a.frequency_penalty),a.presence_penalty!==void 0&&t.setAttribute(Zo,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(Xa,a.model),a.stream!==void 0&&t.setAttribute(dc,a.stream),a.extra_headers&&t.setAttribute(hc,JSON.stringify(a.extra_headers)),a.extra_query&&t.setAttribute(Ko,JSON.stringify(a.extra_query)),a.extra_body&&t.setAttribute(Yo,JSON.stringify(a.extra_body))),t.setAttribute(Jo,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(er,r[0]),t.setAttribute(tr,r[1]),t.setAttribute(nr,r[0]+r[1])),a&&typeof a=="object"){if(a.model&&t.setAttribute(Bo,String(a.model)),a.id&&t.setAttribute(tc,a.id),a.choices&&Array.isArray(a.choices)){const s=a.choices.map(i=>i.finish_reason).filter(i=>i).map(String);s.length>0&&t.setAttribute(qo,s.join(", "))}if(a.service_tier&&t.setAttribute(nc,a.service_tier),a.system_fingerprint&&t.setAttribute(ac,a.system_fingerprint),a.usage_metadata&&typeof a.usage_metadata=="object"){const s=a.usage_metadata;s.input_token_details&&t.setAttribute(rc,JSON.stringify(s.input_token_details)),s.output_token_details&&t.setAttribute(sc,JSON.stringify(s.output_token_details))}}t.setAttribute(Wo,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 i of a){const o=t[i];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 s=Array.isArray(r[0])?r.flat():r;for(const i of s)if(typeof i=="object"&&i.message&&typeof i.message=="object"&&i.message.kwargs&&typeof i.message.kwargs=="object"&&(n=this.extractUnifiedRunTokens(i.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 Pc=[429,500,502,503,504];let sr=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 Pe?this.queue=new Pe.default({concurrency:this.maxConcurrency}):this.queue=new Pe({concurrency:this.maxConcurrency}),this.onFailedResponseHook=t?.onFailedResponseHook}call(t,...n){const a=this.onFailedResponseHook;return this.queue.add(()=>Ht(()=>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 s=r?.response;if(a&&await a(s))return;const i=s?.status??r?.status;if(i&&!Pc.includes(+i))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,s)=>{t.signal?.addEventListener("abort",()=>{s(new Error("AbortError"))})})]):this.call(n,...a)}};function ir(e){return typeof e?._getType=="function"}function or(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 Mc=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function R(e,t){if(!Mc.test(e)){const n=t!==void 0?`Invalid UUID for ${t}: ${e}`:`Invalid UUID: ${e}`;throw new Error(n)}return e}const cr={};function Un(e){cr[e]||(console.warn(e),cr[e]=!0)}function je(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,s]=t.split("/",2);if(!r||!s)throw new Error(`Invalid identifier format: ${e}`);return[r,s,a]}else{if(!t)throw new Error(`Invalid identifier format: ${e}`);return["-",t,a]}}class Lc 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 O(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 Lc(r);const s=new Error(r);throw s.status=e.status,s}const ys="ERR_CONFLICTING_ENDPOINTS";class $c 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:ys}),this.name="ConflictingEndpointsError"}}function jc(e){return typeof e=="object"&&e!==null&&e.code===ys}var lr="[...]",Dc={result:"[Circular]"},Zt=[],it=[];const Fc=new TextEncoder;function Uc(){return{depthLimit:Number.MAX_SAFE_INTEGER,edgesLimit:Number.MAX_SAFE_INTEGER}}function Lt(e){return Fc.encode(e)}function ws(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 Bc(e){return function(t,n){return ws(n)}}function de(e,t,n,a,r){try{const s=JSON.stringify(e,Bc(n),a);return Lt(s)}catch(s){if(!s.message?.includes("Converting circular structure to JSON"))return console.warn(`[WARNING]: LangSmith received unserializable value.${t?`
18
18
  Context: ${t}`:""}`),Lt("[Unserializable]");le("SUPPRESS_CIRCULAR_JSON_WARNINGS")!=="true"&&console.warn(`[WARNING]: LangSmith received circular JSON. This will decrease tracer performance. ${t?`
19
19
  Context: ${t}`:""}`),typeof r>"u"&&(r=Uc()),Bn(e,"",0,[],void 0,0,r);let i;try{it.length===0?i=JSON.stringify(e,n,a):i=JSON.stringify(e,zc(n),a)}catch{return Lt("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;Zt.length!==0;){const o=Zt.pop();o.length===4?Object.defineProperty(o[0],o[1],o[3]):o[0][o[1]]=o[2]}}return Lt(i)}}function An(e,t,n,a){var r=Object.getOwnPropertyDescriptor(a,n);r.get!==void 0?r.configurable?(Object.defineProperty(a,n,{value:e}),Zt.push([a,n,t,r])):it.push([t,n,e]):(a[n]=e,Zt.push([a,n,t]))}function Bn(e,t,n,a,r,s,i){s+=1;var o;if(typeof e=="object"&&e!==null){for(o=0;o<a.length;o++)if(a[o]===e){An(Dc,e,t,r);return}if(typeof i.depthLimit<"u"&&s>i.depthLimit){An(lr,e,t,r);return}if(typeof i.edgesLimit<"u"&&n+1>i.edgesLimit){An(lr,e,t,r);return}if(a.push(e),Array.isArray(e))for(o=0;o<e.length;o++)Bn(e[o],o,o,a,e,s,i);else{e=ws(e);var c=Object.keys(e);for(o=0;o<c.length;o++){var l=c[o];Bn(e[l],l,o,a,e,s,i)}}a.pop()}}function zc(e){return e=typeof e<"u"?e:function(t,n){return n},function(t,n){if(it.length>0)for(var a=0;a<it.length;a++){var r=it[a];if(r[1]===t&&r[0]===n){n=r[2],it.splice(a,1);break}}return e.call(this,t,n)}}function ur(e,t){const n=fs(),a=t??ms(),r=e.extra??{},s=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}:{},...s}},e}const Hc=e=>{const t=e?.toString()??le("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},Gc=e=>{const n=e.replace("http://","").replace("https://","").split("/")[0].split(":")[0];return n==="localhost"||n==="127.0.0.1"||n==="::1"};async function Vc(e){const t=[];for await(const n of e)t.push(n);return t}function $t(e){if(e!==void 0)return e.trim().replace(/^"(.*)"$/,"$1").replace(/^'(.*)'$/,"$1")}const Zc=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 dr(e){return typeof e=="number"?Number(e.toFixed(4)):e}class qc{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(s=>{n=s}),r=de(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 s=this.items.shift();s&&(a.push(s),r+=s.size,this.sizeBytes-=s.size)}if(a.length===0&&this.items.length>0){const s=this.items.shift();a.push(s),r+=s.size,this.sizeBytes-=s.size}return[a.map(s=>({action:s.action,item:s.payload,otelContext:s.otelContext,apiKey:s.apiKey,apiUrl:s.apiUrl})),()=>a.forEach(s=>s.itemPromiseResolve())]}}const Jc=24*1024*1024,Wc=1e4,Kc=100,hr="https://api.smith.langchain.com";class Et{get _fetch(){return this.fetchImplementation||mc(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 qc}),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:xe("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:xe("LANGSMITH_DEBUG")==="true"});const n=Et.getDefaultClientConfig();if(this.tracingSampleRate=Hc(t.tracingSamplingRate),this.apiUrl=$t(t.apiUrl??n.apiUrl)??"",this.apiUrl.endsWith("/")&&(this.apiUrl=this.apiUrl.slice(0,-1)),this.apiKey=$t(t.apiKey??n.apiKey),this.webUrl=$t(t.webUrl??n.webUrl),this.webUrl?.endsWith("/")&&(this.webUrl=this.webUrl.slice(0,-1)),this.workspaceId=$t(t.workspaceId??le("WORKSPACE_ID")),this.timeout_ms=t.timeout_ms??9e4,this.caller=new sr({...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 sr({maxRetries:2,maxConcurrency:this.traceBatchConcurrency,...t.callerOptions??{},onFailedResponseHook:Zc,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,gs()&&(this.langSmithToOTELTranslator=new Rc),this.cachedLSEnvVarsForMetadata=ms()}static getDefaultClientConfig(){const t=le("API_KEY"),n=le("ENDPOINT")??hr,a=le("HIDE_INPUTS")==="true",r=le("HIDE_OUTPUTS")==="true";return{apiUrl:n,apiKey:t,webUrl:void 0,hideInputs:a,hideOutputs:r}}getHostUrl(){return this.webUrl?this.webUrl:Gc(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/${ds}`};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 i=await this._fetch(r,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await O(i,`fetch ${t}`),i})}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 s=Number(n.get("limit"))||100;for(;;){n.set("offset",String(r)),n.set("limit",String(s));const i=`${this.apiUrl}${t}?${n}`,o=await this.caller.call(async()=>{const l=await this._fetch(i,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await O(l,`fetch ${t}`),l}),c=a?a(await o.json()):await o.json();if(c.length===0||(yield c,c.length<s))break;r+=c.length}}async*_getCursorPaginatedList(t,n=null,a="POST",r="runs"){const s=n?{...n}:{};for(;;){const i=JSON.stringify(s),c=await(await this.caller.call(async()=>{const d=await this._fetch(`${this.apiUrl}${t}`,{method:a,headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await O(d,`fetch ${t}`),d})).json();if(!c||!c[r])break;yield c[r];const l=c.cursors;if(!l||!l.next)break;s.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 s=r.trace_id??r.id;this.filteredPostUuids.has(s)||(r.id===s?this._shouldSample()?a.push(r):this.filteredPostUuids.add(s):a.push(r))}return a}}async _getBatchSizeLimitBytes(){const t=await this._ensureServerInfo();return this.batchSizeBytesLimit??t.batch_ingest_config?.size_limit_bytes??Jc}async _getBatchSizeLimit(){const t=await this._ensureServerInfo();return this.batchSizeLimit??t.batch_ingest_config?.size_limit??Kc}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,s]=this.autoBatchQueue.pop({upToSizeBytes:t,upToSize:n});if(!r.length){s();break}const i=r.reduce((l,d)=>{const p=d.apiUrl??this.apiUrl,f=d.apiKey??this.apiKey,y=d.apiKey===this.apiKey&&d.apiUrl===this.apiUrl?"default":`${p}|${f}`;return l[y]||(l[y]=[]),l[y].push(d),l},{}),o=[];for(const[l,d]of Object.entries(i)){const p=this._processBatch(d,{apiUrl:l==="default"?void 0:l.split("|")[0],apiKey:l==="default"?void 0:l.split("|")[1]});o.push(p)}const c=Promise.all(o).finally(s);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(s=>s.action==="create").map(s=>s.item),runUpdates:t.filter(s=>s.action==="update").map(s=>s.item)},r=await this._ensureServerInfo();if(r?.batch_ingest_config?.use_multipart_endpoint){const s=r?.instance_flags?.gzip_body_enabled;await this.multipartIngestRuns(a,{...n,useGzip:s})}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=ur(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(Wc),...this.fetchOptions});return await O(a,"get server info"),a})).json();return this.debug&&console.log(`
20
20
  === LangSmith Server Configuration ===
@@ -46,16 +46,12 @@ Message: ${Array.isArray(i.detail)?i.detail.join(`
46
46
  creating a LangChain Hub handle.
47
47
  You can add a handle by creating a public prompt at:
48
48
 
49
- https://smith.langchain.com/prompts`);const[r,s,i]=je(t);if(!await this._currentTenantIsOwner(r))throw await this._ownerConflictError("create a prompt",r);const o={repo_handle:s,...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 p=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 O(p,"create prompt"),p}),{repo:d}=await l.json();return d}async createCommit(t,n,a){if(!await this.promptExists(t))throw new Error("Prompt does not exist, you must create it first.");const[r,s,i]=je(t),o=a?.parentCommitHash==="latest"||!a?.parentCommitHash?await this._getLatestCommitHash(`${r}/${s}`):a?.parentCommitHash,c={manifest:JSON.parse(JSON.stringify(n)),parent_commit:o},l=JSON.stringify(c),p=await(await this.caller.call(async()=>{const f=await this._fetch(`${this.apiUrl}/commits/${r}/${s}`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:l});return await O(f,"create commit"),f})).json();return this._getPromptUrl(`${r}/${s}${p.commit_hash?`:${p.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 i of n){const o=i.id,c={...i.metadata&&{metadata:i.metadata},...i.split&&{split:i.split}},l=de(c,`Serializing body for example with id: ${o}`),d=new Blob([l],{type:"application/json"});if(a.append(o,d),i.inputs){const p=de(i.inputs,`Serializing inputs for example with id: ${o}`),f=new Blob([p],{type:"application/json"});a.append(`${o}.inputs`,f)}if(i.outputs){const p=de(i.outputs,`Serializing outputs whle updating example with id: ${o}`),f=new Blob([p],{type:"application/json"});a.append(`${o}.outputs`,f)}if(i.attachments)for(const[p,f]of Object.entries(i.attachments)){let m,y;Array.isArray(f)?[m,y]=f:(m=f.mimeType,y=f.data);const b=new Blob([y],{type:`${m}; length=${y.byteLength}`});a.append(`${o}.attachment.${p}`,b)}if(i.attachments_operations){const p=de(i.attachments_operations,`Serializing attachments while updating example with id: ${o}`),f=new Blob([p],{type:"application/json"});a.append(`${o}.attachments_operations`,f)}}const r=t??n[0]?.dataset_id;return(await this.caller.call(async()=>{const i=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 O(i,"update examples"),i})).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 s of n){const i=(s.id??se()).toString(),o={created_at:s.created_at,...s.metadata&&{metadata:s.metadata},...s.split&&{split:s.split},...s.source_run_id&&{source_run_id:s.source_run_id},...s.use_source_run_io&&{use_source_run_io:s.use_source_run_io},...s.use_source_run_attachments&&{use_source_run_attachments:s.use_source_run_attachments}},c=de(o,`Serializing body for uploaded example with id: ${i}`),l=new Blob([c],{type:"application/json"});if(a.append(i,l),s.inputs){const d=de(s.inputs,`Serializing inputs for uploaded example with id: ${i}`),p=new Blob([d],{type:"application/json"});a.append(`${i}.inputs`,p)}if(s.outputs){const d=de(s.outputs,`Serializing outputs for uploaded example with id: ${i}`),p=new Blob([d],{type:"application/json"});a.append(`${i}.outputs`,p)}if(s.attachments)for(const[d,p]of Object.entries(s.attachments)){let f,m;Array.isArray(p)?[f,m]=p:(f=p.mimeType,m=p.data);const y=new Blob([m],{type:`${f}; length=${m.byteLength}`});a.append(`${i}.attachment.${d}`,y)}}return(await this.caller.call(async()=>{const s=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 O(s,"upload examples"),s})).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]=je(t);if(!await this._currentTenantIsOwner(a))throw await this._ownerConflictError("update a prompt",a);const s={};if(n?.description!==void 0&&(s.description=n.description),n?.readme!==void 0&&(s.readme=n.readme),n?.tags!==void 0&&(s.tags=n.tags),n?.isPublic!==void 0&&(s.is_public=n.isPublic),n?.isArchived!==void 0&&(s.is_archived=n.isArchived),Object.keys(s).length===0)throw new Error("No valid update options provided");const i=JSON.stringify(s);return(await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/repos/${a}/${r}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await O(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]=je(t);if(!await this._currentTenantIsOwner(n))throw await this._ownerConflictError("delete a prompt",n);return(await this.caller.call(async()=>{const i=await this._fetch(`${this.apiUrl}/repos/${n}/${a}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await O(i,"delete prompt"),i})).json()}async pullPromptCommit(t,n){const[a,r,s]=je(t),o=await(await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/commits/${a}/${r}/${s}${n?.includeModel?"?include_model=true":""}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await O(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,[s,i]=this.parseTokenOrUrl(t,a),o=new Et({apiUrl:s,apiKey:"placeholder"}),c=await o.readSharedDataset(i),l=r||c.name;try{if(await this.hasDataset({datasetId:l})){console.log(`Dataset ${l} already exists in your tenant. Skipping.`);return}}catch{}const d=await o.listSharedExamples(i),p=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:d.map(f=>f.inputs),outputs:d.flatMap(f=>f.outputs?[f.outputs]:[]),datasetId:p.id})}catch(f){throw console.error(`An error occurred while creating dataset ${l}. You should delete it manually.`),f}}parseTokenOrUrl(t,n,a=2,r="dataset"){try{return R(t),[n,t]}catch{}try{const i=new URL(t).pathname.split("/").filter(o=>o!=="");if(i.length>=a){const o=i[i.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 xc()?.DEFAULT_LANGSMITH_SPAN_PROCESSOR?.forceFlush()}}function pr(e){return"dataset_id"in e||"dataset_name"in e}const Yc=e=>!!["TRACING_V2","TRACING"].find(n=>le(n)==="true"),In=Symbol.for("lc:context_variables");function Qc(e){return e.replace(/[-:.]/g,"")}function bs(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:Qc(r)+t,microsecondPrecisionDatestring:r}}class qt{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=[],s,i;for(const o of n){const[c,l]=o.split("="),d=decodeURIComponent(l);c==="langsmith-metadata"?a=JSON.parse(d):c==="langsmith-tags"?r=d.split(","):c==="langsmith-project"?s=d:c==="langsmith-replicas"&&(i=JSON.parse(d))}return new qt(a,r,s,i)}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 ce{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}),Xc(t)){Object.assign(this,{...t});return}const n=ce.getDefaultConfig(),{metadata:a,...r}=t,s=r.client??ce.getSharedClient(),i={...a,...r?.extra?.metadata};if(r.extra={...r.extra,metadata:i},Object.assign(this,{...n,...r,client:s}),this.trace_id||(this.parent_run?this.trace_id=this.parent_run.trace_id??this.id:this.trace_id=this.id),this.replicas=rl(this.replicas),this.execution_order??=1,this.child_execution_order??=1,!this.dotted_order){const{dottedOrder:o,microsecondPrecisionDatestring:c}=bs(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:se(),run_type:"chain",project_name:us(),child_runs:[],api_url:xe("LANGCHAIN_ENDPOINT")??"http://localhost:1984",api_key:xe("LANGCHAIN_API_KEY"),caller_options:{},start_time:Date.now(),serialized:{},inputs:{},extra:{}}}static getSharedClient(){return ce.sharedClient||(ce.sharedClient=new Et),ce.sharedClient}createChild(t){const n=this.child_execution_order+1,a=new ce({...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});In in this&&(a[In]=this[In]);const r=Symbol.for("lc:child_config"),s=t.extra?.[r]??this.extra[r];if(tl(s)){const c={...s},l=el(c.callbacks)?c.callbacks.copy?.():void 0;l&&(Object.assign(l,{_parentRunId:a.id}),l.handlers?.find(vs)?.updateFromRunTree?.(a),c.callbacks=l),a.extra[r]=c}const i=new Set;let o=this;for(;o!=null&&!i.has(o.id);)i.add(o.id),o.child_execution_order=Math.max(o.child_execution_order,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 s,i;return a?(i=t.parent_run?.id??t.parent_run_id,s=[]):(s=t.child_runs.map(o=>this._convertToCreate(o,n,a)),i=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:s,parent_run_id:i,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 s=p=>Ga(`${p}:${t}`,Ga.DNS),i=s(r.id),o=r.trace_id?s(r.trace_id):void 0,c=r.parent_run_id?s(r.parent_run_id):void 0;let l;if(r.dotted_order){const p=nl(r.dotted_order),f=[];for(let y=0;y<p.length-1;y++){const[b,T]=p[y],v=s(T);f.push(b.toISOString().replace(/[-:]/g,"").replace(".","")+v)}const[m]=p[p.length-1];f.push(m.toISOString().replace(/[-:]/g,"").replace(".","")+i),l=f.join(".")}else l=void 0;return{...r,id:i,trace_id:o,parent_run_id:c,dotted_order:l,session_name:t}}async postRun(t=!0){try{const n=fs();if(this.replicas&&this.replicas.length>0)for(const{projectName:a,apiKey:r,apiUrl:s,workspaceId:i}of this.replicas){const o=this._remapForProject(a??this.project_name,n,!0);await this.client.createRun(o,{apiKey:r,apiUrl:s,workspaceId:i})}else{const a=this._convertToCreate(this,n,t);await this.client.createRun(a)}if(!t){Un("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:s,updates:i}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,...i};t?.excludeInputs||(c.inputs=o.inputs),await this.client.updateRun(o.id,c,{apiKey:a,apiUrl:r,workspaceId:s})}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,s,i,o=Yc();if(a){const l=a?.getParentRunId?.()??"",d=a?.handlers?.find(p=>p?.name=="langchain_tracer");r=d?.getRun?.(l),s=d?.projectName,i=d?.client,o=o||!!d}return r?new ce({name:r.name,id:r.id,trace_id:r.trace_id,dotted_order:r.dotted_order,client:i,tracingEnabled:o,project_name:s,tags:[...new Set((r?.tags??[]).concat(t?.tags??[]))],extra:{metadata:{...r?.extra?.metadata,...t?.metadata}}}).createChild(n):new ce({...n,client:i,tracingEnabled:o,project_name:s})}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 s=r.trim(),i=s.split(".").map(l=>{const[d,p]=l.split("Z");return{strTime:d,time:Date.parse(d+"Z"),uuid:p}}),o=i[0].uuid,c={...n,name:n?.name??"parent",run_type:n?.run_type??"chain",start_time:n?.start_time??Date.now(),id:i.at(-1)?.uuid,trace_id:o,dotted_order:s};if(a.baggage&&typeof a.baggage=="string"){const l=qt.fromHeader(a.baggage);c.metadata=l.metadata,c.tags=l.tags,c.project_name=l.project_name,c.replicas=l.replicas}return new ce(c)}toHeaders(t){const n={"langsmith-trace":this.dotted_order,baggage:new qt(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(ce,"sharedClient",{enumerable:!0,configurable:!0,writable:!0,value:null});function Xc(e){return e!=null&&typeof e.createChild=="function"&&typeof e.postRun=="function"}function vs(e){return typeof e=="object"&&e!=null&&typeof e.name=="string"&&e.name==="langchain_tracer"}function fr(e){return Array.isArray(e)&&e.some(t=>vs(t))}function el(e){return typeof e=="object"&&e!=null&&Array.isArray(e.handlers)}function tl(e){return e!=null&&typeof e.callbacks=="object"&&(fr(e.callbacks?.handlers)||fr(e.callbacks))}function nl(e){return e.split(".").map(n=>{const a=n.slice(0,-36),r=n.slice(-36),s=parseInt(a.slice(0,4)),i=parseInt(a.slice(4,6))-1,o=parseInt(a.slice(6,8)),c=parseInt(a.slice(9,11)),l=parseInt(a.slice(11,13)),d=parseInt(a.slice(13,15)),p=parseInt(a.slice(15,21));return[new Date(s,i,o,c,l,d,p/1e3),r]})}function al(){const e=xe("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){sl(t);const n=[];for(const[a,r]of Object.entries(t)){const s=a.replace(/\/$/,"");if(typeof r=="string")n.push({apiUrl:s,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(jc(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 rl(e){return e?e.map(t=>Array.isArray(t)?{projectName:t[0],updates:t[1]}:t):al()}function sl(e){if(Object.keys(e).length>0&&le("ENDPOINT"))throw new $c}var il={};F(il,{BaseTracer:()=>ft,isBaseTracer:()=>st});const ol=e=>{if(e)return e.events=e.events??[],e.child_runs=e.child_runs??[],e};function zn(e,t){if(e)return new ce({...e,start_time:e._serialized_start_time??e.start_time,parent_run:zn(t),child_runs:e.child_runs.map(n=>zn(n)).filter(n=>n!==void 0),extra:{...e.extra,runtime:is()},tracingEnabled:!1})}function On(e,t){return e&&!Array.isArray(e)&&typeof e=="object"?e:{[t]:e}}function st(e){return typeof e._addRunToRunMap=="function"}var ft=class extends xt{runMap=new Map;runTreeMap=new Map;usesRunTreeMap=!1;constructor(e){super(...arguments)}copy(){return this}getRunById(e){if(e!==void 0)return this.usesRunTreeMap?ol(this.runTreeMap.get(e)):this.runMap.get(e)}stringifyError(e){return e instanceof Error?e.message+(e?.stack?`
49
+ https://smith.langchain.com/prompts`);const[r,s,i]=je(t);if(!await this._currentTenantIsOwner(r))throw await this._ownerConflictError("create a prompt",r);const o={repo_handle:s,...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 p=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 O(p,"create prompt"),p}),{repo:d}=await l.json();return d}async createCommit(t,n,a){if(!await this.promptExists(t))throw new Error("Prompt does not exist, you must create it first.");const[r,s,i]=je(t),o=a?.parentCommitHash==="latest"||!a?.parentCommitHash?await this._getLatestCommitHash(`${r}/${s}`):a?.parentCommitHash,c={manifest:JSON.parse(JSON.stringify(n)),parent_commit:o},l=JSON.stringify(c),p=await(await this.caller.call(async()=>{const f=await this._fetch(`${this.apiUrl}/commits/${r}/${s}`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:l});return await O(f,"create commit"),f})).json();return this._getPromptUrl(`${r}/${s}${p.commit_hash?`:${p.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 i of n){const o=i.id,c={...i.metadata&&{metadata:i.metadata},...i.split&&{split:i.split}},l=de(c,`Serializing body for example with id: ${o}`),d=new Blob([l],{type:"application/json"});if(a.append(o,d),i.inputs){const p=de(i.inputs,`Serializing inputs for example with id: ${o}`),f=new Blob([p],{type:"application/json"});a.append(`${o}.inputs`,f)}if(i.outputs){const p=de(i.outputs,`Serializing outputs whle updating example with id: ${o}`),f=new Blob([p],{type:"application/json"});a.append(`${o}.outputs`,f)}if(i.attachments)for(const[p,f]of Object.entries(i.attachments)){let m,y;Array.isArray(f)?[m,y]=f:(m=f.mimeType,y=f.data);const b=new Blob([y],{type:`${m}; length=${y.byteLength}`});a.append(`${o}.attachment.${p}`,b)}if(i.attachments_operations){const p=de(i.attachments_operations,`Serializing attachments while updating example with id: ${o}`),f=new Blob([p],{type:"application/json"});a.append(`${o}.attachments_operations`,f)}}const r=t??n[0]?.dataset_id;return(await this.caller.call(async()=>{const i=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 O(i,"update examples"),i})).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 s of n){const i=(s.id??se()).toString(),o={created_at:s.created_at,...s.metadata&&{metadata:s.metadata},...s.split&&{split:s.split},...s.source_run_id&&{source_run_id:s.source_run_id},...s.use_source_run_io&&{use_source_run_io:s.use_source_run_io},...s.use_source_run_attachments&&{use_source_run_attachments:s.use_source_run_attachments}},c=de(o,`Serializing body for uploaded example with id: ${i}`),l=new Blob([c],{type:"application/json"});if(a.append(i,l),s.inputs){const d=de(s.inputs,`Serializing inputs for uploaded example with id: ${i}`),p=new Blob([d],{type:"application/json"});a.append(`${i}.inputs`,p)}if(s.outputs){const d=de(s.outputs,`Serializing outputs for uploaded example with id: ${i}`),p=new Blob([d],{type:"application/json"});a.append(`${i}.outputs`,p)}if(s.attachments)for(const[d,p]of Object.entries(s.attachments)){let f,m;Array.isArray(p)?[f,m]=p:(f=p.mimeType,m=p.data);const y=new Blob([m],{type:`${f}; length=${m.byteLength}`});a.append(`${i}.attachment.${d}`,y)}}return(await this.caller.call(async()=>{const s=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 O(s,"upload examples"),s})).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]=je(t);if(!await this._currentTenantIsOwner(a))throw await this._ownerConflictError("update a prompt",a);const s={};if(n?.description!==void 0&&(s.description=n.description),n?.readme!==void 0&&(s.readme=n.readme),n?.tags!==void 0&&(s.tags=n.tags),n?.isPublic!==void 0&&(s.is_public=n.isPublic),n?.isArchived!==void 0&&(s.is_archived=n.isArchived),Object.keys(s).length===0)throw new Error("No valid update options provided");const i=JSON.stringify(s);return(await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/repos/${a}/${r}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await O(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]=je(t);if(!await this._currentTenantIsOwner(n))throw await this._ownerConflictError("delete a prompt",n);return(await this.caller.call(async()=>{const i=await this._fetch(`${this.apiUrl}/repos/${n}/${a}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await O(i,"delete prompt"),i})).json()}async pullPromptCommit(t,n){const[a,r,s]=je(t),o=await(await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/commits/${a}/${r}/${s}${n?.includeModel?"?include_model=true":""}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await O(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,[s,i]=this.parseTokenOrUrl(t,a),o=new Et({apiUrl:s,apiKey:"placeholder"}),c=await o.readSharedDataset(i),l=r||c.name;try{if(await this.hasDataset({datasetId:l})){console.log(`Dataset ${l} already exists in your tenant. Skipping.`);return}}catch{}const d=await o.listSharedExamples(i),p=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:d.map(f=>f.inputs),outputs:d.flatMap(f=>f.outputs?[f.outputs]:[]),datasetId:p.id})}catch(f){throw console.error(`An error occurred while creating dataset ${l}. You should delete it manually.`),f}}parseTokenOrUrl(t,n,a=2,r="dataset"){try{return R(t),[n,t]}catch{}try{const i=new URL(t).pathname.split("/").filter(o=>o!=="");if(i.length>=a){const o=i[i.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 xc()?.DEFAULT_LANGSMITH_SPAN_PROCESSOR?.forceFlush()}}function pr(e){return"dataset_id"in e||"dataset_name"in e}const Yc=e=>!!["TRACING_V2","TRACING"].find(n=>le(n)==="true"),In=Symbol.for("lc:context_variables");function Qc(e){return e.replace(/[-:.]/g,"")}function bs(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:Qc(r)+t,microsecondPrecisionDatestring:r}}class qt{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=[],s,i;for(const o of n){const[c,l]=o.split("="),d=decodeURIComponent(l);c==="langsmith-metadata"?a=JSON.parse(d):c==="langsmith-tags"?r=d.split(","):c==="langsmith-project"?s=d:c==="langsmith-replicas"&&(i=JSON.parse(d))}return new qt(a,r,s,i)}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 ce{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}),Xc(t)){Object.assign(this,{...t});return}const n=ce.getDefaultConfig(),{metadata:a,...r}=t,s=r.client??ce.getSharedClient(),i={...a,...r?.extra?.metadata};if(r.extra={...r.extra,metadata:i},"id"in r&&r.id==null&&delete r.id,Object.assign(this,{...n,...r,client:s}),this.trace_id||(this.parent_run?this.trace_id=this.parent_run.trace_id??this.id:this.trace_id=this.id),this.replicas=rl(this.replicas),this.execution_order??=1,this.child_execution_order??=1,!this.dotted_order){const{dottedOrder:o,microsecondPrecisionDatestring:c}=bs(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:se(),run_type:"chain",project_name:us(),child_runs:[],api_url:xe("LANGCHAIN_ENDPOINT")??"http://localhost:1984",api_key:xe("LANGCHAIN_API_KEY"),caller_options:{},start_time:Date.now(),serialized:{},inputs:{},extra:{}}}static getSharedClient(){return ce.sharedClient||(ce.sharedClient=new Et),ce.sharedClient}createChild(t){const n=this.child_execution_order+1,a=new ce({...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});In in this&&(a[In]=this[In]);const r=Symbol.for("lc:child_config"),s=t.extra?.[r]??this.extra[r];if(tl(s)){const c={...s},l=el(c.callbacks)?c.callbacks.copy?.():void 0;l&&(Object.assign(l,{_parentRunId:a.id}),l.handlers?.find(vs)?.updateFromRunTree?.(a),c.callbacks=l),a.extra[r]=c}const i=new Set;let o=this;for(;o!=null&&!i.has(o.id);)i.add(o.id),o.child_execution_order=Math.max(o.child_execution_order,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 s,i;return a?(i=t.parent_run?.id??t.parent_run_id,s=[]):(s=t.child_runs.map(o=>this._convertToCreate(o,n,a)),i=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:s,parent_run_id:i,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 s=p=>Ga(`${p}:${t}`,Ga.DNS),i=s(r.id),o=r.trace_id?s(r.trace_id):void 0,c=r.parent_run_id?s(r.parent_run_id):void 0;let l;if(r.dotted_order){const p=nl(r.dotted_order),f=[];for(let y=0;y<p.length-1;y++){const[b,T]=p[y],v=s(T);f.push(b.toISOString().replace(/[-:]/g,"").replace(".","")+v)}const[m]=p[p.length-1];f.push(m.toISOString().replace(/[-:]/g,"").replace(".","")+i),l=f.join(".")}else l=void 0;return{...r,id:i,trace_id:o,parent_run_id:c,dotted_order:l,session_name:t}}async postRun(t=!0){try{const n=fs();if(this.replicas&&this.replicas.length>0)for(const{projectName:a,apiKey:r,apiUrl:s,workspaceId:i}of this.replicas){const o=this._remapForProject(a??this.project_name,n,!0);await this.client.createRun(o,{apiKey:r,apiUrl:s,workspaceId:i})}else{const a=this._convertToCreate(this,n,t);await this.client.createRun(a)}if(!t){Un("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:s,updates:i}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,...i};t?.excludeInputs||(c.inputs=o.inputs),await this.client.updateRun(o.id,c,{apiKey:a,apiUrl:r,workspaceId:s})}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,s,i,o=Yc();if(a){const l=a?.getParentRunId?.()??"",d=a?.handlers?.find(p=>p?.name=="langchain_tracer");r=d?.getRun?.(l),s=d?.projectName,i=d?.client,o=o||!!d}return r?new ce({name:r.name,id:r.id,trace_id:r.trace_id,dotted_order:r.dotted_order,client:i,tracingEnabled:o,project_name:s,tags:[...new Set((r?.tags??[]).concat(t?.tags??[]))],extra:{metadata:{...r?.extra?.metadata,...t?.metadata}}}).createChild(n):new ce({...n,client:i,tracingEnabled:o,project_name:s})}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 s=r.trim(),i=s.split(".").map(l=>{const[d,p]=l.split("Z");return{strTime:d,time:Date.parse(d+"Z"),uuid:p}}),o=i[0].uuid,c={...n,name:n?.name??"parent",run_type:n?.run_type??"chain",start_time:n?.start_time??Date.now(),id:i.at(-1)?.uuid,trace_id:o,dotted_order:s};if(a.baggage&&typeof a.baggage=="string"){const l=qt.fromHeader(a.baggage);c.metadata=l.metadata,c.tags=l.tags,c.project_name=l.project_name,c.replicas=l.replicas}return new ce(c)}toHeaders(t){const n={"langsmith-trace":this.dotted_order,baggage:new qt(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(ce,"sharedClient",{enumerable:!0,configurable:!0,writable:!0,value:null});function Xc(e){return e!=null&&typeof e.createChild=="function"&&typeof e.postRun=="function"}function vs(e){return typeof e=="object"&&e!=null&&typeof e.name=="string"&&e.name==="langchain_tracer"}function fr(e){return Array.isArray(e)&&e.some(t=>vs(t))}function el(e){return typeof e=="object"&&e!=null&&Array.isArray(e.handlers)}function tl(e){return e!=null&&typeof e.callbacks=="object"&&(fr(e.callbacks?.handlers)||fr(e.callbacks))}function nl(e){return e.split(".").map(n=>{const a=n.slice(0,-36),r=n.slice(-36),s=parseInt(a.slice(0,4)),i=parseInt(a.slice(4,6))-1,o=parseInt(a.slice(6,8)),c=parseInt(a.slice(9,11)),l=parseInt(a.slice(11,13)),d=parseInt(a.slice(13,15)),p=parseInt(a.slice(15,21));return[new Date(s,i,o,c,l,d,p/1e3),r]})}function al(){const e=xe("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){sl(t);const n=[];for(const[a,r]of Object.entries(t)){const s=a.replace(/\/$/,"");if(typeof r=="string")n.push({apiUrl:s,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(jc(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 rl(e){return e?e.map(t=>Array.isArray(t)?{projectName:t[0],updates:t[1]}:t):al()}function sl(e){if(Object.keys(e).length>0&&le("ENDPOINT"))throw new $c}var il={};F(il,{BaseTracer:()=>ft,isBaseTracer:()=>st});const ol=e=>{if(e)return e.events=e.events??[],e.child_runs=e.child_runs??[],e};function zn(e,t){if(e)return new ce({...e,start_time:e._serialized_start_time??e.start_time,parent_run:zn(t),child_runs:e.child_runs.map(n=>zn(n)).filter(n=>n!==void 0),extra:{...e.extra,runtime:is()},tracingEnabled:!1})}function On(e,t){return e&&!Array.isArray(e)&&typeof e=="object"?e:{[t]:e}}function st(e){return typeof e._addRunToRunMap=="function"}var ft=class extends xt{runMap=new Map;runTreeMap=new Map;usesRunTreeMap=!1;constructor(e){super(...arguments)}copy(){return this}getRunById(e){if(e!==void 0)return this.usesRunTreeMap?ol(this.runTreeMap.get(e)):this.runMap.get(e)}stringifyError(e){return e instanceof Error?e.message+(e?.stack?`
50
50
 
51
51
  ${e.stack}`:""):typeof e=="string"?e:`${e}`}_addChildRun(e,t){e.child_runs.push(t)}_addRunToRunMap(e){const{dottedOrder:t,microsecondPrecisionDatestring:n}=bs(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 s=zn(a,r);s!==void 0&&this.runTreeMap.set(a.id,s)}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,s,i,o){const c=this._getExecutionOrder(a),l=Date.now(),d=i?{...r,metadata:i}:r,p={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:d??{},tags:s||[]};return this._addRunToRunMap(p)}async handleLLMStart(e,t,n,a,r,s,i,o){const c=this.getRunById(n)??this._createRunForLLMStart(e,t,n,a,r,s,i,o);return await this.onRunCreate?.(c),await this.onLLMStart?.(c),c}_createRunForChatModelStart(e,t,n,a,r,s,i,o){const c=this._getExecutionOrder(a),l=Date.now(),d=i?{...r,metadata:i}:r,p={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:d??{},tags:s||[]};return this._addRunToRunMap(p)}async handleChatModelStart(e,t,n,a,r,s,i,o){const c=this.getRunById(n)??this._createRunForChatModelStart(e,t,n,a,r,s,i,o);return await this.onRunCreate?.(c),await this.onLLMStart?.(c),c}async handleLLMEnd(e,t,n,a,r){const s=this.getRunById(t);if(!s||s?.run_type!=="llm")throw new Error("No LLM run to end.");return s.end_time=Date.now(),s.outputs=e,s.events.push({name:"end",time:new Date(s.end_time).toISOString()}),s.extra={...s.extra,...r},await this.onLLMEnd?.(s),await this._endTrace(s),s}async handleLLMError(e,t,n,a,r){const s=this.getRunById(t);if(!s||s?.run_type!=="llm")throw new Error("No LLM run to end.");return s.end_time=Date.now(),s.error=this.stringifyError(e),s.events.push({name:"error",time:new Date(s.end_time).toISOString()}),s.extra={...s.extra,...r},await this.onLLMError?.(s),await this._endTrace(s),s}_createRunForChainStart(e,t,n,a,r,s,i,o){const c=this._getExecutionOrder(a),l=Date.now(),d={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:i??"chain",child_runs:[],extra:s?{metadata:s}:{},tags:r||[]};return this._addRunToRunMap(d)}async handleChainStart(e,t,n,a,r,s,i,o){const c=this.getRunById(n)??this._createRunForChainStart(e,t,n,a,r,s,i,o);return await this.onRunCreate?.(c),await this.onChainStart?.(c),c}async handleChainEnd(e,t,n,a,r){const s=this.getRunById(t);if(!s)throw new Error("No chain run to end.");return s.end_time=Date.now(),s.outputs=On(e,"output"),s.events.push({name:"end",time:new Date(s.end_time).toISOString()}),r?.inputs!==void 0&&(s.inputs=On(r.inputs,"input")),await this.onChainEnd?.(s),await this._endTrace(s),s}async handleChainError(e,t,n,a,r){const s=this.getRunById(t);if(!s)throw new Error("No chain run to end.");return s.end_time=Date.now(),s.error=this.stringifyError(e),s.events.push({name:"error",time:new Date(s.end_time).toISOString()}),r?.inputs!==void 0&&(s.inputs=On(r.inputs,"input")),await this.onChainError?.(s),await this._endTrace(s),s}_createRunForToolStart(e,t,n,a,r,s,i){const o=this._getExecutionOrder(a),c=Date.now(),l={id:n,name:i??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:s?{metadata:s}:{},tags:r||[]};return this._addRunToRunMap(l)}async handleToolStart(e,t,n,a,r,s,i){const o=this.getRunById(n)??this._createRunForToolStart(e,t,n,a,r,s,i);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,s,i){const o=this._getExecutionOrder(a),c=Date.now(),l={id:n,name:i??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:s?{metadata:s}:{},tags:r||[]};return this._addRunToRunMap(l)}async handleRetrieverStart(e,t,n,a,r,s,i){const o=this.getRunById(n)??this._createRunForRetrieverStart(e,t,n,a,r,s,i);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,s){const i=this.getRunById(n);if(!i||i?.run_type!=="llm")throw new Error('Invalid "runId" provided to "handleLLMNewToken" callback.');return i.events.push({name:"new_token",time:new Date().toISOString(),kwargs:{token:e,idx:t,chunk:s?.chunk}}),await this.onLLMNewToken?.(i,e,{chunk:s?.chunk}),i}},cl={};F(cl,{ConsoleCallbackHandler:()=>Hn});function ae(e,t){return`${e.open}${t}${e.close}`}function me(e,t){try{return JSON.stringify(e,null,2)}catch{return t}}function mr(e){return typeof e=="string"?e.trim():e==null?e:me(e,e.toString())}function De(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:oe}=Nr;var Hn=class extends ft{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,s)=>{const i=`${a.execution_order}:${a.run_type}:${a.name}`;return r===s.length-1?ae(Nr.bold,i):i}).join(" > ");return ae(oe.grey,n)}onChainStart(e){const t=this.getBreadcrumbs(e);console.log(`${ae(oe.green,"[chain/start]")} [${t}] Entering Chain run with input: ${me(e.inputs,"[inputs]")}`)}onChainEnd(e){const t=this.getBreadcrumbs(e);console.log(`${ae(oe.cyan,"[chain/end]")} [${t}] [${De(e)}] Exiting Chain run with output: ${me(e.outputs,"[outputs]")}`)}onChainError(e){const t=this.getBreadcrumbs(e);console.log(`${ae(oe.red,"[chain/error]")} [${t}] [${De(e)}] Chain run errored with error: ${me(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(`${ae(oe.green,"[llm/start]")} [${t}] Entering LLM run with input: ${me(n,"[inputs]")}`)}onLLMEnd(e){const t=this.getBreadcrumbs(e);console.log(`${ae(oe.cyan,"[llm/end]")} [${t}] [${De(e)}] Exiting LLM run with output: ${me(e.outputs,"[response]")}`)}onLLMError(e){const t=this.getBreadcrumbs(e);console.log(`${ae(oe.red,"[llm/error]")} [${t}] [${De(e)}] LLM run errored with error: ${me(e.error,"[error]")}`)}onToolStart(e){const t=this.getBreadcrumbs(e);console.log(`${ae(oe.green,"[tool/start]")} [${t}] Entering Tool run with input: "${mr(e.inputs.input)}"`)}onToolEnd(e){const t=this.getBreadcrumbs(e);console.log(`${ae(oe.cyan,"[tool/end]")} [${t}] [${De(e)}] Exiting Tool run with output: "${mr(e.outputs?.output)}"`)}onToolError(e){const t=this.getBreadcrumbs(e);console.log(`${ae(oe.red,"[tool/error]")} [${t}] [${De(e)}] Tool run errored with error: ${me(e.error,"[error]")}`)}onRetrieverStart(e){const t=this.getBreadcrumbs(e);console.log(`${ae(oe.green,"[retriever/start]")} [${t}] Entering Retriever run with input: ${me(e.inputs,"[inputs]")}`)}onRetrieverEnd(e){const t=this.getBreadcrumbs(e);console.log(`${ae(oe.cyan,"[retriever/end]")} [${t}] [${De(e)}] Exiting Retriever run with output: ${me(e.outputs,"[outputs]")}`)}onRetrieverError(e){const t=this.getBreadcrumbs(e);console.log(`${ae(oe.red,"[retriever/error]")} [${t}] [${De(e)}] Retriever run errored with error: ${me(e.error,"[error]")}`)}onAgentAction(e){const t=e,n=this.getBreadcrumbs(e);console.log(`${ae(oe.blue,"[agent/action]")} [${n}] Agent selected action: ${me(t.actions[t.actions.length-1],"[action]")}`)}};let Cn;const Ts=()=>{if(Cn===void 0){const e=Fe("LANGCHAIN_CALLBACKS_BACKGROUND")==="false"?{blockOnRootRunFinalization:!0}:{};Cn=new Et(e)}return Cn};let ll=class{getStore(){}run(t,n){return n()}};const xn=Symbol.for("ls:tracing_async_local_storage"),ul=new ll;let dl=class{getInstance(){return globalThis[xn]??ul}initializeGlobalInstance(t){globalThis[xn]===void 0&&(globalThis[xn]=t)}};const hl=new dl;function pl(e=!1){const t=hl.getInstance().getStore();if(!e&&t===void 0)throw new Error(`Could not get the current run tree.
52
52
 
53
- Please make sure you are calling this method within a traceable function and that tracing is enabled.`);return t}function Ea(e){return typeof e=="function"&&"langsmith:traceable"in e}var fl={};F(fl,{LangChainTracer:()=>Bt});var Bt=class Es extends ft{name="langchain_tracer";projectName;exampleId;client;replicas;usesRunTreeMap=!0;constructor(t={}){super(t);const{exampleId:n,projectName:a,client:r,replicas:s}=t;this.projectName=a??us(),this.replicas=s,this.exampleId=n,this.client=r??Ts();const i=Es.getTraceableRunTree();i&&this.updateFromRunTree(i)}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 s=r.shift();!s||a.has(s.id)||(a.add(s.id),this.runTreeMap.set(s.id,s),s.child_runs&&r.push(...s.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 ce({...n,client:this.client,project_name:this.projectName,replicas:this.replicas,reference_example_id:this.exampleId,tracingEnabled:!0})}static getTraceableRunTree(){try{return pl(!0)}catch{return}}};let qe;function ml(){const e="default"in Pe?Pe.default:Pe;return new e({autoStart:!0,concurrency:1})}function gl(){return typeof qe>"u"&&(qe=ml()),qe}async function q(e,t){if(t===!0){const n=Tt();n!==void 0?await n.run(void 0,async()=>e()):await e()}else qe=gl(),qe.add(async()=>{const n=Tt();n!==void 0?await n.run(void 0,async()=>e()):await e()})}async function _l(){const e=Ts();await Promise.allSettled([typeof qe<"u"?qe.onIdle():Promise.resolve(),e.awaitPendingTraceBatches()])}var yl={};F(yl,{awaitAllCallbacks:()=>_l,consumeCallback:()=>q});const wl=e=>!!["LANGSMITH_TRACING_V2","LANGCHAIN_TRACING_V2","LANGSMITH_TRACING","LANGCHAIN_TRACING"].find(n=>Fe(n)==="true");function Ss(e){const t=Tt();return t===void 0?void 0:t.getStore()?.[bt]?.[e]}const bl=Symbol("lc:configure_hooks"),vl=()=>Ss(bl)||[];var Tl={};F(Tl,{BaseCallbackManager:()=>As,BaseRunManager:()=>Nt,CallbackManager:()=>Oe,CallbackManagerForChainRun:()=>Os,CallbackManagerForLLMRun:()=>Gn,CallbackManagerForRetrieverRun:()=>Is,CallbackManagerForToolRun:()=>Cs,ensureHandler:()=>St,parseCallbackConfigArg:()=>El});function El(e){return e?Array.isArray(e)||"name"in e?{callbacks:e}:e:{}}var As=class{setHandler(e){return this.setHandlers([e])}},Nt=class{constructor(e,t,n,a,r,s,i,o){this.runId=e,this.handlers=t,this.inheritableHandlers=n,this.tags=a,this.inheritableTags=r,this.metadata=s,this.inheritableMetadata=i,this._parentRunId=o}get parentRunId(){return this._parentRunId}async handleText(e){await Promise.all(this.handlers.map(t=>q(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(s=>q(async()=>{try{await s.handleCustomEvent?.(e,t,this.runId,this.tags,this.metadata)}catch(i){if((s.raiseError?console.error:console.warn)(`Error in handler ${s.constructor.name}, handleCustomEvent: ${i}`),s.raiseError)throw i}},s.awaitHandlers)))}},Is=class extends Nt{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=>q(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=>q(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)))}},Gn=class extends Nt{async handleLLMNewToken(e,t,n,a,r,s){await Promise.all(this.handlers.map(i=>q(async()=>{if(!i.ignoreLLM)try{await i.handleLLMNewToken?.(e,t??{prompt:0,completion:0},this.runId,this._parentRunId,this.tags,s)}catch(o){if((i.raiseError?console.error:console.warn)(`Error in handler ${i.constructor.name}, handleLLMNewToken: ${o}`),i.raiseError)throw o}},i.awaitHandlers)))}async handleLLMError(e,t,n,a,r){await Promise.all(this.handlers.map(s=>q(async()=>{if(!s.ignoreLLM)try{await s.handleLLMError?.(e,this.runId,this._parentRunId,this.tags,r)}catch(i){if((s.raiseError?console.error:console.warn)(`Error in handler ${s.constructor.name}, handleLLMError: ${i}`),s.raiseError)throw i}},s.awaitHandlers)))}async handleLLMEnd(e,t,n,a,r){await Promise.all(this.handlers.map(s=>q(async()=>{if(!s.ignoreLLM)try{await s.handleLLMEnd?.(e,this.runId,this._parentRunId,this.tags,r)}catch(i){if((s.raiseError?console.error:console.warn)(`Error in handler ${s.constructor.name}, handleLLMEnd: ${i}`),s.raiseError)throw i}},s.awaitHandlers)))}},Os=class extends Nt{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(s=>q(async()=>{if(!s.ignoreChain)try{await s.handleChainError?.(e,this.runId,this._parentRunId,this.tags,r)}catch(i){if((s.raiseError?console.error:console.warn)(`Error in handler ${s.constructor.name}, handleChainError: ${i}`),s.raiseError)throw i}},s.awaitHandlers)))}async handleChainEnd(e,t,n,a,r){await Promise.all(this.handlers.map(s=>q(async()=>{if(!s.ignoreChain)try{await s.handleChainEnd?.(e,this.runId,this._parentRunId,this.tags,r)}catch(i){if((s.raiseError?console.error:console.warn)(`Error in handler ${s.constructor.name}, handleChainEnd: ${i}`),s.raiseError)throw i}},s.awaitHandlers)))}async handleAgentAction(e){await Promise.all(this.handlers.map(t=>q(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=>q(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)))}},Cs=class extends Nt{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=>q(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=>q(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 _t extends As{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,s=void 0,i=void 0,o=void 0,c=void 0){return Promise.all(n.map(async(l,d)=>{const p=d===0&&a?a:se();return await Promise.all(this.handlers.map(f=>{if(!f.ignoreLLM)return st(f)&&f._createRunForLLMStart(t,[l],p,this._parentRunId,s,this.tags,this.metadata,c),q(async()=>{try{await f.handleLLMStart?.(t,[l],p,this._parentRunId,s,this.tags,this.metadata,c)}catch(m){if((f.raiseError?console.error:console.warn)(`Error in handler ${f.constructor.name}, handleLLMStart: ${m}`),f.raiseError)throw m}},f.awaitHandlers)})),new Gn(p,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChatModelStart(t,n,a=void 0,r=void 0,s=void 0,i=void 0,o=void 0,c=void 0){return Promise.all(n.map(async(l,d)=>{const p=d===0&&a?a:se();return await Promise.all(this.handlers.map(f=>{if(!f.ignoreLLM)return st(f)&&f._createRunForChatModelStart(t,[l],p,this._parentRunId,s,this.tags,this.metadata,c),q(async()=>{try{if(f.handleChatModelStart)await f.handleChatModelStart?.(t,[l],p,this._parentRunId,s,this.tags,this.metadata,c);else if(f.handleLLMStart){const m=ba(l);await f.handleLLMStart?.(t,[m],p,this._parentRunId,s,this.tags,this.metadata,c)}}catch(m){if((f.raiseError?console.error:console.warn)(`Error in handler ${f.constructor.name}, handleLLMStart: ${m}`),f.raiseError)throw m}},f.awaitHandlers)})),new Gn(p,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChainStart(t,n,a=se(),r=void 0,s=void 0,i=void 0,o=void 0){return await Promise.all(this.handlers.map(c=>{if(!c.ignoreChain)return st(c)&&c._createRunForChainStart(t,n,a,this._parentRunId,this.tags,this.metadata,r,o),q(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 Os(a,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleToolStart(t,n,a=se(),r=void 0,s=void 0,i=void 0,o=void 0){return await Promise.all(this.handlers.map(c=>{if(!c.ignoreAgent)return st(c)&&c._createRunForToolStart(t,n,a,this._parentRunId,this.tags,this.metadata,o),q(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 Cs(a,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleRetrieverStart(t,n,a=se(),r=void 0,s=void 0,i=void 0,o=void 0){return await Promise.all(this.handlers.map(c=>{if(!c.ignoreRetriever)return st(c)&&c._createRunForRetrieverStart(t,n,a,this._parentRunId,this.tags,this.metadata,o),q(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 Is(a,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleCustomEvent(t,n,a,r,s){await Promise.all(this.handlers.map(i=>q(async()=>{if(!i.ignoreCustomEvent)try{await i.handleCustomEvent?.(t,n,a,this.tags,this.metadata)}catch(o){if((i.raiseError?console.error:console.warn)(`Error in handler ${i.constructor.name}, handleCustomEvent: ${o}`),i.raiseError)throw o}},i.awaitHandlers)))}addHandler(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 _t(this._parentRunId);for(const r of this.handlers){const s=this.inheritableHandlers.includes(r);a.addHandler(r,s)}for(const r of this.tags){const s=this.inheritableTags.includes(r);a.addTags([r],s)}for(const r of Object.keys(this.metadata)){const s=Object.keys(this.inheritableMetadata).includes(r);a.addMetadata({[r]:this.metadata[r]},s)}for(const r of t)a.handlers.filter(s=>s.name==="console_callback_handler").some(s=>s.name===r.name)||a.addHandler(r,n);return a}static fromHandlers(t){class n extends xt{name=se();constructor(){super(),Object.assign(this,t)}}const a=new this;return a.addHandler(new n),a}static configure(t,n,a,r,s,i,o){return this._configureSync(t,n,a,r,s,i,o)}static _configureSync(t,n,a,r,s,i,o){let c;(t||n)&&(Array.isArray(t)||!t?(c=new _t,c.setHandlers(t?.map(St)??[],!0)):c=t,c=c.copy(Array.isArray(n)?n.map(St):n?.handlers,!1));const l=Fe("LANGCHAIN_VERBOSE")==="true"||o?.verbose,d=Bt.getTraceableRunTree()?.tracingEnabled||wl(),p=d||(Fe("LANGCHAIN_TRACING")??!1);if(l||p){if(c||(c=new _t),l&&!c.handlers.some(f=>f.name===Hn.prototype.name)){const f=new Hn;c.addHandler(f,!0)}if(p&&!c.handlers.some(f=>f.name==="langchain_tracer")&&d){const f=new Bt;c.addHandler(f,!0)}if(d){const f=Bt.getTraceableRunTree();f&&c._parentRunId===void 0&&(c._parentRunId=f.id,c.handlers.find(y=>y.name==="langchain_tracer")?.updateFromRunTree(f))}}for(const{contextVar:f,inheritable:m=!0,handlerClass:y,envVar:b}of vl()){const T=b&&Fe(b)==="true"&&y;let v;const I=f!==void 0?Ss(f):void 0;I&&cs(I)?v=I:T&&(v=new y({})),v!==void 0&&(c||(c=new _t),c.handlers.some(E=>E.name===v.name)||c.addHandler(v,m))}return(a||r)&&c&&(c.addTags(a??[]),c.addTags(r??[],!1)),(s||i)&&c&&(c.addMetadata(s??{}),c.addMetadata(i??{},!1)),c}};function St(e){return"name"in e?e:xt.fromMethods(e)}var xs=class{getStore(){}run(e,t){return t()}enterWith(e){}};const Sl=new xs,gr=Symbol.for("lc:child_config");var Al=class{getInstance(){return Tt()??Sl}getRunnableConfig(){return this.getInstance().getStore()?.extra?.[gr]}runWithConfig(e,t,n){const a=Oe._configureSync(e?.callbacks,void 0,e?.tags,void 0,e?.metadata),r=this.getInstance(),s=r.getStore(),i=a?.getParentRunId(),o=a?.handlers?.find(l=>l?.name==="langchain_tracer");let c;return o&&i?c=o.getRunTreeWithTracingConfig(i):n||(c=new ce({name:"<runnable_lambda>",tracingEnabled:!1})),c&&(c.extra={...c.extra,[gr]:e}),s!==void 0&&s[bt]!==void 0&&(c===void 0&&(c={}),c[bt]=s[bt]),r.run(c,t)}initializeGlobalInstance(e){Tt()===void 0&&Mo(e)}};const Me=new Al;var Il={};F(Il,{AsyncLocalStorageProviderSingleton:()=>Me,MockAsyncLocalStorage:()=>xs,_CONTEXT_VARIABLES_KEY:()=>bt});const Nn=25;async function pe(e){return Oe._configureSync(e?.callbacks,void 0,e?.tags,void 0,e?.metadata)}function Vn(...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,s=n.callbacks;if(Array.isArray(s))if(!r)t.callbacks=s;else if(Array.isArray(r))t.callbacks=r.concat(s);else{const i=r.copy();for(const o of s)i.addHandler(St(o),!0);t.callbacks=i}else if(s)if(!r)t.callbacks=s;else if(Array.isArray(r)){const i=s.copy();for(const o of r)i.addHandler(St(o),!0);t.callbacks=i}else t.callbacks=new Oe(s._parentRunId,{handlers:r.handlers.concat(s.handlers),inheritableHandlers:r.inheritableHandlers.concat(s.inheritableHandlers),tags:Array.from(new Set(r.tags.concat(s.tags))),inheritableTags:Array.from(new Set(r.inheritableTags.concat(s.inheritableTags))),metadata:{...r.metadata,...s.metadata}})}else{const r=a;t[r]=n[r]??t[r]}return t}const Ol=new Set(["string","number","boolean"]);function L(e){const t=Me.getRunnableConfig();let n={tags:[],metadata:{},recursionLimit:25,runId:void 0};if(t){const{runId:a,runName:r,...s}=t;n=Object.entries(s).reduce((i,[o,c])=>(c!==void 0&&(i[o]=c),i),n)}if(e&&(n=Object.entries(e).reduce((a,[r,s])=>(s!==void 0&&(a[r]=s),a),n)),n?.configurable)for(const a of Object.keys(n.configurable))Ol.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 H(e={},{callbacks:t,maxConcurrency:n,recursionLimit:a,runName:r,configurable:s,runId:i}={}){const o=L(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),s!==void 0&&(o.configurable={...o.configurable,...s}),i!==void 0&&delete o.runId,o}function Ye(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 He(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(Jt(t))},t.addEventListener("abort",n),t.aborted&&r(Jt(t))})]).finally(()=>t.removeEventListener("abort",n))}function Jt(e){return e?.reason instanceof Error?e.reason:typeof e?.reason=="string"?new Error(e.reason):new Error("Aborted")}var Cl={};F(Cl,{AsyncGeneratorWithSetup:()=>nt,IterableReadableStream:()=>Te,atee:()=>Sa,concat:()=>Qe,pipeGeneratorWithSetup:()=>Ns});var Te=class Zn 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 Zn({start(a){return r();function r(){return n.read().then(({done:s,value:i})=>{if(s){a.close();return}return a.enqueue(i),r()})}},cancel(){n.releaseLock()}})}static fromAsyncGenerator(t){return new Zn({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 Sa(e,t=2){const n=Array.from({length:t},()=>[]);return n.map(async function*(r){for(;;)if(r.length===0){const s=await e.next();for(const i of n)i.push(s)}else{if(r[0].done)return;yield r.shift().value}})}function Qe(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]=Qe(n[a],r):n[a]=r;return n}else throw new Error(`Cannot concat ${typeof e} and ${typeof t}`)}var nt=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)=>{Me.runWithConfig(Ye(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?Me.runWithConfig(Ye(this.config),this.signal?async()=>He(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 Ns(e,t,n,a,...r){const s=new nt({generator:t,startSetup:n,signal:a}),i=await s.setup;return{output:e(s,i,...r),setup:i}}/*!
54
- * https://github.com/Starcounter-Jack/JSON-Patch
55
- * (c) 2017-2022 Joachim Wester
56
- * MIT licensed
57
- */const xl=Object.prototype.hasOwnProperty;function qn(e,t){return xl.call(e,t)}function Jn(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)qn(e,n)&&t.push(n);return t}function be(e){switch(typeof e){case"object":return JSON.parse(JSON.stringify(e));case"undefined":return null;default:return e}}function Wn(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 rt(e){return e.indexOf("/")===-1&&e.indexOf("~")===-1?e:e.replace(/~/g,"~0").replace(/\//g,"~1")}function Nl(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function Kn(e){if(e===void 0)return!0;if(e){if(Array.isArray(e)){for(let n=0,a=e.length;n<a;n++)if(Kn(e[n]))return!0}else if(typeof e=="object"){const n=Jn(e),a=n.length;for(var t=0;t<a;t++)if(Kn(e[n[t]]))return!0}}return!1}function _r(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 kl=class extends Error{constructor(e,t,n,a,r){super(_r(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=_r(e,{name:t,index:n,operation:a,tree:r})}},ks={};F(ks,{JsonPatchError:()=>G,_areEquals:()=>At,applyOperation:()=>Je,applyPatch:()=>dt,applyReducer:()=>Ml,deepClone:()=>Rl,getValueByPointer:()=>Wt,validate:()=>Rs,validator:()=>Kt});const G=kl,Rl=be,ot={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=Wt(n,this.path);a&&(a=be(a));const r=Je(n,{op:"remove",path:this.from}).removed;return Je(n,{op:"add",path:this.path,value:r}),{newDocument:n,removed:a}},copy:function(e,t,n){const a=Wt(n,this.from);return Je(n,{op:"add",path:this.path,value:be(a)}),{newDocument:n}},test:function(e,t,n){return{newDocument:n,test:At(e[t],this.value)}},_get:function(e,t,n){return this.value=e[t],{newDocument:n}}};var Pl={add:function(e,t,n){return Wn(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:ot.move,copy:ot.copy,test:ot.test,_get:ot._get};function Wt(e,t){if(t=="")return e;var n={op:"_get",path:t};return Je(e,n),n.value}function Je(e,t,n=!1,a=!0,r=!0,s=0){if(n&&(typeof n=="function"?n(t,0,e,t.path):Kt(t,0)),t.path===""){let i={newDocument:e};if(t.op==="add")return i.newDocument=t.value,i;if(t.op==="replace")return i.newDocument=t.value,i.removed=e,i;if(t.op==="move"||t.op==="copy")return i.newDocument=Wt(e,t.from),t.op==="move"&&(i.removed=e),i;if(t.op==="test"){if(i.test=At(e,t.value),i.test===!1)throw new G("Test operation failed","TEST_OPERATION_FAILED",s,t,e);return i.newDocument=e,i}else{if(t.op==="remove")return i.removed=e,i.newDocument=null,i;if(t.op==="_get")return t.value=e,i;if(n)throw new G("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",s,t,e);return i}}else{a||(e=be(e));const o=(t.path||"").split("/");let c=e,l=1,d=o.length,p,f,m;for(typeof n=="function"?m=n:m=Kt;;){if(f=o[l],f&&f.indexOf("~")!=-1&&(f=Nl(f)),r&&(f=="__proto__"||f=="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&&p===void 0&&(c[f]===void 0?p=o.slice(0,l).join("/"):l==d-1&&(p=t.path),p!==void 0&&m(t,0,e,p)),l++,Array.isArray(c)){if(f==="-")f=c.length;else{if(n&&!Wn(f))throw new G("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",s,t,e);Wn(f)&&(f=~~f)}if(l>=d){if(n&&t.op==="add"&&f>c.length)throw new G("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",s,t,e);const y=Pl[t.op].call(t,c,f,e);if(y.test===!1)throw new G("Test operation failed","TEST_OPERATION_FAILED",s,t,e);return y}}else if(l>=d){const y=ot[t.op].call(t,c,f,e);if(y.test===!1)throw new G("Test operation failed","TEST_OPERATION_FAILED",s,t,e);return y}if(c=c[f],n&&l<d&&(!c||typeof c!="object"))throw new G("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",s,t,e)}}}function dt(e,t,n,a=!0,r=!0){if(n&&!Array.isArray(t))throw new G("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");a||(e=be(e));const s=new Array(t.length);for(let i=0,o=t.length;i<o;i++)s[i]=Je(e,t[i],n,!0,r,i),e=s[i].newDocument;return s.newDocument=e,s}function Ml(e,t,n){const a=Je(e,t);if(a.test===!1)throw new G("Test operation failed","TEST_OPERATION_FAILED",n,t,e);return a.newDocument}function Kt(e,t,n,a){if(typeof e!="object"||e===null||Array.isArray(e))throw new G("Operation is not an object","OPERATION_NOT_AN_OBJECT",t,e,n);if(ot[e.op]){if(typeof e.path!="string")throw new G("Operation `path` property is not a string","OPERATION_PATH_INVALID",t,e,n);if(e.path.indexOf("/")!==0&&e.path.length>0)throw new G('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 G("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 G("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")&&Kn(e.value))throw new G("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,s=a.split("/").length;if(r!==s+1&&r!==s)throw new G("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 G("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 i={op:"_get",path:e.from,value:void 0},o=Rs([i],n);if(o&&o.name==="OPERATION_PATH_UNRESOLVABLE")throw new G("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",t,e,n)}}}else throw new G("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",t,e,n)}function Rs(e,t,n){try{if(!Array.isArray(e))throw new G("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(t)dt(be(t),be(e),n||!0);else{n=n||Kt;for(var a=0;a<e.length;a++)n(e[a],a,t,void 0)}}catch(r){if(r instanceof G)return r;throw r}}function At(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,s,i;if(n&&a){if(s=e.length,s!=t.length)return!1;for(r=s;r--!==0;)if(!At(e[r],t[r]))return!1;return!0}if(n!=a)return!1;var o=Object.keys(e);if(s=o.length,s!==Object.keys(t).length)return!1;for(r=s;r--!==0;)if(!t.hasOwnProperty(o[r]))return!1;for(r=s;r--!==0;)if(i=o[r],!At(e[i],t[i]))return!1;return!0}return e!==e&&t!==t}function Ps(e,t,n,a,r){if(t!==e){typeof t.toJSON=="function"&&(t=t.toJSON());for(var s=Jn(t),i=Jn(e),o=!1,c=i.length-1;c>=0;c--){var l=i[c],d=e[l];if(qn(t,l)&&!(t[l]===void 0&&d!==void 0&&Array.isArray(t)===!1)){var p=t[l];typeof d=="object"&&d!=null&&typeof p=="object"&&p!=null&&Array.isArray(d)===Array.isArray(p)?Ps(d,p,n,a+"/"+rt(l),r):d!==p&&(r&&n.push({op:"test",path:a+"/"+rt(l),value:be(d)}),n.push({op:"replace",path:a+"/"+rt(l),value:be(p)}))}else Array.isArray(e)===Array.isArray(t)?(r&&n.push({op:"test",path:a+"/"+rt(l),value:be(d)}),n.push({op:"remove",path:a+"/"+rt(l)}),o=!0):(r&&n.push({op:"test",path:a,value:e}),n.push({op:"replace",path:a,value:t}))}if(!(!o&&s.length==i.length))for(var c=0;c<s.length;c++){var l=s[c];!qn(e,l)&&t[l]!==void 0&&n.push({op:"add",path:a+"/"+rt(l),value:be(t[l])})}}}function Aa(e,t,n=!1){var a=[];return Ps(e,t,a,"",n),a}({...ks});var Ll={};F(Ll,{LogStreamCallbackHandler:()=>Qn,RunLog:()=>Ia,RunLogPatch:()=>ke,isLogStreamHandler:()=>Ms});var ke=class{ops;constructor(e){this.ops=e.ops??[]}concat(e){const t=this.ops.concat(e.ops),n=dt({},t);return new Ia({ops:t,state:n[n.length-1].newDocument})}},Ia=class Yn extends ke{state;constructor(t){super(t),this.state=t.state}concat(t){const n=this.ops.concat(t.ops),a=dt(this.state,t.ops);return new Yn({ops:n,state:a[a.length-1].newDocument})}static fromRunLogPatch(t){const n=dt({},t.ops);return new Yn({ops:t.ops,state:n[n.length-1].newDocument})}};const Ms=e=>e.name==="log_stream_tracer";async function yr(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 wr(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 $l(e){return e!==void 0&&e.message!==void 0}var Qn=class extends ft{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=Te.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 ke({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 ke({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 yr(e,this._schemaFormat)),await this.writer.write(new ke({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 yr(e,this._schemaFormat)}),n.push({op:"add",path:`/logs/${t}/final_output`,value:await wr(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 ke({ops:n});await this.writer.write(a)}finally{if(e.id===this.rootId){const t=new ke({ops:[{op:"replace",path:"/final_output",value:await wr(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 s;r?$l(n?.chunk)?s=n?.chunk:s=new tt({id:`run-${e.id}`,content:t}):s=t;const i=new ke({ops:[{op:"add",path:`/logs/${a}/streamed_output_str/-`,value:t},{op:"add",path:`/logs/${a}/streamed_output/-`,value:s}]});await this.writer.write(i)}},jl={};F(jl,{ChatGenerationChunk:()=>ea,GenerationChunk:()=>It,RUN_KEY:()=>Xn});const Xn="__run";var It=class Ls{text;generationInfo;constructor(t){this.text=t.text,this.generationInfo=t.generationInfo}concat(t){return new Ls({text:this.text+t.text,generationInfo:{...this.generationInfo,...t.generationInfo}})}},ea=class $s extends It{message;constructor(t){super(t),this.message=t.message}concat(t){return new $s({text:this.text+t.text,generationInfo:{...this.generationInfo,...t.generationInfo},message:this.message.concat(t.message)})}};function jt({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 Dl=e=>e.name==="event_stream_tracer";var Fl=class extends ft{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=Te.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(i,o){return i==="llm"&&typeof o=="string"?new It({text:o}):o}let s=this.tappedPromises.get(e);if(s===void 0){let i;s=new Promise(o=>{i=o}),this.tappedPromises.set(e,s);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{i?.()}}else{yield n.value;for await(const i of t)yield i}}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=jt(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,s;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")s="on_chat_model_stream",n?.chunk===void 0?r=new tt({content:t,id:`run-${e.id}`}):r=n.chunk.message;else if(a.runType==="llm")s="on_llm_stream",n?.chunk===void 0?r=new It({text:t}):r=n.chunk;else throw new Error(`Unexpected run type ${a.runType}`);await this.send({event:s,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 s of a??[]){if(r!==void 0)break;r=s[0]?.message}n="on_chat_model_end"}else if(t.runType==="llm")r={generations:a?.map(s=>s.map(i=>({text:i.text,generationInfo:i.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=jt(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??{},s={output:e.outputs?.output??e.outputs,input:a};a.input&&Object.keys(a).length===1&&(s.input=a.input,t.inputs=a.input),await this.sendEndEvent({event:n,data:s,run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata??{}},t)}async onToolStart(e){const t=jt(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=jt(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()})}},Ul={};F(Ul,{AsyncCaller:()=>cn});const Bl=[400,401,402,403,404,405,406,407,409],zl=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&&Bl.includes(+t))throw e;if(e?.error?.code==="insufficient_quota"){const n=new Error(e?.message);throw n.name="InsufficientQuotaError",n}};var cn=class{maxConcurrency;maxRetries;onFailedAttempt;queue;constructor(e){this.maxConcurrency=e.maxConcurrency??1/0,this.maxRetries=e.maxRetries??6,this.onFailedAttempt=e.onFailedAttempt??zl;const t="default"in Pe?Pe.default:Pe;this.queue=new t({concurrency:this.maxConcurrency})}call(e,...t){return this.queue.add(()=>Ht(()=>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(Jt(e.signal))})})]):this.call(t,...n)}fetch(...e){return this.call(()=>fetch(...e).then(t=>t.ok?t:Promise.reject(t)))}},js=class extends ft{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 Oa(e){return e?e.lc_runnable:!1}var Hl=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 Z(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 Y(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 Gl(e){return Z(e)&&console.warn("[WARNING] Attempting to use Zod 4 schema in a context where Zod 3 schema is expected. This may cause unexpected behavior."),Y(e)}function kt(e){return!e||typeof e!="object"||Array.isArray(e)?!1:!!(Z(e)||Y(e))}function Ds(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 Fs(e){return Z(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 Vl(e){return!!(Ds(e)||Fs(e))}async function Zl(e,t){if(Z(e))try{return{success:!0,data:await kr(e,t)}}catch(n){return{success:!1,error:n}}if(Y(e))return await e.safeParseAsync(t);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}async function Ca(e,t){if(Z(e))return await kr(e,t);if(Y(e))return await e.parseAsync(t);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function ql(e,t){if(Z(e))try{return{success:!0,data:ca(e,t)}}catch(n){return{success:!1,error:n}}if(Y(e))return e.safeParse(t);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function Jl(e,t){if(Z(e))return ca(e,t);if(Y(e))return e.parse(t);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function xa(e){if(Z(e))return he.get(e)?.description;if(Y(e)||"description"in e&&typeof e.description=="string")return e.description}function Wl(e){if(!kt(e))return!1;if(Y(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(Z(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 Us(e){return kt(e)?Y(e)?e._def.typeName==="ZodString":Z(e)?e._zod.def.type==="string":!1:!1}function Na(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 Ce(e){return Z(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 ln(e){return Z(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 Kl(e){return!!(Na(e)||Ce(e))}function ta(e){if(Y(e))return e.shape;if(Z(e))return e._zod.def.shape;throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function Yl(e,t){if(Y(e))return e.extend(t);if(Z(e))return Ri(e,t);throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function Ql(e){if(Y(e))return e.partial();if(Z(e))return ki(Rr,e);throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function Yt(e,t=!1){if(Y(e))return e.strict();if(Ce(e)){const n=e._zod.def.shape;if(t)for(const[s,i]of Object.entries(e._zod.def.shape)){if(Ce(i)){const c=Yt(i,t);n[s]=c}else if(ln(i)){let c=i._zod.def.element;Ce(c)&&(c=Yt(c,t)),n[s]=Ke(i,{...i._zod.def,element:c})}else n[s]=i;const o=he.get(i);o&&he.add(n[s],o)}const a=Ke(e,{...e._zod.def,shape:n,catchall:Ci(xi)}),r=he.get(e);return r&&he.add(a,r),a}throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function na(e,t=!1){if(Na(e))return e.passthrough();if(Ce(e)){const n=e._zod.def.shape;if(t)for(const[s,i]of Object.entries(e._zod.def.shape)){if(Ce(i)){const c=na(i,t);n[s]=c}else if(ln(i)){let c=i._zod.def.element;Ce(c)&&(c=na(c,t)),n[s]=Ke(i,{...i._zod.def,element:c})}else n[s]=i;const o=he.get(i);o&&he.add(n[s],o)}const a=Ke(e,{...e._zod.def,shape:n,catchall:Ni(Pi)}),r=he.get(e);return r&&he.add(a,r),a}throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function Xl(e){if(Y(e))try{const t=e.parse(void 0);return()=>t}catch{return}if(Z(e))try{const t=ca(e,void 0);return()=>t}catch{return}}function eu(e){return Y(e)&&"typeName"in e._def&&e._def.typeName==="ZodEffects"}function tu(e){return Z(e)&&e._zod.def.type==="pipe"}function ct(e,t=!1){if(Y(e))return eu(e)?ct(e._def.schema,t):e;if(Z(e)){let n=e;if(tu(e)&&(n=ct(e._zod.def.in,t)),t){if(Ce(n)){const r=n._zod.def.shape;for(const[s,i]of Object.entries(n._zod.def.shape))r[s]=ct(i,t);n=Ke(n,{...n._zod.def,shape:r})}else if(ln(n)){const r=ct(n._zod.def.element,t);n=Ke(n,{...n._zod.def,element:r})}}const a=he.get(e);return a&&he.add(n,a),n}throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function nu(e,t){if(Y(e)){const n=ta(e),a={};for(const[r,s]of Object.entries(n))t(r,s)?a[r]=s.optional():a[r]=s;return e.extend(a)}if(Z(e)){const n=ta(e),a={...e._zod.def.shape};for(const[i,o]of Object.entries(n))t(i,o)&&(a[i]=new Rr({type:"optional",innerType:o}));const r=Ke(e,{...e._zod.def,shape:a}),s=he.get(e);return s&&he.add(r,s),r}throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function kn(e){return e.replace(/[^a-zA-Z-_0-9]/g,"_")}const au=["*","_","`"];function ru(e){let t="";for(const[n,a]of Object.entries(e))t+=` classDef ${n} ${a};
53
+ Please make sure you are calling this method within a traceable function and that tracing is enabled.`);return t}function Ea(e){return typeof e=="function"&&"langsmith:traceable"in e}var fl={};F(fl,{LangChainTracer:()=>Bt});var Bt=class Es extends ft{name="langchain_tracer";projectName;exampleId;client;replicas;usesRunTreeMap=!0;constructor(t={}){super(t);const{exampleId:n,projectName:a,client:r,replicas:s}=t;this.projectName=a??us(),this.replicas=s,this.exampleId=n,this.client=r??Ts();const i=Es.getTraceableRunTree();i&&this.updateFromRunTree(i)}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 s=r.shift();!s||a.has(s.id)||(a.add(s.id),this.runTreeMap.set(s.id,s),s.child_runs&&r.push(...s.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 ce({...n,client:this.client,project_name:this.projectName,replicas:this.replicas,reference_example_id:this.exampleId,tracingEnabled:!0})}static getTraceableRunTree(){try{return pl(!0)}catch{return}}};let qe;function ml(){const e="default"in Pe?Pe.default:Pe;return new e({autoStart:!0,concurrency:1})}function gl(){return typeof qe>"u"&&(qe=ml()),qe}async function q(e,t){if(t===!0){const n=Tt();n!==void 0?await n.run(void 0,async()=>e()):await e()}else qe=gl(),qe.add(async()=>{const n=Tt();n!==void 0?await n.run(void 0,async()=>e()):await e()})}async function _l(){const e=Ts();await Promise.allSettled([typeof qe<"u"?qe.onIdle():Promise.resolve(),e.awaitPendingTraceBatches()])}var yl={};F(yl,{awaitAllCallbacks:()=>_l,consumeCallback:()=>q});const wl=e=>!!["LANGSMITH_TRACING_V2","LANGCHAIN_TRACING_V2","LANGSMITH_TRACING","LANGCHAIN_TRACING"].find(n=>Fe(n)==="true");function Ss(e){const t=Tt();return t===void 0?void 0:t.getStore()?.[bt]?.[e]}const bl=Symbol("lc:configure_hooks"),vl=()=>Ss(bl)||[];var Tl={};F(Tl,{BaseCallbackManager:()=>As,BaseRunManager:()=>Nt,CallbackManager:()=>Oe,CallbackManagerForChainRun:()=>Os,CallbackManagerForLLMRun:()=>Gn,CallbackManagerForRetrieverRun:()=>Is,CallbackManagerForToolRun:()=>Cs,ensureHandler:()=>St,parseCallbackConfigArg:()=>El});function El(e){return e?Array.isArray(e)||"name"in e?{callbacks:e}:e:{}}var As=class{setHandler(e){return this.setHandlers([e])}},Nt=class{constructor(e,t,n,a,r,s,i,o){this.runId=e,this.handlers=t,this.inheritableHandlers=n,this.tags=a,this.inheritableTags=r,this.metadata=s,this.inheritableMetadata=i,this._parentRunId=o}get parentRunId(){return this._parentRunId}async handleText(e){await Promise.all(this.handlers.map(t=>q(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(s=>q(async()=>{try{await s.handleCustomEvent?.(e,t,this.runId,this.tags,this.metadata)}catch(i){if((s.raiseError?console.error:console.warn)(`Error in handler ${s.constructor.name}, handleCustomEvent: ${i}`),s.raiseError)throw i}},s.awaitHandlers)))}},Is=class extends Nt{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=>q(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=>q(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)))}},Gn=class extends Nt{async handleLLMNewToken(e,t,n,a,r,s){await Promise.all(this.handlers.map(i=>q(async()=>{if(!i.ignoreLLM)try{await i.handleLLMNewToken?.(e,t??{prompt:0,completion:0},this.runId,this._parentRunId,this.tags,s)}catch(o){if((i.raiseError?console.error:console.warn)(`Error in handler ${i.constructor.name}, handleLLMNewToken: ${o}`),i.raiseError)throw o}},i.awaitHandlers)))}async handleLLMError(e,t,n,a,r){await Promise.all(this.handlers.map(s=>q(async()=>{if(!s.ignoreLLM)try{await s.handleLLMError?.(e,this.runId,this._parentRunId,this.tags,r)}catch(i){if((s.raiseError?console.error:console.warn)(`Error in handler ${s.constructor.name}, handleLLMError: ${i}`),s.raiseError)throw i}},s.awaitHandlers)))}async handleLLMEnd(e,t,n,a,r){await Promise.all(this.handlers.map(s=>q(async()=>{if(!s.ignoreLLM)try{await s.handleLLMEnd?.(e,this.runId,this._parentRunId,this.tags,r)}catch(i){if((s.raiseError?console.error:console.warn)(`Error in handler ${s.constructor.name}, handleLLMEnd: ${i}`),s.raiseError)throw i}},s.awaitHandlers)))}},Os=class extends Nt{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(s=>q(async()=>{if(!s.ignoreChain)try{await s.handleChainError?.(e,this.runId,this._parentRunId,this.tags,r)}catch(i){if((s.raiseError?console.error:console.warn)(`Error in handler ${s.constructor.name}, handleChainError: ${i}`),s.raiseError)throw i}},s.awaitHandlers)))}async handleChainEnd(e,t,n,a,r){await Promise.all(this.handlers.map(s=>q(async()=>{if(!s.ignoreChain)try{await s.handleChainEnd?.(e,this.runId,this._parentRunId,this.tags,r)}catch(i){if((s.raiseError?console.error:console.warn)(`Error in handler ${s.constructor.name}, handleChainEnd: ${i}`),s.raiseError)throw i}},s.awaitHandlers)))}async handleAgentAction(e){await Promise.all(this.handlers.map(t=>q(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=>q(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)))}},Cs=class extends Nt{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=>q(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=>q(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 _t extends As{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,s=void 0,i=void 0,o=void 0,c=void 0){return Promise.all(n.map(async(l,d)=>{const p=d===0&&a?a:se();return await Promise.all(this.handlers.map(f=>{if(!f.ignoreLLM)return st(f)&&f._createRunForLLMStart(t,[l],p,this._parentRunId,s,this.tags,this.metadata,c),q(async()=>{try{await f.handleLLMStart?.(t,[l],p,this._parentRunId,s,this.tags,this.metadata,c)}catch(m){if((f.raiseError?console.error:console.warn)(`Error in handler ${f.constructor.name}, handleLLMStart: ${m}`),f.raiseError)throw m}},f.awaitHandlers)})),new Gn(p,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChatModelStart(t,n,a=void 0,r=void 0,s=void 0,i=void 0,o=void 0,c=void 0){return Promise.all(n.map(async(l,d)=>{const p=d===0&&a?a:se();return await Promise.all(this.handlers.map(f=>{if(!f.ignoreLLM)return st(f)&&f._createRunForChatModelStart(t,[l],p,this._parentRunId,s,this.tags,this.metadata,c),q(async()=>{try{if(f.handleChatModelStart)await f.handleChatModelStart?.(t,[l],p,this._parentRunId,s,this.tags,this.metadata,c);else if(f.handleLLMStart){const m=ba(l);await f.handleLLMStart?.(t,[m],p,this._parentRunId,s,this.tags,this.metadata,c)}}catch(m){if((f.raiseError?console.error:console.warn)(`Error in handler ${f.constructor.name}, handleLLMStart: ${m}`),f.raiseError)throw m}},f.awaitHandlers)})),new Gn(p,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChainStart(t,n,a=se(),r=void 0,s=void 0,i=void 0,o=void 0){return await Promise.all(this.handlers.map(c=>{if(!c.ignoreChain)return st(c)&&c._createRunForChainStart(t,n,a,this._parentRunId,this.tags,this.metadata,r,o),q(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 Os(a,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleToolStart(t,n,a=se(),r=void 0,s=void 0,i=void 0,o=void 0){return await Promise.all(this.handlers.map(c=>{if(!c.ignoreAgent)return st(c)&&c._createRunForToolStart(t,n,a,this._parentRunId,this.tags,this.metadata,o),q(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 Cs(a,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleRetrieverStart(t,n,a=se(),r=void 0,s=void 0,i=void 0,o=void 0){return await Promise.all(this.handlers.map(c=>{if(!c.ignoreRetriever)return st(c)&&c._createRunForRetrieverStart(t,n,a,this._parentRunId,this.tags,this.metadata,o),q(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 Is(a,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleCustomEvent(t,n,a,r,s){await Promise.all(this.handlers.map(i=>q(async()=>{if(!i.ignoreCustomEvent)try{await i.handleCustomEvent?.(t,n,a,this.tags,this.metadata)}catch(o){if((i.raiseError?console.error:console.warn)(`Error in handler ${i.constructor.name}, handleCustomEvent: ${o}`),i.raiseError)throw o}},i.awaitHandlers)))}addHandler(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 _t(this._parentRunId);for(const r of this.handlers){const s=this.inheritableHandlers.includes(r);a.addHandler(r,s)}for(const r of this.tags){const s=this.inheritableTags.includes(r);a.addTags([r],s)}for(const r of Object.keys(this.metadata)){const s=Object.keys(this.inheritableMetadata).includes(r);a.addMetadata({[r]:this.metadata[r]},s)}for(const r of t)a.handlers.filter(s=>s.name==="console_callback_handler").some(s=>s.name===r.name)||a.addHandler(r,n);return a}static fromHandlers(t){class n extends xt{name=se();constructor(){super(),Object.assign(this,t)}}const a=new this;return a.addHandler(new n),a}static configure(t,n,a,r,s,i,o){return this._configureSync(t,n,a,r,s,i,o)}static _configureSync(t,n,a,r,s,i,o){let c;(t||n)&&(Array.isArray(t)||!t?(c=new _t,c.setHandlers(t?.map(St)??[],!0)):c=t,c=c.copy(Array.isArray(n)?n.map(St):n?.handlers,!1));const l=Fe("LANGCHAIN_VERBOSE")==="true"||o?.verbose,d=Bt.getTraceableRunTree()?.tracingEnabled||wl(),p=d||(Fe("LANGCHAIN_TRACING")??!1);if(l||p){if(c||(c=new _t),l&&!c.handlers.some(f=>f.name===Hn.prototype.name)){const f=new Hn;c.addHandler(f,!0)}if(p&&!c.handlers.some(f=>f.name==="langchain_tracer")&&d){const f=new Bt;c.addHandler(f,!0)}if(d){const f=Bt.getTraceableRunTree();f&&c._parentRunId===void 0&&(c._parentRunId=f.id,c.handlers.find(y=>y.name==="langchain_tracer")?.updateFromRunTree(f))}}for(const{contextVar:f,inheritable:m=!0,handlerClass:y,envVar:b}of vl()){const T=b&&Fe(b)==="true"&&y;let v;const I=f!==void 0?Ss(f):void 0;I&&cs(I)?v=I:T&&(v=new y({})),v!==void 0&&(c||(c=new _t),c.handlers.some(E=>E.name===v.name)||c.addHandler(v,m))}return(a||r)&&c&&(c.addTags(a??[]),c.addTags(r??[],!1)),(s||i)&&c&&(c.addMetadata(s??{}),c.addMetadata(i??{},!1)),c}};function St(e){return"name"in e?e:xt.fromMethods(e)}var xs=class{getStore(){}run(e,t){return t()}enterWith(e){}};const Sl=new xs,gr=Symbol.for("lc:child_config");var Al=class{getInstance(){return Tt()??Sl}getRunnableConfig(){return this.getInstance().getStore()?.extra?.[gr]}runWithConfig(e,t,n){const a=Oe._configureSync(e?.callbacks,void 0,e?.tags,void 0,e?.metadata),r=this.getInstance(),s=r.getStore(),i=a?.getParentRunId(),o=a?.handlers?.find(l=>l?.name==="langchain_tracer");let c;return o&&i?c=o.getRunTreeWithTracingConfig(i):n||(c=new ce({name:"<runnable_lambda>",tracingEnabled:!1})),c&&(c.extra={...c.extra,[gr]:e}),s!==void 0&&s[bt]!==void 0&&(c===void 0&&(c={}),c[bt]=s[bt]),r.run(c,t)}initializeGlobalInstance(e){Tt()===void 0&&Mo(e)}};const Me=new Al;var Il={};F(Il,{AsyncLocalStorageProviderSingleton:()=>Me,MockAsyncLocalStorage:()=>xs,_CONTEXT_VARIABLES_KEY:()=>bt});const Nn=25;async function pe(e){return Oe._configureSync(e?.callbacks,void 0,e?.tags,void 0,e?.metadata)}function Vn(...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,s=n.callbacks;if(Array.isArray(s))if(!r)t.callbacks=s;else if(Array.isArray(r))t.callbacks=r.concat(s);else{const i=r.copy();for(const o of s)i.addHandler(St(o),!0);t.callbacks=i}else if(s)if(!r)t.callbacks=s;else if(Array.isArray(r)){const i=s.copy();for(const o of r)i.addHandler(St(o),!0);t.callbacks=i}else t.callbacks=new Oe(s._parentRunId,{handlers:r.handlers.concat(s.handlers),inheritableHandlers:r.inheritableHandlers.concat(s.inheritableHandlers),tags:Array.from(new Set(r.tags.concat(s.tags))),inheritableTags:Array.from(new Set(r.inheritableTags.concat(s.inheritableTags))),metadata:{...r.metadata,...s.metadata}})}else{const r=a;t[r]=n[r]??t[r]}return t}const Ol=new Set(["string","number","boolean"]);function L(e){const t=Me.getRunnableConfig();let n={tags:[],metadata:{},recursionLimit:25,runId:void 0};if(t){const{runId:a,runName:r,...s}=t;n=Object.entries(s).reduce((i,[o,c])=>(c!==void 0&&(i[o]=c),i),n)}if(e&&(n=Object.entries(e).reduce((a,[r,s])=>(s!==void 0&&(a[r]=s),a),n)),n?.configurable)for(const a of Object.keys(n.configurable))Ol.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 H(e={},{callbacks:t,maxConcurrency:n,recursionLimit:a,runName:r,configurable:s,runId:i}={}){const o=L(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),s!==void 0&&(o.configurable={...o.configurable,...s}),i!==void 0&&delete o.runId,o}function Ye(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 He(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(Jt(t))},t.addEventListener("abort",n),t.aborted&&r(Jt(t))})]).finally(()=>t.removeEventListener("abort",n))}function Jt(e){return e?.reason instanceof Error?e.reason:typeof e?.reason=="string"?new Error(e.reason):new Error("Aborted")}var Cl={};F(Cl,{AsyncGeneratorWithSetup:()=>nt,IterableReadableStream:()=>Te,atee:()=>Sa,concat:()=>Qe,pipeGeneratorWithSetup:()=>Ns});var Te=class Zn 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 Zn({start(a){return r();function r(){return n.read().then(({done:s,value:i})=>{if(s){a.close();return}return a.enqueue(i),r()})}},cancel(){n.releaseLock()}})}static fromAsyncGenerator(t){return new Zn({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 Sa(e,t=2){const n=Array.from({length:t},()=>[]);return n.map(async function*(r){for(;;)if(r.length===0){const s=await e.next();for(const i of n)i.push(s)}else{if(r[0].done)return;yield r.shift().value}})}function Qe(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]=Qe(n[a],r):n[a]=r;return n}else throw new Error(`Cannot concat ${typeof e} and ${typeof t}`)}var nt=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)=>{Me.runWithConfig(Ye(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?Me.runWithConfig(Ye(this.config),this.signal?async()=>He(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 Ns(e,t,n,a,...r){const s=new nt({generator:t,startSetup:n,signal:a}),i=await s.setup;return{output:e(s,i,...r),setup:i}}const xl=Object.prototype.hasOwnProperty;function qn(e,t){return xl.call(e,t)}function Jn(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)qn(e,n)&&t.push(n);return t}function be(e){switch(typeof e){case"object":return JSON.parse(JSON.stringify(e));case"undefined":return null;default:return e}}function Wn(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 rt(e){return e.indexOf("/")===-1&&e.indexOf("~")===-1?e:e.replace(/~/g,"~0").replace(/\//g,"~1")}function Nl(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function Kn(e){if(e===void 0)return!0;if(e){if(Array.isArray(e)){for(let n=0,a=e.length;n<a;n++)if(Kn(e[n]))return!0}else if(typeof e=="object"){const n=Jn(e),a=n.length;for(var t=0;t<a;t++)if(Kn(e[n[t]]))return!0}}return!1}function _r(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(`
54
+ `)}var kl=class extends Error{constructor(e,t,n,a,r){super(_r(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=_r(e,{name:t,index:n,operation:a,tree:r})}},ks={};F(ks,{JsonPatchError:()=>G,_areEquals:()=>At,applyOperation:()=>Je,applyPatch:()=>dt,applyReducer:()=>Ml,deepClone:()=>Rl,getValueByPointer:()=>Wt,validate:()=>Rs,validator:()=>Kt});const G=kl,Rl=be,ot={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=Wt(n,this.path);a&&(a=be(a));const r=Je(n,{op:"remove",path:this.from}).removed;return Je(n,{op:"add",path:this.path,value:r}),{newDocument:n,removed:a}},copy:function(e,t,n){const a=Wt(n,this.from);return Je(n,{op:"add",path:this.path,value:be(a)}),{newDocument:n}},test:function(e,t,n){return{newDocument:n,test:At(e[t],this.value)}},_get:function(e,t,n){return this.value=e[t],{newDocument:n}}};var Pl={add:function(e,t,n){return Wn(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:ot.move,copy:ot.copy,test:ot.test,_get:ot._get};function Wt(e,t){if(t=="")return e;var n={op:"_get",path:t};return Je(e,n),n.value}function Je(e,t,n=!1,a=!0,r=!0,s=0){if(n&&(typeof n=="function"?n(t,0,e,t.path):Kt(t,0)),t.path===""){let i={newDocument:e};if(t.op==="add")return i.newDocument=t.value,i;if(t.op==="replace")return i.newDocument=t.value,i.removed=e,i;if(t.op==="move"||t.op==="copy")return i.newDocument=Wt(e,t.from),t.op==="move"&&(i.removed=e),i;if(t.op==="test"){if(i.test=At(e,t.value),i.test===!1)throw new G("Test operation failed","TEST_OPERATION_FAILED",s,t,e);return i.newDocument=e,i}else{if(t.op==="remove")return i.removed=e,i.newDocument=null,i;if(t.op==="_get")return t.value=e,i;if(n)throw new G("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",s,t,e);return i}}else{a||(e=be(e));const o=(t.path||"").split("/");let c=e,l=1,d=o.length,p,f,m;for(typeof n=="function"?m=n:m=Kt;;){if(f=o[l],f&&f.indexOf("~")!=-1&&(f=Nl(f)),r&&(f=="__proto__"||f=="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&&p===void 0&&(c[f]===void 0?p=o.slice(0,l).join("/"):l==d-1&&(p=t.path),p!==void 0&&m(t,0,e,p)),l++,Array.isArray(c)){if(f==="-")f=c.length;else{if(n&&!Wn(f))throw new G("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",s,t,e);Wn(f)&&(f=~~f)}if(l>=d){if(n&&t.op==="add"&&f>c.length)throw new G("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",s,t,e);const y=Pl[t.op].call(t,c,f,e);if(y.test===!1)throw new G("Test operation failed","TEST_OPERATION_FAILED",s,t,e);return y}}else if(l>=d){const y=ot[t.op].call(t,c,f,e);if(y.test===!1)throw new G("Test operation failed","TEST_OPERATION_FAILED",s,t,e);return y}if(c=c[f],n&&l<d&&(!c||typeof c!="object"))throw new G("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",s,t,e)}}}function dt(e,t,n,a=!0,r=!0){if(n&&!Array.isArray(t))throw new G("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");a||(e=be(e));const s=new Array(t.length);for(let i=0,o=t.length;i<o;i++)s[i]=Je(e,t[i],n,!0,r,i),e=s[i].newDocument;return s.newDocument=e,s}function Ml(e,t,n){const a=Je(e,t);if(a.test===!1)throw new G("Test operation failed","TEST_OPERATION_FAILED",n,t,e);return a.newDocument}function Kt(e,t,n,a){if(typeof e!="object"||e===null||Array.isArray(e))throw new G("Operation is not an object","OPERATION_NOT_AN_OBJECT",t,e,n);if(ot[e.op]){if(typeof e.path!="string")throw new G("Operation `path` property is not a string","OPERATION_PATH_INVALID",t,e,n);if(e.path.indexOf("/")!==0&&e.path.length>0)throw new G('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 G("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 G("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")&&Kn(e.value))throw new G("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,s=a.split("/").length;if(r!==s+1&&r!==s)throw new G("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 G("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 i={op:"_get",path:e.from,value:void 0},o=Rs([i],n);if(o&&o.name==="OPERATION_PATH_UNRESOLVABLE")throw new G("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",t,e,n)}}}else throw new G("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",t,e,n)}function Rs(e,t,n){try{if(!Array.isArray(e))throw new G("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(t)dt(be(t),be(e),n||!0);else{n=n||Kt;for(var a=0;a<e.length;a++)n(e[a],a,t,void 0)}}catch(r){if(r instanceof G)return r;throw r}}function At(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,s,i;if(n&&a){if(s=e.length,s!=t.length)return!1;for(r=s;r--!==0;)if(!At(e[r],t[r]))return!1;return!0}if(n!=a)return!1;var o=Object.keys(e);if(s=o.length,s!==Object.keys(t).length)return!1;for(r=s;r--!==0;)if(!t.hasOwnProperty(o[r]))return!1;for(r=s;r--!==0;)if(i=o[r],!At(e[i],t[i]))return!1;return!0}return e!==e&&t!==t}function Ps(e,t,n,a,r){if(t!==e){typeof t.toJSON=="function"&&(t=t.toJSON());for(var s=Jn(t),i=Jn(e),o=!1,c=i.length-1;c>=0;c--){var l=i[c],d=e[l];if(qn(t,l)&&!(t[l]===void 0&&d!==void 0&&Array.isArray(t)===!1)){var p=t[l];typeof d=="object"&&d!=null&&typeof p=="object"&&p!=null&&Array.isArray(d)===Array.isArray(p)?Ps(d,p,n,a+"/"+rt(l),r):d!==p&&(r&&n.push({op:"test",path:a+"/"+rt(l),value:be(d)}),n.push({op:"replace",path:a+"/"+rt(l),value:be(p)}))}else Array.isArray(e)===Array.isArray(t)?(r&&n.push({op:"test",path:a+"/"+rt(l),value:be(d)}),n.push({op:"remove",path:a+"/"+rt(l)}),o=!0):(r&&n.push({op:"test",path:a,value:e}),n.push({op:"replace",path:a,value:t}))}if(!(!o&&s.length==i.length))for(var c=0;c<s.length;c++){var l=s[c];!qn(e,l)&&t[l]!==void 0&&n.push({op:"add",path:a+"/"+rt(l),value:be(t[l])})}}}function Aa(e,t,n=!1){var a=[];return Ps(e,t,a,"",n),a}({...ks});var Ll={};F(Ll,{LogStreamCallbackHandler:()=>Qn,RunLog:()=>Ia,RunLogPatch:()=>ke,isLogStreamHandler:()=>Ms});var ke=class{ops;constructor(e){this.ops=e.ops??[]}concat(e){const t=this.ops.concat(e.ops),n=dt({},t);return new Ia({ops:t,state:n[n.length-1].newDocument})}},Ia=class Yn extends ke{state;constructor(t){super(t),this.state=t.state}concat(t){const n=this.ops.concat(t.ops),a=dt(this.state,t.ops);return new Yn({ops:n,state:a[a.length-1].newDocument})}static fromRunLogPatch(t){const n=dt({},t.ops);return new Yn({ops:t.ops,state:n[n.length-1].newDocument})}};const Ms=e=>e.name==="log_stream_tracer";async function yr(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 wr(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 $l(e){return e!==void 0&&e.message!==void 0}var Qn=class extends ft{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=Te.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 ke({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 ke({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 yr(e,this._schemaFormat)),await this.writer.write(new ke({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 yr(e,this._schemaFormat)}),n.push({op:"add",path:`/logs/${t}/final_output`,value:await wr(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 ke({ops:n});await this.writer.write(a)}finally{if(e.id===this.rootId){const t=new ke({ops:[{op:"replace",path:"/final_output",value:await wr(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 s;r?$l(n?.chunk)?s=n?.chunk:s=new tt({id:`run-${e.id}`,content:t}):s=t;const i=new ke({ops:[{op:"add",path:`/logs/${a}/streamed_output_str/-`,value:t},{op:"add",path:`/logs/${a}/streamed_output/-`,value:s}]});await this.writer.write(i)}},jl={};F(jl,{ChatGenerationChunk:()=>ea,GenerationChunk:()=>It,RUN_KEY:()=>Xn});const Xn="__run";var It=class Ls{text;generationInfo;constructor(t){this.text=t.text,this.generationInfo=t.generationInfo}concat(t){return new Ls({text:this.text+t.text,generationInfo:{...this.generationInfo,...t.generationInfo}})}},ea=class $s extends It{message;constructor(t){super(t),this.message=t.message}concat(t){return new $s({text:this.text+t.text,generationInfo:{...this.generationInfo,...t.generationInfo},message:this.message.concat(t.message)})}};function jt({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 Dl=e=>e.name==="event_stream_tracer";var Fl=class extends ft{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=Te.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(i,o){return i==="llm"&&typeof o=="string"?new It({text:o}):o}let s=this.tappedPromises.get(e);if(s===void 0){let i;s=new Promise(o=>{i=o}),this.tappedPromises.set(e,s);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{i?.()}}else{yield n.value;for await(const i of t)yield i}}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=jt(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,s;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")s="on_chat_model_stream",n?.chunk===void 0?r=new tt({content:t,id:`run-${e.id}`}):r=n.chunk.message;else if(a.runType==="llm")s="on_llm_stream",n?.chunk===void 0?r=new It({text:t}):r=n.chunk;else throw new Error(`Unexpected run type ${a.runType}`);await this.send({event:s,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 s of a??[]){if(r!==void 0)break;r=s[0]?.message}n="on_chat_model_end"}else if(t.runType==="llm")r={generations:a?.map(s=>s.map(i=>({text:i.text,generationInfo:i.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=jt(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??{},s={output:e.outputs?.output??e.outputs,input:a};a.input&&Object.keys(a).length===1&&(s.input=a.input,t.inputs=a.input),await this.sendEndEvent({event:n,data:s,run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata??{}},t)}async onToolStart(e){const t=jt(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=jt(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()})}},Ul={};F(Ul,{AsyncCaller:()=>cn});const Bl=[400,401,402,403,404,405,406,407,409],zl=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&&Bl.includes(+t))throw e;if(e?.error?.code==="insufficient_quota"){const n=new Error(e?.message);throw n.name="InsufficientQuotaError",n}};var cn=class{maxConcurrency;maxRetries;onFailedAttempt;queue;constructor(e){this.maxConcurrency=e.maxConcurrency??1/0,this.maxRetries=e.maxRetries??6,this.onFailedAttempt=e.onFailedAttempt??zl;const t="default"in Pe?Pe.default:Pe;this.queue=new t({concurrency:this.maxConcurrency})}call(e,...t){return this.queue.add(()=>Ht(()=>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){if(e.signal){let a;return Promise.race([this.call(t,...n),new Promise((r,s)=>{a=()=>{s(Jt(e.signal))},e.signal?.addEventListener("abort",a)})]).finally(()=>{e.signal&&a&&e.signal.removeEventListener("abort",a)})}return this.call(t,...n)}fetch(...e){return this.call(()=>fetch(...e).then(t=>t.ok?t:Promise.reject(t)))}},js=class extends ft{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 Oa(e){return e?e.lc_runnable:!1}var Hl=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 Z(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 Y(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 Gl(e){return Z(e)&&console.warn("[WARNING] Attempting to use Zod 4 schema in a context where Zod 3 schema is expected. This may cause unexpected behavior."),Y(e)}function kt(e){return!e||typeof e!="object"||Array.isArray(e)?!1:!!(Z(e)||Y(e))}function Ds(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 Fs(e){return Z(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 Vl(e){return!!(Ds(e)||Fs(e))}async function Zl(e,t){if(Z(e))try{return{success:!0,data:await kr(e,t)}}catch(n){return{success:!1,error:n}}if(Y(e))return await e.safeParseAsync(t);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}async function Ca(e,t){if(Z(e))return await kr(e,t);if(Y(e))return await e.parseAsync(t);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function ql(e,t){if(Z(e))try{return{success:!0,data:ca(e,t)}}catch(n){return{success:!1,error:n}}if(Y(e))return e.safeParse(t);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function Jl(e,t){if(Z(e))return ca(e,t);if(Y(e))return e.parse(t);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function xa(e){if(Z(e))return he.get(e)?.description;if(Y(e)||"description"in e&&typeof e.description=="string")return e.description}function Wl(e){if(!kt(e))return!1;if(Y(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(Z(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 Us(e){return kt(e)?Y(e)?e._def.typeName==="ZodString":Z(e)?e._zod.def.type==="string":!1:!1}function Na(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 Ce(e){return Z(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 ln(e){return Z(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 Kl(e){return!!(Na(e)||Ce(e))}function ta(e){if(Y(e))return e.shape;if(Z(e))return e._zod.def.shape;throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function Yl(e,t){if(Y(e))return e.extend(t);if(Z(e))return Ri(e,t);throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function Ql(e){if(Y(e))return e.partial();if(Z(e))return ki(Rr,e);throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function Yt(e,t=!1){if(Y(e))return e.strict();if(Ce(e)){const n=e._zod.def.shape;if(t)for(const[s,i]of Object.entries(e._zod.def.shape)){if(Ce(i)){const c=Yt(i,t);n[s]=c}else if(ln(i)){let c=i._zod.def.element;Ce(c)&&(c=Yt(c,t)),n[s]=Ke(i,{...i._zod.def,element:c})}else n[s]=i;const o=he.get(i);o&&he.add(n[s],o)}const a=Ke(e,{...e._zod.def,shape:n,catchall:Ci(xi)}),r=he.get(e);return r&&he.add(a,r),a}throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function na(e,t=!1){if(Na(e))return e.passthrough();if(Ce(e)){const n=e._zod.def.shape;if(t)for(const[s,i]of Object.entries(e._zod.def.shape)){if(Ce(i)){const c=na(i,t);n[s]=c}else if(ln(i)){let c=i._zod.def.element;Ce(c)&&(c=na(c,t)),n[s]=Ke(i,{...i._zod.def,element:c})}else n[s]=i;const o=he.get(i);o&&he.add(n[s],o)}const a=Ke(e,{...e._zod.def,shape:n,catchall:Ni(Pi)}),r=he.get(e);return r&&he.add(a,r),a}throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function Xl(e){if(Y(e))try{const t=e.parse(void 0);return()=>t}catch{return}if(Z(e))try{const t=ca(e,void 0);return()=>t}catch{return}}function eu(e){return Y(e)&&"typeName"in e._def&&e._def.typeName==="ZodEffects"}function tu(e){return Z(e)&&e._zod.def.type==="pipe"}function ct(e,t=!1){if(Y(e))return eu(e)?ct(e._def.schema,t):e;if(Z(e)){let n=e;if(tu(e)&&(n=ct(e._zod.def.in,t)),t){if(Ce(n)){const r=n._zod.def.shape;for(const[s,i]of Object.entries(n._zod.def.shape))r[s]=ct(i,t);n=Ke(n,{...n._zod.def,shape:r})}else if(ln(n)){const r=ct(n._zod.def.element,t);n=Ke(n,{...n._zod.def,element:r})}}const a=he.get(e);return a&&he.add(n,a),n}throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function nu(e,t){if(Y(e)){const n=ta(e),a={};for(const[r,s]of Object.entries(n))t(r,s)?a[r]=s.optional():a[r]=s;return e.extend(a)}if(Z(e)){const n=ta(e),a={...e._zod.def.shape};for(const[i,o]of Object.entries(n))t(i,o)&&(a[i]=new Rr({type:"optional",innerType:o}));const r=Ke(e,{...e._zod.def,shape:a}),s=he.get(e);return s&&he.add(r,s),r}throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function kn(e){return e.replace(/[^a-zA-Z-_0-9]/g,"_")}const au=["*","_","`"];function ru(e){let t="";for(const[n,a]of Object.entries(e))t+=` classDef ${n} ${a};
59
55
  `;return t}function su(e,t,n){const{firstNode:a,lastNode:r,nodeColors:s,withStyles:i=!0,curveStyle:o="linear",wrapLabelNWords:c=9}=n??{};let l=i?`%%{init: {'flowchart': {'curve': '${o}'}}}%%
60
56
  graph TD;
61
57
  `:`graph TD;
@@ -78,7 +74,7 @@ data: ${JSON.stringify(r)}
78
74
  Instead got an unsupported type.`)}var Pa=class extends V{static lc_name(){return"RunnableAssign"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;mapper;constructor(e){e instanceof gt&&(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,s]=Sa(e),i=this.mapper.transform(s,H(n,{callbacks:t?.getChild()})),o=i.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(([d])=>!a.includes(d)));Object.keys(l).length>0&&(yield l)}yield(await o).value;for await(const c of i)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=L(t),r=new nt({generator:this.transform(n(),a),config:a});return await r.setup,Te.fromAsyncGenerator(r)}},ei=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=L(t),r=new nt({generator:this.transform(n(),a),config:a});return await r.setup,Te.fromAsyncGenerator(r)}},sa=class extends ht{name;description;schema;constructor(e){const t=un.from([Ge.from(async n=>{let a;if(Xr(n))try{a=await Ca(this.schema,n.args)}catch{throw new Oo("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 nd(e,t){const n=t.name??e.getName(),a=t.description??xa(t.schema);return Us(t.schema)?new sa({name:n,description:a,schema:la({input:ua()}).transform(r=>r.input),bound:e}):new sa({name:n,description:a,schema:t.schema,bound:e})}const Xt=(e,t)=>{const n=[...new Set(t?.map(r=>{if(typeof r=="string")return r;const s=new r({});if(!("getType"in s)||typeof s.getType!="function")throw new Error("Invalid type provided.");return s.getType()}))],a=e.getType();return n.some(r=>r===a)};function ad(e,t){return Array.isArray(e)?Ir(e,t):Ge.from(n=>Ir(n,e))}function Ir(e,t={}){const{includeNames:n,excludeNames:a,includeTypes:r,excludeTypes:s,includeIds:i,excludeIds:o}=t,c=[];for(const l of e)if(!(a&&l.name&&a.includes(l.name))){{if(s&&Xt(l,s))continue;if(o&&l.id&&o.includes(l.id))continue}r||i||n?(n&&l.name&&n.some(d=>d===l.name)||r&&Xt(l,r)||i&&l.id&&i.some(d=>d===l.id))&&c.push(l):c.push(l)}return c}function rd(e){return Array.isArray(e)?Or(e):Ge.from(Or)}function Or(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 s=Vt(r),i=Vt(a),o=s.concat(i);typeof s.content=="string"&&typeof i.content=="string"&&(o.content=`${s.content}
79
75
  ${i.content}`),t.push(od(o))}}return t}function sd(e,t){if(Array.isArray(e)){const n=e;if(!t)throw new Error("Options parameter is required when providing messages.");return Cr(n,t)}else{const n=e;return Ge.from(a=>Cr(a,n)).withConfig({runName:"trim_messages"})}}async function Cr(e,t){const{maxTokens:n,tokenCounter:a,strategy:r="last",allowPartial:s=!1,endOn:i,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 d;"getNumTokens"in a?d=async f=>(await Promise.all(f.map(y=>a.getNumTokens(y.content)))).reduce((y,b)=>y+b,0):d=async f=>a(f);let p=ni;if(l&&("splitText"in l?p=l.splitText:p=async f=>l(f)),r==="first")return ti(e,{maxTokens:n,tokenCounter:d,textSplitter:p,partialStrategy:s?"first":void 0,endOn:i});if(r==="last")return id(e,{maxTokens:n,tokenCounter:d,textSplitter:p,allowPartial:s,includeSystem:c,startOn:o,endOn:i});throw new Error(`Unrecognized strategy: '${r}'. Must be one of 'first' or 'last'.`)}async function ti(e,t){const{maxTokens:n,tokenCounter:a,textSplitter:r,partialStrategy:s,endOn:i}=t;let o=[...e],c=0;for(let l=0;l<o.length;l+=1){const d=l>0?o.slice(0,-l):o;if(await a(d)<=n){c=o.length-l;break}}if(c<o.length&&s){let l=!1;if(Array.isArray(o[c].content)){const d=o[c];if(typeof d.content=="string")throw new Error("Expected content to be an array.");const p=d.content.length,f=s==="last"?[...d.content].reverse():d.content;for(let m=1;m<=p;m+=1){const y=s==="first"?f.slice(0,m):f.slice(-m),b=Object.fromEntries(Object.entries(d).filter(([I])=>I!=="type"&&!I.startsWith("lc_"))),T=Ma(d.getType(),{...b,content:y}),v=[...o.slice(0,c),T];if(await a(v)<=n)o=v,c+=1,l=!0;else break}l&&s==="last"&&(d.content=[...f].reverse())}if(!l){const d=o[c];let p;if(Array.isArray(d.content)&&d.content.some(f=>typeof f=="string"||f.type==="text")?p=d.content.find(m=>m.type==="text"&&m.text)?.text:typeof d.content=="string"&&(p=d.content),p){const f=await r(p),m=f.length;s==="last"&&f.reverse();for(let y=0;y<m-1;y+=1)if(f.pop(),d.content=f.join(""),await a([...o.slice(0,c),d])<=n){s==="last"&&(d.content=[...f].reverse().join("")),o=[...o.slice(0,c),d],c+=1;break}}}}if(i){const l=Array.isArray(i)?i:[i];for(;c>0&&!Xt(o[c-1],l);)c-=1}return o.slice(0,c)}async function id(e,t){const{allowPartial:n=!1,includeSystem:a=!1,endOn:r,startOn:s,...i}=t;let o=e.map(d=>{const p=Object.fromEntries(Object.entries(d).filter(([f])=>f!=="type"&&!f.startsWith("lc_")));return Ma(d.getType(),p,ga(d))});if(r){const d=Array.isArray(r)?r:[r];for(;o.length>0&&!Xt(o[o.length-1],d);)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 ti(l,{...i,partialStrategy:n?"last":void 0,endOn:s}),c?[l[0],...l.slice(1).reverse()]:l.reverse()}const xr={human:{message:$e,messageChunk:sn},ai:{message:Be,messageChunk:tt},system:{message:ze,messageChunk:ut},developer:{message:ze,messageChunk:ut},tool:{message:pt,messageChunk:tn},function:{message:an,messageChunk:rn},generic:{message:Ct,messageChunk:nn},remove:{message:Gt,messageChunk:Gt}};function Ma(e,t,n){let a,r;switch(e){case"human":n?a=new sn(t):r=new $e(t);break;case"ai":if(n){let s={...t};"tool_calls"in s&&(s={...s,tool_call_chunks:s.tool_calls?.map(i=>({...i,type:"tool_call_chunk",index:void 0,args:JSON.stringify(i.args)}))}),a=new tt(s)}else r=new Be(t);break;case"system":n?a=new ut(t):r=new ze(t);break;case"developer":n?a=new ut({...t,additional_kwargs:{...t.additional_kwargs,__openai_role__:"developer"}}):r=new ze({...t,additional_kwargs:{...t.additional_kwargs,__openai_role__:"developer"}});break;case"tool":if("tool_call_id"in t)n?a=new tn(t):r=new pt(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 rn(t);else{if(!t.name)throw new Error("FunctionMessage must have a 'name' field");r=new an(t)}break;case"generic":if("role"in t)n?a=new nn(t):r=new Ct(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 od(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 xr&&(n=Ma(t,a)),!n)throw new Error(`Unrecognized message chunk class ${t}. Supported classes are ${Object.keys(xr)}`);return n}function ni(e){const t=e.split(`
80
76
  `);return Promise.resolve([...t.slice(0,-1).map(n=>`${n}
81
- `),t[t.length-1]])}const cd=["tool_call","tool_call_chunk","invalid_tool_call","server_tool_call","server_tool_call_chunk","server_tool_call_result"],ld=["image","video","audio","text-plain","file"],ud=["text","reasoning",...cd,...ld];var dd={};F(dd,{AIMessage:()=>Be,AIMessageChunk:()=>tt,BaseMessage:()=>Le,BaseMessageChunk:()=>et,ChatMessage:()=>Ct,ChatMessageChunk:()=>nn,FunctionMessage:()=>an,FunctionMessageChunk:()=>rn,HumanMessage:()=>$e,HumanMessageChunk:()=>sn,KNOWN_BLOCK_TYPES:()=>ud,RemoveMessage:()=>Gt,SystemMessage:()=>ze,SystemMessageChunk:()=>ut,ToolMessage:()=>pt,ToolMessageChunk:()=>tn,_isMessageFieldWithRole:()=>zr,_mergeDicts:()=>ee,_mergeLists:()=>Ot,_mergeObj:()=>Br,_mergeStatus:()=>Ur,coerceMessageLikeToMessage:()=>wt,convertToChunk:()=>Vt,convertToOpenAIImageBlock:()=>Lr,convertToProviderContentBlock:()=>Bi,defaultTextSplitter:()=>ni,defaultToolCallParser:()=>_a,filterMessages:()=>ad,getBufferString:()=>ba,iife:()=>Co,isAIMessage:()=>Kr,isAIMessageChunk:()=>Dn,isBase64ContentBlock:()=>ha,isBaseMessage:()=>Re,isBaseMessageChunk:()=>ga,isChatMessage:()=>wo,isChatMessageChunk:()=>bo,isDataContentBlock:()=>Ue,isDirectToolOutput:()=>Zr,isFunctionMessage:()=>vo,isFunctionMessageChunk:()=>To,isHumanMessage:()=>Eo,isHumanMessageChunk:()=>So,isIDContentBlock:()=>Mr,isMessage:()=>$r,isOpenAIToolCallArray:()=>co,isPlainTextContentBlock:()=>Fi,isSystemMessage:()=>Ao,isSystemMessageChunk:()=>Io,isToolMessage:()=>qr,isToolMessageChunk:()=>Jr,isURLContentBlock:()=>da,mapChatMessagesToStoredMessages:()=>Po,mapStoredMessageToChatMessage:()=>va,mapStoredMessagesToChatMessages:()=>Ro,mergeContent:()=>Xe,mergeMessageRuns:()=>rd,mergeResponseMetadata:()=>Hr,mergeUsageMetadata:()=>Vr,parseBase64DataUrl:()=>$n,parseMimeType:()=>Ui,trimMessages:()=>sd});var hd={};F(hd,{extendInteropZodObject:()=>Yl,getInteropZodDefaultGetter:()=>Xl,getInteropZodObjectShape:()=>ta,getSchemaDescription:()=>xa,interopParse:()=>Jl,interopParseAsync:()=>Ca,interopSafeParse:()=>ql,interopSafeParseAsync:()=>Zl,interopZodObjectMakeFieldsOptional:()=>nu,interopZodObjectPartial:()=>Ql,interopZodObjectPassthrough:()=>na,interopZodObjectStrict:()=>Yt,interopZodTransformInputSchema:()=>ct,isInteropZodLiteral:()=>Vl,isInteropZodObject:()=>Kl,isInteropZodSchema:()=>kt,isShapelessZodSchema:()=>Wl,isSimpleStringZodSchema:()=>Us,isZodArrayV4:()=>ln,isZodLiteralV3:()=>Ds,isZodLiteralV4:()=>Fs,isZodObjectV3:()=>Na,isZodObjectV4:()=>Ce,isZodSchema:()=>Gl,isZodSchemaV3:()=>Y,isZodSchemaV4:()=>Z});function ai(e){return e!==void 0&&Array.isArray(e.lc_namespace)}function ri(e){return e!==void 0&&V.isRunnable(e)&&"lc_name"in e.constructor&&typeof e.constructor.lc_name=="function"&&e.constructor.lc_name()==="RunnableToolLike"}function si(e){return!!e&&typeof e=="object"&&"name"in e&&"schema"in e&&(kt(e.schema)||e.schema!=null&&typeof e.schema=="object"&&"type"in e.schema&&typeof e.schema.type=="string"&&["null","boolean","object","array","number","string"].includes(e.schema.type))}function ii(e){return si(e)||ri(e)||ai(e)}var pd={};F(pd,{convertToOpenAIFunction:()=>oi,convertToOpenAITool:()=>fd,isLangChainTool:()=>ii,isRunnableToolLike:()=>ri,isStructuredTool:()=>ai,isStructuredToolParams:()=>si});function oi(e,t){const n=typeof t=="number"?void 0:t;return{name:e.name,description:e.description,parameters:mt(e.schema),...n?.strict!==void 0?{strict:n.strict}:{}}}function fd(e,t){const n=typeof t=="number"?void 0:t;let a;return ii(e)?a={type:"function",function:oi(e)}:a=e,n?.strict!==void 0&&(a.function.strict=n.strict),a}var md={};F(md,{BasePromptValue:()=>dn,ChatPromptValue:()=>li,ImagePromptValue:()=>gd,StringPromptValue:()=>ci});var dn=class extends lt{},ci=class extends dn{static lc_name(){return"StringPromptValue"}lc_namespace=["langchain_core","prompt_values"];lc_serializable=!0;value;constructor(e){super({value:e}),this.value=e}toString(){return this.value}toChatMessages(){return[new $e(this.value)]}},li=class extends dn{lc_namespace=["langchain_core","prompt_values"];lc_serializable=!0;static lc_name(){return"ChatPromptValue"}messages;constructor(e){Array.isArray(e)&&(e={messages:e}),super(e),this.messages=e.messages}toString(){return ba(this.messages)}toChatMessages(){return this.messages}},gd=class extends dn{lc_namespace=["langchain_core","prompt_values"];lc_serializable=!0;static lc_name(){return"ImagePromptValue"}imageUrl;value;constructor(e){"imageUrl"in e||(e={imageUrl:e}),super(e),this.imageUrl=e.imageUrl}toString(){return this.imageUrl.url}toChatMessages(){return[new $e({content:[{type:"image_url",image_url:{detail:this.imageUrl.detail,url:this.imageUrl.url}}]})]}},A="0123456789abcdef".split(""),_d=[-2147483648,8388608,32768,128],ye=[24,16,8,0],Dt=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],Q=[];function Ee(e,t){t?(Q[0]=Q[16]=Q[1]=Q[2]=Q[3]=Q[4]=Q[5]=Q[6]=Q[7]=Q[8]=Q[9]=Q[10]=Q[11]=Q[12]=Q[13]=Q[14]=Q[15]=0,this.blocks=Q):this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],e?(this.h0=3238371032,this.h1=914150663,this.h2=812702999,this.h3=4144912697,this.h4=4290775857,this.h5=1750603025,this.h6=1694076839,this.h7=3204075428):(this.h0=1779033703,this.h1=3144134277,this.h2=1013904242,this.h3=2773480762,this.h4=1359893119,this.h5=2600822924,this.h6=528734635,this.h7=1541459225),this.block=this.start=this.bytes=this.hBytes=0,this.finalized=this.hashed=!1,this.first=!0,this.is224=e}Ee.prototype.update=function(e){if(!this.finalized){var t,n=typeof e;if(n!=="string"){if(n==="object"){if(e===null)throw new Error(ERROR);if(ARRAY_BUFFER&&e.constructor===ArrayBuffer)e=new Uint8Array(e);else if(!Array.isArray(e)&&(!ARRAY_BUFFER||!ArrayBuffer.isView(e)))throw new Error(ERROR)}else throw new Error(ERROR);t=!0}for(var a,r=0,s,i=e.length,o=this.blocks;r<i;){if(this.hashed&&(this.hashed=!1,o[0]=this.block,this.block=o[16]=o[1]=o[2]=o[3]=o[4]=o[5]=o[6]=o[7]=o[8]=o[9]=o[10]=o[11]=o[12]=o[13]=o[14]=o[15]=0),t)for(s=this.start;r<i&&s<64;++r)o[s>>>2]|=e[r]<<ye[s++&3];else for(s=this.start;r<i&&s<64;++r)a=e.charCodeAt(r),a<128?o[s>>>2]|=a<<ye[s++&3]:a<2048?(o[s>>>2]|=(192|a>>>6)<<ye[s++&3],o[s>>>2]|=(128|a&63)<<ye[s++&3]):a<55296||a>=57344?(o[s>>>2]|=(224|a>>>12)<<ye[s++&3],o[s>>>2]|=(128|a>>>6&63)<<ye[s++&3],o[s>>>2]|=(128|a&63)<<ye[s++&3]):(a=65536+((a&1023)<<10|e.charCodeAt(++r)&1023),o[s>>>2]|=(240|a>>>18)<<ye[s++&3],o[s>>>2]|=(128|a>>>12&63)<<ye[s++&3],o[s>>>2]|=(128|a>>>6&63)<<ye[s++&3],o[s>>>2]|=(128|a&63)<<ye[s++&3]);this.lastByteIndex=s,this.bytes+=s-this.start,s>=64?(this.block=o[16],this.start=s-64,this.hash(),this.hashed=!0):this.start=s}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296<<0,this.bytes=this.bytes%4294967296),this}};Ee.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var e=this.blocks,t=this.lastByteIndex;e[16]=this.block,e[t>>>2]|=_d[t&3],this.block=e[16],t>=56&&(this.hashed||this.hash(),e[0]=this.block,e[16]=e[1]=e[2]=e[3]=e[4]=e[5]=e[6]=e[7]=e[8]=e[9]=e[10]=e[11]=e[12]=e[13]=e[14]=e[15]=0),e[14]=this.hBytes<<3|this.bytes>>>29,e[15]=this.bytes<<3,this.hash()}};Ee.prototype.hash=function(){var e=this.h0,t=this.h1,n=this.h2,a=this.h3,r=this.h4,s=this.h5,i=this.h6,o=this.h7,c=this.blocks,l,d,p,f,m,y,b,T,v,I,E;for(l=16;l<64;++l)m=c[l-15],d=(m>>>7|m<<25)^(m>>>18|m<<14)^m>>>3,m=c[l-2],p=(m>>>17|m<<15)^(m>>>19|m<<13)^m>>>10,c[l]=c[l-16]+d+c[l-7]+p<<0;for(E=t&n,l=0;l<64;l+=4)this.first?(this.is224?(T=300032,m=c[0]-1413257819,o=m-150054599<<0,a=m+24177077<<0):(T=704751109,m=c[0]-210244248,o=m-1521486534<<0,a=m+143694565<<0),this.first=!1):(d=(e>>>2|e<<30)^(e>>>13|e<<19)^(e>>>22|e<<10),p=(r>>>6|r<<26)^(r>>>11|r<<21)^(r>>>25|r<<7),T=e&t,f=T^e&n^E,b=r&s^~r&i,m=o+p+b+Dt[l]+c[l],y=d+f,o=a+m<<0,a=m+y<<0),d=(a>>>2|a<<30)^(a>>>13|a<<19)^(a>>>22|a<<10),p=(o>>>6|o<<26)^(o>>>11|o<<21)^(o>>>25|o<<7),v=a&e,f=v^a&t^T,b=i&o^~i&r,m=s+p+b+Dt[l+1]+c[l+1],y=d+f,i=n+m<<0,n=m+y<<0,d=(n>>>2|n<<30)^(n>>>13|n<<19)^(n>>>22|n<<10),p=(i>>>6|i<<26)^(i>>>11|i<<21)^(i>>>25|i<<7),I=n&a,f=I^n&e^v,b=s&i^~s&o,m=r+p+b+Dt[l+2]+c[l+2],y=d+f,s=t+m<<0,t=m+y<<0,d=(t>>>2|t<<30)^(t>>>13|t<<19)^(t>>>22|t<<10),p=(s>>>6|s<<26)^(s>>>11|s<<21)^(s>>>25|s<<7),E=t&n,f=E^t&a^I,b=s&i^~s&o,m=r+p+b+Dt[l+3]+c[l+3],y=d+f,r=e+m<<0,e=m+y<<0,this.chromeBugWorkAround=!0;this.h0=this.h0+e<<0,this.h1=this.h1+t<<0,this.h2=this.h2+n<<0,this.h3=this.h3+a<<0,this.h4=this.h4+r<<0,this.h5=this.h5+s<<0,this.h6=this.h6+i<<0,this.h7=this.h7+o<<0};Ee.prototype.hex=function(){this.finalize();var e=this.h0,t=this.h1,n=this.h2,a=this.h3,r=this.h4,s=this.h5,i=this.h6,o=this.h7,c=A[e>>>28&15]+A[e>>>24&15]+A[e>>>20&15]+A[e>>>16&15]+A[e>>>12&15]+A[e>>>8&15]+A[e>>>4&15]+A[e&15]+A[t>>>28&15]+A[t>>>24&15]+A[t>>>20&15]+A[t>>>16&15]+A[t>>>12&15]+A[t>>>8&15]+A[t>>>4&15]+A[t&15]+A[n>>>28&15]+A[n>>>24&15]+A[n>>>20&15]+A[n>>>16&15]+A[n>>>12&15]+A[n>>>8&15]+A[n>>>4&15]+A[n&15]+A[a>>>28&15]+A[a>>>24&15]+A[a>>>20&15]+A[a>>>16&15]+A[a>>>12&15]+A[a>>>8&15]+A[a>>>4&15]+A[a&15]+A[r>>>28&15]+A[r>>>24&15]+A[r>>>20&15]+A[r>>>16&15]+A[r>>>12&15]+A[r>>>8&15]+A[r>>>4&15]+A[r&15]+A[s>>>28&15]+A[s>>>24&15]+A[s>>>20&15]+A[s>>>16&15]+A[s>>>12&15]+A[s>>>8&15]+A[s>>>4&15]+A[s&15]+A[i>>>28&15]+A[i>>>24&15]+A[i>>>20&15]+A[i>>>16&15]+A[i>>>12&15]+A[i>>>8&15]+A[i>>>4&15]+A[i&15];return this.is224||(c+=A[o>>>28&15]+A[o>>>24&15]+A[o>>>20&15]+A[o>>>16&15]+A[o>>>12&15]+A[o>>>8&15]+A[o>>>4&15]+A[o&15]),c};Ee.prototype.toString=Ee.prototype.hex;Ee.prototype.digest=function(){this.finalize();var e=this.h0,t=this.h1,n=this.h2,a=this.h3,r=this.h4,s=this.h5,i=this.h6,o=this.h7,c=[e>>>24&255,e>>>16&255,e>>>8&255,e&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255,n>>>24&255,n>>>16&255,n>>>8&255,n&255,a>>>24&255,a>>>16&255,a>>>8&255,a&255,r>>>24&255,r>>>16&255,r>>>8&255,r&255,s>>>24&255,s>>>16&255,s>>>8&255,s&255,i>>>24&255,i>>>16&255,i>>>8&255,i&255];return this.is224||c.push(o>>>24&255,o>>>16&255,o>>>8&255,o&255),c};Ee.prototype.array=Ee.prototype.digest;Ee.prototype.arrayBuffer=function(){this.finalize();var e=new ArrayBuffer(this.is224?28:32),t=new DataView(e);return t.setUint32(0,this.h0),t.setUint32(4,this.h1),t.setUint32(8,this.h2),t.setUint32(12,this.h3),t.setUint32(16,this.h4),t.setUint32(20,this.h5),t.setUint32(24,this.h6),this.is224||t.setUint32(28,this.h7),e};const ui=(...e)=>new Ee(!1,!0).update(e.join("")).hex();var yd={};F(yd,{sha256:()=>ui});var wd={};F(wd,{BaseCache:()=>hi,InMemoryCache:()=>pi,defaultHashKeyEncoder:()=>di,deserializeStoredGeneration:()=>bd,serializeGeneration:()=>vd});const di=(...e)=>ui(e.join("_"));function bd(e){return e.message!==void 0?{text:e.text,message:va(e.message)}:{text:e.text}}function vd(e){const t={text:e.text};return e.message!==void 0&&(t.message=e.message.toDict()),t}var hi=class{keyEncoder=di;makeDefaultKeyEncoder(e){this.keyEncoder=e}};const Td=new Map;var pi=class fi extends hi{cache;constructor(t){super(),this.cache=t??new Map}lookup(t,n){return Promise.resolve(this.cache.get(this.keyEncoder(t,n))??null)}async update(t,n,a){this.cache.set(this.keyEncoder(t,n),a)}static global(){return new fi(Td)}},Ed={};F(Ed,{encodingForModel:()=>La,getEncoding:()=>mi});const Ft={},Sd=new cn({});async function mi(e){return e in Ft||(Ft[e]=Sd.fetch(`https://tiktoken.pages.dev/js/${e}.json`).then(t=>t.json()).then(t=>new ji(t)).catch(t=>{throw delete Ft[e],t})),await Ft[e]}async function La(e){return mi($i(e))}var Ad={};F(Ad,{BaseLangChain:()=>_i,BaseLanguageModel:()=>yi,calculateMaxTokens:()=>Cd,getEmbeddingContextSize:()=>Id,getModelContextSize:()=>gi,getModelNameForTiktoken:()=>hn,isOpenAITool:()=>Od});const hn=e=>e.startsWith("gpt-3.5-turbo-16k")?"gpt-3.5-turbo-16k":e.startsWith("gpt-3.5-turbo-")?"gpt-3.5-turbo":e.startsWith("gpt-4-32k")?"gpt-4-32k":e.startsWith("gpt-4-")?"gpt-4":e.startsWith("gpt-4o")?"gpt-4o":e,Id=e=>{switch(e){case"text-embedding-ada-002":return 8191;default:return 2046}},gi=e=>{switch(hn(e)){case"gpt-3.5-turbo-16k":return 16384;case"gpt-3.5-turbo":return 4096;case"gpt-4-32k":return 32768;case"gpt-4":return 8192;case"text-davinci-003":return 4097;case"text-curie-001":return 2048;case"text-babbage-001":return 2048;case"text-ada-001":return 2048;case"code-davinci-002":return 8e3;case"code-cushman-001":return 2048;default:return 4097}};function Od(e){return typeof e!="object"||!e?!1:!!("type"in e&&e.type==="function"&&"function"in e&&typeof e.function=="object"&&e.function&&"name"in e.function&&"parameters"in e.function)}const Cd=async({prompt:e,modelName:t})=>{let n;try{n=(await La(hn(t))).encode(e).length}catch{console.warn("Failed to calculate number of tokens, falling back to approximate count"),n=Math.ceil(e.length/4)}return gi(t)-n},xd=()=>!1;var _i=class extends V{verbose;callbacks;tags;metadata;get lc_attributes(){return{callbacks:void 0,verbose:void 0}}constructor(e){super(e),this.verbose=e.verbose??xd(),this.callbacks=e.callbacks,this.tags=e.tags??[],this.metadata=e.metadata??{}}},yi=class extends _i{get callKeys(){return["stop","timeout","signal","tags","metadata","callbacks"]}caller;cache;constructor({callbacks:e,callbackManager:t,...n}){const{cache:a,...r}=n;super({callbacks:e??t,...r}),typeof a=="object"?this.cache=a:a?this.cache=pi.global():this.cache=void 0,this.caller=new cn(n??{})}_encoding;async getNumTokens(e){let t;typeof e=="string"?t=e:t=e.map(a=>typeof a=="string"?a:a.type==="text"&&"text"in a?a.text:"").join("");let n=Math.ceil(t.length/4);if(!this._encoding)try{this._encoding=await La("modelName"in this?hn(this.modelName):"gpt2")}catch(a){console.warn("Failed to calculate number of tokens, falling back to approximate count",a)}if(this._encoding)try{n=this._encoding.encode(t).length}catch(a){console.warn("Failed to calculate number of tokens, falling back to approximate count",a)}return n}static _convertInputToPromptValue(e){return typeof e=="string"?new ci(e):Array.isArray(e)?new li(e.map(wt)):e}_identifyingParams(){return{}}_getSerializedCacheKeyParametersForCall({config:e,...t}){const n={...this._identifyingParams(),...t,_type:this._llmType(),_model:this._modelType()};return Object.entries(n).filter(([s,i])=>i!==void 0).map(([s,i])=>`${s}:${JSON.stringify(i)}`).sort().join(",")}serialize(){return{...this._identifyingParams(),_type:this._llmType(),_model:this._modelType()}}static async deserialize(e){throw new Error("Use .toJSON() instead")}},en=class extends V{static lc_name(){return"RunnablePassthrough"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;func;constructor(e){super(e),e&&(this.func=e.func)}async invoke(e,t){const n=L(t);return this.func&&await this.func(e,n),this._callWithConfig(a=>Promise.resolve(a),e,n)}async*transform(e,t){const n=L(t);let a,r=!0;for await(const s of this._transformStreamWithConfig(e,i=>i,n))if(yield s,r)if(a===void 0)a=s;else try{a=Qe(a,s)}catch{a=void 0,r=!1}this.func&&a!==void 0&&await this.func(a,n)}static assign(e){return new Pa(new gt({steps:e}))}};const Nd=e=>e();function Mn(e){const t=e.constructor;return new t({...e,content:e.contentBlocks,response_metadata:{...e.response_metadata,output_version:"v1"}})}var kd={};F(kd,{BaseChatModel:()=>wi,SimpleChatModel:()=>Rd});function Ln(e){const t=[];for(const n of e){let a=n;if(Array.isArray(n.content))for(let r=0;r<n.content.length;r++){const s=n.content[r];(da(s)||ha(s))&&a===n&&(a=new n.constructor({...a,content:[...n.content.slice(0,r),Lr(s),...n.content.slice(r+1)]}))}t.push(a)}return t}var wi=class Ze extends yi{lc_namespace=["langchain","chat_models",this._llmType()];disableStreaming=!1;outputVersion;get callKeys(){return[...super.callKeys,"outputVersion"]}constructor(t){super(t),this.outputVersion=Nd(()=>{const n=t.outputVersion??Fe("LC_OUTPUT_VERSION");return n&&["v0","v1"].includes(n)?n:"v0"})}_separateRunnableConfigFromCallOptionsCompat(t){const[n,a]=super._separateRunnableConfigFromCallOptions(t);return a.signal=n.signal,[n,a]}async invoke(t,n){const a=Ze._convertInputToPromptValue(t);return(await this.generatePrompt([a],n,n?.callbacks)).generations[0][0].message}async*_streamResponseChunks(t,n,a){throw new Error("Not implemented.")}async*_streamIterator(t,n){if(this._streamResponseChunks===Ze.prototype._streamResponseChunks||this.disableStreaming)yield this.invoke(t,n);else{const r=Ze._convertInputToPromptValue(t).toChatMessages(),[s,i]=this._separateRunnableConfigFromCallOptionsCompat(n),o={...s.metadata,...this.getLsParams(i)},c=await Oe.configure(s.callbacks,this.callbacks,s.tags,this.tags,o,this.metadata,{verbose:this.verbose}),l={options:i,invocation_params:this?.invocationParams(i),batch_size:1},d=i.outputVersion??this.outputVersion,p=await c?.handleChatModelStart(this.toJSON(),[Ln(r)],s.runId,void 0,l,void 0,void 0,s.runName);let f,m;try{for await(const y of this._streamResponseChunks(r,i,p?.[0])){if(y.message.id==null){const b=p?.at(0)?.runId;b!=null&&y.message._updateId(`run-${b}`)}y.message.response_metadata={...y.generationInfo,...y.message.response_metadata},d==="v1"?yield Mn(y.message):yield y.message,f?f=f.concat(y):f=y,Dn(y.message)&&y.message.usage_metadata!==void 0&&(m={tokenUsage:{promptTokens:y.message.usage_metadata.input_tokens,completionTokens:y.message.usage_metadata.output_tokens,totalTokens:y.message.usage_metadata.total_tokens}})}}catch(y){throw await Promise.all((p??[]).map(b=>b?.handleLLMError(y))),y}await Promise.all((p??[]).map(y=>y?.handleLLMEnd({generations:[[f]],llmOutput:m})))}}getLsParams(t){const n=this.getName().startsWith("Chat")?this.getName().replace("Chat",""):this.getName();return{ls_model_type:"chat",ls_stop:t.stop,ls_provider:n}}async _generateUncached(t,n,a,r){const s=t.map(f=>f.map(wt));let i;if(r!==void 0&&r.length===s.length)i=r;else{const f={...a.metadata,...this.getLsParams(n)},m=await Oe.configure(a.callbacks,this.callbacks,a.tags,this.tags,f,this.metadata,{verbose:this.verbose}),y={options:n,invocation_params:this?.invocationParams(n),batch_size:1};i=await m?.handleChatModelStart(this.toJSON(),s.map(Ln),a.runId,void 0,y,void 0,void 0,a.runName)}const o=n.outputVersion??this.outputVersion,c=[],l=[];if(!!i?.[0].handlers.find(os)&&!this.disableStreaming&&s.length===1&&this._streamResponseChunks!==Ze.prototype._streamResponseChunks)try{const f=await this._streamResponseChunks(s[0],n,i?.[0]);let m,y;for await(const b of f){if(b.message.id==null){const T=i?.at(0)?.runId;T!=null&&b.message._updateId(`run-${T}`)}m===void 0?m=b:m=Qe(m,b),Dn(b.message)&&b.message.usage_metadata!==void 0&&(y={tokenUsage:{promptTokens:b.message.usage_metadata.input_tokens,completionTokens:b.message.usage_metadata.output_tokens,totalTokens:b.message.usage_metadata.total_tokens}})}if(m===void 0)throw new Error("Received empty response from chat model call.");c.push([m]),await i?.[0].handleLLMEnd({generations:c,llmOutput:y})}catch(f){throw await i?.[0].handleLLMError(f),f}else{const f=await Promise.allSettled(s.map(async(m,y)=>{const b=await this._generate(m,{...n,promptIndex:y},i?.[y]);if(o==="v1")for(const T of b.generations)T.message=Mn(T.message);return b}));await Promise.all(f.map(async(m,y)=>{if(m.status==="fulfilled"){const b=m.value;for(const T of b.generations){if(T.message.id==null){const v=i?.at(0)?.runId;v!=null&&T.message._updateId(`run-${v}`)}T.message.response_metadata={...T.generationInfo,...T.message.response_metadata}}return b.generations.length===1&&(b.generations[0].message.response_metadata={...b.llmOutput,...b.generations[0].message.response_metadata}),c[y]=b.generations,l[y]=b.llmOutput,i?.[y]?.handleLLMEnd({generations:[b.generations],llmOutput:b.llmOutput})}else return await i?.[y]?.handleLLMError(m.reason),Promise.reject(m.reason)}))}const p={generations:c,llmOutput:l.length?this._combineLLMOutput?.(...l):void 0};return Object.defineProperty(p,Xn,{value:i?{runIds:i?.map(f=>f.runId)}:void 0,configurable:!0}),p}async _generateCached({messages:t,cache:n,llmStringKey:a,parsedOptions:r,handledOptions:s}){const i=t.map(v=>v.map(wt)),o={...s.metadata,...this.getLsParams(r)},c=await Oe.configure(s.callbacks,this.callbacks,s.tags,this.tags,o,this.metadata,{verbose:this.verbose}),l={options:r,invocation_params:this?.invocationParams(r),batch_size:1},d=await c?.handleChatModelStart(this.toJSON(),i.map(Ln),s.runId,void 0,l,void 0,void 0,s.runName),p=[],m=(await Promise.allSettled(i.map(async(v,I)=>{const E=Ze._convertInputToPromptValue(v).toString(),x=await n.lookup(E,a);return x==null&&p.push(I),x}))).map((v,I)=>({result:v,runManager:d?.[I]})).filter(({result:v})=>v.status==="fulfilled"&&v.value!=null||v.status==="rejected"),y=r.outputVersion??this.outputVersion,b=[];await Promise.all(m.map(async({result:v,runManager:I},E)=>{if(v.status==="fulfilled"){const x=v.value;return b[E]=x.map(N=>("message"in N&&Re(N.message)&&Kr(N.message)&&(N.message.usage_metadata={input_tokens:0,output_tokens:0,total_tokens:0},y==="v1"&&(N.message=Mn(N.message))),N.generationInfo={...N.generationInfo,tokenUsage:{}},N)),x.length&&await I?.handleLLMNewToken(x[0].text),I?.handleLLMEnd({generations:[x]},void 0,void 0,void 0,{cached:!0})}else return await I?.handleLLMError(v.reason,void 0,void 0,void 0,{cached:!0}),Promise.reject(v.reason)}));const T={generations:b,missingPromptIndices:p,startedRunManagers:d};return Object.defineProperty(T,Xn,{value:d?{runIds:d?.map(v=>v.runId)}:void 0,configurable:!0}),T}async generate(t,n,a){let r;Array.isArray(n)?r={stop:n}:r=n;const s=t.map(y=>y.map(wt)),[i,o]=this._separateRunnableConfigFromCallOptionsCompat(r);if(i.callbacks=i.callbacks??a,!this.cache)return this._generateUncached(s,o,i);const{cache:c}=this,l=this._getSerializedCacheKeyParametersForCall(o),{generations:d,missingPromptIndices:p,startedRunManagers:f}=await this._generateCached({messages:s,cache:c,llmStringKey:l,parsedOptions:o,handledOptions:i});let m={};if(p.length>0){const y=await this._generateUncached(p.map(b=>s[b]),o,i,f!==void 0?p.map(b=>f?.[b]):void 0);await Promise.all(y.generations.map(async(b,T)=>{const v=p[T];d[v]=b;const I=Ze._convertInputToPromptValue(s[v]).toString();return c.update(I,l,b)})),m=y.llmOutput??{}}return{generations:d,llmOutput:m}}invocationParams(t){return{}}_modelType(){return"base_chat_model"}async generatePrompt(t,n,a){const r=t.map(s=>s.toChatMessages());return this.generate(r,n,a)}withStructuredOutput(t,n){if(typeof this.bindTools!="function")throw new Error('Chat model must implement ".bindTools()" to use withStructuredOutput.');if(n?.strict)throw new Error('"strict" mode is not supported for this model by default.');const a=t,r=n?.name,s=xa(a)??"A function available to call.",i=n?.method,o=n?.includeRaw;if(i==="jsonMode")throw new Error('Base withStructuredOutput implementation only supports "functionCalling" as a method.');let c=r??"extract",l;kt(a)?l=[{type:"function",function:{name:c,description:s,parameters:mt(a)}}]:("name"in a&&(c=a.name),l=[{type:"function",function:{name:c,description:s,parameters:a}}]);const d=this.bindTools(l),p=Ge.from(b=>{if(!tt.isInstance(b))throw new Error("Input is not an AIMessageChunk.");if(!b.tool_calls||b.tool_calls.length===0)throw new Error("No tool calls found in the response.");const T=b.tool_calls.find(v=>v.name===c);if(!T)throw new Error(`No tool call found with name ${c}.`);return T.args});if(!o)return d.pipe(p).withConfig({runName:"StructuredOutput"});const f=en.assign({parsed:(b,T)=>p.invoke(b.raw,T)}),m=en.assign({parsed:()=>null}),y=f.withFallbacks({fallbacks:[m]});return un.from([{raw:d},y]).withConfig({runName:"StructuredOutputRunnable"})}},Rd=class extends wi{async _generate(e,t,n){const a=await this._call(e,t,n),r=new Be(a);if(typeof r.content!="string")throw new Error("Cannot generate with a simple chat model when output is not a string.");return{generations:[{text:r.content,message:r}]}}},Pd=class extends V{static lc_name(){return"RouterRunnable"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;runnables;constructor(e){super(e),this.runnables=e.runnables}async invoke(e,t){const{key:n,input:a}=e,r=this.runnables[n];if(r===void 0)throw new Error(`No runnable associated with key "${n}".`);return r.invoke(a,L(t))}async batch(e,t,n){const a=e.map(p=>p.key),r=e.map(p=>p.input);if(a.find(p=>this.runnables[p]===void 0)!==void 0)throw new Error("One or more keys do not have a corresponding runnable.");const i=a.map(p=>this.runnables[p]),o=this._getOptionsList(t??{},e.length),c=o[0]?.maxConcurrency??n?.maxConcurrency,l=c&&c>0?c:e.length,d=[];for(let p=0;p<r.length;p+=l){const f=r.slice(p,p+l).map((y,b)=>i[b].invoke(y,o[b])),m=await Promise.all(f);d.push(m)}return d.flat()}async stream(e,t){const{key:n,input:a}=e,r=this.runnables[n];if(r===void 0)throw new Error(`No runnable associated with key "${n}".`);return r.stream(a,t)}},Md=class extends V{static lc_name(){return"RunnableBranch"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;default;branches;constructor(e){super(e),this.branches=e.branches,this.default=e.default}static from(e){if(e.length<1)throw new Error("RunnableBranch requires at least one branch");const n=e.slice(0,-1).map(([r,s])=>[ve(r),ve(s)]),a=ve(e[e.length-1]);return new this({branches:n,default:a})}async _invoke(e,t,n){let a;for(let r=0;r<this.branches.length;r+=1){const[s,i]=this.branches[r];if(await s.invoke(e,H(t,{callbacks:n?.getChild(`condition:${r+1}`)}))){a=await i.invoke(e,H(t,{callbacks:n?.getChild(`branch:${r+1}`)}));break}}return a||(a=await this.default.invoke(e,H(t,{callbacks:n?.getChild("branch:default")}))),a}async invoke(e,t={}){return this._callWithConfig(this._invoke,e,t)}async*_streamIterator(e,t){const a=await(await pe(t))?.handleChainStart(this.toJSON(),K(e,"input"),t?.runId,void 0,void 0,void 0,t?.runName);let r,s=!0,i;try{for(let o=0;o<this.branches.length;o+=1){const[c,l]=this.branches[o];if(await c.invoke(e,H(t,{callbacks:a?.getChild(`condition:${o+1}`)}))){i=await l.stream(e,H(t,{callbacks:a?.getChild(`branch:${o+1}`)}));for await(const p of i)if(yield p,s)if(r===void 0)r=p;else try{r=Qe(r,p)}catch{r=void 0,s=!1}break}}if(i===void 0){i=await this.default.stream(e,H(t,{callbacks:a?.getChild("branch:default")}));for await(const o of i)if(yield o,s)if(r===void 0)r=o;else try{r=Qe(r,o)}catch{r=void 0,s=!1}}}catch(o){throw await a?.handleChainError(o),o}await a?.handleChainEnd(r??{})}},Ld=class extends ht{runnable;inputMessagesKey;outputMessagesKey;historyMessagesKey;getMessageHistory;constructor(e){let t=Ge.from((s,i)=>this._enterHistory(s,i??{})).withConfig({runName:"loadHistory"});const n=e.historyMessagesKey??e.inputMessagesKey;n&&(t=en.assign({[n]:t}).withConfig({runName:"insertHistory"}));const a=t.pipe(e.runnable.withListeners({onEnd:(s,i)=>this._exitHistory(s,i??{})})).withConfig({runName:"RunnableWithMessageHistory"}),r=e.config??{};super({...e,config:r,bound:a}),this.runnable=e.runnable,this.getMessageHistory=e.getMessageHistory,this.inputMessagesKey=e.inputMessagesKey,this.outputMessagesKey=e.outputMessagesKey,this.historyMessagesKey=e.historyMessagesKey}_getInputMessages(e){let t;if(typeof e=="object"&&!Array.isArray(e)&&!Re(e)){let n;this.inputMessagesKey?n=this.inputMessagesKey:Object.keys(e).length===1?n=Object.keys(e)[0]:n="input",Array.isArray(e[n])&&Array.isArray(e[n][0])?t=e[n][0]:t=e[n]}else t=e;if(typeof t=="string")return[new $e(t)];if(Array.isArray(t))return t;if(Re(t))return[t];throw new Error(`Expected a string, BaseMessage, or array of BaseMessages.
77
+ `),t[t.length-1]])}const cd=["tool_call","tool_call_chunk","invalid_tool_call","server_tool_call","server_tool_call_chunk","server_tool_call_result"],ld=["image","video","audio","text-plain","file"],ud=["text","reasoning",...cd,...ld];var dd={};F(dd,{AIMessage:()=>Be,AIMessageChunk:()=>tt,BaseMessage:()=>Le,BaseMessageChunk:()=>et,ChatMessage:()=>Ct,ChatMessageChunk:()=>nn,FunctionMessage:()=>an,FunctionMessageChunk:()=>rn,HumanMessage:()=>$e,HumanMessageChunk:()=>sn,KNOWN_BLOCK_TYPES:()=>ud,RemoveMessage:()=>Gt,SystemMessage:()=>ze,SystemMessageChunk:()=>ut,ToolMessage:()=>pt,ToolMessageChunk:()=>tn,_isMessageFieldWithRole:()=>zr,_mergeDicts:()=>ee,_mergeLists:()=>Ot,_mergeObj:()=>Br,_mergeStatus:()=>Ur,coerceMessageLikeToMessage:()=>wt,convertToChunk:()=>Vt,convertToOpenAIImageBlock:()=>Lr,convertToProviderContentBlock:()=>Bi,defaultTextSplitter:()=>ni,defaultToolCallParser:()=>_a,filterMessages:()=>ad,getBufferString:()=>ba,iife:()=>Co,isAIMessage:()=>Kr,isAIMessageChunk:()=>Dn,isBase64ContentBlock:()=>ha,isBaseMessage:()=>Re,isBaseMessageChunk:()=>ga,isChatMessage:()=>wo,isChatMessageChunk:()=>bo,isDataContentBlock:()=>Ue,isDirectToolOutput:()=>Zr,isFunctionMessage:()=>vo,isFunctionMessageChunk:()=>To,isHumanMessage:()=>Eo,isHumanMessageChunk:()=>So,isIDContentBlock:()=>Mr,isMessage:()=>$r,isOpenAIToolCallArray:()=>co,isPlainTextContentBlock:()=>Fi,isSystemMessage:()=>Ao,isSystemMessageChunk:()=>Io,isToolMessage:()=>qr,isToolMessageChunk:()=>Jr,isURLContentBlock:()=>da,mapChatMessagesToStoredMessages:()=>Po,mapStoredMessageToChatMessage:()=>va,mapStoredMessagesToChatMessages:()=>Ro,mergeContent:()=>Xe,mergeMessageRuns:()=>rd,mergeResponseMetadata:()=>Hr,mergeUsageMetadata:()=>Vr,parseBase64DataUrl:()=>$n,parseMimeType:()=>Ui,trimMessages:()=>sd});var hd={};F(hd,{extendInteropZodObject:()=>Yl,getInteropZodDefaultGetter:()=>Xl,getInteropZodObjectShape:()=>ta,getSchemaDescription:()=>xa,interopParse:()=>Jl,interopParseAsync:()=>Ca,interopSafeParse:()=>ql,interopSafeParseAsync:()=>Zl,interopZodObjectMakeFieldsOptional:()=>nu,interopZodObjectPartial:()=>Ql,interopZodObjectPassthrough:()=>na,interopZodObjectStrict:()=>Yt,interopZodTransformInputSchema:()=>ct,isInteropZodLiteral:()=>Vl,isInteropZodObject:()=>Kl,isInteropZodSchema:()=>kt,isShapelessZodSchema:()=>Wl,isSimpleStringZodSchema:()=>Us,isZodArrayV4:()=>ln,isZodLiteralV3:()=>Ds,isZodLiteralV4:()=>Fs,isZodObjectV3:()=>Na,isZodObjectV4:()=>Ce,isZodSchema:()=>Gl,isZodSchemaV3:()=>Y,isZodSchemaV4:()=>Z});function ai(e){return e!==void 0&&Array.isArray(e.lc_namespace)}function ri(e){return e!==void 0&&V.isRunnable(e)&&"lc_name"in e.constructor&&typeof e.constructor.lc_name=="function"&&e.constructor.lc_name()==="RunnableToolLike"}function si(e){return!!e&&typeof e=="object"&&"name"in e&&"schema"in e&&(kt(e.schema)||e.schema!=null&&typeof e.schema=="object"&&"type"in e.schema&&typeof e.schema.type=="string"&&["null","boolean","object","array","number","string"].includes(e.schema.type))}function ii(e){return si(e)||ri(e)||ai(e)}var pd={};F(pd,{convertToOpenAIFunction:()=>oi,convertToOpenAITool:()=>fd,isLangChainTool:()=>ii,isRunnableToolLike:()=>ri,isStructuredTool:()=>ai,isStructuredToolParams:()=>si});function oi(e,t){const n=typeof t=="number"?void 0:t;return{name:e.name,description:e.description,parameters:mt(e.schema),...n?.strict!==void 0?{strict:n.strict}:{}}}function fd(e,t){const n=typeof t=="number"?void 0:t;let a;return ii(e)?a={type:"function",function:oi(e)}:a=e,n?.strict!==void 0&&(a.function.strict=n.strict),a}var md={};F(md,{BasePromptValue:()=>dn,ChatPromptValue:()=>li,ImagePromptValue:()=>gd,StringPromptValue:()=>ci});var dn=class extends lt{},ci=class extends dn{static lc_name(){return"StringPromptValue"}lc_namespace=["langchain_core","prompt_values"];lc_serializable=!0;value;constructor(e){super({value:e}),this.value=e}toString(){return this.value}toChatMessages(){return[new $e(this.value)]}},li=class extends dn{lc_namespace=["langchain_core","prompt_values"];lc_serializable=!0;static lc_name(){return"ChatPromptValue"}messages;constructor(e){Array.isArray(e)&&(e={messages:e}),super(e),this.messages=e.messages}toString(){return ba(this.messages)}toChatMessages(){return this.messages}},gd=class extends dn{lc_namespace=["langchain_core","prompt_values"];lc_serializable=!0;static lc_name(){return"ImagePromptValue"}imageUrl;value;constructor(e){"imageUrl"in e||(e={imageUrl:e}),super(e),this.imageUrl=e.imageUrl}toString(){return this.imageUrl.url}toChatMessages(){return[new $e({content:[{type:"image_url",image_url:{detail:this.imageUrl.detail,url:this.imageUrl.url}}]})]}},A="0123456789abcdef".split(""),_d=[-2147483648,8388608,32768,128],ye=[24,16,8,0],Dt=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],Q=[];function Ee(e,t){t?(Q[0]=Q[16]=Q[1]=Q[2]=Q[3]=Q[4]=Q[5]=Q[6]=Q[7]=Q[8]=Q[9]=Q[10]=Q[11]=Q[12]=Q[13]=Q[14]=Q[15]=0,this.blocks=Q):this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],e?(this.h0=3238371032,this.h1=914150663,this.h2=812702999,this.h3=4144912697,this.h4=4290775857,this.h5=1750603025,this.h6=1694076839,this.h7=3204075428):(this.h0=1779033703,this.h1=3144134277,this.h2=1013904242,this.h3=2773480762,this.h4=1359893119,this.h5=2600822924,this.h6=528734635,this.h7=1541459225),this.block=this.start=this.bytes=this.hBytes=0,this.finalized=this.hashed=!1,this.first=!0,this.is224=e}Ee.prototype.update=function(e){if(!this.finalized){var t,n=typeof e;if(n!=="string"){if(n==="object"){if(e===null)throw new Error(ERROR);if(ARRAY_BUFFER&&e.constructor===ArrayBuffer)e=new Uint8Array(e);else if(!Array.isArray(e)&&(!ARRAY_BUFFER||!ArrayBuffer.isView(e)))throw new Error(ERROR)}else throw new Error(ERROR);t=!0}for(var a,r=0,s,i=e.length,o=this.blocks;r<i;){if(this.hashed&&(this.hashed=!1,o[0]=this.block,this.block=o[16]=o[1]=o[2]=o[3]=o[4]=o[5]=o[6]=o[7]=o[8]=o[9]=o[10]=o[11]=o[12]=o[13]=o[14]=o[15]=0),t)for(s=this.start;r<i&&s<64;++r)o[s>>>2]|=e[r]<<ye[s++&3];else for(s=this.start;r<i&&s<64;++r)a=e.charCodeAt(r),a<128?o[s>>>2]|=a<<ye[s++&3]:a<2048?(o[s>>>2]|=(192|a>>>6)<<ye[s++&3],o[s>>>2]|=(128|a&63)<<ye[s++&3]):a<55296||a>=57344?(o[s>>>2]|=(224|a>>>12)<<ye[s++&3],o[s>>>2]|=(128|a>>>6&63)<<ye[s++&3],o[s>>>2]|=(128|a&63)<<ye[s++&3]):(a=65536+((a&1023)<<10|e.charCodeAt(++r)&1023),o[s>>>2]|=(240|a>>>18)<<ye[s++&3],o[s>>>2]|=(128|a>>>12&63)<<ye[s++&3],o[s>>>2]|=(128|a>>>6&63)<<ye[s++&3],o[s>>>2]|=(128|a&63)<<ye[s++&3]);this.lastByteIndex=s,this.bytes+=s-this.start,s>=64?(this.block=o[16],this.start=s-64,this.hash(),this.hashed=!0):this.start=s}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296<<0,this.bytes=this.bytes%4294967296),this}};Ee.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var e=this.blocks,t=this.lastByteIndex;e[16]=this.block,e[t>>>2]|=_d[t&3],this.block=e[16],t>=56&&(this.hashed||this.hash(),e[0]=this.block,e[16]=e[1]=e[2]=e[3]=e[4]=e[5]=e[6]=e[7]=e[8]=e[9]=e[10]=e[11]=e[12]=e[13]=e[14]=e[15]=0),e[14]=this.hBytes<<3|this.bytes>>>29,e[15]=this.bytes<<3,this.hash()}};Ee.prototype.hash=function(){var e=this.h0,t=this.h1,n=this.h2,a=this.h3,r=this.h4,s=this.h5,i=this.h6,o=this.h7,c=this.blocks,l,d,p,f,m,y,b,T,v,I,E;for(l=16;l<64;++l)m=c[l-15],d=(m>>>7|m<<25)^(m>>>18|m<<14)^m>>>3,m=c[l-2],p=(m>>>17|m<<15)^(m>>>19|m<<13)^m>>>10,c[l]=c[l-16]+d+c[l-7]+p<<0;for(E=t&n,l=0;l<64;l+=4)this.first?(this.is224?(T=300032,m=c[0]-1413257819,o=m-150054599<<0,a=m+24177077<<0):(T=704751109,m=c[0]-210244248,o=m-1521486534<<0,a=m+143694565<<0),this.first=!1):(d=(e>>>2|e<<30)^(e>>>13|e<<19)^(e>>>22|e<<10),p=(r>>>6|r<<26)^(r>>>11|r<<21)^(r>>>25|r<<7),T=e&t,f=T^e&n^E,b=r&s^~r&i,m=o+p+b+Dt[l]+c[l],y=d+f,o=a+m<<0,a=m+y<<0),d=(a>>>2|a<<30)^(a>>>13|a<<19)^(a>>>22|a<<10),p=(o>>>6|o<<26)^(o>>>11|o<<21)^(o>>>25|o<<7),v=a&e,f=v^a&t^T,b=i&o^~i&r,m=s+p+b+Dt[l+1]+c[l+1],y=d+f,i=n+m<<0,n=m+y<<0,d=(n>>>2|n<<30)^(n>>>13|n<<19)^(n>>>22|n<<10),p=(i>>>6|i<<26)^(i>>>11|i<<21)^(i>>>25|i<<7),I=n&a,f=I^n&e^v,b=s&i^~s&o,m=r+p+b+Dt[l+2]+c[l+2],y=d+f,s=t+m<<0,t=m+y<<0,d=(t>>>2|t<<30)^(t>>>13|t<<19)^(t>>>22|t<<10),p=(s>>>6|s<<26)^(s>>>11|s<<21)^(s>>>25|s<<7),E=t&n,f=E^t&a^I,b=s&i^~s&o,m=r+p+b+Dt[l+3]+c[l+3],y=d+f,r=e+m<<0,e=m+y<<0,this.chromeBugWorkAround=!0;this.h0=this.h0+e<<0,this.h1=this.h1+t<<0,this.h2=this.h2+n<<0,this.h3=this.h3+a<<0,this.h4=this.h4+r<<0,this.h5=this.h5+s<<0,this.h6=this.h6+i<<0,this.h7=this.h7+o<<0};Ee.prototype.hex=function(){this.finalize();var e=this.h0,t=this.h1,n=this.h2,a=this.h3,r=this.h4,s=this.h5,i=this.h6,o=this.h7,c=A[e>>>28&15]+A[e>>>24&15]+A[e>>>20&15]+A[e>>>16&15]+A[e>>>12&15]+A[e>>>8&15]+A[e>>>4&15]+A[e&15]+A[t>>>28&15]+A[t>>>24&15]+A[t>>>20&15]+A[t>>>16&15]+A[t>>>12&15]+A[t>>>8&15]+A[t>>>4&15]+A[t&15]+A[n>>>28&15]+A[n>>>24&15]+A[n>>>20&15]+A[n>>>16&15]+A[n>>>12&15]+A[n>>>8&15]+A[n>>>4&15]+A[n&15]+A[a>>>28&15]+A[a>>>24&15]+A[a>>>20&15]+A[a>>>16&15]+A[a>>>12&15]+A[a>>>8&15]+A[a>>>4&15]+A[a&15]+A[r>>>28&15]+A[r>>>24&15]+A[r>>>20&15]+A[r>>>16&15]+A[r>>>12&15]+A[r>>>8&15]+A[r>>>4&15]+A[r&15]+A[s>>>28&15]+A[s>>>24&15]+A[s>>>20&15]+A[s>>>16&15]+A[s>>>12&15]+A[s>>>8&15]+A[s>>>4&15]+A[s&15]+A[i>>>28&15]+A[i>>>24&15]+A[i>>>20&15]+A[i>>>16&15]+A[i>>>12&15]+A[i>>>8&15]+A[i>>>4&15]+A[i&15];return this.is224||(c+=A[o>>>28&15]+A[o>>>24&15]+A[o>>>20&15]+A[o>>>16&15]+A[o>>>12&15]+A[o>>>8&15]+A[o>>>4&15]+A[o&15]),c};Ee.prototype.toString=Ee.prototype.hex;Ee.prototype.digest=function(){this.finalize();var e=this.h0,t=this.h1,n=this.h2,a=this.h3,r=this.h4,s=this.h5,i=this.h6,o=this.h7,c=[e>>>24&255,e>>>16&255,e>>>8&255,e&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255,n>>>24&255,n>>>16&255,n>>>8&255,n&255,a>>>24&255,a>>>16&255,a>>>8&255,a&255,r>>>24&255,r>>>16&255,r>>>8&255,r&255,s>>>24&255,s>>>16&255,s>>>8&255,s&255,i>>>24&255,i>>>16&255,i>>>8&255,i&255];return this.is224||c.push(o>>>24&255,o>>>16&255,o>>>8&255,o&255),c};Ee.prototype.array=Ee.prototype.digest;Ee.prototype.arrayBuffer=function(){this.finalize();var e=new ArrayBuffer(this.is224?28:32),t=new DataView(e);return t.setUint32(0,this.h0),t.setUint32(4,this.h1),t.setUint32(8,this.h2),t.setUint32(12,this.h3),t.setUint32(16,this.h4),t.setUint32(20,this.h5),t.setUint32(24,this.h6),this.is224||t.setUint32(28,this.h7),e};const ui=(...e)=>new Ee(!1,!0).update(e.join("")).hex();var yd={};F(yd,{sha256:()=>ui});var wd={};F(wd,{BaseCache:()=>hi,InMemoryCache:()=>pi,defaultHashKeyEncoder:()=>di,deserializeStoredGeneration:()=>bd,serializeGeneration:()=>vd});const di=(...e)=>ui(e.join("_"));function bd(e){return e.message!==void 0?{text:e.text,message:va(e.message)}:{text:e.text}}function vd(e){const t={text:e.text};return e.message!==void 0&&(t.message=e.message.toDict()),t}var hi=class{keyEncoder=di;makeDefaultKeyEncoder(e){this.keyEncoder=e}};const Td=new Map;var pi=class fi extends hi{cache;constructor(t){super(),this.cache=t??new Map}lookup(t,n){return Promise.resolve(this.cache.get(this.keyEncoder(t,n))??null)}async update(t,n,a){this.cache.set(this.keyEncoder(t,n),a)}static global(){return new fi(Td)}},Ed={};F(Ed,{encodingForModel:()=>La,getEncoding:()=>mi});const Ft={},Sd=new cn({});async function mi(e){return e in Ft||(Ft[e]=Sd.fetch(`https://tiktoken.pages.dev/js/${e}.json`).then(t=>t.json()).then(t=>new ji(t)).catch(t=>{throw delete Ft[e],t})),await Ft[e]}async function La(e){return mi($i(e))}var Ad={};F(Ad,{BaseLangChain:()=>_i,BaseLanguageModel:()=>yi,calculateMaxTokens:()=>Cd,getEmbeddingContextSize:()=>Id,getModelContextSize:()=>gi,getModelNameForTiktoken:()=>hn,isOpenAITool:()=>Od});const hn=e=>e.startsWith("gpt-5")?"gpt-5":e.startsWith("gpt-3.5-turbo-16k")?"gpt-3.5-turbo-16k":e.startsWith("gpt-3.5-turbo-")?"gpt-3.5-turbo":e.startsWith("gpt-4-32k")?"gpt-4-32k":e.startsWith("gpt-4-")?"gpt-4":e.startsWith("gpt-4o")?"gpt-4o":e,Id=e=>{switch(e){case"text-embedding-ada-002":return 8191;default:return 2046}},gi=e=>{switch(hn(e)){case"gpt-5":case"gpt-5-turbo":case"gpt-5-turbo-preview":return 4e5;case"gpt-4o":case"gpt-4o-mini":case"gpt-4o-2024-05-13":case"gpt-4o-2024-08-06":return 128e3;case"gpt-4-turbo":case"gpt-4-turbo-preview":case"gpt-4-turbo-2024-04-09":case"gpt-4-0125-preview":case"gpt-4-1106-preview":return 128e3;case"gpt-4-32k":case"gpt-4-32k-0314":case"gpt-4-32k-0613":return 32768;case"gpt-4":case"gpt-4-0314":case"gpt-4-0613":return 8192;case"gpt-3.5-turbo-16k":case"gpt-3.5-turbo-16k-0613":return 16384;case"gpt-3.5-turbo":case"gpt-3.5-turbo-0301":case"gpt-3.5-turbo-0613":case"gpt-3.5-turbo-1106":case"gpt-3.5-turbo-0125":return 4096;case"text-davinci-003":case"text-davinci-002":return 4097;case"text-davinci-001":return 2049;case"text-curie-001":case"text-babbage-001":case"text-ada-001":return 2048;case"code-davinci-002":case"code-davinci-001":return 8e3;case"code-cushman-001":return 2048;case"claude-3-5-sonnet-20241022":case"claude-3-5-sonnet-20240620":case"claude-3-opus-20240229":case"claude-3-sonnet-20240229":case"claude-3-haiku-20240307":case"claude-2.1":return 2e5;case"claude-2.0":case"claude-instant-1.2":return 1e5;case"gemini-1.5-pro":case"gemini-1.5-pro-latest":case"gemini-1.5-flash":case"gemini-1.5-flash-latest":return 1e6;case"gemini-pro":case"gemini-pro-vision":return 32768;default:return 4097}};function Od(e){return typeof e!="object"||!e?!1:!!("type"in e&&e.type==="function"&&"function"in e&&typeof e.function=="object"&&e.function&&"name"in e.function&&"parameters"in e.function)}const Cd=async({prompt:e,modelName:t})=>{let n;try{n=(await La(hn(t))).encode(e).length}catch{console.warn("Failed to calculate number of tokens, falling back to approximate count"),n=Math.ceil(e.length/4)}return gi(t)-n},xd=()=>!1;var _i=class extends V{verbose;callbacks;tags;metadata;get lc_attributes(){return{callbacks:void 0,verbose:void 0}}constructor(e){super(e),this.verbose=e.verbose??xd(),this.callbacks=e.callbacks,this.tags=e.tags??[],this.metadata=e.metadata??{}}},yi=class extends _i{get callKeys(){return["stop","timeout","signal","tags","metadata","callbacks"]}caller;cache;constructor({callbacks:e,callbackManager:t,...n}){const{cache:a,...r}=n;super({callbacks:e??t,...r}),typeof a=="object"?this.cache=a:a?this.cache=pi.global():this.cache=void 0,this.caller=new cn(n??{})}_encoding;async getNumTokens(e){let t;typeof e=="string"?t=e:t=e.map(a=>typeof a=="string"?a:a.type==="text"&&"text"in a?a.text:"").join("");let n=Math.ceil(t.length/4);if(!this._encoding)try{this._encoding=await La("modelName"in this?hn(this.modelName):"gpt2")}catch(a){console.warn("Failed to calculate number of tokens, falling back to approximate count",a)}if(this._encoding)try{n=this._encoding.encode(t).length}catch(a){console.warn("Failed to calculate number of tokens, falling back to approximate count",a)}return n}static _convertInputToPromptValue(e){return typeof e=="string"?new ci(e):Array.isArray(e)?new li(e.map(wt)):e}_identifyingParams(){return{}}_getSerializedCacheKeyParametersForCall({config:e,...t}){const n={...this._identifyingParams(),...t,_type:this._llmType(),_model:this._modelType()};return Object.entries(n).filter(([s,i])=>i!==void 0).map(([s,i])=>`${s}:${JSON.stringify(i)}`).sort().join(",")}serialize(){return{...this._identifyingParams(),_type:this._llmType(),_model:this._modelType()}}static async deserialize(e){throw new Error("Use .toJSON() instead")}},en=class extends V{static lc_name(){return"RunnablePassthrough"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;func;constructor(e){super(e),e&&(this.func=e.func)}async invoke(e,t){const n=L(t);return this.func&&await this.func(e,n),this._callWithConfig(a=>Promise.resolve(a),e,n)}async*transform(e,t){const n=L(t);let a,r=!0;for await(const s of this._transformStreamWithConfig(e,i=>i,n))if(yield s,r)if(a===void 0)a=s;else try{a=Qe(a,s)}catch{a=void 0,r=!1}this.func&&a!==void 0&&await this.func(a,n)}static assign(e){return new Pa(new gt({steps:e}))}};const Nd=e=>e();function Mn(e){const t=e.constructor;return new t({...e,content:e.contentBlocks,response_metadata:{...e.response_metadata,output_version:"v1"}})}var kd={};F(kd,{BaseChatModel:()=>wi,SimpleChatModel:()=>Rd});function Ln(e){const t=[];for(const n of e){let a=n;if(Array.isArray(n.content))for(let r=0;r<n.content.length;r++){const s=n.content[r];(da(s)||ha(s))&&a===n&&(a=new n.constructor({...a,content:[...n.content.slice(0,r),Lr(s),...n.content.slice(r+1)]}))}t.push(a)}return t}var wi=class Ze extends yi{lc_namespace=["langchain","chat_models",this._llmType()];disableStreaming=!1;outputVersion;get callKeys(){return[...super.callKeys,"outputVersion"]}constructor(t){super(t),this.outputVersion=Nd(()=>{const n=t.outputVersion??Fe("LC_OUTPUT_VERSION");return n&&["v0","v1"].includes(n)?n:"v0"})}_separateRunnableConfigFromCallOptionsCompat(t){const[n,a]=super._separateRunnableConfigFromCallOptions(t);return a.signal=n.signal,[n,a]}async invoke(t,n){const a=Ze._convertInputToPromptValue(t);return(await this.generatePrompt([a],n,n?.callbacks)).generations[0][0].message}async*_streamResponseChunks(t,n,a){throw new Error("Not implemented.")}async*_streamIterator(t,n){if(this._streamResponseChunks===Ze.prototype._streamResponseChunks||this.disableStreaming)yield this.invoke(t,n);else{const r=Ze._convertInputToPromptValue(t).toChatMessages(),[s,i]=this._separateRunnableConfigFromCallOptionsCompat(n),o={...s.metadata,...this.getLsParams(i)},c=await Oe.configure(s.callbacks,this.callbacks,s.tags,this.tags,o,this.metadata,{verbose:this.verbose}),l={options:i,invocation_params:this?.invocationParams(i),batch_size:1},d=i.outputVersion??this.outputVersion,p=await c?.handleChatModelStart(this.toJSON(),[Ln(r)],s.runId,void 0,l,void 0,void 0,s.runName);let f,m;try{for await(const y of this._streamResponseChunks(r,i,p?.[0])){if(y.message.id==null){const b=p?.at(0)?.runId;b!=null&&y.message._updateId(`run-${b}`)}y.message.response_metadata={...y.generationInfo,...y.message.response_metadata},d==="v1"?yield Mn(y.message):yield y.message,f?f=f.concat(y):f=y,Dn(y.message)&&y.message.usage_metadata!==void 0&&(m={tokenUsage:{promptTokens:y.message.usage_metadata.input_tokens,completionTokens:y.message.usage_metadata.output_tokens,totalTokens:y.message.usage_metadata.total_tokens}})}}catch(y){throw await Promise.all((p??[]).map(b=>b?.handleLLMError(y))),y}await Promise.all((p??[]).map(y=>y?.handleLLMEnd({generations:[[f]],llmOutput:m})))}}getLsParams(t){const n=this.getName().startsWith("Chat")?this.getName().replace("Chat",""):this.getName();return{ls_model_type:"chat",ls_stop:t.stop,ls_provider:n}}async _generateUncached(t,n,a,r){const s=t.map(f=>f.map(wt));let i;if(r!==void 0&&r.length===s.length)i=r;else{const f={...a.metadata,...this.getLsParams(n)},m=await Oe.configure(a.callbacks,this.callbacks,a.tags,this.tags,f,this.metadata,{verbose:this.verbose}),y={options:n,invocation_params:this?.invocationParams(n),batch_size:1};i=await m?.handleChatModelStart(this.toJSON(),s.map(Ln),a.runId,void 0,y,void 0,void 0,a.runName)}const o=n.outputVersion??this.outputVersion,c=[],l=[];if(!!i?.[0].handlers.find(os)&&!this.disableStreaming&&s.length===1&&this._streamResponseChunks!==Ze.prototype._streamResponseChunks)try{const f=await this._streamResponseChunks(s[0],n,i?.[0]);let m,y;for await(const b of f){if(b.message.id==null){const T=i?.at(0)?.runId;T!=null&&b.message._updateId(`run-${T}`)}m===void 0?m=b:m=Qe(m,b),Dn(b.message)&&b.message.usage_metadata!==void 0&&(y={tokenUsage:{promptTokens:b.message.usage_metadata.input_tokens,completionTokens:b.message.usage_metadata.output_tokens,totalTokens:b.message.usage_metadata.total_tokens}})}if(m===void 0)throw new Error("Received empty response from chat model call.");c.push([m]),await i?.[0].handleLLMEnd({generations:c,llmOutput:y})}catch(f){throw await i?.[0].handleLLMError(f),f}else{const f=await Promise.allSettled(s.map(async(m,y)=>{const b=await this._generate(m,{...n,promptIndex:y},i?.[y]);if(o==="v1")for(const T of b.generations)T.message=Mn(T.message);return b}));await Promise.all(f.map(async(m,y)=>{if(m.status==="fulfilled"){const b=m.value;for(const T of b.generations){if(T.message.id==null){const v=i?.at(0)?.runId;v!=null&&T.message._updateId(`run-${v}`)}T.message.response_metadata={...T.generationInfo,...T.message.response_metadata}}return b.generations.length===1&&(b.generations[0].message.response_metadata={...b.llmOutput,...b.generations[0].message.response_metadata}),c[y]=b.generations,l[y]=b.llmOutput,i?.[y]?.handleLLMEnd({generations:[b.generations],llmOutput:b.llmOutput})}else return await i?.[y]?.handleLLMError(m.reason),Promise.reject(m.reason)}))}const p={generations:c,llmOutput:l.length?this._combineLLMOutput?.(...l):void 0};return Object.defineProperty(p,Xn,{value:i?{runIds:i?.map(f=>f.runId)}:void 0,configurable:!0}),p}async _generateCached({messages:t,cache:n,llmStringKey:a,parsedOptions:r,handledOptions:s}){const i=t.map(v=>v.map(wt)),o={...s.metadata,...this.getLsParams(r)},c=await Oe.configure(s.callbacks,this.callbacks,s.tags,this.tags,o,this.metadata,{verbose:this.verbose}),l={options:r,invocation_params:this?.invocationParams(r),batch_size:1},d=await c?.handleChatModelStart(this.toJSON(),i.map(Ln),s.runId,void 0,l,void 0,void 0,s.runName),p=[],m=(await Promise.allSettled(i.map(async(v,I)=>{const E=Ze._convertInputToPromptValue(v).toString(),x=await n.lookup(E,a);return x==null&&p.push(I),x}))).map((v,I)=>({result:v,runManager:d?.[I]})).filter(({result:v})=>v.status==="fulfilled"&&v.value!=null||v.status==="rejected"),y=r.outputVersion??this.outputVersion,b=[];await Promise.all(m.map(async({result:v,runManager:I},E)=>{if(v.status==="fulfilled"){const x=v.value;return b[E]=x.map(N=>("message"in N&&Re(N.message)&&Kr(N.message)&&(N.message.usage_metadata={input_tokens:0,output_tokens:0,total_tokens:0},y==="v1"&&(N.message=Mn(N.message))),N.generationInfo={...N.generationInfo,tokenUsage:{}},N)),x.length&&await I?.handleLLMNewToken(x[0].text),I?.handleLLMEnd({generations:[x]},void 0,void 0,void 0,{cached:!0})}else return await I?.handleLLMError(v.reason,void 0,void 0,void 0,{cached:!0}),Promise.reject(v.reason)}));const T={generations:b,missingPromptIndices:p,startedRunManagers:d};return Object.defineProperty(T,Xn,{value:d?{runIds:d?.map(v=>v.runId)}:void 0,configurable:!0}),T}async generate(t,n,a){let r;Array.isArray(n)?r={stop:n}:r=n;const s=t.map(y=>y.map(wt)),[i,o]=this._separateRunnableConfigFromCallOptionsCompat(r);if(i.callbacks=i.callbacks??a,!this.cache)return this._generateUncached(s,o,i);const{cache:c}=this,l=this._getSerializedCacheKeyParametersForCall(o),{generations:d,missingPromptIndices:p,startedRunManagers:f}=await this._generateCached({messages:s,cache:c,llmStringKey:l,parsedOptions:o,handledOptions:i});let m={};if(p.length>0){const y=await this._generateUncached(p.map(b=>s[b]),o,i,f!==void 0?p.map(b=>f?.[b]):void 0);await Promise.all(y.generations.map(async(b,T)=>{const v=p[T];d[v]=b;const I=Ze._convertInputToPromptValue(s[v]).toString();return c.update(I,l,b)})),m=y.llmOutput??{}}return{generations:d,llmOutput:m}}invocationParams(t){return{}}_modelType(){return"base_chat_model"}async generatePrompt(t,n,a){const r=t.map(s=>s.toChatMessages());return this.generate(r,n,a)}withStructuredOutput(t,n){if(typeof this.bindTools!="function")throw new Error('Chat model must implement ".bindTools()" to use withStructuredOutput.');if(n?.strict)throw new Error('"strict" mode is not supported for this model by default.');const a=t,r=n?.name,s=xa(a)??"A function available to call.",i=n?.method,o=n?.includeRaw;if(i==="jsonMode")throw new Error('Base withStructuredOutput implementation only supports "functionCalling" as a method.');let c=r??"extract",l;kt(a)?l=[{type:"function",function:{name:c,description:s,parameters:mt(a)}}]:("name"in a&&(c=a.name),l=[{type:"function",function:{name:c,description:s,parameters:a}}]);const d=this.bindTools(l),p=Ge.from(b=>{if(!tt.isInstance(b))throw new Error("Input is not an AIMessageChunk.");if(!b.tool_calls||b.tool_calls.length===0)throw new Error("No tool calls found in the response.");const T=b.tool_calls.find(v=>v.name===c);if(!T)throw new Error(`No tool call found with name ${c}.`);return T.args});if(!o)return d.pipe(p).withConfig({runName:"StructuredOutput"});const f=en.assign({parsed:(b,T)=>p.invoke(b.raw,T)}),m=en.assign({parsed:()=>null}),y=f.withFallbacks({fallbacks:[m]});return un.from([{raw:d},y]).withConfig({runName:"StructuredOutputRunnable"})}},Rd=class extends wi{async _generate(e,t,n){const a=await this._call(e,t,n),r=new Be(a);if(typeof r.content!="string")throw new Error("Cannot generate with a simple chat model when output is not a string.");return{generations:[{text:r.content,message:r}]}}},Pd=class extends V{static lc_name(){return"RouterRunnable"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;runnables;constructor(e){super(e),this.runnables=e.runnables}async invoke(e,t){const{key:n,input:a}=e,r=this.runnables[n];if(r===void 0)throw new Error(`No runnable associated with key "${n}".`);return r.invoke(a,L(t))}async batch(e,t,n){const a=e.map(p=>p.key),r=e.map(p=>p.input);if(a.find(p=>this.runnables[p]===void 0)!==void 0)throw new Error("One or more keys do not have a corresponding runnable.");const i=a.map(p=>this.runnables[p]),o=this._getOptionsList(t??{},e.length),c=o[0]?.maxConcurrency??n?.maxConcurrency,l=c&&c>0?c:e.length,d=[];for(let p=0;p<r.length;p+=l){const f=r.slice(p,p+l).map((y,b)=>i[b].invoke(y,o[b])),m=await Promise.all(f);d.push(m)}return d.flat()}async stream(e,t){const{key:n,input:a}=e,r=this.runnables[n];if(r===void 0)throw new Error(`No runnable associated with key "${n}".`);return r.stream(a,t)}},Md=class extends V{static lc_name(){return"RunnableBranch"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;default;branches;constructor(e){super(e),this.branches=e.branches,this.default=e.default}static from(e){if(e.length<1)throw new Error("RunnableBranch requires at least one branch");const n=e.slice(0,-1).map(([r,s])=>[ve(r),ve(s)]),a=ve(e[e.length-1]);return new this({branches:n,default:a})}async _invoke(e,t,n){let a;for(let r=0;r<this.branches.length;r+=1){const[s,i]=this.branches[r];if(await s.invoke(e,H(t,{callbacks:n?.getChild(`condition:${r+1}`)}))){a=await i.invoke(e,H(t,{callbacks:n?.getChild(`branch:${r+1}`)}));break}}return a||(a=await this.default.invoke(e,H(t,{callbacks:n?.getChild("branch:default")}))),a}async invoke(e,t={}){return this._callWithConfig(this._invoke,e,t)}async*_streamIterator(e,t){const a=await(await pe(t))?.handleChainStart(this.toJSON(),K(e,"input"),t?.runId,void 0,void 0,void 0,t?.runName);let r,s=!0,i;try{for(let o=0;o<this.branches.length;o+=1){const[c,l]=this.branches[o];if(await c.invoke(e,H(t,{callbacks:a?.getChild(`condition:${o+1}`)}))){i=await l.stream(e,H(t,{callbacks:a?.getChild(`branch:${o+1}`)}));for await(const p of i)if(yield p,s)if(r===void 0)r=p;else try{r=Qe(r,p)}catch{r=void 0,s=!1}break}}if(i===void 0){i=await this.default.stream(e,H(t,{callbacks:a?.getChild("branch:default")}));for await(const o of i)if(yield o,s)if(r===void 0)r=o;else try{r=Qe(r,o)}catch{r=void 0,s=!1}}}catch(o){throw await a?.handleChainError(o),o}await a?.handleChainEnd(r??{})}},Ld=class extends ht{runnable;inputMessagesKey;outputMessagesKey;historyMessagesKey;getMessageHistory;constructor(e){let t=Ge.from((s,i)=>this._enterHistory(s,i??{})).withConfig({runName:"loadHistory"});const n=e.historyMessagesKey??e.inputMessagesKey;n&&(t=en.assign({[n]:t}).withConfig({runName:"insertHistory"}));const a=t.pipe(e.runnable.withListeners({onEnd:(s,i)=>this._exitHistory(s,i??{})})).withConfig({runName:"RunnableWithMessageHistory"}),r=e.config??{};super({...e,config:r,bound:a}),this.runnable=e.runnable,this.getMessageHistory=e.getMessageHistory,this.inputMessagesKey=e.inputMessagesKey,this.outputMessagesKey=e.outputMessagesKey,this.historyMessagesKey=e.historyMessagesKey}_getInputMessages(e){let t;if(typeof e=="object"&&!Array.isArray(e)&&!Re(e)){let n;this.inputMessagesKey?n=this.inputMessagesKey:Object.keys(e).length===1?n=Object.keys(e)[0]:n="input",Array.isArray(e[n])&&Array.isArray(e[n][0])?t=e[n][0]:t=e[n]}else t=e;if(typeof t=="string")return[new $e(t)];if(Array.isArray(t))return t;if(Re(t))return[t];throw new Error(`Expected a string, BaseMessage, or array of BaseMessages.
82
78
  Got ${JSON.stringify(t,null,2)}`)}_getOutputMessages(e){let t;if(!Array.isArray(e)&&!Re(e)&&typeof e!="string"){let n;this.outputMessagesKey!==void 0?n=this.outputMessagesKey:Object.keys(e).length===1?n=Object.keys(e)[0]:n="output",e.generations!==void 0?t=e.generations[0][0].message:t=e[n]}else t=e;if(typeof t=="string")return[new Be(t)];if(Array.isArray(t))return t;if(Re(t))return[t];throw new Error(`Expected a string, BaseMessage, or array of BaseMessages. Received: ${JSON.stringify(t,null,2)}`)}async _enterHistory(e,t){const a=await(t?.configurable?.messageHistory).getMessages();return this.historyMessagesKey===void 0?a.concat(this._getInputMessages(e)):a}async _exitHistory(e,t){const n=t.configurable?.messageHistory;let a;Array.isArray(e.inputs)&&Array.isArray(e.inputs[0])?a=e.inputs[0]:a=e.inputs;let r=this._getInputMessages(a);if(this.historyMessagesKey===void 0){const o=await n.getMessages();r=r.slice(o.length)}const s=e.outputs;if(!s)throw new Error(`Output values from 'Run' undefined. Run: ${JSON.stringify(e,null,2)}`);const i=this._getOutputMessages(s);await n.addMessages([...r,...i])}async _mergeConfig(...e){const t=await super._mergeConfig(...e);if(!t.configurable||!t.configurable.sessionId){const a={[this.inputMessagesKey??"input"]:"foo"},r={configurable:{sessionId:"123"}};throw new Error(`sessionId is required. Pass it in as part of the config argument to .invoke() or .stream()
83
79
  eg. chain.invoke(${JSON.stringify(a)}, ${JSON.stringify(r)})`)}const{sessionId:n}=t.configurable;return t.configurable.messageHistory=await this.getMessageHistory(n),t}},$d={};F($d,{RouterRunnable:()=>Pd,Runnable:()=>V,RunnableAssign:()=>Pa,RunnableBinding:()=>ht,RunnableBranch:()=>Md,RunnableEach:()=>Qu,RunnableLambda:()=>Ge,RunnableMap:()=>gt,RunnableParallel:()=>td,RunnablePassthrough:()=>en,RunnablePick:()=>ei,RunnableRetry:()=>Ra,RunnableSequence:()=>un,RunnableToolLike:()=>sa,RunnableWithFallbacks:()=>Xs,RunnableWithMessageHistory:()=>Ld,_coerceToRunnable:()=>ve,ensureConfig:()=>L,getCallbackManagerForConfig:()=>pe,mergeConfigs:()=>Vn,patchConfig:()=>H,pickRunnableConfigKeys:()=>Ye});var bi=class extends V{parseResultWithPrompt(e,t,n){return this.parseResult(e,n)}_baseMessageToString(e){return typeof e.content=="string"?e.content:this._baseMessageContentToString(e.content)}_baseMessageContentToString(e){return JSON.stringify(e)}async invoke(e,t){return typeof e=="string"?this._callWithConfig(async(n,a)=>this.parseResult([{text:n}],a?.callbacks),e,{...t,runType:"parser"}):this._callWithConfig(async(n,a)=>this.parseResult([{message:n,text:this._baseMessageToString(n)}],a?.callbacks),e,{...t,runType:"parser"})}},pn=class extends bi{parseResult(e,t){return this.parse(e[0].text,t)}async parseWithPrompt(e,t,n){return this.parse(e,n)}_type(){throw new Error("_type not implemented")}},We=class extends Error{llmOutput;observation;sendToLLM;constructor(e,t,n,a=!1){if(super(e),this.llmOutput=t,this.observation=n,this.sendToLLM=a,a&&(n===void 0||t===void 0))throw new Error("Arguments 'observation' & 'llmOutput' are required if 'sendToLlm' is true");Qr(this,"OUTPUT_PARSING_FAILURE")}},Rt=class extends pn{async*_transform(e){for await(const t of e)typeof t=="string"?yield this.parseResult([{text:t}]):yield this.parseResult([{message:t,text:this._baseMessageToString(t)}])}async*transform(e,t){yield*this._transformStreamWithConfig(e,this._transform.bind(this),{...t,runType:"parser"})}},$a=class extends Rt{diff=!1;constructor(e){super(e),this.diff=e?.diff??this.diff}async*_transform(e){let t,n;for await(const a of e){if(typeof a!="string"&&typeof a.content!="string")throw new Error("Cannot handle non-string output.");let r;if(ga(a)){if(typeof a.content!="string")throw new Error("Cannot handle non-string message output.");r=new ea({message:a,text:a.content})}else if(Re(a)){if(typeof a.content!="string")throw new Error("Cannot handle non-string message output.");r=new ea({message:Vt(a),text:a.content})}else r=new It({text:a});n===void 0?n=r:n=n.concat(r);const s=await this.parsePartialResult([n]);s!=null&&!Pr(s,t)&&(this.diff?yield this._diff(t,s):yield s,t=s)}}getFormatInstructions(){return""}},jd=class extends Rt{static lc_name(){return"BytesOutputParser"}lc_namespace=["langchain_core","output_parsers","bytes"];lc_serializable=!0;textEncoder=new TextEncoder;parse(e){return Promise.resolve(this.textEncoder.encode(e))}getFormatInstructions(){return""}},Pt=class extends Rt{re;async*_transform(e){let t="";for await(const n of e)if(typeof n=="string"?t+=n:t+=n.content,this.re){const a=[...t.matchAll(this.re)];if(a.length>1){let r=0;for(const s of a.slice(0,-1))yield[s[1]],r+=(s.index??0)+s[0].length;t=t.slice(r)}}else{const a=await this.parse(t);if(a.length>1){for(const r of a.slice(0,-1))yield[r];t=a[a.length-1]}}for(const n of await this.parse(t))yield[n]}},Dd=class extends Pt{static lc_name(){return"CommaSeparatedListOutputParser"}lc_namespace=["langchain_core","output_parsers","list"];lc_serializable=!0;async parse(e){try{return e.trim().split(",").map(t=>t.trim())}catch{throw new We(`Could not parse output: ${e}`,e)}}getFormatInstructions(){return"Your response should be a list of comma separated values, eg: `foo, bar, baz`"}},Fd=class extends Pt{lc_namespace=["langchain_core","output_parsers","list"];length;separator;constructor({length:e,separator:t}){super(...arguments),this.length=e,this.separator=t||","}async parse(e){try{const t=e.trim().split(this.separator).map(n=>n.trim());if(this.length!==void 0&&t.length!==this.length)throw new We(`Incorrect number of items. Expected ${this.length}, got ${t.length}.`);return t}catch(t){throw Object.getPrototypeOf(t)===We.prototype?t:new We(`Could not parse output: ${e}`)}}getFormatInstructions(){return`Your response should be a list of ${this.length===void 0?"":`${this.length} `}items separated by "${this.separator}" (eg: \`foo${this.separator} bar${this.separator} baz\`)`}},Ud=class extends Pt{static lc_name(){return"NumberedListOutputParser"}lc_namespace=["langchain_core","output_parsers","list"];lc_serializable=!0;getFormatInstructions(){return`Your response should be a numbered list with each item on a new line. For example:
84
80
 
@@ -123,7 +119,7 @@ Char: `+h.c),u=new Error(u),h.error=u,ne(h,"onerror",u),h}function Da(h){return
123
119
  Actual: `+h.attribValue);else if(_==="xmlns"&&h.attribValue!==m)U(h,"xmlns: prefix must be bound to "+m+`
124
120
  Actual: `+h.attribValue);else{var j=h.tag,J=h.tags[h.tags.length-1]||h;j.ns===J.ns&&(j.ns=Object.create(J.ns)),j.ns[_]=h.attribValue}h.attribList.push([h.attribName,h.attribValue])}else h.tag.attributes[h.attribName]=h.attribValue,z(h,"onattribute",{name:h.attribName,value:h.attribValue});h.attribName=h.attribValue=""}function Ve(h,u){if(h.opt.xmlns){var w=h.tag,_=fn(h.tagName);w.prefix=_.prefix,w.local=_.local,w.uri=w.ns[_.prefix]||"",w.prefix&&!w.uri&&(U(h,"Unbound namespace prefix: "+JSON.stringify(h.tagName)),w.uri=_.prefix);var j=h.tags[h.tags.length-1]||h;w.ns&&j.ns!==w.ns&&Object.keys(w.ns).forEach(function(Ha){z(h,"onopennamespace",{prefix:Ha,uri:w.ns[Ha]})});for(var J=0,W=h.attribList.length;J<W;J++){var ie=h.attribList[J],fe=ie[0],at=ie[1],X=fn(fe,!0),Ne=X.prefix,Ii=X.local,za=Ne===""?"":w.ns[Ne]||"",_n={name:fe,value:at,prefix:Ne,local:Ii,uri:za};Ne&&Ne!=="xmlns"&&!za&&(U(h,"Unbound namespace prefix: "+JSON.stringify(Ne)),_n.uri=Ne),h.tag.attributes[fe]=_n,z(h,"onattribute",_n)}h.attribList.length=0}h.tag.isSelfClosing=!!u,h.sawRoot=!0,h.tags.push(h.tag),z(h,"onopentag",h.tag),u||(!h.noscript&&h.tagName.toLowerCase()==="script"?h.state=g.SCRIPT:h.state=g.TEXT,h.tag=null,h.tagName=""),h.attribName=h.attribValue="",h.attribList.length=0}function gn(h){if(!h.tagName){U(h,"Weird empty close tag."),h.textNode+="</>",h.state=g.TEXT;return}if(h.script){if(h.tagName!=="script"){h.script+="</"+h.tagName+">",h.tagName="",h.state=g.SCRIPT;return}z(h,"onscript",h.script),h.script=""}var u=h.tags.length,w=h.tagName;h.strict||(w=w[h.looseCase]());for(var _=w;u--;){var j=h.tags[u];if(j.name!==_)U(h,"Unexpected close tag");else break}if(u<0){U(h,"Unmatched closing tag: "+h.tagName),h.textNode+="</"+h.tagName+">",h.state=g.TEXT;return}h.tagName=w;for(var J=h.tags.length;J-- >u;){var W=h.tag=h.tags.pop();h.tagName=h.tag.name,z(h,"onclosetag",h.tagName);var ie={};for(var fe in W.ns)ie[fe]=W.ns[fe];var at=h.tags[h.tags.length-1]||h;h.opt.xmlns&&W.ns!==at.ns&&Object.keys(W.ns).forEach(function(X){var Ne=W.ns[X];z(h,"onclosenamespace",{prefix:X,uri:Ne})})}u===0&&(h.closedRoot=!0),h.tagName=h.attribValue=h.attribName="",h.attribList.length=0,h.state=g.TEXT}function Fa(h){var u=h.entity,w=u.toLowerCase(),_,j="";return h.ENTITIES[u]?h.ENTITIES[u]:h.ENTITIES[w]?h.ENTITIES[w]:(u=w,u.charAt(0)==="#"&&(u.charAt(1)==="x"?(u=u.slice(2),_=parseInt(u,16),j=_.toString(16)):(u=u.slice(1),_=parseInt(u,10),j=_.toString(10))),u=u.replace(/^0+/,""),isNaN(_)||j.toLowerCase()!==u?(U(h,"Invalid character entity"),"&"+h.entity+";"):String.fromCodePoint(_))}function Ua(h,u){u==="<"?(h.state=g.OPEN_WAKA,h.startTagPosition=h.position):E(u)||(U(h,"Non-whitespace before first tag."),h.textNode=u,h.state=g.TEXT)}function Ba(h,u){var w="";return u<h.length&&(w=h.charAt(u)),w}function Ai(h){var u=this;if(this.error)throw this.error;if(u.closed)return Mt(u,"Cannot write after close. Assign an onready handler.");if(h===null)return Da(u);typeof h=="object"&&(h=h.toString());for(var w=0,_="";_=Ba(h,w++),u.c=_,!!_;)switch(u.trackPosition&&(u.position++,_===`
125
121
  `?(u.line++,u.column=0):u.column++),u.state){case g.BEGIN:if(u.state=g.BEGIN_WHITESPACE,_==="\uFEFF")continue;Ua(u,_);continue;case g.BEGIN_WHITESPACE:Ua(u,_);continue;case g.TEXT:if(u.sawRoot&&!u.closedRoot){for(var j=w-1;_&&_!=="<"&&_!=="&";)_=Ba(h,w++),_&&u.trackPosition&&(u.position++,_===`
126
- `?(u.line++,u.column=0):u.column++);u.textNode+=h.substring(j,w-1)}_==="<"&&!(u.sawRoot&&u.closedRoot&&!u.strict)?(u.state=g.OPEN_WAKA,u.startTagPosition=u.position):(!E(_)&&(!u.sawRoot||u.closedRoot)&&U(u,"Text data outside of root node."),_==="&"?u.state=g.TEXT_ENTITY:u.textNode+=_);continue;case g.SCRIPT:_==="<"?u.state=g.SCRIPT_ENDING:u.script+=_;continue;case g.SCRIPT_ENDING:_==="/"?u.state=g.CLOSE_TAG:(u.script+="<"+_,u.state=g.SCRIPT);continue;case g.OPEN_WAKA:if(_==="!")u.state=g.SGML_DECL,u.sgmlDecl="";else if(!E(_))if(M(b,_))u.state=g.OPEN_TAG,u.tagName=_;else if(_==="/")u.state=g.CLOSE_TAG,u.tagName="";else if(_==="?")u.state=g.PROC_INST,u.procInstName=u.procInstBody="";else{if(U(u,"Unencoded <"),u.startTagPosition+1<u.position){var J=u.position-u.startTagPosition;_=new Array(J).join(" ")+_}u.textNode+="<"+_,u.state=g.TEXT}continue;case g.SGML_DECL:(u.sgmlDecl+_).toUpperCase()===d?(z(u,"onopencdata"),u.state=g.CDATA,u.sgmlDecl="",u.cdata=""):u.sgmlDecl+_==="--"?(u.state=g.COMMENT,u.comment="",u.sgmlDecl=""):(u.sgmlDecl+_).toUpperCase()===p?(u.state=g.DOCTYPE,(u.doctype||u.sawRoot)&&U(u,"Inappropriately located doctype declaration"),u.doctype="",u.sgmlDecl=""):_===">"?(z(u,"onsgmldeclaration",u.sgmlDecl),u.sgmlDecl="",u.state=g.TEXT):(x(_)&&(u.state=g.SGML_DECL_QUOTED),u.sgmlDecl+=_);continue;case g.SGML_DECL_QUOTED:_===u.q&&(u.state=g.SGML_DECL,u.q=""),u.sgmlDecl+=_;continue;case g.DOCTYPE:_===">"?(u.state=g.TEXT,z(u,"ondoctype",u.doctype),u.doctype=!0):(u.doctype+=_,_==="["?u.state=g.DOCTYPE_DTD:x(_)&&(u.state=g.DOCTYPE_QUOTED,u.q=_));continue;case g.DOCTYPE_QUOTED:u.doctype+=_,_===u.q&&(u.q="",u.state=g.DOCTYPE);continue;case g.DOCTYPE_DTD:u.doctype+=_,_==="]"?u.state=g.DOCTYPE:x(_)&&(u.state=g.DOCTYPE_DTD_QUOTED,u.q=_);continue;case g.DOCTYPE_DTD_QUOTED:u.doctype+=_,_===u.q&&(u.state=g.DOCTYPE_DTD,u.q="");continue;case g.COMMENT:_==="-"?u.state=g.COMMENT_ENDING:u.comment+=_;continue;case g.COMMENT_ENDING:_==="-"?(u.state=g.COMMENT_ENDED,u.comment=ja(u.opt,u.comment),u.comment&&z(u,"oncomment",u.comment),u.comment=""):(u.comment+="-"+_,u.state=g.COMMENT);continue;case g.COMMENT_ENDED:_!==">"?(U(u,"Malformed comment"),u.comment+="--"+_,u.state=g.COMMENT):u.state=g.TEXT;continue;case g.CDATA:_==="]"?u.state=g.CDATA_ENDING:u.cdata+=_;continue;case g.CDATA_ENDING:_==="]"?u.state=g.CDATA_ENDING_2:(u.cdata+="]"+_,u.state=g.CDATA);continue;case g.CDATA_ENDING_2:_===">"?(u.cdata&&z(u,"oncdata",u.cdata),z(u,"onclosecdata"),u.cdata="",u.state=g.TEXT):_==="]"?u.cdata+="]":(u.cdata+="]]"+_,u.state=g.CDATA);continue;case g.PROC_INST:_==="?"?u.state=g.PROC_INST_ENDING:E(_)?u.state=g.PROC_INST_BODY:u.procInstName+=_;continue;case g.PROC_INST_BODY:if(!u.procInstBody&&E(_))continue;_==="?"?u.state=g.PROC_INST_ENDING:u.procInstBody+=_;continue;case g.PROC_INST_ENDING:_===">"?(z(u,"onprocessinginstruction",{name:u.procInstName,body:u.procInstBody}),u.procInstName=u.procInstBody="",u.state=g.TEXT):(u.procInstBody+="?"+_,u.state=g.PROC_INST_BODY);continue;case g.OPEN_TAG:M(T,_)?u.tagName+=_:(Si(u),_===">"?Ve(u):_==="/"?u.state=g.OPEN_TAG_SLASH:(E(_)||U(u,"Invalid character in tag name"),u.state=g.ATTRIB));continue;case g.OPEN_TAG_SLASH:_===">"?(Ve(u,!0),gn(u)):(U(u,"Forward-slash in opening tag not followed by >"),u.state=g.ATTRIB);continue;case g.ATTRIB:if(E(_))continue;_===">"?Ve(u):_==="/"?u.state=g.OPEN_TAG_SLASH:M(b,_)?(u.attribName=_,u.attribValue="",u.state=g.ATTRIB_NAME):U(u,"Invalid attribute name");continue;case g.ATTRIB_NAME:_==="="?u.state=g.ATTRIB_VALUE:_===">"?(U(u,"Attribute without value"),u.attribValue=u.attribName,mn(u),Ve(u)):E(_)?u.state=g.ATTRIB_NAME_SAW_WHITE:M(T,_)?u.attribName+=_:U(u,"Invalid attribute name");continue;case g.ATTRIB_NAME_SAW_WHITE:if(_==="=")u.state=g.ATTRIB_VALUE;else{if(E(_))continue;U(u,"Attribute without value"),u.tag.attributes[u.attribName]="",u.attribValue="",z(u,"onattribute",{name:u.attribName,value:""}),u.attribName="",_===">"?Ve(u):M(b,_)?(u.attribName=_,u.state=g.ATTRIB_NAME):(U(u,"Invalid attribute name"),u.state=g.ATTRIB)}continue;case g.ATTRIB_VALUE:if(E(_))continue;x(_)?(u.q=_,u.state=g.ATTRIB_VALUE_QUOTED):(U(u,"Unquoted attribute value"),u.state=g.ATTRIB_VALUE_UNQUOTED,u.attribValue=_);continue;case g.ATTRIB_VALUE_QUOTED:if(_!==u.q){_==="&"?u.state=g.ATTRIB_VALUE_ENTITY_Q:u.attribValue+=_;continue}mn(u),u.q="",u.state=g.ATTRIB_VALUE_CLOSED;continue;case g.ATTRIB_VALUE_CLOSED:E(_)?u.state=g.ATTRIB:_===">"?Ve(u):_==="/"?u.state=g.OPEN_TAG_SLASH:M(b,_)?(U(u,"No whitespace between attributes"),u.attribName=_,u.attribValue="",u.state=g.ATTRIB_NAME):U(u,"Invalid attribute name");continue;case g.ATTRIB_VALUE_UNQUOTED:if(!N(_)){_==="&"?u.state=g.ATTRIB_VALUE_ENTITY_U:u.attribValue+=_;continue}mn(u),_===">"?Ve(u):u.state=g.ATTRIB;continue;case g.CLOSE_TAG:if(u.tagName)_===">"?gn(u):M(T,_)?u.tagName+=_:u.script?(u.script+="</"+u.tagName,u.tagName="",u.state=g.SCRIPT):(E(_)||U(u,"Invalid tagname in closing tag"),u.state=g.CLOSE_TAG_SAW_WHITE);else{if(E(_))continue;B(b,_)?u.script?(u.script+="</"+_,u.state=g.SCRIPT):U(u,"Invalid tagname in closing tag."):u.tagName=_}continue;case g.CLOSE_TAG_SAW_WHITE:if(E(_))continue;_===">"?gn(u):U(u,"Invalid characters in closing tag");continue;case g.TEXT_ENTITY:case g.ATTRIB_VALUE_ENTITY_Q:case g.ATTRIB_VALUE_ENTITY_U:var W,ie;switch(u.state){case g.TEXT_ENTITY:W=g.TEXT,ie="textNode";break;case g.ATTRIB_VALUE_ENTITY_Q:W=g.ATTRIB_VALUE_QUOTED,ie="attribValue";break;case g.ATTRIB_VALUE_ENTITY_U:W=g.ATTRIB_VALUE_UNQUOTED,ie="attribValue";break}if(_===";")if(u.opt.unparsedEntities){var fe=Fa(u);u.entity="",u.state=W,u.write(fe)}else u[ie]+=Fa(u),u.entity="",u.state=W;else M(u.entity.length?I:v,_)?u.entity+=_:(U(u,"Invalid character in entity name"),u[ie]+="&"+u.entity+_,u.entity="",u.state=W);continue;default:throw new Error(u,"Unknown state: "+u.state)}return u.position>=u.bufferCheckPosition&&a(u),u}/*! http://mths.be/fromcodepoint v0.1.0 by @mathias */return String.fromCodePoint||(function(){var h=String.fromCharCode,u=Math.floor,w=function(){var _=16384,j=[],J,W,ie=-1,fe=arguments.length;if(!fe)return"";for(var at="";++ie<fe;){var X=Number(arguments[ie]);if(!isFinite(X)||X<0||X>1114111||u(X)!==X)throw RangeError("Invalid code point: "+X);X<=65535?j.push(X):(X-=65536,J=(X>>10)+55296,W=X%1024+56320,j.push(J,W)),(ie+1===fe||j.length>_)&&(at+=h.apply(null,j),j.length=0)}return at};Object.defineProperty?Object.defineProperty(String,"fromCodePoint",{value:w,configurable:!0,writable:!0}):String.fromCodePoint=w})(),e},qd=Zd(),ia=`The output should be formatted as a XML file.
122
+ `?(u.line++,u.column=0):u.column++);u.textNode+=h.substring(j,w-1)}_==="<"&&!(u.sawRoot&&u.closedRoot&&!u.strict)?(u.state=g.OPEN_WAKA,u.startTagPosition=u.position):(!E(_)&&(!u.sawRoot||u.closedRoot)&&U(u,"Text data outside of root node."),_==="&"?u.state=g.TEXT_ENTITY:u.textNode+=_);continue;case g.SCRIPT:_==="<"?u.state=g.SCRIPT_ENDING:u.script+=_;continue;case g.SCRIPT_ENDING:_==="/"?u.state=g.CLOSE_TAG:(u.script+="<"+_,u.state=g.SCRIPT);continue;case g.OPEN_WAKA:if(_==="!")u.state=g.SGML_DECL,u.sgmlDecl="";else if(!E(_))if(M(b,_))u.state=g.OPEN_TAG,u.tagName=_;else if(_==="/")u.state=g.CLOSE_TAG,u.tagName="";else if(_==="?")u.state=g.PROC_INST,u.procInstName=u.procInstBody="";else{if(U(u,"Unencoded <"),u.startTagPosition+1<u.position){var J=u.position-u.startTagPosition;_=new Array(J).join(" ")+_}u.textNode+="<"+_,u.state=g.TEXT}continue;case g.SGML_DECL:(u.sgmlDecl+_).toUpperCase()===d?(z(u,"onopencdata"),u.state=g.CDATA,u.sgmlDecl="",u.cdata=""):u.sgmlDecl+_==="--"?(u.state=g.COMMENT,u.comment="",u.sgmlDecl=""):(u.sgmlDecl+_).toUpperCase()===p?(u.state=g.DOCTYPE,(u.doctype||u.sawRoot)&&U(u,"Inappropriately located doctype declaration"),u.doctype="",u.sgmlDecl=""):_===">"?(z(u,"onsgmldeclaration",u.sgmlDecl),u.sgmlDecl="",u.state=g.TEXT):(x(_)&&(u.state=g.SGML_DECL_QUOTED),u.sgmlDecl+=_);continue;case g.SGML_DECL_QUOTED:_===u.q&&(u.state=g.SGML_DECL,u.q=""),u.sgmlDecl+=_;continue;case g.DOCTYPE:_===">"?(u.state=g.TEXT,z(u,"ondoctype",u.doctype),u.doctype=!0):(u.doctype+=_,_==="["?u.state=g.DOCTYPE_DTD:x(_)&&(u.state=g.DOCTYPE_QUOTED,u.q=_));continue;case g.DOCTYPE_QUOTED:u.doctype+=_,_===u.q&&(u.q="",u.state=g.DOCTYPE);continue;case g.DOCTYPE_DTD:u.doctype+=_,_==="]"?u.state=g.DOCTYPE:x(_)&&(u.state=g.DOCTYPE_DTD_QUOTED,u.q=_);continue;case g.DOCTYPE_DTD_QUOTED:u.doctype+=_,_===u.q&&(u.state=g.DOCTYPE_DTD,u.q="");continue;case g.COMMENT:_==="-"?u.state=g.COMMENT_ENDING:u.comment+=_;continue;case g.COMMENT_ENDING:_==="-"?(u.state=g.COMMENT_ENDED,u.comment=ja(u.opt,u.comment),u.comment&&z(u,"oncomment",u.comment),u.comment=""):(u.comment+="-"+_,u.state=g.COMMENT);continue;case g.COMMENT_ENDED:_!==">"?(U(u,"Malformed comment"),u.comment+="--"+_,u.state=g.COMMENT):u.state=g.TEXT;continue;case g.CDATA:_==="]"?u.state=g.CDATA_ENDING:u.cdata+=_;continue;case g.CDATA_ENDING:_==="]"?u.state=g.CDATA_ENDING_2:(u.cdata+="]"+_,u.state=g.CDATA);continue;case g.CDATA_ENDING_2:_===">"?(u.cdata&&z(u,"oncdata",u.cdata),z(u,"onclosecdata"),u.cdata="",u.state=g.TEXT):_==="]"?u.cdata+="]":(u.cdata+="]]"+_,u.state=g.CDATA);continue;case g.PROC_INST:_==="?"?u.state=g.PROC_INST_ENDING:E(_)?u.state=g.PROC_INST_BODY:u.procInstName+=_;continue;case g.PROC_INST_BODY:if(!u.procInstBody&&E(_))continue;_==="?"?u.state=g.PROC_INST_ENDING:u.procInstBody+=_;continue;case g.PROC_INST_ENDING:_===">"?(z(u,"onprocessinginstruction",{name:u.procInstName,body:u.procInstBody}),u.procInstName=u.procInstBody="",u.state=g.TEXT):(u.procInstBody+="?"+_,u.state=g.PROC_INST_BODY);continue;case g.OPEN_TAG:M(T,_)?u.tagName+=_:(Si(u),_===">"?Ve(u):_==="/"?u.state=g.OPEN_TAG_SLASH:(E(_)||U(u,"Invalid character in tag name"),u.state=g.ATTRIB));continue;case g.OPEN_TAG_SLASH:_===">"?(Ve(u,!0),gn(u)):(U(u,"Forward-slash in opening tag not followed by >"),u.state=g.ATTRIB);continue;case g.ATTRIB:if(E(_))continue;_===">"?Ve(u):_==="/"?u.state=g.OPEN_TAG_SLASH:M(b,_)?(u.attribName=_,u.attribValue="",u.state=g.ATTRIB_NAME):U(u,"Invalid attribute name");continue;case g.ATTRIB_NAME:_==="="?u.state=g.ATTRIB_VALUE:_===">"?(U(u,"Attribute without value"),u.attribValue=u.attribName,mn(u),Ve(u)):E(_)?u.state=g.ATTRIB_NAME_SAW_WHITE:M(T,_)?u.attribName+=_:U(u,"Invalid attribute name");continue;case g.ATTRIB_NAME_SAW_WHITE:if(_==="=")u.state=g.ATTRIB_VALUE;else{if(E(_))continue;U(u,"Attribute without value"),u.tag.attributes[u.attribName]="",u.attribValue="",z(u,"onattribute",{name:u.attribName,value:""}),u.attribName="",_===">"?Ve(u):M(b,_)?(u.attribName=_,u.state=g.ATTRIB_NAME):(U(u,"Invalid attribute name"),u.state=g.ATTRIB)}continue;case g.ATTRIB_VALUE:if(E(_))continue;x(_)?(u.q=_,u.state=g.ATTRIB_VALUE_QUOTED):(U(u,"Unquoted attribute value"),u.state=g.ATTRIB_VALUE_UNQUOTED,u.attribValue=_);continue;case g.ATTRIB_VALUE_QUOTED:if(_!==u.q){_==="&"?u.state=g.ATTRIB_VALUE_ENTITY_Q:u.attribValue+=_;continue}mn(u),u.q="",u.state=g.ATTRIB_VALUE_CLOSED;continue;case g.ATTRIB_VALUE_CLOSED:E(_)?u.state=g.ATTRIB:_===">"?Ve(u):_==="/"?u.state=g.OPEN_TAG_SLASH:M(b,_)?(U(u,"No whitespace between attributes"),u.attribName=_,u.attribValue="",u.state=g.ATTRIB_NAME):U(u,"Invalid attribute name");continue;case g.ATTRIB_VALUE_UNQUOTED:if(!N(_)){_==="&"?u.state=g.ATTRIB_VALUE_ENTITY_U:u.attribValue+=_;continue}mn(u),_===">"?Ve(u):u.state=g.ATTRIB;continue;case g.CLOSE_TAG:if(u.tagName)_===">"?gn(u):M(T,_)?u.tagName+=_:u.script?(u.script+="</"+u.tagName,u.tagName="",u.state=g.SCRIPT):(E(_)||U(u,"Invalid tagname in closing tag"),u.state=g.CLOSE_TAG_SAW_WHITE);else{if(E(_))continue;B(b,_)?u.script?(u.script+="</"+_,u.state=g.SCRIPT):U(u,"Invalid tagname in closing tag."):u.tagName=_}continue;case g.CLOSE_TAG_SAW_WHITE:if(E(_))continue;_===">"?gn(u):U(u,"Invalid characters in closing tag");continue;case g.TEXT_ENTITY:case g.ATTRIB_VALUE_ENTITY_Q:case g.ATTRIB_VALUE_ENTITY_U:var W,ie;switch(u.state){case g.TEXT_ENTITY:W=g.TEXT,ie="textNode";break;case g.ATTRIB_VALUE_ENTITY_Q:W=g.ATTRIB_VALUE_QUOTED,ie="attribValue";break;case g.ATTRIB_VALUE_ENTITY_U:W=g.ATTRIB_VALUE_UNQUOTED,ie="attribValue";break}if(_===";")if(u.opt.unparsedEntities){var fe=Fa(u);u.entity="",u.state=W,u.write(fe)}else u[ie]+=Fa(u),u.entity="",u.state=W;else M(u.entity.length?I:v,_)?u.entity+=_:(U(u,"Invalid character in entity name"),u[ie]+="&"+u.entity+_,u.entity="",u.state=W);continue;default:throw new Error(u,"Unknown state: "+u.state)}return u.position>=u.bufferCheckPosition&&a(u),u}return String.fromCodePoint||(function(){var h=String.fromCharCode,u=Math.floor,w=function(){var _=16384,j=[],J,W,ie=-1,fe=arguments.length;if(!fe)return"";for(var at="";++ie<fe;){var X=Number(arguments[ie]);if(!isFinite(X)||X<0||X>1114111||u(X)!==X)throw RangeError("Invalid code point: "+X);X<=65535?j.push(X):(X-=65536,J=(X>>10)+55296,W=X%1024+56320,j.push(J,W)),(ie+1===fe||j.length>_)&&(at+=h.apply(null,j),j.length=0)}return at};Object.defineProperty?Object.defineProperty(String,"fromCodePoint",{value:w,configurable:!0,writable:!0}):String.fromCodePoint=w})(),e},qd=Zd(),ia=`The output should be formatted as a XML file.
127
123
  1. Output should conform to the tags below.
128
124
  2. If tags are not given, make them on your own.
129
125
  3. Remember to always open and close all the tags.
@@ -147,4 +143,4 @@ Here are the output tags:
147
143
  {tags}
148
144
  \`\`\``;var Jd=class extends $a{tags;constructor(e){super(e),this.tags=e?.tags}static lc_name(){return"XMLOutputParser"}lc_namespace=["langchain_core","output_parsers"];lc_serializable=!0;_diff(e,t){if(t)return e?Aa(e,t):[{op:"replace",path:"",value:t}]}async parsePartialResult(e){return oa(e[0].text)}async parse(e){return oa(e)}getFormatInstructions(){return!!(this.tags&&this.tags.length>0)?ia.replace("{tags}",this.tags?.join(", ")??""):ia}};const Wd=e=>e.split(`
149
145
  `).map(t=>t.replace(/^\s+/,"")).join(`
150
- `).trim(),Ei=e=>{if(Object.keys(e).length===0)return{};const t={};return e.children.length>0?(t[e.name]=e.children.map(Ei),t):(t[e.name]=e.text??void 0,t)};function oa(e){const t=Wd(e),n=qd.parser(!0);let a={};const r=[];n.onopentag=o=>{const c={name:o.name,attributes:o.attributes,children:[],text:"",isSelfClosing:o.isSelfClosing};r.length>0?r[r.length-1].children.push(c):a=c,o.isSelfClosing||r.push(c)},n.onclosetag=()=>{if(r.length>0){const o=r.pop();r.length===0&&o&&(a=o)}},n.ontext=o=>{if(r.length>0){const c=r[r.length-1];c.text+=o}},n.onattribute=o=>{if(r.length>0){const c=r[r.length-1];c.attributes[o.name]=o.value}};const s=/```(xml)?(.*)```/s.exec(t),i=s?s[2]:t;return n.write(i).close(),a&&a.name==="?xml"&&(a=a.children[0]),Ei(a)}var Kd={};F(Kd,{AsymmetricStructuredOutputParser:()=>Hd,BaseCumulativeTransformOutputParser:()=>$a,BaseLLMOutputParser:()=>bi,BaseOutputParser:()=>pn,BaseTransformOutputParser:()=>Rt,BytesOutputParser:()=>jd,CommaSeparatedListOutputParser:()=>Dd,CustomListOutputParser:()=>Fd,JsonMarkdownStructuredOutputParser:()=>Ti,JsonOutputParser:()=>Vd,ListOutputParser:()=>Pt,MarkdownListOutputParser:()=>Bd,NumberedListOutputParser:()=>Ud,OutputParserException:()=>We,StringOutputParser:()=>zd,StructuredOutputParser:()=>vi,XMLOutputParser:()=>Jd,XML_FORMAT_INSTRUCTIONS:()=>ia,parseJsonMarkdown:()=>jn,parsePartialJson:()=>ya,parseXMLMarkdown:()=>oa});export{Xr as $,cn as A,bi as B,ea as C,ut as D,tn as E,rn as F,nn as G,$e as H,yi as I,Vd as J,Oe as K,It as L,os as M,Qe as N,We as O,Xn as P,si as Q,en as R,vi as S,pt as T,ai as U,ri as V,Oo as W,_i as X,L as Y,Vn as Z,F as _,Re as a,Ca as a0,El as a1,Xd as a2,Us as a3,zt as a4,H as a5,Me as a6,Ye as a7,Jt as a8,Zr as a9,Be as b,tt as c,Ct as d,qr as e,Kr as f,ii as g,Od as h,kt as i,Ue as j,Bi as k,Zl as l,wi as m,Fe as n,un as o,$n as p,fd as q,Y as r,Z as s,mt as t,ya as u,$a as v,xa as w,Ge as x,Ui as y,sn as z};
146
+ `).trim(),Ei=e=>{if(Object.keys(e).length===0)return{};const t={};return e.children.length>0?(t[e.name]=e.children.map(Ei),t):(t[e.name]=e.text??void 0,t)};function oa(e){const t=Wd(e),n=qd.parser(!0);let a={};const r=[];n.onopentag=o=>{const c={name:o.name,attributes:o.attributes,children:[],text:"",isSelfClosing:o.isSelfClosing};r.length>0?r[r.length-1].children.push(c):a=c,o.isSelfClosing||r.push(c)},n.onclosetag=()=>{if(r.length>0){const o=r.pop();r.length===0&&o&&(a=o)}},n.ontext=o=>{if(r.length>0){const c=r[r.length-1];c.text+=o}},n.onattribute=o=>{if(r.length>0){const c=r[r.length-1];c.attributes[o.name]=o.value}};const s=/```(xml)?(.*)```/s.exec(t),i=s?s[2]:t;return n.write(i).close(),a&&a.name==="?xml"&&(a=a.children[0]),Ei(a)}var Kd={};F(Kd,{AsymmetricStructuredOutputParser:()=>Hd,BaseCumulativeTransformOutputParser:()=>$a,BaseLLMOutputParser:()=>bi,BaseOutputParser:()=>pn,BaseTransformOutputParser:()=>Rt,BytesOutputParser:()=>jd,CommaSeparatedListOutputParser:()=>Dd,CustomListOutputParser:()=>Fd,JsonMarkdownStructuredOutputParser:()=>Ti,JsonOutputParser:()=>Vd,ListOutputParser:()=>Pt,MarkdownListOutputParser:()=>Bd,NumberedListOutputParser:()=>Ud,OutputParserException:()=>We,StringOutputParser:()=>zd,StructuredOutputParser:()=>vi,XMLOutputParser:()=>Jd,XML_FORMAT_INSTRUCTIONS:()=>ia,parseJsonMarkdown:()=>jn,parsePartialJson:()=>ya,parseXMLMarkdown:()=>oa});export{Vn as $,cn as A,bi as B,ea as C,tn as D,nn as E,rn as F,Ui as G,$e as H,Co as I,Vd as J,yi as K,Oe as L,It as M,os as N,We as O,Qe as P,Xn as Q,en as R,vi as S,pt as T,si as U,ai as V,ri as W,Oo as X,_i as Y,L as Z,F as _,Re as a,Xr as a0,Ca as a1,El as a2,Xd as a3,Us as a4,zt as a5,H as a6,Me as a7,Ye as a8,Zr as a9,Jt as aa,Be as b,tt as c,Ct as d,qr as e,Kr as f,ii as g,Od as h,kt as i,Ue as j,Bi as k,Zl as l,wi as m,Fe as n,un as o,$n as p,fd as q,Y as r,Z as s,mt as t,$a as u,ya as v,xa as w,Ge as x,sn as y,ut as z};