@mcp-use/inspector 0.26.0 → 0.26.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cdn/inspector.js +12 -12
- package/dist/client/index.js +31 -31
- package/dist/web/assets/{browser-CqnU_bMs.js → browser-CUjguYn6.js} +3 -3
- package/dist/web/assets/{chunk-RJUJMGGE-Ckike6v2.js → chunk-6E445R5C-ny1rw8Le.js} +1 -1
- package/dist/web/assets/{chunk-RPN2XO5I-BsQOpC8p.js → chunk-RPN2XO5I-_4a18lz2.js} +1 -1
- package/dist/web/assets/{chunk_array-Drzz3Bxj.js → chunk_array-cMM4je5w.js} +1 -1
- package/dist/web/assets/{client-CnWipjEl.js → client-DEFMLVFC.js} +1 -1
- package/dist/web/assets/{client-2CASVELM-BYYvwD7E.js → client-S6L7XHLF-Dqmt1wRx.js} +3 -3
- package/dist/web/assets/{dist-DXjAPY-W.js → dist-BG8NAFfu.js} +1 -1
- package/dist/web/assets/{dist-CFOVbGE_.js → dist-CKth7ANk.js} +1 -1
- package/dist/web/assets/{dist-jBWD8iGG.js → dist-YxwKnKYL.js} +1 -1
- package/dist/web/assets/{function_calling-BLGGrcJY.js → function_calling-XyGNNvjR.js} +1 -1
- package/dist/web/assets/{index-DnLjyl1f.js → index-zqVFP8t5.js} +10 -10
- package/dist/web/assets/{llms-CUFNg0bG.js → llms-DmE4p8kW.js} +1 -1
- package/dist/web/assets/messages-DmWRSzWI.js +1 -0
- package/dist/web/assets/react-Cg35ZZKt.js +1 -0
- package/dist/web/assets/{rpc-logger-TPNV75J4-DaBpv6Xr.js → rpc-logger-TPNV75J4-BPgEimJH.js} +1 -1
- package/dist/web/assets/{stdio-IOUVQROQ-CeewE_Ia.js → stdio-LLTXMSZH-CQ-zxwTS.js} +1 -1
- package/dist/web/assets/{tools-Bn2uguc_.js → tools-DWDA-ZTt.js} +1 -1
- package/dist/web/index.html +4 -4
- package/package.json +4 -3
- package/dist/web/assets/messages-D9QOZWGX.js +0 -1
- package/dist/web/assets/react-DDmrI2D-.js +0 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{En as e,G as t,I as n,Kt as r,Pn as i,cr as a,fr as o,g as s,nn as c,or as l,ot as u,qn as d,rn as f,tn as p,w as ee}from"./index-DnLjyl1f.js";import{A as te,M as m,O as ne,p as h,r as g,s as re,w as ie}from"./function_calling-BLGGrcJY.js";import"./chunk_array-Drzz3Bxj.js";function _(e){if(typeof e==`object`&&e){let t={...e};`additionalProperties`in t&&delete t.additionalProperties,`$schema`in t&&delete t.$schema,`strict`in t&&delete t.strict;for(let e in t)e in t&&(Array.isArray(t[e])?t[e]=t[e].map(_):typeof t[e]==`object`&&t[e]!==null&&(t[e]=_(t[e])));return t}return e}function v(e){let{$schema:n,...r}=_(t(e)?ee(e):e);return r}function ae(e){let{$schema:t,...n}=_(e);return n}function y(e,t,n=[]){if(typeof e!=`object`||!e)return;let r=e;if(Array.isArray(r.enum)&&r.enum.some(e=>e===``)){let e=n.length?` at path "${n.join(`.`)}"`:``,r=t?` in tool "${t}"`:``;throw Error(`Invalid enum: empty string not allowed${r}${e}. Gemini API rejects empty strings in enums.`)}if(r.type===`object`&&r.properties&&typeof r.properties==`object`)for(let[e,i]of Object.entries(r.properties))y(i,t,[...n,e]);r.items&&y(r.items,t,[...n,`[]`]);for(let e of[`anyOf`,`oneOf`,`allOf`]){let i=r[e];Array.isArray(i)&&i.forEach((r,i)=>y(r,t,[...n,`${e}[${i}]`]))}r.additionalProperties&&typeof r.additionalProperties==`object`&&y(r.additionalProperties,t,[...n,`additionalProperties`])}var b=[];for(let e=0;e<256;++e)b.push((e+256).toString(16).slice(1));function oe(e,t=0){return(b[e[t+0]]+b[e[t+1]]+b[e[t+2]]+b[e[t+3]]+`-`+b[e[t+4]]+b[e[t+5]]+`-`+b[e[t+6]]+b[e[t+7]]+`-`+b[e[t+8]]+b[e[t+9]]+`-`+b[e[t+10]]+b[e[t+11]]+b[e[t+12]]+b[e[t+13]]+b[e[t+14]]+b[e[t+15]]).toLowerCase()}var x,se=new Uint8Array(16);function ce(){if(!x){if(typeof crypto>`u`||!crypto.getRandomValues)throw Error(`crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported`);x=crypto.getRandomValues.bind(crypto)}return x(se)}var S={randomUUID:typeof crypto<`u`&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function C(e,t,n){if(S.randomUUID&&!t&&!e)return S.randomUUID();e||={};let r=e.random??e.rng?.()??ce();if(r.length<16)throw Error(`Random bytes length must be >= 16`);if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,t){if(n||=0,n<0||n+16>t.length)throw RangeError(`UUID byte range ${n}:${n+15} is out of buffer bounds`);for(let e=0;e<16;++e)t[n+e]=r[e];return t}return oe(r)}var w=`__gemini_function_call_thought_signatures__`,le=`ErYCCrMCAdHtim9kOoOkrPiCNVsmlpMIKd7ZMxgiFbVQOkgp7nlLcDMzVsZwIzvuT7nQROivoXA72ccC2lSDvR0Gh7dkWaGuj7ctv6t7ZceHnecx0QYa+ix8tYpRfjhyWozQ49lWiws6+YGjCt10KRTyWsZ2h6O7iHTYJwKIRwGUHRKy/qK/6kFxJm5ML00gLq4D8s5Z6DBpp2ZlR+uF4G8jJgeWQgyHWVdx2wGYElaceVAc66tZdPQRdOHpWtgYSI1YdaXgVI8KHY3/EfNc2YqqMIulvkDBAnuMhkAjV9xmBa54Tq+ih3Im4+r3DzqhGqYdsSkhS0kZMwte4Hjs65dZzCw9lANxIqYi1DJ639WNPYihp/DCJCos7o+/EeSPJaio5sgWDyUnMGkY1atsJZ+m7pj7DD5tvQ==`,ue=e=>e();function de(t){return e.isInstance(t)?t.role:t.type}function fe(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 Error(`Unknown / unsupported author: ${e}`)}}function pe(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 Error(`Invalid media content`)}function me(e,t){return t.map(e=>f(e)?e.tool_calls??[]:[]).flat().find(t=>t.id===e.tool_call_id)?.name}function he(e){return{providerName:`Google Gemini`,fromStandardTextBlock(e){return{text:e.text}},fromStandardImageBlock(t){if(!e)throw Error(`This model does not support images`);if(t.source_type===`url`){let e=o({dataUrl:t.url});return e?{inlineData:{mimeType:e.mime_type,data:e.data}}:{fileData:{mimeType:t.mime_type??``,fileUri:t.url}}}if(t.source_type===`base64`)return{inlineData:{mimeType:t.mime_type??``,data:t.data}};throw Error(`Unsupported source type: ${t.source_type}`)},fromStandardAudioBlock(t){if(!e)throw Error(`This model does not support audio`);if(t.source_type===`url`){let e=o({dataUrl:t.url});return e?{inlineData:{mimeType:e.mime_type,data:e.data}}:{fileData:{mimeType:t.mime_type??``,fileUri:t.url}}}if(t.source_type===`base64`)return{inlineData:{mimeType:t.mime_type??``,data:t.data}};throw Error(`Unsupported source type: ${t.source_type}`)},fromStandardFileBlock(t){if(!e)throw Error(`This model does not support files`);if(t.source_type===`text`)return{text:t.text};if(t.source_type===`url`){let e=o({dataUrl:t.url});return e?{inlineData:{mimeType:e.mime_type,data:e.data}}:{fileData:{mimeType:t.mime_type??``,fileUri:t.url}}}if(t.source_type===`base64`)return{inlineData:{mimeType:t.mime_type??``,data:t.data}};throw Error(`Unsupported source type: ${t.source_type}`)}}}function T(e,t){if(a(e))return l(e,he(t));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(!t)throw Error(`This model does not support images`);let n;if(typeof e.image_url==`string`)n=e.image_url;else if(typeof e.image_url==`object`&&`url`in e.image_url)n=e.image_url.url;else throw Error(`Please provide image as base64 encoded data URL`);let[r,i]=n.split(`,`);if(!r.startsWith(`data:`))throw Error(`Please provide image as base64 encoded data URL`);let[a,o]=r.replace(/^data:/,``).split(`;`);if(o!==`base64`)throw Error(`Please provide image as base64 encoded data URL`);return{inlineData:{data:i,mimeType:a}}}else if(e.type===`media`)return pe(e);else if(e.type===`tool_use`)return{functionCall:{name:e.name,args:e.input}};else if(e.type===`tool_call`)return{functionCall:{name:e.name,args:e.args}};else if(e.type?.includes(`/`)&&e.type.split(`/`).length===2&&`data`in e&&typeof e.data==`string`)return{inlineData:{mimeType:e.type,data:e.data}};else if(`functionCall`in e)return;else if(`type`in e)throw Error(`Unknown content type ${e.type}`);else throw Error(`Unknown content ${JSON.stringify(e)}`)}function ge(e,t,n,r){if(i(e)){let r=e.name??me(e,n);if(r===void 0)throw 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.`);let i=Array.isArray(e.content)?e.content.map(e=>T(e,t)).filter(e=>e!==void 0):e.content;return e.status===`error`?[{functionResponse:{name:r,response:{error:{details:i}}}}]:[{functionResponse:{name:r,response:{result:i}}}]}let a=[],o=[];typeof e.content==`string`&&e.content&&o.push({text:e.content}),Array.isArray(e.content)&&o.push(...e.content.map(e=>T(e,t)).filter(e=>e!==void 0));let s=e.additional_kwargs?.[w];return f(e)&&e.tool_calls?.length&&(a=e.tool_calls.map(e=>{let t=ue(()=>{if(e.id){let t=s?.[e.id];if(t)return t}return r?.includes(`gemini-3`)?le:``});return{functionCall:{name:e.name,args:e.args},...t?{thoughtSignature:t}:{}}})),[...o,...a]}function E(e,t,n=!1,r){return e.reduce((i,a,o)=>{if(!d(a))throw Error(`Unsupported message input`);let s=de(a);if(s===`system`&&o!==0)throw Error(`System message should be the first one`);let c=fe(s),l=i.content[i.content.length];if(!i.mergeWithPreviousContent&&l&&l.role===c)throw Error(`Google Generative AI requires alternate messages between authors`);let u=ge(a,t,e.slice(0,o),r);if(i.mergeWithPreviousContent){let e=i.content[i.content.length-1];if(!e)throw Error(`There was a problem parsing your system message. Please try a prompt without one.`);return e.parts.push(...u),{mergeWithPreviousContent:!1,content:i.content}}let f=c;(f===`function`||f===`system`&&!n)&&(f=`user`);let p={role:f,parts:u};return{mergeWithPreviousContent:s===`system`&&!n,content:[...i.content,p]}},{content:[],mergeWithPreviousContent:!1}).content}function _e(e,t){if(!e.candidates||e.candidates.length===0||!e.candidates[0])return{generations:[],llmOutput:{filters:e.promptFeedback}};let[n]=e.candidates,{content:r,...i}=n,a=r.parts?.reduce((e,t)=>(`functionCall`in t&&t.functionCall&&e.push({...t,id:`id`in t.functionCall&&typeof t.functionCall.id==`string`?t.functionCall.id:C()}),e),[]),o,s=r?.parts;o=Array.isArray(s)&&s.length===1&&`text`in s[0]&&s[0].text&&!s[0].thought?s[0].text:Array.isArray(s)&&s.length>0?s.map(e=>e.thought&&`text`in e&&e.text?{type:`thinking`,thinking:e.text,...e.thoughtSignature?{signature:e.thoughtSignature}:{}}:`text`in e?{type:`text`,text:e.text}:`inlineData`in e?{type:`inlineData`,inlineData:e.inlineData}:`functionCall`in e?{type:`functionCall`,functionCall:e.functionCall}:`functionResponse`in e?{type:`functionResponse`,functionResponse:e.functionResponse}:`fileData`in e?{type:`fileData`,fileData:e.fileData}:`executableCode`in e?{type:`executableCode`,executableCode:e.executableCode}:`codeExecutionResult`in e?{type:`codeExecutionResult`,codeExecutionResult:e.codeExecutionResult}:e):[];let c=a?.reduce((e,t)=>(`thoughtSignature`in t&&typeof t.thoughtSignature==`string`&&(e[t.id]=t.thoughtSignature),e),{}),l=``;return typeof o==`string`?l=o:Array.isArray(o)&&o.length>0&&(l=o.find(e=>`text`in e)?.text??l),{generations:[{text:l,message:new p({content:o??``,tool_calls:a?.map(e=>({type:`tool_call`,id:e.id,name:e.functionCall.name,args:e.functionCall.args})),additional_kwargs:{...i,[w]:c},usage_metadata:t?.usageMetadata}),generationInfo:i}],llmOutput:{tokenUsage:{promptTokens:t?.usageMetadata?.input_tokens,completionTokens:t?.usageMetadata?.output_tokens,totalTokens:t?.usageMetadata?.total_tokens}}}}function ve(e,t){if(!e.candidates||e.candidates.length===0)return null;let[n]=e.candidates,{content:r,...i}=n,a=r.parts?.reduce((e,t)=>(`functionCall`in t&&t.functionCall&&e.push({...t,id:`id`in t.functionCall&&typeof t.functionCall.id==`string`?t.functionCall.id:C()}),e),[]),o,s=r?.parts;o=Array.isArray(s)&&s.every(e=>`text`in e&&!e.thought)?s.map(e=>e.text).join(``):Array.isArray(s)?s.map(e=>e.thought&&`text`in e&&e.text?{type:`thinking`,thinking:e.text,...e.thoughtSignature?{signature:e.thoughtSignature}:{}}:`text`in e?{type:`text`,text:e.text}:`inlineData`in e?{type:`inlineData`,inlineData:e.inlineData}:`functionCall`in e?{type:`functionCall`,functionCall:e.functionCall}:`functionResponse`in e?{type:`functionResponse`,functionResponse:e.functionResponse}:`fileData`in e?{type:`fileData`,fileData:e.fileData}:`executableCode`in e?{type:`executableCode`,executableCode:e.executableCode}:`codeExecutionResult`in e?{type:`codeExecutionResult`,codeExecutionResult:e.codeExecutionResult}:e):[];let l=``;o&&typeof o==`string`?l=o:Array.isArray(o)&&(l=o.find(e=>`text`in e)?.text??``);let d=[];a&&d.push(...a.map(e=>({type:`tool_call_chunk`,id:e.id,name:e.functionCall.name,args:JSON.stringify(e.functionCall.args)})));let f=a?.reduce((e,t)=>(`thoughtSignature`in t&&typeof t.thoughtSignature==`string`&&(e[t.id]=t.thoughtSignature),e),{});return new u({text:l,message:new c({content:o||``,name:r?r.role:void 0,tool_call_chunks:d,additional_kwargs:{[w]:f},response_metadata:{model_provider:`google-genai`},usage_metadata:t.usageMetadata}),generationInfo:i})}function ye(e){return e.every(e=>`functionDeclarations`in e&&Array.isArray(e.functionDeclarations))?e:[{functionDeclarations:e.map(e=>{if(g(e)){let t=v(e.schema);return t.type===`object`&&`properties`in t&&Object.keys(t.properties).length===0?{name:e.name,description:e.description}:(y(t,e.name),{name:e.name,description:e.description,parameters:t})}if(h(e)){let t=ae(e.function.parameters);return y(t,e.function.name),{name:e.function.name,description:e.function.description??`A function available to call.`,parameters:t}}return e})}]}function D(e,t){let n={input_tokens:e?.promptTokenCount??0,output_tokens:e?.candidatesTokenCount??0,total_tokens:e?.totalTokenCount??0};if(e?.cachedContentTokenCount&&(n.input_token_details??={},n.input_token_details.cache_read=e.cachedContentTokenCount),t===`gemini-3-pro-preview`){let t=Math.max(0,e?.promptTokenCount??-2e5),r=Math.max(0,e?.cachedContentTokenCount??-2e5);t&&(n.input_token_details={...n.input_token_details,over_200k:t}),r&&(n.input_token_details={...n.input_token_details,cache_read_over_200k:r})}return n}var O=class extends ne{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;let t=await n(this.zodSchema,e);if(t.success)return t.data;throw new te(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(t.error.issues)}`,JSON.stringify(e,null,2))}async parseResult(e){let t=e.flatMap(e=>{let{message:t}=e;return!(`tool_calls`in t)||!Array.isArray(t.tool_calls)?[]:t.tool_calls});if(t[0]===void 0)throw Error(`No parseable tool calls provided to GoogleGenerativeAIToolsOutputParser.`);let[n]=t;return await this._validateResult(n.args)}},be;(function(e){e.STRING=`string`,e.NUMBER=`number`,e.INTEGER=`integer`,e.BOOLEAN=`boolean`,e.ARRAY=`array`,e.OBJECT=`object`})(be||={});var xe;(function(e){e.LANGUAGE_UNSPECIFIED=`language_unspecified`,e.PYTHON=`python`})(xe||={});var Se;(function(e){e.OUTCOME_UNSPECIFIED=`outcome_unspecified`,e.OUTCOME_OK=`outcome_ok`,e.OUTCOME_FAILED=`outcome_failed`,e.OUTCOME_DEADLINE_EXCEEDED=`outcome_deadline_exceeded`})(Se||={});var k=[`user`,`model`,`function`,`system`],Ce;(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`})(Ce||={});var we;(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`})(we||={});var Te;(function(e){e.HARM_PROBABILITY_UNSPECIFIED=`HARM_PROBABILITY_UNSPECIFIED`,e.NEGLIGIBLE=`NEGLIGIBLE`,e.LOW=`LOW`,e.MEDIUM=`MEDIUM`,e.HIGH=`HIGH`})(Te||={});var Ee;(function(e){e.BLOCKED_REASON_UNSPECIFIED=`BLOCKED_REASON_UNSPECIFIED`,e.SAFETY=`SAFETY`,e.OTHER=`OTHER`})(Ee||={});var A;(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`})(A||={});var De;(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`})(De||={});var j;(function(e){e.MODE_UNSPECIFIED=`MODE_UNSPECIFIED`,e.AUTO=`AUTO`,e.ANY=`ANY`,e.NONE=`NONE`})(j||={});var Oe;(function(e){e.MODE_UNSPECIFIED=`MODE_UNSPECIFIED`,e.MODE_DYNAMIC=`MODE_DYNAMIC`})(Oe||={});var M=class extends Error{constructor(e){super(`[GoogleGenerativeAI Error]: ${e}`)}},N=class extends M{constructor(e,t){super(e),this.response=t}},P=class extends M{constructor(e,t,n,r){super(e),this.status=t,this.statusText=n,this.errorDetails=r}},F=class extends M{},I=class extends M{},ke=`https://generativelanguage.googleapis.com`,Ae=`v1beta`,je=`0.24.1`,Me=`genai-js`,L;(function(e){e.GENERATE_CONTENT=`generateContent`,e.STREAM_GENERATE_CONTENT=`streamGenerateContent`,e.COUNT_TOKENS=`countTokens`,e.EMBED_CONTENT=`embedContent`,e.BATCH_EMBED_CONTENTS=`batchEmbedContents`})(L||={});var Ne=class{constructor(e,t,n,r,i){this.model=e,this.task=t,this.apiKey=n,this.stream=r,this.requestOptions=i}toString(){let e=this.requestOptions?.apiVersion||Ae,t=`${this.requestOptions?.baseUrl||ke}/${e}/${this.model}:${this.task}`;return this.stream&&(t+=`?alt=sse`),t}};function Pe(e){let t=[];return e?.apiClient&&t.push(e.apiClient),t.push(`${Me}/${je}`),t.join(` `)}async function Fe(e){let t=new Headers;t.append(`Content-Type`,`application/json`),t.append(`x-goog-api-client`,Pe(e.requestOptions)),t.append(`x-goog-api-key`,e.apiKey);let n=e.requestOptions?.customHeaders;if(n){if(!(n instanceof Headers))try{n=new Headers(n)}catch(e){throw new F(`unable to convert customHeaders value ${JSON.stringify(n)} to Headers: ${e.message}`)}for(let[e,r]of n.entries()){if(e===`x-goog-api-key`)throw new F(`Cannot set reserved header name ${e}`);if(e===`x-goog-api-client`)throw new F(`Header name ${e} can only be set using the apiClient field`);t.append(e,r)}}return t}async function Ie(e,t,n,r,i,a){let o=new Ne(e,t,n,r,a);return{url:o.toString(),fetchOptions:Object.assign(Object.assign({},Be(a)),{method:`POST`,headers:await Fe(o),body:i})}}async function R(e,t,n,r,i,a={},o=fetch){let{url:s,fetchOptions:c}=await Ie(e,t,n,r,i,a);return Le(s,c,o)}async function Le(e,t,n=fetch){let r;try{r=await n(e,t)}catch(t){Re(t,e)}return r.ok||await ze(r,e),r}function Re(e,t){let n=e;throw n.name===`AbortError`?(n=new I(`Request aborted when fetching ${t.toString()}: ${e.message}`),n.stack=e.stack):e instanceof P||e instanceof F||(n=new M(`Error fetching from ${t.toString()}: ${e.message}`),n.stack=e.stack),n}async function ze(e,t){let n=``,r;try{let t=await e.json();n=t.error.message,t.error.details&&(n+=` ${JSON.stringify(t.error.details)}`,r=t.error.details)}catch{}throw new P(`Error fetching from ${t.toString()}: [${e.status} ${e.statusText}] ${n}`,e.status,e.statusText,r)}function Be(e){let t={};if(e?.signal!==void 0||e?.timeout>=0){let n=new AbortController;e?.timeout>=0&&setTimeout(()=>n.abort(),e.timeout),e?.signal&&e.signal.addEventListener(`abort`,()=>{n.abort()}),t.signal=n.signal}return t}function z(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.`),V(e.candidates[0]))throw new N(`${H(e)}`,e);return Ve(e)}else if(e.promptFeedback)throw new N(`Text not available. ${H(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.`),V(e.candidates[0]))throw new N(`${H(e)}`,e);return console.warn(`response.functionCall() is deprecated. Use response.functionCalls() instead.`),B(e)[0]}else if(e.promptFeedback)throw new N(`Function call not available. ${H(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.`),V(e.candidates[0]))throw new N(`${H(e)}`,e);return B(e)}else if(e.promptFeedback)throw new N(`Function call not available. ${H(e)}`,e)},e}function Ve(e){let t=[];if(e.candidates?.[0].content?.parts)for(let n of e.candidates?.[0].content?.parts)n.text&&t.push(n.text),n.executableCode&&t.push("\n```"+n.executableCode.language+`
|
|
1
|
+
import{En as e,G as t,I as n,Kt as r,Pn as i,cr as a,fr as o,g as s,nn as c,or as l,ot as u,qn as d,rn as f,tn as p,w as ee}from"./index-zqVFP8t5.js";import{A as te,M as m,O as ne,p as h,r as g,s as re,w as ie}from"./function_calling-XyGNNvjR.js";import"./chunk_array-cMM4je5w.js";function _(e){if(typeof e==`object`&&e){let t={...e};`additionalProperties`in t&&delete t.additionalProperties,`$schema`in t&&delete t.$schema,`strict`in t&&delete t.strict;for(let e in t)e in t&&(Array.isArray(t[e])?t[e]=t[e].map(_):typeof t[e]==`object`&&t[e]!==null&&(t[e]=_(t[e])));return t}return e}function v(e){let{$schema:n,...r}=_(t(e)?ee(e):e);return r}function ae(e){let{$schema:t,...n}=_(e);return n}function y(e,t,n=[]){if(typeof e!=`object`||!e)return;let r=e;if(Array.isArray(r.enum)&&r.enum.some(e=>e===``)){let e=n.length?` at path "${n.join(`.`)}"`:``,r=t?` in tool "${t}"`:``;throw Error(`Invalid enum: empty string not allowed${r}${e}. Gemini API rejects empty strings in enums.`)}if(r.type===`object`&&r.properties&&typeof r.properties==`object`)for(let[e,i]of Object.entries(r.properties))y(i,t,[...n,e]);r.items&&y(r.items,t,[...n,`[]`]);for(let e of[`anyOf`,`oneOf`,`allOf`]){let i=r[e];Array.isArray(i)&&i.forEach((r,i)=>y(r,t,[...n,`${e}[${i}]`]))}r.additionalProperties&&typeof r.additionalProperties==`object`&&y(r.additionalProperties,t,[...n,`additionalProperties`])}var b=[];for(let e=0;e<256;++e)b.push((e+256).toString(16).slice(1));function oe(e,t=0){return(b[e[t+0]]+b[e[t+1]]+b[e[t+2]]+b[e[t+3]]+`-`+b[e[t+4]]+b[e[t+5]]+`-`+b[e[t+6]]+b[e[t+7]]+`-`+b[e[t+8]]+b[e[t+9]]+`-`+b[e[t+10]]+b[e[t+11]]+b[e[t+12]]+b[e[t+13]]+b[e[t+14]]+b[e[t+15]]).toLowerCase()}var x,se=new Uint8Array(16);function ce(){if(!x){if(typeof crypto>`u`||!crypto.getRandomValues)throw Error(`crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported`);x=crypto.getRandomValues.bind(crypto)}return x(se)}var S={randomUUID:typeof crypto<`u`&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function C(e,t,n){if(S.randomUUID&&!t&&!e)return S.randomUUID();e||={};let r=e.random??e.rng?.()??ce();if(r.length<16)throw Error(`Random bytes length must be >= 16`);if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,t){if(n||=0,n<0||n+16>t.length)throw RangeError(`UUID byte range ${n}:${n+15} is out of buffer bounds`);for(let e=0;e<16;++e)t[n+e]=r[e];return t}return oe(r)}var w=`__gemini_function_call_thought_signatures__`,le=`ErYCCrMCAdHtim9kOoOkrPiCNVsmlpMIKd7ZMxgiFbVQOkgp7nlLcDMzVsZwIzvuT7nQROivoXA72ccC2lSDvR0Gh7dkWaGuj7ctv6t7ZceHnecx0QYa+ix8tYpRfjhyWozQ49lWiws6+YGjCt10KRTyWsZ2h6O7iHTYJwKIRwGUHRKy/qK/6kFxJm5ML00gLq4D8s5Z6DBpp2ZlR+uF4G8jJgeWQgyHWVdx2wGYElaceVAc66tZdPQRdOHpWtgYSI1YdaXgVI8KHY3/EfNc2YqqMIulvkDBAnuMhkAjV9xmBa54Tq+ih3Im4+r3DzqhGqYdsSkhS0kZMwte4Hjs65dZzCw9lANxIqYi1DJ639WNPYihp/DCJCos7o+/EeSPJaio5sgWDyUnMGkY1atsJZ+m7pj7DD5tvQ==`,ue=e=>e();function de(t){return e.isInstance(t)?t.role:t.type}function fe(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 Error(`Unknown / unsupported author: ${e}`)}}function pe(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 Error(`Invalid media content`)}function me(e,t){return t.map(e=>f(e)?e.tool_calls??[]:[]).flat().find(t=>t.id===e.tool_call_id)?.name}function he(e){return{providerName:`Google Gemini`,fromStandardTextBlock(e){return{text:e.text}},fromStandardImageBlock(t){if(!e)throw Error(`This model does not support images`);if(t.source_type===`url`){let e=o({dataUrl:t.url});return e?{inlineData:{mimeType:e.mime_type,data:e.data}}:{fileData:{mimeType:t.mime_type??``,fileUri:t.url}}}if(t.source_type===`base64`)return{inlineData:{mimeType:t.mime_type??``,data:t.data}};throw Error(`Unsupported source type: ${t.source_type}`)},fromStandardAudioBlock(t){if(!e)throw Error(`This model does not support audio`);if(t.source_type===`url`){let e=o({dataUrl:t.url});return e?{inlineData:{mimeType:e.mime_type,data:e.data}}:{fileData:{mimeType:t.mime_type??``,fileUri:t.url}}}if(t.source_type===`base64`)return{inlineData:{mimeType:t.mime_type??``,data:t.data}};throw Error(`Unsupported source type: ${t.source_type}`)},fromStandardFileBlock(t){if(!e)throw Error(`This model does not support files`);if(t.source_type===`text`)return{text:t.text};if(t.source_type===`url`){let e=o({dataUrl:t.url});return e?{inlineData:{mimeType:e.mime_type,data:e.data}}:{fileData:{mimeType:t.mime_type??``,fileUri:t.url}}}if(t.source_type===`base64`)return{inlineData:{mimeType:t.mime_type??``,data:t.data}};throw Error(`Unsupported source type: ${t.source_type}`)}}}function T(e,t){if(a(e))return l(e,he(t));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(!t)throw Error(`This model does not support images`);let n;if(typeof e.image_url==`string`)n=e.image_url;else if(typeof e.image_url==`object`&&`url`in e.image_url)n=e.image_url.url;else throw Error(`Please provide image as base64 encoded data URL`);let[r,i]=n.split(`,`);if(!r.startsWith(`data:`))throw Error(`Please provide image as base64 encoded data URL`);let[a,o]=r.replace(/^data:/,``).split(`;`);if(o!==`base64`)throw Error(`Please provide image as base64 encoded data URL`);return{inlineData:{data:i,mimeType:a}}}else if(e.type===`media`)return pe(e);else if(e.type===`tool_use`)return{functionCall:{name:e.name,args:e.input}};else if(e.type===`tool_call`)return{functionCall:{name:e.name,args:e.args}};else if(e.type?.includes(`/`)&&e.type.split(`/`).length===2&&`data`in e&&typeof e.data==`string`)return{inlineData:{mimeType:e.type,data:e.data}};else if(`functionCall`in e)return;else if(`type`in e)throw Error(`Unknown content type ${e.type}`);else throw Error(`Unknown content ${JSON.stringify(e)}`)}function ge(e,t,n,r){if(i(e)){let r=e.name??me(e,n);if(r===void 0)throw 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.`);let i=Array.isArray(e.content)?e.content.map(e=>T(e,t)).filter(e=>e!==void 0):e.content;return e.status===`error`?[{functionResponse:{name:r,response:{error:{details:i}}}}]:[{functionResponse:{name:r,response:{result:i}}}]}let a=[],o=[];typeof e.content==`string`&&e.content&&o.push({text:e.content}),Array.isArray(e.content)&&o.push(...e.content.map(e=>T(e,t)).filter(e=>e!==void 0));let s=e.additional_kwargs?.[w];return f(e)&&e.tool_calls?.length&&(a=e.tool_calls.map(e=>{let t=ue(()=>{if(e.id){let t=s?.[e.id];if(t)return t}return r?.includes(`gemini-3`)?le:``});return{functionCall:{name:e.name,args:e.args},...t?{thoughtSignature:t}:{}}})),[...o,...a]}function E(e,t,n=!1,r){return e.reduce((i,a,o)=>{if(!d(a))throw Error(`Unsupported message input`);let s=de(a);if(s===`system`&&o!==0)throw Error(`System message should be the first one`);let c=fe(s),l=i.content[i.content.length];if(!i.mergeWithPreviousContent&&l&&l.role===c)throw Error(`Google Generative AI requires alternate messages between authors`);let u=ge(a,t,e.slice(0,o),r);if(i.mergeWithPreviousContent){let e=i.content[i.content.length-1];if(!e)throw Error(`There was a problem parsing your system message. Please try a prompt without one.`);return e.parts.push(...u),{mergeWithPreviousContent:!1,content:i.content}}let f=c;(f===`function`||f===`system`&&!n)&&(f=`user`);let p={role:f,parts:u};return{mergeWithPreviousContent:s===`system`&&!n,content:[...i.content,p]}},{content:[],mergeWithPreviousContent:!1}).content}function _e(e,t){if(!e.candidates||e.candidates.length===0||!e.candidates[0])return{generations:[],llmOutput:{filters:e.promptFeedback}};let[n]=e.candidates,{content:r,...i}=n,a=r.parts?.reduce((e,t)=>(`functionCall`in t&&t.functionCall&&e.push({...t,id:`id`in t.functionCall&&typeof t.functionCall.id==`string`?t.functionCall.id:C()}),e),[]),o,s=r?.parts;o=Array.isArray(s)&&s.length===1&&`text`in s[0]&&s[0].text&&!s[0].thought?s[0].text:Array.isArray(s)&&s.length>0?s.map(e=>e.thought&&`text`in e&&e.text?{type:`thinking`,thinking:e.text,...e.thoughtSignature?{signature:e.thoughtSignature}:{}}:`text`in e?{type:`text`,text:e.text}:`inlineData`in e?{type:`inlineData`,inlineData:e.inlineData}:`functionCall`in e?{type:`functionCall`,functionCall:e.functionCall}:`functionResponse`in e?{type:`functionResponse`,functionResponse:e.functionResponse}:`fileData`in e?{type:`fileData`,fileData:e.fileData}:`executableCode`in e?{type:`executableCode`,executableCode:e.executableCode}:`codeExecutionResult`in e?{type:`codeExecutionResult`,codeExecutionResult:e.codeExecutionResult}:e):[];let c=a?.reduce((e,t)=>(`thoughtSignature`in t&&typeof t.thoughtSignature==`string`&&(e[t.id]=t.thoughtSignature),e),{}),l=``;return typeof o==`string`?l=o:Array.isArray(o)&&o.length>0&&(l=o.find(e=>`text`in e)?.text??l),{generations:[{text:l,message:new p({content:o??``,tool_calls:a?.map(e=>({type:`tool_call`,id:e.id,name:e.functionCall.name,args:e.functionCall.args})),additional_kwargs:{...i,[w]:c},usage_metadata:t?.usageMetadata}),generationInfo:i}],llmOutput:{tokenUsage:{promptTokens:t?.usageMetadata?.input_tokens,completionTokens:t?.usageMetadata?.output_tokens,totalTokens:t?.usageMetadata?.total_tokens}}}}function ve(e,t){if(!e.candidates||e.candidates.length===0)return null;let[n]=e.candidates,{content:r,...i}=n,a=r.parts?.reduce((e,t)=>(`functionCall`in t&&t.functionCall&&e.push({...t,id:`id`in t.functionCall&&typeof t.functionCall.id==`string`?t.functionCall.id:C()}),e),[]),o,s=r?.parts;o=Array.isArray(s)&&s.every(e=>`text`in e&&!e.thought)?s.map(e=>e.text).join(``):Array.isArray(s)?s.map(e=>e.thought&&`text`in e&&e.text?{type:`thinking`,thinking:e.text,...e.thoughtSignature?{signature:e.thoughtSignature}:{}}:`text`in e?{type:`text`,text:e.text}:`inlineData`in e?{type:`inlineData`,inlineData:e.inlineData}:`functionCall`in e?{type:`functionCall`,functionCall:e.functionCall}:`functionResponse`in e?{type:`functionResponse`,functionResponse:e.functionResponse}:`fileData`in e?{type:`fileData`,fileData:e.fileData}:`executableCode`in e?{type:`executableCode`,executableCode:e.executableCode}:`codeExecutionResult`in e?{type:`codeExecutionResult`,codeExecutionResult:e.codeExecutionResult}:e):[];let l=``;o&&typeof o==`string`?l=o:Array.isArray(o)&&(l=o.find(e=>`text`in e)?.text??``);let d=[];a&&d.push(...a.map(e=>({type:`tool_call_chunk`,id:e.id,name:e.functionCall.name,args:JSON.stringify(e.functionCall.args)})));let f=a?.reduce((e,t)=>(`thoughtSignature`in t&&typeof t.thoughtSignature==`string`&&(e[t.id]=t.thoughtSignature),e),{});return new u({text:l,message:new c({content:o||``,name:r?r.role:void 0,tool_call_chunks:d,additional_kwargs:{[w]:f},response_metadata:{model_provider:`google-genai`},usage_metadata:t.usageMetadata}),generationInfo:i})}function ye(e){return e.every(e=>`functionDeclarations`in e&&Array.isArray(e.functionDeclarations))?e:[{functionDeclarations:e.map(e=>{if(g(e)){let t=v(e.schema);return t.type===`object`&&`properties`in t&&Object.keys(t.properties).length===0?{name:e.name,description:e.description}:(y(t,e.name),{name:e.name,description:e.description,parameters:t})}if(h(e)){let t=ae(e.function.parameters);return y(t,e.function.name),{name:e.function.name,description:e.function.description??`A function available to call.`,parameters:t}}return e})}]}function D(e,t){let n={input_tokens:e?.promptTokenCount??0,output_tokens:e?.candidatesTokenCount??0,total_tokens:e?.totalTokenCount??0};if(e?.cachedContentTokenCount&&(n.input_token_details??={},n.input_token_details.cache_read=e.cachedContentTokenCount),t===`gemini-3-pro-preview`){let t=Math.max(0,e?.promptTokenCount??-2e5),r=Math.max(0,e?.cachedContentTokenCount??-2e5);t&&(n.input_token_details={...n.input_token_details,over_200k:t}),r&&(n.input_token_details={...n.input_token_details,cache_read_over_200k:r})}return n}var O=class extends ne{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;let t=await n(this.zodSchema,e);if(t.success)return t.data;throw new te(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(t.error.issues)}`,JSON.stringify(e,null,2))}async parseResult(e){let t=e.flatMap(e=>{let{message:t}=e;return!(`tool_calls`in t)||!Array.isArray(t.tool_calls)?[]:t.tool_calls});if(t[0]===void 0)throw Error(`No parseable tool calls provided to GoogleGenerativeAIToolsOutputParser.`);let[n]=t;return await this._validateResult(n.args)}},be;(function(e){e.STRING=`string`,e.NUMBER=`number`,e.INTEGER=`integer`,e.BOOLEAN=`boolean`,e.ARRAY=`array`,e.OBJECT=`object`})(be||={});var xe;(function(e){e.LANGUAGE_UNSPECIFIED=`language_unspecified`,e.PYTHON=`python`})(xe||={});var Se;(function(e){e.OUTCOME_UNSPECIFIED=`outcome_unspecified`,e.OUTCOME_OK=`outcome_ok`,e.OUTCOME_FAILED=`outcome_failed`,e.OUTCOME_DEADLINE_EXCEEDED=`outcome_deadline_exceeded`})(Se||={});var k=[`user`,`model`,`function`,`system`],Ce;(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`})(Ce||={});var we;(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`})(we||={});var Te;(function(e){e.HARM_PROBABILITY_UNSPECIFIED=`HARM_PROBABILITY_UNSPECIFIED`,e.NEGLIGIBLE=`NEGLIGIBLE`,e.LOW=`LOW`,e.MEDIUM=`MEDIUM`,e.HIGH=`HIGH`})(Te||={});var Ee;(function(e){e.BLOCKED_REASON_UNSPECIFIED=`BLOCKED_REASON_UNSPECIFIED`,e.SAFETY=`SAFETY`,e.OTHER=`OTHER`})(Ee||={});var A;(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`})(A||={});var De;(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`})(De||={});var j;(function(e){e.MODE_UNSPECIFIED=`MODE_UNSPECIFIED`,e.AUTO=`AUTO`,e.ANY=`ANY`,e.NONE=`NONE`})(j||={});var Oe;(function(e){e.MODE_UNSPECIFIED=`MODE_UNSPECIFIED`,e.MODE_DYNAMIC=`MODE_DYNAMIC`})(Oe||={});var M=class extends Error{constructor(e){super(`[GoogleGenerativeAI Error]: ${e}`)}},N=class extends M{constructor(e,t){super(e),this.response=t}},P=class extends M{constructor(e,t,n,r){super(e),this.status=t,this.statusText=n,this.errorDetails=r}},F=class extends M{},I=class extends M{},ke=`https://generativelanguage.googleapis.com`,Ae=`v1beta`,je=`0.24.1`,Me=`genai-js`,L;(function(e){e.GENERATE_CONTENT=`generateContent`,e.STREAM_GENERATE_CONTENT=`streamGenerateContent`,e.COUNT_TOKENS=`countTokens`,e.EMBED_CONTENT=`embedContent`,e.BATCH_EMBED_CONTENTS=`batchEmbedContents`})(L||={});var Ne=class{constructor(e,t,n,r,i){this.model=e,this.task=t,this.apiKey=n,this.stream=r,this.requestOptions=i}toString(){let e=this.requestOptions?.apiVersion||Ae,t=`${this.requestOptions?.baseUrl||ke}/${e}/${this.model}:${this.task}`;return this.stream&&(t+=`?alt=sse`),t}};function Pe(e){let t=[];return e?.apiClient&&t.push(e.apiClient),t.push(`${Me}/${je}`),t.join(` `)}async function Fe(e){let t=new Headers;t.append(`Content-Type`,`application/json`),t.append(`x-goog-api-client`,Pe(e.requestOptions)),t.append(`x-goog-api-key`,e.apiKey);let n=e.requestOptions?.customHeaders;if(n){if(!(n instanceof Headers))try{n=new Headers(n)}catch(e){throw new F(`unable to convert customHeaders value ${JSON.stringify(n)} to Headers: ${e.message}`)}for(let[e,r]of n.entries()){if(e===`x-goog-api-key`)throw new F(`Cannot set reserved header name ${e}`);if(e===`x-goog-api-client`)throw new F(`Header name ${e} can only be set using the apiClient field`);t.append(e,r)}}return t}async function Ie(e,t,n,r,i,a){let o=new Ne(e,t,n,r,a);return{url:o.toString(),fetchOptions:Object.assign(Object.assign({},Be(a)),{method:`POST`,headers:await Fe(o),body:i})}}async function R(e,t,n,r,i,a={},o=fetch){let{url:s,fetchOptions:c}=await Ie(e,t,n,r,i,a);return Le(s,c,o)}async function Le(e,t,n=fetch){let r;try{r=await n(e,t)}catch(t){Re(t,e)}return r.ok||await ze(r,e),r}function Re(e,t){let n=e;throw n.name===`AbortError`?(n=new I(`Request aborted when fetching ${t.toString()}: ${e.message}`),n.stack=e.stack):e instanceof P||e instanceof F||(n=new M(`Error fetching from ${t.toString()}: ${e.message}`),n.stack=e.stack),n}async function ze(e,t){let n=``,r;try{let t=await e.json();n=t.error.message,t.error.details&&(n+=` ${JSON.stringify(t.error.details)}`,r=t.error.details)}catch{}throw new P(`Error fetching from ${t.toString()}: [${e.status} ${e.statusText}] ${n}`,e.status,e.statusText,r)}function Be(e){let t={};if(e?.signal!==void 0||e?.timeout>=0){let n=new AbortController;e?.timeout>=0&&setTimeout(()=>n.abort(),e.timeout),e?.signal&&e.signal.addEventListener(`abort`,()=>{n.abort()}),t.signal=n.signal}return t}function z(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.`),V(e.candidates[0]))throw new N(`${H(e)}`,e);return Ve(e)}else if(e.promptFeedback)throw new N(`Text not available. ${H(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.`),V(e.candidates[0]))throw new N(`${H(e)}`,e);return console.warn(`response.functionCall() is deprecated. Use response.functionCalls() instead.`),B(e)[0]}else if(e.promptFeedback)throw new N(`Function call not available. ${H(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.`),V(e.candidates[0]))throw new N(`${H(e)}`,e);return B(e)}else if(e.promptFeedback)throw new N(`Function call not available. ${H(e)}`,e)},e}function Ve(e){let t=[];if(e.candidates?.[0].content?.parts)for(let n of e.candidates?.[0].content?.parts)n.text&&t.push(n.text),n.executableCode&&t.push("\n```"+n.executableCode.language+`
|
|
2
2
|
`+n.executableCode.code+"\n```\n"),n.codeExecutionResult&&t.push("\n```\n"+n.codeExecutionResult.output+"\n```\n");return t.length>0?t.join(``):``}function B(e){let t=[];if(e.candidates?.[0].content?.parts)for(let n of e.candidates?.[0].content?.parts)n.functionCall&&t.push(n.functionCall);if(t.length>0)return t}var He=[A.RECITATION,A.SAFETY,A.LANGUAGE];function V(e){return!!e.finishReason&&He.includes(e.finishReason)}function H(e){let t=``;if((!e.candidates||e.candidates.length===0)&&e.promptFeedback)t+=`Response was blocked`,e.promptFeedback?.blockReason&&(t+=` due to ${e.promptFeedback.blockReason}`),e.promptFeedback?.blockReasonMessage&&(t+=`: ${e.promptFeedback.blockReasonMessage}`);else if(e.candidates?.[0]){let n=e.candidates[0];V(n)&&(t+=`Candidate was blocked due to ${n.finishReason}`,n.finishMessage&&(t+=`: ${n.finishMessage}`))}return t}function U(e){return this instanceof U?(this.v=e,this):new U(e)}function Ue(e,t,n){if(!Symbol.asyncIterator)throw TypeError(`Symbol.asyncIterator is not defined.`);var r=n.apply(e,t||[]),i,a=[];return i={},o(`next`),o(`throw`),o(`return`),i[Symbol.asyncIterator]=function(){return this},i;function o(e){r[e]&&(i[e]=function(t){return new Promise(function(n,r){a.push([e,t,n,r])>1||s(e,t)})})}function s(e,t){try{c(r[e](t))}catch(e){d(a[0][3],e)}}function c(e){e.value instanceof U?Promise.resolve(e.value.v).then(l,u):d(a[0][2],e)}function l(e){s(`next`,e)}function u(e){s(`throw`,e)}function d(e,t){e(t),a.shift(),a.length&&s(a[0][0],a[0][1])}}var W=/^data\: (.*)(?:\n\n|\r\r|\r\n\r\n)/;function We(e){let[t,n]=qe(e.body.pipeThrough(new TextDecoderStream(`utf8`,{fatal:!0}))).tee();return{stream:Ke(t),response:Ge(n)}}async function Ge(e){let t=[],n=e.getReader();for(;;){let{done:e,value:r}=await n.read();if(e)return z(Je(t));t.push(r)}}function Ke(e){return Ue(this,arguments,function*(){let t=e.getReader();for(;;){let{value:e,done:n}=yield U(t.read());if(n)break;yield yield U(z(e))}})}function qe(e){let t=e.getReader();return new ReadableStream({start(e){let n=``;return r();function r(){return t.read().then(({value:t,done:i})=>{if(i){if(n.trim()){e.error(new M(`Failed to parse stream`));return}e.close();return}n+=t;let a=n.match(W),o;for(;a;){try{o=JSON.parse(a[1])}catch{e.error(new M(`Error parsing JSON response: "${a[1]}"`));return}e.enqueue(o),n=n.substring(a[0].length),a=n.match(W)}return r()}).catch(e=>{let t=e;throw t.stack=e.stack,t=t.name===`AbortError`?new I(`Request aborted when reading from the stream`):new M(`Error reading from the stream`),t})}}})}function Je(e){let t={promptFeedback:e[e.length-1]?.promptFeedback};for(let n of e){if(n.candidates){let e=0;for(let r of n.candidates)if(t.candidates||=[],t.candidates[e]||(t.candidates[e]={index:e}),t.candidates[e].citationMetadata=r.citationMetadata,t.candidates[e].groundingMetadata=r.groundingMetadata,t.candidates[e].finishReason=r.finishReason,t.candidates[e].finishMessage=r.finishMessage,t.candidates[e].safetyRatings=r.safetyRatings,r.content&&r.content.parts){t.candidates[e].content||(t.candidates[e].content={role:r.content.role||`user`,parts:[]});let n={};for(let i of r.content.parts)i.text&&(n.text=i.text),i.functionCall&&(n.functionCall=i.functionCall),i.executableCode&&(n.executableCode=i.executableCode),i.codeExecutionResult&&(n.codeExecutionResult=i.codeExecutionResult),Object.keys(n).length===0&&(n.text=``),t.candidates[e].content.parts.push(n)}e++}n.usageMetadata&&(t.usageMetadata=n.usageMetadata)}return t}async function G(e,t,n,r){return We(await R(t,L.STREAM_GENERATE_CONTENT,e,!0,JSON.stringify(n),r))}async function K(e,t,n,r){return{response:z(await(await R(t,L.GENERATE_CONTENT,e,!1,JSON.stringify(n),r)).json())}}function q(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 J(e){let t=[];if(typeof e==`string`)t=[{text:e}];else for(let n of e)typeof n==`string`?t.push({text:n}):t.push(n);return Ye(t)}function Ye(e){let t={role:`user`,parts:[]},n={role:`function`,parts:[]},r=!1,i=!1;for(let a of e)`functionResponse`in a?(n.parts.push(a),i=!0):(t.parts.push(a),r=!0);if(r&&i)throw new M(`Within a single message, FunctionResponse cannot be mixed with other type of part in the request for sending chat message.`);if(!r&&!i)throw new M(`No content is provided for sending chat message.`);return r?t:n}function Xe(e,t){let n={model:t?.model,generationConfig:t?.generationConfig,safetySettings:t?.safetySettings,tools:t?.tools,toolConfig:t?.toolConfig,systemInstruction:t?.systemInstruction,cachedContent:t?.cachedContent?.name,contents:[]},r=e.generateContentRequest!=null;if(e.contents){if(r)throw new F(`CountTokensRequest must have one of contents or generateContentRequest, not both.`);n.contents=e.contents}else if(r)n=Object.assign(Object.assign({},n),e.generateContentRequest);else{let t=J(e);n.contents=[t]}return{generateContentRequest:n}}function Y(e){let t;return t=e.contents?e:{contents:[J(e)]},e.systemInstruction&&(t.systemInstruction=q(e.systemInstruction)),t}function Ze(e){return typeof e==`string`||Array.isArray(e)?{content:J(e)}:e}var X=[`text`,`inlineData`,`functionCall`,`functionResponse`,`executableCode`,`codeExecutionResult`],Qe={user:[`text`,`inlineData`],function:[`functionResponse`],model:[`text`,`functionCall`,`executableCode`,`codeExecutionResult`],system:[`text`]};function $e(e){let t=!1;for(let n of e){let{role:e,parts:r}=n;if(!t&&e!==`user`)throw new M(`First content should be with role 'user', got ${e}`);if(!k.includes(e))throw new M(`Each item should include role field. Got ${e} but valid roles are: ${JSON.stringify(k)}`);if(!Array.isArray(r))throw new M(`Content should have 'parts' property with an array of Parts`);if(r.length===0)throw new M(`Each Content should have at least one part`);let i={text:0,inlineData:0,functionCall:0,functionResponse:0,fileData:0,executableCode:0,codeExecutionResult:0};for(let e of r)for(let t of X)t in e&&(i[t]+=1);let a=Qe[e];for(let t of X)if(!a.includes(t)&&i[t]>0)throw new M(`Content with role '${e}' can't contain '${t}' part`);t=!0}}function Z(e){if(e.candidates===void 0||e.candidates.length===0)return!1;let t=e.candidates[0]?.content;if(t===void 0||t.parts===void 0||t.parts.length===0)return!1;for(let e of t.parts)if(e===void 0||Object.keys(e).length===0||e.text!==void 0&&e.text===``)return!1;return!0}var Q=`SILENT_ERROR`,et=class{constructor(e,t,n,r={}){this.model=t,this.params=n,this._requestOptions=r,this._history=[],this._sendPromise=Promise.resolve(),this._apiKey=e,n?.history&&($e(n.history),this._history=n.history)}async getHistory(){return await this._sendPromise,this._history}async sendMessage(e,t={}){await this._sendPromise;let n=J(e),r={safetySettings:this.params?.safetySettings,generationConfig:this.params?.generationConfig,tools:this.params?.tools,toolConfig:this.params?.toolConfig,systemInstruction:this.params?.systemInstruction,cachedContent:this.params?.cachedContent,contents:[...this._history,n]},i=Object.assign(Object.assign({},this._requestOptions),t),a;return this._sendPromise=this._sendPromise.then(()=>K(this._apiKey,this.model,r,i)).then(e=>{if(Z(e.response)){this._history.push(n);let t=Object.assign({parts:[],role:`model`},e.response.candidates?.[0].content);this._history.push(t)}else{let t=H(e.response);t&&console.warn(`sendMessage() was unsuccessful. ${t}. Inspect response object for details.`)}a=e}).catch(e=>{throw this._sendPromise=Promise.resolve(),e}),await this._sendPromise,a}async sendMessageStream(e,t={}){await this._sendPromise;let n=J(e),r={safetySettings:this.params?.safetySettings,generationConfig:this.params?.generationConfig,tools:this.params?.tools,toolConfig:this.params?.toolConfig,systemInstruction:this.params?.systemInstruction,cachedContent:this.params?.cachedContent,contents:[...this._history,n]},i=Object.assign(Object.assign({},this._requestOptions),t),a=G(this._apiKey,this.model,r,i);return this._sendPromise=this._sendPromise.then(()=>a).catch(e=>{throw Error(Q)}).then(e=>e.response).then(e=>{if(Z(e)){this._history.push(n);let t=Object.assign({},e.candidates[0].content);t.role||=`model`,this._history.push(t)}else{let t=H(e);t&&console.warn(`sendMessageStream() was unsuccessful. ${t}. Inspect response object for details.`)}}).catch(e=>{e.message!==Q&&console.error(e)}),a}};async function tt(e,t,n,r){return(await R(t,L.COUNT_TOKENS,e,!1,JSON.stringify(n),r)).json()}async function nt(e,t,n,r){return(await R(t,L.EMBED_CONTENT,e,!1,JSON.stringify(n),r)).json()}async function rt(e,t,n,r){let i=n.requests.map(e=>Object.assign(Object.assign({},e),{model:t}));return(await R(t,L.BATCH_EMBED_CONTENTS,e,!1,JSON.stringify({requests:i}),r)).json()}var $=class{constructor(e,t,n={}){this.apiKey=e,this._requestOptions=n,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=q(t.systemInstruction),this.cachedContent=t.cachedContent}async generateContent(e,t={}){let n=Y(e),r=Object.assign(Object.assign({},this._requestOptions),t);return K(this.apiKey,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:this.cachedContent?.name},n),r)}async generateContentStream(e,t={}){let n=Y(e),r=Object.assign(Object.assign({},this._requestOptions),t);return G(this.apiKey,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:this.cachedContent?.name},n),r)}startChat(e){return new et(this.apiKey,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:this.cachedContent?.name},e),this._requestOptions)}async countTokens(e,t={}){let n=Xe(e,{model:this.model,generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:this.cachedContent}),r=Object.assign(Object.assign({},this._requestOptions),t);return tt(this.apiKey,this.model,n,r)}async embedContent(e,t={}){let n=Ze(e),r=Object.assign(Object.assign({},this._requestOptions),t);return nt(this.apiKey,this.model,n,r)}async batchEmbedContents(e,t={}){let n=Object.assign(Object.assign({},this._requestOptions),t);return rt(this.apiKey,this.model,e,n)}},it=class{constructor(e){this.apiKey=e}getGenerativeModel(e,t){if(!e.model)throw new M(`Must provide a model name. Example: genai.getGenerativeModel({ model: 'my-model-name' })`);return new $(this.apiKey,e,t)}getGenerativeModelFromCachedContent(e,t,n){if(!e.name)throw new F("Cached content must contain a `name` field.");if(!e.model)throw new F("Cached content must contain a `model` field.");for(let n of[`model`,`systemInstruction`])if(t?.[n]&&e[n]&&t?.[n]!==e[n]){if(n===`model`&&(t.model.startsWith(`models/`)?t.model.replace(`models/`,``):t.model)===(e.model.startsWith(`models/`)?e.model.replace(`models/`,``):e.model))continue;throw new F(`Different value for "${n}" specified in modelParams (${t[n]}) and cachedContent (${e[n]})`)}let r=Object.assign(Object.assign({},t),{model:e.model,tools:e.tools,toolConfig:e.toolConfig,systemInstruction:e.systemInstruction,cachedContent:e});return new $(this.apiKey,r,n)}};function at(e,t){let n=ot(e);return{tools:n,toolConfig:ct(n,t)}}function ot(e){let t=[],n=[];return e.forEach(e=>{if(g(e)){let[n]=ye([e]);n.functionDeclarations&&t.push(...n.functionDeclarations)}else if(h(e)){let{functionDeclarations:n}=st(e);if(n)t.push(...n);else throw Error(`Failed to convert OpenAI structured tool to GenerativeAI tool`)}else n.push(e)}),n.find(e=>`functionDeclarations`in e)?n.map(e=>{if(t?.length>0&&`functionDeclarations`in e){let n={functionDeclarations:[...e.functionDeclarations||[],...t]};return t=[],n}return e}):[...n,...t.length>0?[{functionDeclarations:t}]:[]]}function st(e){return{functionDeclarations:[{name:e.function.name,description:e.function.description,parameters:_(e.function.parameters)}]}}function ct(e,t){if(!e.length||!t)return;let{toolChoice:n,allowedFunctionNames:r}=t,i={any:j.ANY,auto:j.AUTO,none:j.NONE};if(n&&[`any`,`auto`,`none`].includes(n))return{functionCallingConfig:{mode:i[n]??`MODE_UNSPECIFIED`,allowedFunctionNames:r}};if(typeof n==`string`||r)return{functionCallingConfig:{mode:j.ANY,allowedFunctionNames:[...r??[],...n&&typeof n==`string`?[n]:[]]}}}var lt={"gemini-embedding-001":{maxInputTokens:2048,imageInputs:!1,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:3072,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!1},"gemini-2.5-flash-lite-preview-09-2025":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-2.5-pro-preview-06-05":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-2.5-flash-preview-04-17":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1},"gemini-2.5-flash-preview-09-2025":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-2.5-pro-preview-05-06":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-2.5-flash-preview-05-20":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-2.5-flash":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-live-2.5-flash":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!0,pdfInputs:!1,videoInputs:!0,maxOutputTokens:8e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!0,videoOutputs:!1,toolCalling:!0,structuredOutput:!1},"gemini-3-flash-preview":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-live-2.5-flash-preview-native-audio":{maxInputTokens:131072,imageInputs:!1,audioInputs:!0,pdfInputs:!1,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!0,videoOutputs:!1,toolCalling:!0,structuredOutput:!1},"gemini-2.5-flash-lite":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-2.5-flash-preview-tts":{maxInputTokens:8e3,imageInputs:!1,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:16e3,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!0,videoOutputs:!1,toolCalling:!1,structuredOutput:!1},"gemini-flash-latest":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-2.5-flash-lite-preview-06-17":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1},"gemini-2.5-flash-image":{maxInputTokens:32768,imageInputs:!0,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!0,imageOutputs:!0,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!1},"gemini-2.5-pro-preview-tts":{maxInputTokens:8e3,imageInputs:!1,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:16e3,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!0,videoOutputs:!1,toolCalling:!1,structuredOutput:!1},"gemini-2.5-flash-image-preview":{maxInputTokens:32768,imageInputs:!0,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!0,imageOutputs:!0,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!1},"gemini-1.5-flash-8b":{maxInputTokens:1e6,imageInputs:!0,audioInputs:!0,pdfInputs:!1,videoInputs:!0,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1},"gemini-3-pro-preview":{maxInputTokens:1e6,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:64e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-2.0-flash-lite":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-1.5-flash":{maxInputTokens:1e6,imageInputs:!0,audioInputs:!0,pdfInputs:!1,videoInputs:!0,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1},"gemini-flash-lite-latest":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-2.5-pro":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-2.0-flash":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-1.5-pro":{maxInputTokens:1e6,imageInputs:!0,audioInputs:!0,pdfInputs:!1,videoInputs:!0,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1}},ut=class extends re{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;thinkingConfig;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`)||this.model.startsWith(`gemini-3`)}constructor(e){if(super(e),this.model=e.model.replace(/^models\//,``),this.maxOutputTokens=e.maxOutputTokens??this.maxOutputTokens,this.maxOutputTokens&&this.maxOutputTokens<0)throw Error("`maxOutputTokens` must be a positive integer");if(this.temperature=e.temperature??this.temperature,this.temperature&&(this.temperature<0||this.temperature>2))throw 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 Error("`topP` must be a positive integer");if(this.topP&&this.topP>1)throw Error("`topP` must be below 1.");if(this.topK=e.topK??this.topK,this.topK&&this.topK<0)throw Error("`topK` must be a positive integer");if(this.stopSequences=e.stopSequences??this.stopSequences,this.apiKey=e.apiKey??r(`GOOGLE_API_KEY`),!this.apiKey)throw 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(e=>e.category)).size!==this.safetySettings.length)throw Error("The categories in `safetySettings` array must be unique");this.streaming=e.streaming??this.streaming,this.json=e.json,this.thinkingConfig=e.thinkingConfig??this.thinkingConfig,this.client=new it(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`}:{},...this.thinkingConfig?{thinkingConfig:this.thinkingConfig}:{}}},{apiVersion:e.apiVersion,baseUrl:e.baseUrl,customHeaders:e.customHeaders}),this.streamUsage=e.streamUsage??this.streamUsage}useCachedContent(e,t,n){this.apiKey&&(this.client=new it(this.apiKey).getGenerativeModelFromCachedContent(e,t,n))}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,t){return this.withConfig({tools:at(e)?.tools,...t})}invocationParams(e){let t=e?.tools?.length?at(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),{...t?.tools?{tools:t.tools}:{},...t?.toolConfig?{toolConfig:t.toolConfig}:{}}}async _generate(e,t,n){t.signal?.throwIfAborted();let r=E(e,this._isMultimodalModel,this.useSystemInstruction,this.model),i=r;if(r[0].role===`system`){let[e]=r;this.client.systemInstruction=e,i=r.slice(1)}let a=this.invocationParams(t);if(this.streaming){let r={},i=this._streamResponseChunks(e,t,n),a=[];for await(let e of i){let t=e.generationInfo?.completion??0;a[t]===void 0?a[t]=e:a[t]=a[t].concat(e)}return{generations:a.filter(e=>e!==void 0),llmOutput:{estimatedTokenUsage:r}}}let o=await this.completionWithRetry({...a,contents:i}),s;`usageMetadata`in o.response&&(s=D(o.response.usageMetadata,this.model));let c=_e(o.response,{usageMetadata:s});return c.generations?.length>0&&await n?.handleLLMNewToken(c.generations[0]?.text??``),c}async*_streamResponseChunks(e,t,n){let r=E(e,this._isMultimodalModel,this.useSystemInstruction,this.model),i=r;if(r[0].role===`system`){let[e]=r;this.client.systemInstruction=e,i=r.slice(1)}let a={...this.invocationParams(t),contents:i},o=await this.caller.callWithOptions({signal:t?.signal},async()=>{let{stream:e}=await this.client.generateContentStream(a,{signal:t?.signal});return e}),s,c=0,l=0,u=0,d=0;for await(let e of o){if(t.signal?.aborted)return;if(`usageMetadata`in e&&e.usageMetadata!==void 0&&this.streamUsage!==!1&&t.streamUsage!==!1){s=D(e.usageMetadata,this.model);let t=e.usageMetadata.promptTokenCount??0;s.input_tokens=Math.max(0,t-c),c=t;let n=e.usageMetadata.candidatesTokenCount??0;s.output_tokens=Math.max(0,n-l),l=n;let r=e.usageMetadata.totalTokenCount??0;s.total_tokens=Math.max(0,r-u),u=r}let r=ve(e,{usageMetadata:s,index:d});d+=1,r&&(yield r,await n?.handleLLMNewToken(r.text??``))}}async completionWithRetry(e,t){return this.caller.callWithOptions({signal:t?.signal},async()=>{try{return await this.client.generateContent(e,{signal:t?.signal})}catch(e){throw e.message?.includes(`400 Bad Request`)&&(e.status=400),e}})}get profile(){return lt[this.model]??{}}withStructuredOutput(e,n){let r=e,i=n?.name,a=n?.method,o=n?.includeRaw;if(a===`jsonMode`)throw Error(`ChatGoogleGenerativeAI only supports "jsonSchema" or "functionCalling" as a method.`);let c,l;if(a===`functionCalling`){let e=i??`extract`,n;if(t(r)){let t=v(r);n=[{functionDeclarations:[{name:e,description:t.description??`A function available to call.`,parameters:t}]}],l=new O({returnSingle:!0,keyName:e,zodSchema:r})}else{let t;typeof r.name==`string`&&typeof r.parameters==`object`&&r.parameters!=null?(t=r,t.parameters=_(r.parameters),e=r.name):t={name:e,description:r.description??``,parameters:_(r)},n=[{functionDeclarations:[t]}],l=new O({returnSingle:!0,keyName:e})}c=this.bindTools(n).withConfig({allowedFunctionNames:[e]})}else{let e=v(r);c=this.withConfig({responseSchema:e}),l=new ie}if(!o)return c.pipe(l).withConfig({runName:`ChatGoogleGenerativeAIStructuredOutput`});let u=m.assign({parsed:(e,t)=>l.invoke(e.raw,t)}),d=m.assign({parsed:()=>null}),f=u.withFallbacks({fallbacks:[d]});return s.from([{raw:c},f]).withConfig({runName:`StructuredOutputRunnable`})}};export{ut as ChatGoogleGenerativeAI};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{b as e,c as t,d as n,l as r,m as i,o as a,p as o,r as s,s as c,v as l,x as u,y as ee}from"./schemas-79owEkeD.js";import{G as d,I as f,Kt as te,cr as ne,fr as re,g as ie,nn as p,or as ae,ot as oe,tn as se,vn as ce,w as m}from"./index-DnLjyl1f.js";import{A as le,E as ue,M as de,O as fe,p as pe,r as me,s as he,w as ge}from"./function_calling-BLGGrcJY.js";import"./tools-Bn2uguc_.js";var _e=class extends fe{static lc_name(){return`AnthropicToolsOutputParser`}lc_namespace=[`langchain`,`anthropic`,`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){let t=e;if(typeof e==`string`)try{t=JSON.parse(e)}catch(t){throw new le(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(t.message)}`,e)}else t=e;if(this.zodSchema===void 0)return t;let n=await f(this.zodSchema,t);if(n.success)return n.data;throw new le(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(n.error.issues)}`,JSON.stringify(t,null,2))}async parseResult(e){let t=e.flatMap(e=>{let{message:t}=e;return Array.isArray(t.content)?ve(t.content)[0]:[]});if(t[0]===void 0)throw Error(`No parseable tool calls provided to AnthropicToolsOutputParser.`);let[n]=t;return await this._validateResult(n.args)}};function ve(e){let t=[];for(let n of e)n.type===`tool_use`&&t.push({name:n.name,args:n.input,id:n.id,type:`tool_call`});return t}function ye(e){if(e)return e===`any`?{type:`any`}:e===`auto`?{type:`auto`}:e===`none`?{type:`none`}:typeof e==`string`?{type:`tool`,name:e}:e}var be=i({cache_control:t().optional().nullable(),defer_loading:c().optional(),input_examples:a(u()).optional(),allowed_callers:a(u()).optional()}),xe={tool_search_tool_regex_20251119:`advanced-tool-use-2025-11-20`,tool_search_tool_bm25_20251119:`advanced-tool-use-2025-11-20`,memory_20250818:`context-management-2025-06-27`,web_fetch_20250910:`web-fetch-2025-09-10`,code_execution_20250825:`code-execution-2025-08-25`,computer_20251124:`computer-use-2025-11-24`,computer_20250124:`computer-use-2025-01-24`,mcp_toolset:`mcp-client-2025-11-20`};function Se(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`thinking`}function Ce(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`redacted_thinking`}function we(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`search_result`}function Te(e){return typeof e!=`object`||!e||!(`type`in e)||e.type!==`image`||!(`source`in e)||typeof e.source!=`object`||e.source==null||!(`type`in e.source)?!1:e.source.type===`base64`?!(!(`media_type`in e.source)||typeof e.source.media_type!=`string`||!(`data`in e.source)||typeof e.source.data!=`string`):e.source.type===`url`?!(!(`url`in e.source)||typeof e.source.url!=`string`):!1}var Ee={providerName:`anthropic`,fromStandardTextBlock(e){return{type:`text`,text:e.text,...`citations`in(e.metadata??{})?{citations:e.metadata.citations}:{},...`cache_control`in(e.metadata??{})?{cache_control:e.metadata.cache_control}:{}}},fromStandardImageBlock(e){if(e.source_type===`url`){let t=re({dataUrl:e.url,asTypedArray:!1});return t?{type:`image`,source:{type:`base64`,data:t.data,media_type:t.mime_type},...`cache_control`in(e.metadata??{})?{cache_control:e.metadata.cache_control}:{}}:{type:`image`,source:{type:`url`,url:e.url},...`cache_control`in(e.metadata??{})?{cache_control:e.metadata.cache_control}:{}}}else if(e.source_type===`base64`)return{type:`image`,source:{type:`base64`,data:e.data,media_type:e.mime_type??``},...`cache_control`in(e.metadata??{})?{cache_control:e.metadata.cache_control}:{}};else throw Error(`Unsupported image source type: ${e.source_type}`)},fromStandardFileBlock(e){let t=(e.mime_type??``).split(`;`)[0];if(e.source_type===`url`){if(t===`application/pdf`||t===``)return{type:`document`,source:{type:`url`,url:e.url},...`cache_control`in(e.metadata??{})?{cache_control:e.metadata.cache_control}:{},...`citations`in(e.metadata??{})?{citations:e.metadata.citations}:{},...`context`in(e.metadata??{})?{context:e.metadata.context}:{},...`title`in(e.metadata??{})?{title:e.metadata.title}:{}};throw Error(`Unsupported file mime type for file url source: ${e.mime_type}`)}else if(e.source_type===`text`){if(t===`text/plain`||t===``)return{type:`document`,source:{type:`text`,data:e.text,media_type:e.mime_type??``},...`cache_control`in(e.metadata??{})?{cache_control:e.metadata.cache_control}:{},...`citations`in(e.metadata??{})?{citations:e.metadata.citations}:{},...`context`in(e.metadata??{})?{context:e.metadata.context}:{},...`title`in(e.metadata??{})?{title:e.metadata.title}:{}};throw Error(`Unsupported file mime type for file text source: ${e.mime_type}`)}else if(e.source_type===`base64`){if(t===`application/pdf`||t===``)return{type:`document`,source:{type:`base64`,data:e.data,media_type:`application/pdf`},...`cache_control`in(e.metadata??{})?{cache_control:e.metadata.cache_control}:{},...`citations`in(e.metadata??{})?{citations:e.metadata.citations}:{},...`context`in(e.metadata??{})?{context:e.metadata.context}:{},...`title`in(e.metadata??{})?{title:e.metadata.title}:{}};if([`image/jpeg`,`image/png`,`image/gif`,`image/webp`].includes(t))return{type:`document`,source:{type:`content`,content:[{type:`image`,source:{type:`base64`,data:e.data,media_type:t}}]},...`cache_control`in(e.metadata??{})?{cache_control:e.metadata.cache_control}:{},...`citations`in(e.metadata??{})?{citations:e.metadata.citations}:{},...`context`in(e.metadata??{})?{context:e.metadata.context}:{},...`title`in(e.metadata??{})?{title:e.metadata.title}:{}};throw Error(`Unsupported file mime type for file base64 source: ${e.mime_type}`)}else throw Error(`Unsupported file source type: ${e.source_type}`)}},De=e=>e();function Oe(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`citation`}function ke(e){function*t(){for(let t of e)Oe(t)&&(t.source===`char`?yield{type:`char_location`,file_id:t.url??``,start_char_index:t.startIndex??0,end_char_index:t.endIndex??0,document_title:t.title??null,document_index:0,cited_text:t.citedText??``}:t.source===`page`?yield{type:`page_location`,file_id:t.url??``,start_page_number:t.startIndex??0,end_page_number:t.endIndex??0,document_title:t.title??null,document_index:0,cited_text:t.citedText??``}:t.source===`block`?yield{type:`content_block_location`,file_id:t.url??``,start_block_index:t.startIndex??0,end_block_index:t.endIndex??0,document_title:t.title??null,document_index:0,cited_text:t.citedText??``}:t.source===`url`?yield{type:`web_search_result_location`,url:t.url??``,title:t.title??null,encrypted_index:String(t.startIndex??0),cited_text:t.citedText??``}:t.source===`search`&&(yield{type:`search_result_location`,title:t.title??null,start_block_index:t.startIndex??0,end_block_index:t.endIndex??0,search_result_index:0,source:t.source??``,cited_text:t.citedText??``}))}return Array.from(t())}function Ae(e){return typeof e==`string`?e:je(e)}function je(e){let t=[];for(let n=0,{length:r}=e;n<r;n++)t.push(String.fromCharCode(e[n]));return btoa(t.join(``))}function Me(e){return(e??``).split(`;`)[0].toLowerCase()}function h(e,t){if(typeof e==`object`&&e&&t in e)return e[t]}function g(e,t){let n=h(t,`cache_control`);n!==void 0&&(e.cache_control=n);let r=h(t,`citations`);r!==void 0&&(e.citations=r);let i=h(t,`context`);i!==void 0&&(e.context=i);let a=h(t,`title`);return a!==void 0&&(e.title=a),e}function Ne(e,t){let n=h(t,`cache_control`);return n!==void 0&&(e.cache_control=n),e}function Pe(e){return new Set([`image/jpeg`,`image/png`,`image/gif`,`image/webp`]).has(e)}function Fe(e){let t=[],n=e.response_metadata,r=`model_provider`in n&&n?.model_provider===`anthropic`;for(let n of e.contentBlocks)if(n.type===`text`)n.annotations?t.push({type:`text`,text:n.text,citations:ke(n.annotations)}):t.push({type:`text`,text:n.text});else if(n.type===`tool_call`)t.push({type:`tool_use`,id:n.id??``,name:n.name,input:n.args});else if(n.type===`tool_call_chunk`){let e=De(()=>{if(typeof n.args!=`string`)return n.args;try{return JSON.parse(n.args)}catch{return{}}});t.push({type:`tool_use`,id:n.id??``,name:n.name??``,input:e})}else if(n.type===`reasoning`&&r)t.push({type:`thinking`,thinking:n.reasoning,signature:String(n.signature)});else if(n.type===`server_tool_call`&&r)(n.name===`web_search`||n.name===`code_execution`)&&t.push({type:`server_tool_use`,name:n.name,id:n.id??``,input:n.args});else if(n.type===`server_tool_call_result`&&r)if(n.name===`web_search`&&Array.isArray(n.output.urls)){let e=n.output.urls.map(e=>({type:`web_search_result`,title:``,encrypted_content:``,url:e}));t.push({type:`web_search_tool_result`,tool_use_id:n.toolCallId??``,content:e})}else n.name===`code_execution`?t.push({type:`code_execution_tool_result`,tool_use_id:n.toolCallId??``,content:n.output}):n.name===`mcp_tool_result`&&t.push({type:`mcp_tool_result`,tool_use_id:n.toolCallId??``,content:n.output});else if(n.type===`audio`)throw Error(`Anthropic does not support audio content blocks.`);else if(n.type===`file`){let e=n.metadata;if(n.fileId){t.push(g({type:`document`,source:{type:`file`,file_id:n.fileId}},e));continue}if(n.url){let r=Me(n.mimeType);if(r===`application/pdf`||r===``){t.push(g({type:`document`,source:{type:`url`,url:n.url}},e));continue}}if(n.data){let r=Me(n.mimeType);if(r===``||r===`application/pdf`)t.push(g({type:`document`,source:{type:`base64`,data:Ae(n.data),media_type:`application/pdf`}},e));else if(r===`text/plain`)t.push(g({type:`document`,source:{type:`text`,data:Ae(n.data),media_type:`text/plain`}},e));else if(Pe(r))t.push(g({type:`document`,source:{type:`content`,content:[{type:`image`,source:{type:`base64`,data:Ae(n.data),media_type:r}}]}},e));else throw Error(`Unsupported file mime type for Anthropic base64 source: ${r}`);continue}throw Error(`File content block must include a fileId, url, or data property.`)}else if(n.type===`image`){let e=n.metadata;if(n.fileId){t.push(Ne({type:`image`,source:{type:`file`,file_id:n.fileId}},e));continue}if(n.url){t.push(Ne({type:`image`,source:{type:`url`,url:n.url}},e));continue}if(n.data){let r=Me(n.mimeType)||`image/png`;Pe(r)&&t.push(Ne({type:`image`,source:{type:`base64`,data:Ae(n.data),media_type:r}},e));continue}throw Error(`Image content block must include a fileId, url, or data property.`)}else n.type===`video`||(n.type===`text-plain`?n.data&&t.push(g({type:`document`,source:{type:`text`,data:Ae(n.data),media_type:`text/plain`}},n.metadata)):n.type===`non_standard`&&r&&t.push(n.value));return t}function Ie(e){let t=re({dataUrl:e});if(t)return{type:`base64`,media_type:t.mime_type,data:t.data};let n;try{n=new URL(e)}catch{throw Error([`Malformed image URL: ${JSON.stringify(e)}. 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 e,c as t,d as n,l as r,m as i,o as a,p as o,r as s,s as c,v as l,x as u,y as ee}from"./schemas-79owEkeD.js";import{G as d,I as f,Kt as te,cr as ne,fr as re,g as ie,nn as p,or as ae,ot as oe,tn as se,vn as ce,w as m}from"./index-zqVFP8t5.js";import{A as le,E as ue,M as de,O as fe,p as pe,r as me,s as he,w as ge}from"./function_calling-XyGNNvjR.js";import"./tools-DWDA-ZTt.js";var _e=class extends fe{static lc_name(){return`AnthropicToolsOutputParser`}lc_namespace=[`langchain`,`anthropic`,`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){let t=e;if(typeof e==`string`)try{t=JSON.parse(e)}catch(t){throw new le(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(t.message)}`,e)}else t=e;if(this.zodSchema===void 0)return t;let n=await f(this.zodSchema,t);if(n.success)return n.data;throw new le(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(n.error.issues)}`,JSON.stringify(t,null,2))}async parseResult(e){let t=e.flatMap(e=>{let{message:t}=e;return Array.isArray(t.content)?ve(t.content)[0]:[]});if(t[0]===void 0)throw Error(`No parseable tool calls provided to AnthropicToolsOutputParser.`);let[n]=t;return await this._validateResult(n.args)}};function ve(e){let t=[];for(let n of e)n.type===`tool_use`&&t.push({name:n.name,args:n.input,id:n.id,type:`tool_call`});return t}function ye(e){if(e)return e===`any`?{type:`any`}:e===`auto`?{type:`auto`}:e===`none`?{type:`none`}:typeof e==`string`?{type:`tool`,name:e}:e}var be=i({cache_control:t().optional().nullable(),defer_loading:c().optional(),input_examples:a(u()).optional(),allowed_callers:a(u()).optional()}),xe={tool_search_tool_regex_20251119:`advanced-tool-use-2025-11-20`,tool_search_tool_bm25_20251119:`advanced-tool-use-2025-11-20`,memory_20250818:`context-management-2025-06-27`,web_fetch_20250910:`web-fetch-2025-09-10`,code_execution_20250825:`code-execution-2025-08-25`,computer_20251124:`computer-use-2025-11-24`,computer_20250124:`computer-use-2025-01-24`,mcp_toolset:`mcp-client-2025-11-20`};function Se(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`thinking`}function Ce(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`redacted_thinking`}function we(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`search_result`}function Te(e){return typeof e!=`object`||!e||!(`type`in e)||e.type!==`image`||!(`source`in e)||typeof e.source!=`object`||e.source==null||!(`type`in e.source)?!1:e.source.type===`base64`?!(!(`media_type`in e.source)||typeof e.source.media_type!=`string`||!(`data`in e.source)||typeof e.source.data!=`string`):e.source.type===`url`?!(!(`url`in e.source)||typeof e.source.url!=`string`):!1}var Ee={providerName:`anthropic`,fromStandardTextBlock(e){return{type:`text`,text:e.text,...`citations`in(e.metadata??{})?{citations:e.metadata.citations}:{},...`cache_control`in(e.metadata??{})?{cache_control:e.metadata.cache_control}:{}}},fromStandardImageBlock(e){if(e.source_type===`url`){let t=re({dataUrl:e.url,asTypedArray:!1});return t?{type:`image`,source:{type:`base64`,data:t.data,media_type:t.mime_type},...`cache_control`in(e.metadata??{})?{cache_control:e.metadata.cache_control}:{}}:{type:`image`,source:{type:`url`,url:e.url},...`cache_control`in(e.metadata??{})?{cache_control:e.metadata.cache_control}:{}}}else if(e.source_type===`base64`)return{type:`image`,source:{type:`base64`,data:e.data,media_type:e.mime_type??``},...`cache_control`in(e.metadata??{})?{cache_control:e.metadata.cache_control}:{}};else throw Error(`Unsupported image source type: ${e.source_type}`)},fromStandardFileBlock(e){let t=(e.mime_type??``).split(`;`)[0];if(e.source_type===`url`){if(t===`application/pdf`||t===``)return{type:`document`,source:{type:`url`,url:e.url},...`cache_control`in(e.metadata??{})?{cache_control:e.metadata.cache_control}:{},...`citations`in(e.metadata??{})?{citations:e.metadata.citations}:{},...`context`in(e.metadata??{})?{context:e.metadata.context}:{},...`title`in(e.metadata??{})?{title:e.metadata.title}:{}};throw Error(`Unsupported file mime type for file url source: ${e.mime_type}`)}else if(e.source_type===`text`){if(t===`text/plain`||t===``)return{type:`document`,source:{type:`text`,data:e.text,media_type:e.mime_type??``},...`cache_control`in(e.metadata??{})?{cache_control:e.metadata.cache_control}:{},...`citations`in(e.metadata??{})?{citations:e.metadata.citations}:{},...`context`in(e.metadata??{})?{context:e.metadata.context}:{},...`title`in(e.metadata??{})?{title:e.metadata.title}:{}};throw Error(`Unsupported file mime type for file text source: ${e.mime_type}`)}else if(e.source_type===`base64`){if(t===`application/pdf`||t===``)return{type:`document`,source:{type:`base64`,data:e.data,media_type:`application/pdf`},...`cache_control`in(e.metadata??{})?{cache_control:e.metadata.cache_control}:{},...`citations`in(e.metadata??{})?{citations:e.metadata.citations}:{},...`context`in(e.metadata??{})?{context:e.metadata.context}:{},...`title`in(e.metadata??{})?{title:e.metadata.title}:{}};if([`image/jpeg`,`image/png`,`image/gif`,`image/webp`].includes(t))return{type:`document`,source:{type:`content`,content:[{type:`image`,source:{type:`base64`,data:e.data,media_type:t}}]},...`cache_control`in(e.metadata??{})?{cache_control:e.metadata.cache_control}:{},...`citations`in(e.metadata??{})?{citations:e.metadata.citations}:{},...`context`in(e.metadata??{})?{context:e.metadata.context}:{},...`title`in(e.metadata??{})?{title:e.metadata.title}:{}};throw Error(`Unsupported file mime type for file base64 source: ${e.mime_type}`)}else throw Error(`Unsupported file source type: ${e.source_type}`)}},De=e=>e();function Oe(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`citation`}function ke(e){function*t(){for(let t of e)Oe(t)&&(t.source===`char`?yield{type:`char_location`,file_id:t.url??``,start_char_index:t.startIndex??0,end_char_index:t.endIndex??0,document_title:t.title??null,document_index:0,cited_text:t.citedText??``}:t.source===`page`?yield{type:`page_location`,file_id:t.url??``,start_page_number:t.startIndex??0,end_page_number:t.endIndex??0,document_title:t.title??null,document_index:0,cited_text:t.citedText??``}:t.source===`block`?yield{type:`content_block_location`,file_id:t.url??``,start_block_index:t.startIndex??0,end_block_index:t.endIndex??0,document_title:t.title??null,document_index:0,cited_text:t.citedText??``}:t.source===`url`?yield{type:`web_search_result_location`,url:t.url??``,title:t.title??null,encrypted_index:String(t.startIndex??0),cited_text:t.citedText??``}:t.source===`search`&&(yield{type:`search_result_location`,title:t.title??null,start_block_index:t.startIndex??0,end_block_index:t.endIndex??0,search_result_index:0,source:t.source??``,cited_text:t.citedText??``}))}return Array.from(t())}function Ae(e){return typeof e==`string`?e:je(e)}function je(e){let t=[];for(let n=0,{length:r}=e;n<r;n++)t.push(String.fromCharCode(e[n]));return btoa(t.join(``))}function Me(e){return(e??``).split(`;`)[0].toLowerCase()}function h(e,t){if(typeof e==`object`&&e&&t in e)return e[t]}function g(e,t){let n=h(t,`cache_control`);n!==void 0&&(e.cache_control=n);let r=h(t,`citations`);r!==void 0&&(e.citations=r);let i=h(t,`context`);i!==void 0&&(e.context=i);let a=h(t,`title`);return a!==void 0&&(e.title=a),e}function Ne(e,t){let n=h(t,`cache_control`);return n!==void 0&&(e.cache_control=n),e}function Pe(e){return new Set([`image/jpeg`,`image/png`,`image/gif`,`image/webp`]).has(e)}function Fe(e){let t=[],n=e.response_metadata,r=`model_provider`in n&&n?.model_provider===`anthropic`;for(let n of e.contentBlocks)if(n.type===`text`)n.annotations?t.push({type:`text`,text:n.text,citations:ke(n.annotations)}):t.push({type:`text`,text:n.text});else if(n.type===`tool_call`)t.push({type:`tool_use`,id:n.id??``,name:n.name,input:n.args});else if(n.type===`tool_call_chunk`){let e=De(()=>{if(typeof n.args!=`string`)return n.args;try{return JSON.parse(n.args)}catch{return{}}});t.push({type:`tool_use`,id:n.id??``,name:n.name??``,input:e})}else if(n.type===`reasoning`&&r)t.push({type:`thinking`,thinking:n.reasoning,signature:String(n.signature)});else if(n.type===`server_tool_call`&&r)(n.name===`web_search`||n.name===`code_execution`)&&t.push({type:`server_tool_use`,name:n.name,id:n.id??``,input:n.args});else if(n.type===`server_tool_call_result`&&r)if(n.name===`web_search`&&Array.isArray(n.output.urls)){let e=n.output.urls.map(e=>({type:`web_search_result`,title:``,encrypted_content:``,url:e}));t.push({type:`web_search_tool_result`,tool_use_id:n.toolCallId??``,content:e})}else n.name===`code_execution`?t.push({type:`code_execution_tool_result`,tool_use_id:n.toolCallId??``,content:n.output}):n.name===`mcp_tool_result`&&t.push({type:`mcp_tool_result`,tool_use_id:n.toolCallId??``,content:n.output});else if(n.type===`audio`)throw Error(`Anthropic does not support audio content blocks.`);else if(n.type===`file`){let e=n.metadata;if(n.fileId){t.push(g({type:`document`,source:{type:`file`,file_id:n.fileId}},e));continue}if(n.url){let r=Me(n.mimeType);if(r===`application/pdf`||r===``){t.push(g({type:`document`,source:{type:`url`,url:n.url}},e));continue}}if(n.data){let r=Me(n.mimeType);if(r===``||r===`application/pdf`)t.push(g({type:`document`,source:{type:`base64`,data:Ae(n.data),media_type:`application/pdf`}},e));else if(r===`text/plain`)t.push(g({type:`document`,source:{type:`text`,data:Ae(n.data),media_type:`text/plain`}},e));else if(Pe(r))t.push(g({type:`document`,source:{type:`content`,content:[{type:`image`,source:{type:`base64`,data:Ae(n.data),media_type:r}}]}},e));else throw Error(`Unsupported file mime type for Anthropic base64 source: ${r}`);continue}throw Error(`File content block must include a fileId, url, or data property.`)}else if(n.type===`image`){let e=n.metadata;if(n.fileId){t.push(Ne({type:`image`,source:{type:`file`,file_id:n.fileId}},e));continue}if(n.url){t.push(Ne({type:`image`,source:{type:`url`,url:n.url}},e));continue}if(n.data){let r=Me(n.mimeType)||`image/png`;Pe(r)&&t.push(Ne({type:`image`,source:{type:`base64`,data:Ae(n.data),media_type:r}},e));continue}throw Error(`Image content block must include a fileId, url, or data property.`)}else n.type===`video`||(n.type===`text-plain`?n.data&&t.push(g({type:`document`,source:{type:`text`,data:Ae(n.data),media_type:`text/plain`}},n.metadata)):n.type===`non_standard`&&r&&t.push(n.value));return t}function Ie(e){let t=re({dataUrl:e});if(t)return{type:`base64`,media_type:t.mime_type,data:t.data};let n;try{n=new URL(e)}catch{throw Error([`Malformed image URL: ${JSON.stringify(e)}. 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:e};throw 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
|
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{o as e,t}from"./chunk-zsgVPwQN.js";import{$ as n,$t as r,A as i,B as a,Ct as o,Et as s,F as c,Fr as l,G as u,H as d,I as f,J as p,Jn as m,K as h,Kt as g,L as _,Lt as v,M as y,N as b,O as ee,P as x,Q as te,R as S,Rr as C,St as w,U as T,V as E,W as ne,X as D,Xt as re,Y as O,Yt as ie,Z as k,Zn as A,_ as j,an as M,ar as ae,b as N,bt as P,c as oe,ct as se,d as ce,dn as le,dr as ue,dt as de,et as fe,f as pe,ft as me,g as he,h as ge,ht as F,in as _e,it as ve,j as ye,k as be,l as xe,m as Se,mr as I,nn as Ce,nt as we,on as Te,ot as Ee,p as De,q as Oe,qn as L,qt as R,rn as ke,rt as Ae,s as z,sr as je,st as Me,tn as Ne,tt as Pe,u as Fe,un as Ie,v as Le,vn as Re,vt as ze,w as B,xt as Be,y as Ve,yt as V,z as He}from"./index-DnLjyl1f.js";var H=class extends z{static lc_name(){return`RunnablePassthrough`}lc_namespace=[`langchain_core`,`runnables`];lc_serializable=!0;func;constructor(e){super(e),e&&(this.func=e.func)}async invoke(e,t){let n=V(t);return this.func&&await this.func(e,n),this._callWithConfig(e=>Promise.resolve(e),e,n)}async*transform(e,t){let n=V(t),r,i=!0;for await(let t of this._transformStreamWithConfig(e,e=>e,n))if(yield t,i)if(r===void 0)r=t;else try{r=F(r,t)}catch{r=void 0,i=!1}this.func&&r!==void 0&&await this.func(r,n)}static assign(e){return new oe(new pe({steps:e}))}},Ue=class extends z{static lc_name(){return`RouterRunnable`}lc_namespace=[`langchain_core`,`runnables`];lc_serializable=!0;runnables;constructor(e){super(e),this.runnables=e.runnables}async invoke(e,t){let{key:n,input:r}=e,i=this.runnables[n];if(i===void 0)throw Error(`No runnable associated with key "${n}".`);return i.invoke(r,V(t))}async batch(e,t,n){let r=e.map(e=>e.key),i=e.map(e=>e.input);if(r.find(e=>this.runnables[e]===void 0)!==void 0)throw Error(`One or more keys do not have a corresponding runnable.`);let a=r.map(e=>this.runnables[e]),o=this._getOptionsList(t??{},e.length),s=o[0]?.maxConcurrency??n?.maxConcurrency,c=s&&s>0?s:e.length,l=[];for(let e=0;e<i.length;e+=c){let t=i.slice(e,e+c).map((e,t)=>a[t].invoke(e,o[t])),n=await Promise.all(t);l.push(n)}return l.flat()}async stream(e,t){let{key:n,input:r}=e,i=this.runnables[n];if(i===void 0)throw Error(`No runnable associated with key "${n}".`);return i.stream(r,t)}},We=class extends z{static lc_name(){return`RunnableBranch`}lc_namespace=[`langchain_core`,`runnables`];lc_serializable=!0;default;branches;constructor(e){super(e),this.branches=e.branches,this.default=e.default}static from(e){if(e.length<1)throw Error(`RunnableBranch requires at least one branch`);let t=e.slice(0,-1).map(([e,t])=>[N(e),N(t)]),n=N(e[e.length-1]);return new this({branches:t,default:n})}async _invoke(e,t,n){let r;for(let i=0;i<this.branches.length;i+=1){let[a,o]=this.branches[i];if(await a.invoke(e,w(t,{callbacks:n?.getChild(`condition:${i+1}`)}))){r=await o.invoke(e,w(t,{callbacks:n?.getChild(`branch:${i+1}`)}));break}}return r||=await this.default.invoke(e,w(t,{callbacks:n?.getChild(`branch:default`)})),r}async invoke(e,t={}){return this._callWithConfig(this._invoke,e,t)}async*_streamIterator(e,t){let n=await(await P(t))?.handleChainStart(this.toJSON(),Ve(e,`input`),t?.runId,void 0,void 0,void 0,t?.runName),r,i=!0,a;try{for(let o=0;o<this.branches.length;o+=1){let[s,c]=this.branches[o];if(await s.invoke(e,w(t,{callbacks:n?.getChild(`condition:${o+1}`)}))){a=await c.stream(e,w(t,{callbacks:n?.getChild(`branch:${o+1}`)}));for await(let e of a)if(yield e,i)if(r===void 0)r=e;else try{r=F(r,e)}catch{r=void 0,i=!1}break}}if(a===void 0){a=await this.default.stream(e,w(t,{callbacks:n?.getChild(`branch:default`)}));for await(let e of a)if(yield e,i)if(r===void 0)r=e;else try{r=F(r,e)}catch{r=void 0,i=!1}}}catch(e){throw await n?.handleChainError(e),e}await n?.handleChainEnd(r??{})}},Ge=class extends xe{runnable;inputMessagesKey;outputMessagesKey;historyMessagesKey;getMessageHistory;constructor(e){let t=ce.from((e,t)=>this._enterHistory(e,t??{})).withConfig({runName:`loadHistory`}),n=e.historyMessagesKey??e.inputMessagesKey;n&&(t=H.assign({[n]:t}).withConfig({runName:`insertHistory`}));let r=t.pipe(e.runnable.withListeners({onEnd:(e,t)=>this._exitHistory(e,t??{})})).withConfig({runName:`RunnableWithMessageHistory`}),i=e.config??{};super({...e,config:i,bound:r}),this.runnable=e.runnable,this.getMessageHistory=e.getMessageHistory,this.inputMessagesKey=e.inputMessagesKey,this.outputMessagesKey=e.outputMessagesKey,this.historyMessagesKey=e.historyMessagesKey}_getInputMessages(e){let t;if(typeof e==`object`&&!Array.isArray(e)&&!L(e)){let n;n=this.inputMessagesKey?this.inputMessagesKey:Object.keys(e).length===1?Object.keys(e)[0]:`input`,t=Array.isArray(e[n])&&Array.isArray(e[n][0])?e[n][0]:e[n]}else t=e;if(typeof t==`string`)return[new Re(t)];if(Array.isArray(t))return t;if(L(t))return[t];throw Error(`Expected a string, BaseMessage, or array of BaseMessages.\nGot ${JSON.stringify(t,null,2)}`)}_getOutputMessages(e){let t;if(!Array.isArray(e)&&!L(e)&&typeof e!=`string`){let n;n=this.outputMessagesKey===void 0?Object.keys(e).length===1?Object.keys(e)[0]:`output`:this.outputMessagesKey,t=e.generations===void 0?e[n]:e.generations[0][0].message}else t=e;if(typeof t==`string`)return[new Ne(t)];if(Array.isArray(t))return t;if(L(t))return[t];throw Error(`Expected a string, BaseMessage, or array of BaseMessages. Received: ${JSON.stringify(t,null,2)}`)}async _enterHistory(e,t){let n=await(t?.configurable?.messageHistory).getMessages();return this.historyMessagesKey===void 0?n.concat(this._getInputMessages(e)):n}async _exitHistory(e,t){let n=t.configurable?.messageHistory,r;r=Array.isArray(e.inputs)&&Array.isArray(e.inputs[0])?e.inputs[0]:e.inputs;let i=this._getInputMessages(r);if(this.historyMessagesKey===void 0){let e=await n.getMessages();i=i.slice(e.length)}let a=e.outputs;if(!a)throw Error(`Output values from 'Run' undefined. Run: ${JSON.stringify(e,null,2)}`);let o=this._getOutputMessages(a);await n.addMessages([...i,...o])}async _mergeConfig(...e){let t=await super._mergeConfig(...e);if(!t.configurable||!t.configurable.sessionId){let e={[this.inputMessagesKey??`input`]:`foo`};throw Error(`sessionId is required. Pass it in as part of the config argument to .invoke() or .stream()\neg. chain.invoke(${JSON.stringify(e)}, ${JSON.stringify({configurable:{sessionId:`123`}})})`)}let{sessionId:n}=t.configurable;return t.configurable.messageHistory=await this.getMessageHistory(n),t}},Ke={};I(Ke,{RouterRunnable:()=>Ue,Runnable:()=>z,RunnableAssign:()=>oe,RunnableBinding:()=>xe,RunnableBranch:()=>We,RunnableEach:()=>Fe,RunnableLambda:()=>ce,RunnableMap:()=>pe,RunnableParallel:()=>De,RunnablePassthrough:()=>H,RunnablePick:()=>Se,RunnableRetry:()=>ge,RunnableSequence:()=>he,RunnableToolLike:()=>j,RunnableWithFallbacks:()=>Le,RunnableWithMessageHistory:()=>Ge,_coerceToRunnable:()=>N,ensureConfig:()=>V,getCallbackManagerForConfig:()=>P,mergeConfigs:()=>Be,patchConfig:()=>w,pickRunnableConfigKeys:()=>o,raceWithSignal:()=>ze});var qe=class extends z{parseResultWithPrompt(e,t,n){return this.parseResult(e,n)}_baseMessageToString(e){return typeof e.content==`string`?e.content:this._baseMessageContentToString(e.content)}_baseMessageContentToString(e){return JSON.stringify(e)}async invoke(e,t){return typeof e==`string`?this._callWithConfig(async(e,t)=>this.parseResult([{text:e}],t?.callbacks),e,{...t,runType:`parser`}):this._callWithConfig(async(e,t)=>this.parseResult([{message:e,text:this._baseMessageToString(e)}],t?.callbacks),e,{...t,runType:`parser`})}},U=class extends qe{parseResult(e,t){return this.parse(e[0].text,t)}async parseWithPrompt(e,t,n){return this.parse(e,n)}_type(){throw Error(`_type not implemented`)}},W=class extends Error{llmOutput;observation;sendToLLM;constructor(e,t,n,r=!1){if(super(e),this.llmOutput=t,this.observation=n,this.sendToLLM=r,r&&(n===void 0||t===void 0))throw Error(`Arguments 'observation' & 'llmOutput' are required if 'sendToLlm' is true`);le(this,`OUTPUT_PARSING_FAILURE`)}},G=class extends U{async*_transform(e){for await(let t of e)typeof t==`string`?yield this.parseResult([{text:t}]):yield this.parseResult([{message:t,text:this._baseMessageToString(t)}])}async*transform(e,t){yield*this._transformStreamWithConfig(e,this._transform.bind(this),{...t,runType:`parser`})}},K=class extends G{diff=!1;constructor(e){super(e),this.diff=e?.diff??this.diff}async*_transform(e){let t,n;for await(let r of e){if(typeof r!=`string`&&typeof r.content!=`string`)throw Error(`Cannot handle non-string output.`);let e;if(m(r)){if(typeof r.content!=`string`)throw Error(`Cannot handle non-string message output.`);e=new Ee({message:r,text:r.content})}else if(L(r)){if(typeof r.content!=`string`)throw Error(`Cannot handle non-string message output.`);e=new Ee({message:ie(r),text:r.content})}else e=new Me({text:r});n=n===void 0?e:n.concat(e);let i=await this.parsePartialResult([n]);i!=null&&!ee(i,t)&&(this.diff?yield this._diff(t,i):yield i,t=i)}}getFormatInstructions(){return``}},Je=class extends G{static lc_name(){return`BytesOutputParser`}lc_namespace=[`langchain_core`,`output_parsers`,`bytes`];lc_serializable=!0;textEncoder=new TextEncoder;parse(e){return Promise.resolve(this.textEncoder.encode(e))}getFormatInstructions(){return``}},q=class extends G{re;async*_transform(e){let t=``;for await(let n of e)if(typeof n==`string`?t+=n:t+=n.content,this.re){let e=[...t.matchAll(this.re)];if(e.length>1){let n=0;for(let t of e.slice(0,-1))yield[t[1]],n+=(t.index??0)+t[0].length;t=t.slice(n)}}else{let e=await this.parse(t);if(e.length>1){for(let t of e.slice(0,-1))yield[t];t=e[e.length-1]}}for(let e of await this.parse(t))yield[e]}},Ye=class extends q{static lc_name(){return`CommaSeparatedListOutputParser`}lc_namespace=[`langchain_core`,`output_parsers`,`list`];lc_serializable=!0;async parse(e){try{return e.trim().split(`,`).map(e=>e.trim())}catch{throw new W(`Could not parse output: ${e}`,e)}}getFormatInstructions(){return"Your response should be a list of comma separated values, eg: `foo, bar, baz`"}},Xe=class extends q{lc_namespace=[`langchain_core`,`output_parsers`,`list`];length;separator;constructor({length:e,separator:t}){super(...arguments),this.length=e,this.separator=t||`,`}async parse(e){try{let t=e.trim().split(this.separator).map(e=>e.trim());if(this.length!==void 0&&t.length!==this.length)throw new W(`Incorrect number of items. Expected ${this.length}, got ${t.length}.`);return t}catch(t){throw Object.getPrototypeOf(t)===W.prototype?t:new W(`Could not parse output: ${e}`)}}getFormatInstructions(){return`Your response should be a list of ${this.length===void 0?``:`${this.length} `}items separated by "${this.separator}" (eg: \`foo${this.separator} bar${this.separator} baz\`)`}},Ze=class extends q{static lc_name(){return`NumberedListOutputParser`}lc_namespace=[`langchain_core`,`output_parsers`,`list`];lc_serializable=!0;getFormatInstructions(){return`Your response should be a numbered list with each item on a new line. For example:
|
|
1
|
+
import{o as e,t}from"./chunk-zsgVPwQN.js";import{$ as n,$t as r,A as i,B as a,Ct as o,Et as s,F as c,Fr as l,G as u,H as d,I as f,J as p,Jn as m,K as h,Kt as g,L as _,Lt as v,M as y,N as b,O as ee,P as x,Q as te,R as S,Rr as C,St as w,U as T,V as E,W as ne,X as D,Xt as re,Y as O,Yt as ie,Z as k,Zn as A,_ as j,an as M,ar as ae,b as N,bt as P,c as oe,ct as se,d as ce,dn as le,dr as ue,dt as de,et as fe,f as pe,ft as me,g as he,h as ge,ht as F,in as _e,it as ve,j as ye,k as be,l as xe,m as Se,mr as I,nn as Ce,nt as we,on as Te,ot as Ee,p as De,q as Oe,qn as L,qt as R,rn as ke,rt as Ae,s as z,sr as je,st as Me,tn as Ne,tt as Pe,u as Fe,un as Ie,v as Le,vn as Re,vt as ze,w as B,xt as Be,y as Ve,yt as V,z as He}from"./index-zqVFP8t5.js";var H=class extends z{static lc_name(){return`RunnablePassthrough`}lc_namespace=[`langchain_core`,`runnables`];lc_serializable=!0;func;constructor(e){super(e),e&&(this.func=e.func)}async invoke(e,t){let n=V(t);return this.func&&await this.func(e,n),this._callWithConfig(e=>Promise.resolve(e),e,n)}async*transform(e,t){let n=V(t),r,i=!0;for await(let t of this._transformStreamWithConfig(e,e=>e,n))if(yield t,i)if(r===void 0)r=t;else try{r=F(r,t)}catch{r=void 0,i=!1}this.func&&r!==void 0&&await this.func(r,n)}static assign(e){return new oe(new pe({steps:e}))}},Ue=class extends z{static lc_name(){return`RouterRunnable`}lc_namespace=[`langchain_core`,`runnables`];lc_serializable=!0;runnables;constructor(e){super(e),this.runnables=e.runnables}async invoke(e,t){let{key:n,input:r}=e,i=this.runnables[n];if(i===void 0)throw Error(`No runnable associated with key "${n}".`);return i.invoke(r,V(t))}async batch(e,t,n){let r=e.map(e=>e.key),i=e.map(e=>e.input);if(r.find(e=>this.runnables[e]===void 0)!==void 0)throw Error(`One or more keys do not have a corresponding runnable.`);let a=r.map(e=>this.runnables[e]),o=this._getOptionsList(t??{},e.length),s=o[0]?.maxConcurrency??n?.maxConcurrency,c=s&&s>0?s:e.length,l=[];for(let e=0;e<i.length;e+=c){let t=i.slice(e,e+c).map((e,t)=>a[t].invoke(e,o[t])),n=await Promise.all(t);l.push(n)}return l.flat()}async stream(e,t){let{key:n,input:r}=e,i=this.runnables[n];if(i===void 0)throw Error(`No runnable associated with key "${n}".`);return i.stream(r,t)}},We=class extends z{static lc_name(){return`RunnableBranch`}lc_namespace=[`langchain_core`,`runnables`];lc_serializable=!0;default;branches;constructor(e){super(e),this.branches=e.branches,this.default=e.default}static from(e){if(e.length<1)throw Error(`RunnableBranch requires at least one branch`);let t=e.slice(0,-1).map(([e,t])=>[N(e),N(t)]),n=N(e[e.length-1]);return new this({branches:t,default:n})}async _invoke(e,t,n){let r;for(let i=0;i<this.branches.length;i+=1){let[a,o]=this.branches[i];if(await a.invoke(e,w(t,{callbacks:n?.getChild(`condition:${i+1}`)}))){r=await o.invoke(e,w(t,{callbacks:n?.getChild(`branch:${i+1}`)}));break}}return r||=await this.default.invoke(e,w(t,{callbacks:n?.getChild(`branch:default`)})),r}async invoke(e,t={}){return this._callWithConfig(this._invoke,e,t)}async*_streamIterator(e,t){let n=await(await P(t))?.handleChainStart(this.toJSON(),Ve(e,`input`),t?.runId,void 0,void 0,void 0,t?.runName),r,i=!0,a;try{for(let o=0;o<this.branches.length;o+=1){let[s,c]=this.branches[o];if(await s.invoke(e,w(t,{callbacks:n?.getChild(`condition:${o+1}`)}))){a=await c.stream(e,w(t,{callbacks:n?.getChild(`branch:${o+1}`)}));for await(let e of a)if(yield e,i)if(r===void 0)r=e;else try{r=F(r,e)}catch{r=void 0,i=!1}break}}if(a===void 0){a=await this.default.stream(e,w(t,{callbacks:n?.getChild(`branch:default`)}));for await(let e of a)if(yield e,i)if(r===void 0)r=e;else try{r=F(r,e)}catch{r=void 0,i=!1}}}catch(e){throw await n?.handleChainError(e),e}await n?.handleChainEnd(r??{})}},Ge=class extends xe{runnable;inputMessagesKey;outputMessagesKey;historyMessagesKey;getMessageHistory;constructor(e){let t=ce.from((e,t)=>this._enterHistory(e,t??{})).withConfig({runName:`loadHistory`}),n=e.historyMessagesKey??e.inputMessagesKey;n&&(t=H.assign({[n]:t}).withConfig({runName:`insertHistory`}));let r=t.pipe(e.runnable.withListeners({onEnd:(e,t)=>this._exitHistory(e,t??{})})).withConfig({runName:`RunnableWithMessageHistory`}),i=e.config??{};super({...e,config:i,bound:r}),this.runnable=e.runnable,this.getMessageHistory=e.getMessageHistory,this.inputMessagesKey=e.inputMessagesKey,this.outputMessagesKey=e.outputMessagesKey,this.historyMessagesKey=e.historyMessagesKey}_getInputMessages(e){let t;if(typeof e==`object`&&!Array.isArray(e)&&!L(e)){let n;n=this.inputMessagesKey?this.inputMessagesKey:Object.keys(e).length===1?Object.keys(e)[0]:`input`,t=Array.isArray(e[n])&&Array.isArray(e[n][0])?e[n][0]:e[n]}else t=e;if(typeof t==`string`)return[new Re(t)];if(Array.isArray(t))return t;if(L(t))return[t];throw Error(`Expected a string, BaseMessage, or array of BaseMessages.\nGot ${JSON.stringify(t,null,2)}`)}_getOutputMessages(e){let t;if(!Array.isArray(e)&&!L(e)&&typeof e!=`string`){let n;n=this.outputMessagesKey===void 0?Object.keys(e).length===1?Object.keys(e)[0]:`output`:this.outputMessagesKey,t=e.generations===void 0?e[n]:e.generations[0][0].message}else t=e;if(typeof t==`string`)return[new Ne(t)];if(Array.isArray(t))return t;if(L(t))return[t];throw Error(`Expected a string, BaseMessage, or array of BaseMessages. Received: ${JSON.stringify(t,null,2)}`)}async _enterHistory(e,t){let n=await(t?.configurable?.messageHistory).getMessages();return this.historyMessagesKey===void 0?n.concat(this._getInputMessages(e)):n}async _exitHistory(e,t){let n=t.configurable?.messageHistory,r;r=Array.isArray(e.inputs)&&Array.isArray(e.inputs[0])?e.inputs[0]:e.inputs;let i=this._getInputMessages(r);if(this.historyMessagesKey===void 0){let e=await n.getMessages();i=i.slice(e.length)}let a=e.outputs;if(!a)throw Error(`Output values from 'Run' undefined. Run: ${JSON.stringify(e,null,2)}`);let o=this._getOutputMessages(a);await n.addMessages([...i,...o])}async _mergeConfig(...e){let t=await super._mergeConfig(...e);if(!t.configurable||!t.configurable.sessionId){let e={[this.inputMessagesKey??`input`]:`foo`};throw Error(`sessionId is required. Pass it in as part of the config argument to .invoke() or .stream()\neg. chain.invoke(${JSON.stringify(e)}, ${JSON.stringify({configurable:{sessionId:`123`}})})`)}let{sessionId:n}=t.configurable;return t.configurable.messageHistory=await this.getMessageHistory(n),t}},Ke={};I(Ke,{RouterRunnable:()=>Ue,Runnable:()=>z,RunnableAssign:()=>oe,RunnableBinding:()=>xe,RunnableBranch:()=>We,RunnableEach:()=>Fe,RunnableLambda:()=>ce,RunnableMap:()=>pe,RunnableParallel:()=>De,RunnablePassthrough:()=>H,RunnablePick:()=>Se,RunnableRetry:()=>ge,RunnableSequence:()=>he,RunnableToolLike:()=>j,RunnableWithFallbacks:()=>Le,RunnableWithMessageHistory:()=>Ge,_coerceToRunnable:()=>N,ensureConfig:()=>V,getCallbackManagerForConfig:()=>P,mergeConfigs:()=>Be,patchConfig:()=>w,pickRunnableConfigKeys:()=>o,raceWithSignal:()=>ze});var qe=class extends z{parseResultWithPrompt(e,t,n){return this.parseResult(e,n)}_baseMessageToString(e){return typeof e.content==`string`?e.content:this._baseMessageContentToString(e.content)}_baseMessageContentToString(e){return JSON.stringify(e)}async invoke(e,t){return typeof e==`string`?this._callWithConfig(async(e,t)=>this.parseResult([{text:e}],t?.callbacks),e,{...t,runType:`parser`}):this._callWithConfig(async(e,t)=>this.parseResult([{message:e,text:this._baseMessageToString(e)}],t?.callbacks),e,{...t,runType:`parser`})}},U=class extends qe{parseResult(e,t){return this.parse(e[0].text,t)}async parseWithPrompt(e,t,n){return this.parse(e,n)}_type(){throw Error(`_type not implemented`)}},W=class extends Error{llmOutput;observation;sendToLLM;constructor(e,t,n,r=!1){if(super(e),this.llmOutput=t,this.observation=n,this.sendToLLM=r,r&&(n===void 0||t===void 0))throw Error(`Arguments 'observation' & 'llmOutput' are required if 'sendToLlm' is true`);le(this,`OUTPUT_PARSING_FAILURE`)}},G=class extends U{async*_transform(e){for await(let t of e)typeof t==`string`?yield this.parseResult([{text:t}]):yield this.parseResult([{message:t,text:this._baseMessageToString(t)}])}async*transform(e,t){yield*this._transformStreamWithConfig(e,this._transform.bind(this),{...t,runType:`parser`})}},K=class extends G{diff=!1;constructor(e){super(e),this.diff=e?.diff??this.diff}async*_transform(e){let t,n;for await(let r of e){if(typeof r!=`string`&&typeof r.content!=`string`)throw Error(`Cannot handle non-string output.`);let e;if(m(r)){if(typeof r.content!=`string`)throw Error(`Cannot handle non-string message output.`);e=new Ee({message:r,text:r.content})}else if(L(r)){if(typeof r.content!=`string`)throw Error(`Cannot handle non-string message output.`);e=new Ee({message:ie(r),text:r.content})}else e=new Me({text:r});n=n===void 0?e:n.concat(e);let i=await this.parsePartialResult([n]);i!=null&&!ee(i,t)&&(this.diff?yield this._diff(t,i):yield i,t=i)}}getFormatInstructions(){return``}},Je=class extends G{static lc_name(){return`BytesOutputParser`}lc_namespace=[`langchain_core`,`output_parsers`,`bytes`];lc_serializable=!0;textEncoder=new TextEncoder;parse(e){return Promise.resolve(this.textEncoder.encode(e))}getFormatInstructions(){return``}},q=class extends G{re;async*_transform(e){let t=``;for await(let n of e)if(typeof n==`string`?t+=n:t+=n.content,this.re){let e=[...t.matchAll(this.re)];if(e.length>1){let n=0;for(let t of e.slice(0,-1))yield[t[1]],n+=(t.index??0)+t[0].length;t=t.slice(n)}}else{let e=await this.parse(t);if(e.length>1){for(let t of e.slice(0,-1))yield[t];t=e[e.length-1]}}for(let e of await this.parse(t))yield[e]}},Ye=class extends q{static lc_name(){return`CommaSeparatedListOutputParser`}lc_namespace=[`langchain_core`,`output_parsers`,`list`];lc_serializable=!0;async parse(e){try{return e.trim().split(`,`).map(e=>e.trim())}catch{throw new W(`Could not parse output: ${e}`,e)}}getFormatInstructions(){return"Your response should be a list of comma separated values, eg: `foo, bar, baz`"}},Xe=class extends q{lc_namespace=[`langchain_core`,`output_parsers`,`list`];length;separator;constructor({length:e,separator:t}){super(...arguments),this.length=e,this.separator=t||`,`}async parse(e){try{let t=e.trim().split(this.separator).map(e=>e.trim());if(this.length!==void 0&&t.length!==this.length)throw new W(`Incorrect number of items. Expected ${this.length}, got ${t.length}.`);return t}catch(t){throw Object.getPrototypeOf(t)===W.prototype?t:new W(`Could not parse output: ${e}`)}}getFormatInstructions(){return`Your response should be a list of ${this.length===void 0?``:`${this.length} `}items separated by "${this.separator}" (eg: \`foo${this.separator} bar${this.separator} baz\`)`}},Ze=class extends q{static lc_name(){return`NumberedListOutputParser`}lc_namespace=[`langchain_core`,`output_parsers`,`list`];lc_serializable=!0;getFormatInstructions(){return`Your response should be a numbered list with each item on a new line. For example:
|
|
2
2
|
|
|
3
3
|
1. foo
|
|
4
4
|
|