@mcp-use/inspector 0.9.2 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,8 +1,8 @@
1
- import{V as $n,O as bt,i as jn,U as nn,a as xt,a0 as St,Q as Bn,S as Ln,L as A,J as kt,W as Un,X as qn,P as Wn,t as Fn,H as be,j as Mt,K as Dn,Z as Tt,$ as Hn}from"./index-BxlzAdRz.js";import"./index-DZxMwvFi.js";import"./index-DRz5BQNA.js";var Rt=class extends $n{static lc_name(){return"AnthropicToolsOutputParser"}lc_namespace=["langchain","anthropic","output_parsers"];returnId=!1;keyName;returnSingle=!1;zodSchema;constructor(t){super(t),this.keyName=t.keyName,this.returnSingle=t.returnSingle??this.returnSingle,this.zodSchema=t.zodSchema}async _validateResult(t){let e=t;if(typeof t=="string")try{e=JSON.parse(t)}catch(s){throw new bt(`Failed to parse. Text: "${JSON.stringify(t,null,2)}". Error: ${JSON.stringify(s.message)}`,t)}else e=t;if(this.zodSchema===void 0)return e;const n=await jn(this.zodSchema,e);if(n.success)return n.data;throw new bt(`Failed to parse. Text: "${JSON.stringify(t,null,2)}". Error: ${JSON.stringify(n.error.issues)}`,JSON.stringify(e,null,2))}async parseResult(t){const e=t.flatMap(r=>{const{message:i}=r;return Array.isArray(i.content)?sn(i.content)[0]:[]});if(e[0]===void 0)throw new Error("No parseable tool calls provided to AnthropicToolsOutputParser.");const[n]=e;return await this._validateResult(n.args)}};function sn(t){const e=[];for(const n of t)n.type==="tool_use"&&e.push({name:n.name,args:n.input,id:n.id,type:"tool_call"});return e}function Kn(t){if(t)return t==="any"?{type:"any"}:t==="auto"?{type:"auto"}:t==="none"?{type:"none"}:typeof t=="string"?{type:"tool",name:t}:t}function Jn(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="thinking"}function Xn(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="redacted_thinking"}function zn(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="search_result"}function Vn(t){return typeof t!="object"||t==null||!("type"in t)||t.type!=="image"||!("source"in t)||typeof t.source!="object"||t.source==null||!("type"in t.source)?!1:t.source.type==="base64"?!(!("media_type"in t.source)||typeof t.source.media_type!="string"||!("data"in t.source)||typeof t.source.data!="string"):t.source.type==="url"?!(!("url"in t.source)||typeof t.source.url!="string"):!1}const Qn={providerName:"anthropic",fromStandardTextBlock(t){return{type:"text",text:t.text,..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}}},fromStandardImageBlock(t){if(t.source_type==="url"){const e=nn({dataUrl:t.url,asTypedArray:!1});return e?{type:"image",source:{type:"base64",data:e.data,media_type:e.mime_type},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}}:{type:"image",source:{type:"url",url:t.url},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}}}else{if(t.source_type==="base64")return{type:"image",source:{type:"base64",data:t.data,media_type:t.mime_type??""},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}};throw new Error(`Unsupported image source type: ${t.source_type}`)}},fromStandardFileBlock(t){const e=(t.mime_type??"").split(";")[0];if(t.source_type==="url"){if(e==="application/pdf"||e==="")return{type:"document",source:{type:"url",url:t.url},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};throw new Error(`Unsupported file mime type for file url source: ${t.mime_type}`)}else if(t.source_type==="text"){if(e==="text/plain"||e==="")return{type:"document",source:{type:"text",data:t.text,media_type:t.mime_type??""},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};throw new Error(`Unsupported file mime type for file text source: ${t.mime_type}`)}else if(t.source_type==="base64"){if(e==="application/pdf"||e==="")return{type:"document",source:{type:"base64",data:t.data,media_type:"application/pdf"},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};if(["image/jpeg","image/png","image/gif","image/webp"].includes(e))return{type:"document",source:{type:"content",content:[{type:"image",source:{type:"base64",data:t.data,media_type:e}}]},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};throw new Error(`Unsupported file mime type for file base64 source: ${t.mime_type}`)}else throw new Error(`Unsupported file source type: ${t.source_type}`)}},Gn=t=>t();function Yn(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="citation"}function Zn(t){function*e(){for(const n of t)Yn(n)&&(n.source==="char"?yield{type:"char_location",file_id:n.url??"",start_char_index:n.startIndex??0,end_char_index:n.endIndex??0,document_title:n.title??null,document_index:0,cited_text:n.citedText??""}:n.source==="page"?yield{type:"page_location",file_id:n.url??"",start_page_number:n.startIndex??0,end_page_number:n.endIndex??0,document_title:n.title??null,document_index:0,cited_text:n.citedText??""}:n.source==="block"?yield{type:"content_block_location",file_id:n.url??"",start_block_index:n.startIndex??0,end_block_index:n.endIndex??0,document_title:n.title??null,document_index:0,cited_text:n.citedText??""}:n.source==="url"?yield{type:"web_search_result_location",url:n.url??"",title:n.title??null,encrypted_index:String(n.startIndex??0),cited_text:n.citedText??""}:n.source==="search"&&(yield{type:"search_result_location",title:n.title??null,start_block_index:n.startIndex??0,end_block_index:n.endIndex??0,search_result_index:0,source:n.source??"",cited_text:n.citedText??""}))}return Array.from(e())}function G(t){return typeof t=="string"?t:es(t)}function es(t){const e=[];for(let n=0,{length:s}=t;n<s;n++)e.push(String.fromCharCode(t[n]));return btoa(e.join(""))}function Ve(t){return(t??"").split(";")[0].toLowerCase()}function he(t,e){if(t!=null&&typeof t=="object"&&e in t)return t[e]}function H(t,e){const n=he(e,"cache_control");n!==void 0&&(t.cache_control=n);const s=he(e,"citations");s!==void 0&&(t.citations=s);const r=he(e,"context");r!==void 0&&(t.context=r);const i=he(e,"title");return i!==void 0&&(t.title=i),t}function Qe(t,e){const n=he(e,"cache_control");return n!==void 0&&(t.cache_control=n),t}function At(t){return new Set(["image/jpeg","image/png","image/gif","image/webp"]).has(t)}function ts(t){const e=[],n=t.response_metadata,s="model_provider"in n&&n?.model_provider==="anthropic";for(const r of t.contentBlocks)if(r.type==="text")r.annotations?e.push({type:"text",text:r.text,citations:Zn(r.annotations)}):e.push({type:"text",text:r.text});else if(r.type==="tool_call")e.push({type:"tool_use",id:r.id??"",name:r.name,input:r.args});else if(r.type==="tool_call_chunk"){const i=Gn(()=>{if(typeof r.args!="string")return r.args;try{return JSON.parse(r.args)}catch{return{}}});e.push({type:"tool_use",id:r.id??"",name:r.name??"",input:i})}else if(r.type==="reasoning"&&s)e.push({type:"thinking",thinking:r.reasoning,signature:String(r.signature)});else if(r.type==="server_tool_call"&&s)r.name==="web_search"?e.push({type:"server_tool_use",name:r.name,id:r.id??"",input:r.args}):r.name==="code_execution"&&e.push({type:"server_tool_use",name:r.name,id:r.id??"",input:r.args});else if(r.type==="server_tool_call_result"&&s)if(r.name==="web_search"&&Array.isArray(r.output.urls)){const i=r.output.urls.map(a=>({type:"web_search_result",title:"",encrypted_content:"",url:a}));e.push({type:"web_search_tool_result",tool_use_id:r.toolCallId??"",content:i})}else r.name==="code_execution"?e.push({type:"code_execution_tool_result",tool_use_id:r.toolCallId??"",content:r.output}):r.name==="mcp_tool_result"&&e.push({type:"mcp_tool_result",tool_use_id:r.toolCallId??"",content:r.output});else{if(r.type==="audio")throw new Error("Anthropic does not support audio content blocks.");if(r.type==="file"){const i=r.metadata;if(r.fileId){e.push(H({type:"document",source:{type:"file",file_id:r.fileId}},i));continue}if(r.url){const a=Ve(r.mimeType);if(a==="application/pdf"||a===""){e.push(H({type:"document",source:{type:"url",url:r.url}},i));continue}}if(r.data){const a=Ve(r.mimeType);if(a===""||a==="application/pdf")e.push(H({type:"document",source:{type:"base64",data:G(r.data),media_type:"application/pdf"}},i));else if(a==="text/plain")e.push(H({type:"document",source:{type:"text",data:G(r.data),media_type:"text/plain"}},i));else if(At(a))e.push(H({type:"document",source:{type:"content",content:[{type:"image",source:{type:"base64",data:G(r.data),media_type:a}}]}},i));else throw new Error(`Unsupported file mime type for Anthropic base64 source: ${a}`);continue}throw new Error("File content block must include a fileId, url, or data property.")}else if(r.type==="image"){const i=r.metadata;if(r.fileId){e.push(Qe({type:"image",source:{type:"file",file_id:r.fileId}},i));continue}if(r.url){e.push(Qe({type:"image",source:{type:"url",url:r.url}},i));continue}if(r.data){const a=Ve(r.mimeType)||"image/png";At(a)&&e.push(Qe({type:"image",source:{type:"base64",data:G(r.data),media_type:a}},i));continue}throw new Error("Image content block must include a fileId, url, or data property.")}else r.type==="video"||(r.type==="text-plain"?r.data&&e.push(H({type:"document",source:{type:"text",data:G(r.data),media_type:"text/plain"}},r.metadata)):r.type==="non_standard"&&s&&e.push(r.value))}return e}function vt(t){const e=nn({dataUrl:t});if(e)return{type:"base64",media_type:e.mime_type,data:e.data};let n;try{n=new URL(t)}catch{throw new Error([`Malformed image URL: ${JSON.stringify(t)}. Content blocks of type 'image_url' must be a valid http, https, or base64-encoded data URL.`,"Example: data:image/png;base64,/9j/4AAQSk...","Example: https://example.com/image.jpg"].join(`
1
+ import{g as $n,O as bt,h as jn,f as Bn,e as Ln,R as xt}from"./index-uLaqVHqx.js";import{i as Un,J as nn,a as St,ae as kt,H as qn,I as Wn,D as A,z as Mt,K as Fn,x as be,g as Tt,B as Dn,L as Hn}from"./index-DLvycrCn.js";import"./index-C86qnUPq.js";import"./index-DRz5BQNA.js";var Rt=class extends $n{static lc_name(){return"AnthropicToolsOutputParser"}lc_namespace=["langchain","anthropic","output_parsers"];returnId=!1;keyName;returnSingle=!1;zodSchema;constructor(t){super(t),this.keyName=t.keyName,this.returnSingle=t.returnSingle??this.returnSingle,this.zodSchema=t.zodSchema}async _validateResult(t){let e=t;if(typeof t=="string")try{e=JSON.parse(t)}catch(s){throw new bt(`Failed to parse. Text: "${JSON.stringify(t,null,2)}". Error: ${JSON.stringify(s.message)}`,t)}else e=t;if(this.zodSchema===void 0)return e;const n=await Un(this.zodSchema,e);if(n.success)return n.data;throw new bt(`Failed to parse. Text: "${JSON.stringify(t,null,2)}". Error: ${JSON.stringify(n.error.issues)}`,JSON.stringify(e,null,2))}async parseResult(t){const e=t.flatMap(r=>{const{message:i}=r;return Array.isArray(i.content)?sn(i.content)[0]:[]});if(e[0]===void 0)throw new Error("No parseable tool calls provided to AnthropicToolsOutputParser.");const[n]=e;return await this._validateResult(n.args)}};function sn(t){const e=[];for(const n of t)n.type==="tool_use"&&e.push({name:n.name,args:n.input,id:n.id,type:"tool_call"});return e}function Kn(t){if(t)return t==="any"?{type:"any"}:t==="auto"?{type:"auto"}:t==="none"?{type:"none"}:typeof t=="string"?{type:"tool",name:t}:t}function Jn(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="thinking"}function Xn(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="redacted_thinking"}function zn(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="search_result"}function Vn(t){return typeof t!="object"||t==null||!("type"in t)||t.type!=="image"||!("source"in t)||typeof t.source!="object"||t.source==null||!("type"in t.source)?!1:t.source.type==="base64"?!(!("media_type"in t.source)||typeof t.source.media_type!="string"||!("data"in t.source)||typeof t.source.data!="string"):t.source.type==="url"?!(!("url"in t.source)||typeof t.source.url!="string"):!1}const Qn={providerName:"anthropic",fromStandardTextBlock(t){return{type:"text",text:t.text,..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}}},fromStandardImageBlock(t){if(t.source_type==="url"){const e=nn({dataUrl:t.url,asTypedArray:!1});return e?{type:"image",source:{type:"base64",data:e.data,media_type:e.mime_type},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}}:{type:"image",source:{type:"url",url:t.url},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}}}else{if(t.source_type==="base64")return{type:"image",source:{type:"base64",data:t.data,media_type:t.mime_type??""},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}};throw new Error(`Unsupported image source type: ${t.source_type}`)}},fromStandardFileBlock(t){const e=(t.mime_type??"").split(";")[0];if(t.source_type==="url"){if(e==="application/pdf"||e==="")return{type:"document",source:{type:"url",url:t.url},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};throw new Error(`Unsupported file mime type for file url source: ${t.mime_type}`)}else if(t.source_type==="text"){if(e==="text/plain"||e==="")return{type:"document",source:{type:"text",data:t.text,media_type:t.mime_type??""},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};throw new Error(`Unsupported file mime type for file text source: ${t.mime_type}`)}else if(t.source_type==="base64"){if(e==="application/pdf"||e==="")return{type:"document",source:{type:"base64",data:t.data,media_type:"application/pdf"},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};if(["image/jpeg","image/png","image/gif","image/webp"].includes(e))return{type:"document",source:{type:"content",content:[{type:"image",source:{type:"base64",data:t.data,media_type:e}}]},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};throw new Error(`Unsupported file mime type for file base64 source: ${t.mime_type}`)}else throw new Error(`Unsupported file source type: ${t.source_type}`)}},Gn=t=>t();function Yn(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="citation"}function Zn(t){function*e(){for(const n of t)Yn(n)&&(n.source==="char"?yield{type:"char_location",file_id:n.url??"",start_char_index:n.startIndex??0,end_char_index:n.endIndex??0,document_title:n.title??null,document_index:0,cited_text:n.citedText??""}:n.source==="page"?yield{type:"page_location",file_id:n.url??"",start_page_number:n.startIndex??0,end_page_number:n.endIndex??0,document_title:n.title??null,document_index:0,cited_text:n.citedText??""}:n.source==="block"?yield{type:"content_block_location",file_id:n.url??"",start_block_index:n.startIndex??0,end_block_index:n.endIndex??0,document_title:n.title??null,document_index:0,cited_text:n.citedText??""}:n.source==="url"?yield{type:"web_search_result_location",url:n.url??"",title:n.title??null,encrypted_index:String(n.startIndex??0),cited_text:n.citedText??""}:n.source==="search"&&(yield{type:"search_result_location",title:n.title??null,start_block_index:n.startIndex??0,end_block_index:n.endIndex??0,search_result_index:0,source:n.source??"",cited_text:n.citedText??""}))}return Array.from(e())}function G(t){return typeof t=="string"?t:es(t)}function es(t){const e=[];for(let n=0,{length:s}=t;n<s;n++)e.push(String.fromCharCode(t[n]));return btoa(e.join(""))}function Ve(t){return(t??"").split(";")[0].toLowerCase()}function he(t,e){if(t!=null&&typeof t=="object"&&e in t)return t[e]}function H(t,e){const n=he(e,"cache_control");n!==void 0&&(t.cache_control=n);const s=he(e,"citations");s!==void 0&&(t.citations=s);const r=he(e,"context");r!==void 0&&(t.context=r);const i=he(e,"title");return i!==void 0&&(t.title=i),t}function Qe(t,e){const n=he(e,"cache_control");return n!==void 0&&(t.cache_control=n),t}function At(t){return new Set(["image/jpeg","image/png","image/gif","image/webp"]).has(t)}function ts(t){const e=[],n=t.response_metadata,s="model_provider"in n&&n?.model_provider==="anthropic";for(const r of t.contentBlocks)if(r.type==="text")r.annotations?e.push({type:"text",text:r.text,citations:Zn(r.annotations)}):e.push({type:"text",text:r.text});else if(r.type==="tool_call")e.push({type:"tool_use",id:r.id??"",name:r.name,input:r.args});else if(r.type==="tool_call_chunk"){const i=Gn(()=>{if(typeof r.args!="string")return r.args;try{return JSON.parse(r.args)}catch{return{}}});e.push({type:"tool_use",id:r.id??"",name:r.name??"",input:i})}else if(r.type==="reasoning"&&s)e.push({type:"thinking",thinking:r.reasoning,signature:String(r.signature)});else if(r.type==="server_tool_call"&&s)r.name==="web_search"?e.push({type:"server_tool_use",name:r.name,id:r.id??"",input:r.args}):r.name==="code_execution"&&e.push({type:"server_tool_use",name:r.name,id:r.id??"",input:r.args});else if(r.type==="server_tool_call_result"&&s)if(r.name==="web_search"&&Array.isArray(r.output.urls)){const i=r.output.urls.map(a=>({type:"web_search_result",title:"",encrypted_content:"",url:a}));e.push({type:"web_search_tool_result",tool_use_id:r.toolCallId??"",content:i})}else r.name==="code_execution"?e.push({type:"code_execution_tool_result",tool_use_id:r.toolCallId??"",content:r.output}):r.name==="mcp_tool_result"&&e.push({type:"mcp_tool_result",tool_use_id:r.toolCallId??"",content:r.output});else{if(r.type==="audio")throw new Error("Anthropic does not support audio content blocks.");if(r.type==="file"){const i=r.metadata;if(r.fileId){e.push(H({type:"document",source:{type:"file",file_id:r.fileId}},i));continue}if(r.url){const a=Ve(r.mimeType);if(a==="application/pdf"||a===""){e.push(H({type:"document",source:{type:"url",url:r.url}},i));continue}}if(r.data){const a=Ve(r.mimeType);if(a===""||a==="application/pdf")e.push(H({type:"document",source:{type:"base64",data:G(r.data),media_type:"application/pdf"}},i));else if(a==="text/plain")e.push(H({type:"document",source:{type:"text",data:G(r.data),media_type:"text/plain"}},i));else if(At(a))e.push(H({type:"document",source:{type:"content",content:[{type:"image",source:{type:"base64",data:G(r.data),media_type:a}}]}},i));else throw new Error(`Unsupported file mime type for Anthropic base64 source: ${a}`);continue}throw new Error("File content block must include a fileId, url, or data property.")}else if(r.type==="image"){const i=r.metadata;if(r.fileId){e.push(Qe({type:"image",source:{type:"file",file_id:r.fileId}},i));continue}if(r.url){e.push(Qe({type:"image",source:{type:"url",url:r.url}},i));continue}if(r.data){const a=Ve(r.mimeType)||"image/png";At(a)&&e.push(Qe({type:"image",source:{type:"base64",data:G(r.data),media_type:a}},i));continue}throw new Error("Image content block must include a fileId, url, or data property.")}else r.type==="video"||(r.type==="text-plain"?r.data&&e.push(H({type:"document",source:{type:"text",data:G(r.data),media_type:"text/plain"}},r.metadata)):r.type==="non_standard"&&s&&e.push(r.value))}return e}function vt(t){const e=nn({dataUrl:t});if(e)return{type:"base64",media_type:e.mime_type,data:e.data};let n;try{n=new URL(t)}catch{throw new Error([`Malformed image URL: ${JSON.stringify(t)}. Content blocks of type 'image_url' must be a valid http, https, or base64-encoded data URL.`,"Example: data:image/png;base64,/9j/4AAQSk...","Example: https://example.com/image.jpg"].join(`
2
2
 
3
3
  `))}if(n.protocol==="http:"||n.protocol==="https:")return{type:"url",url:t};throw new Error([`Invalid image URL protocol: ${JSON.stringify(n.protocol)}. Anthropic only supports images as http, https, or base64-encoded data URLs on 'image_url' content blocks.`,"Example: data:image/png;base64,/9j/4AAQSk...","Example: https://example.com/image.jpg"].join(`
4
4
 
5
- `))}function ns(t){const e=[];for(const n of t)if(n._getType()==="tool")if(typeof n.content=="string"){const s=e[e.length-1];s?._getType()==="human"&&Array.isArray(s.content)&&"type"in s.content[0]&&s.content[0].type==="tool_result"?s.content.push({type:"tool_result",content:n.content,tool_use_id:n.tool_call_id}):e.push(new St({content:[{type:"tool_result",content:n.content,tool_use_id:n.tool_call_id}]}))}else e.push(new St({content:[{type:"tool_result",...n.content!=null?{content:at(n)}:{},tool_use_id:n.tool_call_id}]}));else e.push(n);return e}function Et(t){if(t.id===void 0)throw new Error('Anthropic requires all tool calls to have an "id".');return{type:"tool_use",id:t.id,name:t.name,input:t.args}}function*ss(t){const e=["bash_code_execution_tool_result","input_json_delta","server_tool_use","text_editor_code_execution_tool_result","tool_result","tool_use","web_search_result","web_search_tool_result"],n=["text","text_delta"];for(const s of t){Bn(s)&&(yield Ln(s,Qn));const r="cache_control"in s?s.cache_control:void 0;if(s.type==="image_url"){let i;typeof s.image_url=="string"?i=vt(s.image_url):typeof s.image_url=="object"&&s.image_url!==null&&"url"in s.image_url&&typeof s.image_url.url=="string"&&(i=vt(s.image_url.url)),i&&(yield{type:"image",source:i,...r?{cache_control:r}:{}})}else{if(Vn(s))return s;if(s.type==="document")yield{...s,...r?{cache_control:r}:{}};else if(Jn(s))yield{type:"thinking",thinking:s.thinking,signature:s.signature,...r?{cache_control:r}:{}};else if(Xn(s))yield{type:"redacted_thinking",data:s.data,...r?{cache_control:r}:{}};else if(zn(s))yield{type:"search_result",title:s.title,source:s.source,..."cache_control"in s&&s.cache_control?{cache_control:s.cache_control}:{},..."citations"in s&&s.citations?{citations:s.citations}:{},content:s.content};else if(n.find(i=>i===s.type)&&"text"in s)yield{type:"text",text:s.text,...r?{cache_control:r}:{},..."citations"in s&&s.citations?{citations:s.citations}:{}};else if(e.find(i=>i===s.type)){const i={...s};if("index"in i&&delete i.index,i.type==="input_json_delta"&&(i.type="tool_use"),"input"in i&&typeof i.input=="string")try{i.input=JSON.parse(i.input)}catch{i.input={}}yield{...i,...r?{cache_control:r}:{}}}else s.type==="container_upload"&&(yield{...s,...r?{cache_control:r}:{}})}}}function at(t){const{content:e}=t;return typeof e=="string"?e:Array.from(ss(e))}function Pt(t){const e=ns(t);let n;e.length>0&&e[0]._getType()==="system"&&(n=t[0].content);const r=(n!==void 0?e.slice(1):e).map(i=>{let a;if(i._getType()==="human")a="user";else if(i._getType()==="ai")a="assistant";else if(i._getType()==="tool")a="user";else throw i._getType()==="system"?new Error("System messages are only permitted as the first passed message."):new Error(`Message type "${i.type}" is not supported.`);if(xt(i)&&i.response_metadata?.output_version==="v1")return{role:a,content:ts(i)};if(xt(i)&&i.tool_calls?.length){if(typeof i.content=="string")return i.content===""?{role:a,content:i.tool_calls.map(Et)}:{role:a,content:[{type:"text",text:i.content},...i.tool_calls.map(Et)]};{const{content:c}=i;return!i.tool_calls.every(d=>c.find(f=>(f.type==="tool_use"||f.type==="input_json_delta"||f.type==="server_tool_use")&&f.id===d.id))&&console.warn('The "tool_calls" field on a message is only respected if content is a string.'),{role:a,content:at(i)}}}else return{role:a,content:at(i)}});return{messages:rs(r),system:n}}function rs(t){if(!t||t.length<=1)return t;const e=[];let n=t[0];const s=i=>typeof i=="string"?[{type:"text",text:i}]:i,r=i=>i.role!=="user"||typeof i.content=="string"?!1:Array.isArray(i.content)&&i.content.every(a=>a.type==="tool_result");for(let i=1;i<t.length;i+=1){const a=t[i];r(n)&&r(a)?n={...n,content:[...s(n.content),...s(a.content)]}:(e.push(n),n=a)}return e.push(n),e}function is(t,e){const n={model_provider:"anthropic"};if(t.type==="message_start"){const{content:s,usage:r,...i}=t.message,a={};for(const[m,_]of Object.entries(i))_!=null&&(a[m]=_);const{input_tokens:c,output_tokens:l,...d}=r??{},f={input_tokens:c,output_tokens:l,total_tokens:c+l,input_token_details:{cache_creation:d.cache_creation_input_tokens,cache_read:d.cache_read_input_tokens}};return{chunk:new A({content:e.coerceContentToString?"":[],additional_kwargs:a,usage_metadata:e.streamUsage?f:void 0,response_metadata:{...n,usage:{...d}},id:t.message.id})}}else if(t.type==="message_delta"){const s={input_tokens:0,output_tokens:t.usage.output_tokens,total_tokens:t.usage.output_tokens,input_token_details:{cache_creation:t.usage.cache_creation_input_tokens,cache_read:t.usage.cache_read_input_tokens}},r="context_management"in t.delta?{context_management:t.delta.context_management}:void 0;return{chunk:new A({content:e.coerceContentToString?"":[],response_metadata:r,additional_kwargs:{...t.delta},usage_metadata:e.streamUsage?s:void 0})}}else if(t.type==="content_block_start"&&["tool_use","document","server_tool_use","web_search_tool_result"].includes(t.content_block.type)){const s=t.content_block;let r;return s.type==="tool_use"?r=[{id:s.id,index:t.index,name:s.name,args:""}]:r=[],{chunk:new A({content:e.coerceContentToString?"":[{index:t.index,...t.content_block,input:s.type==="server_tool_use"||s.type==="tool_use"?"":void 0}],response_metadata:n,additional_kwargs:{},tool_call_chunks:r})}}else if(t.type==="content_block_delta"&&["text_delta","citations_delta","thinking_delta","signature_delta"].includes(t.delta.type)){if(e.coerceContentToString&&"text"in t.delta)return{chunk:new A({content:t.delta.text})};{const s=t.delta;return"citation"in s&&(s.citations=[s.citation],delete s.citation),s.type==="thinking_delta"||s.type==="signature_delta"?{chunk:new A({content:[{index:t.index,...s,type:"thinking"}],response_metadata:n})}:{chunk:new A({content:[{index:t.index,...s,type:"text"}],response_metadata:n})}}}else{if(t.type==="content_block_delta"&&t.delta.type==="input_json_delta")return{chunk:new A({content:e.coerceContentToString?"":[{index:t.index,input:t.delta.partial_json,type:t.delta.type}],response_metadata:n,additional_kwargs:{},tool_call_chunks:[{index:t.index,args:t.delta.partial_json}]})};if(t.type==="content_block_start"&&t.content_block.type==="text"){const s=t.content_block?.text;if(s!==void 0)return{chunk:new A({content:e.coerceContentToString?s:[{index:t.index,...t.content_block}],response_metadata:n,additional_kwargs:{}})}}else{if(t.type==="content_block_start"&&t.content_block.type==="redacted_thinking")return{chunk:new A({content:e.coerceContentToString?"":[{index:t.index,...t.content_block}],response_metadata:n})};if(t.type==="content_block_start"&&t.content_block.type==="thinking"){const s=t.content_block.thinking;return{chunk:new A({content:e.coerceContentToString?s:[{index:t.index,...t.content_block}],response_metadata:n})}}}}return null}function as(t,e){const n={...e,model_provider:"anthropic"},s=e.usage,r=s!=null?{input_tokens:s.input_tokens??0,output_tokens:s.output_tokens??0,total_tokens:(s.input_tokens??0)+(s.output_tokens??0),input_token_details:{cache_creation:s.cache_creation_input_tokens,cache_read:s.cache_read_input_tokens}}:void 0;if(t.length===1&&t[0].type==="text")return[{text:t[0].text,message:new kt({content:t[0].text,additional_kwargs:e,usage_metadata:r,response_metadata:n,id:e.id})}];{const i=sn(t);return[{text:"",message:new kt({content:t,additional_kwargs:e,tool_calls:i,usage_metadata:r,response_metadata:n,id:e.id})}]}}function xe(t,e){return t.lc_error_code=e,t.message=`${t.message}
5
+ `))}function ns(t){const e=[];for(const n of t)if(n._getType()==="tool")if(typeof n.content=="string"){const s=e[e.length-1];s?._getType()==="human"&&Array.isArray(s.content)&&"type"in s.content[0]&&s.content[0].type==="tool_result"?s.content.push({type:"tool_result",content:n.content,tool_use_id:n.tool_call_id}):e.push(new kt({content:[{type:"tool_result",content:n.content,tool_use_id:n.tool_call_id}]}))}else e.push(new kt({content:[{type:"tool_result",...n.content!=null?{content:at(n)}:{},tool_use_id:n.tool_call_id}]}));else e.push(n);return e}function Et(t){if(t.id===void 0)throw new Error('Anthropic requires all tool calls to have an "id".');return{type:"tool_use",id:t.id,name:t.name,input:t.args}}function*ss(t){const e=["bash_code_execution_tool_result","input_json_delta","server_tool_use","text_editor_code_execution_tool_result","tool_result","tool_use","web_search_result","web_search_tool_result"],n=["text","text_delta"];for(const s of t){qn(s)&&(yield Wn(s,Qn));const r="cache_control"in s?s.cache_control:void 0;if(s.type==="image_url"){let i;typeof s.image_url=="string"?i=vt(s.image_url):typeof s.image_url=="object"&&s.image_url!==null&&"url"in s.image_url&&typeof s.image_url.url=="string"&&(i=vt(s.image_url.url)),i&&(yield{type:"image",source:i,...r?{cache_control:r}:{}})}else{if(Vn(s))return s;if(s.type==="document")yield{...s,...r?{cache_control:r}:{}};else if(Jn(s))yield{type:"thinking",thinking:s.thinking,signature:s.signature,...r?{cache_control:r}:{}};else if(Xn(s))yield{type:"redacted_thinking",data:s.data,...r?{cache_control:r}:{}};else if(zn(s))yield{type:"search_result",title:s.title,source:s.source,..."cache_control"in s&&s.cache_control?{cache_control:s.cache_control}:{},..."citations"in s&&s.citations?{citations:s.citations}:{},content:s.content};else if(n.find(i=>i===s.type)&&"text"in s)yield{type:"text",text:s.text,...r?{cache_control:r}:{},..."citations"in s&&s.citations?{citations:s.citations}:{}};else if(e.find(i=>i===s.type)){const i={...s};if("index"in i&&delete i.index,i.type==="input_json_delta"&&(i.type="tool_use"),"input"in i&&typeof i.input=="string")try{i.input=JSON.parse(i.input)}catch{i.input={}}yield{...i,...r?{cache_control:r}:{}}}else s.type==="container_upload"&&(yield{...s,...r?{cache_control:r}:{}})}}}function at(t){const{content:e}=t;return typeof e=="string"?e:Array.from(ss(e))}function Pt(t){const e=ns(t);let n;e.length>0&&e[0]._getType()==="system"&&(n=t[0].content);const r=(n!==void 0?e.slice(1):e).map(i=>{let a;if(i._getType()==="human")a="user";else if(i._getType()==="ai")a="assistant";else if(i._getType()==="tool")a="user";else throw i._getType()==="system"?new Error("System messages are only permitted as the first passed message."):new Error(`Message type "${i.type}" is not supported.`);if(St(i)&&i.response_metadata?.output_version==="v1")return{role:a,content:ts(i)};if(St(i)&&i.tool_calls?.length){if(typeof i.content=="string")return i.content===""?{role:a,content:i.tool_calls.map(Et)}:{role:a,content:[{type:"text",text:i.content},...i.tool_calls.map(Et)]};{const{content:c}=i;return!i.tool_calls.every(d=>c.find(f=>(f.type==="tool_use"||f.type==="input_json_delta"||f.type==="server_tool_use")&&f.id===d.id))&&console.warn('The "tool_calls" field on a message is only respected if content is a string.'),{role:a,content:at(i)}}}else return{role:a,content:at(i)}});return{messages:rs(r),system:n}}function rs(t){if(!t||t.length<=1)return t;const e=[];let n=t[0];const s=i=>typeof i=="string"?[{type:"text",text:i}]:i,r=i=>i.role!=="user"||typeof i.content=="string"?!1:Array.isArray(i.content)&&i.content.every(a=>a.type==="tool_result");for(let i=1;i<t.length;i+=1){const a=t[i];r(n)&&r(a)?n={...n,content:[...s(n.content),...s(a.content)]}:(e.push(n),n=a)}return e.push(n),e}function is(t,e){const n={model_provider:"anthropic"};if(t.type==="message_start"){const{content:s,usage:r,...i}=t.message,a={};for(const[m,_]of Object.entries(i))_!=null&&(a[m]=_);const{input_tokens:c,output_tokens:l,...d}=r??{},f={input_tokens:c,output_tokens:l,total_tokens:c+l,input_token_details:{cache_creation:d.cache_creation_input_tokens,cache_read:d.cache_read_input_tokens}};return{chunk:new A({content:e.coerceContentToString?"":[],additional_kwargs:a,usage_metadata:e.streamUsage?f:void 0,response_metadata:{...n,usage:{...d}},id:t.message.id})}}else if(t.type==="message_delta"){const s={input_tokens:0,output_tokens:t.usage.output_tokens,total_tokens:t.usage.output_tokens,input_token_details:{cache_creation:t.usage.cache_creation_input_tokens,cache_read:t.usage.cache_read_input_tokens}},r="context_management"in t.delta?{context_management:t.delta.context_management}:void 0;return{chunk:new A({content:e.coerceContentToString?"":[],response_metadata:r,additional_kwargs:{...t.delta},usage_metadata:e.streamUsage?s:void 0})}}else if(t.type==="content_block_start"&&["tool_use","document","server_tool_use","web_search_tool_result"].includes(t.content_block.type)){const s=t.content_block;let r;return s.type==="tool_use"?r=[{id:s.id,index:t.index,name:s.name,args:""}]:r=[],{chunk:new A({content:e.coerceContentToString?"":[{index:t.index,...t.content_block,input:s.type==="server_tool_use"||s.type==="tool_use"?"":void 0}],response_metadata:n,additional_kwargs:{},tool_call_chunks:r})}}else if(t.type==="content_block_delta"&&["text_delta","citations_delta","thinking_delta","signature_delta"].includes(t.delta.type)){if(e.coerceContentToString&&"text"in t.delta)return{chunk:new A({content:t.delta.text})};{const s=t.delta;return"citation"in s&&(s.citations=[s.citation],delete s.citation),s.type==="thinking_delta"||s.type==="signature_delta"?{chunk:new A({content:[{index:t.index,...s,type:"thinking"}],response_metadata:n})}:{chunk:new A({content:[{index:t.index,...s,type:"text"}],response_metadata:n})}}}else{if(t.type==="content_block_delta"&&t.delta.type==="input_json_delta")return{chunk:new A({content:e.coerceContentToString?"":[{index:t.index,input:t.delta.partial_json,type:t.delta.type}],response_metadata:n,additional_kwargs:{},tool_call_chunks:[{index:t.index,args:t.delta.partial_json}]})};if(t.type==="content_block_start"&&t.content_block.type==="text"){const s=t.content_block?.text;if(s!==void 0)return{chunk:new A({content:e.coerceContentToString?s:[{index:t.index,...t.content_block}],response_metadata:n,additional_kwargs:{}})}}else{if(t.type==="content_block_start"&&t.content_block.type==="redacted_thinking")return{chunk:new A({content:e.coerceContentToString?"":[{index:t.index,...t.content_block}],response_metadata:n})};if(t.type==="content_block_start"&&t.content_block.type==="thinking"){const s=t.content_block.thinking;return{chunk:new A({content:e.coerceContentToString?s:[{index:t.index,...t.content_block}],response_metadata:n})}}}}return null}function as(t,e){const n={...e,model_provider:"anthropic"},s=e.usage,r=s!=null?{input_tokens:s.input_tokens??0,output_tokens:s.output_tokens??0,total_tokens:(s.input_tokens??0)+(s.output_tokens??0),input_token_details:{cache_creation:s.cache_creation_input_tokens,cache_read:s.cache_read_input_tokens}}:void 0;if(t.length===1&&t[0].type==="text")return[{text:t[0].text,message:new Mt({content:t[0].text,additional_kwargs:e,usage_metadata:r,response_metadata:n,id:e.id})}];{const i=sn(t);return[{text:"",message:new Mt({content:t,additional_kwargs:e,tool_calls:i,usage_metadata:r,response_metadata:n,id:e.id})}]}}function xe(t,e){return t.lc_error_code=e,t.message=`${t.message}
6
6
 
7
7
  Troubleshooting URL: https://js.langchain.com/docs/troubleshooting/errors/${e}/
8
8
  `,t}function Ot(t){let e;return t.status===400&&t.message.includes("tool")?e=xe(t,"INVALID_TOOL_RESULTS"):t.status===401?e=xe(t,"MODEL_AUTHENTICATION"):t.status===404?e=xe(t,"MODEL_NOT_FOUND"):t.status===429?e=xe(t,"MODEL_RATE_LIMIT"):e=t,e}function u(t,e,n,s,r){if(typeof e=="function"?t!==e||!0:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(t,n),n}function o(t,e,n,s){if(n==="a"&&!s)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!s:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return n==="m"?s:n==="a"?s.call(t):s?s.value:e.get(t)}let rn=function(){const{crypto:t}=globalThis;if(t?.randomUUID)return rn=t.randomUUID.bind(t),t.randomUUID();const e=new Uint8Array(1),n=t?()=>t.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,s=>(+s^n()&15>>+s/4).toString(16))};function fe(t){return typeof t=="object"&&t!==null&&("name"in t&&t.name==="AbortError"||"message"in t&&String(t.message).includes("FetchRequestCanceledException"))}const ot=t=>{if(t instanceof Error)return t;if(typeof t=="object"&&t!==null){try{if(Object.prototype.toString.call(t)==="[object Error]"){const e=new Error(t.message,t.cause?{cause:t.cause}:{});return t.stack&&(e.stack=t.stack),t.cause&&!e.cause&&(e.cause=t.cause),t.name&&(e.name=t.name),e}}catch{}try{return new Error(JSON.stringify(t))}catch{}}return new Error(t)};class p extends Error{}class w extends p{constructor(e,n,s,r){super(`${w.makeMessage(e,n,s)}`),this.status=e,this.headers=r,this.requestID=r?.get("request-id"),this.error=n}static makeMessage(e,n,s){const r=n?.message?typeof n.message=="string"?n.message:JSON.stringify(n.message):n?JSON.stringify(n):s;return e&&r?`${e} ${r}`:e?`${e} status code (no body)`:r||"(no status code or body)"}static generate(e,n,s,r){if(!e||!r)return new He({message:s,cause:ot(n)});const i=n;return e===400?new on(e,i,s,r):e===401?new cn(e,i,s,r):e===403?new ln(e,i,s,r):e===404?new un(e,i,s,r):e===409?new hn(e,i,s,r):e===422?new dn(e,i,s,r):e===429?new pn(e,i,s,r):e>=500?new fn(e,i,s,r):new w(e,i,s,r)}}class v extends w{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class He extends w{constructor({message:e,cause:n}){super(void 0,void 0,e||"Connection error.",void 0),n&&(this.cause=n)}}class an extends He{constructor({message:e}={}){super({message:e??"Request timed out."})}}class on extends w{}class cn extends w{}class ln extends w{}class un extends w{}class hn extends w{}class dn extends w{}class pn extends w{}class fn extends w{}const os=/^[a-z][a-z0-9+.-]*:/i,cs=t=>os.test(t);let ct=t=>(ct=Array.isArray,ct(t)),Ct=ct;function It(t){return typeof t!="object"?{}:t??{}}function ls(t){if(!t)return!0;for(const e in t)return!1;return!0}function us(t,e){return Object.prototype.hasOwnProperty.call(t,e)}const hs=(t,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new p(`${t} must be an integer`);if(e<0)throw new p(`${t} must be a positive integer`);return e},mn=t=>{try{return JSON.parse(t)}catch{return}},ds=t=>new Promise(e=>setTimeout(e,t)),z="0.65.0",ps=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function fs(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}const ms=()=>{const t=fs();if(t==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":z,"X-Stainless-OS":$t(Deno.build.os),"X-Stainless-Arch":Nt(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":z,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(t==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":z,"X-Stainless-OS":$t(globalThis.process.platform??"unknown"),"X-Stainless-Arch":Nt(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};const e=gs();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":z,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":z,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function gs(){if(typeof navigator>"u"||!navigator)return null;const t=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(const{key:e,pattern:n}of t){const s=n.exec(navigator.userAgent);if(s){const r=s[1]||0,i=s[2]||0,a=s[3]||0;return{browser:e,version:`${r}.${i}.${a}`}}}return null}const Nt=t=>t==="x32"?"x32":t==="x86_64"||t==="x64"?"x64":t==="arm"?"arm":t==="aarch64"||t==="arm64"?"arm64":t?`other:${t}`:"unknown",$t=t=>(t=t.toLowerCase(),t.includes("ios")?"iOS":t==="android"?"Android":t==="darwin"?"MacOS":t==="win32"?"Windows":t==="freebsd"?"FreeBSD":t==="openbsd"?"OpenBSD":t==="linux"?"Linux":t?`Other:${t}`:"Unknown");let jt;const _s=()=>jt??(jt=ms());function ys(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Anthropic({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function gn(...t){const e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...t)}function _n(t){let e=Symbol.asyncIterator in t?t[Symbol.asyncIterator]():t[Symbol.iterator]();return gn({start(){},async pull(n){const{done:s,value:r}=await e.next();s?n.close():n.enqueue(r)},async cancel(){await e.return?.()}})}function pt(t){if(t[Symbol.asyncIterator])return t;const e=t.getReader();return{async next(){try{const n=await e.read();return n?.done&&e.releaseLock(),n}catch(n){throw e.releaseLock(),n}},async return(){const n=e.cancel();return e.releaseLock(),await n,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function ws(t){if(t===null||typeof t!="object")return;if(t[Symbol.asyncIterator]){await t[Symbol.asyncIterator]().return?.();return}const e=t.getReader(),n=e.cancel();e.releaseLock(),await n}const bs=({headers:t,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});function xs(t){let e=0;for(const r of t)e+=r.length;const n=new Uint8Array(e);let s=0;for(const r of t)n.set(r,s),s+=r.length;return n}let Bt;function ft(t){let e;return(Bt??(e=new globalThis.TextEncoder,Bt=e.encode.bind(e)))(t)}let Lt;function Ut(t){let e;return(Lt??(e=new globalThis.TextDecoder,Lt=e.decode.bind(e)))(t)}var k,M;class me{constructor(){k.set(this,void 0),M.set(this,void 0),u(this,k,new Uint8Array),u(this,M,null)}decode(e){if(e==null)return[];const n=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?ft(e):e;u(this,k,xs([o(this,k,"f"),n]));const s=[];let r;for(;(r=Ss(o(this,k,"f"),o(this,M,"f")))!=null;){if(r.carriage&&o(this,M,"f")==null){u(this,M,r.index);continue}if(o(this,M,"f")!=null&&(r.index!==o(this,M,"f")+1||r.carriage)){s.push(Ut(o(this,k,"f").subarray(0,o(this,M,"f")-1))),u(this,k,o(this,k,"f").subarray(o(this,M,"f"))),u(this,M,null);continue}const i=o(this,M,"f")!==null?r.preceding-1:r.preceding,a=Ut(o(this,k,"f").subarray(0,i));s.push(a),u(this,k,o(this,k,"f").subarray(r.index)),u(this,M,null)}return s}flush(){return o(this,k,"f").length?this.decode(`
@@ -22,4 +22,4 @@ If you understand the risks and have appropriate mitigations in place,
22
22
  you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
23
23
 
24
24
  new Anthropic({ apiKey, dangerouslyAllowBrowser: true });
25
- `);this.baseURL=i.baseURL,this.timeout=i.timeout??gt.DEFAULT_TIMEOUT,this.logger=i.logger??console;const a="warn";this.logLevel=a,this.logLevel=qt(i.logLevel,"ClientOptions.logLevel",this)??qt(Le("ANTHROPIC_LOG"),"process.env['ANTHROPIC_LOG']",this)??a,this.fetchOptions=i.fetchOptions,this.maxRetries=i.maxRetries??2,this.fetch=i.fetch??ys(),u(this,qe,bs),this._options=i,this.apiKey=n,this.authToken=s}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,authToken:this.authToken,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:n}){if(!(this.apiKey&&e.get("x-api-key"))&&!n.has("x-api-key")&&!(this.authToken&&e.get("authorization"))&&!n.has("authorization"))throw new Error('Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted')}async authHeaders(e){return g([await this.apiKeyAuth(e),await this.bearerAuth(e)])}async apiKeyAuth(e){if(this.apiKey!=null)return g([{"X-Api-Key":this.apiKey}])}async bearerAuth(e){if(this.authToken!=null)return g([{Authorization:`Bearer ${this.authToken}`}])}stringifyQuery(e){return Object.entries(e).filter(([n,s])=>typeof s<"u").map(([n,s])=>{if(typeof s=="string"||typeof s=="number"||typeof s=="boolean")return`${encodeURIComponent(n)}=${encodeURIComponent(s)}`;if(s===null)return`${encodeURIComponent(n)}=`;throw new p(`Cannot stringify type ${typeof s}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}getUserAgent(){return`${this.constructor.name}/JS ${z}`}defaultIdempotencyKey(){return`stainless-node-retry-${rn()}`}makeStatusError(e,n,s,r){return w.generate(e,n,s,r)}buildURL(e,n,s){const r=!o(this,dt,"m",Nn).call(this)&&s||this.baseURL,i=cs(e)?new URL(e):new URL(r+(r.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),a=this.defaultQuery();return ls(a)||(n={...a,...n}),typeof n=="object"&&n&&!Array.isArray(n)&&(i.search=this.stringifyQuery(n)),i.toString()}_calculateNonstreamingTimeout(e){if(3600*e/128e3>600)throw new p("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details");return 600*1e3}async prepareOptions(e){}async prepareRequest(e,{url:n,options:s}){}get(e,n){return this.methodRequest("get",e,n)}post(e,n){return this.methodRequest("post",e,n)}patch(e,n){return this.methodRequest("patch",e,n)}put(e,n){return this.methodRequest("put",e,n)}delete(e,n){return this.methodRequest("delete",e,n)}methodRequest(e,n,s){return this.request(Promise.resolve(s).then(r=>({method:e,path:n,...r})))}request(e,n=null){return new Ke(this,this.makeRequest(e,n,void 0))}async makeRequest(e,n,s){const r=await e,i=r.maxRetries??this.maxRetries;n==null&&(n=i),await this.prepareOptions(r);const{req:a,url:c,timeout:l}=await this.buildRequest(r,{retryCount:i-n});await this.prepareRequest(a,{url:c,options:r});const d="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),f=s===void 0?"":`, retryOf: ${s}`,m=Date.now();if(x(this).debug(`[${d}] sending request`,D({retryOfRequestLogID:s,method:r.method,url:c,options:r,headers:a.headers})),r.signal?.aborted)throw new v;const _=new AbortController,h=await this.fetchWithTimeout(c,a,l,_).catch(ot),b=Date.now();if(h instanceof globalThis.Error){const I=`retrying, ${n} attempts remaining`;if(r.signal?.aborted)throw new v;const P=fe(h)||/timed? ?out/i.test(String(h)+("cause"in h?String(h.cause):""));if(n)return x(this).info(`[${d}] connection ${P?"timed out":"failed"} - ${I}`),x(this).debug(`[${d}] connection ${P?"timed out":"failed"} (${I})`,D({retryOfRequestLogID:s,url:c,durationMs:b-m,message:h.message})),this.retryRequest(r,n,s??d);throw x(this).info(`[${d}] connection ${P?"timed out":"failed"} - error; no more retries left`),x(this).debug(`[${d}] connection ${P?"timed out":"failed"} (error; no more retries left)`,D({retryOfRequestLogID:s,url:c,durationMs:b-m,message:h.message})),P?new an:new He({cause:h})}const W=[...h.headers.entries()].filter(([I])=>I==="request-id").map(([I,P])=>", "+I+": "+JSON.stringify(P)).join(""),ze=`[${d}${f}${W}] ${a.method} ${c} ${h.ok?"succeeded":"failed"} with status ${h.status} in ${b-m}ms`;if(!h.ok){const I=await this.shouldRetry(h);if(n&&I){const we=`retrying, ${n} attempts remaining`;return await ws(h.body),x(this).info(`${ze} - ${we}`),x(this).debug(`[${d}] response error (${we})`,D({retryOfRequestLogID:s,url:h.url,status:h.status,headers:h.headers,durationMs:b-m})),this.retryRequest(r,n,s??d,h.headers)}const P=I?"error; no more retries left":"error; not retryable";x(this).info(`${ze} - ${P}`);const _t=await h.text().catch(we=>ot(we).message),yt=mn(_t),wt=yt?void 0:_t;throw x(this).debug(`[${d}] response error (${P})`,D({retryOfRequestLogID:s,url:h.url,status:h.status,headers:h.headers,message:wt,durationMs:Date.now()-m})),this.makeStatusError(h.status,yt,wt,h.headers)}return x(this).info(ze),x(this).debug(`[${d}] response start`,D({retryOfRequestLogID:s,url:h.url,status:h.status,headers:h.headers,durationMs:b-m})),{response:h,options:r,controller:_,requestLogID:d,retryOfRequestLogID:s,startTime:m}}getAPIList(e,n,s){return this.requestAPIList(n,{method:"get",path:e,...s})}requestAPIList(e,n){const s=this.makeRequest(n,null,void 0);return new Ps(this,s,e)}async fetchWithTimeout(e,n,s,r){const{signal:i,method:a,...c}=n||{};i&&i.addEventListener("abort",()=>r.abort());const l=setTimeout(()=>r.abort(),s),d=globalThis.ReadableStream&&c.body instanceof globalThis.ReadableStream||typeof c.body=="object"&&c.body!==null&&Symbol.asyncIterator in c.body,f={signal:r.signal,...d?{duplex:"half"}:{},method:"GET",...c};a&&(f.method=a.toUpperCase());try{return await this.fetch.call(void 0,e,f)}finally{clearTimeout(l)}}async shouldRetry(e){const n=e.headers.get("x-should-retry");return n==="true"?!0:n==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,n,s,r){let i;const a=r?.get("retry-after-ms");if(a){const l=parseFloat(a);Number.isNaN(l)||(i=l)}const c=r?.get("retry-after");if(c&&!i){const l=parseFloat(c);Number.isNaN(l)?i=Date.parse(c)-Date.now():i=l*1e3}if(!(i&&0<=i&&i<60*1e3)){const l=e.maxRetries??this.maxRetries;i=this.calculateDefaultRetryTimeoutMillis(n,l)}return await ds(i),this.makeRequest(e,n-1,s)}calculateDefaultRetryTimeoutMillis(e,n){const i=n-e,a=Math.min(.5*Math.pow(2,i),8),c=1-Math.random()*.25;return a*c*1e3}calculateNonstreamingTimeout(e,n){if(36e5*e/128e3>6e5||n!=null&&e>n)throw new p("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#long-requests for more details");return 6e5}async buildRequest(e,{retryCount:n=0}={}){const s={...e},{method:r,path:i,query:a,defaultBaseURL:c}=s,l=this.buildURL(i,a,c);"timeout"in s&&hs("timeout",s.timeout),s.timeout=s.timeout??this.timeout;const{bodyHeaders:d,body:f}=this.buildBody({options:s}),m=await this.buildHeaders({options:e,method:r,bodyHeaders:d,retryCount:n});return{req:{method:r,headers:m,...s.signal&&{signal:s.signal},...globalThis.ReadableStream&&f instanceof globalThis.ReadableStream&&{duplex:"half"},...f&&{body:f},...this.fetchOptions??{},...s.fetchOptions??{}},url:l,timeout:s.timeout}}async buildHeaders({options:e,method:n,bodyHeaders:s,retryCount:r}){let i={};this.idempotencyHeader&&n!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),i[this.idempotencyHeader]=e.idempotencyKey);const a=g([i,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(r),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},..._s(),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":"true"}:void 0,"anthropic-version":"2023-06-01"},await this.authHeaders(e),this._options.defaultHeaders,s,e.headers]);return this.validateHeaders(a),a.values}buildBody({options:{body:e,headers:n}}){if(!e)return{bodyHeaders:void 0,body:void 0};const s=g([n]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&s.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:_n(e)}:o(this,qe,"f").call(this,{body:e,headers:s})}}gt=y,qe=new WeakMap,dt=new WeakSet,Nn=function(){return this.baseURL!=="https://api.anthropic.com"};y.Anthropic=gt;y.HUMAN_PROMPT=Js;y.AI_PROMPT=Xs;y.DEFAULT_TIMEOUT=6e5;y.AnthropicError=p;y.APIError=w;y.APIConnectionError=He;y.APIConnectionTimeoutError=an;y.APIUserAbortError=v;y.NotFoundError=un;y.ConflictError=hn;y.RateLimitError=pn;y.BadRequestError=on;y.AuthenticationError=cn;y.InternalServerError=fn;y.PermissionDeniedError=ln;y.UnprocessableEntityError=dn;y.toFile=Bs;class ye extends y{constructor(){super(...arguments),this.completions=new On(this),this.messages=new mt(this),this.models=new In(this),this.beta=new _e(this)}}ye.Completions=On;ye.Messages=mt;ye.Models=In;ye.Beta=_e;const zs={"claude-opus-4-1":8192,"claude-opus-4":8192,"claude-sonnet-4":8192,"claude-sonnet-3-7-sonnet":8192,"claude-3-5-sonnet":4096,"claude-3-5-haiku":4096,"claude-3-haiku":2048},tn=2048;function Vs(t){return t?Object.entries(zs).find(([n])=>t.startsWith(n))?.[1]??tn:tn}function Qs(t){return!!(t.tools&&t.tools.length>0)}function Gs(t){for(const e of t.messages??[])if(typeof e.content!="string"){for(const n of e.content??[])if(typeof n=="object"&&n!=null&&n.type==="document"&&typeof n.citations=="object"&&n.citations?.enabled)return!0}return!1}function Ys(t){return!!(t.thinking&&t.thinking.type==="enabled")}function Zs(t){return"input_schema"in t}function er(t){const e=["text_editor_","computer_","bash_","web_search_","web_fetch_","str_replace_editor_","str_replace_based_edit_tool_","code_execution_","memory_"];return typeof t=="object"&&t!==null&&"type"in t&&"name"in t&&typeof t.type=="string"&&e.some(n=>typeof t.type=="string"&&t.type.startsWith(n))}function tr(t){if(typeof t.content=="string")return t.content;if(Array.isArray(t.content)&&t.content.length>=1&&"input"in t.content[0])return typeof t.content[0].input=="string"?t.content[0].input:JSON.stringify(t.content[0].input);if(Array.isArray(t.content)&&t.content.length>=1&&"text"in t.content[0]&&typeof t.content[0].text=="string")return t.content[0].text}var nr=class extends Un{static lc_name(){return"ChatAnthropic"}get lc_secrets(){return{anthropicApiKey:"ANTHROPIC_API_KEY",apiKey:"ANTHROPIC_API_KEY"}}get lc_aliases(){return{modelName:"model"}}lc_serializable=!0;anthropicApiKey;apiKey;apiUrl;temperature;topK;topP;maxTokens;modelName="claude-3-5-sonnet-latest";model="claude-3-5-sonnet-latest";invocationKwargs;stopSequences;streaming=!1;clientOptions;thinking={type:"disabled"};contextManagement;batchClient;streamingClient;streamUsage=!0;createClient;constructor(t){if(super(t??{}),this.anthropicApiKey=t?.apiKey??t?.anthropicApiKey??qn("ANTHROPIC_API_KEY"),!this.anthropicApiKey&&!t?.createClient)throw new Error("Anthropic API key not found");this.clientOptions=t?.clientOptions??{},this.apiKey=this.anthropicApiKey,this.apiUrl=t?.anthropicApiUrl,this.modelName=t?.model??t?.modelName??this.model,this.model=this.modelName,this.invocationKwargs=t?.invocationKwargs??{},this.topP=t?.topP??this.topP,this.temperature=t?.temperature??this.temperature,this.topK=t?.topK??this.topK,this.maxTokens=t?.maxTokens??Vs(this.model),this.stopSequences=t?.stopSequences??this.stopSequences,this.streaming=t?.streaming??!1,this.streamUsage=t?.streamUsage??this.streamUsage,this.thinking=t?.thinking??this.thinking,this.contextManagement=t?.contextManagement??this.contextManagement,this.createClient=t?.createClient??(e=>new ye(e))}getLsParams(t){const e=this.invocationParams(t);return{ls_provider:"anthropic",ls_model_name:this.model,ls_model_type:"chat",ls_temperature:e.temperature??void 0,ls_max_tokens:e.max_tokens??void 0,ls_stop:t.stop}}formatStructuredToolToAnthropic(t){if(!(!t||!t.length))return t.map(e=>{if(er(e)||Zs(e))return e;if(Wn(e))return{name:e.function.name,description:e.function.description,input_schema:e.function.parameters};if(Fn(e))return{name:e.name,description:e.description,input_schema:Mt(e.schema)?be(e.schema):e.schema};throw new Error(`Unknown tool type passed to ChatAnthropic: ${JSON.stringify(e,null,2)}`)})}bindTools(t,e){return this.withConfig({tools:this.formatStructuredToolToAnthropic(t),...e})}invocationParams(t){const e=Kn(t?.tool_choice);if(this.thinking.type==="enabled"){if(this.topP!==void 0&&this.topK!==-1)throw new Error("topK is not supported when thinking is enabled");if(this.temperature!==void 0&&this.temperature!==1)throw new Error("temperature is not supported when thinking is enabled");return{model:this.model,stop_sequences:t?.stop??this.stopSequences,stream:this.streaming,max_tokens:this.maxTokens,tools:this.formatStructuredToolToAnthropic(t?.tools),tool_choice:e,thinking:this.thinking,context_management:this.contextManagement,...this.invocationKwargs,container:t?.container}}return{model:this.model,temperature:this.temperature,top_k:this.topK,top_p:this.topP,stop_sequences:t?.stop??this.stopSequences,stream:this.streaming,max_tokens:this.maxTokens,tools:this.formatStructuredToolToAnthropic(t?.tools),tool_choice:e,thinking:this.thinking,context_management:this.contextManagement,...this.invocationKwargs,container:t?.container}}_identifyingParams(){return{model_name:this.model,...this.invocationParams()}}identifyingParams(){return{model_name:this.model,...this.invocationParams()}}async*_streamResponseChunks(t,e,n){const s=this.invocationParams(e),r=Pt(t),i={...s,...r,stream:!0},a=!Qs(i)&&!Gs(i)&&!Ys(i),c=await this.createStreamWithRetry(i,{headers:e.headers});for await(const l of c){if(e.signal?.aborted)throw c.controller.abort(),new Error("AbortError: User aborted the request.");const d=this.streamUsage??e.streamUsage,f=is(l,{streamUsage:d,coerceContentToString:a});if(!f)continue;const{chunk:m}=f,_=tr(m),h=new Dn({message:new A({content:m.content,additional_kwargs:m.additional_kwargs,tool_call_chunks:m.tool_call_chunks,usage_metadata:d?m.usage_metadata:void 0,response_metadata:m.response_metadata,id:m.id}),text:_??""});yield h,await n?.handleLLMNewToken(_??"",void 0,void 0,void 0,void 0,{chunk:h})}}async _generateNonStreaming(t,e,n){const s=await this.completionWithRetry({...e,stream:!1,...Pt(t)},n),{content:r,...i}=s,a=as(r,i),{role:c,type:l,...d}=i;return{generations:a,llmOutput:d}}async _generate(t,e,n){if(this.stopSequences&&e.stop)throw new Error('"stopSequence" parameter found in input and default params');const s=this.invocationParams(e);if(s.stream){let r;const i=this._streamResponseChunks(t,e,n);for await(const a of i)r===void 0?r=a:r=r.concat(a);if(r===void 0)throw new Error("No chunks returned from Anthropic API.");return{generations:[{text:r.text,message:r.message}]}}else return this._generateNonStreaming(t,s,{signal:e.signal,headers:e.headers})}async createStreamWithRetry(t,e){if(!this.streamingClient){const s=this.apiUrl?{baseURL:this.apiUrl}:void 0;this.streamingClient=this.createClient({dangerouslyAllowBrowser:!0,...this.clientOptions,...s,apiKey:this.apiKey,maxRetries:0})}const n=async()=>{try{return await this.streamingClient.messages.create({...t,...this.invocationKwargs,stream:!0},e)}catch(s){throw Ot(s)}};return this.caller.call(n)}async completionWithRetry(t,e){if(!this.batchClient){const s=this.apiUrl?{baseURL:this.apiUrl}:void 0;this.batchClient=this.createClient({dangerouslyAllowBrowser:!0,...this.clientOptions,...s,apiKey:this.apiKey,maxRetries:0})}const n=async()=>{try{return await this.batchClient.messages.create({...t,...this.invocationKwargs},e)}catch(s){throw Ot(s)}};return this.caller.callWithOptions({signal:e.signal??void 0},n)}_llmType(){return"anthropic"}withStructuredOutput(t,e){const n=t,s=e?.name,r=e?.method,i=e?.includeRaw;if(r==="jsonMode")throw new Error('Anthropic only supports "functionCalling" as a method.');let a=s??"extract",c,l;if(Mt(n)){const h=be(n);l=[{name:a,description:h.description??"A function available to call.",input_schema:h}],c=new Rt({returnSingle:!0,keyName:a,zodSchema:n})}else{let h;typeof n.name=="string"&&typeof n.description=="string"&&typeof n.input_schema=="object"&&n.input_schema!=null?(h=n,a=n.name):h={name:a,description:n.description??"",input_schema:n},l=[h],c=new Rt({returnSingle:!0,keyName:a})}let d;if(this.thinking?.type==="enabled"){const h="Anthropic structured output relies on forced tool calling, which is not supported when `thinking` is enabled. This method will raise OutputParserException if tool calls are not generated. Consider disabling `thinking` or adjust your prompt to ensure the tool is called.";console.warn(h),d=this.withConfig({outputVersion:"v0",tools:l,ls_structured_output_format:{kwargs:{method:"functionCalling"},schema:be(n)}});const b=W=>{if(!W.tool_calls||W.tool_calls.length===0)throw new Error(h);return W};d=d.pipe(b)}else d=this.withConfig({outputVersion:"v0",tools:l,tool_choice:{type:"tool",name:a},ls_structured_output_format:{kwargs:{method:"functionCalling"},schema:be(n)}});if(!i)return d.pipe(c).withConfig({runName:"ChatAnthropicStructuredOutput"});const f=Tt.assign({parsed:(h,b)=>c.invoke(h.raw,b)}),m=Tt.assign({parsed:()=>null}),_=f.withFallbacks({fallbacks:[m]});return Hn.from([{raw:d},_]).withConfig({runName:"StructuredOutputRunnable"})}},ur=class extends nr{};export{ur as ChatAnthropic,nr as ChatAnthropicMessages};
25
+ `);this.baseURL=i.baseURL,this.timeout=i.timeout??gt.DEFAULT_TIMEOUT,this.logger=i.logger??console;const a="warn";this.logLevel=a,this.logLevel=qt(i.logLevel,"ClientOptions.logLevel",this)??qt(Le("ANTHROPIC_LOG"),"process.env['ANTHROPIC_LOG']",this)??a,this.fetchOptions=i.fetchOptions,this.maxRetries=i.maxRetries??2,this.fetch=i.fetch??ys(),u(this,qe,bs),this._options=i,this.apiKey=n,this.authToken=s}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,authToken:this.authToken,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:n}){if(!(this.apiKey&&e.get("x-api-key"))&&!n.has("x-api-key")&&!(this.authToken&&e.get("authorization"))&&!n.has("authorization"))throw new Error('Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted')}async authHeaders(e){return g([await this.apiKeyAuth(e),await this.bearerAuth(e)])}async apiKeyAuth(e){if(this.apiKey!=null)return g([{"X-Api-Key":this.apiKey}])}async bearerAuth(e){if(this.authToken!=null)return g([{Authorization:`Bearer ${this.authToken}`}])}stringifyQuery(e){return Object.entries(e).filter(([n,s])=>typeof s<"u").map(([n,s])=>{if(typeof s=="string"||typeof s=="number"||typeof s=="boolean")return`${encodeURIComponent(n)}=${encodeURIComponent(s)}`;if(s===null)return`${encodeURIComponent(n)}=`;throw new p(`Cannot stringify type ${typeof s}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}getUserAgent(){return`${this.constructor.name}/JS ${z}`}defaultIdempotencyKey(){return`stainless-node-retry-${rn()}`}makeStatusError(e,n,s,r){return w.generate(e,n,s,r)}buildURL(e,n,s){const r=!o(this,dt,"m",Nn).call(this)&&s||this.baseURL,i=cs(e)?new URL(e):new URL(r+(r.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),a=this.defaultQuery();return ls(a)||(n={...a,...n}),typeof n=="object"&&n&&!Array.isArray(n)&&(i.search=this.stringifyQuery(n)),i.toString()}_calculateNonstreamingTimeout(e){if(3600*e/128e3>600)throw new p("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details");return 600*1e3}async prepareOptions(e){}async prepareRequest(e,{url:n,options:s}){}get(e,n){return this.methodRequest("get",e,n)}post(e,n){return this.methodRequest("post",e,n)}patch(e,n){return this.methodRequest("patch",e,n)}put(e,n){return this.methodRequest("put",e,n)}delete(e,n){return this.methodRequest("delete",e,n)}methodRequest(e,n,s){return this.request(Promise.resolve(s).then(r=>({method:e,path:n,...r})))}request(e,n=null){return new Ke(this,this.makeRequest(e,n,void 0))}async makeRequest(e,n,s){const r=await e,i=r.maxRetries??this.maxRetries;n==null&&(n=i),await this.prepareOptions(r);const{req:a,url:c,timeout:l}=await this.buildRequest(r,{retryCount:i-n});await this.prepareRequest(a,{url:c,options:r});const d="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),f=s===void 0?"":`, retryOf: ${s}`,m=Date.now();if(x(this).debug(`[${d}] sending request`,D({retryOfRequestLogID:s,method:r.method,url:c,options:r,headers:a.headers})),r.signal?.aborted)throw new v;const _=new AbortController,h=await this.fetchWithTimeout(c,a,l,_).catch(ot),b=Date.now();if(h instanceof globalThis.Error){const I=`retrying, ${n} attempts remaining`;if(r.signal?.aborted)throw new v;const P=fe(h)||/timed? ?out/i.test(String(h)+("cause"in h?String(h.cause):""));if(n)return x(this).info(`[${d}] connection ${P?"timed out":"failed"} - ${I}`),x(this).debug(`[${d}] connection ${P?"timed out":"failed"} (${I})`,D({retryOfRequestLogID:s,url:c,durationMs:b-m,message:h.message})),this.retryRequest(r,n,s??d);throw x(this).info(`[${d}] connection ${P?"timed out":"failed"} - error; no more retries left`),x(this).debug(`[${d}] connection ${P?"timed out":"failed"} (error; no more retries left)`,D({retryOfRequestLogID:s,url:c,durationMs:b-m,message:h.message})),P?new an:new He({cause:h})}const W=[...h.headers.entries()].filter(([I])=>I==="request-id").map(([I,P])=>", "+I+": "+JSON.stringify(P)).join(""),ze=`[${d}${f}${W}] ${a.method} ${c} ${h.ok?"succeeded":"failed"} with status ${h.status} in ${b-m}ms`;if(!h.ok){const I=await this.shouldRetry(h);if(n&&I){const we=`retrying, ${n} attempts remaining`;return await ws(h.body),x(this).info(`${ze} - ${we}`),x(this).debug(`[${d}] response error (${we})`,D({retryOfRequestLogID:s,url:h.url,status:h.status,headers:h.headers,durationMs:b-m})),this.retryRequest(r,n,s??d,h.headers)}const P=I?"error; no more retries left":"error; not retryable";x(this).info(`${ze} - ${P}`);const _t=await h.text().catch(we=>ot(we).message),yt=mn(_t),wt=yt?void 0:_t;throw x(this).debug(`[${d}] response error (${P})`,D({retryOfRequestLogID:s,url:h.url,status:h.status,headers:h.headers,message:wt,durationMs:Date.now()-m})),this.makeStatusError(h.status,yt,wt,h.headers)}return x(this).info(ze),x(this).debug(`[${d}] response start`,D({retryOfRequestLogID:s,url:h.url,status:h.status,headers:h.headers,durationMs:b-m})),{response:h,options:r,controller:_,requestLogID:d,retryOfRequestLogID:s,startTime:m}}getAPIList(e,n,s){return this.requestAPIList(n,{method:"get",path:e,...s})}requestAPIList(e,n){const s=this.makeRequest(n,null,void 0);return new Ps(this,s,e)}async fetchWithTimeout(e,n,s,r){const{signal:i,method:a,...c}=n||{};i&&i.addEventListener("abort",()=>r.abort());const l=setTimeout(()=>r.abort(),s),d=globalThis.ReadableStream&&c.body instanceof globalThis.ReadableStream||typeof c.body=="object"&&c.body!==null&&Symbol.asyncIterator in c.body,f={signal:r.signal,...d?{duplex:"half"}:{},method:"GET",...c};a&&(f.method=a.toUpperCase());try{return await this.fetch.call(void 0,e,f)}finally{clearTimeout(l)}}async shouldRetry(e){const n=e.headers.get("x-should-retry");return n==="true"?!0:n==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,n,s,r){let i;const a=r?.get("retry-after-ms");if(a){const l=parseFloat(a);Number.isNaN(l)||(i=l)}const c=r?.get("retry-after");if(c&&!i){const l=parseFloat(c);Number.isNaN(l)?i=Date.parse(c)-Date.now():i=l*1e3}if(!(i&&0<=i&&i<60*1e3)){const l=e.maxRetries??this.maxRetries;i=this.calculateDefaultRetryTimeoutMillis(n,l)}return await ds(i),this.makeRequest(e,n-1,s)}calculateDefaultRetryTimeoutMillis(e,n){const i=n-e,a=Math.min(.5*Math.pow(2,i),8),c=1-Math.random()*.25;return a*c*1e3}calculateNonstreamingTimeout(e,n){if(36e5*e/128e3>6e5||n!=null&&e>n)throw new p("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#long-requests for more details");return 6e5}async buildRequest(e,{retryCount:n=0}={}){const s={...e},{method:r,path:i,query:a,defaultBaseURL:c}=s,l=this.buildURL(i,a,c);"timeout"in s&&hs("timeout",s.timeout),s.timeout=s.timeout??this.timeout;const{bodyHeaders:d,body:f}=this.buildBody({options:s}),m=await this.buildHeaders({options:e,method:r,bodyHeaders:d,retryCount:n});return{req:{method:r,headers:m,...s.signal&&{signal:s.signal},...globalThis.ReadableStream&&f instanceof globalThis.ReadableStream&&{duplex:"half"},...f&&{body:f},...this.fetchOptions??{},...s.fetchOptions??{}},url:l,timeout:s.timeout}}async buildHeaders({options:e,method:n,bodyHeaders:s,retryCount:r}){let i={};this.idempotencyHeader&&n!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),i[this.idempotencyHeader]=e.idempotencyKey);const a=g([i,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(r),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},..._s(),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":"true"}:void 0,"anthropic-version":"2023-06-01"},await this.authHeaders(e),this._options.defaultHeaders,s,e.headers]);return this.validateHeaders(a),a.values}buildBody({options:{body:e,headers:n}}){if(!e)return{bodyHeaders:void 0,body:void 0};const s=g([n]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&s.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:_n(e)}:o(this,qe,"f").call(this,{body:e,headers:s})}}gt=y,qe=new WeakMap,dt=new WeakSet,Nn=function(){return this.baseURL!=="https://api.anthropic.com"};y.Anthropic=gt;y.HUMAN_PROMPT=Js;y.AI_PROMPT=Xs;y.DEFAULT_TIMEOUT=6e5;y.AnthropicError=p;y.APIError=w;y.APIConnectionError=He;y.APIConnectionTimeoutError=an;y.APIUserAbortError=v;y.NotFoundError=un;y.ConflictError=hn;y.RateLimitError=pn;y.BadRequestError=on;y.AuthenticationError=cn;y.InternalServerError=fn;y.PermissionDeniedError=ln;y.UnprocessableEntityError=dn;y.toFile=Bs;class ye extends y{constructor(){super(...arguments),this.completions=new On(this),this.messages=new mt(this),this.models=new In(this),this.beta=new _e(this)}}ye.Completions=On;ye.Messages=mt;ye.Models=In;ye.Beta=_e;const zs={"claude-opus-4-1":8192,"claude-opus-4":8192,"claude-sonnet-4":8192,"claude-sonnet-3-7-sonnet":8192,"claude-3-5-sonnet":4096,"claude-3-5-haiku":4096,"claude-3-haiku":2048},tn=2048;function Vs(t){return t?Object.entries(zs).find(([n])=>t.startsWith(n))?.[1]??tn:tn}function Qs(t){return!!(t.tools&&t.tools.length>0)}function Gs(t){for(const e of t.messages??[])if(typeof e.content!="string"){for(const n of e.content??[])if(typeof n=="object"&&n!=null&&n.type==="document"&&typeof n.citations=="object"&&n.citations?.enabled)return!0}return!1}function Ys(t){return!!(t.thinking&&t.thinking.type==="enabled")}function Zs(t){return"input_schema"in t}function er(t){const e=["text_editor_","computer_","bash_","web_search_","web_fetch_","str_replace_editor_","str_replace_based_edit_tool_","code_execution_","memory_"];return typeof t=="object"&&t!==null&&"type"in t&&"name"in t&&typeof t.type=="string"&&e.some(n=>typeof t.type=="string"&&t.type.startsWith(n))}function tr(t){if(typeof t.content=="string")return t.content;if(Array.isArray(t.content)&&t.content.length>=1&&"input"in t.content[0])return typeof t.content[0].input=="string"?t.content[0].input:JSON.stringify(t.content[0].input);if(Array.isArray(t.content)&&t.content.length>=1&&"text"in t.content[0]&&typeof t.content[0].text=="string")return t.content[0].text}var nr=class extends jn{static lc_name(){return"ChatAnthropic"}get lc_secrets(){return{anthropicApiKey:"ANTHROPIC_API_KEY",apiKey:"ANTHROPIC_API_KEY"}}get lc_aliases(){return{modelName:"model"}}lc_serializable=!0;anthropicApiKey;apiKey;apiUrl;temperature;topK;topP;maxTokens;modelName="claude-3-5-sonnet-latest";model="claude-3-5-sonnet-latest";invocationKwargs;stopSequences;streaming=!1;clientOptions;thinking={type:"disabled"};contextManagement;batchClient;streamingClient;streamUsage=!0;createClient;constructor(t){if(super(t??{}),this.anthropicApiKey=t?.apiKey??t?.anthropicApiKey??Fn("ANTHROPIC_API_KEY"),!this.anthropicApiKey&&!t?.createClient)throw new Error("Anthropic API key not found");this.clientOptions=t?.clientOptions??{},this.apiKey=this.anthropicApiKey,this.apiUrl=t?.anthropicApiUrl,this.modelName=t?.model??t?.modelName??this.model,this.model=this.modelName,this.invocationKwargs=t?.invocationKwargs??{},this.topP=t?.topP??this.topP,this.temperature=t?.temperature??this.temperature,this.topK=t?.topK??this.topK,this.maxTokens=t?.maxTokens??Vs(this.model),this.stopSequences=t?.stopSequences??this.stopSequences,this.streaming=t?.streaming??!1,this.streamUsage=t?.streamUsage??this.streamUsage,this.thinking=t?.thinking??this.thinking,this.contextManagement=t?.contextManagement??this.contextManagement,this.createClient=t?.createClient??(e=>new ye(e))}getLsParams(t){const e=this.invocationParams(t);return{ls_provider:"anthropic",ls_model_name:this.model,ls_model_type:"chat",ls_temperature:e.temperature??void 0,ls_max_tokens:e.max_tokens??void 0,ls_stop:t.stop}}formatStructuredToolToAnthropic(t){if(!(!t||!t.length))return t.map(e=>{if(er(e)||Zs(e))return e;if(Bn(e))return{name:e.function.name,description:e.function.description,input_schema:e.function.parameters};if(Ln(e))return{name:e.name,description:e.description,input_schema:Tt(e.schema)?be(e.schema):e.schema};throw new Error(`Unknown tool type passed to ChatAnthropic: ${JSON.stringify(e,null,2)}`)})}bindTools(t,e){return this.withConfig({tools:this.formatStructuredToolToAnthropic(t),...e})}invocationParams(t){const e=Kn(t?.tool_choice);if(this.thinking.type==="enabled"){if(this.topP!==void 0&&this.topK!==-1)throw new Error("topK is not supported when thinking is enabled");if(this.temperature!==void 0&&this.temperature!==1)throw new Error("temperature is not supported when thinking is enabled");return{model:this.model,stop_sequences:t?.stop??this.stopSequences,stream:this.streaming,max_tokens:this.maxTokens,tools:this.formatStructuredToolToAnthropic(t?.tools),tool_choice:e,thinking:this.thinking,context_management:this.contextManagement,...this.invocationKwargs,container:t?.container}}return{model:this.model,temperature:this.temperature,top_k:this.topK,top_p:this.topP,stop_sequences:t?.stop??this.stopSequences,stream:this.streaming,max_tokens:this.maxTokens,tools:this.formatStructuredToolToAnthropic(t?.tools),tool_choice:e,thinking:this.thinking,context_management:this.contextManagement,...this.invocationKwargs,container:t?.container}}_identifyingParams(){return{model_name:this.model,...this.invocationParams()}}identifyingParams(){return{model_name:this.model,...this.invocationParams()}}async*_streamResponseChunks(t,e,n){const s=this.invocationParams(e),r=Pt(t),i={...s,...r,stream:!0},a=!Qs(i)&&!Gs(i)&&!Ys(i),c=await this.createStreamWithRetry(i,{headers:e.headers});for await(const l of c){if(e.signal?.aborted)throw c.controller.abort(),new Error("AbortError: User aborted the request.");const d=this.streamUsage??e.streamUsage,f=is(l,{streamUsage:d,coerceContentToString:a});if(!f)continue;const{chunk:m}=f,_=tr(m),h=new Dn({message:new A({content:m.content,additional_kwargs:m.additional_kwargs,tool_call_chunks:m.tool_call_chunks,usage_metadata:d?m.usage_metadata:void 0,response_metadata:m.response_metadata,id:m.id}),text:_??""});yield h,await n?.handleLLMNewToken(_??"",void 0,void 0,void 0,void 0,{chunk:h})}}async _generateNonStreaming(t,e,n){const s=await this.completionWithRetry({...e,stream:!1,...Pt(t)},n),{content:r,...i}=s,a=as(r,i),{role:c,type:l,...d}=i;return{generations:a,llmOutput:d}}async _generate(t,e,n){if(this.stopSequences&&e.stop)throw new Error('"stopSequence" parameter found in input and default params');const s=this.invocationParams(e);if(s.stream){let r;const i=this._streamResponseChunks(t,e,n);for await(const a of i)r===void 0?r=a:r=r.concat(a);if(r===void 0)throw new Error("No chunks returned from Anthropic API.");return{generations:[{text:r.text,message:r.message}]}}else return this._generateNonStreaming(t,s,{signal:e.signal,headers:e.headers})}async createStreamWithRetry(t,e){if(!this.streamingClient){const s=this.apiUrl?{baseURL:this.apiUrl}:void 0;this.streamingClient=this.createClient({dangerouslyAllowBrowser:!0,...this.clientOptions,...s,apiKey:this.apiKey,maxRetries:0})}const n=async()=>{try{return await this.streamingClient.messages.create({...t,...this.invocationKwargs,stream:!0},e)}catch(s){throw Ot(s)}};return this.caller.call(n)}async completionWithRetry(t,e){if(!this.batchClient){const s=this.apiUrl?{baseURL:this.apiUrl}:void 0;this.batchClient=this.createClient({dangerouslyAllowBrowser:!0,...this.clientOptions,...s,apiKey:this.apiKey,maxRetries:0})}const n=async()=>{try{return await this.batchClient.messages.create({...t,...this.invocationKwargs},e)}catch(s){throw Ot(s)}};return this.caller.callWithOptions({signal:e.signal??void 0},n)}_llmType(){return"anthropic"}withStructuredOutput(t,e){const n=t,s=e?.name,r=e?.method,i=e?.includeRaw;if(r==="jsonMode")throw new Error('Anthropic only supports "functionCalling" as a method.');let a=s??"extract",c,l;if(Tt(n)){const h=be(n);l=[{name:a,description:h.description??"A function available to call.",input_schema:h}],c=new Rt({returnSingle:!0,keyName:a,zodSchema:n})}else{let h;typeof n.name=="string"&&typeof n.description=="string"&&typeof n.input_schema=="object"&&n.input_schema!=null?(h=n,a=n.name):h={name:a,description:n.description??"",input_schema:n},l=[h],c=new Rt({returnSingle:!0,keyName:a})}let d;if(this.thinking?.type==="enabled"){const h="Anthropic structured output relies on forced tool calling, which is not supported when `thinking` is enabled. This method will raise OutputParserException if tool calls are not generated. Consider disabling `thinking` or adjust your prompt to ensure the tool is called.";console.warn(h),d=this.withConfig({outputVersion:"v0",tools:l,ls_structured_output_format:{kwargs:{method:"functionCalling"},schema:be(n)}});const b=W=>{if(!W.tool_calls||W.tool_calls.length===0)throw new Error(h);return W};d=d.pipe(b)}else d=this.withConfig({outputVersion:"v0",tools:l,tool_choice:{type:"tool",name:a},ls_structured_output_format:{kwargs:{method:"functionCalling"},schema:be(n)}});if(!i)return d.pipe(c).withConfig({runName:"ChatAnthropicStructuredOutput"});const f=xt.assign({parsed:(h,b)=>c.invoke(h.raw,b)}),m=xt.assign({parsed:()=>null}),_=f.withFallbacks({fallbacks:[m]});return Hn.from([{raw:d},_]).withConfig({runName:"StructuredOutputRunnable"})}},hr=class extends nr{};export{hr as ChatAnthropic,nr as ChatAnthropicMessages};
@@ -0,0 +1,71 @@
1
+ import{M as Be,N as Ue,O as X,P as te,_ as U,Q as At,S as Ot,U as Nt,V as kt,W as xt,X as Pt,Y as Mt,Z as Rt,n as Dt,$ as Lt,g as Ce,a0 as Ft,a1 as Bt,a2 as Ut,a3 as jt,a4 as Vt,a5 as zt,a6 as Gt,i as $t,a7 as Zt,h as Ge,a8 as Ht,a9 as $e,aa as Wt,ab as Xt,ac as Yt,ad as H,x as ue,ae as Se,af as Jt,ag as Kt,ah as qt,A as Ze,ai as ne,e as ie,aj as He,ak as We,b as oe,K as Qt,C as be,al as je,c as ea,R as Ve,y as Y,a as ta,am as Ie,D as aa,L as Xe,an as sa,ao as na,ap as ra,z as Ye,aq as re,r as G,ar as Je,as as ia,at as Ke,u as oa,m as ca,au as ua,av as la,aw as ha,ax as pa,ay as ga,az as ma,aA as fa,aB as da,B as ze,aC as ba,G as _a,aD as ya,o as qe,s as Qe,aE as Ta,aF as Te,p as va}from"./index-DLvycrCn.js";import{g as Ea}from"./index-C86qnUPq.js";import{r as wa}from"./index-DRz5BQNA.js";function et(e,a,n,r,i){if(a!==e){typeof a.toJSON=="function"&&(a=a.toJSON());for(var c=Be(a),h=Be(e),l=!1,m=h.length-1;m>=0;m--){var g=h[m],T=e[g];if(Ue(a,g)&&!(a[g]===void 0&&T!==void 0&&Array.isArray(a)===!1)){var _=a[g];typeof T=="object"&&T!=null&&typeof _=="object"&&_!=null&&Array.isArray(T)===Array.isArray(_)?et(T,_,n,r+"/"+X(g),i):T!==_&&(i&&n.push({op:"test",path:r+"/"+X(g),value:te(T)}),n.push({op:"replace",path:r+"/"+X(g),value:te(_)}))}else Array.isArray(e)===Array.isArray(a)?(i&&n.push({op:"test",path:r+"/"+X(g),value:te(T)}),n.push({op:"remove",path:r+"/"+X(g)}),l=!0):(i&&n.push({op:"test",path:r,value:e}),n.push({op:"replace",path:r,value:a}))}if(!(!l&&c.length==h.length))for(var m=0;m<c.length;m++){var g=c[m];!Ue(e,g)&&a[g]!==void 0&&n.push({op:"add",path:r+"/"+X(g),value:te(a[g])})}}}function Ae(e,a,n=!1){var r=[];return et(e,a,r,"",n),r}var Ca={};U(Ca,{extendInteropZodObject:()=>Yt,getInteropZodDefaultGetter:()=>Xt,getInteropZodObjectShape:()=>Wt,getSchemaDescription:()=>$e,interopParse:()=>Ht,interopParseAsync:()=>Ge,interopSafeParse:()=>Zt,interopSafeParseAsync:()=>$t,interopZodObjectMakeFieldsOptional:()=>Gt,interopZodObjectPartial:()=>zt,interopZodObjectPassthrough:()=>Vt,interopZodObjectStrict:()=>jt,interopZodTransformInputSchema:()=>Ut,isInteropZodLiteral:()=>Bt,isInteropZodObject:()=>Ft,isInteropZodSchema:()=>Ce,isShapelessZodSchema:()=>Lt,isSimpleStringZodSchema:()=>Dt,isZodArrayV4:()=>Rt,isZodLiteralV3:()=>Mt,isZodLiteralV4:()=>Pt,isZodObjectV3:()=>xt,isZodObjectV4:()=>kt,isZodSchema:()=>Nt,isZodSchemaV3:()=>Ot,isZodSchemaV4:()=>At});function tt(e){return e!==void 0&&Array.isArray(e.lc_namespace)}function at(e){return e!==void 0&&H.isRunnable(e)&&"lc_name"in e.constructor&&typeof e.constructor.lc_name=="function"&&e.constructor.lc_name()==="RunnableToolLike"}function st(e){return!!e&&typeof e=="object"&&"name"in e&&"schema"in e&&(Ce(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 nt(e){return st(e)||at(e)||tt(e)}var Sa={};U(Sa,{convertToOpenAIFunction:()=>rt,convertToOpenAITool:()=>Ia,isLangChainTool:()=>nt,isRunnableToolLike:()=>at,isStructuredTool:()=>tt,isStructuredToolParams:()=>st});function rt(e,a){const n=typeof a=="number"?void 0:a;return{name:e.name,description:e.description,parameters:ue(e.schema),...n?.strict!==void 0?{strict:n.strict}:{}}}function Ia(e,a){const n=typeof a=="number"?void 0:a;let r;return nt(e)?r={type:"function",function:rt(e)}:r=e,n?.strict!==void 0&&(r.function.strict=n.strict),r}var Aa={};U(Aa,{BasePromptValue:()=>le,ChatPromptValue:()=>ot,ImagePromptValue:()=>Oa,StringPromptValue:()=>it});var le=class extends Kt{},it=class extends le{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 Se(this.value)]}},ot=class extends le{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 Jt(this.messages)}toChatMessages(){return this.messages}},Oa=class extends le{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 Se({content:[{type:"image_url",image_url:{detail:this.imageUrl.detail,url:this.imageUrl.url}}]})]}},b="0123456789abcdef".split(""),Na=[-2147483648,8388608,32768,128],F=[24,16,8,0],ae=[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],k=[];function B(e,a){a?(k[0]=k[16]=k[1]=k[2]=k[3]=k[4]=k[5]=k[6]=k[7]=k[8]=k[9]=k[10]=k[11]=k[12]=k[13]=k[14]=k[15]=0,this.blocks=k):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}B.prototype.update=function(e){if(!this.finalized){var a,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);a=!0}for(var r,i=0,c,h=e.length,l=this.blocks;i<h;){if(this.hashed&&(this.hashed=!1,l[0]=this.block,this.block=l[16]=l[1]=l[2]=l[3]=l[4]=l[5]=l[6]=l[7]=l[8]=l[9]=l[10]=l[11]=l[12]=l[13]=l[14]=l[15]=0),a)for(c=this.start;i<h&&c<64;++i)l[c>>>2]|=e[i]<<F[c++&3];else for(c=this.start;i<h&&c<64;++i)r=e.charCodeAt(i),r<128?l[c>>>2]|=r<<F[c++&3]:r<2048?(l[c>>>2]|=(192|r>>>6)<<F[c++&3],l[c>>>2]|=(128|r&63)<<F[c++&3]):r<55296||r>=57344?(l[c>>>2]|=(224|r>>>12)<<F[c++&3],l[c>>>2]|=(128|r>>>6&63)<<F[c++&3],l[c>>>2]|=(128|r&63)<<F[c++&3]):(r=65536+((r&1023)<<10|e.charCodeAt(++i)&1023),l[c>>>2]|=(240|r>>>18)<<F[c++&3],l[c>>>2]|=(128|r>>>12&63)<<F[c++&3],l[c>>>2]|=(128|r>>>6&63)<<F[c++&3],l[c>>>2]|=(128|r&63)<<F[c++&3]);this.lastByteIndex=c,this.bytes+=c-this.start,c>=64?(this.block=l[16],this.start=c-64,this.hash(),this.hashed=!0):this.start=c}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296<<0,this.bytes=this.bytes%4294967296),this}};B.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var e=this.blocks,a=this.lastByteIndex;e[16]=this.block,e[a>>>2]|=Na[a&3],this.block=e[16],a>=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()}};B.prototype.hash=function(){var e=this.h0,a=this.h1,n=this.h2,r=this.h3,i=this.h4,c=this.h5,h=this.h6,l=this.h7,m=this.blocks,g,T,_,v,d,y,f,E,w,P,I;for(g=16;g<64;++g)d=m[g-15],T=(d>>>7|d<<25)^(d>>>18|d<<14)^d>>>3,d=m[g-2],_=(d>>>17|d<<15)^(d>>>19|d<<13)^d>>>10,m[g]=m[g-16]+T+m[g-7]+_<<0;for(I=a&n,g=0;g<64;g+=4)this.first?(this.is224?(E=300032,d=m[0]-1413257819,l=d-150054599<<0,r=d+24177077<<0):(E=704751109,d=m[0]-210244248,l=d-1521486534<<0,r=d+143694565<<0),this.first=!1):(T=(e>>>2|e<<30)^(e>>>13|e<<19)^(e>>>22|e<<10),_=(i>>>6|i<<26)^(i>>>11|i<<21)^(i>>>25|i<<7),E=e&a,v=E^e&n^I,f=i&c^~i&h,d=l+_+f+ae[g]+m[g],y=T+v,l=r+d<<0,r=d+y<<0),T=(r>>>2|r<<30)^(r>>>13|r<<19)^(r>>>22|r<<10),_=(l>>>6|l<<26)^(l>>>11|l<<21)^(l>>>25|l<<7),w=r&e,v=w^r&a^E,f=h&l^~h&i,d=c+_+f+ae[g+1]+m[g+1],y=T+v,h=n+d<<0,n=d+y<<0,T=(n>>>2|n<<30)^(n>>>13|n<<19)^(n>>>22|n<<10),_=(h>>>6|h<<26)^(h>>>11|h<<21)^(h>>>25|h<<7),P=n&r,v=P^n&e^w,f=c&h^~c&l,d=i+_+f+ae[g+2]+m[g+2],y=T+v,c=a+d<<0,a=d+y<<0,T=(a>>>2|a<<30)^(a>>>13|a<<19)^(a>>>22|a<<10),_=(c>>>6|c<<26)^(c>>>11|c<<21)^(c>>>25|c<<7),I=a&n,v=I^a&r^P,f=c&h^~c&l,d=i+_+f+ae[g+3]+m[g+3],y=T+v,i=e+d<<0,e=d+y<<0,this.chromeBugWorkAround=!0;this.h0=this.h0+e<<0,this.h1=this.h1+a<<0,this.h2=this.h2+n<<0,this.h3=this.h3+r<<0,this.h4=this.h4+i<<0,this.h5=this.h5+c<<0,this.h6=this.h6+h<<0,this.h7=this.h7+l<<0};B.prototype.hex=function(){this.finalize();var e=this.h0,a=this.h1,n=this.h2,r=this.h3,i=this.h4,c=this.h5,h=this.h6,l=this.h7,m=b[e>>>28&15]+b[e>>>24&15]+b[e>>>20&15]+b[e>>>16&15]+b[e>>>12&15]+b[e>>>8&15]+b[e>>>4&15]+b[e&15]+b[a>>>28&15]+b[a>>>24&15]+b[a>>>20&15]+b[a>>>16&15]+b[a>>>12&15]+b[a>>>8&15]+b[a>>>4&15]+b[a&15]+b[n>>>28&15]+b[n>>>24&15]+b[n>>>20&15]+b[n>>>16&15]+b[n>>>12&15]+b[n>>>8&15]+b[n>>>4&15]+b[n&15]+b[r>>>28&15]+b[r>>>24&15]+b[r>>>20&15]+b[r>>>16&15]+b[r>>>12&15]+b[r>>>8&15]+b[r>>>4&15]+b[r&15]+b[i>>>28&15]+b[i>>>24&15]+b[i>>>20&15]+b[i>>>16&15]+b[i>>>12&15]+b[i>>>8&15]+b[i>>>4&15]+b[i&15]+b[c>>>28&15]+b[c>>>24&15]+b[c>>>20&15]+b[c>>>16&15]+b[c>>>12&15]+b[c>>>8&15]+b[c>>>4&15]+b[c&15]+b[h>>>28&15]+b[h>>>24&15]+b[h>>>20&15]+b[h>>>16&15]+b[h>>>12&15]+b[h>>>8&15]+b[h>>>4&15]+b[h&15];return this.is224||(m+=b[l>>>28&15]+b[l>>>24&15]+b[l>>>20&15]+b[l>>>16&15]+b[l>>>12&15]+b[l>>>8&15]+b[l>>>4&15]+b[l&15]),m};B.prototype.toString=B.prototype.hex;B.prototype.digest=function(){this.finalize();var e=this.h0,a=this.h1,n=this.h2,r=this.h3,i=this.h4,c=this.h5,h=this.h6,l=this.h7,m=[e>>>24&255,e>>>16&255,e>>>8&255,e&255,a>>>24&255,a>>>16&255,a>>>8&255,a&255,n>>>24&255,n>>>16&255,n>>>8&255,n&255,r>>>24&255,r>>>16&255,r>>>8&255,r&255,i>>>24&255,i>>>16&255,i>>>8&255,i&255,c>>>24&255,c>>>16&255,c>>>8&255,c&255,h>>>24&255,h>>>16&255,h>>>8&255,h&255];return this.is224||m.push(l>>>24&255,l>>>16&255,l>>>8&255,l&255),m};B.prototype.array=B.prototype.digest;B.prototype.arrayBuffer=function(){this.finalize();var e=new ArrayBuffer(this.is224?28:32),a=new DataView(e);return a.setUint32(0,this.h0),a.setUint32(4,this.h1),a.setUint32(8,this.h2),a.setUint32(12,this.h3),a.setUint32(16,this.h4),a.setUint32(20,this.h5),a.setUint32(24,this.h6),this.is224||a.setUint32(28,this.h7),e};const ct=(...e)=>new B(!1,!0).update(e.join("")).hex();var ka={};U(ka,{sha256:()=>ct});var xa={};U(xa,{BaseCache:()=>lt,InMemoryCache:()=>ht,defaultHashKeyEncoder:()=>ut,deserializeStoredGeneration:()=>Pa,serializeGeneration:()=>Ma});const ut=(...e)=>ct(e.join("_"));function Pa(e){return e.message!==void 0?{text:e.text,message:qt(e.message)}:{text:e.text}}function Ma(e){const a={text:e.text};return e.message!==void 0&&(a.message=e.message.toDict()),a}var lt=class{keyEncoder=ut;makeDefaultKeyEncoder(e){this.keyEncoder=e}};const Ra=new Map;var ht=class pt extends lt{cache;constructor(a){super(),this.cache=a??new Map}lookup(a,n){return Promise.resolve(this.cache.get(this.keyEncoder(a,n))??null)}async update(a,n,r){this.cache.set(this.keyEncoder(a,n),r)}static global(){return new pt(Ra)}},Da=wa();const La=Ea(Da);var Fa=Object.defineProperty,Ba=(e,a,n)=>a in e?Fa(e,a,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[a]=n,Ua=(e,a,n)=>(Ba(e,a+"",n),n);function ja(e,a){let n=Array.from({length:e.length},(r,i)=>({start:i,end:i+1}));for(;n.length>1;){let r=null;for(let i=0;i<n.length-1;i++){const c=e.slice(n[i].start,n[i+1].end),h=a.get(c.join(","));h!=null&&(r==null||h<r[0])&&(r=[h,i])}if(r!=null){const i=r[1];n[i]={start:n[i].start,end:n[i+1].end},n.splice(i+1,1)}else break}return n}function Va(e,a){return e.length===1?[a.get(e.join(","))]:ja(e,a).map(n=>a.get(e.slice(n.start,n.end).join(","))).filter(n=>n!=null)}function za(e){return e.replace(/[\\^$*+?.()|[\]{}]/g,"\\$&")}var ve=class{specialTokens;inverseSpecialTokens;patStr;textEncoder=new TextEncoder;textDecoder=new TextDecoder("utf-8");rankMap=new Map;textMap=new Map;constructor(e,a){this.patStr=e.pat_str;const n=e.bpe_ranks.split(`
2
+ `).filter(Boolean).reduce((r,i)=>{const[c,h,...l]=i.split(" "),m=Number.parseInt(h,10);return l.forEach((g,T)=>r[g]=m+T),r},{});for(const[r,i]of Object.entries(n)){const c=La.toByteArray(r);this.rankMap.set(c.join(","),i),this.textMap.set(i,c)}this.specialTokens={...e.special_tokens,...a},this.inverseSpecialTokens=Object.entries(this.specialTokens).reduce((r,[i,c])=>(r[c]=this.textEncoder.encode(i),r),{})}encode(e,a=[],n="all"){const r=new RegExp(this.patStr,"ug"),i=ve.specialTokenRegex(Object.keys(this.specialTokens)),c=[],h=new Set(a==="all"?Object.keys(this.specialTokens):a),l=new Set(n==="all"?Object.keys(this.specialTokens).filter(g=>!h.has(g)):n);if(l.size>0){const g=ve.specialTokenRegex([...l]),T=e.match(g);if(T!=null)throw new Error(`The text contains a special token that is not allowed: ${T[0]}`)}let m=0;for(;;){let g=null,T=m;for(;i.lastIndex=T,g=i.exec(e),!(g==null||h.has(g[0]));)T=g.index+1;const _=g?.index??e.length;for(const d of e.substring(m,_).matchAll(r)){const y=this.textEncoder.encode(d[0]),f=this.rankMap.get(y.join(","));if(f!=null){c.push(f);continue}c.push(...Va(y,this.rankMap))}if(g==null)break;let v=this.specialTokens[g[0]];c.push(v),m=g.index+g[0].length}return c}decode(e){const a=[];let n=0;for(let c=0;c<e.length;++c){const h=e[c],l=this.textMap.get(h)??this.inverseSpecialTokens[h];l!=null&&(a.push(l),n+=l.length)}const r=new Uint8Array(n);let i=0;for(const c of a)r.set(c,i),i+=c.length;return this.textDecoder.decode(r)}},gt=ve;Ua(gt,"specialTokenRegex",e=>new RegExp(e.map(a=>za(a)).join("|"),"g"));function Ga(e){switch(e){case"gpt2":return"gpt2";case"code-cushman-001":case"code-cushman-002":case"code-davinci-001":case"code-davinci-002":case"cushman-codex":case"davinci-codex":case"davinci-002":case"text-davinci-002":case"text-davinci-003":return"p50k_base";case"code-davinci-edit-001":case"text-davinci-edit-001":return"p50k_edit";case"ada":case"babbage":case"babbage-002":case"code-search-ada-code-001":case"code-search-babbage-code-001":case"curie":case"davinci":case"text-ada-001":case"text-babbage-001":case"text-curie-001":case"text-davinci-001":case"text-search-ada-doc-001":case"text-search-babbage-doc-001":case"text-search-curie-doc-001":case"text-search-davinci-doc-001":case"text-similarity-ada-001":case"text-similarity-babbage-001":case"text-similarity-curie-001":case"text-similarity-davinci-001":return"r50k_base";case"gpt-3.5-turbo-instruct-0914":case"gpt-3.5-turbo-instruct":case"gpt-3.5-turbo-16k-0613":case"gpt-3.5-turbo-16k":case"gpt-3.5-turbo-0613":case"gpt-3.5-turbo-0301":case"gpt-3.5-turbo":case"gpt-4-32k-0613":case"gpt-4-32k-0314":case"gpt-4-32k":case"gpt-4-0613":case"gpt-4-0314":case"gpt-4":case"gpt-3.5-turbo-1106":case"gpt-35-turbo":case"gpt-4-1106-preview":case"gpt-4-vision-preview":case"gpt-3.5-turbo-0125":case"gpt-4-turbo":case"gpt-4-turbo-2024-04-09":case"gpt-4-turbo-preview":case"gpt-4-0125-preview":case"text-embedding-ada-002":case"text-embedding-3-small":case"text-embedding-3-large":return"cl100k_base";case"gpt-4o":case"gpt-4o-2024-05-13":case"gpt-4o-2024-08-06":case"gpt-4o-2024-11-20":case"gpt-4o-mini-2024-07-18":case"gpt-4o-mini":case"gpt-4o-search-preview":case"gpt-4o-search-preview-2025-03-11":case"gpt-4o-mini-search-preview":case"gpt-4o-mini-search-preview-2025-03-11":case"gpt-4o-audio-preview":case"gpt-4o-audio-preview-2024-12-17":case"gpt-4o-audio-preview-2024-10-01":case"gpt-4o-mini-audio-preview":case"gpt-4o-mini-audio-preview-2024-12-17":case"o1":case"o1-2024-12-17":case"o1-mini":case"o1-mini-2024-09-12":case"o1-preview":case"o1-preview-2024-09-12":case"o1-pro":case"o1-pro-2025-03-19":case"o3":case"o3-2025-04-16":case"o3-mini":case"o3-mini-2025-01-31":case"o4-mini":case"o4-mini-2025-04-16":case"chatgpt-4o-latest":case"gpt-4o-realtime":case"gpt-4o-realtime-preview-2024-10-01":case"gpt-4o-realtime-preview-2024-12-17":case"gpt-4o-mini-realtime-preview":case"gpt-4o-mini-realtime-preview-2024-12-17":case"gpt-4.1":case"gpt-4.1-2025-04-14":case"gpt-4.1-mini":case"gpt-4.1-mini-2025-04-14":case"gpt-4.1-nano":case"gpt-4.1-nano-2025-04-14":case"gpt-4.5-preview":case"gpt-4.5-preview-2025-02-27":case"gpt-5":case"gpt-5-2025-08-07":case"gpt-5-nano":case"gpt-5-nano-2025-08-07":case"gpt-5-mini":case"gpt-5-mini-2025-08-07":case"gpt-5-chat-latest":return"o200k_base";default:throw new Error("Unknown model")}}var $a={};U($a,{encodingForModel:()=>Oe,getEncoding:()=>mt});const se={},Za=new Ze({});async function mt(e){return e in se||(se[e]=Za.fetch(`https://tiktoken.pages.dev/js/${e}.json`).then(a=>a.json()).then(a=>new gt(a)).catch(a=>{throw delete se[e],a})),await se[e]}async function Oe(e){return mt(Ga(e))}var Ha={};U(Ha,{BaseLangChain:()=>dt,BaseLanguageModel:()=>bt,calculateMaxTokens:()=>Ya,getEmbeddingContextSize:()=>Wa,getModelContextSize:()=>ft,getModelNameForTiktoken:()=>he,isOpenAITool:()=>Xa});const he=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,Wa=e=>{switch(e){case"text-embedding-ada-002":return 8191;default:return 2046}},ft=e=>{switch(he(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 Xa(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 Ya=async({prompt:e,modelName:a})=>{let n;try{n=(await Oe(he(a))).encode(e).length}catch{console.warn("Failed to calculate number of tokens, falling back to approximate count"),n=Math.ceil(e.length/4)}return ft(a)-n},Ja=()=>!1;var dt=class extends H{verbose;callbacks;tags;metadata;get lc_attributes(){return{callbacks:void 0,verbose:void 0}}constructor(e){super(e),this.verbose=e.verbose??Ja(),this.callbacks=e.callbacks,this.tags=e.tags??[],this.metadata=e.metadata??{}}},bt=class extends dt{get callKeys(){return["stop","timeout","signal","tags","metadata","callbacks"]}caller;cache;constructor({callbacks:e,callbackManager:a,...n}){const{cache:r,...i}=n;super({callbacks:e??a,...i}),typeof r=="object"?this.cache=r:r?this.cache=ht.global():this.cache=void 0,this.caller=new Ze(n??{})}_encoding;async getNumTokens(e){let a;typeof e=="string"?a=e:a=e.map(r=>typeof r=="string"?r:r.type==="text"&&"text"in r?r.text:"").join("");let n=Math.ceil(a.length/4);if(!this._encoding)try{this._encoding=await Oe("modelName"in this?he(this.modelName):"gpt2")}catch(r){console.warn("Failed to calculate number of tokens, falling back to approximate count",r)}if(this._encoding)try{n=this._encoding.encode(a).length}catch(r){console.warn("Failed to calculate number of tokens, falling back to approximate count",r)}return n}static _convertInputToPromptValue(e){return typeof e=="string"?new it(e):Array.isArray(e)?new ot(e.map(ne)):e}_identifyingParams(){return{}}_getSerializedCacheKeyParametersForCall({config:e,...a}){const n={...this._identifyingParams(),...a,_type:this._llmType(),_model:this._modelType()};return Object.entries(n).filter(([c,h])=>h!==void 0).map(([c,h])=>`${c}:${JSON.stringify(h)}`).sort().join(",")}serialize(){return{...this._identifyingParams(),_type:this._llmType(),_model:this._modelType()}}static async deserialize(e){throw new Error("Use .toJSON() instead")}},ce=class extends H{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,a){const n=ie(a);return this.func&&await this.func(e,n),this._callWithConfig(r=>Promise.resolve(r),e,n)}async*transform(e,a){const n=ie(a);let r,i=!0;for await(const c of this._transformStreamWithConfig(e,h=>h,n))if(yield c,i)if(r===void 0)r=c;else try{r=oe(r,c)}catch{r=void 0,i=!1}this.func&&r!==void 0&&await this.func(r,n)}static assign(e){return new He(new We({steps:e}))}};const Ka=e=>e();function _e(e){const a=e.constructor;return new a({...e,content:e.contentBlocks,response_metadata:{...e.response_metadata,output_version:"v1"}})}var qa={};U(qa,{BaseChatModel:()=>_t,SimpleChatModel:()=>Qa});function ye(e){const a=[];for(const n of e){let r=n;if(Array.isArray(n.content))for(let i=0;i<n.content.length;i++){const c=n.content[i];(sa(c)||na(c))&&r===n&&(r=new n.constructor({...r,content:[...n.content.slice(0,i),ra(c),...n.content.slice(i+1)]}))}a.push(r)}return a}var _t=class $ extends bt{lc_namespace=["langchain","chat_models",this._llmType()];disableStreaming=!1;outputVersion;get callKeys(){return[...super.callKeys,"outputVersion"]}constructor(a){super(a),this.outputVersion=Ka(()=>{const n=a.outputVersion??Qt("LC_OUTPUT_VERSION");return n&&["v0","v1"].includes(n)?n:"v0"})}_separateRunnableConfigFromCallOptionsCompat(a){const[n,r]=super._separateRunnableConfigFromCallOptions(a);return r.signal=n.signal,[n,r]}async invoke(a,n){const r=$._convertInputToPromptValue(a);return(await this.generatePrompt([r],n,n?.callbacks)).generations[0][0].message}async*_streamResponseChunks(a,n,r){throw new Error("Not implemented.")}async*_streamIterator(a,n){if(this._streamResponseChunks===$.prototype._streamResponseChunks||this.disableStreaming)yield this.invoke(a,n);else{const i=$._convertInputToPromptValue(a).toChatMessages(),[c,h]=this._separateRunnableConfigFromCallOptionsCompat(n),l={...c.metadata,...this.getLsParams(h)},m=await be.configure(c.callbacks,this.callbacks,c.tags,this.tags,l,this.metadata,{verbose:this.verbose}),g={options:h,invocation_params:this?.invocationParams(h),batch_size:1},T=h.outputVersion??this.outputVersion,_=await m?.handleChatModelStart(this.toJSON(),[ye(i)],c.runId,void 0,g,void 0,void 0,c.runName);let v,d;try{for await(const y of this._streamResponseChunks(i,h,_?.[0])){if(y.message.id==null){const f=_?.at(0)?.runId;f!=null&&y.message._updateId(`run-${f}`)}y.message.response_metadata={...y.generationInfo,...y.message.response_metadata},T==="v1"?yield _e(y.message):yield y.message,v?v=v.concat(y):v=y,je(y.message)&&y.message.usage_metadata!==void 0&&(d={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((_??[]).map(f=>f?.handleLLMError(y))),y}await Promise.all((_??[]).map(y=>y?.handleLLMEnd({generations:[[v]],llmOutput:d})))}}getLsParams(a){const n=this.getName().startsWith("Chat")?this.getName().replace("Chat",""):this.getName();return{ls_model_type:"chat",ls_stop:a.stop,ls_provider:n}}async _generateUncached(a,n,r,i){const c=a.map(v=>v.map(ne));let h;if(i!==void 0&&i.length===c.length)h=i;else{const v={...r.metadata,...this.getLsParams(n)},d=await be.configure(r.callbacks,this.callbacks,r.tags,this.tags,v,this.metadata,{verbose:this.verbose}),y={options:n,invocation_params:this?.invocationParams(n),batch_size:1};h=await d?.handleChatModelStart(this.toJSON(),c.map(ye),r.runId,void 0,y,void 0,void 0,r.runName)}const l=n.outputVersion??this.outputVersion,m=[],g=[];if(!!h?.[0].handlers.find(ea)&&!this.disableStreaming&&c.length===1&&this._streamResponseChunks!==$.prototype._streamResponseChunks)try{const v=await this._streamResponseChunks(c[0],n,h?.[0]);let d,y;for await(const f of v){if(f.message.id==null){const E=h?.at(0)?.runId;E!=null&&f.message._updateId(`run-${E}`)}d===void 0?d=f:d=oe(d,f),je(f.message)&&f.message.usage_metadata!==void 0&&(y={tokenUsage:{promptTokens:f.message.usage_metadata.input_tokens,completionTokens:f.message.usage_metadata.output_tokens,totalTokens:f.message.usage_metadata.total_tokens}})}if(d===void 0)throw new Error("Received empty response from chat model call.");m.push([d]),await h?.[0].handleLLMEnd({generations:m,llmOutput:y})}catch(v){throw await h?.[0].handleLLMError(v),v}else{const v=await Promise.allSettled(c.map(async(d,y)=>{const f=await this._generate(d,{...n,promptIndex:y},h?.[y]);if(l==="v1")for(const E of f.generations)E.message=_e(E.message);return f}));await Promise.all(v.map(async(d,y)=>{if(d.status==="fulfilled"){const f=d.value;for(const E of f.generations){if(E.message.id==null){const w=h?.at(0)?.runId;w!=null&&E.message._updateId(`run-${w}`)}E.message.response_metadata={...E.generationInfo,...E.message.response_metadata}}return f.generations.length===1&&(f.generations[0].message.response_metadata={...f.llmOutput,...f.generations[0].message.response_metadata}),m[y]=f.generations,g[y]=f.llmOutput,h?.[y]?.handleLLMEnd({generations:[f.generations],llmOutput:f.llmOutput})}else return await h?.[y]?.handleLLMError(d.reason),Promise.reject(d.reason)}))}const _={generations:m,llmOutput:g.length?this._combineLLMOutput?.(...g):void 0};return Object.defineProperty(_,Ve,{value:h?{runIds:h?.map(v=>v.runId)}:void 0,configurable:!0}),_}async _generateCached({messages:a,cache:n,llmStringKey:r,parsedOptions:i,handledOptions:c}){const h=a.map(w=>w.map(ne)),l={...c.metadata,...this.getLsParams(i)},m=await be.configure(c.callbacks,this.callbacks,c.tags,this.tags,l,this.metadata,{verbose:this.verbose}),g={options:i,invocation_params:this?.invocationParams(i),batch_size:1},T=await m?.handleChatModelStart(this.toJSON(),h.map(ye),c.runId,void 0,g,void 0,void 0,c.runName),_=[],d=(await Promise.allSettled(h.map(async(w,P)=>{const I=$._convertInputToPromptValue(w).toString(),R=await n.lookup(I,r);return R==null&&_.push(P),R}))).map((w,P)=>({result:w,runManager:T?.[P]})).filter(({result:w})=>w.status==="fulfilled"&&w.value!=null||w.status==="rejected"),y=i.outputVersion??this.outputVersion,f=[];await Promise.all(d.map(async({result:w,runManager:P},I)=>{if(w.status==="fulfilled"){const R=w.value;return f[I]=R.map(L=>("message"in L&&Y(L.message)&&ta(L.message)&&(L.message.usage_metadata={input_tokens:0,output_tokens:0,total_tokens:0},y==="v1"&&(L.message=_e(L.message))),L.generationInfo={...L.generationInfo,tokenUsage:{}},L)),R.length&&await P?.handleLLMNewToken(R[0].text),P?.handleLLMEnd({generations:[R]},void 0,void 0,void 0,{cached:!0})}else return await P?.handleLLMError(w.reason,void 0,void 0,void 0,{cached:!0}),Promise.reject(w.reason)}));const E={generations:f,missingPromptIndices:_,startedRunManagers:T};return Object.defineProperty(E,Ve,{value:T?{runIds:T?.map(w=>w.runId)}:void 0,configurable:!0}),E}async generate(a,n,r){let i;Array.isArray(n)?i={stop:n}:i=n;const c=a.map(y=>y.map(ne)),[h,l]=this._separateRunnableConfigFromCallOptionsCompat(i);if(h.callbacks=h.callbacks??r,!this.cache)return this._generateUncached(c,l,h);const{cache:m}=this,g=this._getSerializedCacheKeyParametersForCall(l),{generations:T,missingPromptIndices:_,startedRunManagers:v}=await this._generateCached({messages:c,cache:m,llmStringKey:g,parsedOptions:l,handledOptions:h});let d={};if(_.length>0){const y=await this._generateUncached(_.map(f=>c[f]),l,h,v!==void 0?_.map(f=>v?.[f]):void 0);await Promise.all(y.generations.map(async(f,E)=>{const w=_[E];T[w]=f;const P=$._convertInputToPromptValue(c[w]).toString();return m.update(P,g,f)})),d=y.llmOutput??{}}return{generations:T,llmOutput:d}}invocationParams(a){return{}}_modelType(){return"base_chat_model"}async generatePrompt(a,n,r){const i=a.map(c=>c.toChatMessages());return this.generate(i,n,r)}withStructuredOutput(a,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 r=a,i=n?.name,c=$e(r)??"A function available to call.",h=n?.method,l=n?.includeRaw;if(h==="jsonMode")throw new Error('Base withStructuredOutput implementation only supports "functionCalling" as a method.');let m=i??"extract",g;Ce(r)?g=[{type:"function",function:{name:m,description:c,parameters:ue(r)}}]:("name"in r&&(m=r.name),g=[{type:"function",function:{name:m,description:c,parameters:r}}]);const T=this.bindTools(g),_=Ie.from(f=>{if(!aa.isInstance(f))throw new Error("Input is not an AIMessageChunk.");if(!f.tool_calls||f.tool_calls.length===0)throw new Error("No tool calls found in the response.");const E=f.tool_calls.find(w=>w.name===m);if(!E)throw new Error(`No tool call found with name ${m}.`);return E.args});if(!l)return T.pipe(_).withConfig({runName:"StructuredOutput"});const v=ce.assign({parsed:(f,E)=>_.invoke(f.raw,E)}),d=ce.assign({parsed:()=>null}),y=v.withFallbacks({fallbacks:[d]});return Xe.from([{raw:T},y]).withConfig({runName:"StructuredOutputRunnable"})}},Qa=class extends _t{async _generate(e,a,n){const r=await this._call(e,a,n),i=new Ye(r);if(typeof i.content!="string")throw new Error("Cannot generate with a simple chat model when output is not a string.");return{generations:[{text:i.content,message:i}]}}},es=class extends H{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,a){const{key:n,input:r}=e,i=this.runnables[n];if(i===void 0)throw new Error(`No runnable associated with key "${n}".`);return i.invoke(r,ie(a))}async batch(e,a,n){const r=e.map(_=>_.key),i=e.map(_=>_.input);if(r.find(_=>this.runnables[_]===void 0)!==void 0)throw new Error("One or more keys do not have a corresponding runnable.");const h=r.map(_=>this.runnables[_]),l=this._getOptionsList(a??{},e.length),m=l[0]?.maxConcurrency??n?.maxConcurrency,g=m&&m>0?m:e.length,T=[];for(let _=0;_<i.length;_+=g){const v=i.slice(_,_+g).map((y,f)=>h[f].invoke(y,l[f])),d=await Promise.all(v);T.push(d)}return T.flat()}async stream(e,a){const{key:n,input:r}=e,i=this.runnables[n];if(i===void 0)throw new Error(`No runnable associated with key "${n}".`);return i.stream(r,a)}},ts=class extends H{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(([i,c])=>[re(i),re(c)]),r=re(e[e.length-1]);return new this({branches:n,default:r})}async _invoke(e,a,n){let r;for(let i=0;i<this.branches.length;i+=1){const[c,h]=this.branches[i];if(await c.invoke(e,G(a,{callbacks:n?.getChild(`condition:${i+1}`)}))){r=await h.invoke(e,G(a,{callbacks:n?.getChild(`branch:${i+1}`)}));break}}return r||(r=await this.default.invoke(e,G(a,{callbacks:n?.getChild("branch:default")}))),r}async invoke(e,a={}){return this._callWithConfig(this._invoke,e,a)}async*_streamIterator(e,a){const r=await(await Je(a))?.handleChainStart(this.toJSON(),ia(e,"input"),a?.runId,void 0,void 0,void 0,a?.runName);let i,c=!0,h;try{for(let l=0;l<this.branches.length;l+=1){const[m,g]=this.branches[l];if(await m.invoke(e,G(a,{callbacks:r?.getChild(`condition:${l+1}`)}))){h=await g.stream(e,G(a,{callbacks:r?.getChild(`branch:${l+1}`)}));for await(const _ of h)if(yield _,c)if(i===void 0)i=_;else try{i=oe(i,_)}catch{i=void 0,c=!1}break}}if(h===void 0){h=await this.default.stream(e,G(a,{callbacks:r?.getChild("branch:default")}));for await(const l of h)if(yield l,c)if(i===void 0)i=l;else try{i=oe(i,l)}catch{i=void 0,c=!1}}}catch(l){throw await r?.handleChainError(l),l}await r?.handleChainEnd(i??{})}},as=class extends Ke{runnable;inputMessagesKey;outputMessagesKey;historyMessagesKey;getMessageHistory;constructor(e){let a=Ie.from((c,h)=>this._enterHistory(c,h??{})).withConfig({runName:"loadHistory"});const n=e.historyMessagesKey??e.inputMessagesKey;n&&(a=ce.assign({[n]:a}).withConfig({runName:"insertHistory"}));const r=a.pipe(e.runnable.withListeners({onEnd:(c,h)=>this._exitHistory(c,h??{})})).withConfig({runName:"RunnableWithMessageHistory"}),i=e.config??{};super({...e,config:i,bound:r}),this.runnable=e.runnable,this.getMessageHistory=e.getMessageHistory,this.inputMessagesKey=e.inputMessagesKey,this.outputMessagesKey=e.outputMessagesKey,this.historyMessagesKey=e.historyMessagesKey}_getInputMessages(e){let a;if(typeof e=="object"&&!Array.isArray(e)&&!Y(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])?a=e[n][0]:a=e[n]}else a=e;if(typeof a=="string")return[new Se(a)];if(Array.isArray(a))return a;if(Y(a))return[a];throw new Error(`Expected a string, BaseMessage, or array of BaseMessages.
3
+ Got ${JSON.stringify(a,null,2)}`)}_getOutputMessages(e){let a;if(!Array.isArray(e)&&!Y(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?a=e.generations[0][0].message:a=e[n]}else a=e;if(typeof a=="string")return[new Ye(a)];if(Array.isArray(a))return a;if(Y(a))return[a];throw new Error(`Expected a string, BaseMessage, or array of BaseMessages. Received: ${JSON.stringify(a,null,2)}`)}async _enterHistory(e,a){const r=await(a?.configurable?.messageHistory).getMessages();return this.historyMessagesKey===void 0?r.concat(this._getInputMessages(e)):r}async _exitHistory(e,a){const n=a.configurable?.messageHistory;let r;Array.isArray(e.inputs)&&Array.isArray(e.inputs[0])?r=e.inputs[0]:r=e.inputs;let i=this._getInputMessages(r);if(this.historyMessagesKey===void 0){const l=await n.getMessages();i=i.slice(l.length)}const c=e.outputs;if(!c)throw new Error(`Output values from 'Run' undefined. Run: ${JSON.stringify(e,null,2)}`);const h=this._getOutputMessages(c);await n.addMessages([...i,...h])}async _mergeConfig(...e){const a=await super._mergeConfig(...e);if(!a.configurable||!a.configurable.sessionId){const r={[this.inputMessagesKey??"input"]:"foo"},i={configurable:{sessionId:"123"}};throw new Error(`sessionId is required. Pass it in as part of the config argument to .invoke() or .stream()
4
+ eg. chain.invoke(${JSON.stringify(r)}, ${JSON.stringify(i)})`)}const{sessionId:n}=a.configurable;return a.configurable.messageHistory=await this.getMessageHistory(n),a}},ss={};U(ss,{RouterRunnable:()=>es,Runnable:()=>H,RunnableAssign:()=>He,RunnableBinding:()=>Ke,RunnableBranch:()=>ts,RunnableEach:()=>ma,RunnableLambda:()=>Ie,RunnableMap:()=>We,RunnableParallel:()=>ga,RunnablePassthrough:()=>ce,RunnablePick:()=>pa,RunnableRetry:()=>ha,RunnableSequence:()=>Xe,RunnableToolLike:()=>la,RunnableWithFallbacks:()=>ua,RunnableWithMessageHistory:()=>as,_coerceToRunnable:()=>re,ensureConfig:()=>ie,getCallbackManagerForConfig:()=>Je,mergeConfigs:()=>ca,patchConfig:()=>G,pickRunnableConfigKeys:()=>oa});var yt=class extends H{parseResultWithPrompt(e,a,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,a){return typeof e=="string"?this._callWithConfig(async(n,r)=>this.parseResult([{text:n}],r?.callbacks),e,{...a,runType:"parser"}):this._callWithConfig(async(n,r)=>this.parseResult([{message:n,text:this._baseMessageToString(n)}],r?.callbacks),e,{...a,runType:"parser"})}},pe=class extends yt{parseResult(e,a){return this.parse(e[0].text,a)}async parseWithPrompt(e,a,n){return this.parse(e,n)}_type(){throw new Error("_type not implemented")}},Z=class extends Error{llmOutput;observation;sendToLLM;constructor(e,a,n,r=!1){if(super(e),this.llmOutput=a,this.observation=n,this.sendToLLM=r,r&&(n===void 0||a===void 0))throw new Error("Arguments 'observation' & 'llmOutput' are required if 'sendToLlm' is true");fa(this,"OUTPUT_PARSING_FAILURE")}},q=class extends pe{async*_transform(e){for await(const a of e)typeof a=="string"?yield this.parseResult([{text:a}]):yield this.parseResult([{message:a,text:this._baseMessageToString(a)}])}async*transform(e,a){yield*this._transformStreamWithConfig(e,this._transform.bind(this),{...a,runType:"parser"})}},Ne=class extends q{diff=!1;constructor(e){super(e),this.diff=e?.diff??this.diff}async*_transform(e){let a,n;for await(const r of e){if(typeof r!="string"&&typeof r.content!="string")throw new Error("Cannot handle non-string output.");let i;if(da(r)){if(typeof r.content!="string")throw new Error("Cannot handle non-string message output.");i=new ze({message:r,text:r.content})}else if(Y(r)){if(typeof r.content!="string")throw new Error("Cannot handle non-string message output.");i=new ze({message:ba(r),text:r.content})}else i=new _a({text:r});n===void 0?n=i:n=n.concat(i);const c=await this.parsePartialResult([n]);c!=null&&!ya(c,a)&&(this.diff?yield this._diff(a,c):yield c,a=c)}}getFormatInstructions(){return""}},ns=class extends q{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""}},Q=class extends q{re;async*_transform(e){let a="";for await(const n of e)if(typeof n=="string"?a+=n:a+=n.content,this.re){const r=[...a.matchAll(this.re)];if(r.length>1){let i=0;for(const c of r.slice(0,-1))yield[c[1]],i+=(c.index??0)+c[0].length;a=a.slice(i)}}else{const r=await this.parse(a);if(r.length>1){for(const i of r.slice(0,-1))yield[i];a=r[r.length-1]}}for(const n of await this.parse(a))yield[n]}},rs=class extends Q{static lc_name(){return"CommaSeparatedListOutputParser"}lc_namespace=["langchain_core","output_parsers","list"];lc_serializable=!0;async parse(e){try{return e.trim().split(",").map(a=>a.trim())}catch{throw new Z(`Could not parse output: ${e}`,e)}}getFormatInstructions(){return"Your response should be a list of comma separated values, eg: `foo, bar, baz`"}},is=class extends Q{lc_namespace=["langchain_core","output_parsers","list"];length;separator;constructor({length:e,separator:a}){super(...arguments),this.length=e,this.separator=a||","}async parse(e){try{const a=e.trim().split(this.separator).map(n=>n.trim());if(this.length!==void 0&&a.length!==this.length)throw new Z(`Incorrect number of items. Expected ${this.length}, got ${a.length}.`);return a}catch(a){throw Object.getPrototypeOf(a)===Z.prototype?a:new Z(`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\`)`}},os=class extends Q{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:
5
+
6
+ 1. foo
7
+
8
+ 2. bar
9
+
10
+ 3. baz`}re=/\d+\.\s([^\n]+)/g;async parse(e){return[...e.matchAll(this.re)??[]].map(a=>a[1])}},cs=class extends Q{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:
11
+
12
+ 1. foo
13
+
14
+ 2. bar
15
+
16
+ 3. baz`}re=/^\s*[-*]\s([^\n]+)$/gm;async parse(e){return[...e.matchAll(this.re)??[]].map(a=>a[1])}},us=class extends q{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((a,n)=>a+this._messageContentToString(n),"")}},Tt=class extends pe{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 a=qe(Object.fromEntries(Object.entries(e).map(([n,r])=>[n,Qe().describe(r)])));return new this(a)}getFormatInstructions(){return`You must format your output as a JSON value that adheres to a given "JSON Schema" instance.
17
+
18
+ "JSON Schema" is a declarative language that allows you to annotate and validate JSON documents.
19
+
20
+ For example, the example "JSON Schema" instance {{"properties": {{"foo": {{"description": "a list of test words", "type": "array", "items": {{"type": "string"}}}}}}, "required": ["foo"]}}
21
+ 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.
22
+ 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.
23
+
24
+ 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!
25
+
26
+ Here is the JSON Schema instance your output must adhere to. Include the enclosing markdown codeblock:
27
+ \`\`\`json
28
+ ${JSON.stringify(ue(this.schema))}
29
+ \`\`\`
30
+ `}async parse(e){try{const a=e.trim(),r=(a.match(/^```(?:json)?\s*([\s\S]*?)```/)?.[1]||a.match(/```json\s*([\s\S]*?)```/)?.[1]||a).replace(/"([^"\\]*(\\.[^"\\]*)*)"/g,(i,c)=>`"${c.replace(/\n/g,"\\n")}"`).replace(/\n/g,"");return await Ge(this.schema,JSON.parse(r))}catch(a){throw new Z(`Failed to parse. Text: "${e}". Error: ${a}`,e)}}},vt=class extends Tt{static lc_name(){return"JsonMarkdownStructuredOutputParser"}getFormatInstructions(e){const a=e?.interpolationDepth??1;if(a<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:
31
+ \`\`\`json
32
+ ${this._schemaToInstruction(ue(this.schema)).replaceAll("{","{".repeat(a)).replaceAll("}","}".repeat(a))}
33
+ \`\`\``}_schemaToInstruction(e,a=2){const n=e;if("type"in n){let r=!1,i;if(Array.isArray(n.type)){const l=n.type.findIndex(m=>m==="null");l!==-1&&(r=!0,n.type.splice(l,1)),i=n.type.join(" | ")}else i=n.type;if(n.type==="object"&&n.properties){const l=n.description?` // ${n.description}`:"";return`{
34
+ ${Object.entries(n.properties).map(([g,T])=>{const _=n.required?.includes(g)?"":" (optional)";return`${" ".repeat(a)}"${g}": ${this._schemaToInstruction(T,a+2)}${_}`}).join(`
35
+ `)}
36
+ ${" ".repeat(a-2)}}${l}`}if(n.type==="array"&&n.items){const l=n.description?` // ${n.description}`:"";return`array[
37
+ ${" ".repeat(a)}${this._schemaToInstruction(n.items,a+2)}
38
+ ${" ".repeat(a-2)}] ${l}`}const c=r?" (nullable)":"",h=n.description?` // ${n.description}`:"";return`${i}${h}${c}`}if("anyOf"in n)return n.anyOf.map(r=>this._schemaToInstruction(r,a)).join(`
39
+ ${" ".repeat(a-2)}`);throw new Error("unsupported schema type")}static fromZodSchema(e){return new this(e)}static fromNamesAndDescriptions(e){const a=qe(Object.fromEntries(Object.entries(e).map(([n,r])=>[n,Qe().describe(r)])));return new this(a)}},ls=class extends pe{structuredInputParser;constructor({inputSchema:e}){super(...arguments),this.structuredInputParser=new vt(e)}async parse(e){let a;try{a=await this.structuredInputParser.parse(e)}catch(n){throw new Z(`Failed to parse. Text: "${e}". Error: ${n}`,e)}return this.outputProcessor(a)}getFormatInstructions(){return this.structuredInputParser.getFormatInstructions()}},hs={};U(hs,{applyPatch:()=>Ta,compare:()=>Ae});var ps=class extends Ne{static lc_name(){return"JsonOutputParser"}lc_namespace=["langchain_core","output_parsers"];lc_serializable=!0;_concatOutputChunks(e,a){return this.diff?super._concatOutputChunks(e,a):a}_diff(e,a){if(a)return e?Ae(e,a):[{op:"replace",path:"",value:a}]}async parsePartialResult(e){return Te(e[0].text)}async parse(e){return Te(e,JSON.parse)}getFormatInstructions(){return""}};const gs=function(){const e={};e.parser=function(s,t){return new n(s,t)},e.SAXParser=n,e.SAXStream=g,e.createStream=m,e.MAX_BUFFER_LENGTH=64*1024;const a=["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(s,t){if(!(this instanceof n))return new n(s,t);var p=this;i(p),p.q=p.c="",p.bufferCheckPosition=e.MAX_BUFFER_LENGTH,p.opt=t||{},p.opt.lowercase=p.opt.lowercase||p.opt.lowercasetags,p.looseCase=p.opt.lowercase?"toLowerCase":"toUpperCase",p.tags=[],p.closed=p.closedRoot=p.sawRoot=!1,p.tag=p.error=null,p.strict=!!s,p.noscript=!!(s||p.opt.noscript),p.state=u.BEGIN,p.strictEntities=p.opt.strictEntities,p.ENTITIES=p.strictEntities?Object.create(e.XML_ENTITIES):Object.create(e.ENTITIES),p.attribList=[],p.opt.xmlns&&(p.ns=Object.create(y)),p.trackPosition=p.opt.position!==!1,p.trackPosition&&(p.position=p.line=p.column=0),J(p,"onready")}Object.create||(Object.create=function(s){function t(){}t.prototype=s;var p=new t;return p}),Object.keys||(Object.keys=function(s){var t=[];for(var p in s)s.hasOwnProperty(p)&&t.push(p);return t});function r(s){for(var t=Math.max(e.MAX_BUFFER_LENGTH,10),p=0,o=0,C=a.length;o<C;o++){var O=s[a[o]].length;if(O>t)switch(a[o]){case"textNode":K(s);break;case"cdata":A(s,"oncdata",s.cdata),s.cdata="";break;case"script":A(s,"onscript",s.script),s.script="";break;default:ee(s,"Max buffer length exceeded: "+a[o])}p=Math.max(p,O)}var N=e.MAX_BUFFER_LENGTH-p;s.bufferCheckPosition=N+s.position}function i(s){for(var t=0,p=a.length;t<p;t++)s[a[t]]=""}function c(s){K(s),s.cdata!==""&&(A(s,"oncdata",s.cdata),s.cdata=""),s.script!==""&&(A(s,"onscript",s.script),s.script="")}n.prototype={end:function(){Pe(this)},write:St,resume:function(){return this.error=null,this},close:function(){return this.write(null)},flush:function(){c(this)}};var h=ReadableStream;h||(h=function(){});var l=e.EVENTS.filter(function(s){return s!=="error"&&s!=="end"});function m(s,t){return new g(s,t)}function g(s,t){if(!(this instanceof g))return new g(s,t);h.apply(this),this._parser=new n(s,t),this.writable=!0,this.readable=!0;var p=this;this._parser.onend=function(){p.emit("end")},this._parser.onerror=function(o){p.emit("error",o),p._parser.error=null},this._decoder=null,l.forEach(function(o){Object.defineProperty(p,"on"+o,{get:function(){return p._parser["on"+o]},set:function(C){if(!C)return p.removeAllListeners(o),p._parser["on"+o]=C,C;p.on(o,C)},enumerable:!0,configurable:!1})})}g.prototype=Object.create(h.prototype,{constructor:{value:g}}),g.prototype.write=function(s){return this._parser.write(s.toString()),this.emit("data",s),!0},g.prototype.end=function(s){return s&&s.length&&this.write(s),this._parser.end(),!0},g.prototype.on=function(s,t){var p=this;return!p._parser["on"+s]&&l.indexOf(s)!==-1&&(p._parser["on"+s]=function(){var o=arguments.length===1?[arguments[0]]:Array.apply(null,arguments);o.splice(0,0,s),p.emit.apply(p,o)}),h.prototype.on.call(p,s,t)};var T="[CDATA[",_="DOCTYPE",v="http://www.w3.org/XML/1998/namespace",d="http://www.w3.org/2000/xmlns/",y={xml:v,xmlns:d},f=/[:_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]/,E=/[:_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-]/,w=/[#:_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]/,P=/[#:_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 I(s){return s===" "||s===`
40
+ `||s==="\r"||s===" "}function R(s){return s==='"'||s==="'"}function L(s){return s===">"||I(s)}function j(s,t){return s.test(t)}function wt(s,t){return!j(s,t)}var u=0;e.STATE={BEGIN:u++,BEGIN_WHITESPACE:u++,TEXT:u++,TEXT_ENTITY:u++,OPEN_WAKA:u++,SGML_DECL:u++,SGML_DECL_QUOTED:u++,DOCTYPE:u++,DOCTYPE_QUOTED:u++,DOCTYPE_DTD:u++,DOCTYPE_DTD_QUOTED:u++,COMMENT_STARTING:u++,COMMENT:u++,COMMENT_ENDING:u++,COMMENT_ENDED:u++,CDATA:u++,CDATA_ENDING:u++,CDATA_ENDING_2:u++,PROC_INST:u++,PROC_INST_BODY:u++,PROC_INST_ENDING:u++,OPEN_TAG:u++,OPEN_TAG_SLASH:u++,ATTRIB:u++,ATTRIB_NAME:u++,ATTRIB_NAME_SAW_WHITE:u++,ATTRIB_VALUE:u++,ATTRIB_VALUE_QUOTED:u++,ATTRIB_VALUE_CLOSED:u++,ATTRIB_VALUE_UNQUOTED:u++,ATTRIB_VALUE_ENTITY_Q:u++,ATTRIB_VALUE_ENTITY_U:u++,CLOSE_TAG:u++,CLOSE_TAG_SAW_WHITE:u++,SCRIPT:u++,SCRIPT_ENDING:u++},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(s){var t=e.ENTITIES[s],p=typeof t=="number"?String.fromCharCode(t):t;e.ENTITIES[s]=p});for(var ke in e.STATE)e.STATE[e.STATE[ke]]=ke;u=e.STATE;function J(s,t,p){s[t]&&s[t](p)}function A(s,t,p){s.textNode&&K(s),J(s,t,p)}function K(s){s.textNode=xe(s.opt,s.textNode),s.textNode&&J(s,"ontext",s.textNode),s.textNode=""}function xe(s,t){return s.trim&&(t=t.trim()),s.normalize&&(t=t.replace(/\s+/g," ")),t}function ee(s,t){return K(s),s.trackPosition&&(t+=`
41
+ Line: `+s.line+`
42
+ Column: `+s.column+`
43
+ Char: `+s.c),t=new Error(t),s.error=t,J(s,"onerror",t),s}function Pe(s){return s.sawRoot&&!s.closedRoot&&S(s,"Unclosed root tag"),s.state!==u.BEGIN&&s.state!==u.BEGIN_WHITESPACE&&s.state!==u.TEXT&&ee(s,"Unexpected end"),K(s),s.c="",s.closed=!0,J(s,"onend"),n.call(s,s.strict,s.opt),s}function S(s,t){if(typeof s!="object"||!(s instanceof n))throw new Error("bad call to strictFail");s.strict&&ee(s,t)}function Ct(s){s.strict||(s.tagName=s.tagName[s.looseCase]());var t=s.tags[s.tags.length-1]||s,p=s.tag={name:s.tagName,attributes:{}};s.opt.xmlns&&(p.ns=t.ns),s.attribList.length=0,A(s,"onopentagstart",p)}function ge(s,t){var p=s.indexOf(":"),o=p<0?["",s]:s.split(":"),C=o[0],O=o[1];return t&&s==="xmlns"&&(C="xmlns",O=""),{prefix:C,local:O}}function me(s){if(s.strict||(s.attribName=s.attribName[s.looseCase]()),s.attribList.indexOf(s.attribName)!==-1||s.tag.attributes.hasOwnProperty(s.attribName)){s.attribName=s.attribValue="";return}if(s.opt.xmlns){var t=ge(s.attribName,!0),p=t.prefix,o=t.local;if(p==="xmlns")if(o==="xml"&&s.attribValue!==v)S(s,"xml: prefix must be bound to "+v+`
44
+ Actual: `+s.attribValue);else if(o==="xmlns"&&s.attribValue!==d)S(s,"xmlns: prefix must be bound to "+d+`
45
+ Actual: `+s.attribValue);else{var C=s.tag,O=s.tags[s.tags.length-1]||s;C.ns===O.ns&&(C.ns=Object.create(O.ns)),C.ns[o]=s.attribValue}s.attribList.push([s.attribName,s.attribValue])}else s.tag.attributes[s.attribName]=s.attribValue,A(s,"onattribute",{name:s.attribName,value:s.attribValue});s.attribName=s.attribValue=""}function z(s,t){if(s.opt.xmlns){var p=s.tag,o=ge(s.tagName);p.prefix=o.prefix,p.local=o.local,p.uri=p.ns[o.prefix]||"",p.prefix&&!p.uri&&(S(s,"Unbound namespace prefix: "+JSON.stringify(s.tagName)),p.uri=o.prefix);var C=s.tags[s.tags.length-1]||s;p.ns&&C.ns!==p.ns&&Object.keys(p.ns).forEach(function(Fe){A(s,"onopennamespace",{prefix:Fe,uri:p.ns[Fe]})});for(var O=0,N=s.attribList.length;O<N;O++){var M=s.attribList[O],D=M[0],W=M[1],x=ge(D,!0),V=x.prefix,It=x.local,Le=V===""?"":p.ns[V]||"",de={name:D,value:W,prefix:V,local:It,uri:Le};V&&V!=="xmlns"&&!Le&&(S(s,"Unbound namespace prefix: "+JSON.stringify(V)),de.uri=V),s.tag.attributes[D]=de,A(s,"onattribute",de)}s.attribList.length=0}s.tag.isSelfClosing=!!t,s.sawRoot=!0,s.tags.push(s.tag),A(s,"onopentag",s.tag),t||(!s.noscript&&s.tagName.toLowerCase()==="script"?s.state=u.SCRIPT:s.state=u.TEXT,s.tag=null,s.tagName=""),s.attribName=s.attribValue="",s.attribList.length=0}function fe(s){if(!s.tagName){S(s,"Weird empty close tag."),s.textNode+="</>",s.state=u.TEXT;return}if(s.script){if(s.tagName!=="script"){s.script+="</"+s.tagName+">",s.tagName="",s.state=u.SCRIPT;return}A(s,"onscript",s.script),s.script=""}var t=s.tags.length,p=s.tagName;s.strict||(p=p[s.looseCase]());for(var o=p;t--;){var C=s.tags[t];if(C.name!==o)S(s,"Unexpected close tag");else break}if(t<0){S(s,"Unmatched closing tag: "+s.tagName),s.textNode+="</"+s.tagName+">",s.state=u.TEXT;return}s.tagName=p;for(var O=s.tags.length;O-- >t;){var N=s.tag=s.tags.pop();s.tagName=s.tag.name,A(s,"onclosetag",s.tagName);var M={};for(var D in N.ns)M[D]=N.ns[D];var W=s.tags[s.tags.length-1]||s;s.opt.xmlns&&N.ns!==W.ns&&Object.keys(N.ns).forEach(function(x){var V=N.ns[x];A(s,"onclosenamespace",{prefix:x,uri:V})})}t===0&&(s.closedRoot=!0),s.tagName=s.attribValue=s.attribName="",s.attribList.length=0,s.state=u.TEXT}function Me(s){var t=s.entity,p=t.toLowerCase(),o,C="";return s.ENTITIES[t]?s.ENTITIES[t]:s.ENTITIES[p]?s.ENTITIES[p]:(t=p,t.charAt(0)==="#"&&(t.charAt(1)==="x"?(t=t.slice(2),o=parseInt(t,16),C=o.toString(16)):(t=t.slice(1),o=parseInt(t,10),C=o.toString(10))),t=t.replace(/^0+/,""),isNaN(o)||C.toLowerCase()!==t?(S(s,"Invalid character entity"),"&"+s.entity+";"):String.fromCodePoint(o))}function Re(s,t){t==="<"?(s.state=u.OPEN_WAKA,s.startTagPosition=s.position):I(t)||(S(s,"Non-whitespace before first tag."),s.textNode=t,s.state=u.TEXT)}function De(s,t){var p="";return t<s.length&&(p=s.charAt(t)),p}function St(s){var t=this;if(this.error)throw this.error;if(t.closed)return ee(t,"Cannot write after close. Assign an onready handler.");if(s===null)return Pe(t);typeof s=="object"&&(s=s.toString());for(var p=0,o="";o=De(s,p++),t.c=o,!!o;)switch(t.trackPosition&&(t.position++,o===`
46
+ `?(t.line++,t.column=0):t.column++),t.state){case u.BEGIN:if(t.state=u.BEGIN_WHITESPACE,o==="\uFEFF")continue;Re(t,o);continue;case u.BEGIN_WHITESPACE:Re(t,o);continue;case u.TEXT:if(t.sawRoot&&!t.closedRoot){for(var C=p-1;o&&o!=="<"&&o!=="&";)o=De(s,p++),o&&t.trackPosition&&(t.position++,o===`
47
+ `?(t.line++,t.column=0):t.column++);t.textNode+=s.substring(C,p-1)}o==="<"&&!(t.sawRoot&&t.closedRoot&&!t.strict)?(t.state=u.OPEN_WAKA,t.startTagPosition=t.position):(!I(o)&&(!t.sawRoot||t.closedRoot)&&S(t,"Text data outside of root node."),o==="&"?t.state=u.TEXT_ENTITY:t.textNode+=o);continue;case u.SCRIPT:o==="<"?t.state=u.SCRIPT_ENDING:t.script+=o;continue;case u.SCRIPT_ENDING:o==="/"?t.state=u.CLOSE_TAG:(t.script+="<"+o,t.state=u.SCRIPT);continue;case u.OPEN_WAKA:if(o==="!")t.state=u.SGML_DECL,t.sgmlDecl="";else if(!I(o))if(j(f,o))t.state=u.OPEN_TAG,t.tagName=o;else if(o==="/")t.state=u.CLOSE_TAG,t.tagName="";else if(o==="?")t.state=u.PROC_INST,t.procInstName=t.procInstBody="";else{if(S(t,"Unencoded <"),t.startTagPosition+1<t.position){var O=t.position-t.startTagPosition;o=new Array(O).join(" ")+o}t.textNode+="<"+o,t.state=u.TEXT}continue;case u.SGML_DECL:(t.sgmlDecl+o).toUpperCase()===T?(A(t,"onopencdata"),t.state=u.CDATA,t.sgmlDecl="",t.cdata=""):t.sgmlDecl+o==="--"?(t.state=u.COMMENT,t.comment="",t.sgmlDecl=""):(t.sgmlDecl+o).toUpperCase()===_?(t.state=u.DOCTYPE,(t.doctype||t.sawRoot)&&S(t,"Inappropriately located doctype declaration"),t.doctype="",t.sgmlDecl=""):o===">"?(A(t,"onsgmldeclaration",t.sgmlDecl),t.sgmlDecl="",t.state=u.TEXT):(R(o)&&(t.state=u.SGML_DECL_QUOTED),t.sgmlDecl+=o);continue;case u.SGML_DECL_QUOTED:o===t.q&&(t.state=u.SGML_DECL,t.q=""),t.sgmlDecl+=o;continue;case u.DOCTYPE:o===">"?(t.state=u.TEXT,A(t,"ondoctype",t.doctype),t.doctype=!0):(t.doctype+=o,o==="["?t.state=u.DOCTYPE_DTD:R(o)&&(t.state=u.DOCTYPE_QUOTED,t.q=o));continue;case u.DOCTYPE_QUOTED:t.doctype+=o,o===t.q&&(t.q="",t.state=u.DOCTYPE);continue;case u.DOCTYPE_DTD:t.doctype+=o,o==="]"?t.state=u.DOCTYPE:R(o)&&(t.state=u.DOCTYPE_DTD_QUOTED,t.q=o);continue;case u.DOCTYPE_DTD_QUOTED:t.doctype+=o,o===t.q&&(t.state=u.DOCTYPE_DTD,t.q="");continue;case u.COMMENT:o==="-"?t.state=u.COMMENT_ENDING:t.comment+=o;continue;case u.COMMENT_ENDING:o==="-"?(t.state=u.COMMENT_ENDED,t.comment=xe(t.opt,t.comment),t.comment&&A(t,"oncomment",t.comment),t.comment=""):(t.comment+="-"+o,t.state=u.COMMENT);continue;case u.COMMENT_ENDED:o!==">"?(S(t,"Malformed comment"),t.comment+="--"+o,t.state=u.COMMENT):t.state=u.TEXT;continue;case u.CDATA:o==="]"?t.state=u.CDATA_ENDING:t.cdata+=o;continue;case u.CDATA_ENDING:o==="]"?t.state=u.CDATA_ENDING_2:(t.cdata+="]"+o,t.state=u.CDATA);continue;case u.CDATA_ENDING_2:o===">"?(t.cdata&&A(t,"oncdata",t.cdata),A(t,"onclosecdata"),t.cdata="",t.state=u.TEXT):o==="]"?t.cdata+="]":(t.cdata+="]]"+o,t.state=u.CDATA);continue;case u.PROC_INST:o==="?"?t.state=u.PROC_INST_ENDING:I(o)?t.state=u.PROC_INST_BODY:t.procInstName+=o;continue;case u.PROC_INST_BODY:if(!t.procInstBody&&I(o))continue;o==="?"?t.state=u.PROC_INST_ENDING:t.procInstBody+=o;continue;case u.PROC_INST_ENDING:o===">"?(A(t,"onprocessinginstruction",{name:t.procInstName,body:t.procInstBody}),t.procInstName=t.procInstBody="",t.state=u.TEXT):(t.procInstBody+="?"+o,t.state=u.PROC_INST_BODY);continue;case u.OPEN_TAG:j(E,o)?t.tagName+=o:(Ct(t),o===">"?z(t):o==="/"?t.state=u.OPEN_TAG_SLASH:(I(o)||S(t,"Invalid character in tag name"),t.state=u.ATTRIB));continue;case u.OPEN_TAG_SLASH:o===">"?(z(t,!0),fe(t)):(S(t,"Forward-slash in opening tag not followed by >"),t.state=u.ATTRIB);continue;case u.ATTRIB:if(I(o))continue;o===">"?z(t):o==="/"?t.state=u.OPEN_TAG_SLASH:j(f,o)?(t.attribName=o,t.attribValue="",t.state=u.ATTRIB_NAME):S(t,"Invalid attribute name");continue;case u.ATTRIB_NAME:o==="="?t.state=u.ATTRIB_VALUE:o===">"?(S(t,"Attribute without value"),t.attribValue=t.attribName,me(t),z(t)):I(o)?t.state=u.ATTRIB_NAME_SAW_WHITE:j(E,o)?t.attribName+=o:S(t,"Invalid attribute name");continue;case u.ATTRIB_NAME_SAW_WHITE:if(o==="=")t.state=u.ATTRIB_VALUE;else{if(I(o))continue;S(t,"Attribute without value"),t.tag.attributes[t.attribName]="",t.attribValue="",A(t,"onattribute",{name:t.attribName,value:""}),t.attribName="",o===">"?z(t):j(f,o)?(t.attribName=o,t.state=u.ATTRIB_NAME):(S(t,"Invalid attribute name"),t.state=u.ATTRIB)}continue;case u.ATTRIB_VALUE:if(I(o))continue;R(o)?(t.q=o,t.state=u.ATTRIB_VALUE_QUOTED):(S(t,"Unquoted attribute value"),t.state=u.ATTRIB_VALUE_UNQUOTED,t.attribValue=o);continue;case u.ATTRIB_VALUE_QUOTED:if(o!==t.q){o==="&"?t.state=u.ATTRIB_VALUE_ENTITY_Q:t.attribValue+=o;continue}me(t),t.q="",t.state=u.ATTRIB_VALUE_CLOSED;continue;case u.ATTRIB_VALUE_CLOSED:I(o)?t.state=u.ATTRIB:o===">"?z(t):o==="/"?t.state=u.OPEN_TAG_SLASH:j(f,o)?(S(t,"No whitespace between attributes"),t.attribName=o,t.attribValue="",t.state=u.ATTRIB_NAME):S(t,"Invalid attribute name");continue;case u.ATTRIB_VALUE_UNQUOTED:if(!L(o)){o==="&"?t.state=u.ATTRIB_VALUE_ENTITY_U:t.attribValue+=o;continue}me(t),o===">"?z(t):t.state=u.ATTRIB;continue;case u.CLOSE_TAG:if(t.tagName)o===">"?fe(t):j(E,o)?t.tagName+=o:t.script?(t.script+="</"+t.tagName,t.tagName="",t.state=u.SCRIPT):(I(o)||S(t,"Invalid tagname in closing tag"),t.state=u.CLOSE_TAG_SAW_WHITE);else{if(I(o))continue;wt(f,o)?t.script?(t.script+="</"+o,t.state=u.SCRIPT):S(t,"Invalid tagname in closing tag."):t.tagName=o}continue;case u.CLOSE_TAG_SAW_WHITE:if(I(o))continue;o===">"?fe(t):S(t,"Invalid characters in closing tag");continue;case u.TEXT_ENTITY:case u.ATTRIB_VALUE_ENTITY_Q:case u.ATTRIB_VALUE_ENTITY_U:var N,M;switch(t.state){case u.TEXT_ENTITY:N=u.TEXT,M="textNode";break;case u.ATTRIB_VALUE_ENTITY_Q:N=u.ATTRIB_VALUE_QUOTED,M="attribValue";break;case u.ATTRIB_VALUE_ENTITY_U:N=u.ATTRIB_VALUE_UNQUOTED,M="attribValue";break}if(o===";")if(t.opt.unparsedEntities){var D=Me(t);t.entity="",t.state=N,t.write(D)}else t[M]+=Me(t),t.entity="",t.state=N;else j(t.entity.length?P:w,o)?t.entity+=o:(S(t,"Invalid character in entity name"),t[M]+="&"+t.entity+o,t.entity="",t.state=N);continue;default:throw new Error(t,"Unknown state: "+t.state)}return t.position>=t.bufferCheckPosition&&r(t),t}return String.fromCodePoint||(function(){var s=String.fromCharCode,t=Math.floor,p=function(){var o=16384,C=[],O,N,M=-1,D=arguments.length;if(!D)return"";for(var W="";++M<D;){var x=Number(arguments[M]);if(!isFinite(x)||x<0||x>1114111||t(x)!==x)throw RangeError("Invalid code point: "+x);x<=65535?C.push(x):(x-=65536,O=(x>>10)+55296,N=x%1024+56320,C.push(O,N)),(M+1===D||C.length>o)&&(W+=s.apply(null,C),C.length=0)}return W};Object.defineProperty?Object.defineProperty(String,"fromCodePoint",{value:p,configurable:!0,writable:!0}):String.fromCodePoint=p})(),e},ms=gs(),Ee=`The output should be formatted as a XML file.
48
+ 1. Output should conform to the tags below.
49
+ 2. If tags are not given, make them on your own.
50
+ 3. Remember to always open and close all the tags.
51
+
52
+ As an example, for the tags ["foo", "bar", "baz"]:
53
+ 1. String "<foo>
54
+ <bar>
55
+ <baz></baz>
56
+ </bar>
57
+ </foo>" is a well-formatted instance of the schema.
58
+ 2. String "<foo>
59
+ <bar>
60
+ </foo>" is a badly-formatted instance.
61
+ 3. String "<foo>
62
+ <tag>
63
+ </tag>
64
+ </foo>" is a badly-formatted instance.
65
+
66
+ Here are the output tags:
67
+ \`\`\`
68
+ {tags}
69
+ \`\`\``;var fs=class extends Ne{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,a){if(a)return e?Ae(e,a):[{op:"replace",path:"",value:a}]}async parsePartialResult(e){return we(e[0].text)}async parse(e){return we(e)}getFormatInstructions(){return!!(this.tags&&this.tags.length>0)?Ee.replace("{tags}",this.tags?.join(", ")??""):Ee}};const ds=e=>e.split(`
70
+ `).map(a=>a.replace(/^\s+/,"")).join(`
71
+ `).trim(),Et=e=>{if(Object.keys(e).length===0)return{};const a={};return e.children.length>0?(a[e.name]=e.children.map(Et),a):(a[e.name]=e.text??void 0,a)};function we(e){const a=ds(e),n=ms.parser(!0);let r={};const i=[];n.onopentag=l=>{const m={name:l.name,attributes:l.attributes,children:[],text:"",isSelfClosing:l.isSelfClosing};i.length>0?i[i.length-1].children.push(m):r=m,l.isSelfClosing||i.push(m)},n.onclosetag=()=>{if(i.length>0){const l=i.pop();i.length===0&&l&&(r=l)}},n.ontext=l=>{if(i.length>0){const m=i[i.length-1];m.text+=l}},n.onattribute=l=>{if(i.length>0){const m=i[i.length-1];m.attributes[l.name]=l.value}};const c=/```(xml)?(.*)```/s.exec(a),h=c?c[2]:a;return n.write(h).close(),r&&r.name==="?xml"&&(r=r.children[0]),Et(r)}var bs={};U(bs,{AsymmetricStructuredOutputParser:()=>ls,BaseCumulativeTransformOutputParser:()=>Ne,BaseLLMOutputParser:()=>yt,BaseOutputParser:()=>pe,BaseTransformOutputParser:()=>q,BytesOutputParser:()=>ns,CommaSeparatedListOutputParser:()=>rs,CustomListOutputParser:()=>is,JsonMarkdownStructuredOutputParser:()=>vt,JsonOutputParser:()=>ps,ListOutputParser:()=>Q,MarkdownListOutputParser:()=>cs,NumberedListOutputParser:()=>os,OutputParserException:()=>Z,StringOutputParser:()=>us,StructuredOutputParser:()=>Tt,XMLOutputParser:()=>fs,XML_FORMAT_INSTRUCTIONS:()=>Ee,parseJsonMarkdown:()=>Te,parsePartialJson:()=>va,parseXMLMarkdown:()=>we});export{Ne as B,ot as C,Oa as I,ps as J,Z as O,ce as R,Tt as S,bt as a,dt as b,tt as c,at as d,nt as e,Xa as f,yt as g,_t as h,st as i,Ia as j,Ae as k,it as l,pe as m,$a as n,hs as o,ka as p,Sa as q,ss as r,ct as s,Ca as t,Aa as u,bs as v,qa as w,Ha as x,xa as y,ft as z};
@@ -1,4 +1,4 @@
1
- import{g as St,e as zo}from"./index-DZxMwvFi.js";import{u as Go}from"./util-t-trnxQI.js";import{o as $o}from"./__vite-browser-external-DFygW7-s.js";import{r as Yo}from"./index-DRz5BQNA.js";import{p as Vo}from"./path-C9FudP8b.js";function Ko(r,i){for(var g=0;g<i.length;g++){const E=i[g];if(typeof E!="string"&&!Array.isArray(E)){for(const d in E)if(d!=="default"&&!(d in r)){const l=Object.getOwnPropertyDescriptor(E,d);l&&Object.defineProperty(r,d,l.get?l:{enumerable:!0,get:()=>E[d]})}}}return Object.freeze(Object.defineProperty(r,Symbol.toStringTag,{value:"Module"}))}var Pt={},ze={},Tt,rn;function ye(){if(rn)return Tt;rn=1;function r(m){"@babel/helpers - typeof";return r=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(s){return typeof s}:function(s){return s&&typeof Symbol=="function"&&s.constructor===Symbol&&s!==Symbol.prototype?"symbol":typeof s},r(m)}function i(m,s,c){return Object.defineProperty(m,"prototype",{writable:!1}),m}function g(m,s){if(!(m instanceof s))throw new TypeError("Cannot call a class as a function")}function E(m,s,c){return s=p(s),d(m,_()?Reflect.construct(s,c||[],p(m).constructor):s.apply(m,c))}function d(m,s){if(s&&(r(s)=="object"||typeof s=="function"))return s;if(s!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return l(m)}function l(m){if(m===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return m}function h(m,s){if(typeof s!="function"&&s!==null)throw new TypeError("Super expression must either be null or a function");m.prototype=Object.create(s&&s.prototype,{constructor:{value:m,writable:!0,configurable:!0}}),Object.defineProperty(m,"prototype",{writable:!1}),s&&x(m,s)}function t(m){var s=typeof Map=="function"?new Map:void 0;return t=function(a){if(a===null||!y(a))return a;if(typeof a!="function")throw new TypeError("Super expression must either be null or a function");if(s!==void 0){if(s.has(a))return s.get(a);s.set(a,o)}function o(){return u(a,arguments,p(this).constructor)}return o.prototype=Object.create(a.prototype,{constructor:{value:o,enumerable:!1,writable:!0,configurable:!0}}),x(o,a)},t(m)}function u(m,s,c){if(_())return Reflect.construct.apply(null,arguments);var a=[null];a.push.apply(a,s);var o=new(m.bind.apply(m,a));return c&&x(o,c.prototype),o}function _(){try{var m=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(_=function(){return!!m})()}function y(m){try{return Function.toString.call(m).indexOf("[native code]")!==-1}catch{return typeof m=="function"}}function x(m,s){return x=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(c,a){return c.__proto__=a,c},x(m,s)}function p(m){return p=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(s){return s.__proto__||Object.getPrototypeOf(s)},p(m)}var w=(function(m){function s(c){var a;return g(this,s),a=E(this,s,[`Format functions must be synchronous taking a two arguments: (info, opts)
1
+ import{e as St,g as zo}from"./index-C86qnUPq.js";import{u as Go}from"./util-t-trnxQI.js";import{o as $o}from"./__vite-browser-external-DFygW7-s.js";import{r as Yo}from"./index-DRz5BQNA.js";import{p as Vo}from"./path-C9FudP8b.js";function Ko(r,i){for(var g=0;g<i.length;g++){const E=i[g];if(typeof E!="string"&&!Array.isArray(E)){for(const d in E)if(d!=="default"&&!(d in r)){const l=Object.getOwnPropertyDescriptor(E,d);l&&Object.defineProperty(r,d,l.get?l:{enumerable:!0,get:()=>E[d]})}}}return Object.freeze(Object.defineProperty(r,Symbol.toStringTag,{value:"Module"}))}var Pt={},ze={},Tt,rn;function ye(){if(rn)return Tt;rn=1;function r(m){"@babel/helpers - typeof";return r=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(s){return typeof s}:function(s){return s&&typeof Symbol=="function"&&s.constructor===Symbol&&s!==Symbol.prototype?"symbol":typeof s},r(m)}function i(m,s,c){return Object.defineProperty(m,"prototype",{writable:!1}),m}function g(m,s){if(!(m instanceof s))throw new TypeError("Cannot call a class as a function")}function E(m,s,c){return s=p(s),d(m,_()?Reflect.construct(s,c||[],p(m).constructor):s.apply(m,c))}function d(m,s){if(s&&(r(s)=="object"||typeof s=="function"))return s;if(s!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return l(m)}function l(m){if(m===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return m}function h(m,s){if(typeof s!="function"&&s!==null)throw new TypeError("Super expression must either be null or a function");m.prototype=Object.create(s&&s.prototype,{constructor:{value:m,writable:!0,configurable:!0}}),Object.defineProperty(m,"prototype",{writable:!1}),s&&x(m,s)}function t(m){var s=typeof Map=="function"?new Map:void 0;return t=function(a){if(a===null||!y(a))return a;if(typeof a!="function")throw new TypeError("Super expression must either be null or a function");if(s!==void 0){if(s.has(a))return s.get(a);s.set(a,o)}function o(){return u(a,arguments,p(this).constructor)}return o.prototype=Object.create(a.prototype,{constructor:{value:o,enumerable:!1,writable:!0,configurable:!0}}),x(o,a)},t(m)}function u(m,s,c){if(_())return Reflect.construct.apply(null,arguments);var a=[null];a.push.apply(a,s);var o=new(m.bind.apply(m,a));return c&&x(o,c.prototype),o}function _(){try{var m=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(_=function(){return!!m})()}function y(m){try{return Function.toString.call(m).indexOf("[native code]")!==-1}catch{return typeof m=="function"}}function x(m,s){return x=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(c,a){return c.__proto__=a,c},x(m,s)}function p(m){return p=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(s){return s.__proto__||Object.getPrototypeOf(s)},p(m)}var w=(function(m){function s(c){var a;return g(this,s),a=E(this,s,[`Format functions must be synchronous taking a two arguments: (info, opts)
2
2
  Found: `.concat(c.toString().split(`
3
3
  `)[0],`
4
4
  `)]),Error.captureStackTrace(a,s),a}return h(s,m),i(s)})(t(Error));return Tt=function(m){if(m.length>2)throw new w(m);function s(){var a=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};this.options=a}s.prototype.transform=m;function c(a){return new s(a)}return c.Format=s,c},Tt}var Be={exports:{}},jt={exports:{}},Lt={exports:{}};const _e=St(Go);var Mt={exports:{}},nn;function Jo(){return nn||(nn=1,(function(r){var i={};r.exports=i;var g={reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],inverse:[7,27],hidden:[8,28],strikethrough:[9,29],black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],gray:[90,39],grey:[90,39],brightRed:[91,39],brightGreen:[92,39],brightYellow:[93,39],brightBlue:[94,39],brightMagenta:[95,39],brightCyan:[96,39],brightWhite:[97,39],bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgGray:[100,49],bgGrey:[100,49],bgBrightRed:[101,49],bgBrightGreen:[102,49],bgBrightYellow:[103,49],bgBrightBlue:[104,49],bgBrightMagenta:[105,49],bgBrightCyan:[106,49],bgBrightWhite:[107,49],blackBG:[40,49],redBG:[41,49],greenBG:[42,49],yellowBG:[43,49],blueBG:[44,49],magentaBG:[45,49],cyanBG:[46,49],whiteBG:[47,49]};Object.keys(g).forEach(function(E){var d=g[E],l=i[E]=[];l.open="\x1B["+d[0]+"m",l.close="\x1B["+d[1]+"m"})})(Mt)),Mt.exports}const be=St($o);var At,on;function Zo(){return on||(on=1,At=function(r,i){i=i||process.argv||[];var g=i.indexOf("--"),E=/^-{1,2}/.test(r)?"":"--",d=i.indexOf(E+r);return d!==-1&&(g===-1?!0:d<g)}),At}var Ct,an;function Qo(){if(an)return Ct;an=1;var r={},i=Zo(),g=r,E=void 0;i("no-color")||i("no-colors")||i("color=false")?E=!1:(i("color")||i("colors")||i("color=true")||i("color=always"))&&(E=!0),"FORCE_COLOR"in g&&(E=g.FORCE_COLOR.length===0||parseInt(g.FORCE_COLOR,10)!==0);function d(t){return t===0?!1:{level:t,hasBasic:!0,has256:t>=2,has16m:t>=3}}function l(t){if(E===!1)return 0;if(i("color=16m")||i("color=full")||i("color=truecolor"))return 3;if(i("color=256"))return 2;if(t&&!t.isTTY&&E!==!0)return 0;var u=E?1:0;if("CI"in g)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI"].some(function(y){return y in g})||g.CI_NAME==="codeship"?1:u;if("TEAMCITY_VERSION"in g)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(g.TEAMCITY_VERSION)?1:0;if("TERM_PROGRAM"in g){var _=parseInt((g.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(g.TERM_PROGRAM){case"iTerm.app":return _>=3?3:2;case"Hyper":return 3;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(g.TERM)?2:/^screen|^xterm|^vt100|^rxvt|color|ansi|cygwin|linux/i.test(g.TERM)||"COLORTERM"in g?1:(g.TERM==="dumb",u)}function h(t){var u=l(t);return d(u)}return Ct={supportsColor:h,stdout:h(process.stdout),stderr:h(process.stderr)},Ct}var It={exports:{}},un;function Xo(){return un||(un=1,(function(r){r.exports=function(g,E){var d="";g=g||"Run the trap, drop the bass",g=g.split("");var l={a:["@","Ą","Ⱥ","Ʌ","Δ","Λ","Д"],b:["ß","Ɓ","Ƀ","ɮ","β","฿"],c:["©","Ȼ","Ͼ"],d:["Ð","Ɗ","Ԁ","ԁ","Ԃ","ԃ"],e:["Ë","ĕ","Ǝ","ɘ","Σ","ξ","Ҽ","੬"],f:["Ӻ"],g:["ɢ"],h:["Ħ","ƕ","Ң","Һ","Ӈ","Ԋ"],i:["༏"],j:["Ĵ"],k:["ĸ","Ҡ","Ӄ","Ԟ"],l:["Ĺ"],m:["ʍ","Ӎ","ӎ","Ԡ","ԡ","൩"],n:["Ñ","ŋ","Ɲ","Ͷ","Π","Ҋ"],o:["Ø","õ","ø","Ǿ","ʘ","Ѻ","ם","۝","๏"],p:["Ƿ","Ҏ"],q:["্"],r:["®","Ʀ","Ȑ","Ɍ","ʀ","Я"],s:["§","Ϟ","ϟ","Ϩ"],t:["Ł","Ŧ","ͳ"],u:["Ʊ","Ս"],v:["ט"],w:["Ш","Ѡ","Ѽ","൰"],x:["Ҳ","Ӿ","Ӽ","ӽ"],y:["¥","Ұ","Ӌ"],z:["Ƶ","ɀ"]};return g.forEach(function(h){h=h.toLowerCase();var t=l[h]||[" "],u=Math.floor(Math.random()*t.length);typeof l[h]<"u"?d+=l[h][u]:d+=h}),d}})(It)),It.exports}var qt={exports:{}},sn;function ea(){return sn||(sn=1,(function(r){r.exports=function(g,E){g=g||" he is here ";var d={up:["̍","̎","̄","̅","̿","̑","̆","̐","͒","͗","͑","̇","̈","̊","͂","̓","̈","͊","͋","͌","̃","̂","̌","͐","̀","́","̋","̏","̒","̓","̔","̽","̉","ͣ","ͤ","ͥ","ͦ","ͧ","ͨ","ͩ","ͪ","ͫ","ͬ","ͭ","ͮ","ͯ","̾","͛","͆","̚"],down:["̖","̗","̘","̙","̜","̝","̞","̟","̠","̤","̥","̦","̩","̪","̫","̬","̭","̮","̯","̰","̱","̲","̳","̹","̺","̻","̼","ͅ","͇","͈","͉","͍","͎","͓","͔","͕","͖","͙","͚","̣"],mid:["̕","̛","̀","́","͘","̡","̢","̧","̨","̴","̵","̶","͜","͝","͞","͟","͠","͢","̸","̷","͡"," ҉"]},l=[].concat(d.up,d.down,d.mid);function h(_){var y=Math.floor(Math.random()*_);return y}function t(_){var y=!1;return l.filter(function(x){y=x===_}),y}function u(_,y){var x="",p,w;y=y||{},y.up=typeof y.up<"u"?y.up:!0,y.mid=typeof y.mid<"u"?y.mid:!0,y.down=typeof y.down<"u"?y.down:!0,y.size=typeof y.size<"u"?y.size:"maxi",_=_.split("");for(w in _)if(!t(w)){switch(x=x+_[w],p={up:0,down:0,mid:0},y.size){case"mini":p.up=h(8),p.mid=h(2),p.down=h(8);break;case"maxi":p.up=h(16)+3,p.mid=h(4)+1,p.down=h(64)+3;break;default:p.up=h(8)+1,p.mid=h(6)/2,p.down=h(8)+1;break}var m=["up","mid","down"];for(var s in m)for(var c=m[s],a=0;a<=p[c];a++)y[c]&&(x=x+d[c][h(d[c].length)])}return x}return u(g,E)}})(qt)),qt.exports}var Bt={exports:{}},fn;function ta(){return fn||(fn=1,(function(r){r.exports=function(i){return function(g,E,d){if(g===" ")return g;switch(E%3){case 0:return i.red(g);case 1:return i.white(g);case 2:return i.blue(g)}}}})(Bt)),Bt.exports}var Nt={exports:{}},ln;function ra(){return ln||(ln=1,(function(r){r.exports=function(i){return function(g,E,d){return E%2===0?g:i.inverse(g)}}})(Nt)),Nt.exports}var Ft={exports:{}},cn;function na(){return cn||(cn=1,(function(r){r.exports=function(i){var g=["red","yellow","green","blue","magenta"];return function(E,d,l){return E===" "?E:i[g[d++%g.length]](E)}}})(Ft)),Ft.exports}var Dt={exports:{}},hn;function ia(){return hn||(hn=1,(function(r){r.exports=function(i){var g=["underline","inverse","grey","yellow","red","green","blue","white","cyan","magenta","brightYellow","brightRed","brightGreen","brightBlue","brightWhite","brightCyan","brightMagenta"];return function(E,d,l){return E===" "?E:i[g[Math.round(Math.random()*(g.length-2))]](E)}}})(Dt)),Dt.exports}var pn;function oa(){return pn||(pn=1,(function(r){var i={};r.exports=i,i.themes={};var g=_e,E=i.styles=Jo(),d=Object.defineProperties,l=new RegExp(/[\r\n]+/g);i.supportsColor=Qo().supportsColor,typeof i.enabled>"u"&&(i.enabled=i.supportsColor()!==!1),i.enable=function(){i.enabled=!0},i.disable=function(){i.enabled=!1},i.stripColors=i.strip=function(s){return(""+s).replace(/\x1B\[\d+m/g,"")},i.stylize=function(c,a){if(!i.enabled)return c+"";var o=E[a];return!o&&a in i?i[a](c):o.open+c+o.close};var h=/[|\\{}()[\]^$+*?.]/g,t=function(s){if(typeof s!="string")throw new TypeError("Expected a string");return s.replace(h,"\\$&")};function u(s){var c=function a(){return x.apply(a,arguments)};return c._styles=s,c.__proto__=y,c}var _=(function(){var s={};return E.grey=E.gray,Object.keys(E).forEach(function(c){E[c].closeRe=new RegExp(t(E[c].close),"g"),s[c]={get:function(){return u(this._styles.concat(c))}}}),s})(),y=d(function(){},_);function x(){var s=Array.prototype.slice.call(arguments),c=s.map(function(S){return S!=null&&S.constructor===String?S:g.inspect(S)}).join(" ");if(!i.enabled||!c)return c;for(var a=c.indexOf(`
@@ -27,9 +27,9 @@
27
27
  rel="stylesheet"
28
28
  />
29
29
  <title>Inspector | mcp-use</title>
30
- <script type="module" crossorigin src="/inspector/assets/index-DZxMwvFi.js"></script>
31
- <link rel="stylesheet" crossorigin href="/inspector/assets/index-CHNXgq6o.css">
32
- <script>window.__INSPECTOR_VERSION__ = "0.9.2";</script>
30
+ <script type="module" crossorigin src="/inspector/assets/index-C86qnUPq.js"></script>
31
+ <link rel="stylesheet" crossorigin href="/inspector/assets/index-BlKiZ9Yy.css">
32
+ <script>window.__INSPECTOR_VERSION__ = "0.10.0";</script>
33
33
  </head>
34
34
  <body>
35
35
  <script>
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@mcp-use/inspector",
3
3
  "type": "module",
4
- "version": "0.9.2",
4
+ "version": "0.10.0",
5
5
  "description": "MCP Inspector - A tool for inspecting and debugging MCP servers",
6
6
  "author": "",
7
7
  "license": "MIT",
@@ -83,7 +83,7 @@
83
83
  "sonner": "^2.0.7",
84
84
  "tailwind-merge": "^3.4.0",
85
85
  "vite-express": "^0.21.1",
86
- "mcp-use": "1.7.2"
86
+ "mcp-use": "1.8.0"
87
87
  },
88
88
  "publishConfig": {
89
89
  "access": "public"