@mcp-use/inspector 0.6.1 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/dist/cli.js +295 -19
  2. package/dist/client/assets/__vite-browser-external-CHS79mP1.js +8 -0
  3. package/dist/client/assets/browser-BdCJ_qyB.js +38211 -0
  4. package/dist/client/assets/chunk-VL2OQCWN-CxD8xDNw.js +6475 -0
  5. package/dist/client/assets/display-YIYC6WJE-B6ZSv77R.js +44742 -0
  6. package/dist/client/assets/embeddings-DlCMB9po.js +21 -0
  7. package/dist/client/assets/index-B0NYybvW.js +5371 -0
  8. package/dist/client/assets/index-CKXUnlZB.js +94617 -0
  9. package/dist/client/assets/index-Cb09SlUY.js +17535 -0
  10. package/dist/client/assets/index-CsP5AdwX.js +10699 -0
  11. package/dist/client/assets/index-DX0TIfSM.js +102 -0
  12. package/dist/client/assets/index-Q_pqNaNk.js +1780 -0
  13. package/dist/client/assets/index-kVFYovMy.css +5752 -0
  14. package/dist/client/assets/path-QsnVvLoj.js +62 -0
  15. package/dist/client/assets/transport-wrapper-browser-ChPHVnHg.js +165 -0
  16. package/dist/client/assets/winston-qgF6niUt.js +12326 -0
  17. package/dist/client/index.html +3 -3
  18. package/dist/server/{chunk-37X7HLUV.js → chunk-3T2VCYG6.js} +87 -13
  19. package/dist/server/chunk-CVECQ7BJ.js +78 -0
  20. package/dist/server/{chunk-555LGZ3I.js → chunk-FS77NTZN.js} +133 -10
  21. package/dist/server/chunk-PKBMQBKP.js +7 -0
  22. package/dist/server/{chunk-WYBXXYSP.js → chunk-RRPLH7DL.js} +1 -1
  23. package/dist/server/{chunk-PYGYQT2G.js → chunk-S7NOZBMG.js} +3 -3
  24. package/dist/server/{chunk-DGUMOD7P.js → chunk-ZONLXYBO.js} +92 -10
  25. package/dist/server/cli.js +6 -4
  26. package/dist/server/index.js +7 -5
  27. package/dist/server/middleware.js +7 -5
  28. package/dist/server/rpc-log-bus.d.ts +17 -0
  29. package/dist/server/rpc-log-bus.d.ts.map +1 -0
  30. package/dist/server/rpc-log-bus.js +7 -0
  31. package/dist/server/server.js +6 -4
  32. package/dist/server/shared-routes.d.ts.map +1 -1
  33. package/dist/server/shared-routes.js +4 -2
  34. package/dist/server/shared-static.js +3 -2
  35. package/dist/server/shared-utils-browser.d.ts +2 -1
  36. package/dist/server/shared-utils-browser.d.ts.map +1 -1
  37. package/dist/server/shared-utils-browser.js +2 -1
  38. package/dist/server/shared-utils.d.ts +4 -1
  39. package/dist/server/shared-utils.d.ts.map +1 -1
  40. package/dist/server/shared-utils.js +2 -1
  41. package/dist/server/transport-wrapper.d.ts +6 -0
  42. package/dist/server/transport-wrapper.d.ts.map +1 -0
  43. package/dist/server/transport-wrapper.js +68 -0
  44. package/dist/server/utils.js +1 -0
  45. package/package.json +12 -3
  46. package/dist/client/assets/__vite-browser-external-DFygW7-s.js +0 -1
  47. package/dist/client/assets/chunk-VL2OQCWN-iRVOQjqe.js +0 -8
  48. package/dist/client/assets/display-LIYVTGEU-D2dm8q2H.js +0 -30
  49. package/dist/client/assets/embeddings-Dcyp0Vlp.js +0 -1
  50. package/dist/client/assets/index-6zrNEwtM.js +0 -4
  51. package/dist/client/assets/index-CAnbiFOL.css +0 -1
  52. package/dist/client/assets/index-CB1s6Wr6.js +0 -146
  53. package/dist/client/assets/index-CoMldIFv.js +0 -2
  54. package/dist/client/assets/index-DRz5BQNA.js +0 -1
  55. package/dist/client/assets/index-DUf1336L.js +0 -1559
  56. package/dist/client/assets/index-DmIKR5St.js +0 -1
  57. package/dist/client/assets/index-DpUpZFq2.js +0 -25
  58. package/dist/client/assets/index-DzegZXPW.js +0 -40
  59. package/dist/client/assets/langfuse-C4HKZ3NL-vCtAvQQV.js +0 -564
  60. package/dist/client/assets/path-C9FudP8b.js +0 -1
  61. package/dist/client/assets/winston-BVJ8PyEn.js +0 -37
@@ -1,146 +0,0 @@
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-iRVOQjqe.js";import{Z as P,a as Za,o as la,s as ua}from"./index-DUf1336L.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
- `)}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
- Left ${typeof e}
4
- Right ${typeof t}`);if(typeof e=="string"&&typeof t=="string")return e+t;if(Array.isArray(e)&&Array.isArray(t))return 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.
5
- Left ${e}
6
- Right ${t}`)}var et=class extends Le{static isInstance(e){return super.isInstance(e)&&"concat"in e&&typeof e.concat=="function"}};function zr(e){return typeof e.role=="string"}function Re(e){return typeof e?._getType=="function"}function ga(e){return Re(e)&&typeof e.concat=="function"}function Hr(e,t){return ee(e??{},t??{})}function Gr(e,t){const n={};return(e?.audio!==void 0||t?.audio!==void 0)&&(n.audio=(e?.audio??0)+(t?.audio??0)),(e?.image!==void 0||t?.image!==void 0)&&(n.image=(e?.image??0)+(t?.image??0)),(e?.video!==void 0||t?.video!==void 0)&&(n.video=(e?.video??0)+(t?.video??0)),(e?.document!==void 0||t?.document!==void 0)&&(n.document=(e?.document??0)+(t?.document??0)),(e?.text!==void 0||t?.text!==void 0)&&(n.text=(e?.text??0)+(t?.text??0)),n}function lo(e,t){const n={...Gr(e,t)};return(e?.cache_read!==void 0||t?.cache_read!==void 0)&&(n.cache_read=(e?.cache_read??0)+(t?.cache_read??0)),(e?.cache_creation!==void 0||t?.cache_creation!==void 0)&&(n.cache_creation=(e?.cache_creation??0)+(t?.cache_creation??0)),n}function uo(e,t){const n={...Gr(e,t)};return(e?.reasoning!==void 0||t?.reasoning!==void 0)&&(n.reasoning=(e?.reasoning??0)+(t?.reasoning??0)),n}function Vr(e,t){return{input_tokens:(e?.input_tokens??0)+(t?.input_tokens??0),output_tokens:(e?.output_tokens??0)+(t?.output_tokens??0),total_tokens:(e?.total_tokens??0)+(t?.total_tokens??0),input_token_details:lo(e?.input_token_details,t?.input_token_details),output_token_details:uo(e?.output_token_details,t?.output_token_details)}}var ho={};F(ho,{ToolMessage:()=>pt,ToolMessageChunk:()=>tn,defaultToolCallParser:()=>_a,isDirectToolOutput:()=>Zr,isToolMessage:()=>qr,isToolMessageChunk:()=>Jr});function Zr(e){return e!=null&&typeof e=="object"&&"lc_direct_tool_output"in e&&e.lc_direct_tool_output===!0}var pt=class extends Le{static lc_name(){return"ToolMessage"}get lc_aliases(){return{tool_call_id:"tool_call_id"}}lc_direct_tool_output=!0;type="tool";status;tool_call_id;metadata;artifact;constructor(e,t,n){const a=typeof e=="string"||Array.isArray(e)?{content:e,name:n,tool_call_id:t}:e;super(a),this.tool_call_id=a.tool_call_id,this.artifact=a.artifact,this.status=a.status,this.metadata=a.metadata}static isInstance(e){return super.isInstance(e)&&e.type==="tool"}get _printableFields(){return{...super._printableFields,tool_call_id:this.tool_call_id,artifact:this.artifact}}},tn=class extends et{type="tool";tool_call_id;status;artifact;constructor(e){super(e),this.tool_call_id=e.tool_call_id,this.artifact=e.artifact,this.status=e.status}static lc_name(){return"ToolMessageChunk"}concat(e){const t=this.constructor;return new t({content:Xe(this.content,e.content),additional_kwargs:ee(this.additional_kwargs,e.additional_kwargs),response_metadata:ee(this.response_metadata,e.response_metadata),artifact:Br(this.artifact,e.artifact),tool_call_id:this.tool_call_id,id:this.id??e.id,status:Ur(this.status,e.status)})}get _printableFields(){return{...super._printableFields,tool_call_id:this.tool_call_id,artifact:this.artifact}}};function _a(e){const t=[],n=[];for(const a of e)if(a.function){const r=a.function.name;try{const s=JSON.parse(a.function.arguments);t.push({name:r||"",args:s||{},id:a.id})}catch{n.push({name:r,args:a.function.arguments,id:a.id,error:"Malformed args."})}}else continue;return[t,n]}function qr(e){return typeof e=="object"&&e!==null&&"getType"in e&&typeof e.getType=="function"&&e.getType()==="tool"}function Jr(e){return e._getType()==="tool"}function jn(e,t=ya){e=e.trim();const n=e.indexOf("```");if(n===-1)return t(e);let a=e.substring(n+3);a.startsWith(`json
7
- `)?a=a.substring(5):a.startsWith("json")?a=a.substring(4):a.startsWith(`
8
- `)&&(a=a.substring(1));const r=a.indexOf("```");let s=a;return r!==-1&&(s=a.substring(0,r)),t(s.trim())}function ya(e){if(typeof e>"u")return null;try{return JSON.parse(e)}catch{}let t="";const n=[];let a=!1,r=!1;for(let s of e){if(a)s==='"'&&!r?a=!1:s===`
9
- `&&!r?s="\\n":s==="\\"?r=!r:r=!1;else if(s==='"')a=!0,r=!1;else if(s==="{")n.push("}");else if(s==="[")n.push("]");else if(s==="}"||s==="]")if(n&&n[n.length-1]===s)n.pop();else return null;t+=s}a&&(t+='"');for(let s=n.length-1;s>=0;s-=1)t+=n[s];try{return JSON.parse(t)}catch{return null}}function wa(e){switch(e){case"csv":return"text/csv";case"doc":return"application/vnd.openxmlformats-officedocument.wordprocessingml.document";case"docx":return"application/vnd.openxmlformats-officedocument.wordprocessingml.document";case"html":return"text/html";case"md":return"text/markdown";case"pdf":return"application/pdf";case"txt":return"text/plain";case"xls":return"application/vnd.ms-excel";case"xlsx":return"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";case"gif":return"image/gif";case"jpeg":return"image/jpeg";case"jpg":return"image/jpeg";case"png":return"image/png";case"webp":return"image/webp";case"flv":return"video/flv";case"mkv":return"video/mkv";case"mov":return"video/mov";case"mp4":return"video/mp4";case"mpeg":return"video/mpeg";case"mpg":return"video/mpg";case"three_gp":return"video/three_gp";case"webm":return"video/webm";case"wmv":return"video/wmv";default:return"application/octet-stream"}}function po(e){if(k(e.document)&&k(e.document.source)){const t=k(e.document)&&S(e.document.format)?e.document.format:"",n=wa(t);if(k(e.document.source)){if(k(e.document.source.s3Location)&&S(e.document.source.s3Location.uri))return{type:"file",mimeType:n,fileId:e.document.source.s3Location.uri};if(fa(e.document.source.bytes))return{type:"file",mimeType:n,data:e.document.source.bytes};if(S(e.document.source.text))return{type:"file",mimeType:n,data:Buffer.from(e.document.source.text).toString("base64")};if(Ie(e.document.source.content)){const a=e.document.source.content.reduce((r,s)=>k(s)&&S(s.text)?r+s.text:r,"");return{type:"file",mimeType:n,data:a}}}}return{type:"non_standard",value:e}}function fo(e){if(C(e,"image")&&k(e.image)){const t=k(e.image)&&S(e.image.format)?e.image.format:"",n=wa(t);if(k(e.image.source)){if(k(e.image.source.s3Location)&&S(e.image.source.s3Location.uri))return{type:"image",mimeType:n,fileId:e.image.source.s3Location.uri};if(fa(e.image.source.bytes))return{type:"image",mimeType:n,data:e.image.source.bytes}}}return{type:"non_standard",value:e}}function mo(e){if(C(e,"video")&&k(e.video)){const t=k(e.video)&&S(e.video.format)?e.video.format:"",n=wa(t);if(k(e.video.source)){if(k(e.video.source.s3Location)&&S(e.video.source.s3Location.uri))return{type:"video",mimeType:n,fileId:e.video.source.s3Location.uri};if(fa(e.video.source.bytes))return{type:"video",mimeType:n,data:e.video.source.bytes}}}return{type:"non_standard",value:e}}function Ka(e){function*t(){const n=typeof e.content=="string"?[{type:"text",text:e.content}]:e.content;for(const a of n){if(C(a,"cache_point")){yield{type:"non_standard",value:a};continue}else if(C(a,"citations_content")&&k(a.citationsContent)){const r=Ie(a.citationsContent.content)?a.citationsContent.content.reduce((i,o)=>k(o)&&S(o.text)?i+o.text:i,""):"",s=Ie(a.citationsContent.citations)?a.citationsContent.citations.reduce((i,o)=>{if(k(o)){const c=Ie(o.sourceContent)?o.sourceContent.reduce((d,p)=>k(p)&&S(p.text)?d+p.text:d,""):"",l=vt(()=>{if(k(o.location)){const d=o.location.documentChar||o.location.documentPage||o.location.documentChunk;if(k(d))return{source:we(d.documentIndex)?d.documentIndex.toString():void 0,startIndex:we(d.start)?d.start:void 0,endIndex:we(d.end)?d.end:void 0}}return{}});i.push({type:"citation",citedText:c,...l})}return i},[]):[];yield{type:"text",text:r,annotations:s};continue}else if(C(a,"document")&&k(a.document)){yield po(a);continue}else if(C(a,"guard_content")){yield{type:"non_standard",value:a};continue}else if(C(a,"image")&&k(a.image)){yield fo(a);continue}else if(C(a,"reasoning_content")&&S(a.reasoningText)){yield{type:"reasoning",reasoning:a.reasoningText};continue}else if(C(a,"text")&&S(a.text)){yield{type:"text",text:a.text};continue}else if(C(a,"tool_result")){yield{type:"non_standard",value:a};continue}else{if(C(a,"tool_call"))continue;if(C(a,"video")&&k(a.video)){yield mo(a);continue}}yield{type:"non_standard",value:a}}}return Array.from(t())}const go={translateContent:Ka,translateContentChunk:Ka};function Ya(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)){yield{type:"text",text:a.text};continue}else if(C(a,"inlineData")&&k(a.inlineData)&&S(a.inlineData.mimeType)&&S(a.inlineData.data)){yield{type:"file",mimeType:a.inlineData.mimeType,data:a.inlineData.data};continue}else if(C(a,"functionCall")&&k(a.functionCall)&&S(a.functionCall.name)&&k(a.functionCall.args)){yield{type:"tool_call",id:e.id,name:a.functionCall.name,args:a.functionCall.args};continue}else if(C(a,"functionResponse")){yield{type:"non_standard",value:a};continue}else if(C(a,"fileData")&&k(a.fileData)&&S(a.fileData.mimeType)&&S(a.fileData.fileUri)){yield{type:"file",mimeType:a.fileData.mimeType,fileId:a.fileData.fileUri};continue}else if(C(a,"executableCode")){yield{type:"non_standard",value:a};continue}else if(C(a,"codeExecutionResult")){yield{type:"non_standard",value:a};continue}yield{type:"non_standard",value:a}}}return Array.from(t())}const _o={translateContent:Ya,translateContentChunk:Ya};function Qa(e){function*t(){const n=typeof e.content=="string"?[{type:"text",text:e.content}]:e.content;for(const a of n){if(C(a,"reasoning")&&S(a.reasoning)){const r=vt(()=>{const s=n.indexOf(a);if(Ie(e.additional_kwargs?.signatures)&&s>=0)return e.additional_kwargs.signatures.at(s)});S(r)?yield{type:"reasoning",reasoning:a.reasoning,signature:r}:yield{type:"reasoning",reasoning:a.reasoning};continue}else if(C(a,"text")&&S(a.text)){yield{type:"text",text:a.text};continue}else if(C(a,"image_url")){if(S(a.image_url))if(a.image_url.startsWith("data:")){const r=/^data:([^;]+);base64,(.+)$/,s=a.image_url.match(r);s?yield{type:"image",data:s[2],mimeType:s[1]}:yield{type:"image",url:a.image_url}}else yield{type:"image",url:a.image_url};continue}else if(C(a,"media")&&S(a.mimeType)&&S(a.data)){yield{type:"file",mimeType:a.mimeType,data:a.data};continue}yield{type:"non_standard",value:a}}}return Array.from(t())}const yo={translateContent:Qa,translateContentChunk:Qa};globalThis.lc_block_translators_registry??=new Map([["anthropic",Ji],["bedrock-converse",go],["google-genai",_o],["google-vertexai",yo],["openai",ro]]);function Wr(e){return globalThis.lc_block_translators_registry.get(e)}var Be=class extends Le{type="ai";tool_calls=[];invalid_tool_calls=[];usage_metadata;get lc_aliases(){return{...super.lc_aliases,tool_calls:"tool_calls",invalid_tool_calls:"invalid_tool_calls"}}constructor(e){let t;if(typeof e=="string"||Array.isArray(e))t={content:e,tool_calls:[],invalid_tool_calls:[],additional_kwargs:{}};else{t=e;const n=t.additional_kwargs?.tool_calls,a=t.tool_calls;n!=null&&n.length>0&&(a===void 0||a.length===0)&&console.warn(["New LangChain packages are available that more efficiently handle",`tool calling.
10
-
11
- Please upgrade your packages to versions that set`,"message tool calls. e.g., `pnpm install @langchain/anthropic`,","pnpm install @langchain/openai`, etc."].join(" "));try{if(n!=null&&a===void 0){const[r,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
-
13
- Troubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${t}/
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
-
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.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
- Context: ${t}`:""}`),Lt("[Unserializable]");le("SUPPRESS_CIRCULAR_JSON_WARNINGS")!=="true"&&console.warn(`[WARNING]: LangSmith received circular JSON. This will decrease tracer performance. ${t?`
19
- Context: ${t}`:""}`),typeof r>"u"&&(r=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
- === LangSmith Server Configuration ===
21
- `+JSON.stringify(n,null,2)+`
22
- `),n}async _ensureServerInfo(){return this._getServerInfoPromise===void 0&&(this._getServerInfoPromise=(async()=>{if(this._serverInfo===void 0)try{this._serverInfo=await this._getServerInfo()}catch(t){console.warn(`[LANGSMITH]: Failed to fetch info on supported operations. Falling back to batch operations and default limits. Info: ${t.status??"Unspecified status code"} ${t.message}`)}return this._serverInfo??{}})()),this._getServerInfoPromise.then(t=>(this._serverInfo===void 0&&(this._getServerInfoPromise=void 0),t))}async _getSettings(){return this.settings||(this.settings=this._get("/settings")),await this.settings}async flush(){const t=await this._getBatchSizeLimitBytes(),n=await this._getBatchSizeLimit();await this.drainAutoBatchQueue({batchSizeLimitBytes:t,batchSizeLimit:n})}_cloneCurrentOTELContext(){const t=_s(),n=Cc();if(this.langSmithToOTELTranslator!==void 0){const a=t.getActiveSpan();if(a)return t.setSpan(n.active(),a)}}async createRun(t,n){if(!this._filterForSampling([t]).length)return;const a={...this.headers,"Content-Type":"application/json"},r=t.project_name;delete t.project_name;const s=await this.prepareRunCreateOrUpdateInputs({session_name:r,...t,start_time:t.start_time??Date.now()});if(this.autoBatchTracing&&s.trace_id!==void 0&&s.dotted_order!==void 0){const c=this._cloneCurrentOTELContext();this.processRunOperation({action:"create",item:s,otelContext:c,apiKey:n?.apiKey,apiUrl:n?.apiUrl}).catch(console.error);return}const i=ur(s,this.cachedLSEnvVarsForMetadata);n?.apiKey!==void 0&&(a["x-api-key"]=n.apiKey),n?.workspaceId!==void 0&&(a["x-tenant-id"]=n.workspaceId);const o=de(i,`Creating run with id: ${i.id}`);await this.caller.call(async()=>{const c=await this._fetch(`${n?.apiUrl??this.apiUrl}/runs`,{method:"POST",headers:a,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await O(c,"create run",!0),c})}async batchIngestRuns({runCreates:t,runUpdates:n},a){if(t===void 0&&n===void 0)return;let r=await Promise.all(t?.map(c=>this.prepareRunCreateOrUpdateInputs(c))??[]),s=await Promise.all(n?.map(c=>this.prepareRunCreateOrUpdateInputs(c))??[]);if(r.length>0&&s.length>0){const c=r.reduce((d,p)=>(p.id&&(d[p.id]=p),d),{}),l=[];for(const d of s)d.id!==void 0&&c[d.id]?c[d.id]={...c[d.id],...d}:l.push(d);r=Object.values(c),s=l}const i={post:r,patch:s};if(!i.post.length&&!i.patch.length)return;const o={post:[],patch:[]};for(const c of["post","patch"]){const l=c,d=i[l].reverse();let p=d.pop();for(;p!==void 0;)o[l].push(p),p=d.pop()}if(o.post.length>0||o.patch.length>0){const c=o.post.map(l=>l.id).concat(o.patch.map(l=>l.id)).join(",");await this._postBatchIngestRuns(de(o,`Ingesting runs with ids: ${c}`),a)}}async _postBatchIngestRuns(t,n){const a={...this.headers,"Content-Type":"application/json",Accept:"application/json"};n?.apiKey!==void 0&&(a["x-api-key"]=n.apiKey),await this.batchIngestCaller.call(async()=>{const r=await this._fetch(`${n?.apiUrl??this.apiUrl}/runs/batch`,{method:"POST",headers:a,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:t});return await O(r,"batch create run",!0),r})}async multipartIngestRuns({runCreates:t,runUpdates:n},a){if(t===void 0&&n===void 0)return;const r={};let s=[];for(const p of t??[]){const f=await this.prepareRunCreateOrUpdateInputs(p);f.id!==void 0&&f.attachments!==void 0&&(r[f.id]=f.attachments),delete f.attachments,s.push(f)}let i=[];for(const p of n??[])i.push(await this.prepareRunCreateOrUpdateInputs(p));if(s.find(p=>p.trace_id===void 0||p.dotted_order===void 0)!==void 0)throw new Error('Multipart ingest requires "trace_id" and "dotted_order" to be set when creating a run');if(i.find(p=>p.trace_id===void 0||p.dotted_order===void 0)!==void 0)throw new Error('Multipart ingest requires "trace_id" and "dotted_order" to be set when updating a run');if(s.length>0&&i.length>0){const p=s.reduce((m,y)=>(y.id&&(m[y.id]=y),m),{}),f=[];for(const m of i)m.id!==void 0&&p[m.id]?p[m.id]={...p[m.id],...m}:f.push(m);s=Object.values(p),i=f}if(s.length===0&&i.length===0)return;const l=[],d=[];for(const[p,f]of[["post",s],["patch",i]])for(const m of f){const{inputs:y,outputs:b,events:T,extra:v,error:I,serialized:E,attachments:x,...N}=m,M={inputs:y,outputs:b,events:T,extra:v,error:I,serialized:E},B=de(N,`Serializing for multipart ingestion of run with id: ${N.id}`);d.push({name:`${p}.${N.id}`,payload:new Blob([B],{type:`application/json; length=${B.length}`})});for(const[g,te]of Object.entries(M)){if(te===void 0)continue;const ne=de(te,`Serializing ${g} for multipart ingestion of run with id: ${N.id}`);d.push({name:`${p}.${N.id}.${g}`,payload:new Blob([ne],{type:`application/json; length=${ne.length}`})})}if(N.id!==void 0){const g=r[N.id];if(g){delete r[N.id];for(const[te,ne]of Object.entries(g)){let z,Se;if(Array.isArray(ne)?[z,Se]=ne:(z=ne.mimeType,Se=ne.data),te.includes(".")){console.warn(`Skipping attachment '${te}' for run ${N.id}: Invalid attachment name. Attachment names must not contain periods ('.'). Please rename the attachment and try again.`);continue}d.push({name:`attachment.${N.id}.${te}`,payload:new Blob([Se],{type:`${z}; length=${Se.byteLength}`})})}}}l.push(`trace=${N.trace_id},id=${N.id}`)}await this._sendMultipartRequest(d,l.join("; "),a)}async _createNodeFetchBody(t,n){const a=[];for(const i of t)a.push(new Blob([`--${n}\r
23
- `])),a.push(new Blob([`Content-Disposition: form-data; name="${i.name}"\r
24
- `,`Content-Type: ${i.payload.type}\r
25
- \r
26
- `])),a.push(i.payload),a.push(new Blob([`\r
27
- `]));return a.push(new Blob([`--${n}--\r
28
- `])),await new Blob(a).arrayBuffer()}async _createMultipartStream(t,n){const a=new TextEncoder;return new ReadableStream({async start(s){const i=async o=>{typeof o=="string"?s.enqueue(a.encode(o)):s.enqueue(o)};for(const o of t){await i(`--${n}\r
29
- `),await i(`Content-Disposition: form-data; name="${o.name}"\r
30
- `),await i(`Content-Type: ${o.payload.type}\r
31
- \r
32
- `);const l=o.payload.stream().getReader();try{let d;for(;!(d=await l.read()).done;)s.enqueue(d.value)}finally{l.releaseLock()}await i(`\r
33
- `)}await i(`--${n}--\r
34
- `),s.close()}})}async _sendMultipartRequest(t,n,a){const r="----LangSmithFormBoundary"+Math.random().toString(36).slice(2),s=fc(),i=()=>this._createNodeFetchBody(t,r),o=()=>this._createMultipartStream(t,r),c=async l=>this.batchIngestCaller.call(async()=>{const d=await l(),p={...this.headers,"Content-Type":`multipart/form-data; boundary=${r}`};a?.apiKey!==void 0&&(p["x-api-key"]=a.apiKey);let f=d;a?.useGzip&&typeof d=="object"&&"pipeThrough"in d&&(f=d.pipeThrough(new CompressionStream("gzip")),p["Content-Encoding"]="gzip");const m=await this._fetch(`${a?.apiUrl??this.apiUrl}/runs/multipart`,{method:"POST",headers:p,body:f,duplex:"half",signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await O(m,"Failed to send multipart request",!0),m});try{let l,d=!1;!s&&!this.multipartStreamingDisabled&&ps()!=="bun"?(d=!0,l=await c(o)):l=await c(i),(!this.multipartStreamingDisabled||d)&&l.status===422&&(a?.apiUrl??this.apiUrl)!==hr&&(console.warn(`Streaming multipart upload to ${a?.apiUrl??this.apiUrl}/runs/multipart failed. This usually means the host does not support chunked uploads. Retrying with a buffered upload for operation "${n}".`),this.multipartStreamingDisabled=!0,l=await c(i))}catch(l){console.warn(`${l.message.trim()}
35
-
36
- Context: ${n}`)}}async updateRun(t,n,a){R(t),n.inputs&&(n.inputs=await this.processInputs(n.inputs)),n.outputs&&(n.outputs=await this.processOutputs(n.outputs));const r={...n,id:t};if(!this._filterForSampling([r],!0).length)return;if(this.autoBatchTracing&&r.trace_id!==void 0&&r.dotted_order!==void 0){const o=this._cloneCurrentOTELContext();if(n.end_time!==void 0&&r.parent_run_id===void 0&&this.blockOnRootRunFinalization&&!this.manualFlushMode){await this.processRunOperation({action:"update",item:r,otelContext:o,apiKey:a?.apiKey,apiUrl:a?.apiUrl}).catch(console.error);return}else this.processRunOperation({action:"update",item:r,otelContext:o,apiKey:a?.apiKey,apiUrl:a?.apiUrl}).catch(console.error);return}const s={...this.headers,"Content-Type":"application/json"};a?.apiKey!==void 0&&(s["x-api-key"]=a.apiKey),a?.workspaceId!==void 0&&(s["x-tenant-id"]=a.workspaceId);const i=de(n,`Serializing payload to update run with id: ${t}`);await this.caller.call(async()=>{const o=await this._fetch(`${a?.apiUrl??this.apiUrl}/runs/${t}`,{method:"PATCH",headers:s,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await O(o,"update run",!0),o})}async readRun(t,{loadChildRuns:n}={loadChildRuns:!1}){R(t);let a=await this._get(`/runs/${t}`);return n&&(a=await this._loadChildRuns(a)),a}async getRunUrl({runId:t,run:n,projectOpts:a}){if(n!==void 0){let r;n.session_id?r=n.session_id:a?.projectName?r=(await this.readProject({projectName:a?.projectName})).id:a?.projectId?r=a?.projectId:r=(await this.readProject({projectName:le("PROJECT")||"default"})).id;const s=await this._getTenantId();return`${this.getHostUrl()}/o/${s}/projects/p/${r}/r/${n.id}?poll=true`}else if(t!==void 0){const r=await this.readRun(t);if(!r.app_path)throw new Error(`Run ${t} has no app_path`);return`${this.getHostUrl()}${r.app_path}`}else throw new Error("Must provide either runId or run")}async _loadChildRuns(t){const n=await Vc(this.listRuns({isRoot:!1,projectId:t.session_id,traceId:t.trace_id})),a={},r={};n.sort((s,i)=>(s?.dotted_order??"").localeCompare(i?.dotted_order??""));for(const s of n){if(s.parent_run_id===null||s.parent_run_id===void 0)throw new Error(`Child run ${s.id} has no parent`);s.dotted_order?.startsWith(t.dotted_order??"")&&s.id!==t.id&&(s.parent_run_id in a||(a[s.parent_run_id]=[]),a[s.parent_run_id].push(s),r[s.id]=s)}t.child_runs=a[t.id]||[];for(const s in a)s!==t.id&&(r[s].child_runs=a[s]);return t}async*listRuns(t){const{projectId:n,projectName:a,parentRunId:r,traceId:s,referenceExampleId:i,startTime:o,executionOrder:c,isRoot:l,runType:d,error:p,id:f,query:m,filter:y,traceFilter:b,treeFilter:T,limit:v,select:I,order:E}=t;let x=[];if(n&&(x=Array.isArray(n)?n:[n]),a){const g=Array.isArray(a)?a:[a],te=await Promise.all(g.map(ne=>this.readProject({projectName:ne}).then(z=>z.id)));x.push(...te)}const N=["app_path","completion_cost","completion_tokens","dotted_order","end_time","error","events","extra","feedback_stats","first_token_time","id","inputs","name","outputs","parent_run_id","parent_run_ids","prompt_cost","prompt_tokens","reference_example_id","run_type","session_id","start_time","status","tags","total_cost","total_tokens","trace_id"],M={session:x.length?x:null,run_type:d,reference_example:i,query:m,filter:y,trace_filter:b,tree_filter:T,execution_order:c,parent_run:r,start_time:o?o.toISOString():null,error:p,id:f,limit:v,trace:s,select:I||N,is_root:l,order:E};M.select.includes("child_run_ids")&&Un("Deprecated: 'child_run_ids' in the listRuns select parameter is deprecated and will be removed in a future version.");let B=0;for await(const g of this._getCursorPaginatedList("/runs/query",M))if(v){if(B>=v)break;if(g.length+B>v){yield*g.slice(0,v-B);break}B+=g.length,yield*g}else yield*g}async*listGroupRuns(t){const{projectId:n,projectName:a,groupBy:r,filter:s,startTime:i,endTime:o,limit:c,offset:l}=t,p={session_id:n||(await this.readProject({projectName:a})).id,group_by:r,filter:s,start_time:i?i.toISOString():null,end_time:o?o.toISOString():null,limit:Number(c)||100};let f=Number(l)||0;const m="/runs/group",y=`${this.apiUrl}${m}`;for(;;){const b={...p,offset:f},T=Object.fromEntries(Object.entries(b).filter(([M,B])=>B!==void 0)),v=JSON.stringify(T),E=await(await this.caller.call(async()=>{const M=await this._fetch(y,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:v});return await O(M,`Failed to fetch ${m}`),M})).json(),{groups:x,total:N}=E;if(x.length===0)break;for(const M of x)yield M;if(f+=x.length,f>=N)break}}async getRunStats({id:t,trace:n,parentRun:a,runType:r,projectNames:s,projectIds:i,referenceExampleIds:o,startTime:c,endTime:l,error:d,query:p,filter:f,traceFilter:m,treeFilter:y,isRoot:b,dataSourceType:T}){let v=i||[];s&&(v=[...i||[],...await Promise.all(s.map(B=>this.readProject({projectName:B}).then(g=>g.id)))]);const E=Object.fromEntries(Object.entries({id:t,trace:n,parent_run:a,run_type:r,session:v,reference_example:o,start_time:c,end_time:l,error:d,query:p,filter:f,trace_filter:m,tree_filter:y,is_root:b,data_source_type:T}).filter(([B,g])=>g!==void 0)),x=JSON.stringify(E);return await(await this.caller.call(async()=>{const B=await this._fetch(`${this.apiUrl}/runs/stats`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:x});return await O(B,"get run stats"),B})).json()}async shareRun(t,{shareId:n}={}){const a={run_id:t,share_token:n||se()};R(t);const r=JSON.stringify(a),i=await(await this.caller.call(async()=>{const o=await this._fetch(`${this.apiUrl}/runs/${t}/share`,{method:"PUT",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:r});return await O(o,"share run"),o})).json();if(i===null||!("share_token"in i))throw new Error("Invalid response from server");return`${this.getHostUrl()}/public/${i.share_token}/r`}async unshareRun(t){R(t),await this.caller.call(async()=>{const n=await this._fetch(`${this.apiUrl}/runs/${t}/share`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await O(n,"unshare run",!0),n})}async readRunSharedLink(t){R(t);const a=await(await this.caller.call(async()=>{const r=await this._fetch(`${this.apiUrl}/runs/${t}/share`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await O(r,"read run shared link"),r})).json();if(!(a===null||!("share_token"in a)))return`${this.getHostUrl()}/public/${a.share_token}/r`}async listSharedRuns(t,{runIds:n}={}){const a=new URLSearchParams({share_token:t});if(n!==void 0)for(const i of n)a.append("id",i);return R(t),await(await this.caller.call(async()=>{const i=await this._fetch(`${this.apiUrl}/public/${t}/runs${a}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await O(i,"list shared runs"),i})).json()}async readDatasetSharedSchema(t,n){if(!t&&!n)throw new Error("Either datasetId or datasetName must be given");t||(t=(await this.readDataset({datasetName:n})).id),R(t);const r=await(await this.caller.call(async()=>{const s=await this._fetch(`${this.apiUrl}/datasets/${t}/share`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await O(s,"read dataset shared schema"),s})).json();return r.url=`${this.getHostUrl()}/public/${r.share_token}/d`,r}async shareDataset(t,n){if(!t&&!n)throw new Error("Either datasetId or datasetName must be given");t||(t=(await this.readDataset({datasetName:n})).id);const a={dataset_id:t};R(t);const r=JSON.stringify(a),i=await(await this.caller.call(async()=>{const o=await this._fetch(`${this.apiUrl}/datasets/${t}/share`,{method:"PUT",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:r});return await O(o,"share dataset"),o})).json();return i.url=`${this.getHostUrl()}/public/${i.share_token}/d`,i}async unshareDataset(t){R(t),await this.caller.call(async()=>{const n=await this._fetch(`${this.apiUrl}/datasets/${t}/share`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await O(n,"unshare dataset",!0),n})}async readSharedDataset(t){return R(t),await(await this.caller.call(async()=>{const r=await this._fetch(`${this.apiUrl}/public/${t}/datasets`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await O(r,"read shared dataset"),r})).json()}async listSharedExamples(t,n){const a={};n?.exampleIds&&(a.id=n.exampleIds);const r=new URLSearchParams;Object.entries(a).forEach(([o,c])=>{Array.isArray(c)?c.forEach(l=>r.append(o,l)):r.append(o,c)});const s=await this.caller.call(async()=>{const o=await this._fetch(`${this.apiUrl}/public/${t}/examples?${r.toString()}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await O(o,"list shared examples"),o}),i=await s.json();if(!s.ok)throw"detail"in i?new Error(`Failed to list shared examples.
37
- Status: ${s.status}
38
- Message: ${Array.isArray(i.detail)?i.detail.join(`
39
- `):"Unspecified error"}`):new Error(`Failed to list shared examples: ${s.status} ${s.statusText}`);return i.map(o=>({...o,_hostUrl:this.getHostUrl()}))}async createProject({projectName:t,description:n=null,metadata:a=null,upsert:r=!1,projectExtra:s=null,referenceDatasetId:i=null}){const o=r?"?upsert=true":"",c=`${this.apiUrl}/sessions${o}`,l=s||{};a&&(l.metadata=a);const d={name:t,extra:l,description:n};i!==null&&(d.reference_dataset_id=i);const p=JSON.stringify(d);return await(await this.caller.call(async()=>{const y=await this._fetch(c,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:p});return await O(y,"create project"),y})).json()}async updateProject(t,{name:n=null,description:a=null,metadata:r=null,projectExtra:s=null,endTime:i=null}){const o=`${this.apiUrl}/sessions/${t}`;let c=s;r&&(c={...c||{},metadata:r});const l=JSON.stringify({name:n,extra:c,description:a,end_time:i?new Date(i).toISOString():null});return await(await this.caller.call(async()=>{const f=await this._fetch(o,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:l});return await O(f,"update project"),f})).json()}async hasProject({projectId:t,projectName:n}){let a="/sessions";const r=new URLSearchParams;if(t!==void 0&&n!==void 0)throw new Error("Must provide either projectName or projectId, not both");if(t!==void 0)R(t),a+=`/${t}`;else if(n!==void 0)r.append("name",n);else throw new Error("Must provide projectName or projectId");const s=await this.caller.call(async()=>{const i=await this._fetch(`${this.apiUrl}${a}?${r}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await O(i,"has project"),i});try{const i=await s.json();return s.ok?Array.isArray(i)?i.length>0:!0:!1}catch{return!1}}async readProject({projectId:t,projectName:n,includeStats:a}){let r="/sessions";const s=new URLSearchParams;if(t!==void 0&&n!==void 0)throw new Error("Must provide either projectName or projectId, not both");if(t!==void 0)R(t),r+=`/${t}`;else if(n!==void 0)s.append("name",n);else throw new Error("Must provide projectName or projectId");a!==void 0&&s.append("include_stats",a.toString());const i=await this._get(r,s);let o;if(Array.isArray(i)){if(i.length===0)throw new Error(`Project[id=${t}, name=${n}] not found`);o=i[0]}else o=i;return o}async getProjectUrl({projectId:t,projectName:n}){if(t===void 0&&n===void 0)throw new Error("Must provide either projectName or projectId");const a=await this.readProject({projectId:t,projectName:n}),r=await this._getTenantId();return`${this.getHostUrl()}/o/${r}/projects/p/${a.id}`}async getDatasetUrl({datasetId:t,datasetName:n}){if(t===void 0&&n===void 0)throw new Error("Must provide either datasetName or datasetId");const a=await this.readDataset({datasetId:t,datasetName:n}),r=await this._getTenantId();return`${this.getHostUrl()}/o/${r}/datasets/${a.id}`}async _getTenantId(){if(this._tenantId!==null)return this._tenantId;const t=new URLSearchParams({limit:"1"});for await(const n of this._getPaginated("/sessions",t))return this._tenantId=n[0].tenant_id,n[0].tenant_id;throw new Error("No projects found to resolve tenant.")}async*listProjects({projectIds:t,name:n,nameContains:a,referenceDatasetId:r,referenceDatasetName:s,includeStats:i,datasetVersion:o,referenceFree:c,metadata:l}={}){const d=new URLSearchParams;if(t!==void 0)for(const p of t)d.append("id",p);if(n!==void 0&&d.append("name",n),a!==void 0&&d.append("name_contains",a),r!==void 0)d.append("reference_dataset",r);else if(s!==void 0){const p=await this.readDataset({datasetName:s});d.append("reference_dataset",p.id)}i!==void 0&&d.append("include_stats",i.toString()),o!==void 0&&d.append("dataset_version",o),c!==void 0&&d.append("reference_free",c.toString()),l!==void 0&&d.append("metadata",JSON.stringify(l));for await(const p of this._getPaginated("/sessions",d))yield*p}async deleteProject({projectId:t,projectName:n}){let a;if(t===void 0&&n===void 0)throw new Error("Must provide projectName or projectId");if(t!==void 0&&n!==void 0)throw new Error("Must provide either projectName or projectId, not both");t===void 0?a=(await this.readProject({projectName:n})).id:a=t,R(a),await this.caller.call(async()=>{const r=await this._fetch(`${this.apiUrl}/sessions/${a}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await O(r,`delete session ${a} (${n})`,!0),r})}async uploadCsv({csvFile:t,fileName:n,inputKeys:a,outputKeys:r,description:s,dataType:i,name:o}){const c=`${this.apiUrl}/datasets/upload`,l=new FormData;return l.append("file",t,n),a.forEach(f=>{l.append("input_keys",f)}),r.forEach(f=>{l.append("output_keys",f)}),s&&l.append("description",s),i&&l.append("data_type",i),o&&l.append("name",o),await(await this.caller.call(async()=>{const f=await this._fetch(c,{method:"POST",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:l});return await O(f,"upload CSV"),f})).json()}async createDataset(t,{description:n,dataType:a,inputsSchema:r,outputsSchema:s,metadata:i}={}){const o={name:t,description:n,extra:i?{metadata:i}:void 0};a&&(o.data_type=a),r&&(o.inputs_schema_definition=r),s&&(o.outputs_schema_definition=s);const c=JSON.stringify(o);return await(await this.caller.call(async()=>{const p=await this._fetch(`${this.apiUrl}/datasets`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await O(p,"create dataset"),p})).json()}async readDataset({datasetId:t,datasetName:n}){let a="/datasets";const r=new URLSearchParams({limit:"1"});if(t&&n)throw new Error("Must provide either datasetName or datasetId, not both");if(t)R(t),a+=`/${t}`;else if(n)r.append("name",n);else throw new Error("Must provide datasetName or datasetId");const s=await this._get(a,r);let i;if(Array.isArray(s)){if(s.length===0)throw new Error(`Dataset[id=${t}, name=${n}] not found`);i=s[0]}else i=s;return i}async hasDataset({datasetId:t,datasetName:n}){try{return await this.readDataset({datasetId:t,datasetName:n}),!0}catch(a){if(a instanceof Error&&a.message.toLocaleLowerCase().includes("not found"))return!1;throw a}}async diffDatasetVersions({datasetId:t,datasetName:n,fromVersion:a,toVersion:r}){let s=t;if(s===void 0&&n===void 0)throw new Error("Must provide either datasetName or datasetId");if(s!==void 0&&n!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");s===void 0&&(s=(await this.readDataset({datasetName:n})).id);const i=new URLSearchParams({from_version:typeof a=="string"?a:a.toISOString(),to_version:typeof r=="string"?r:r.toISOString()});return await this._get(`/datasets/${s}/versions/diff`,i)}async readDatasetOpenaiFinetuning({datasetId:t,datasetName:n}){const a="/datasets";if(t===void 0)if(n!==void 0)t=(await this.readDataset({datasetName:n})).id;else throw new Error("Must provide either datasetName or datasetId");return(await(await this._getResponse(`${a}/${t}/openai_ft`)).text()).trim().split(`
40
- `).map(o=>JSON.parse(o))}async*listDatasets({limit:t=100,offset:n=0,datasetIds:a,datasetName:r,datasetNameContains:s,metadata:i}={}){const o="/datasets",c=new URLSearchParams({limit:t.toString(),offset:n.toString()});if(a!==void 0)for(const l of a)c.append("id",l);r!==void 0&&c.append("name",r),s!==void 0&&c.append("name_contains",s),i!==void 0&&c.append("metadata",JSON.stringify(i));for await(const l of this._getPaginated(o,c))yield*l}async updateDataset(t){const{datasetId:n,datasetName:a,...r}=t;if(!n&&!a)throw new Error("Must provide either datasetName or datasetId");const s=n??(await this.readDataset({datasetName:a})).id;R(s);const i=JSON.stringify(r);return await(await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/datasets/${s}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await O(c,"update dataset"),c})).json()}async updateDatasetTag(t){const{datasetId:n,datasetName:a,asOf:r,tag:s}=t;if(!n&&!a)throw new Error("Must provide either datasetName or datasetId");const i=n??(await this.readDataset({datasetName:a})).id;R(i);const o=JSON.stringify({as_of:typeof r=="string"?r:r.toISOString(),tag:s});await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/datasets/${i}/tags`,{method:"PUT",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await O(c,"update dataset tags",!0),c})}async deleteDataset({datasetId:t,datasetName:n}){let a="/datasets",r=t;if(t!==void 0&&n!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");if(n!==void 0&&(r=(await this.readDataset({datasetName:n})).id),r!==void 0)R(r),a+=`/${r}`;else throw new Error("Must provide datasetName or datasetId");await this.caller.call(async()=>{const s=await this._fetch(this.apiUrl+a,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await O(s,`delete ${a}`,!0),s})}async indexDataset({datasetId:t,datasetName:n,tag:a}){let r=t;if(!r&&!n)throw new Error("Must provide either datasetName or datasetId");if(r&&n)throw new Error("Must provide either datasetName or datasetId, not both");r||(r=(await this.readDataset({datasetName:n})).id),R(r);const i=JSON.stringify({tag:a});await(await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/datasets/${r}/index`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await O(c,"index dataset"),c})).json()}async similarExamples(t,n,a,{filter:r}={}){const s={limit:a,inputs:t};r!==void 0&&(s.filter=r),R(n);const i=JSON.stringify(s);return(await(await this.caller.call(async()=>{const l=await this._fetch(`${this.apiUrl}/datasets/${n}/search`,{headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,method:"POST",body:i});return await O(l,"fetch similar examples"),l})).json()).examples}async createExample(t,n,a){if(pr(t)&&(n!==void 0||a!==void 0))throw new Error("Cannot provide outputs or options when using ExampleCreate object");let r=n?a?.datasetId:t.dataset_id;const s=n?a?.datasetName:t.dataset_name;if(r===void 0&&s===void 0)throw new Error("Must provide either datasetName or datasetId");if(r!==void 0&&s!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");r===void 0&&(r=(await this.readDataset({datasetName:s})).id);const i=(n?a?.createdAt:t.created_at)||new Date;let o;pr(t)?o=t:o={inputs:t,outputs:n,created_at:i?.toISOString(),id:a?.exampleId,metadata:a?.metadata,split:a?.split,source_run_id:a?.sourceRunId,use_source_run_io:a?.useSourceRunIO,use_source_run_attachments:a?.useSourceRunAttachments,attachments:a?.attachments};const c=await this._uploadExamplesMultipart(r,[o]);return await this.readExample(c.example_ids?.[0]??se())}async createExamples(t){if(Array.isArray(t)){if(t.length===0)return[];const I=t;let E=I[0].dataset_id;const x=I[0].dataset_name;if(E===void 0&&x===void 0)throw new Error("Must provide either datasetName or datasetId");if(E!==void 0&&x!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");E===void 0&&(E=(await this.readDataset({datasetName:x})).id);const N=await this._uploadExamplesMultipart(E,I);return await Promise.all(N.example_ids.map(B=>this.readExample(B)))}const{inputs:n,outputs:a,metadata:r,splits:s,sourceRunIds:i,useSourceRunIOs:o,useSourceRunAttachments:c,attachments:l,exampleIds:d,datasetId:p,datasetName:f}=t;if(n===void 0)throw new Error("Must provide inputs when using legacy parameters");let m=p;const y=f;if(m===void 0&&y===void 0)throw new Error("Must provide either datasetName or datasetId");if(m!==void 0&&y!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");m===void 0&&(m=(await this.readDataset({datasetName:y})).id);const b=n.map((I,E)=>({dataset_id:m,inputs:I,outputs:a?.[E],metadata:r?.[E],split:s?.[E],id:d?.[E],attachments:l?.[E],source_run_id:i?.[E],use_source_run_io:o?.[E],use_source_run_attachments:c?.[E]})),T=await this._uploadExamplesMultipart(m,b);return await Promise.all(T.example_ids.map(I=>this.readExample(I)))}async createLLMExample(t,n,a){return this.createExample({input:t},{output:n},a)}async createChatExample(t,n,a){const r=t.map(i=>ir(i)?or(i):i),s=ir(n)?or(n):n;return this.createExample({input:r},{output:s},a)}async readExample(t){R(t);const n=`/examples/${t}`,a=await this._get(n),{attachment_urls:r,...s}=a,i=s;return r&&(i.attachments=Object.entries(r).reduce((o,[c,l])=>(o[c.slice(11)]={presigned_url:l.presigned_url,mime_type:l.mime_type},o),{})),i}async*listExamples({datasetId:t,datasetName:n,exampleIds:a,asOf:r,splits:s,inlineS3Urls:i,metadata:o,limit:c,offset:l,filter:d,includeAttachments:p}={}){let f;if(t!==void 0&&n!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");if(t!==void 0)f=t;else if(n!==void 0)f=(await this.readDataset({datasetName:n})).id;else throw new Error("Must provide a datasetName or datasetId");const m=new URLSearchParams({dataset:f}),y=r?typeof r=="string"?r:r?.toISOString():void 0;y&&m.append("as_of",y);const b=i??!0;if(m.append("inline_s3_urls",b.toString()),a!==void 0)for(const v of a)m.append("id",v);if(s!==void 0)for(const v of s)m.append("splits",v);if(o!==void 0){const v=JSON.stringify(o);m.append("metadata",v)}c!==void 0&&m.append("limit",c.toString()),l!==void 0&&m.append("offset",l.toString()),d!==void 0&&m.append("filter",d),p===!0&&["attachment_urls","outputs","metadata"].forEach(v=>m.append("select",v));let T=0;for await(const v of this._getPaginated("/examples",m)){for(const I of v){const{attachment_urls:E,...x}=I,N=x;E&&(N.attachments=Object.entries(E).reduce((M,[B,g])=>(M[B.slice(11)]={presigned_url:g.presigned_url,mime_type:g.mime_type||void 0},M),{})),yield N,T++}if(c!==void 0&&T>=c)break}}async deleteExample(t){R(t);const n=`/examples/${t}`;await this.caller.call(async()=>{const a=await this._fetch(this.apiUrl+n,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await O(a,`delete ${n}`,!0),a})}async updateExample(t,n){let a;n?a=t:a=t.id,R(a);let r;n?r={id:a,...n}:r=t;let s;return r.dataset_id!==void 0?s=r.dataset_id:s=(await this.readExample(a)).dataset_id,this._updateExamplesMultipart(s,[r])}async updateExamples(t){let n;return t[0].dataset_id===void 0?n=(await this.readExample(t[0].id)).dataset_id:n=t[0].dataset_id,this._updateExamplesMultipart(n,t)}async readDatasetVersion({datasetId:t,datasetName:n,asOf:a,tag:r}){let s;if(t?s=t:s=(await this.readDataset({datasetName:n})).id,R(s),a&&r||!a&&!r)throw new Error("Exactly one of asOf and tag must be specified.");const i=new URLSearchParams;return a!==void 0&&i.append("as_of",typeof a=="string"?a:a.toISOString()),r!==void 0&&i.append("tag",r),await(await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/datasets/${s}/version?${i.toString()}`,{method:"GET",headers:{...this.headers},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await O(c,"read dataset version"),c})).json()}async listDatasetSplits({datasetId:t,datasetName:n,asOf:a}){let r;if(t===void 0&&n===void 0)throw new Error("Must provide dataset name or ID");if(t!==void 0&&n!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");t===void 0?r=(await this.readDataset({datasetName:n})).id:r=t,R(r);const s=new URLSearchParams,i=a?typeof a=="string"?a:a?.toISOString():void 0;return i&&s.append("as_of",i),await this._get(`/datasets/${r}/splits`,s)}async updateDatasetSplits({datasetId:t,datasetName:n,splitName:a,exampleIds:r,remove:s=!1}){let i;if(t===void 0&&n===void 0)throw new Error("Must provide dataset name or ID");if(t!==void 0&&n!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");t===void 0?i=(await this.readDataset({datasetName:n})).id:i=t,R(i);const o={split_name:a,examples:r.map(l=>(R(l),l)),remove:s},c=JSON.stringify(o);await this.caller.call(async()=>{const l=await this._fetch(`${this.apiUrl}/datasets/${i}/splits`,{method:"PUT",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await O(l,"update dataset splits",!0),l})}async evaluateRun(t,n,{sourceInfo:a,loadChildRuns:r,referenceExample:s}={loadChildRuns:!1}){Un("This method is deprecated and will be removed in future LangSmith versions, use `evaluate` from `langsmith/evaluation` instead.");let i;if(typeof t=="string")i=await this.readRun(t,{loadChildRuns:r});else if(typeof t=="object"&&"id"in t)i=t;else throw new Error(`Invalid run type: ${typeof t}`);i.reference_example_id!==null&&i.reference_example_id!==void 0&&(s=await this.readExample(i.reference_example_id));const o=await n.evaluateRun(i,s),[c,l]=await this._logEvaluationFeedback(o,i,a);return l[0]}async createFeedback(t,n,{score:a,value:r,correction:s,comment:i,sourceInfo:o,feedbackSourceType:c="api",sourceRunId:l,feedbackId:d,feedbackConfig:p,projectId:f,comparativeExperimentId:m}){if(!t&&!f)throw new Error("One of runId or projectId must be provided");if(t&&f)throw new Error("Only one of runId or projectId can be provided");const y={type:c??"api",metadata:o??{}};l!==void 0&&y?.metadata!==void 0&&!y.metadata.__run&&(y.metadata.__run={run_id:l}),y?.metadata!==void 0&&y.metadata.__run?.run_id!==void 0&&R(y.metadata.__run.run_id);const b={id:d??se(),run_id:t,key:n,score:dr(a),value:r,correction:s,comment:i,feedback_source:y,comparative_experiment_id:m,feedbackConfig:p,session_id:f},T=JSON.stringify(b),v=`${this.apiUrl}/feedback`;return await this.caller.call(async()=>{const I=await this._fetch(v,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:T});return await O(I,"create feedback",!0),I}),b}async updateFeedback(t,{score:n,value:a,correction:r,comment:s}){const i={};n!=null&&(i.score=dr(n)),a!=null&&(i.value=a),r!=null&&(i.correction=r),s!=null&&(i.comment=s),R(t);const o=JSON.stringify(i);await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/feedback/${t}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await O(c,"update feedback",!0),c})}async readFeedback(t){R(t);const n=`/feedback/${t}`;return await this._get(n)}async deleteFeedback(t){R(t);const n=`/feedback/${t}`;await this.caller.call(async()=>{const a=await this._fetch(this.apiUrl+n,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await O(a,`delete ${n}`,!0),a})}async*listFeedback({runIds:t,feedbackKeys:n,feedbackSourceTypes:a}={}){const r=new URLSearchParams;if(t)for(const s of t)R(s),r.append("run",s);if(n)for(const s of n)r.append("key",s);if(a)for(const s of a)r.append("source",s);for await(const s of this._getPaginated("/feedback",r))yield*s}async createPresignedFeedbackToken(t,n,{expiration:a,feedbackConfig:r}={}){const s={run_id:t,feedback_key:n,feedback_config:r};a?typeof a=="string"?s.expires_at=a:(a?.hours||a?.minutes||a?.days)&&(s.expires_in=a):s.expires_in={hours:3};const i=JSON.stringify(s);return await(await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/feedback/tokens`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await O(c,"create presigned feedback token"),c})).json()}async createComparativeExperiment({name:t,experimentIds:n,referenceDatasetId:a,createdAt:r,description:s,metadata:i,id:o}){if(n.length===0)throw new Error("At least one experiment is required");if(a||(a=(await this.readProject({projectId:n[0]})).reference_dataset_id),!a==null)throw new Error("A reference dataset is required");const c={id:o,name:t,experiment_ids:n,reference_dataset_id:a,description:s,created_at:(r??new Date)?.toISOString(),extra:{}};i&&(c.extra.metadata=i);const l=JSON.stringify(c);return(await this.caller.call(async()=>{const p=await this._fetch(`${this.apiUrl}/datasets/comparative`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:l});return await O(p,"create comparative experiment"),p})).json()}async*listPresignedFeedbackTokens(t){R(t);const n=new URLSearchParams({run_id:t});for await(const a of this._getPaginated("/feedback/tokens",n))yield*a}_selectEvalResults(t){let n;return"results"in t?n=t.results:Array.isArray(t)?n=t:n=[t],n}async _logEvaluationFeedback(t,n,a){const r=this._selectEvalResults(t),s=[];for(const i of r){let o=a||{};i.evaluatorInfo&&(o={...i.evaluatorInfo,...o});let c=null;i.targetRunId?c=i.targetRunId:n&&(c=n.id),s.push(await this.createFeedback(c,i.key,{score:i.score,value:i.value,comment:i.comment,correction:i.correction,sourceInfo:o,sourceRunId:i.sourceRunId,feedbackConfig:i.feedbackConfig,feedbackSourceType:"model"}))}return[r,s]}async logEvaluationFeedback(t,n,a){const[r]=await this._logEvaluationFeedback(t,n,a);return r}async*listAnnotationQueues(t={}){const{queueIds:n,name:a,nameContains:r,limit:s}=t,i=new URLSearchParams;n&&n.forEach((c,l)=>{R(c,`queueIds[${l}]`),i.append("ids",c)}),a&&i.append("name",a),r&&i.append("name_contains",r),i.append("limit",(s!==void 0?Math.min(s,100):100).toString());let o=0;for await(const c of this._getPaginated("/annotation-queues",i))if(yield*c,o++,s!==void 0&&o>=s)break}async createAnnotationQueue(t){const{name:n,description:a,queueId:r,rubricInstructions:s}=t,i={name:n,description:a,id:r||se(),rubric_instructions:s},o=JSON.stringify(Object.fromEntries(Object.entries(i).filter(([l,d])=>d!==void 0)));return(await this.caller.call(async()=>{const l=await this._fetch(`${this.apiUrl}/annotation-queues`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await O(l,"create annotation queue"),l})).json()}async readAnnotationQueue(t){return(await this.caller.call(async()=>{const a=await this._fetch(`${this.apiUrl}/annotation-queues/${R(t,"queueId")}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await O(a,"read annotation queue"),a})).json()}async updateAnnotationQueue(t,n){const{name:a,description:r,rubricInstructions:s}=n,i=JSON.stringify({name:a,description:r,rubric_instructions:s});await this.caller.call(async()=>{const o=await this._fetch(`${this.apiUrl}/annotation-queues/${R(t,"queueId")}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await O(o,"update annotation queue",!0),o})}async deleteAnnotationQueue(t){await this.caller.call(async()=>{const n=await this._fetch(`${this.apiUrl}/annotation-queues/${R(t,"queueId")}`,{method:"DELETE",headers:{...this.headers,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await O(n,"delete annotation queue",!0),n})}async addRunsToAnnotationQueue(t,n){const a=JSON.stringify(n.map((r,s)=>R(r,`runIds[${s}]`).toString()));await this.caller.call(async()=>{const r=await this._fetch(`${this.apiUrl}/annotation-queues/${R(t,"queueId")}/runs`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await O(r,"add runs to annotation queue",!0),r})}async getRunFromAnnotationQueue(t,n){const a=`/annotation-queues/${R(t,"queueId")}/run`;return(await this.caller.call(async()=>{const s=await this._fetch(`${this.apiUrl}${a}/${n}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await O(s,"get run from annotation queue"),s})).json()}async deleteRunFromAnnotationQueue(t,n){await this.caller.call(async()=>{const a=await this._fetch(`${this.apiUrl}/annotation-queues/${R(t,"queueId")}/runs/${R(n,"queueRunId")}`,{method:"DELETE",headers:{...this.headers,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await O(a,"delete run from annotation queue",!0),a})}async getSizeFromAnnotationQueue(t){return(await this.caller.call(async()=>{const a=await this._fetch(`${this.apiUrl}/annotation-queues/${R(t,"queueId")}/size`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await O(a,"get size from annotation queue"),a})).json()}async _currentTenantIsOwner(t){const n=await this._getSettings();return t=="-"||n.tenant_handle===t}async _ownerConflictError(t,n){const a=await this._getSettings();return new Error(`Cannot ${t} for another tenant.
41
-
42
- Current tenant: ${a.tenant_handle}
43
-
44
- Requested tenant: ${n}`)}async _getLatestCommitHash(t){const a=await(await this.caller.call(async()=>{const r=await this._fetch(`${this.apiUrl}/commits/${t}/?limit=1&offset=0`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await O(r,"get latest commit hash"),r})).json();if(a.commits.length!==0)return a.commits[0].commit_hash}async _likeOrUnlikePrompt(t,n){const[a,r,s]=je(t),i=JSON.stringify({like:n});return(await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/likes/${a}/${r}`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await O(c,`${n?"like":"unlike"} prompt`),c})).json()}async _getPromptUrl(t){const[n,a,r]=je(t);if(await this._currentTenantIsOwner(n)){const s=await this._getSettings();return r!=="latest"?`${this.getHostUrl()}/prompts/${a}/${r.substring(0,8)}?organizationId=${s.id}`:`${this.getHostUrl()}/prompts/${a}?organizationId=${s.id}`}else return r!=="latest"?`${this.getHostUrl()}/hub/${n}/${a}/${r.substring(0,8)}`:`${this.getHostUrl()}/hub/${n}/${a}`}async promptExists(t){return!!await this.getPrompt(t)}async likePrompt(t){return this._likeOrUnlikePrompt(t,!0)}async unlikePrompt(t){return this._likeOrUnlikePrompt(t,!1)}async*listCommits(t){for await(const n of this._getPaginated(`/commits/${t}/`,new URLSearchParams,a=>a.commits))yield*n}async*listPrompts(t){const n=new URLSearchParams;n.append("sort_field",t?.sortField??"updated_at"),n.append("sort_direction","desc"),n.append("is_archived",(!!t?.isArchived).toString()),t?.isPublic!==void 0&&n.append("is_public",t.isPublic.toString()),t?.query&&n.append("query",t.query);for await(const a of this._getPaginated("/repos",n,r=>r.repos))yield*a}async getPrompt(t){const[n,a,r]=je(t),i=await(await this.caller.call(async()=>{const o=await this._fetch(`${this.apiUrl}/repos/${n}/${a}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return o?.status===404?null:(await O(o,"get prompt"),o)}))?.json();return i?.repo?i.repo:null}async createPrompt(t,n){const a=await this._getSettings();if(n?.isPublic&&!a.tenant_handle)throw new Error(`Cannot create a public prompt without first
45
-
46
- creating a LangChain Hub handle.
47
- You can add a handle by creating a public prompt at:
48
-
49
- https://smith.langchain.com/prompts`);const[r,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
-
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
-
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};
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}'}}}%%
56
- graph TD;
57
- `:`graph TD;
58
- `;if(i){const m="default",y={[m]:"{0}({1})"};a!==void 0&&(y[a]="{0}([{1}]):::first"),r!==void 0&&(y[r]="{0}([{1}]):::last");for(const[b,T]of Object.entries(e)){const v=T.name.split(":").pop()??"";let E=au.some(N=>v.startsWith(N)&&v.endsWith(N))?`<p>${v}</p>`:v;Object.keys(T.metadata??{}).length&&(E+=`<hr/><small><em>${Object.entries(T.metadata??{}).map(([N,M])=>`${N} = ${M}`).join(`
59
- `)}</em></small>`);const x=(y[b]??y[m]).replace("{0}",kn(b)).replace("{1}",E);l+=` ${x}
60
- `}}const d={};for(const m of t){const y=m.source.split(":"),b=m.target.split(":"),T=y.filter((v,I)=>v===b[I]).join(":");d[T]||(d[T]=[]),d[T].push(m)}const p=new Set;function f(m,y){const b=m.length===1&&m[0].source===m[0].target;if(y&&!b){const T=y.split(":").pop();if(p.has(T))throw new Error(`Found duplicate subgraph '${T}' -- this likely means that you're reusing a subgraph node with the same name. Please adjust your graph to have subgraph nodes with unique names.`);p.add(T),l+=` subgraph ${T}
61
- `}for(const T of m){const{source:v,target:I,data:E,conditional:x}=T;let N="";if(E!==void 0){let M=E;const B=M.split(" ");B.length>c&&(M=Array.from({length:Math.ceil(B.length/c)},(g,te)=>B.slice(te*c,(te+1)*c).join(" ")).join("&nbsp;<br>&nbsp;")),N=x?` -. &nbsp;${M}&nbsp; .-> `:` -- &nbsp;${M}&nbsp; --> `}else N=x?" -.-> ":" --> ";l+=` ${kn(v)}${N}${kn(I)};
62
- `}for(const T in d)T.startsWith(`${y}:`)&&T!==y&&f(d[T],T);y&&!b&&(l+=` end
63
- `)}f(d[""]??[],"");for(const m in d)!m.includes(":")&&m!==""&&f(d[m],m);return i&&(l+=ru(s??{})),l}async function iu(e,t){let n=t?.backgroundColor??"white";const a=t?.imageType??"png",r=btoa(e);n!==void 0&&(/^#(?:[0-9a-fA-F]{3}){1,2}$/.test(n)||(n=`!${n}`));const s=`https://mermaid.ink/img/${r}?bgColor=${n}&type=${a}`,i=await fetch(s);if(!i.ok)throw new Error(["Failed to render the graph using the Mermaid.INK API.",`Status code: ${i.status}`,`Status text: ${i.statusText}`].join(`
64
- `));return await i.blob()}const ou=Symbol("Let zodToJsonSchema decide on which parser to use"),cu={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},lu=e=>({...cu,...e}),uu=e=>{const t=lu(e),n=t.name!==void 0?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,flags:{hasReferencedOpenAiAnyType:!1},currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([a,r])=>[r._def,{def:r._def,path:[...t.basePath,t.definitionPath,a],jsonSchema:void 0}]))}},Bs=(e,t)=>{let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];n++);return[(e.length-n).toString(),...t.slice(n)].join("/")};function ue(e){if(e.target!=="openAi")return{};const t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy==="relative"?Bs(t,e.currentPath):t.join("/")}}function zs(e,t,n,a){a?.errorMessages&&n&&(e.errorMessage={...e.errorMessage,[t]:n})}function D(e,t,n,a,r){e[t]=n,zs(e,t,a,r)}function du(e,t){const n={type:"array"};return e.type?._def&&e.type?._def?.typeName!==P.ZodAny&&(n.items=$(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&D(n,"minItems",e.minLength.value,e.minLength.message,t),e.maxLength&&D(n,"maxItems",e.maxLength.value,e.maxLength.message,t),e.exactLength&&(D(n,"minItems",e.exactLength.value,e.exactLength.message,t),D(n,"maxItems",e.exactLength.value,e.exactLength.message,t)),n}function hu(e,t){const n={type:"integer",format:"int64"};if(!e.checks)return n;for(const a of e.checks)switch(a.kind){case"min":t.target==="jsonSchema7"?a.inclusive?D(n,"minimum",a.value,a.message,t):D(n,"exclusiveMinimum",a.value,a.message,t):(a.inclusive||(n.exclusiveMinimum=!0),D(n,"minimum",a.value,a.message,t));break;case"max":t.target==="jsonSchema7"?a.inclusive?D(n,"maximum",a.value,a.message,t):D(n,"exclusiveMaximum",a.value,a.message,t):(a.inclusive||(n.exclusiveMaximum=!0),D(n,"maximum",a.value,a.message,t));break;case"multipleOf":D(n,"multipleOf",a.value,a.message,t);break}return n}function pu(){return{type:"boolean"}}function Hs(e,t){return $(e.type._def,t)}const fu=(e,t)=>$(e.innerType._def,t);function Gs(e,t,n){const a=n??t.dateStrategy;if(Array.isArray(a))return{anyOf:a.map(r=>Gs(e,t,r))};switch(a){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return mu(e,t)}}const mu=(e,t)=>{const n={type:"integer",format:"unix-time"};if(t.target==="openApi3")return n;for(const a of e.checks)switch(a.kind){case"min":D(n,"minimum",a.value,a.message,t);break;case"max":D(n,"maximum",a.value,a.message,t);break}return n};function gu(e,t){return{...$(e.innerType._def,t),default:e.defaultValue()}}function _u(e,t){return t.effectStrategy==="input"?$(e.schema._def,t):ue(t)}function yu(e){return{type:"string",enum:Array.from(e.values)}}const wu=e=>"type"in e&&e.type==="string"?!1:"allOf"in e;function bu(e,t){const n=[$(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),$(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(s=>!!s);let a=t.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0;const r=[];return n.forEach(s=>{if(wu(s))r.push(...s.allOf),s.unevaluatedProperties===void 0&&(a=void 0);else{let i=s;if("additionalProperties"in s&&s.additionalProperties===!1){const{additionalProperties:o,...c}=s;i=c}else a=void 0;r.push(i)}}),r.length?{allOf:r,...a}:void 0}function vu(e,t){const n=typeof e.value;return n!=="bigint"&&n!=="number"&&n!=="boolean"&&n!=="string"?{type:Array.isArray(e.value)?"array":"object"}:t.target==="openApi3"?{type:n==="bigint"?"integer":n,enum:[e.value]}:{type:n==="bigint"?"integer":n,const:e.value}}let Rn;const ge={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(Rn===void 0&&(Rn=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Rn),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function Vs(e,t){const n={type:"string"};if(e.checks)for(const a of e.checks)switch(a.kind){case"min":D(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,a.value):a.value,a.message,t);break;case"max":D(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,a.value):a.value,a.message,t);break;case"email":switch(t.emailStrategy){case"format:email":_e(n,"email",a.message,t);break;case"format:idn-email":_e(n,"idn-email",a.message,t);break;case"pattern:zod":re(n,ge.email,a.message,t);break}break;case"url":_e(n,"uri",a.message,t);break;case"uuid":_e(n,"uuid",a.message,t);break;case"regex":re(n,a.regex,a.message,t);break;case"cuid":re(n,ge.cuid,a.message,t);break;case"cuid2":re(n,ge.cuid2,a.message,t);break;case"startsWith":re(n,RegExp(`^${Pn(a.value,t)}`),a.message,t);break;case"endsWith":re(n,RegExp(`${Pn(a.value,t)}$`),a.message,t);break;case"datetime":_e(n,"date-time",a.message,t);break;case"date":_e(n,"date",a.message,t);break;case"time":_e(n,"time",a.message,t);break;case"duration":_e(n,"duration",a.message,t);break;case"length":D(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,a.value):a.value,a.message,t),D(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,a.value):a.value,a.message,t);break;case"includes":re(n,RegExp(Pn(a.value,t)),a.message,t);break;case"ip":a.version!=="v6"&&_e(n,"ipv4",a.message,t),a.version!=="v4"&&_e(n,"ipv6",a.message,t);break;case"base64url":re(n,ge.base64url,a.message,t);break;case"jwt":re(n,ge.jwt,a.message,t);break;case"cidr":a.version!=="v6"&&re(n,ge.ipv4Cidr,a.message,t),a.version!=="v4"&&re(n,ge.ipv6Cidr,a.message,t);break;case"emoji":re(n,ge.emoji(),a.message,t);break;case"ulid":re(n,ge.ulid,a.message,t);break;case"base64":switch(t.base64Strategy){case"format:binary":_e(n,"binary",a.message,t);break;case"contentEncoding:base64":D(n,"contentEncoding","base64",a.message,t);break;case"pattern:zod":re(n,ge.base64,a.message,t);break}break;case"nanoid":re(n,ge.nanoid,a.message,t);break}return n}function Pn(e,t){return t.patternStrategy==="escape"?Eu(e):e}const Tu=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Eu(e){let t="";for(let n=0;n<e.length;n++)Tu.has(e[n])||(t+="\\"),t+=e[n];return t}function _e(e,t,n,a){e.format||e.anyOf?.some(r=>r.format)?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&a.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.anyOf.push({format:t,...n&&a.errorMessages&&{errorMessage:{format:n}}})):D(e,"format",t,n,a)}function re(e,t,n,a){e.pattern||e.allOf?.some(r=>r.pattern)?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&a.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.allOf.push({pattern:br(t,a),...n&&a.errorMessages&&{errorMessage:{pattern:n}}})):D(e,"pattern",br(t,a),n,a)}function br(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;const n={i:e.flags.includes("i"),m:e.flags.includes("m"),s:e.flags.includes("s")},a=n.i?e.source.toLowerCase():e.source;let r="",s=!1,i=!1,o=!1;for(let c=0;c<a.length;c++){if(s){r+=a[c],s=!1;continue}if(n.i){if(i){if(a[c].match(/[a-z]/)){o?(r+=a[c],r+=`${a[c-2]}-${a[c]}`.toUpperCase(),o=!1):a[c+1]==="-"&&a[c+2]?.match(/[a-z]/)?(r+=a[c],o=!0):r+=`${a[c]}${a[c].toUpperCase()}`;continue}}else if(a[c].match(/[a-z]/)){r+=`[${a[c]}${a[c].toUpperCase()}]`;continue}}if(n.m){if(a[c]==="^"){r+=`(^|(?<=[\r
65
- ]))`;continue}else if(a[c]==="$"){r+=`($|(?=[\r
66
- ]))`;continue}}if(n.s&&a[c]==="."){r+=i?`${a[c]}\r
67
- `:`[${a[c]}\r
68
- ]`;continue}r+=a[c],a[c]==="\\"?s=!0:i&&a[c]==="]"?i=!1:!i&&a[c]==="["&&(i=!0)}try{new RegExp(r)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return r}function Zs(e,t){if(t.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),t.target==="openApi3"&&e.keyType?._def.typeName===P.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((a,r)=>({...a,[r]:$(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",r]})??ue(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};const n={type:"object",additionalProperties:$(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if(t.target==="openApi3")return n;if(e.keyType?._def.typeName===P.ZodString&&e.keyType._def.checks?.length){const{type:a,...r}=Vs(e.keyType._def,t);return{...n,propertyNames:r}}else{if(e.keyType?._def.typeName===P.ZodEnum)return{...n,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===P.ZodBranded&&e.keyType._def.type._def.typeName===P.ZodString&&e.keyType._def.type._def.checks?.length){const{type:a,...r}=Hs(e.keyType._def,t);return{...n,propertyNames:r}}}return n}function Su(e,t){if(t.mapStrategy==="record")return Zs(e,t);const n=$(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||ue(t),a=$(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||ue(t);return{type:"array",maxItems:125,items:{type:"array",items:[n,a],minItems:2,maxItems:2}}}function Au(e){const t=e.values,a=Object.keys(e.values).filter(s=>typeof t[t[s]]!="number").map(s=>t[s]),r=Array.from(new Set(a.map(s=>typeof s)));return{type:r.length===1?r[0]==="string"?"string":"number":["string","number"],enum:a}}function Iu(e){return e.target==="openAi"?void 0:{not:ue({...e,currentPath:[...e.currentPath,"not"]})}}function Ou(e){return e.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}const Qt={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Cu(e,t){if(t.target==="openApi3")return vr(e,t);const n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(a=>a._def.typeName in Qt&&(!a._def.checks||!a._def.checks.length))){const a=n.reduce((r,s)=>{const i=Qt[s._def.typeName];return i&&!r.includes(i)?[...r,i]:r},[]);return{type:a.length>1?a:a[0]}}else if(n.every(a=>a._def.typeName==="ZodLiteral"&&!a.description)){const a=n.reduce((r,s)=>{const i=typeof s._def.value;switch(i){case"string":case"number":case"boolean":return[...r,i];case"bigint":return[...r,"integer"];case"object":return s._def.value===null?[...r,"null"]:r;case"symbol":case"undefined":case"function":default:return r}},[]);if(a.length===n.length){const r=a.filter((s,i,o)=>o.indexOf(s)===i);return{type:r.length>1?r:r[0],enum:n.reduce((s,i)=>s.includes(i._def.value)?s:[...s,i._def.value],[])}}}else if(n.every(a=>a._def.typeName==="ZodEnum"))return{type:"string",enum:n.reduce((a,r)=>[...a,...r._def.values.filter(s=>!a.includes(s))],[])};return vr(e,t)}const vr=(e,t)=>{const n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((a,r)=>$(a._def,{...t,currentPath:[...t.currentPath,"anyOf",`${r}`]})).filter(a=>!!a&&(!t.strictUnions||typeof a=="object"&&Object.keys(a).length>0));return n.length?{anyOf:n}:void 0};function xu(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return t.target==="openApi3"?{type:Qt[e.innerType._def.typeName],nullable:!0}:{type:[Qt[e.innerType._def.typeName],"null"]};if(t.target==="openApi3"){const a=$(e.innerType._def,{...t,currentPath:[...t.currentPath]});return a&&"$ref"in a?{allOf:[a],nullable:!0}:a&&{...a,nullable:!0}}const n=$(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}function Nu(e,t){const n={type:"number"};if(!e.checks)return n;for(const a of e.checks)switch(a.kind){case"int":n.type="integer",zs(n,"type",a.message,t);break;case"min":t.target==="jsonSchema7"?a.inclusive?D(n,"minimum",a.value,a.message,t):D(n,"exclusiveMinimum",a.value,a.message,t):(a.inclusive||(n.exclusiveMinimum=!0),D(n,"minimum",a.value,a.message,t));break;case"max":t.target==="jsonSchema7"?a.inclusive?D(n,"maximum",a.value,a.message,t):D(n,"exclusiveMaximum",a.value,a.message,t):(a.inclusive||(n.exclusiveMaximum=!0),D(n,"maximum",a.value,a.message,t));break;case"multipleOf":D(n,"multipleOf",a.value,a.message,t);break}return n}function ku(e,t){const n=t.target==="openAi",a={type:"object",properties:{}},r=[],s=e.shape();for(const o in s){let c=s[o];if(c===void 0||c._def===void 0)continue;let l=Pu(c);l&&n&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),l=!1);const d=$(c._def,{...t,currentPath:[...t.currentPath,"properties",o],propertyPath:[...t.currentPath,"properties",o]});d!==void 0&&(a.properties[o]=d,l||r.push(o))}r.length&&(a.required=r);const i=Ru(e,t);return i!==void 0&&(a.additionalProperties=i),a}function Ru(e,t){if(e.catchall._def.typeName!=="ZodNever")return $(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;case"strip":return t.removeAdditionalStrategy==="strict"?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function Pu(e){try{return e.isOptional()}catch{return!0}}const Mu=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return $(e.innerType._def,t);const n=$(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return n?{anyOf:[{not:ue(t)},n]}:ue(t)},Lu=(e,t)=>{if(t.pipeStrategy==="input")return $(e.in._def,t);if(t.pipeStrategy==="output")return $(e.out._def,t);const n=$(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),a=$(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",n?"1":"0"]});return{allOf:[n,a].filter(r=>r!==void 0)}};function $u(e,t){return $(e.type._def,t)}function ju(e,t){const a={type:"array",uniqueItems:!0,items:$(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&D(a,"minItems",e.minSize.value,e.minSize.message,t),e.maxSize&&D(a,"maxItems",e.maxSize.value,e.maxSize.message,t),a}function Du(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((n,a)=>$(n._def,{...t,currentPath:[...t.currentPath,"items",`${a}`]})).reduce((n,a)=>a===void 0?n:[...n,a],[]),additionalItems:$(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((n,a)=>$(n._def,{...t,currentPath:[...t.currentPath,"items",`${a}`]})).reduce((n,a)=>a===void 0?n:[...n,a],[])}}function Fu(e){return{not:ue(e)}}function Uu(e){return ue(e)}const Bu=(e,t)=>$(e.innerType._def,t),zu=(e,t,n)=>{switch(t){case P.ZodString:return Vs(e,n);case P.ZodNumber:return Nu(e,n);case P.ZodObject:return ku(e,n);case P.ZodBigInt:return hu(e,n);case P.ZodBoolean:return pu();case P.ZodDate:return Gs(e,n);case P.ZodUndefined:return Fu(n);case P.ZodNull:return Ou(n);case P.ZodArray:return du(e,n);case P.ZodUnion:case P.ZodDiscriminatedUnion:return Cu(e,n);case P.ZodIntersection:return bu(e,n);case P.ZodTuple:return Du(e,n);case P.ZodRecord:return Zs(e,n);case P.ZodLiteral:return vu(e,n);case P.ZodEnum:return yu(e);case P.ZodNativeEnum:return Au(e);case P.ZodNullable:return xu(e,n);case P.ZodOptional:return Mu(e,n);case P.ZodMap:return Su(e,n);case P.ZodSet:return ju(e,n);case P.ZodLazy:return()=>e.getter()._def;case P.ZodPromise:return $u(e,n);case P.ZodNaN:case P.ZodNever:return Iu(n);case P.ZodEffects:return _u(e,n);case P.ZodAny:return ue(n);case P.ZodUnknown:return Uu(n);case P.ZodDefault:return gu(e,n);case P.ZodBranded:return Hs(e,n);case P.ZodReadonly:return Bu(e,n);case P.ZodCatch:return fu(e,n);case P.ZodPipeline:return Lu(e,n);case P.ZodFunction:case P.ZodVoid:case P.ZodSymbol:return;default:return(a=>{})()}};function $(e,t,n=!1){const a=t.seen.get(e);if(t.override){const o=t.override?.(e,t,a,n);if(o!==ou)return o}if(a&&!n){const o=Hu(a,t);if(o!==void 0)return o}const r={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,r);const s=zu(e,e.typeName,t),i=typeof s=="function"?$(s(),t):s;if(i&&Gu(e,t,i),t.postProcess){const o=t.postProcess(i,e,t);return r.jsonSchema=i,o}return r.jsonSchema=i,i}const Hu=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:Bs(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every((n,a)=>t.currentPath[a]===n)?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),ue(t)):t.$refStrategy==="seen"?ue(t):void 0}},Gu=(e,t,n)=>(e.description&&(n.description=e.description,t.markdownDescription&&(n.markdownDescription=e.description)),n),Vu=(e,t)=>{const n=uu(t);let a=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((o,[c,l])=>({...o,[c]:$(l._def,{...n,currentPath:[...n.basePath,n.definitionPath,c]},!0)??ue(n)}),{}):void 0;const r=typeof t=="string"?t:t?.name,s=$(e._def,n,!1)??ue(n);n.flags.hasReferencedOpenAiAnyType&&(a||(a={}),a[n.openAiAnyTypeName]||(a[n.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:n.$refStrategy==="relative"?"1":[...n.basePath,n.definitionPath,n.openAiAnyTypeName].join("/")}}));const i=r===void 0?a?{...s,[n.definitionPath]:a}:s:{$ref:[...n.$refStrategy==="relative"?[]:n.basePath,n.definitionPath,r].join("/"),[n.definitionPath]:{...a,[r]:s}};return n.target==="jsonSchema7"?i.$schema="http://json-schema.org/draft-07/schema#":(n.target==="jsonSchema2019-09"||n.target==="openAi")&&(i.$schema="https://json-schema.org/draft/2019-09/schema#"),n.target==="openAi"&&("anyOf"in i||"oneOf"in i||"allOf"in i||"type"in i&&Array.isArray(i.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),i};var Zu={};F(Zu,{Validator:()=>Mi,deepCompareStrict:()=>Pr,toJsonSchema:()=>mt,validatesOnlyStrings:()=>zt});function mt(e){if(Z(e)){const t=ct(e,!0);if(Ce(t)){const n=Yt(t,!0);return Va(n)}else return Va(e)}return Y(e)?Vu(e):e}function zt(e){if(!e||typeof e!="object"||Object.keys(e).length===0||Array.isArray(e))return!1;if("type"in e)return typeof e.type=="string"?e.type==="string":Array.isArray(e.type)?e.type.every(t=>t==="string"):!1;if("enum"in e)return Array.isArray(e.enum)&&e.enum.length>0&&e.enum.every(t=>typeof t=="string");if("const"in e)return typeof e.const=="string";if("allOf"in e&&Array.isArray(e.allOf))return e.allOf.some(t=>zt(t));if("anyOf"in e&&Array.isArray(e.anyOf)||"oneOf"in e&&Array.isArray(e.oneOf)){const t="anyOf"in e?e.anyOf:e.oneOf;return t.length>0&&t.every(n=>zt(n))}if("not"in e)return!1;if("$ref"in e&&typeof e.$ref=="string"){const t=e.$ref,n=Li(e);return n[t]?zt(n[t]):!1}return!1}var qu={};F(qu,{Graph:()=>ka});function Ju(e,t){if(e!==void 0&&!Ut(e))return e;if(Oa(t))try{let n=t.getName();return n=n.startsWith("Runnable")?n.slice(8):n,n}catch{return t.getName()}else return t.name??"UnknownSchema"}function Wu(e){return Oa(e.data)?{type:"runnable",data:{id:e.data.lc_id,name:e.data.getName()}}:{type:"schema",data:{...mt(e.data.schema),title:e.data.name}}}var ka=class qs{nodes={};edges=[];constructor(t){this.nodes=t?.nodes??this.nodes,this.edges=t?.edges??this.edges}toJSON(){const t={};return Object.values(this.nodes).forEach((n,a)=>{t[n.id]=Ut(n.id)?a:n.id}),{nodes:Object.values(this.nodes).map(n=>({id:t[n.id],...Wu(n)})),edges:this.edges.map(n=>{const a={source:t[n.source],target:t[n.target]};return typeof n.data<"u"&&(a.data=n.data),typeof n.conditional<"u"&&(a.conditional=n.conditional),a})}}addNode(t,n,a){if(n!==void 0&&this.nodes[n]!==void 0)throw new Error(`Node with id ${n} already exists`);const r=n??se(),s={id:r,data:t,name:Ju(n,t),metadata:a};return this.nodes[r]=s,s}removeNode(t){delete this.nodes[t.id],this.edges=this.edges.filter(n=>n.source!==t.id&&n.target!==t.id)}addEdge(t,n,a,r){if(this.nodes[t.id]===void 0)throw new Error(`Source node ${t.id} not in graph`);if(this.nodes[n.id]===void 0)throw new Error(`Target node ${n.id} not in graph`);const s={source:t.id,target:n.id,data:a,conditional:r};return this.edges.push(s),s}firstNode(){return Tr(this)}lastNode(){return Er(this)}extend(t,n=""){let a=n;Object.values(t.nodes).map(l=>l.id).every(Ut)&&(a="");const s=l=>a?`${a}:${l}`:l;Object.entries(t.nodes).forEach(([l,d])=>{this.nodes[s(l)]={...d,id:s(l)}});const i=t.edges.map(l=>({...l,source:s(l.source),target:s(l.target)}));this.edges=[...this.edges,...i];const o=t.firstNode(),c=t.lastNode();return[o?{id:s(o.id),data:o.data}:void 0,c?{id:s(c.id),data:c.data}:void 0]}trimFirstNode(){const t=this.firstNode();t&&Tr(this,[t.id])&&this.removeNode(t)}trimLastNode(){const t=this.lastNode();t&&Er(this,[t.id])&&this.removeNode(t)}reid(){const t=Object.fromEntries(Object.values(this.nodes).map(r=>[r.id,r.name])),n=new Map;Object.values(t).forEach(r=>{n.set(r,(n.get(r)||0)+1)});const a=r=>{const s=t[r];return Ut(r)&&n.get(s)===1?s:r};return new qs({nodes:Object.fromEntries(Object.entries(this.nodes).map(([r,s])=>[a(r),{...s,id:a(r)}])),edges:this.edges.map(r=>({...r,source:a(r.source),target:a(r.target)}))})}drawMermaid(t){const{withStyles:n,curveStyle:a,nodeColors:r={default:"fill:#f2f0ff,line-height:1.2",first:"fill-opacity:0",last:"fill:#bfb6fc"},wrapLabelNWords:s}=t??{},i=this.reid(),o=i.firstNode(),c=i.lastNode();return su(i.nodes,i.edges,{firstNode:o?.id,lastNode:c?.id,withStyles:n,curveStyle:a,nodeColors:r,wrapLabelNWords:s})}async drawMermaidPng(t){const n=this.drawMermaid(t);return iu(n,{backgroundColor:t?.backgroundColor})}};function Tr(e,t=[]){const n=new Set(e.edges.filter(r=>!t.includes(r.source)).map(r=>r.target)),a=[];for(const r of Object.values(e.nodes))!t.includes(r.id)&&!n.has(r.id)&&a.push(r);return a.length===1?a[0]:void 0}function Er(e,t=[]){const n=new Set(e.edges.filter(r=>!t.includes(r.target)).map(r=>r.source)),a=[];for(const r of Object.values(e.nodes))!t.includes(r.id)&&!n.has(r.id)&&a.push(r);return a.length===1?a[0]:void 0}function Ku(e){const t=new TextEncoder,n=new ReadableStream({async start(a){for await(const r of e)a.enqueue(t.encode(`event: data
69
- data: ${JSON.stringify(r)}
70
-
71
- `));a.enqueue(t.encode(`event: end
72
-
73
- `)),a.close()}});return Te.fromReadableStream(n)}function Sr(e){return typeof e=="object"&&e!==null&&typeof e[Symbol.iterator]=="function"&&typeof e.next=="function"}const Yu=e=>e!=null&&typeof e=="object"&&"next"in e&&typeof e.next=="function";function aa(e){return typeof e=="object"&&e!==null&&typeof e[Symbol.asyncIterator]=="function"}function*Ar(e,t){for(;;){const{value:n,done:a}=Me.runWithConfig(Ye(e),t.next.bind(t),!0);if(a)break;yield n}}async function*ra(e,t){const n=t[Symbol.asyncIterator]();for(;;){const{value:a,done:r}=await Me.runWithConfig(Ye(e),n.next.bind(t),!0);if(r)break;yield a}}function K(e,t){return e&&!Array.isArray(e)&&!(e instanceof Date)&&typeof e=="object"?e:{[t]:e}}var V=class extends lt{lc_runnable=!0;name;getName(e){const t=this.name??this.constructor.lc_name()??this.constructor.name;return e?`${t}${e}`:t}withRetry(e){return new Ra({bound:this,kwargs:{},config:{},maxAttemptNumber:e?.stopAfterAttempt,...e})}withConfig(e){return new ht({bound:this,config:e,kwargs:{}})}withFallbacks(e){const t=Array.isArray(e)?e:e.fallbacks;return new Xs({runnable:this,fallbacks:t})}_getOptionsList(e,t=0){if(Array.isArray(e)&&e.length!==t)throw new Error(`Passed "options" must be an array with the same length as the inputs, but got ${e.length} options for ${t} inputs`);if(Array.isArray(e))return e.map(L);if(t>1&&!Array.isArray(e)&&e.runId){console.warn("Provided runId will be used only for the first element of the batch.");const n=Object.fromEntries(Object.entries(e).filter(([a])=>a!=="runId"));return Array.from({length:t},(a,r)=>L(r===0?e:n))}return Array.from({length:t},()=>L(e))}async batch(e,t,n){const a=this._getOptionsList(t??{},e.length),r=a[0]?.maxConcurrency??n?.maxConcurrency,s=new cn({maxConcurrency:r,onFailedAttempt:o=>{throw o}}),i=e.map((o,c)=>s.call(async()=>{try{return await this.invoke(o,a[c])}catch(l){if(n?.returnExceptions)return l;throw l}}));return Promise.all(i)}async*_streamIterator(e,t){yield this.invoke(e,t)}async stream(e,t){const n=L(t),a=new nt({generator:this._streamIterator(e,n),config:n});return await a.setup,Te.fromAsyncGenerator(a)}_separateRunnableConfigFromCallOptions(e){let t;e===void 0?t=L(e):t=L({callbacks:e.callbacks,tags:e.tags,metadata:e.metadata,runName:e.runName,configurable:e.configurable,recursionLimit:e.recursionLimit,maxConcurrency:e.maxConcurrency,runId:e.runId,timeout:e.timeout,signal:e.signal});const n={...e};return delete n.callbacks,delete n.tags,delete n.metadata,delete n.runName,delete n.configurable,delete n.recursionLimit,delete n.maxConcurrency,delete n.runId,delete n.timeout,delete n.signal,[t,n]}async _callWithConfig(e,t,n){const a=L(n),s=await(await pe(a))?.handleChainStart(this.toJSON(),K(t,"input"),a.runId,a?.runType,void 0,void 0,a?.runName??this.getName());delete a.runId;let i;try{const o=e.call(this,t,a,s);i=await He(o,n?.signal)}catch(o){throw await s?.handleChainError(o),o}return await s?.handleChainEnd(K(i,"output")),i}async _batchWithConfig(e,t,n,a){const r=this._getOptionsList(n??{},t.length),s=await Promise.all(r.map(pe)),i=await Promise.all(s.map(async(c,l)=>{const d=await c?.handleChainStart(this.toJSON(),K(t[l],"input"),r[l].runId,r[l].runType,void 0,void 0,r[l].runName??this.getName());return delete r[l].runId,d}));let o;try{const c=e.call(this,t,r,i,a);o=await He(c,r?.[0]?.signal)}catch(c){throw await Promise.all(i.map(l=>l?.handleChainError(c))),c}return await Promise.all(i.map(c=>c?.handleChainEnd(K(o,"output")))),o}_concatOutputChunks(e,t){return Qe(e,t)}async*_transformStreamWithConfig(e,t,n){let a,r=!0,s,i=!0;const o=L(n),c=await pe(o),l=this;async function*d(){for await(const f of e){if(r)if(a===void 0)a=f;else try{a=l._concatOutputChunks(a,f)}catch{a=void 0,r=!1}yield f}}let p;try{const f=await Ns(t.bind(this),d(),async()=>c?.handleChainStart(this.toJSON(),{input:""},o.runId,o.runType,void 0,void 0,o.runName??this.getName()),n?.signal,o);delete o.runId,p=f.setup;const m=p?.handlers.find(Dl);let y=f.output;m!==void 0&&p!==void 0&&(y=m.tapOutputIterable(p.runId,y));const b=p?.handlers.find(Ms);b!==void 0&&p!==void 0&&(y=b.tapOutputIterable(p.runId,y));for await(const T of y)if(yield T,i)if(s===void 0)s=T;else try{s=this._concatOutputChunks(s,T)}catch{s=void 0,i=!1}}catch(f){throw await p?.handleChainError(f,void 0,void 0,void 0,{inputs:K(a,"input")}),f}await p?.handleChainEnd(s??{},void 0,void 0,void 0,{inputs:K(a,"input")})}getGraph(e){const t=new ka,n=t.addNode({name:`${this.getName()}Input`,schema:Za()}),a=t.addNode(this),r=t.addNode({name:`${this.getName()}Output`,schema:Za()});return t.addEdge(n,a),t.addEdge(a,r),t}pipe(e){return new un({first:this,last:ve(e)})}pick(e){return this.pipe(new ei(e))}assign(e){return this.pipe(new Pa(new gt({steps:e})))}async*transform(e,t){let n;for await(const a of e)n===void 0?n=a:n=this._concatOutputChunks(n,a);yield*this._streamIterator(n,L(t))}async*streamLog(e,t,n){const a=new Qn({...n,autoClose:!1,_schemaFormat:"original"}),r=L(t);yield*this._streamLog(e,a,r)}async*_streamLog(e,t,n){const{callbacks:a}=n;if(a===void 0)n.callbacks=[t];else if(Array.isArray(a))n.callbacks=a.concat([t]);else{const o=a.copy();o.addHandler(t,!0),n.callbacks=o}const r=this.stream(e,n);async function s(){try{const o=await r;for await(const c of o){const l=new ke({ops:[{op:"add",path:"/streamed_output/-",value:c}]});await t.writer.write(l)}}finally{await t.writer.close()}}const i=s();try{for await(const o of t)yield o}finally{await i}}streamEvents(e,t,n){let a;if(t.version==="v1")a=this._streamEventsV1(e,t,n);else if(t.version==="v2")a=this._streamEventsV2(e,t,n);else throw new Error('Only versions "v1" and "v2" of the schema are currently supported.');return t.encoding==="text/event-stream"?Ku(a):Te.fromAsyncGenerator(a)}async*_streamEventsV2(e,t,n){const a=new Fl({...n,autoClose:!1}),r=L(t),s=r.runId??se();r.runId=s;const i=r.callbacks;if(i===void 0)r.callbacks=[a];else if(Array.isArray(i))r.callbacks=i.concat(a);else{const m=i.copy();m.addHandler(a,!0),r.callbacks=m}const o=new AbortController,c=this;async function l(){let m,y=null;try{t?.signal?"any"in AbortSignal?m=AbortSignal.any([o.signal,t.signal]):(m=t.signal,y=()=>{o.abort()},t.signal.addEventListener("abort",y,{once:!0})):m=o.signal;const b=await c.stream(e,{...r,signal:m}),T=a.tapOutputIterable(s,b);for await(const v of T)if(o.signal.aborted)break}finally{await a.finish(),m&&y&&m.removeEventListener("abort",y)}}const d=l();let p=!1,f;try{for await(const m of a){if(!p){m.data.input=e,p=!0,f=m.run_id,yield m;continue}m.run_id===f&&m.event.endsWith("_end")&&m.data?.input&&delete m.data.input,yield m}}finally{o.abort(),await d}}async*_streamEventsV1(e,t,n){let a,r=!1;const s=L(t),i=s.tags??[],o=s.metadata??{},c=s.runName??this.getName(),l=new Qn({...n,autoClose:!1,_schemaFormat:"streaming_events"}),d=new Hl({...n}),p=this._streamLog(e,l,s);for await(const m of p){if(a?a=a.concat(m):a=Ia.fromRunLogPatch(m),a.state===void 0)throw new Error('Internal error: "streamEvents" state is missing. Please open a bug report.');if(!r){r=!0;const v={...a.state},I={run_id:v.id,event:`on_${v.type}_start`,name:c,tags:i,metadata:o,data:{input:e}};d.includeEvent(I,v.type)&&(yield I)}const y=m.ops.filter(v=>v.path.startsWith("/logs/")).map(v=>v.path.split("/")[2]),b=[...new Set(y)];for(const v of b){let I,E={};const x=a.state.logs[v];if(x.end_time===void 0?x.streamed_output.length>0?I="stream":I="start":I="end",I==="start")x.inputs!==void 0&&(E.input=x.inputs);else if(I==="end")x.inputs!==void 0&&(E.input=x.inputs),E.output=x.final_output;else if(I==="stream"){const N=x.streamed_output.length;if(N!==1)throw new Error(`Expected exactly one chunk of streamed output, got ${N} instead. Encountered in: "${x.name}"`);E={chunk:x.streamed_output[0]},x.streamed_output=[]}yield{event:`on_${x.type}_${I}`,name:x.name,run_id:x.id,tags:x.tags,metadata:x.metadata,data:E}}const{state:T}=a;if(T.streamed_output.length>0){const v=T.streamed_output.length;if(v!==1)throw new Error(`Expected exactly one chunk of streamed output, got ${v} instead. Encountered in: "${T.name}"`);const I={chunk:T.streamed_output[0]};T.streamed_output=[];const E={event:`on_${T.type}_stream`,run_id:T.id,tags:i,metadata:o,name:c,data:I};d.includeEvent(E,T.type)&&(yield E)}}const f=a?.state;if(f!==void 0){const m={event:`on_${f.type}_end`,name:c,run_id:f.id,tags:i,metadata:o,data:{output:f.final_output}};d.includeEvent(m,f.type)&&(yield m)}}static isRunnable(e){return Oa(e)}withListeners({onStart:e,onEnd:t,onError:n}){return new ht({bound:this,config:{},configFactories:[a=>({callbacks:[new js({config:a,onStart:e,onEnd:t,onError:n})]})]})}asTool(e){return nd(this,e)}},ht=class Js extends V{static lc_name(){return"RunnableBinding"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;bound;config;kwargs;configFactories;constructor(t){super(t),this.bound=t.bound,this.kwargs=t.kwargs,this.config=t.config,this.configFactories=t.configFactories}getName(t){return this.bound.getName(t)}async _mergeConfig(...t){const n=Vn(this.config,...t);return Vn(n,...this.configFactories?await Promise.all(this.configFactories.map(async a=>await a(n))):[])}withConfig(t){return new this.constructor({bound:this.bound,kwargs:this.kwargs,config:{...this.config,...t}})}withRetry(t){return new Ra({bound:this.bound,kwargs:this.kwargs,config:this.config,maxAttemptNumber:t?.stopAfterAttempt,...t})}async invoke(t,n){return this.bound.invoke(t,await this._mergeConfig(n,this.kwargs))}async batch(t,n,a){const r=Array.isArray(n)?await Promise.all(n.map(async s=>this._mergeConfig(L(s),this.kwargs))):await this._mergeConfig(L(n),this.kwargs);return this.bound.batch(t,r,a)}_concatOutputChunks(t,n){return this.bound._concatOutputChunks(t,n)}async*_streamIterator(t,n){yield*this.bound._streamIterator(t,await this._mergeConfig(L(n),this.kwargs))}async stream(t,n){return this.bound.stream(t,await this._mergeConfig(L(n),this.kwargs))}async*transform(t,n){yield*this.bound.transform(t,await this._mergeConfig(L(n),this.kwargs))}streamEvents(t,n,a){const r=this,s=async function*(){yield*r.bound.streamEvents(t,{...await r._mergeConfig(L(n),r.kwargs),version:n.version},a)};return Te.fromAsyncGenerator(s())}static isRunnableBinding(t){return t.bound&&V.isRunnable(t.bound)}withListeners({onStart:t,onEnd:n,onError:a}){return new Js({bound:this.bound,kwargs:this.kwargs,config:this.config,configFactories:[r=>({callbacks:[new js({config:r,onStart:t,onEnd:n,onError:a})]})]})}},Qu=class Ws extends V{static lc_name(){return"RunnableEach"}lc_serializable=!0;lc_namespace=["langchain_core","runnables"];bound;constructor(t){super(t),this.bound=t.bound}async invoke(t,n){return this._callWithConfig(this._invoke.bind(this),t,n)}async _invoke(t,n,a){return this.bound.batch(t,H(n,{callbacks:a?.getChild()}))}withListeners({onStart:t,onEnd:n,onError:a}){return new Ws({bound:this.bound.withListeners({onStart:t,onEnd:n,onError:a})})}},Ra=class extends ht{static lc_name(){return"RunnableRetry"}lc_namespace=["langchain_core","runnables"];maxAttemptNumber=3;onFailedAttempt=()=>{};constructor(e){super(e),this.maxAttemptNumber=e.maxAttemptNumber??this.maxAttemptNumber,this.onFailedAttempt=e.onFailedAttempt??this.onFailedAttempt}_patchConfigForRetry(e,t,n){const a=e>1?`retry:attempt:${e}`:void 0;return H(t,{callbacks:n?.getChild(a)})}async _invoke(e,t,n){return Ht(a=>super.invoke(e,this._patchConfigForRetry(a,t,n)),{onFailedAttempt:a=>this.onFailedAttempt(a,e),retries:Math.max(this.maxAttemptNumber-1,0),randomize:!0})}async invoke(e,t){return this._callWithConfig(this._invoke.bind(this),e,t)}async _batch(e,t,n,a){const r={};try{await Ht(async s=>{const i=e.map((p,f)=>f).filter(p=>r[p.toString()]===void 0||r[p.toString()]instanceof Error),o=i.map(p=>e[p]),c=i.map(p=>this._patchConfigForRetry(s,t?.[p],n?.[p])),l=await super.batch(o,c,{...a,returnExceptions:!0});let d;for(let p=0;p<l.length;p+=1){const f=l[p],m=i[p];f instanceof Error&&d===void 0&&(d=f,d.input=o[p]),r[m.toString()]=f}if(d)throw d;return l},{onFailedAttempt:s=>this.onFailedAttempt(s,s.input),retries:Math.max(this.maxAttemptNumber-1,0),randomize:!0})}catch(s){if(a?.returnExceptions!==!0)throw s}return Object.keys(r).sort((s,i)=>parseInt(s,10)-parseInt(i,10)).map(s=>r[parseInt(s,10)])}async batch(e,t,n){return this._batchWithConfig(this._batch.bind(this),e,t,n)}},un=class yt extends V{static lc_name(){return"RunnableSequence"}first;middle=[];last;omitSequenceTags=!1;lc_serializable=!0;lc_namespace=["langchain_core","runnables"];constructor(t){super(t),this.first=t.first,this.middle=t.middle??this.middle,this.last=t.last,this.name=t.name,this.omitSequenceTags=t.omitSequenceTags??this.omitSequenceTags}get steps(){return[this.first,...this.middle,this.last]}async invoke(t,n){const a=L(n),s=await(await pe(a))?.handleChainStart(this.toJSON(),K(t,"input"),a.runId,void 0,void 0,void 0,a?.runName);delete a.runId;let i=t,o;try{const c=[this.first,...this.middle];for(let l=0;l<c.length;l+=1){const p=c[l].invoke(i,H(a,{callbacks:s?.getChild(this.omitSequenceTags?void 0:`seq:step:${l+1}`)}));i=await He(p,n?.signal)}if(n?.signal?.aborted)throw Jt(n.signal);o=await this.last.invoke(i,H(a,{callbacks:s?.getChild(this.omitSequenceTags?void 0:`seq:step:${this.steps.length}`)}))}catch(c){throw await s?.handleChainError(c),c}return await s?.handleChainEnd(K(o,"output")),o}async batch(t,n,a){const r=this._getOptionsList(n??{},t.length),s=await Promise.all(r.map(pe)),i=await Promise.all(s.map(async(c,l)=>{const d=await c?.handleChainStart(this.toJSON(),K(t[l],"input"),r[l].runId,void 0,void 0,void 0,r[l].runName);return delete r[l].runId,d}));let o=t;try{for(let c=0;c<this.steps.length;c+=1){const d=this.steps[c].batch(o,i.map((p,f)=>{const m=p?.getChild(this.omitSequenceTags?void 0:`seq:step:${c+1}`);return H(r[f],{callbacks:m})}),a);o=await He(d,r[0]?.signal)}}catch(c){throw await Promise.all(i.map(l=>l?.handleChainError(c))),c}return await Promise.all(i.map(c=>c?.handleChainEnd(K(o,"output")))),o}_concatOutputChunks(t,n){return this.last._concatOutputChunks(t,n)}async*_streamIterator(t,n){const a=await pe(n),{runId:r,...s}=n??{},i=await a?.handleChainStart(this.toJSON(),K(t,"input"),r,void 0,void 0,void 0,s?.runName),o=[this.first,...this.middle,this.last];let c=!0,l;async function*d(){yield t}try{let p=o[0].transform(d(),H(s,{callbacks:i?.getChild(this.omitSequenceTags?void 0:"seq:step:1")}));for(let f=1;f<o.length;f+=1)p=await o[f].transform(p,H(s,{callbacks:i?.getChild(this.omitSequenceTags?void 0:`seq:step:${f+1}`)}));for await(const f of p)if(n?.signal?.throwIfAborted(),yield f,c)if(l===void 0)l=f;else try{l=this._concatOutputChunks(l,f)}catch{l=void 0,c=!1}}catch(p){throw await i?.handleChainError(p),p}await i?.handleChainEnd(K(l,"output"))}getGraph(t){const n=new ka;let a=null;return this.steps.forEach((r,s)=>{const i=r.getGraph(t);s!==0&&i.trimFirstNode(),s!==this.steps.length-1&&i.trimLastNode(),n.extend(i);const o=i.firstNode();if(!o)throw new Error(`Runnable ${r} has no first node`);a&&n.addEdge(a,o),a=i.lastNode()}),n}pipe(t){return yt.isRunnableSequence(t)?new yt({first:this.first,middle:this.middle.concat([this.last,t.first,...t.middle]),last:t.last,name:this.name??t.name}):new yt({first:this.first,middle:[...this.middle,this.last],last:ve(t),name:this.name})}static isRunnableSequence(t){return Array.isArray(t.middle)&&V.isRunnable(t)}static from([t,...n],a){let r={};return typeof a=="string"?r.name=a:a!==void 0&&(r=a),new yt({...r,first:ve(t),middle:n.slice(0,-1).map(ve),last:ve(n[n.length-1])})}},gt=class Ks extends V{static lc_name(){return"RunnableMap"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;steps;getStepsKeys(){return Object.keys(this.steps)}constructor(t){super(t),this.steps={};for(const[n,a]of Object.entries(t.steps))this.steps[n]=ve(a)}static from(t){return new Ks({steps:t})}async invoke(t,n){const a=L(n),s=await(await pe(a))?.handleChainStart(this.toJSON(),{input:t},a.runId,void 0,void 0,void 0,a?.runName);delete a.runId;const i={};try{const o=Object.entries(this.steps).map(async([c,l])=>{i[c]=await l.invoke(t,H(a,{callbacks:s?.getChild(`map:key:${c}`)}))});await He(Promise.all(o),n?.signal)}catch(o){throw await s?.handleChainError(o),o}return await s?.handleChainEnd(i),i}async*_transform(t,n,a){const r={...this.steps},s=Sa(t,Object.keys(r).length),i=new Map(Object.entries(r).map(([o,c],l)=>{const d=c.transform(s[l],H(a,{callbacks:n?.getChild(`map:key:${o}`)}));return[o,d.next().then(p=>({key:o,gen:d,result:p}))]}));for(;i.size;){const o=Promise.race(i.values()),{key:c,result:l,gen:d}=await He(o,a?.signal);i.delete(c),l.done||(yield{[c]:l.value},i.set(c,d.next().then(p=>({key:c,gen:d,result:p}))))}}transform(t,n){return this._transformStreamWithConfig(t,this._transform.bind(this),n)}async stream(t,n){async function*a(){yield t}const r=L(n),s=new nt({generator:this.transform(a(),r),config:r});return await s.setup,Te.fromAsyncGenerator(s)}},Xu=class Ys extends V{lc_serializable=!1;lc_namespace=["langchain_core","runnables"];func;constructor(t){if(super(t),!Ea(t.func))throw new Error("RunnableTraceable requires a function that is wrapped in traceable higher-order function");this.func=t.func}async invoke(t,n){const[a]=this._getOptionsList(n??{},1),r=await pe(a),s=this.func(H(a,{callbacks:r}),t);return He(s,a?.signal)}async*_streamIterator(t,n){const[a]=this._getOptionsList(n??{},1),r=await this.invoke(t,n);if(aa(r)){for await(const s of r)a?.signal?.throwIfAborted(),yield s;return}if(Yu(r)){for(;;){a?.signal?.throwIfAborted();const s=r.next();if(s.done)break;yield s.value}return}yield r}static from(t){return new Ys({func:t})}};function ed(e){if(Ea(e))throw new Error("RunnableLambda requires a function that is not wrapped in traceable higher-order function. This shouldn't happen.")}var Ge=class Qs extends V{static lc_name(){return"RunnableLambda"}lc_namespace=["langchain_core","runnables"];func;constructor(t){if(Ea(t.func))return Xu.from(t.func);super(t),ed(t.func),this.func=t.func}static from(t){return new Qs({func:t})}async _invoke(t,n,a){return new Promise((r,s)=>{const i=H(n,{callbacks:a?.getChild(),recursionLimit:(n?.recursionLimit??Nn)-1});Me.runWithConfig(Ye(i),async()=>{try{let o=await this.func(t,{...i});if(o&&V.isRunnable(o)){if(n?.recursionLimit===0)throw new Error("Recursion limit reached.");o=await o.invoke(t,{...i,recursionLimit:(i.recursionLimit??Nn)-1})}else if(aa(o)){let c;for await(const l of ra(i,o))if(n?.signal?.throwIfAborted(),c===void 0)c=l;else try{c=this._concatOutputChunks(c,l)}catch{c=l}o=c}else if(Sr(o)){let c;for(const l of Ar(i,o))if(n?.signal?.throwIfAborted(),c===void 0)c=l;else try{c=this._concatOutputChunks(c,l)}catch{c=l}o=c}r(o)}catch(o){s(o)}})})}async invoke(t,n){return this._callWithConfig(this._invoke.bind(this),t,n)}async*_transform(t,n,a){let r;for await(const o of t)if(r===void 0)r=o;else try{r=this._concatOutputChunks(r,o)}catch{r=o}const s=H(a,{callbacks:n?.getChild(),recursionLimit:(a?.recursionLimit??Nn)-1}),i=await new Promise((o,c)=>{Me.runWithConfig(Ye(s),async()=>{try{const l=await this.func(r,{...s,config:s});o(l)}catch(l){c(l)}})});if(i&&V.isRunnable(i)){if(a?.recursionLimit===0)throw new Error("Recursion limit reached.");const o=await i.stream(r,s);for await(const c of o)yield c}else if(aa(i))for await(const o of ra(s,i))a?.signal?.throwIfAborted(),yield o;else if(Sr(i))for(const o of Ar(s,i))a?.signal?.throwIfAborted(),yield o;else yield i}transform(t,n){return this._transformStreamWithConfig(t,this._transform.bind(this),n)}async stream(t,n){async function*a(){yield t}const r=L(n),s=new nt({generator:this.transform(a(),r),config:r});return await s.setup,Te.fromAsyncGenerator(s)}},td=class extends gt{},Xs=class extends V{static lc_name(){return"RunnableWithFallbacks"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;runnable;fallbacks;constructor(e){super(e),this.runnable=e.runnable,this.fallbacks=e.fallbacks}*runnables(){yield this.runnable;for(const e of this.fallbacks)yield e}async invoke(e,t){const n=L(t),a=await pe(n),{runId:r,...s}=n,i=await a?.handleChainStart(this.toJSON(),K(e,"input"),r,void 0,void 0,void 0,s?.runName),o=H(s,{callbacks:i?.getChild()});return await Me.runWithConfig(o,async()=>{let l;for(const d of this.runnables()){n?.signal?.throwIfAborted();try{const p=await d.invoke(e,o);return await i?.handleChainEnd(K(p,"output")),p}catch(p){l===void 0&&(l=p)}}throw l===void 0?new Error("No error stored at end of fallback."):(await i?.handleChainError(l),l)})}async*_streamIterator(e,t){const n=L(t),a=await pe(n),{runId:r,...s}=n,i=await a?.handleChainStart(this.toJSON(),K(e,"input"),r,void 0,void 0,void 0,s?.runName);let o,c;for(const d of this.runnables()){n?.signal?.throwIfAborted();const p=H(s,{callbacks:i?.getChild()});try{const f=await d.stream(e,p);c=ra(p,f);break}catch(f){o===void 0&&(o=f)}}if(c===void 0){const d=o??new Error("No error stored at end of fallback.");throw await i?.handleChainError(d),d}let l;try{for await(const d of c){yield d;try{l=l===void 0?l:this._concatOutputChunks(l,d)}catch{l=void 0}}}catch(d){throw await i?.handleChainError(d),d}await i?.handleChainEnd(K(l,"output"))}async batch(e,t,n){if(n?.returnExceptions)throw new Error("Not implemented.");const a=this._getOptionsList(t??{},e.length),r=await Promise.all(a.map(o=>pe(o))),s=await Promise.all(r.map(async(o,c)=>{const l=await o?.handleChainStart(this.toJSON(),K(e[c],"input"),a[c].runId,void 0,void 0,void 0,a[c].runName);return delete a[c].runId,l}));let i;for(const o of this.runnables()){a[0].signal?.throwIfAborted();try{const c=await o.batch(e,s.map((l,d)=>H(a[d],{callbacks:l?.getChild()})),n);return await Promise.all(s.map((l,d)=>l?.handleChainEnd(K(c[d],"output")))),c}catch(c){i===void 0&&(i=c)}}throw i?(await Promise.all(s.map(o=>o?.handleChainError(i))),i):new Error("No error stored at end of fallbacks.")}};function ve(e){if(typeof e=="function")return new Ge({func:e});if(V.isRunnable(e))return e;if(!Array.isArray(e)&&typeof e=="object"){const t={};for(const[n,a]of Object.entries(e))t[n]=ve(a);return new gt({steps:t})}else throw new Error(`Expected a Runnable, function or object.
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}
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(`
76
- `);return Promise.resolve([...t.slice(0,-1).map(n=>`${n}
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.
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()
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:
80
-
81
- 1. foo
82
-
83
- 2. bar
84
-
85
- 3. baz`}re=/\d+\.\s([^\n]+)/g;async parse(e){return[...e.matchAll(this.re)??[]].map(t=>t[1])}},Bd=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:
86
-
87
- 1. foo
88
-
89
- 2. bar
90
-
91
- 3. baz`}re=/^\s*[-*]\s([^\n]+)$/gm;async parse(e){return[...e.matchAll(this.re)??[]].map(t=>t[1])}},zd=class extends Rt{static lc_name(){return"StrOutputParser"}lc_namespace=["langchain_core","output_parsers","string"];lc_serializable=!0;parse(e){return Promise.resolve(e)}getFormatInstructions(){return""}_textContentToString(e){return e.text}_imageUrlContentToString(e){throw new Error('Cannot coerce a multimodal "image_url" message part into a string.')}_messageContentToString(e){switch(e.type){case"text":case"text_delta":if("text"in e)return this._textContentToString(e);break;case"image_url":if("image_url"in e)return this._imageUrlContentToString(e);break;default:throw new Error(`Cannot coerce "${e.type}" message part into a string.`)}throw new Error(`Invalid content type: ${e.type}`)}_baseMessageContentToString(e){return e.reduce((t,n)=>t+this._messageContentToString(n),"")}},vi=class extends pn{static lc_name(){return"StructuredOutputParser"}lc_namespace=["langchain","output_parsers","structured"];toJSON(){return this.toJSONNotImplemented()}constructor(e){super(e),this.schema=e}static fromZodSchema(e){return new this(e)}static fromNamesAndDescriptions(e){const t=la(Object.fromEntries(Object.entries(e).map(([n,a])=>[n,ua().describe(a)])));return new this(t)}getFormatInstructions(){return`You must format your output as a JSON value that adheres to a given "JSON Schema" instance.
92
-
93
- "JSON Schema" is a declarative language that allows you to annotate and validate JSON documents.
94
-
95
- For example, the example "JSON Schema" instance {{"properties": {{"foo": {{"description": "a list of test words", "type": "array", "items": {{"type": "string"}}}}}}, "required": ["foo"]}}
96
- would match an object with one required property, "foo". The "type" property specifies "foo" must be an "array", and the "description" property semantically describes it as "a list of test words". The items within "foo" must be strings.
97
- Thus, the object {{"foo": ["bar", "baz"]}} is a well-formatted instance of this example "JSON Schema". The object {{"properties": {{"foo": ["bar", "baz"]}}}} is not well-formatted.
98
-
99
- Your output will be parsed and type-checked according to the provided schema instance, so make sure all fields in your output match the schema exactly and there are no trailing commas!
100
-
101
- Here is the JSON Schema instance your output must adhere to. Include the enclosing markdown codeblock:
102
- \`\`\`json
103
- ${JSON.stringify(mt(this.schema))}
104
- \`\`\`
105
- `}async parse(e){try{const t=e.trim(),a=(t.match(/^```(?:json)?\s*([\s\S]*?)```/)?.[1]||t.match(/```json\s*([\s\S]*?)```/)?.[1]||t).replace(/"([^"\\]*(\\.[^"\\]*)*)"/g,(r,s)=>`"${s.replace(/\n/g,"\\n")}"`).replace(/\n/g,"");return await Ca(this.schema,JSON.parse(a))}catch(t){throw new We(`Failed to parse. Text: "${e}". Error: ${t}`,e)}}},Ti=class extends vi{static lc_name(){return"JsonMarkdownStructuredOutputParser"}getFormatInstructions(e){const t=e?.interpolationDepth??1;if(t<1)throw new Error("f string interpolation depth must be at least 1");return`Return a markdown code snippet with a JSON object formatted to look like:
106
- \`\`\`json
107
- ${this._schemaToInstruction(mt(this.schema)).replaceAll("{","{".repeat(t)).replaceAll("}","}".repeat(t))}
108
- \`\`\``}_schemaToInstruction(e,t=2){const n=e;if("type"in n){let a=!1,r;if(Array.isArray(n.type)){const o=n.type.findIndex(c=>c==="null");o!==-1&&(a=!0,n.type.splice(o,1)),r=n.type.join(" | ")}else r=n.type;if(n.type==="object"&&n.properties){const o=n.description?` // ${n.description}`:"";return`{
109
- ${Object.entries(n.properties).map(([l,d])=>{const p=n.required?.includes(l)?"":" (optional)";return`${" ".repeat(t)}"${l}": ${this._schemaToInstruction(d,t+2)}${p}`}).join(`
110
- `)}
111
- ${" ".repeat(t-2)}}${o}`}if(n.type==="array"&&n.items){const o=n.description?` // ${n.description}`:"";return`array[
112
- ${" ".repeat(t)}${this._schemaToInstruction(n.items,t+2)}
113
- ${" ".repeat(t-2)}] ${o}`}const s=a?" (nullable)":"",i=n.description?` // ${n.description}`:"";return`${r}${i}${s}`}if("anyOf"in n)return n.anyOf.map(a=>this._schemaToInstruction(a,t)).join(`
114
- ${" ".repeat(t-2)}`);throw new Error("unsupported schema type")}static fromZodSchema(e){return new this(e)}static fromNamesAndDescriptions(e){const t=la(Object.fromEntries(Object.entries(e).map(([n,a])=>[n,ua().describe(a)])));return new this(t)}},Hd=class extends pn{structuredInputParser;constructor({inputSchema:e}){super(...arguments),this.structuredInputParser=new Ti(e)}async parse(e){let t;try{t=await this.structuredInputParser.parse(e)}catch(n){throw new We(`Failed to parse. Text: "${e}". Error: ${n}`,e)}return this.outputProcessor(t)}getFormatInstructions(){return this.structuredInputParser.getFormatInstructions()}},Gd={};F(Gd,{applyPatch:()=>dt,compare:()=>Aa});var Vd=class extends $a{static lc_name(){return"JsonOutputParser"}lc_namespace=["langchain_core","output_parsers"];lc_serializable=!0;_concatOutputChunks(e,t){return this.diff?super._concatOutputChunks(e,t):t}_diff(e,t){if(t)return e?Aa(e,t):[{op:"replace",path:"",value:t}]}async parsePartialResult(e){return jn(e[0].text)}async parse(e){return jn(e,JSON.parse)}getFormatInstructions(){return""}};const Zd=function(){const e={};e.parser=function(h,u){return new n(h,u)},e.SAXParser=n,e.SAXStream=l,e.createStream=c,e.MAX_BUFFER_LENGTH=64*1024;const t=["comment","sgmlDecl","textNode","tagName","doctype","procInstName","procInstBody","entity","attribName","attribValue","cdata","script"];e.EVENTS=["text","processinginstruction","sgmldeclaration","doctype","comment","opentagstart","attribute","opentag","closetag","opencdata","cdata","closecdata","error","end","ready","script","opennamespace","closenamespace"];function n(h,u){if(!(this instanceof n))return new n(h,u);var w=this;r(w),w.q=w.c="",w.bufferCheckPosition=e.MAX_BUFFER_LENGTH,w.opt=u||{},w.opt.lowercase=w.opt.lowercase||w.opt.lowercasetags,w.looseCase=w.opt.lowercase?"toLowerCase":"toUpperCase",w.tags=[],w.closed=w.closedRoot=w.sawRoot=!1,w.tag=w.error=null,w.strict=!!h,w.noscript=!!(h||w.opt.noscript),w.state=g.BEGIN,w.strictEntities=w.opt.strictEntities,w.ENTITIES=w.strictEntities?Object.create(e.XML_ENTITIES):Object.create(e.ENTITIES),w.attribList=[],w.opt.xmlns&&(w.ns=Object.create(y)),w.trackPosition=w.opt.position!==!1,w.trackPosition&&(w.position=w.line=w.column=0),ne(w,"onready")}Object.create||(Object.create=function(h){function u(){}u.prototype=h;var w=new u;return w}),Object.keys||(Object.keys=function(h){var u=[];for(var w in h)h.hasOwnProperty(w)&&u.push(w);return u});function a(h){for(var u=Math.max(e.MAX_BUFFER_LENGTH,10),w=0,_=0,j=t.length;_<j;_++){var J=h[t[_]].length;if(J>u)switch(t[_]){case"textNode":Se(h);break;case"cdata":z(h,"oncdata",h.cdata),h.cdata="";break;case"script":z(h,"onscript",h.script),h.script="";break;default:Mt(h,"Max buffer length exceeded: "+t[_])}w=Math.max(w,J)}var W=e.MAX_BUFFER_LENGTH-w;h.bufferCheckPosition=W+h.position}function r(h){for(var u=0,w=t.length;u<w;u++)h[t[u]]=""}function s(h){Se(h),h.cdata!==""&&(z(h,"oncdata",h.cdata),h.cdata=""),h.script!==""&&(z(h,"onscript",h.script),h.script="")}n.prototype={end:function(){Da(this)},write:Ai,resume:function(){return this.error=null,this},close:function(){return this.write(null)},flush:function(){s(this)}};var i=ReadableStream;i||(i=function(){});var o=e.EVENTS.filter(function(h){return h!=="error"&&h!=="end"});function c(h,u){return new l(h,u)}function l(h,u){if(!(this instanceof l))return new l(h,u);i.apply(this),this._parser=new n(h,u),this.writable=!0,this.readable=!0;var w=this;this._parser.onend=function(){w.emit("end")},this._parser.onerror=function(_){w.emit("error",_),w._parser.error=null},this._decoder=null,o.forEach(function(_){Object.defineProperty(w,"on"+_,{get:function(){return w._parser["on"+_]},set:function(j){if(!j)return w.removeAllListeners(_),w._parser["on"+_]=j,j;w.on(_,j)},enumerable:!0,configurable:!1})})}l.prototype=Object.create(i.prototype,{constructor:{value:l}}),l.prototype.write=function(h){return this._parser.write(h.toString()),this.emit("data",h),!0},l.prototype.end=function(h){return h&&h.length&&this.write(h),this._parser.end(),!0},l.prototype.on=function(h,u){var w=this;return!w._parser["on"+h]&&o.indexOf(h)!==-1&&(w._parser["on"+h]=function(){var _=arguments.length===1?[arguments[0]]:Array.apply(null,arguments);_.splice(0,0,h),w.emit.apply(w,_)}),i.prototype.on.call(w,h,u)};var d="[CDATA[",p="DOCTYPE",f="http://www.w3.org/XML/1998/namespace",m="http://www.w3.org/2000/xmlns/",y={xml:f,xmlns:m},b=/[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/,T=/[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/,v=/[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/,I=/[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/;function E(h){return h===" "||h===`
115
- `||h==="\r"||h===" "}function x(h){return h==='"'||h==="'"}function N(h){return h===">"||E(h)}function M(h,u){return h.test(u)}function B(h,u){return!M(h,u)}var g=0;e.STATE={BEGIN:g++,BEGIN_WHITESPACE:g++,TEXT:g++,TEXT_ENTITY:g++,OPEN_WAKA:g++,SGML_DECL:g++,SGML_DECL_QUOTED:g++,DOCTYPE:g++,DOCTYPE_QUOTED:g++,DOCTYPE_DTD:g++,DOCTYPE_DTD_QUOTED:g++,COMMENT_STARTING:g++,COMMENT:g++,COMMENT_ENDING:g++,COMMENT_ENDED:g++,CDATA:g++,CDATA_ENDING:g++,CDATA_ENDING_2:g++,PROC_INST:g++,PROC_INST_BODY:g++,PROC_INST_ENDING:g++,OPEN_TAG:g++,OPEN_TAG_SLASH:g++,ATTRIB:g++,ATTRIB_NAME:g++,ATTRIB_NAME_SAW_WHITE:g++,ATTRIB_VALUE:g++,ATTRIB_VALUE_QUOTED:g++,ATTRIB_VALUE_CLOSED:g++,ATTRIB_VALUE_UNQUOTED:g++,ATTRIB_VALUE_ENTITY_Q:g++,ATTRIB_VALUE_ENTITY_U:g++,CLOSE_TAG:g++,CLOSE_TAG_SAW_WHITE:g++,SCRIPT:g++,SCRIPT_ENDING:g++},e.XML_ENTITIES={amp:"&",gt:">",lt:"<",quot:'"',apos:"'"},e.ENTITIES={amp:"&",gt:">",lt:"<",quot:'"',apos:"'",AElig:198,Aacute:193,Acirc:194,Agrave:192,Aring:197,Atilde:195,Auml:196,Ccedil:199,ETH:208,Eacute:201,Ecirc:202,Egrave:200,Euml:203,Iacute:205,Icirc:206,Igrave:204,Iuml:207,Ntilde:209,Oacute:211,Ocirc:212,Ograve:210,Oslash:216,Otilde:213,Ouml:214,THORN:222,Uacute:218,Ucirc:219,Ugrave:217,Uuml:220,Yacute:221,aacute:225,acirc:226,aelig:230,agrave:224,aring:229,atilde:227,auml:228,ccedil:231,eacute:233,ecirc:234,egrave:232,eth:240,euml:235,iacute:237,icirc:238,igrave:236,iuml:239,ntilde:241,oacute:243,ocirc:244,ograve:242,oslash:248,otilde:245,ouml:246,szlig:223,thorn:254,uacute:250,ucirc:251,ugrave:249,uuml:252,yacute:253,yuml:255,copy:169,reg:174,nbsp:160,iexcl:161,cent:162,pound:163,curren:164,yen:165,brvbar:166,sect:167,uml:168,ordf:170,laquo:171,not:172,shy:173,macr:175,deg:176,plusmn:177,sup1:185,sup2:178,sup3:179,acute:180,micro:181,para:182,middot:183,cedil:184,ordm:186,raquo:187,frac14:188,frac12:189,frac34:190,iquest:191,times:215,divide:247,OElig:338,oelig:339,Scaron:352,scaron:353,Yuml:376,fnof:402,circ:710,tilde:732,Alpha:913,Beta:914,Gamma:915,Delta:916,Epsilon:917,Zeta:918,Eta:919,Theta:920,Iota:921,Kappa:922,Lambda:923,Mu:924,Nu:925,Xi:926,Omicron:927,Pi:928,Rho:929,Sigma:931,Tau:932,Upsilon:933,Phi:934,Chi:935,Psi:936,Omega:937,alpha:945,beta:946,gamma:947,delta:948,epsilon:949,zeta:950,eta:951,theta:952,iota:953,kappa:954,lambda:955,mu:956,nu:957,xi:958,omicron:959,pi:960,rho:961,sigmaf:962,sigma:963,tau:964,upsilon:965,phi:966,chi:967,psi:968,omega:969,thetasym:977,upsih:978,piv:982,ensp:8194,emsp:8195,thinsp:8201,zwnj:8204,zwj:8205,lrm:8206,rlm:8207,ndash:8211,mdash:8212,lsquo:8216,rsquo:8217,sbquo:8218,ldquo:8220,rdquo:8221,bdquo:8222,dagger:8224,Dagger:8225,bull:8226,hellip:8230,permil:8240,prime:8242,Prime:8243,lsaquo:8249,rsaquo:8250,oline:8254,frasl:8260,euro:8364,image:8465,weierp:8472,real:8476,trade:8482,alefsym:8501,larr:8592,uarr:8593,rarr:8594,darr:8595,harr:8596,crarr:8629,lArr:8656,uArr:8657,rArr:8658,dArr:8659,hArr:8660,forall:8704,part:8706,exist:8707,empty:8709,nabla:8711,isin:8712,notin:8713,ni:8715,prod:8719,sum:8721,minus:8722,lowast:8727,radic:8730,prop:8733,infin:8734,ang:8736,and:8743,or:8744,cap:8745,cup:8746,int:8747,there4:8756,sim:8764,cong:8773,asymp:8776,ne:8800,equiv:8801,le:8804,ge:8805,sub:8834,sup:8835,nsub:8836,sube:8838,supe:8839,oplus:8853,otimes:8855,perp:8869,sdot:8901,lceil:8968,rceil:8969,lfloor:8970,rfloor:8971,lang:9001,rang:9002,loz:9674,spades:9824,clubs:9827,hearts:9829,diams:9830},Object.keys(e.ENTITIES).forEach(function(h){var u=e.ENTITIES[h],w=typeof u=="number"?String.fromCharCode(u):u;e.ENTITIES[h]=w});for(var te in e.STATE)e.STATE[e.STATE[te]]=te;g=e.STATE;function ne(h,u,w){h[u]&&h[u](w)}function z(h,u,w){h.textNode&&Se(h),ne(h,u,w)}function Se(h){h.textNode=ja(h.opt,h.textNode),h.textNode&&ne(h,"ontext",h.textNode),h.textNode=""}function ja(h,u){return h.trim&&(u=u.trim()),h.normalize&&(u=u.replace(/\s+/g," ")),u}function Mt(h,u){return Se(h),h.trackPosition&&(u+=`
116
- Line: `+h.line+`
117
- Column: `+h.column+`
118
- Char: `+h.c),u=new Error(u),h.error=u,ne(h,"onerror",u),h}function Da(h){return h.sawRoot&&!h.closedRoot&&U(h,"Unclosed root tag"),h.state!==g.BEGIN&&h.state!==g.BEGIN_WHITESPACE&&h.state!==g.TEXT&&Mt(h,"Unexpected end"),Se(h),h.c="",h.closed=!0,ne(h,"onend"),n.call(h,h.strict,h.opt),h}function U(h,u){if(typeof h!="object"||!(h instanceof n))throw new Error("bad call to strictFail");h.strict&&Mt(h,u)}function Si(h){h.strict||(h.tagName=h.tagName[h.looseCase]());var u=h.tags[h.tags.length-1]||h,w=h.tag={name:h.tagName,attributes:{}};h.opt.xmlns&&(w.ns=u.ns),h.attribList.length=0,z(h,"onopentagstart",w)}function fn(h,u){var w=h.indexOf(":"),_=w<0?["",h]:h.split(":"),j=_[0],J=_[1];return u&&h==="xmlns"&&(j="xmlns",J=""),{prefix:j,local:J}}function mn(h){if(h.strict||(h.attribName=h.attribName[h.looseCase]()),h.attribList.indexOf(h.attribName)!==-1||h.tag.attributes.hasOwnProperty(h.attribName)){h.attribName=h.attribValue="";return}if(h.opt.xmlns){var u=fn(h.attribName,!0),w=u.prefix,_=u.local;if(w==="xmlns")if(_==="xml"&&h.attribValue!==f)U(h,"xml: prefix must be bound to "+f+`
119
- Actual: `+h.attribValue);else if(_==="xmlns"&&h.attribValue!==m)U(h,"xmlns: prefix must be bound to "+m+`
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++,_===`
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++,_===`
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.
123
- 1. Output should conform to the tags below.
124
- 2. If tags are not given, make them on your own.
125
- 3. Remember to always open and close all the tags.
126
-
127
- As an example, for the tags ["foo", "bar", "baz"]:
128
- 1. String "<foo>
129
- <bar>
130
- <baz></baz>
131
- </bar>
132
- </foo>" is a well-formatted instance of the schema.
133
- 2. String "<foo>
134
- <bar>
135
- </foo>" is a badly-formatted instance.
136
- 3. String "<foo>
137
- <tag>
138
- </tag>
139
- </foo>" is a badly-formatted instance.
140
-
141
- Here are the output tags:
142
- \`\`\`
143
- {tags}
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(`
145
- `).map(t=>t.replace(/^\s+/,"")).join(`
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};