@mcp-use/inspector 0.5.1 → 0.5.2-canary.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{B as $n,O as bt,l as jn,p as nn,f as xt,H as St,j as Bn,k as Ln,c as A,b as kt,m as Un,n as qn,h as Wn,g as Fn,t as be,i as Mt,C as Dn,R as Tt,o as Hn}from"./index-CeVhU8eb.js";import"./chunk-VL2OQCWN-DBinT58-.js";import"./index-CNwZaJQ9.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{B as $n,O as bt,b as jn,a as Bn,i as Ln,R as xt}from"./index-XJN6bkWW.js";import{k as Un,p as nn,g as St,H as kt,h as qn,j as Wn,b as A,A as Mt,l as Fn,t as be,i as Tt,e as Dn,R as Hn}from"./index-W-7_hJeO.js";import"./chunk-VL2OQCWN-D_jxyPOp.js";import"./index-CUf6Dwjh.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"})}},hr=class extends nr{};export{hr 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"})}},dr=class extends nr{};export{dr as ChatAnthropic,nr as ChatAnthropicMessages};
@@ -1,2 +1,2 @@
1
- import{i as ne,t as fe,a as he,b as pe,C as ge,c as me,d as Ce,e as ye,f as oe,g as se,h as ie,j as _e,k as Ee,p as A,B as ve,l as we,O as Te,m as Ie,n as Oe,J as Re,R as D,o as Se}from"./index-CeVhU8eb.js";import{v as ae}from"./index-CNwZaJQ9.js";import"./embeddings-P__c62U6.js";import"./chunk-VL2OQCWN-DBinT58-.js";import"./index-DRz5BQNA.js";function _(e){if(typeof e=="object"&&e!==null){const n={...e};"additionalProperties"in n&&delete n.additionalProperties,"$schema"in n&&delete n.$schema,"strict"in n&&delete n.strict;for(const t in n)t in n&&(Array.isArray(n[t])?n[t]=n[t].map(_):typeof n[t]=="object"&&n[t]!==null&&(n[t]=_(n[t])));return n}return e}function N(e){const n=_(ne(e)?fe(e):e),{$schema:t,...o}=n;return o}function Ae(e){const n=_(e),{$schema:t,...o}=n;return o}function Ne(e){const n=e._getType();return Ce.isInstance(e)?e.role:n==="tool"?n:e.name??n}function be(e){switch(e){case"supervisor":case"ai":case"model":return"model";case"system":return"system";case"human":return"user";case"tool":case"function":return"function";default:throw new Error(`Unknown / unsupported author: ${e}`)}}function Me(e){if("mimeType"in e&&"data"in e)return{inlineData:{mimeType:e.mimeType,data:e.data}};if("mimeType"in e&&"fileUri"in e)return{fileData:{mimeType:e.mimeType,fileUri:e.fileUri}};throw new Error("Invalid media content")}function xe(e,n){return n.map(t=>oe(t)?t.tool_calls??[]:[]).flat().find(t=>t.id===e.tool_call_id)?.name}function De(e){return{providerName:"Google Gemini",fromStandardTextBlock(t){return{text:t.text}},fromStandardImageBlock(t){if(!e)throw new Error("This model does not support images");if(t.source_type==="url"){const o=A({dataUrl:t.url});return o?{inlineData:{mimeType:o.mime_type,data:o.data}}:{fileData:{mimeType:t.mime_type??"",fileUri:t.url}}}if(t.source_type==="base64")return{inlineData:{mimeType:t.mime_type??"",data:t.data}};throw new Error(`Unsupported source type: ${t.source_type}`)},fromStandardAudioBlock(t){if(!e)throw new Error("This model does not support audio");if(t.source_type==="url"){const o=A({dataUrl:t.url});return o?{inlineData:{mimeType:o.mime_type,data:o.data}}:{fileData:{mimeType:t.mime_type??"",fileUri:t.url}}}if(t.source_type==="base64")return{inlineData:{mimeType:t.mime_type??"",data:t.data}};throw new Error(`Unsupported source type: ${t.source_type}`)},fromStandardFileBlock(t){if(!e)throw new Error("This model does not support files");if(t.source_type==="text")return{text:t.text};if(t.source_type==="url"){const o=A({dataUrl:t.url});return o?{inlineData:{mimeType:o.mime_type,data:o.data}}:{fileData:{mimeType:t.mime_type??"",fileUri:t.url}}}if(t.source_type==="base64")return{inlineData:{mimeType:t.mime_type??"",data:t.data}};throw new Error(`Unsupported source type: ${t.source_type}`)}}}function G(e,n){if(_e(e))return Ee(e,De(n));if(e.type==="text")return{text:e.text};if(e.type==="executableCode")return{executableCode:e.executableCode};if(e.type==="codeExecutionResult")return{codeExecutionResult:e.codeExecutionResult};if(e.type==="image_url"){if(!n)throw new Error("This model does not support images");let t;if(typeof e.image_url=="string")t=e.image_url;else if(typeof e.image_url=="object"&&"url"in e.image_url)t=e.image_url.url;else throw new Error("Please provide image as base64 encoded data URL");const[o,s]=t.split(",");if(!o.startsWith("data:"))throw new Error("Please provide image as base64 encoded data URL");const[i,a]=o.replace(/^data:/,"").split(";");if(a!=="base64")throw new Error("Please provide image as base64 encoded data URL");return{inlineData:{data:s,mimeType:i}}}else{if(e.type==="media")return Me(e);if(e.type==="tool_use")return{functionCall:{name:e.name,args:e.input}};if(e.type?.includes("/")&&e.type.split("/").length===2&&"data"in e&&typeof e.data=="string")return{inlineData:{mimeType:e.type,data:e.data}};if("functionCall"in e)return;throw"type"in e?new Error(`Unknown content type ${e.type}`):new Error(`Unknown content ${JSON.stringify(e)}`)}}function Ge(e,n,t){if(ye(e)){const i=e.name??xe(e,t);if(i===void 0)throw new Error(`Google requires a tool name for each tool call response, and we could not infer a called tool name for ToolMessage "${e.id}" from your passed messages. Please populate a "name" field on that ToolMessage explicitly.`);const a=Array.isArray(e.content)?e.content.map(c=>G(c,n)).filter(c=>c!==void 0):e.content;return e.status==="error"?[{functionResponse:{name:i,response:{error:{details:a}}}}]:[{functionResponse:{name:i,response:{result:a}}}]}let o=[];const s=[];return typeof e.content=="string"&&e.content&&s.push({text:e.content}),Array.isArray(e.content)&&s.push(...e.content.map(i=>G(i,n)).filter(i=>i!==void 0)),oe(e)&&e.tool_calls?.length&&(o=e.tool_calls.map(i=>({functionCall:{name:i.name,args:i.args}}))),[...s,...o]}function k(e,n,t=!1){return e.reduce((o,s,i)=>{if(!he(s))throw new Error("Unsupported message input");const a=Ne(s);if(a==="system"&&i!==0)throw new Error("System message should be the first one");const c=be(a),u=o.content[o.content.length];if(!o.mergeWithPreviousContent&&u&&u.role===c)throw new Error("Google Generative AI requires alternate messages between authors");const r=Ge(s,n,e.slice(0,i));if(o.mergeWithPreviousContent){const d=o.content[o.content.length-1];if(!d)throw new Error("There was a problem parsing your system message. Please try a prompt without one.");return d.parts.push(...r),{mergeWithPreviousContent:!1,content:o.content}}let p=c;(p==="function"||p==="system"&&!t)&&(p="user");const f={role:p,parts:r};return{mergeWithPreviousContent:a==="system"&&!t,content:[...o.content,f]}},{content:[],mergeWithPreviousContent:!1}).content}function ke(e,n){if(!e.candidates||e.candidates.length===0||!e.candidates[0])return{generations:[],llmOutput:{filters:e.promptFeedback}};const t=e.functionCalls(),[o]=e.candidates,{content:s,...i}=o;let a;Array.isArray(s?.parts)&&s.parts.length===1&&s.parts[0].text?a=s.parts[0].text:Array.isArray(s?.parts)&&s.parts.length>0?a=s.parts.map(r=>"text"in r?{type:"text",text:r.text}:"inlineData"in r?{type:"inlineData",inlineData:r.inlineData}:"functionCall"in r?{type:"functionCall",functionCall:r.functionCall}:"functionResponse"in r?{type:"functionResponse",functionResponse:r.functionResponse}:"fileData"in r?{type:"fileData",fileData:r.fileData}:"executableCode"in r?{type:"executableCode",executableCode:r.executableCode}:"codeExecutionResult"in r?{type:"codeExecutionResult",codeExecutionResult:r.codeExecutionResult}:r):a=[];let c="";return typeof a=="string"?c=a:Array.isArray(a)&&a.length>0&&(c=a.find(p=>"text"in p)?.text??c),{generations:[{text:c,message:new pe({content:a??"",tool_calls:t?.map(r=>({...r,type:"tool_call",id:"id"in r&&typeof r.id=="string"?r.id:ae()})),additional_kwargs:{...i},usage_metadata:n?.usageMetadata}),generationInfo:i}],llmOutput:{tokenUsage:{promptTokens:n?.usageMetadata?.input_tokens,completionTokens:n?.usageMetadata?.output_tokens,totalTokens:n?.usageMetadata?.total_tokens}}}}function Ue(e,n){if(!e.candidates||e.candidates.length===0)return null;const t=e.functionCalls(),[o]=e.candidates,{content:s,...i}=o;let a;Array.isArray(s?.parts)&&s.parts.every(r=>"text"in r)?a=s.parts.map(r=>r.text).join(""):Array.isArray(s?.parts)?a=s.parts.map(r=>"text"in r?{type:"text",text:r.text}:"inlineData"in r?{type:"inlineData",inlineData:r.inlineData}:"functionCall"in r?{type:"functionCall",functionCall:r.functionCall}:"functionResponse"in r?{type:"functionResponse",functionResponse:r.functionResponse}:"fileData"in r?{type:"fileData",fileData:r.fileData}:"executableCode"in r?{type:"executableCode",executableCode:r.executableCode}:"codeExecutionResult"in r?{type:"codeExecutionResult",codeExecutionResult:r.codeExecutionResult}:r):a=[];let c="";a&&typeof a=="string"?c=a:Array.isArray(a)&&(c=a.find(p=>"text"in p)?.text??"");const u=[];return t&&u.push(...t.map(r=>({...r,args:JSON.stringify(r.args),index:n.index,type:"tool_call_chunk",id:"id"in r&&typeof r.id=="string"?r.id:ae()}))),new ge({text:c,message:new me({content:a||"",name:s?s.role:void 0,tool_call_chunks:u,additional_kwargs:{},response_metadata:{model_provider:"google-genai"},usage_metadata:n.usageMetadata}),generationInfo:i})}function Le(e){return e.every(n=>"functionDeclarations"in n&&Array.isArray(n.functionDeclarations))?e:[{functionDeclarations:e.map(n=>{if(se(n)){const t=N(n.schema);return t.type==="object"&&"properties"in t&&Object.keys(t.properties).length===0?{name:n.name,description:n.description}:{name:n.name,description:n.description,parameters:t}}return ie(n)?{name:n.function.name,description:n.function.description??"A function available to call.",parameters:Ae(n.function.parameters)}:n})}]}var U=class extends ve{static lc_name(){return"GoogleGenerativeAIToolsOutputParser"}lc_namespace=["langchain","google_genai","output_parsers"];returnId=!1;keyName;returnSingle=!1;zodSchema;constructor(e){super(e),this.keyName=e.keyName,this.returnSingle=e.returnSingle??this.returnSingle,this.zodSchema=e.zodSchema}async _validateResult(e){if(this.zodSchema===void 0)return e;const n=await we(this.zodSchema,e);if(n.success)return n.data;throw new Te(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(n.error.issues)}`,JSON.stringify(e,null,2))}async parseResult(e){const n=e.flatMap(s=>{const{message:i}=s;return!("tool_calls"in i)||!Array.isArray(i.tool_calls)?[]:i.tool_calls});if(n[0]===void 0)throw new Error("No parseable tool calls provided to GoogleGenerativeAIToolsOutputParser.");const[t]=n;return await this._validateResult(t.args)}},L;(function(e){e.STRING="string",e.NUMBER="number",e.INTEGER="integer",e.BOOLEAN="boolean",e.ARRAY="array",e.OBJECT="object"})(L||(L={}));var P;(function(e){e.LANGUAGE_UNSPECIFIED="language_unspecified",e.PYTHON="python"})(P||(P={}));var j;(function(e){e.OUTCOME_UNSPECIFIED="outcome_unspecified",e.OUTCOME_OK="outcome_ok",e.OUTCOME_FAILED="outcome_failed",e.OUTCOME_DEADLINE_EXCEEDED="outcome_deadline_exceeded"})(j||(j={}));const F=["user","model","function","system"];var K;(function(e){e.HARM_CATEGORY_UNSPECIFIED="HARM_CATEGORY_UNSPECIFIED",e.HARM_CATEGORY_HATE_SPEECH="HARM_CATEGORY_HATE_SPEECH",e.HARM_CATEGORY_SEXUALLY_EXPLICIT="HARM_CATEGORY_SEXUALLY_EXPLICIT",e.HARM_CATEGORY_HARASSMENT="HARM_CATEGORY_HARASSMENT",e.HARM_CATEGORY_DANGEROUS_CONTENT="HARM_CATEGORY_DANGEROUS_CONTENT",e.HARM_CATEGORY_CIVIC_INTEGRITY="HARM_CATEGORY_CIVIC_INTEGRITY"})(K||(K={}));var $;(function(e){e.HARM_BLOCK_THRESHOLD_UNSPECIFIED="HARM_BLOCK_THRESHOLD_UNSPECIFIED",e.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",e.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",e.BLOCK_ONLY_HIGH="BLOCK_ONLY_HIGH",e.BLOCK_NONE="BLOCK_NONE"})($||($={}));var H;(function(e){e.HARM_PROBABILITY_UNSPECIFIED="HARM_PROBABILITY_UNSPECIFIED",e.NEGLIGIBLE="NEGLIGIBLE",e.LOW="LOW",e.MEDIUM="MEDIUM",e.HIGH="HIGH"})(H||(H={}));var B;(function(e){e.BLOCKED_REASON_UNSPECIFIED="BLOCKED_REASON_UNSPECIFIED",e.SAFETY="SAFETY",e.OTHER="OTHER"})(B||(B={}));var T;(function(e){e.FINISH_REASON_UNSPECIFIED="FINISH_REASON_UNSPECIFIED",e.STOP="STOP",e.MAX_TOKENS="MAX_TOKENS",e.SAFETY="SAFETY",e.RECITATION="RECITATION",e.LANGUAGE="LANGUAGE",e.BLOCKLIST="BLOCKLIST",e.PROHIBITED_CONTENT="PROHIBITED_CONTENT",e.SPII="SPII",e.MALFORMED_FUNCTION_CALL="MALFORMED_FUNCTION_CALL",e.OTHER="OTHER"})(T||(T={}));var Y;(function(e){e.TASK_TYPE_UNSPECIFIED="TASK_TYPE_UNSPECIFIED",e.RETRIEVAL_QUERY="RETRIEVAL_QUERY",e.RETRIEVAL_DOCUMENT="RETRIEVAL_DOCUMENT",e.SEMANTIC_SIMILARITY="SEMANTIC_SIMILARITY",e.CLASSIFICATION="CLASSIFICATION",e.CLUSTERING="CLUSTERING"})(Y||(Y={}));var w;(function(e){e.MODE_UNSPECIFIED="MODE_UNSPECIFIED",e.AUTO="AUTO",e.ANY="ANY",e.NONE="NONE"})(w||(w={}));var q;(function(e){e.MODE_UNSPECIFIED="MODE_UNSPECIFIED",e.MODE_DYNAMIC="MODE_DYNAMIC"})(q||(q={}));class g extends Error{constructor(n){super(`[GoogleGenerativeAI Error]: ${n}`)}}class v extends g{constructor(n,t){super(n),this.response=t}}class re extends g{constructor(n,t,o,s){super(n),this.status=t,this.statusText=o,this.errorDetails=s}}class y extends g{}class ce extends g{}const Pe="https://generativelanguage.googleapis.com",je="v1beta",Fe="0.24.1",Ke="genai-js";var E;(function(e){e.GENERATE_CONTENT="generateContent",e.STREAM_GENERATE_CONTENT="streamGenerateContent",e.COUNT_TOKENS="countTokens",e.EMBED_CONTENT="embedContent",e.BATCH_EMBED_CONTENTS="batchEmbedContents"})(E||(E={}));class $e{constructor(n,t,o,s,i){this.model=n,this.task=t,this.apiKey=o,this.stream=s,this.requestOptions=i}toString(){var n,t;const o=((n=this.requestOptions)===null||n===void 0?void 0:n.apiVersion)||je;let i=`${((t=this.requestOptions)===null||t===void 0?void 0:t.baseUrl)||Pe}/${o}/${this.model}:${this.task}`;return this.stream&&(i+="?alt=sse"),i}}function He(e){const n=[];return e?.apiClient&&n.push(e.apiClient),n.push(`${Ke}/${Fe}`),n.join(" ")}async function Be(e){var n;const t=new Headers;t.append("Content-Type","application/json"),t.append("x-goog-api-client",He(e.requestOptions)),t.append("x-goog-api-key",e.apiKey);let o=(n=e.requestOptions)===null||n===void 0?void 0:n.customHeaders;if(o){if(!(o instanceof Headers))try{o=new Headers(o)}catch(s){throw new y(`unable to convert customHeaders value ${JSON.stringify(o)} to Headers: ${s.message}`)}for(const[s,i]of o.entries()){if(s==="x-goog-api-key")throw new y(`Cannot set reserved header name ${s}`);if(s==="x-goog-api-client")throw new y(`Header name ${s} can only be set using the apiClient field`);t.append(s,i)}}return t}async function Ye(e,n,t,o,s,i){const a=new $e(e,n,t,o,i);return{url:a.toString(),fetchOptions:Object.assign(Object.assign({},Je(i)),{method:"POST",headers:await Be(a),body:s})}}async function R(e,n,t,o,s,i={},a=fetch){const{url:c,fetchOptions:u}=await Ye(e,n,t,o,s,i);return qe(c,u,a)}async function qe(e,n,t=fetch){let o;try{o=await t(e,n)}catch(s){We(s,e)}return o.ok||await Ve(o,e),o}function We(e,n){let t=e;throw t.name==="AbortError"?(t=new ce(`Request aborted when fetching ${n.toString()}: ${e.message}`),t.stack=e.stack):e instanceof re||e instanceof y||(t=new g(`Error fetching from ${n.toString()}: ${e.message}`),t.stack=e.stack),t}async function Ve(e,n){let t="",o;try{const s=await e.json();t=s.error.message,s.error.details&&(t+=` ${JSON.stringify(s.error.details)}`,o=s.error.details)}catch{}throw new re(`Error fetching from ${n.toString()}: [${e.status} ${e.statusText}] ${t}`,e.status,e.statusText,o)}function Je(e){const n={};if(e?.signal!==void 0||e?.timeout>=0){const t=new AbortController;e?.timeout>=0&&setTimeout(()=>t.abort(),e.timeout),e?.signal&&e.signal.addEventListener("abort",()=>{t.abort()}),n.signal=t.signal}return n}function b(e){return e.text=()=>{if(e.candidates&&e.candidates.length>0){if(e.candidates.length>1&&console.warn(`This response had ${e.candidates.length} candidates. Returning text from the first candidate only. Access response.candidates directly to use the other candidates.`),S(e.candidates[0]))throw new v(`${C(e)}`,e);return ze(e)}else if(e.promptFeedback)throw new v(`Text not available. ${C(e)}`,e);return""},e.functionCall=()=>{if(e.candidates&&e.candidates.length>0){if(e.candidates.length>1&&console.warn(`This response had ${e.candidates.length} candidates. Returning function calls from the first candidate only. Access response.candidates directly to use the other candidates.`),S(e.candidates[0]))throw new v(`${C(e)}`,e);return console.warn("response.functionCall() is deprecated. Use response.functionCalls() instead."),W(e)[0]}else if(e.promptFeedback)throw new v(`Function call not available. ${C(e)}`,e)},e.functionCalls=()=>{if(e.candidates&&e.candidates.length>0){if(e.candidates.length>1&&console.warn(`This response had ${e.candidates.length} candidates. Returning function calls from the first candidate only. Access response.candidates directly to use the other candidates.`),S(e.candidates[0]))throw new v(`${C(e)}`,e);return W(e)}else if(e.promptFeedback)throw new v(`Function call not available. ${C(e)}`,e)},e}function ze(e){var n,t,o,s;const i=[];if(!((t=(n=e.candidates)===null||n===void 0?void 0:n[0].content)===null||t===void 0)&&t.parts)for(const a of(s=(o=e.candidates)===null||o===void 0?void 0:o[0].content)===null||s===void 0?void 0:s.parts)a.text&&i.push(a.text),a.executableCode&&i.push("\n```"+a.executableCode.language+`
2
- `+a.executableCode.code+"\n```\n"),a.codeExecutionResult&&i.push("\n```\n"+a.codeExecutionResult.output+"\n```\n");return i.length>0?i.join(""):""}function W(e){var n,t,o,s;const i=[];if(!((t=(n=e.candidates)===null||n===void 0?void 0:n[0].content)===null||t===void 0)&&t.parts)for(const a of(s=(o=e.candidates)===null||o===void 0?void 0:o[0].content)===null||s===void 0?void 0:s.parts)a.functionCall&&i.push(a.functionCall);if(i.length>0)return i}const Xe=[T.RECITATION,T.SAFETY,T.LANGUAGE];function S(e){return!!e.finishReason&&Xe.includes(e.finishReason)}function C(e){var n,t,o;let s="";if((!e.candidates||e.candidates.length===0)&&e.promptFeedback)s+="Response was blocked",!((n=e.promptFeedback)===null||n===void 0)&&n.blockReason&&(s+=` due to ${e.promptFeedback.blockReason}`),!((t=e.promptFeedback)===null||t===void 0)&&t.blockReasonMessage&&(s+=`: ${e.promptFeedback.blockReasonMessage}`);else if(!((o=e.candidates)===null||o===void 0)&&o[0]){const i=e.candidates[0];S(i)&&(s+=`Candidate was blocked due to ${i.finishReason}`,i.finishMessage&&(s+=`: ${i.finishMessage}`))}return s}function I(e){return this instanceof I?(this.v=e,this):new I(e)}function Qe(e,n,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var o=t.apply(e,n||[]),s,i=[];return s={},a("next"),a("throw"),a("return"),s[Symbol.asyncIterator]=function(){return this},s;function a(d){o[d]&&(s[d]=function(l){return new Promise(function(h,m){i.push([d,l,h,m])>1||c(d,l)})})}function c(d,l){try{u(o[d](l))}catch(h){f(i[0][3],h)}}function u(d){d.value instanceof I?Promise.resolve(d.value.v).then(r,p):f(i[0][2],d)}function r(d){c("next",d)}function p(d){c("throw",d)}function f(d,l){d(l),i.shift(),i.length&&c(i[0][0],i[0][1])}}const V=/^data\: (.*)(?:\n\n|\r\r|\r\n\r\n)/;function Ze(e){const n=e.body.pipeThrough(new TextDecoderStream("utf8",{fatal:!0})),t=nt(n),[o,s]=t.tee();return{stream:tt(o),response:et(s)}}async function et(e){const n=[],t=e.getReader();for(;;){const{done:o,value:s}=await t.read();if(o)return b(ot(n));n.push(s)}}function tt(e){return Qe(this,arguments,function*(){const t=e.getReader();for(;;){const{value:o,done:s}=yield I(t.read());if(s)break;yield yield I(b(o))}})}function nt(e){const n=e.getReader();return new ReadableStream({start(o){let s="";return i();function i(){return n.read().then(({value:a,done:c})=>{if(c){if(s.trim()){o.error(new g("Failed to parse stream"));return}o.close();return}s+=a;let u=s.match(V),r;for(;u;){try{r=JSON.parse(u[1])}catch{o.error(new g(`Error parsing JSON response: "${u[1]}"`));return}o.enqueue(r),s=s.substring(u[0].length),u=s.match(V)}return i()}).catch(a=>{let c=a;throw c.stack=a.stack,c.name==="AbortError"?c=new ce("Request aborted when reading from the stream"):c=new g("Error reading from the stream"),c})}}})}function ot(e){const n=e[e.length-1],t={promptFeedback:n?.promptFeedback};for(const o of e){if(o.candidates){let s=0;for(const i of o.candidates)if(t.candidates||(t.candidates=[]),t.candidates[s]||(t.candidates[s]={index:s}),t.candidates[s].citationMetadata=i.citationMetadata,t.candidates[s].groundingMetadata=i.groundingMetadata,t.candidates[s].finishReason=i.finishReason,t.candidates[s].finishMessage=i.finishMessage,t.candidates[s].safetyRatings=i.safetyRatings,i.content&&i.content.parts){t.candidates[s].content||(t.candidates[s].content={role:i.content.role||"user",parts:[]});const a={};for(const c of i.content.parts)c.text&&(a.text=c.text),c.functionCall&&(a.functionCall=c.functionCall),c.executableCode&&(a.executableCode=c.executableCode),c.codeExecutionResult&&(a.codeExecutionResult=c.codeExecutionResult),Object.keys(a).length===0&&(a.text=""),t.candidates[s].content.parts.push(a)}s++}o.usageMetadata&&(t.usageMetadata=o.usageMetadata)}return t}async function le(e,n,t,o){const s=await R(n,E.STREAM_GENERATE_CONTENT,e,!0,JSON.stringify(t),o);return Ze(s)}async function ue(e,n,t,o){const i=await(await R(n,E.GENERATE_CONTENT,e,!1,JSON.stringify(t),o)).json();return{response:b(i)}}function de(e){if(e!=null){if(typeof e=="string")return{role:"system",parts:[{text:e}]};if(e.text)return{role:"system",parts:[e]};if(e.parts)return e.role?e:{role:"system",parts:e.parts}}}function O(e){let n=[];if(typeof e=="string")n=[{text:e}];else for(const t of e)typeof t=="string"?n.push({text:t}):n.push(t);return st(n)}function st(e){const n={role:"user",parts:[]},t={role:"function",parts:[]};let o=!1,s=!1;for(const i of e)"functionResponse"in i?(t.parts.push(i),s=!0):(n.parts.push(i),o=!0);if(o&&s)throw new g("Within a single message, FunctionResponse cannot be mixed with other type of part in the request for sending chat message.");if(!o&&!s)throw new g("No content is provided for sending chat message.");return o?n:t}function it(e,n){var t;let o={model:n?.model,generationConfig:n?.generationConfig,safetySettings:n?.safetySettings,tools:n?.tools,toolConfig:n?.toolConfig,systemInstruction:n?.systemInstruction,cachedContent:(t=n?.cachedContent)===null||t===void 0?void 0:t.name,contents:[]};const s=e.generateContentRequest!=null;if(e.contents){if(s)throw new y("CountTokensRequest must have one of contents or generateContentRequest, not both.");o.contents=e.contents}else if(s)o=Object.assign(Object.assign({},o),e.generateContentRequest);else{const i=O(e);o.contents=[i]}return{generateContentRequest:o}}function J(e){let n;return e.contents?n=e:n={contents:[O(e)]},e.systemInstruction&&(n.systemInstruction=de(e.systemInstruction)),n}function at(e){return typeof e=="string"||Array.isArray(e)?{content:O(e)}:e}const z=["text","inlineData","functionCall","functionResponse","executableCode","codeExecutionResult"],rt={user:["text","inlineData"],function:["functionResponse"],model:["text","functionCall","executableCode","codeExecutionResult"],system:["text"]};function ct(e){let n=!1;for(const t of e){const{role:o,parts:s}=t;if(!n&&o!=="user")throw new g(`First content should be with role 'user', got ${o}`);if(!F.includes(o))throw new g(`Each item should include role field. Got ${o} but valid roles are: ${JSON.stringify(F)}`);if(!Array.isArray(s))throw new g("Content should have 'parts' property with an array of Parts");if(s.length===0)throw new g("Each Content should have at least one part");const i={text:0,inlineData:0,functionCall:0,functionResponse:0,fileData:0,executableCode:0,codeExecutionResult:0};for(const c of s)for(const u of z)u in c&&(i[u]+=1);const a=rt[o];for(const c of z)if(!a.includes(c)&&i[c]>0)throw new g(`Content with role '${o}' can't contain '${c}' part`);n=!0}}function X(e){var n;if(e.candidates===void 0||e.candidates.length===0)return!1;const t=(n=e.candidates[0])===null||n===void 0?void 0:n.content;if(t===void 0||t.parts===void 0||t.parts.length===0)return!1;for(const o of t.parts)if(o===void 0||Object.keys(o).length===0||o.text!==void 0&&o.text==="")return!1;return!0}const Q="SILENT_ERROR";class lt{constructor(n,t,o,s={}){this.model=t,this.params=o,this._requestOptions=s,this._history=[],this._sendPromise=Promise.resolve(),this._apiKey=n,o?.history&&(ct(o.history),this._history=o.history)}async getHistory(){return await this._sendPromise,this._history}async sendMessage(n,t={}){var o,s,i,a,c,u;await this._sendPromise;const r=O(n),p={safetySettings:(o=this.params)===null||o===void 0?void 0:o.safetySettings,generationConfig:(s=this.params)===null||s===void 0?void 0:s.generationConfig,tools:(i=this.params)===null||i===void 0?void 0:i.tools,toolConfig:(a=this.params)===null||a===void 0?void 0:a.toolConfig,systemInstruction:(c=this.params)===null||c===void 0?void 0:c.systemInstruction,cachedContent:(u=this.params)===null||u===void 0?void 0:u.cachedContent,contents:[...this._history,r]},f=Object.assign(Object.assign({},this._requestOptions),t);let d;return this._sendPromise=this._sendPromise.then(()=>ue(this._apiKey,this.model,p,f)).then(l=>{var h;if(X(l.response)){this._history.push(r);const m=Object.assign({parts:[],role:"model"},(h=l.response.candidates)===null||h===void 0?void 0:h[0].content);this._history.push(m)}else{const m=C(l.response);m&&console.warn(`sendMessage() was unsuccessful. ${m}. Inspect response object for details.`)}d=l}).catch(l=>{throw this._sendPromise=Promise.resolve(),l}),await this._sendPromise,d}async sendMessageStream(n,t={}){var o,s,i,a,c,u;await this._sendPromise;const r=O(n),p={safetySettings:(o=this.params)===null||o===void 0?void 0:o.safetySettings,generationConfig:(s=this.params)===null||s===void 0?void 0:s.generationConfig,tools:(i=this.params)===null||i===void 0?void 0:i.tools,toolConfig:(a=this.params)===null||a===void 0?void 0:a.toolConfig,systemInstruction:(c=this.params)===null||c===void 0?void 0:c.systemInstruction,cachedContent:(u=this.params)===null||u===void 0?void 0:u.cachedContent,contents:[...this._history,r]},f=Object.assign(Object.assign({},this._requestOptions),t),d=le(this._apiKey,this.model,p,f);return this._sendPromise=this._sendPromise.then(()=>d).catch(l=>{throw new Error(Q)}).then(l=>l.response).then(l=>{if(X(l)){this._history.push(r);const h=Object.assign({},l.candidates[0].content);h.role||(h.role="model"),this._history.push(h)}else{const h=C(l);h&&console.warn(`sendMessageStream() was unsuccessful. ${h}. Inspect response object for details.`)}}).catch(l=>{l.message!==Q&&console.error(l)}),d}}async function ut(e,n,t,o){return(await R(n,E.COUNT_TOKENS,e,!1,JSON.stringify(t),o)).json()}async function dt(e,n,t,o){return(await R(n,E.EMBED_CONTENT,e,!1,JSON.stringify(t),o)).json()}async function ft(e,n,t,o){const s=t.requests.map(a=>Object.assign(Object.assign({},a),{model:n}));return(await R(n,E.BATCH_EMBED_CONTENTS,e,!1,JSON.stringify({requests:s}),o)).json()}class Z{constructor(n,t,o={}){this.apiKey=n,this._requestOptions=o,t.model.includes("/")?this.model=t.model:this.model=`models/${t.model}`,this.generationConfig=t.generationConfig||{},this.safetySettings=t.safetySettings||[],this.tools=t.tools,this.toolConfig=t.toolConfig,this.systemInstruction=de(t.systemInstruction),this.cachedContent=t.cachedContent}async generateContent(n,t={}){var o;const s=J(n),i=Object.assign(Object.assign({},this._requestOptions),t);return ue(this.apiKey,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:(o=this.cachedContent)===null||o===void 0?void 0:o.name},s),i)}async generateContentStream(n,t={}){var o;const s=J(n),i=Object.assign(Object.assign({},this._requestOptions),t);return le(this.apiKey,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:(o=this.cachedContent)===null||o===void 0?void 0:o.name},s),i)}startChat(n){var t;return new lt(this.apiKey,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:(t=this.cachedContent)===null||t===void 0?void 0:t.name},n),this._requestOptions)}async countTokens(n,t={}){const o=it(n,{model:this.model,generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:this.cachedContent}),s=Object.assign(Object.assign({},this._requestOptions),t);return ut(this.apiKey,this.model,o,s)}async embedContent(n,t={}){const o=at(n),s=Object.assign(Object.assign({},this._requestOptions),t);return dt(this.apiKey,this.model,o,s)}async batchEmbedContents(n,t={}){const o=Object.assign(Object.assign({},this._requestOptions),t);return ft(this.apiKey,this.model,n,o)}}class ee{constructor(n){this.apiKey=n}getGenerativeModel(n,t){if(!n.model)throw new g("Must provide a model name. Example: genai.getGenerativeModel({ model: 'my-model-name' })");return new Z(this.apiKey,n,t)}getGenerativeModelFromCachedContent(n,t,o){if(!n.name)throw new y("Cached content must contain a `name` field.");if(!n.model)throw new y("Cached content must contain a `model` field.");const s=["model","systemInstruction"];for(const a of s)if(t?.[a]&&n[a]&&t?.[a]!==n[a]){if(a==="model"){const c=t.model.startsWith("models/")?t.model.replace("models/",""):t.model,u=n.model.startsWith("models/")?n.model.replace("models/",""):n.model;if(c===u)continue}throw new y(`Different value for "${a}" specified in modelParams (${t[a]}) and cachedContent (${n[a]})`)}const i=Object.assign(Object.assign({},t),{model:n.model,tools:n.tools,toolConfig:n.toolConfig,systemInstruction:n.systemInstruction,cachedContent:n});return new Z(this.apiKey,i,o)}}function te(e,n){const t=ht(e),o=gt(t,n);return{tools:t,toolConfig:o}}function ht(e){let n=[];const t=[];return e.forEach(s=>{if(se(s)){const[i]=Le([s]);i.functionDeclarations&&n.push(...i.functionDeclarations)}else if(ie(s)){const{functionDeclarations:i}=pt(s);if(i)n.push(...i);else throw new Error("Failed to convert OpenAI structured tool to GenerativeAI tool")}else t.push(s)}),t.find(s=>"functionDeclarations"in s)?t.map(s=>{if(n?.length>0&&"functionDeclarations"in s){const i={functionDeclarations:[...s.functionDeclarations||[],...n]};return n=[],i}return s}):[...t,...n.length>0?[{functionDeclarations:n}]:[]]}function pt(e){return{functionDeclarations:[{name:e.function.name,description:e.function.description,parameters:_(e.function.parameters)}]}}function gt(e,n){if(!e.length||!n)return;const{toolChoice:t,allowedFunctionNames:o}=n,s={any:w.ANY,auto:w.AUTO,none:w.NONE};if(t&&["any","auto","none"].includes(t))return{functionCallingConfig:{mode:s[t]??"MODE_UNSPECIFIED",allowedFunctionNames:o}};if(typeof t=="string"||o)return{functionCallingConfig:{mode:w.ANY,allowedFunctionNames:[...o??[],...t&&typeof t=="string"?[t]:[]]}}}var vt=class extends Ie{static lc_name(){return"ChatGoogleGenerativeAI"}lc_serializable=!0;get lc_secrets(){return{apiKey:"GOOGLE_API_KEY"}}lc_namespace=["langchain","chat_models","google_genai"];get lc_aliases(){return{apiKey:"google_api_key"}}model;temperature;maxOutputTokens;topP;topK;stopSequences=[];safetySettings;apiKey;streaming=!1;json;streamUsage=!0;convertSystemMessageToHumanContent;client;get _isMultimodalModel(){return this.model.includes("vision")||this.model.startsWith("gemini-1.5")||this.model.startsWith("gemini-2")||this.model.startsWith("gemma-3-")&&!this.model.startsWith("gemma-3-1b")}constructor(e){if(super(e),this.model=e.model.replace(/^models\//,""),this.maxOutputTokens=e.maxOutputTokens??this.maxOutputTokens,this.maxOutputTokens&&this.maxOutputTokens<0)throw new Error("`maxOutputTokens` must be a positive integer");if(this.temperature=e.temperature??this.temperature,this.temperature&&(this.temperature<0||this.temperature>2))throw new Error("`temperature` must be in the range of [0.0,2.0]");if(this.topP=e.topP??this.topP,this.topP&&this.topP<0)throw new Error("`topP` must be a positive integer");if(this.topP&&this.topP>1)throw new Error("`topP` must be below 1.");if(this.topK=e.topK??this.topK,this.topK&&this.topK<0)throw new Error("`topK` must be a positive integer");if(this.stopSequences=e.stopSequences??this.stopSequences,this.apiKey=e.apiKey??Oe("GOOGLE_API_KEY"),!this.apiKey)throw new Error("Please set an API key for Google GenerativeAI in the environment variable GOOGLE_API_KEY or in the `apiKey` field of the ChatGoogleGenerativeAI constructor");if(this.safetySettings=e.safetySettings??this.safetySettings,this.safetySettings&&this.safetySettings.length>0&&new Set(this.safetySettings.map(t=>t.category)).size!==this.safetySettings.length)throw new Error("The categories in `safetySettings` array must be unique");this.streaming=e.streaming??this.streaming,this.json=e.json,this.client=new ee(this.apiKey).getGenerativeModel({model:this.model,safetySettings:this.safetySettings,generationConfig:{stopSequences:this.stopSequences,maxOutputTokens:this.maxOutputTokens,temperature:this.temperature,topP:this.topP,topK:this.topK,...this.json?{responseMimeType:"application/json"}:{}}},{apiVersion:e.apiVersion,baseUrl:e.baseUrl}),this.streamUsage=e.streamUsage??this.streamUsage}useCachedContent(e,n,t){this.apiKey&&(this.client=new ee(this.apiKey).getGenerativeModelFromCachedContent(e,n,t))}get useSystemInstruction(){return typeof this.convertSystemMessageToHumanContent=="boolean"?!this.convertSystemMessageToHumanContent:this.computeUseSystemInstruction}get computeUseSystemInstruction(){return this.model==="gemini-1.0-pro-001"||this.model.startsWith("gemini-pro-vision")||this.model.startsWith("gemini-1.0-pro-vision")?!1:this.model!=="gemini-pro"}getLsParams(e){return{ls_provider:"google_genai",ls_model_name:this.model,ls_model_type:"chat",ls_temperature:this.client.generationConfig.temperature,ls_max_tokens:this.client.generationConfig.maxOutputTokens,ls_stop:e.stop}}_combineLLMOutput(){return[]}_llmType(){return"googlegenerativeai"}bindTools(e,n){return this.withConfig({tools:te(e)?.tools,...n})}invocationParams(e){const n=e?.tools?.length?te(e.tools,{toolChoice:e.tool_choice,allowedFunctionNames:e.allowedFunctionNames}):void 0;return e?.responseSchema?(this.client.generationConfig.responseSchema=e.responseSchema,this.client.generationConfig.responseMimeType="application/json"):(this.client.generationConfig.responseSchema=void 0,this.client.generationConfig.responseMimeType=this.json?"application/json":void 0),{...n?.tools?{tools:n.tools}:{},...n?.toolConfig?{toolConfig:n.toolConfig}:{}}}async _generate(e,n,t){const o=k(e,this._isMultimodalModel,this.useSystemInstruction);let s=o;if(o[0].role==="system"){const[r]=o;this.client.systemInstruction=r,s=o.slice(1)}const i=this.invocationParams(n);if(this.streaming){const r={},p=this._streamResponseChunks(e,n,t),f={};for await(const l of p){const h=l.generationInfo?.completion??0;f[h]===void 0?f[h]=l:f[h]=f[h].concat(l)}return{generations:Object.entries(f).sort(([l],[h])=>parseInt(l,10)-parseInt(h,10)).map(([l,h])=>h),llmOutput:{estimatedTokenUsage:r}}}const a=await this.completionWithRetry({...i,contents:s});let c;if("usageMetadata"in a.response){const r=a.response.usageMetadata;c={input_tokens:r.promptTokenCount??0,output_tokens:r.candidatesTokenCount??0,total_tokens:r.totalTokenCount??0}}const u=ke(a.response,{usageMetadata:c});return u.generations?.length>0&&await t?.handleLLMNewToken(u.generations[0]?.text??""),u}async*_streamResponseChunks(e,n,t){const o=k(e,this._isMultimodalModel,this.useSystemInstruction);let s=o;if(o[0].role==="system"){const[l]=o;this.client.systemInstruction=l,s=o.slice(1)}const a={...this.invocationParams(n),contents:s},c=await this.caller.callWithOptions({signal:n?.signal},async()=>{const{stream:l}=await this.client.generateContentStream(a);return l});let u,r=0,p=0,f=0,d=0;for await(const l of c){if("usageMetadata"in l&&l.usageMetadata!==void 0&&this.streamUsage!==!1&&n.streamUsage!==!1){u={input_tokens:l.usageMetadata.promptTokenCount??0,output_tokens:l.usageMetadata.candidatesTokenCount??0,total_tokens:l.usageMetadata.totalTokenCount??0};const m=l.usageMetadata.promptTokenCount??0;u.input_tokens=Math.max(0,m-r),r=m;const M=l.usageMetadata.candidatesTokenCount??0;u.output_tokens=Math.max(0,M-p),p=M;const x=l.usageMetadata.totalTokenCount??0;u.total_tokens=Math.max(0,x-f),f=x}const h=Ue(l,{usageMetadata:u,index:d});d+=1,h&&(yield h,await t?.handleLLMNewToken(h.text??""))}}async completionWithRetry(e,n){return this.caller.callWithOptions({signal:n?.signal},async()=>{try{return await this.client.generateContent(e)}catch(t){throw t.message?.includes("400 Bad Request")&&(t.status=400),t}})}withStructuredOutput(e,n){const t=e,o=n?.name,s=n?.method,i=n?.includeRaw;if(s==="jsonMode")throw new Error('ChatGoogleGenerativeAI only supports "jsonSchema" or "functionCalling" as a method.');let a,c;if(s==="functionCalling"){let f=o??"extract",d;if(ne(t)){const l=N(t);d=[{functionDeclarations:[{name:f,description:l.description??"A function available to call.",parameters:l}]}],c=new U({returnSingle:!0,keyName:f,zodSchema:t})}else{let l;typeof t.name=="string"&&typeof t.parameters=="object"&&t.parameters!=null?(l=t,l.parameters=_(t.parameters),f=t.name):l={name:f,description:t.description??"",parameters:_(t)},d=[{functionDeclarations:[l]}],c=new U({returnSingle:!0,keyName:f})}a=this.bindTools(d).withConfig({allowedFunctionNames:[f]})}else{const f=N(t);a=this.withConfig({responseSchema:f}),c=new Re}if(!i)return a.pipe(c).withConfig({runName:"ChatGoogleGenerativeAIStructuredOutput"});const u=D.assign({parsed:(f,d)=>c.invoke(f.raw,d)}),r=D.assign({parsed:()=>null}),p=u.withFallbacks({fallbacks:[r]});return Se.from([{raw:a},p]).withConfig({runName:"StructuredOutputRunnable"})}};export{vt as ChatGoogleGenerativeAI};
1
+ import{i as ne,a as oe,B as fe,O as he,b as pe,J as ge,R as D}from"./index-XJN6bkWW.js";import{i as se,t as me,d as Ce,A as ye,e as _e,b as Ee,C as ve,f as we,g as ie,h as Te,j as Ie,p as S,k as Oe,l as Re,R as Ae}from"./index-W-7_hJeO.js";import{v as ae}from"./index-CUf6Dwjh.js";import"./embeddings-BPl-tQn3.js";import"./chunk-VL2OQCWN-D_jxyPOp.js";import"./index-DRz5BQNA.js";function _(e){if(typeof e=="object"&&e!==null){const n={...e};"additionalProperties"in n&&delete n.additionalProperties,"$schema"in n&&delete n.$schema,"strict"in n&&delete n.strict;for(const t in n)t in n&&(Array.isArray(n[t])?n[t]=n[t].map(_):typeof n[t]=="object"&&n[t]!==null&&(n[t]=_(n[t])));return n}return e}function N(e){const n=_(se(e)?me(e):e),{$schema:t,...o}=n;return o}function Se(e){const n=_(e),{$schema:t,...o}=n;return o}function Ne(e){const n=e._getType();return ve.isInstance(e)?e.role:n==="tool"?n:e.name??n}function be(e){switch(e){case"supervisor":case"ai":case"model":return"model";case"system":return"system";case"human":return"user";case"tool":case"function":return"function";default:throw new Error(`Unknown / unsupported author: ${e}`)}}function Me(e){if("mimeType"in e&&"data"in e)return{inlineData:{mimeType:e.mimeType,data:e.data}};if("mimeType"in e&&"fileUri"in e)return{fileData:{mimeType:e.mimeType,fileUri:e.fileUri}};throw new Error("Invalid media content")}function xe(e,n){return n.map(t=>ie(t)?t.tool_calls??[]:[]).flat().find(t=>t.id===e.tool_call_id)?.name}function De(e){return{providerName:"Google Gemini",fromStandardTextBlock(t){return{text:t.text}},fromStandardImageBlock(t){if(!e)throw new Error("This model does not support images");if(t.source_type==="url"){const o=S({dataUrl:t.url});return o?{inlineData:{mimeType:o.mime_type,data:o.data}}:{fileData:{mimeType:t.mime_type??"",fileUri:t.url}}}if(t.source_type==="base64")return{inlineData:{mimeType:t.mime_type??"",data:t.data}};throw new Error(`Unsupported source type: ${t.source_type}`)},fromStandardAudioBlock(t){if(!e)throw new Error("This model does not support audio");if(t.source_type==="url"){const o=S({dataUrl:t.url});return o?{inlineData:{mimeType:o.mime_type,data:o.data}}:{fileData:{mimeType:t.mime_type??"",fileUri:t.url}}}if(t.source_type==="base64")return{inlineData:{mimeType:t.mime_type??"",data:t.data}};throw new Error(`Unsupported source type: ${t.source_type}`)},fromStandardFileBlock(t){if(!e)throw new Error("This model does not support files");if(t.source_type==="text")return{text:t.text};if(t.source_type==="url"){const o=S({dataUrl:t.url});return o?{inlineData:{mimeType:o.mime_type,data:o.data}}:{fileData:{mimeType:t.mime_type??"",fileUri:t.url}}}if(t.source_type==="base64")return{inlineData:{mimeType:t.mime_type??"",data:t.data}};throw new Error(`Unsupported source type: ${t.source_type}`)}}}function G(e,n){if(Te(e))return Ie(e,De(n));if(e.type==="text")return{text:e.text};if(e.type==="executableCode")return{executableCode:e.executableCode};if(e.type==="codeExecutionResult")return{codeExecutionResult:e.codeExecutionResult};if(e.type==="image_url"){if(!n)throw new Error("This model does not support images");let t;if(typeof e.image_url=="string")t=e.image_url;else if(typeof e.image_url=="object"&&"url"in e.image_url)t=e.image_url.url;else throw new Error("Please provide image as base64 encoded data URL");const[o,s]=t.split(",");if(!o.startsWith("data:"))throw new Error("Please provide image as base64 encoded data URL");const[i,a]=o.replace(/^data:/,"").split(";");if(a!=="base64")throw new Error("Please provide image as base64 encoded data URL");return{inlineData:{data:s,mimeType:i}}}else{if(e.type==="media")return Me(e);if(e.type==="tool_use")return{functionCall:{name:e.name,args:e.input}};if(e.type?.includes("/")&&e.type.split("/").length===2&&"data"in e&&typeof e.data=="string")return{inlineData:{mimeType:e.type,data:e.data}};if("functionCall"in e)return;throw"type"in e?new Error(`Unknown content type ${e.type}`):new Error(`Unknown content ${JSON.stringify(e)}`)}}function Ge(e,n,t){if(we(e)){const i=e.name??xe(e,t);if(i===void 0)throw new Error(`Google requires a tool name for each tool call response, and we could not infer a called tool name for ToolMessage "${e.id}" from your passed messages. Please populate a "name" field on that ToolMessage explicitly.`);const a=Array.isArray(e.content)?e.content.map(c=>G(c,n)).filter(c=>c!==void 0):e.content;return e.status==="error"?[{functionResponse:{name:i,response:{error:{details:a}}}}]:[{functionResponse:{name:i,response:{result:a}}}]}let o=[];const s=[];return typeof e.content=="string"&&e.content&&s.push({text:e.content}),Array.isArray(e.content)&&s.push(...e.content.map(i=>G(i,n)).filter(i=>i!==void 0)),ie(e)&&e.tool_calls?.length&&(o=e.tool_calls.map(i=>({functionCall:{name:i.name,args:i.args}}))),[...s,...o]}function k(e,n,t=!1){return e.reduce((o,s,i)=>{if(!Ce(s))throw new Error("Unsupported message input");const a=Ne(s);if(a==="system"&&i!==0)throw new Error("System message should be the first one");const c=be(a),u=o.content[o.content.length];if(!o.mergeWithPreviousContent&&u&&u.role===c)throw new Error("Google Generative AI requires alternate messages between authors");const r=Ge(s,n,e.slice(0,i));if(o.mergeWithPreviousContent){const d=o.content[o.content.length-1];if(!d)throw new Error("There was a problem parsing your system message. Please try a prompt without one.");return d.parts.push(...r),{mergeWithPreviousContent:!1,content:o.content}}let p=c;(p==="function"||p==="system"&&!t)&&(p="user");const f={role:p,parts:r};return{mergeWithPreviousContent:a==="system"&&!t,content:[...o.content,f]}},{content:[],mergeWithPreviousContent:!1}).content}function ke(e,n){if(!e.candidates||e.candidates.length===0||!e.candidates[0])return{generations:[],llmOutput:{filters:e.promptFeedback}};const t=e.functionCalls(),[o]=e.candidates,{content:s,...i}=o;let a;Array.isArray(s?.parts)&&s.parts.length===1&&s.parts[0].text?a=s.parts[0].text:Array.isArray(s?.parts)&&s.parts.length>0?a=s.parts.map(r=>"text"in r?{type:"text",text:r.text}:"inlineData"in r?{type:"inlineData",inlineData:r.inlineData}:"functionCall"in r?{type:"functionCall",functionCall:r.functionCall}:"functionResponse"in r?{type:"functionResponse",functionResponse:r.functionResponse}:"fileData"in r?{type:"fileData",fileData:r.fileData}:"executableCode"in r?{type:"executableCode",executableCode:r.executableCode}:"codeExecutionResult"in r?{type:"codeExecutionResult",codeExecutionResult:r.codeExecutionResult}:r):a=[];let c="";return typeof a=="string"?c=a:Array.isArray(a)&&a.length>0&&(c=a.find(p=>"text"in p)?.text??c),{generations:[{text:c,message:new ye({content:a??"",tool_calls:t?.map(r=>({...r,type:"tool_call",id:"id"in r&&typeof r.id=="string"?r.id:ae()})),additional_kwargs:{...i},usage_metadata:n?.usageMetadata}),generationInfo:i}],llmOutput:{tokenUsage:{promptTokens:n?.usageMetadata?.input_tokens,completionTokens:n?.usageMetadata?.output_tokens,totalTokens:n?.usageMetadata?.total_tokens}}}}function Ue(e,n){if(!e.candidates||e.candidates.length===0)return null;const t=e.functionCalls(),[o]=e.candidates,{content:s,...i}=o;let a;Array.isArray(s?.parts)&&s.parts.every(r=>"text"in r)?a=s.parts.map(r=>r.text).join(""):Array.isArray(s?.parts)?a=s.parts.map(r=>"text"in r?{type:"text",text:r.text}:"inlineData"in r?{type:"inlineData",inlineData:r.inlineData}:"functionCall"in r?{type:"functionCall",functionCall:r.functionCall}:"functionResponse"in r?{type:"functionResponse",functionResponse:r.functionResponse}:"fileData"in r?{type:"fileData",fileData:r.fileData}:"executableCode"in r?{type:"executableCode",executableCode:r.executableCode}:"codeExecutionResult"in r?{type:"codeExecutionResult",codeExecutionResult:r.codeExecutionResult}:r):a=[];let c="";a&&typeof a=="string"?c=a:Array.isArray(a)&&(c=a.find(p=>"text"in p)?.text??"");const u=[];return t&&u.push(...t.map(r=>({...r,args:JSON.stringify(r.args),index:n.index,type:"tool_call_chunk",id:"id"in r&&typeof r.id=="string"?r.id:ae()}))),new _e({text:c,message:new Ee({content:a||"",name:s?s.role:void 0,tool_call_chunks:u,additional_kwargs:{},response_metadata:{model_provider:"google-genai"},usage_metadata:n.usageMetadata}),generationInfo:i})}function Le(e){return e.every(n=>"functionDeclarations"in n&&Array.isArray(n.functionDeclarations))?e:[{functionDeclarations:e.map(n=>{if(ne(n)){const t=N(n.schema);return t.type==="object"&&"properties"in t&&Object.keys(t.properties).length===0?{name:n.name,description:n.description}:{name:n.name,description:n.description,parameters:t}}return oe(n)?{name:n.function.name,description:n.function.description??"A function available to call.",parameters:Se(n.function.parameters)}:n})}]}var U=class extends fe{static lc_name(){return"GoogleGenerativeAIToolsOutputParser"}lc_namespace=["langchain","google_genai","output_parsers"];returnId=!1;keyName;returnSingle=!1;zodSchema;constructor(e){super(e),this.keyName=e.keyName,this.returnSingle=e.returnSingle??this.returnSingle,this.zodSchema=e.zodSchema}async _validateResult(e){if(this.zodSchema===void 0)return e;const n=await Oe(this.zodSchema,e);if(n.success)return n.data;throw new he(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(n.error.issues)}`,JSON.stringify(e,null,2))}async parseResult(e){const n=e.flatMap(s=>{const{message:i}=s;return!("tool_calls"in i)||!Array.isArray(i.tool_calls)?[]:i.tool_calls});if(n[0]===void 0)throw new Error("No parseable tool calls provided to GoogleGenerativeAIToolsOutputParser.");const[t]=n;return await this._validateResult(t.args)}},L;(function(e){e.STRING="string",e.NUMBER="number",e.INTEGER="integer",e.BOOLEAN="boolean",e.ARRAY="array",e.OBJECT="object"})(L||(L={}));var P;(function(e){e.LANGUAGE_UNSPECIFIED="language_unspecified",e.PYTHON="python"})(P||(P={}));var j;(function(e){e.OUTCOME_UNSPECIFIED="outcome_unspecified",e.OUTCOME_OK="outcome_ok",e.OUTCOME_FAILED="outcome_failed",e.OUTCOME_DEADLINE_EXCEEDED="outcome_deadline_exceeded"})(j||(j={}));const F=["user","model","function","system"];var K;(function(e){e.HARM_CATEGORY_UNSPECIFIED="HARM_CATEGORY_UNSPECIFIED",e.HARM_CATEGORY_HATE_SPEECH="HARM_CATEGORY_HATE_SPEECH",e.HARM_CATEGORY_SEXUALLY_EXPLICIT="HARM_CATEGORY_SEXUALLY_EXPLICIT",e.HARM_CATEGORY_HARASSMENT="HARM_CATEGORY_HARASSMENT",e.HARM_CATEGORY_DANGEROUS_CONTENT="HARM_CATEGORY_DANGEROUS_CONTENT",e.HARM_CATEGORY_CIVIC_INTEGRITY="HARM_CATEGORY_CIVIC_INTEGRITY"})(K||(K={}));var $;(function(e){e.HARM_BLOCK_THRESHOLD_UNSPECIFIED="HARM_BLOCK_THRESHOLD_UNSPECIFIED",e.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",e.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",e.BLOCK_ONLY_HIGH="BLOCK_ONLY_HIGH",e.BLOCK_NONE="BLOCK_NONE"})($||($={}));var H;(function(e){e.HARM_PROBABILITY_UNSPECIFIED="HARM_PROBABILITY_UNSPECIFIED",e.NEGLIGIBLE="NEGLIGIBLE",e.LOW="LOW",e.MEDIUM="MEDIUM",e.HIGH="HIGH"})(H||(H={}));var B;(function(e){e.BLOCKED_REASON_UNSPECIFIED="BLOCKED_REASON_UNSPECIFIED",e.SAFETY="SAFETY",e.OTHER="OTHER"})(B||(B={}));var T;(function(e){e.FINISH_REASON_UNSPECIFIED="FINISH_REASON_UNSPECIFIED",e.STOP="STOP",e.MAX_TOKENS="MAX_TOKENS",e.SAFETY="SAFETY",e.RECITATION="RECITATION",e.LANGUAGE="LANGUAGE",e.BLOCKLIST="BLOCKLIST",e.PROHIBITED_CONTENT="PROHIBITED_CONTENT",e.SPII="SPII",e.MALFORMED_FUNCTION_CALL="MALFORMED_FUNCTION_CALL",e.OTHER="OTHER"})(T||(T={}));var Y;(function(e){e.TASK_TYPE_UNSPECIFIED="TASK_TYPE_UNSPECIFIED",e.RETRIEVAL_QUERY="RETRIEVAL_QUERY",e.RETRIEVAL_DOCUMENT="RETRIEVAL_DOCUMENT",e.SEMANTIC_SIMILARITY="SEMANTIC_SIMILARITY",e.CLASSIFICATION="CLASSIFICATION",e.CLUSTERING="CLUSTERING"})(Y||(Y={}));var w;(function(e){e.MODE_UNSPECIFIED="MODE_UNSPECIFIED",e.AUTO="AUTO",e.ANY="ANY",e.NONE="NONE"})(w||(w={}));var q;(function(e){e.MODE_UNSPECIFIED="MODE_UNSPECIFIED",e.MODE_DYNAMIC="MODE_DYNAMIC"})(q||(q={}));class g extends Error{constructor(n){super(`[GoogleGenerativeAI Error]: ${n}`)}}class v extends g{constructor(n,t){super(n),this.response=t}}class re extends g{constructor(n,t,o,s){super(n),this.status=t,this.statusText=o,this.errorDetails=s}}class y extends g{}class ce extends g{}const Pe="https://generativelanguage.googleapis.com",je="v1beta",Fe="0.24.1",Ke="genai-js";var E;(function(e){e.GENERATE_CONTENT="generateContent",e.STREAM_GENERATE_CONTENT="streamGenerateContent",e.COUNT_TOKENS="countTokens",e.EMBED_CONTENT="embedContent",e.BATCH_EMBED_CONTENTS="batchEmbedContents"})(E||(E={}));class $e{constructor(n,t,o,s,i){this.model=n,this.task=t,this.apiKey=o,this.stream=s,this.requestOptions=i}toString(){var n,t;const o=((n=this.requestOptions)===null||n===void 0?void 0:n.apiVersion)||je;let i=`${((t=this.requestOptions)===null||t===void 0?void 0:t.baseUrl)||Pe}/${o}/${this.model}:${this.task}`;return this.stream&&(i+="?alt=sse"),i}}function He(e){const n=[];return e?.apiClient&&n.push(e.apiClient),n.push(`${Ke}/${Fe}`),n.join(" ")}async function Be(e){var n;const t=new Headers;t.append("Content-Type","application/json"),t.append("x-goog-api-client",He(e.requestOptions)),t.append("x-goog-api-key",e.apiKey);let o=(n=e.requestOptions)===null||n===void 0?void 0:n.customHeaders;if(o){if(!(o instanceof Headers))try{o=new Headers(o)}catch(s){throw new y(`unable to convert customHeaders value ${JSON.stringify(o)} to Headers: ${s.message}`)}for(const[s,i]of o.entries()){if(s==="x-goog-api-key")throw new y(`Cannot set reserved header name ${s}`);if(s==="x-goog-api-client")throw new y(`Header name ${s} can only be set using the apiClient field`);t.append(s,i)}}return t}async function Ye(e,n,t,o,s,i){const a=new $e(e,n,t,o,i);return{url:a.toString(),fetchOptions:Object.assign(Object.assign({},Je(i)),{method:"POST",headers:await Be(a),body:s})}}async function R(e,n,t,o,s,i={},a=fetch){const{url:c,fetchOptions:u}=await Ye(e,n,t,o,s,i);return qe(c,u,a)}async function qe(e,n,t=fetch){let o;try{o=await t(e,n)}catch(s){We(s,e)}return o.ok||await Ve(o,e),o}function We(e,n){let t=e;throw t.name==="AbortError"?(t=new ce(`Request aborted when fetching ${n.toString()}: ${e.message}`),t.stack=e.stack):e instanceof re||e instanceof y||(t=new g(`Error fetching from ${n.toString()}: ${e.message}`),t.stack=e.stack),t}async function Ve(e,n){let t="",o;try{const s=await e.json();t=s.error.message,s.error.details&&(t+=` ${JSON.stringify(s.error.details)}`,o=s.error.details)}catch{}throw new re(`Error fetching from ${n.toString()}: [${e.status} ${e.statusText}] ${t}`,e.status,e.statusText,o)}function Je(e){const n={};if(e?.signal!==void 0||e?.timeout>=0){const t=new AbortController;e?.timeout>=0&&setTimeout(()=>t.abort(),e.timeout),e?.signal&&e.signal.addEventListener("abort",()=>{t.abort()}),n.signal=t.signal}return n}function b(e){return e.text=()=>{if(e.candidates&&e.candidates.length>0){if(e.candidates.length>1&&console.warn(`This response had ${e.candidates.length} candidates. Returning text from the first candidate only. Access response.candidates directly to use the other candidates.`),A(e.candidates[0]))throw new v(`${C(e)}`,e);return ze(e)}else if(e.promptFeedback)throw new v(`Text not available. ${C(e)}`,e);return""},e.functionCall=()=>{if(e.candidates&&e.candidates.length>0){if(e.candidates.length>1&&console.warn(`This response had ${e.candidates.length} candidates. Returning function calls from the first candidate only. Access response.candidates directly to use the other candidates.`),A(e.candidates[0]))throw new v(`${C(e)}`,e);return console.warn("response.functionCall() is deprecated. Use response.functionCalls() instead."),W(e)[0]}else if(e.promptFeedback)throw new v(`Function call not available. ${C(e)}`,e)},e.functionCalls=()=>{if(e.candidates&&e.candidates.length>0){if(e.candidates.length>1&&console.warn(`This response had ${e.candidates.length} candidates. Returning function calls from the first candidate only. Access response.candidates directly to use the other candidates.`),A(e.candidates[0]))throw new v(`${C(e)}`,e);return W(e)}else if(e.promptFeedback)throw new v(`Function call not available. ${C(e)}`,e)},e}function ze(e){var n,t,o,s;const i=[];if(!((t=(n=e.candidates)===null||n===void 0?void 0:n[0].content)===null||t===void 0)&&t.parts)for(const a of(s=(o=e.candidates)===null||o===void 0?void 0:o[0].content)===null||s===void 0?void 0:s.parts)a.text&&i.push(a.text),a.executableCode&&i.push("\n```"+a.executableCode.language+`
2
+ `+a.executableCode.code+"\n```\n"),a.codeExecutionResult&&i.push("\n```\n"+a.codeExecutionResult.output+"\n```\n");return i.length>0?i.join(""):""}function W(e){var n,t,o,s;const i=[];if(!((t=(n=e.candidates)===null||n===void 0?void 0:n[0].content)===null||t===void 0)&&t.parts)for(const a of(s=(o=e.candidates)===null||o===void 0?void 0:o[0].content)===null||s===void 0?void 0:s.parts)a.functionCall&&i.push(a.functionCall);if(i.length>0)return i}const Xe=[T.RECITATION,T.SAFETY,T.LANGUAGE];function A(e){return!!e.finishReason&&Xe.includes(e.finishReason)}function C(e){var n,t,o;let s="";if((!e.candidates||e.candidates.length===0)&&e.promptFeedback)s+="Response was blocked",!((n=e.promptFeedback)===null||n===void 0)&&n.blockReason&&(s+=` due to ${e.promptFeedback.blockReason}`),!((t=e.promptFeedback)===null||t===void 0)&&t.blockReasonMessage&&(s+=`: ${e.promptFeedback.blockReasonMessage}`);else if(!((o=e.candidates)===null||o===void 0)&&o[0]){const i=e.candidates[0];A(i)&&(s+=`Candidate was blocked due to ${i.finishReason}`,i.finishMessage&&(s+=`: ${i.finishMessage}`))}return s}function I(e){return this instanceof I?(this.v=e,this):new I(e)}function Qe(e,n,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var o=t.apply(e,n||[]),s,i=[];return s={},a("next"),a("throw"),a("return"),s[Symbol.asyncIterator]=function(){return this},s;function a(d){o[d]&&(s[d]=function(l){return new Promise(function(h,m){i.push([d,l,h,m])>1||c(d,l)})})}function c(d,l){try{u(o[d](l))}catch(h){f(i[0][3],h)}}function u(d){d.value instanceof I?Promise.resolve(d.value.v).then(r,p):f(i[0][2],d)}function r(d){c("next",d)}function p(d){c("throw",d)}function f(d,l){d(l),i.shift(),i.length&&c(i[0][0],i[0][1])}}const V=/^data\: (.*)(?:\n\n|\r\r|\r\n\r\n)/;function Ze(e){const n=e.body.pipeThrough(new TextDecoderStream("utf8",{fatal:!0})),t=nt(n),[o,s]=t.tee();return{stream:tt(o),response:et(s)}}async function et(e){const n=[],t=e.getReader();for(;;){const{done:o,value:s}=await t.read();if(o)return b(ot(n));n.push(s)}}function tt(e){return Qe(this,arguments,function*(){const t=e.getReader();for(;;){const{value:o,done:s}=yield I(t.read());if(s)break;yield yield I(b(o))}})}function nt(e){const n=e.getReader();return new ReadableStream({start(o){let s="";return i();function i(){return n.read().then(({value:a,done:c})=>{if(c){if(s.trim()){o.error(new g("Failed to parse stream"));return}o.close();return}s+=a;let u=s.match(V),r;for(;u;){try{r=JSON.parse(u[1])}catch{o.error(new g(`Error parsing JSON response: "${u[1]}"`));return}o.enqueue(r),s=s.substring(u[0].length),u=s.match(V)}return i()}).catch(a=>{let c=a;throw c.stack=a.stack,c.name==="AbortError"?c=new ce("Request aborted when reading from the stream"):c=new g("Error reading from the stream"),c})}}})}function ot(e){const n=e[e.length-1],t={promptFeedback:n?.promptFeedback};for(const o of e){if(o.candidates){let s=0;for(const i of o.candidates)if(t.candidates||(t.candidates=[]),t.candidates[s]||(t.candidates[s]={index:s}),t.candidates[s].citationMetadata=i.citationMetadata,t.candidates[s].groundingMetadata=i.groundingMetadata,t.candidates[s].finishReason=i.finishReason,t.candidates[s].finishMessage=i.finishMessage,t.candidates[s].safetyRatings=i.safetyRatings,i.content&&i.content.parts){t.candidates[s].content||(t.candidates[s].content={role:i.content.role||"user",parts:[]});const a={};for(const c of i.content.parts)c.text&&(a.text=c.text),c.functionCall&&(a.functionCall=c.functionCall),c.executableCode&&(a.executableCode=c.executableCode),c.codeExecutionResult&&(a.codeExecutionResult=c.codeExecutionResult),Object.keys(a).length===0&&(a.text=""),t.candidates[s].content.parts.push(a)}s++}o.usageMetadata&&(t.usageMetadata=o.usageMetadata)}return t}async function le(e,n,t,o){const s=await R(n,E.STREAM_GENERATE_CONTENT,e,!0,JSON.stringify(t),o);return Ze(s)}async function ue(e,n,t,o){const i=await(await R(n,E.GENERATE_CONTENT,e,!1,JSON.stringify(t),o)).json();return{response:b(i)}}function de(e){if(e!=null){if(typeof e=="string")return{role:"system",parts:[{text:e}]};if(e.text)return{role:"system",parts:[e]};if(e.parts)return e.role?e:{role:"system",parts:e.parts}}}function O(e){let n=[];if(typeof e=="string")n=[{text:e}];else for(const t of e)typeof t=="string"?n.push({text:t}):n.push(t);return st(n)}function st(e){const n={role:"user",parts:[]},t={role:"function",parts:[]};let o=!1,s=!1;for(const i of e)"functionResponse"in i?(t.parts.push(i),s=!0):(n.parts.push(i),o=!0);if(o&&s)throw new g("Within a single message, FunctionResponse cannot be mixed with other type of part in the request for sending chat message.");if(!o&&!s)throw new g("No content is provided for sending chat message.");return o?n:t}function it(e,n){var t;let o={model:n?.model,generationConfig:n?.generationConfig,safetySettings:n?.safetySettings,tools:n?.tools,toolConfig:n?.toolConfig,systemInstruction:n?.systemInstruction,cachedContent:(t=n?.cachedContent)===null||t===void 0?void 0:t.name,contents:[]};const s=e.generateContentRequest!=null;if(e.contents){if(s)throw new y("CountTokensRequest must have one of contents or generateContentRequest, not both.");o.contents=e.contents}else if(s)o=Object.assign(Object.assign({},o),e.generateContentRequest);else{const i=O(e);o.contents=[i]}return{generateContentRequest:o}}function J(e){let n;return e.contents?n=e:n={contents:[O(e)]},e.systemInstruction&&(n.systemInstruction=de(e.systemInstruction)),n}function at(e){return typeof e=="string"||Array.isArray(e)?{content:O(e)}:e}const z=["text","inlineData","functionCall","functionResponse","executableCode","codeExecutionResult"],rt={user:["text","inlineData"],function:["functionResponse"],model:["text","functionCall","executableCode","codeExecutionResult"],system:["text"]};function ct(e){let n=!1;for(const t of e){const{role:o,parts:s}=t;if(!n&&o!=="user")throw new g(`First content should be with role 'user', got ${o}`);if(!F.includes(o))throw new g(`Each item should include role field. Got ${o} but valid roles are: ${JSON.stringify(F)}`);if(!Array.isArray(s))throw new g("Content should have 'parts' property with an array of Parts");if(s.length===0)throw new g("Each Content should have at least one part");const i={text:0,inlineData:0,functionCall:0,functionResponse:0,fileData:0,executableCode:0,codeExecutionResult:0};for(const c of s)for(const u of z)u in c&&(i[u]+=1);const a=rt[o];for(const c of z)if(!a.includes(c)&&i[c]>0)throw new g(`Content with role '${o}' can't contain '${c}' part`);n=!0}}function X(e){var n;if(e.candidates===void 0||e.candidates.length===0)return!1;const t=(n=e.candidates[0])===null||n===void 0?void 0:n.content;if(t===void 0||t.parts===void 0||t.parts.length===0)return!1;for(const o of t.parts)if(o===void 0||Object.keys(o).length===0||o.text!==void 0&&o.text==="")return!1;return!0}const Q="SILENT_ERROR";class lt{constructor(n,t,o,s={}){this.model=t,this.params=o,this._requestOptions=s,this._history=[],this._sendPromise=Promise.resolve(),this._apiKey=n,o?.history&&(ct(o.history),this._history=o.history)}async getHistory(){return await this._sendPromise,this._history}async sendMessage(n,t={}){var o,s,i,a,c,u;await this._sendPromise;const r=O(n),p={safetySettings:(o=this.params)===null||o===void 0?void 0:o.safetySettings,generationConfig:(s=this.params)===null||s===void 0?void 0:s.generationConfig,tools:(i=this.params)===null||i===void 0?void 0:i.tools,toolConfig:(a=this.params)===null||a===void 0?void 0:a.toolConfig,systemInstruction:(c=this.params)===null||c===void 0?void 0:c.systemInstruction,cachedContent:(u=this.params)===null||u===void 0?void 0:u.cachedContent,contents:[...this._history,r]},f=Object.assign(Object.assign({},this._requestOptions),t);let d;return this._sendPromise=this._sendPromise.then(()=>ue(this._apiKey,this.model,p,f)).then(l=>{var h;if(X(l.response)){this._history.push(r);const m=Object.assign({parts:[],role:"model"},(h=l.response.candidates)===null||h===void 0?void 0:h[0].content);this._history.push(m)}else{const m=C(l.response);m&&console.warn(`sendMessage() was unsuccessful. ${m}. Inspect response object for details.`)}d=l}).catch(l=>{throw this._sendPromise=Promise.resolve(),l}),await this._sendPromise,d}async sendMessageStream(n,t={}){var o,s,i,a,c,u;await this._sendPromise;const r=O(n),p={safetySettings:(o=this.params)===null||o===void 0?void 0:o.safetySettings,generationConfig:(s=this.params)===null||s===void 0?void 0:s.generationConfig,tools:(i=this.params)===null||i===void 0?void 0:i.tools,toolConfig:(a=this.params)===null||a===void 0?void 0:a.toolConfig,systemInstruction:(c=this.params)===null||c===void 0?void 0:c.systemInstruction,cachedContent:(u=this.params)===null||u===void 0?void 0:u.cachedContent,contents:[...this._history,r]},f=Object.assign(Object.assign({},this._requestOptions),t),d=le(this._apiKey,this.model,p,f);return this._sendPromise=this._sendPromise.then(()=>d).catch(l=>{throw new Error(Q)}).then(l=>l.response).then(l=>{if(X(l)){this._history.push(r);const h=Object.assign({},l.candidates[0].content);h.role||(h.role="model"),this._history.push(h)}else{const h=C(l);h&&console.warn(`sendMessageStream() was unsuccessful. ${h}. Inspect response object for details.`)}}).catch(l=>{l.message!==Q&&console.error(l)}),d}}async function ut(e,n,t,o){return(await R(n,E.COUNT_TOKENS,e,!1,JSON.stringify(t),o)).json()}async function dt(e,n,t,o){return(await R(n,E.EMBED_CONTENT,e,!1,JSON.stringify(t),o)).json()}async function ft(e,n,t,o){const s=t.requests.map(a=>Object.assign(Object.assign({},a),{model:n}));return(await R(n,E.BATCH_EMBED_CONTENTS,e,!1,JSON.stringify({requests:s}),o)).json()}class Z{constructor(n,t,o={}){this.apiKey=n,this._requestOptions=o,t.model.includes("/")?this.model=t.model:this.model=`models/${t.model}`,this.generationConfig=t.generationConfig||{},this.safetySettings=t.safetySettings||[],this.tools=t.tools,this.toolConfig=t.toolConfig,this.systemInstruction=de(t.systemInstruction),this.cachedContent=t.cachedContent}async generateContent(n,t={}){var o;const s=J(n),i=Object.assign(Object.assign({},this._requestOptions),t);return ue(this.apiKey,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:(o=this.cachedContent)===null||o===void 0?void 0:o.name},s),i)}async generateContentStream(n,t={}){var o;const s=J(n),i=Object.assign(Object.assign({},this._requestOptions),t);return le(this.apiKey,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:(o=this.cachedContent)===null||o===void 0?void 0:o.name},s),i)}startChat(n){var t;return new lt(this.apiKey,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:(t=this.cachedContent)===null||t===void 0?void 0:t.name},n),this._requestOptions)}async countTokens(n,t={}){const o=it(n,{model:this.model,generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:this.cachedContent}),s=Object.assign(Object.assign({},this._requestOptions),t);return ut(this.apiKey,this.model,o,s)}async embedContent(n,t={}){const o=at(n),s=Object.assign(Object.assign({},this._requestOptions),t);return dt(this.apiKey,this.model,o,s)}async batchEmbedContents(n,t={}){const o=Object.assign(Object.assign({},this._requestOptions),t);return ft(this.apiKey,this.model,n,o)}}class ee{constructor(n){this.apiKey=n}getGenerativeModel(n,t){if(!n.model)throw new g("Must provide a model name. Example: genai.getGenerativeModel({ model: 'my-model-name' })");return new Z(this.apiKey,n,t)}getGenerativeModelFromCachedContent(n,t,o){if(!n.name)throw new y("Cached content must contain a `name` field.");if(!n.model)throw new y("Cached content must contain a `model` field.");const s=["model","systemInstruction"];for(const a of s)if(t?.[a]&&n[a]&&t?.[a]!==n[a]){if(a==="model"){const c=t.model.startsWith("models/")?t.model.replace("models/",""):t.model,u=n.model.startsWith("models/")?n.model.replace("models/",""):n.model;if(c===u)continue}throw new y(`Different value for "${a}" specified in modelParams (${t[a]}) and cachedContent (${n[a]})`)}const i=Object.assign(Object.assign({},t),{model:n.model,tools:n.tools,toolConfig:n.toolConfig,systemInstruction:n.systemInstruction,cachedContent:n});return new Z(this.apiKey,i,o)}}function te(e,n){const t=ht(e),o=gt(t,n);return{tools:t,toolConfig:o}}function ht(e){let n=[];const t=[];return e.forEach(s=>{if(ne(s)){const[i]=Le([s]);i.functionDeclarations&&n.push(...i.functionDeclarations)}else if(oe(s)){const{functionDeclarations:i}=pt(s);if(i)n.push(...i);else throw new Error("Failed to convert OpenAI structured tool to GenerativeAI tool")}else t.push(s)}),t.find(s=>"functionDeclarations"in s)?t.map(s=>{if(n?.length>0&&"functionDeclarations"in s){const i={functionDeclarations:[...s.functionDeclarations||[],...n]};return n=[],i}return s}):[...t,...n.length>0?[{functionDeclarations:n}]:[]]}function pt(e){return{functionDeclarations:[{name:e.function.name,description:e.function.description,parameters:_(e.function.parameters)}]}}function gt(e,n){if(!e.length||!n)return;const{toolChoice:t,allowedFunctionNames:o}=n,s={any:w.ANY,auto:w.AUTO,none:w.NONE};if(t&&["any","auto","none"].includes(t))return{functionCallingConfig:{mode:s[t]??"MODE_UNSPECIFIED",allowedFunctionNames:o}};if(typeof t=="string"||o)return{functionCallingConfig:{mode:w.ANY,allowedFunctionNames:[...o??[],...t&&typeof t=="string"?[t]:[]]}}}var wt=class extends pe{static lc_name(){return"ChatGoogleGenerativeAI"}lc_serializable=!0;get lc_secrets(){return{apiKey:"GOOGLE_API_KEY"}}lc_namespace=["langchain","chat_models","google_genai"];get lc_aliases(){return{apiKey:"google_api_key"}}model;temperature;maxOutputTokens;topP;topK;stopSequences=[];safetySettings;apiKey;streaming=!1;json;streamUsage=!0;convertSystemMessageToHumanContent;client;get _isMultimodalModel(){return this.model.includes("vision")||this.model.startsWith("gemini-1.5")||this.model.startsWith("gemini-2")||this.model.startsWith("gemma-3-")&&!this.model.startsWith("gemma-3-1b")}constructor(e){if(super(e),this.model=e.model.replace(/^models\//,""),this.maxOutputTokens=e.maxOutputTokens??this.maxOutputTokens,this.maxOutputTokens&&this.maxOutputTokens<0)throw new Error("`maxOutputTokens` must be a positive integer");if(this.temperature=e.temperature??this.temperature,this.temperature&&(this.temperature<0||this.temperature>2))throw new Error("`temperature` must be in the range of [0.0,2.0]");if(this.topP=e.topP??this.topP,this.topP&&this.topP<0)throw new Error("`topP` must be a positive integer");if(this.topP&&this.topP>1)throw new Error("`topP` must be below 1.");if(this.topK=e.topK??this.topK,this.topK&&this.topK<0)throw new Error("`topK` must be a positive integer");if(this.stopSequences=e.stopSequences??this.stopSequences,this.apiKey=e.apiKey??Re("GOOGLE_API_KEY"),!this.apiKey)throw new Error("Please set an API key for Google GenerativeAI in the environment variable GOOGLE_API_KEY or in the `apiKey` field of the ChatGoogleGenerativeAI constructor");if(this.safetySettings=e.safetySettings??this.safetySettings,this.safetySettings&&this.safetySettings.length>0&&new Set(this.safetySettings.map(t=>t.category)).size!==this.safetySettings.length)throw new Error("The categories in `safetySettings` array must be unique");this.streaming=e.streaming??this.streaming,this.json=e.json,this.client=new ee(this.apiKey).getGenerativeModel({model:this.model,safetySettings:this.safetySettings,generationConfig:{stopSequences:this.stopSequences,maxOutputTokens:this.maxOutputTokens,temperature:this.temperature,topP:this.topP,topK:this.topK,...this.json?{responseMimeType:"application/json"}:{}}},{apiVersion:e.apiVersion,baseUrl:e.baseUrl}),this.streamUsage=e.streamUsage??this.streamUsage}useCachedContent(e,n,t){this.apiKey&&(this.client=new ee(this.apiKey).getGenerativeModelFromCachedContent(e,n,t))}get useSystemInstruction(){return typeof this.convertSystemMessageToHumanContent=="boolean"?!this.convertSystemMessageToHumanContent:this.computeUseSystemInstruction}get computeUseSystemInstruction(){return this.model==="gemini-1.0-pro-001"||this.model.startsWith("gemini-pro-vision")||this.model.startsWith("gemini-1.0-pro-vision")?!1:this.model!=="gemini-pro"}getLsParams(e){return{ls_provider:"google_genai",ls_model_name:this.model,ls_model_type:"chat",ls_temperature:this.client.generationConfig.temperature,ls_max_tokens:this.client.generationConfig.maxOutputTokens,ls_stop:e.stop}}_combineLLMOutput(){return[]}_llmType(){return"googlegenerativeai"}bindTools(e,n){return this.withConfig({tools:te(e)?.tools,...n})}invocationParams(e){const n=e?.tools?.length?te(e.tools,{toolChoice:e.tool_choice,allowedFunctionNames:e.allowedFunctionNames}):void 0;return e?.responseSchema?(this.client.generationConfig.responseSchema=e.responseSchema,this.client.generationConfig.responseMimeType="application/json"):(this.client.generationConfig.responseSchema=void 0,this.client.generationConfig.responseMimeType=this.json?"application/json":void 0),{...n?.tools?{tools:n.tools}:{},...n?.toolConfig?{toolConfig:n.toolConfig}:{}}}async _generate(e,n,t){const o=k(e,this._isMultimodalModel,this.useSystemInstruction);let s=o;if(o[0].role==="system"){const[r]=o;this.client.systemInstruction=r,s=o.slice(1)}const i=this.invocationParams(n);if(this.streaming){const r={},p=this._streamResponseChunks(e,n,t),f={};for await(const l of p){const h=l.generationInfo?.completion??0;f[h]===void 0?f[h]=l:f[h]=f[h].concat(l)}return{generations:Object.entries(f).sort(([l],[h])=>parseInt(l,10)-parseInt(h,10)).map(([l,h])=>h),llmOutput:{estimatedTokenUsage:r}}}const a=await this.completionWithRetry({...i,contents:s});let c;if("usageMetadata"in a.response){const r=a.response.usageMetadata;c={input_tokens:r.promptTokenCount??0,output_tokens:r.candidatesTokenCount??0,total_tokens:r.totalTokenCount??0}}const u=ke(a.response,{usageMetadata:c});return u.generations?.length>0&&await t?.handleLLMNewToken(u.generations[0]?.text??""),u}async*_streamResponseChunks(e,n,t){const o=k(e,this._isMultimodalModel,this.useSystemInstruction);let s=o;if(o[0].role==="system"){const[l]=o;this.client.systemInstruction=l,s=o.slice(1)}const a={...this.invocationParams(n),contents:s},c=await this.caller.callWithOptions({signal:n?.signal},async()=>{const{stream:l}=await this.client.generateContentStream(a);return l});let u,r=0,p=0,f=0,d=0;for await(const l of c){if("usageMetadata"in l&&l.usageMetadata!==void 0&&this.streamUsage!==!1&&n.streamUsage!==!1){u={input_tokens:l.usageMetadata.promptTokenCount??0,output_tokens:l.usageMetadata.candidatesTokenCount??0,total_tokens:l.usageMetadata.totalTokenCount??0};const m=l.usageMetadata.promptTokenCount??0;u.input_tokens=Math.max(0,m-r),r=m;const M=l.usageMetadata.candidatesTokenCount??0;u.output_tokens=Math.max(0,M-p),p=M;const x=l.usageMetadata.totalTokenCount??0;u.total_tokens=Math.max(0,x-f),f=x}const h=Ue(l,{usageMetadata:u,index:d});d+=1,h&&(yield h,await t?.handleLLMNewToken(h.text??""))}}async completionWithRetry(e,n){return this.caller.callWithOptions({signal:n?.signal},async()=>{try{return await this.client.generateContent(e)}catch(t){throw t.message?.includes("400 Bad Request")&&(t.status=400),t}})}withStructuredOutput(e,n){const t=e,o=n?.name,s=n?.method,i=n?.includeRaw;if(s==="jsonMode")throw new Error('ChatGoogleGenerativeAI only supports "jsonSchema" or "functionCalling" as a method.');let a,c;if(s==="functionCalling"){let f=o??"extract",d;if(se(t)){const l=N(t);d=[{functionDeclarations:[{name:f,description:l.description??"A function available to call.",parameters:l}]}],c=new U({returnSingle:!0,keyName:f,zodSchema:t})}else{let l;typeof t.name=="string"&&typeof t.parameters=="object"&&t.parameters!=null?(l=t,l.parameters=_(t.parameters),f=t.name):l={name:f,description:t.description??"",parameters:_(t)},d=[{functionDeclarations:[l]}],c=new U({returnSingle:!0,keyName:f})}a=this.bindTools(d).withConfig({allowedFunctionNames:[f]})}else{const f=N(t);a=this.withConfig({responseSchema:f}),c=new ge}if(!i)return a.pipe(c).withConfig({runName:"ChatGoogleGenerativeAIStructuredOutput"});const u=D.assign({parsed:(f,d)=>c.invoke(f.raw,d)}),r=D.assign({parsed:()=>null}),p=u.withFallbacks({fallbacks:[r]});return Ae.from([{raw:a},p]).withConfig({runName:"StructuredOutputRunnable"})}};export{wt as ChatGoogleGenerativeAI};