@mcp-use/inspector 0.13.2 → 0.14.0-canary.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/dist/cli.js +7 -53
  2. package/dist/client/assets/base-Aouj1Yhj.js +2 -0
  3. package/dist/client/assets/{index-CR9w_74S.js → base-ZEkF4ver.js} +33 -36
  4. package/dist/client/assets/browser-BWolhM7l.js +12 -0
  5. package/dist/client/assets/embeddings-BTUgP3x_.js +1 -0
  6. package/dist/client/assets/{index-BYR-I2bf.js → index-BOIA9kd1.js} +2 -2
  7. package/dist/client/assets/{index-sQyTG4jp.js → index-BSuQO5pd.js} +3 -3
  8. package/dist/client/assets/index-Bfe1ynAS.js +4 -0
  9. package/dist/client/assets/{index-ClpBZU-N.js → index-C88Q8iJs.js} +1 -1
  10. package/dist/client/assets/index-CNfmoBX-.js +1701 -0
  11. package/dist/client/assets/index-CSZqqrHs.js +34 -0
  12. package/dist/client/assets/index-CtWrgdCi.js +7 -0
  13. package/dist/client/assets/index-DIlJ2WcE.js +70 -0
  14. package/dist/client/assets/index-cMXsdFDY.css +1 -0
  15. package/dist/client/index.html +3 -3
  16. package/dist/server/{chunk-XGILHZOF.js → chunk-F7YWZTWJ.js} +4 -48
  17. package/dist/server/{chunk-JEKCWLHD.js → chunk-Y4GX3FDV.js} +1 -1
  18. package/dist/server/{chunk-MCMZDGO6.js → chunk-Z5QIR3IS.js} +2 -2
  19. package/dist/server/cli.js +2 -2
  20. package/dist/server/index.js +3 -3
  21. package/dist/server/middleware.js +3 -3
  22. package/dist/server/server.d.ts.map +1 -1
  23. package/dist/server/server.js +28 -5
  24. package/dist/server/shared-routes.d.ts.map +1 -1
  25. package/dist/server/shared-routes.js +2 -2
  26. package/dist/server/shared-utils-browser.d.ts.map +1 -1
  27. package/dist/server/shared-utils-browser.js +1 -1
  28. package/package.json +2 -2
  29. package/dist/client/assets/browser-DZ15LLaB.js +0 -501
  30. package/dist/client/assets/display-A5IEINAP-HkQbiJ2E.js +0 -17
  31. package/dist/client/assets/embeddings-C0rUXJ5F.js +0 -1
  32. package/dist/client/assets/fs-u42MReIY.js +0 -1
  33. package/dist/client/assets/index-B5kLR_Rv.js +0 -33
  34. package/dist/client/assets/index-CkHH_UI9.js +0 -1676
  35. package/dist/client/assets/index-DQ7i0BFM.css +0 -1
  36. package/dist/client/assets/index-DRz5BQNA.js +0 -1
  37. package/dist/client/assets/index-DiwCBW8I.js +0 -7
  38. package/dist/client/assets/index-Dj6Mccu_.js +0 -20
  39. package/dist/client/assets/index-JiKw9JSs.js +0 -5
  40. package/dist/client/assets/index-Zctd0Z8B.js +0 -71
  41. package/dist/client/assets/llms-BDMth6TQ.js +0 -2
  42. package/dist/client/assets/path-BOQPmbms.js +0 -1
  43. package/dist/client/assets/path-MNZaYwxc.js +0 -1
  44. package/dist/client/assets/posthog-node-CuYhrq1Q.js +0 -1
  45. package/dist/client/assets/util-t-trnxQI.js +0 -1
  46. package/dist/client/assets/winston-CEUa9Wj-.js +0 -37
@@ -0,0 +1,12 @@
1
+ import{B as d,C as O,D as a,h as Y,Z as N,f as T,E,c as Z,n as W,s as z,b as Q,o as w,F as X}from"./index-CNfmoBX-.js";import{G as ve,H as Se,T as we,I as Ee,L as Ae,J as Ce,M as _e,T as Pe,K as Ie,V as Le,N as $e,O as Oe,P as Ne,P as Te}from"./index-CNfmoBX-.js";import{D as k}from"./index-CtWrgdCi.js";import"./base-ZEkF4ver.js";import"./base-Aouj1Yhj.js";async function*ee(c){for await(const e of c)if(e.event==="on_chat_model_stream"&&e.data?.chunk?.text){const t=e.data.chunk.text;typeof t=="string"&&t.length>0&&(yield t)}}d(ee,"streamEventsToAISDK");function te(c){return new ReadableStream({async start(e){try{for await(const t of c)e.enqueue(t);e.close()}catch(t){e.error(t)}}})}d(te,"createReadableStreamFromGenerator");async function*re(c){for await(const e of c)switch(e.event){case"on_chat_model_stream":if(e.data?.chunk?.text){const t=e.data.chunk.text;typeof t=="string"&&t.length>0&&(yield t)}break;case"on_tool_start":yield`
2
+ 🔧 Using tool: ${e.name}
3
+ `;break;case"on_tool_end":yield`
4
+ ✅ Tool completed: ${e.name}
5
+ `;break}}d(re,"streamEventsToAISDKWithTools");var M={},A;A=class{customCallbacks;availableHandlers=[];handlerNames=[];initialized=!1;verbose;observe;agentId;metadata;metadataProvider;tagsProvider;constructor(e={}){this.customCallbacks=e.customCallbacks,this.verbose=e.verbose??!1,this.observe=e.observe??!0,this.agentId=e.agentId,this.metadata=e.metadata,this.metadataProvider=e.metadataProvider,this.tagsProvider=e.tagsProvider}async collectAvailableHandlers(){if(!this.initialized){try{const{langfuseHandler:e,langfuseInitPromise:t}=await O(async()=>{const{langfuseHandler:n,langfuseInitPromise:s}=await Promise.resolve().then(()=>K);return{langfuseHandler:n,langfuseInitPromise:s}},void 0);if(this.agentId||this.metadata||this.metadataProvider||this.tagsProvider){const{initializeLangfuse:n}=await O(async()=>{const{initializeLangfuse:s}=await Promise.resolve().then(()=>K);return{initializeLangfuse:s}},void 0);await n(this.agentId,this.metadata,this.metadataProvider,this.tagsProvider),a.debug(`ObservabilityManager: Reinitialized Langfuse with agent ID: ${this.agentId}, metadata: ${JSON.stringify(this.metadata)}`)}else{const n=t();n&&await n}const r=e();r&&(this.availableHandlers.push(r),this.handlerNames.push("Langfuse"),a.debug("ObservabilityManager: Langfuse handler available"))}catch{a.debug("ObservabilityManager: Langfuse module not available")}this.initialized=!0}}async getCallbacks(){return this.observe?this.customCallbacks?(a.debug(`ObservabilityManager: Using ${this.customCallbacks.length} custom callbacks`),this.customCallbacks):(await this.collectAvailableHandlers(),this.availableHandlers.length>0?a.debug(`ObservabilityManager: Using ${this.availableHandlers.length} handlers`):a.debug("ObservabilityManager: No callbacks configured"),this.availableHandlers):(a.debug("ObservabilityManager: Observability disabled via observe=false"),[])}async getHandlerNames(){return this.observe?this.customCallbacks?this.customCallbacks.map(e=>e.constructor.name):(await this.collectAvailableHandlers(),this.handlerNames):[]}async hasCallbacks(){return this.observe?(await this.getCallbacks()).length>0:!1}async getStatus(){const e=await this.getCallbacks(),t=await this.getHandlerNames(),r=this.metadataProvider?this.metadataProvider():this.metadata||{},n=this.tagsProvider?this.tagsProvider():[];return{enabled:this.observe&&e.length>0,callbackCount:e.length,handlerNames:t,metadata:r,tags:n}}addCallback(e){this.customCallbacks||(this.customCallbacks=[]),this.customCallbacks.push(e),a.debug(`ObservabilityManager: Added custom callback: ${e.constructor.name}`)}clearCallbacks(){this.customCallbacks=[],a.debug("ObservabilityManager: Cleared all custom callbacks")}async flush(){const e=await this.getCallbacks();for(const t of e)"flushAsync"in t&&typeof t.flushAsync=="function"&&await t.flushAsync();a.debug("ObservabilityManager: All traces flushed")}async shutdown(){await this.flush();const e=await this.getCallbacks();for(const t of e)"shutdownAsync"in t&&typeof t.shutdownAsync=="function"?await t.shutdownAsync():"shutdown"in t&&typeof t.shutdown=="function"&&await t.shutdown();a.debug("ObservabilityManager: All handlers shutdown")}toString(){const e=this.handlerNames;return e.length>0?`ObservabilityManager(handlers=${e.join(", ")})`:"ObservabilityManager(no handlers)"}},d(A,"ObservabilityManager");var ne="/api/v1/chats",se="/api/v1/chats/{chat_id}/execute";function q(c,e,t,r,n){if(typeof c=="object"&&c!==null){const s=c;return{query:s.prompt,maxSteps:s.maxSteps,manageConnector:s.manageConnector,externalHistory:s.externalHistory,outputSchema:s.schema}}return{query:c,maxSteps:e,manageConnector:t,externalHistory:r,outputSchema:n}}d(q,"normalizeRemoteRunOptions");var C;C=class{agentId;apiKey;baseUrl;chatId=null;constructor(e){this.agentId=e.agentId,this.baseUrl=e.baseUrl??"https://cloud.mcp-use.com";const t=e.apiKey??(typeof process<"u"&&M?.MCP_USE_API_KEY);if(!t)throw new Error("API key is required for remote execution. Please provide it as a parameter or set the MCP_USE_API_KEY environment variable. You can get an API key from https://cloud.mcp-use.com");this.apiKey=t}pydanticToJsonSchema(e){return Y(e)}parseStructuredResponse(e,t){let r;if(typeof e=="object"&&e!==null)if("result"in e){const n=e.result;typeof n=="object"&&n!==null&&"result"in n?r=n.result:r=n}else r=e;else if(typeof e=="string")try{r=JSON.parse(e)}catch{r={content:e}}else r=e;try{return t.parse(r)}catch(n){a.warn(`Failed to parse structured output: ${n}`);const s=t._def?.shape();if(s&&"content"in s)return t.parse({content:String(r)});throw n}}async createChatSession(){const e={title:`Remote Agent Session - ${this.agentId}`,agent_id:this.agentId,type:"agent_execution"},t={"Content-Type":"application/json","x-api-key":this.apiKey},r=`${this.baseUrl}${ne}`;a.info(`📝 Creating chat session for agent ${this.agentId}`);try{const n=await fetch(r,{method:"POST",headers:t,body:JSON.stringify(e)});if(!n.ok){const o=await n.text(),u=n.status;throw u===404?new Error(`Agent not found: Agent '${this.agentId}' does not exist or you don't have access to it. Please verify the agent ID and ensure it exists in your account.`):new Error(`Failed to create chat session: ${u} - ${o}`)}const i=(await n.json()).id;return a.info(`✅ Chat session created: ${i}`),i}catch(n){throw n instanceof Error?new TypeError(`Failed to create chat session: ${n.message}`):new Error(`Failed to create chat session: ${String(n)}`)}}async run(e,t,r,n,s){const{query:i,maxSteps:o,externalHistory:u,outputSchema:p}=q(e,t,r,n,s);u!==void 0&&a.warn("External history is not yet supported for remote execution");try{a.info(`🌐 Executing query on remote agent ${this.agentId}`),this.chatId===null&&(this.chatId=await this.createChatSession());const b=this.chatId,S={query:i,max_steps:o??10};p&&(S.output_schema=this.pydanticToJsonSchema(p),a.info("🔧 Using structured output with schema"));const l={"Content-Type":"application/json","x-api-key":this.apiKey},g=`${this.baseUrl}${se.replace("{chat_id}",b)}`;a.info(`🚀 Executing agent in chat ${b}`);const m=await fetch(g,{method:"POST",headers:l,body:JSON.stringify(S),signal:AbortSignal.timeout(3e5)});if(!m.ok){const y=await m.text(),v=m.status;throw v===401?(a.error(`❌ Authentication failed: ${y}`),new Error("Authentication failed: Invalid or missing API key. Please check your API key and ensure the MCP_USE_API_KEY environment variable is set correctly.")):v===403?(a.error(`❌ Access forbidden: ${y}`),new Error(`Access denied: You don't have permission to execute agent '${this.agentId}'. Check if the agent exists and you have the necessary permissions.`)):v===404?(a.error(`❌ Agent not found: ${y}`),new Error(`Agent not found: Agent '${this.agentId}' does not exist or you don't have access to it. Please verify the agent ID and ensure it exists in your account.`)):v===422?(a.error(`❌ Validation error: ${y}`),new Error(`Request validation failed: ${y}. Please check your query parameters and output schema format.`)):v===500?(a.error(`❌ Server error: ${y}`),new Error("Internal server error occurred during agent execution. Please try again later or contact support if the issue persists.")):(a.error(`❌ Remote execution failed with status ${v}: ${y}`),new Error(`Remote agent execution failed: ${v} - ${y}`))}const f=await m.json();if(a.info(`🔧 Response: ${JSON.stringify(f)}`),a.info("✅ Remote execution completed successfully"),typeof f=="object"&&f!==null){if(f.status==="error"||f.error!==null){const y=f.error??String(f);throw a.error(`❌ Remote agent execution failed: ${y}`),new Error(`Remote agent execution failed: ${y}`)}if(String(f).includes("failed to initialize"))throw a.error(`❌ Agent initialization failed: ${f}`),new Error(`Agent initialization failed on remote server. This usually indicates:
6
+ • Invalid agent configuration (LLM model, system prompt)
7
+ • Missing or invalid MCP server configurations
8
+ • Network connectivity issues with MCP servers
9
+ • Missing environment variables or credentials
10
+ Raw error: ${f}`)}return p?this.parseStructuredResponse(f,p):typeof f=="object"&&f!==null&&"result"in f?f.result:typeof f=="string"?f:String(f)}catch(b){throw b instanceof Error?b.name==="AbortError"?(a.error(`❌ Remote execution timed out: ${b}`),new Error("Remote agent execution timed out. The server may be overloaded or the query is taking too long to process. Try again or use a simpler query.")):(a.error(`❌ Remote execution error: ${b}`),new Error(`Remote agent execution failed: ${b.message}`)):(a.error(`❌ Remote execution error: ${b}`),new Error(`Remote agent execution failed: ${String(b)}`))}}async*stream(e,t,r,n,s){return await this.run(e,t,r,n,s)}async close(){a.info("🔌 Remote agent client closed")}},d(C,"RemoteAgent");var L={openai:{package:"@langchain/openai",className:"ChatOpenAI",envVars:["OPENAI_API_KEY"],defaultModel:"gpt-4o"},anthropic:{package:"@langchain/anthropic",className:"ChatAnthropic",envVars:["ANTHROPIC_API_KEY"],defaultModel:"claude-3-5-sonnet-20241022"},google:{package:"@langchain/google-genai",className:"ChatGoogleGenerativeAI",envVars:["GOOGLE_API_KEY","GOOGLE_GENERATIVE_AI_API_KEY"],defaultModel:"gemini-pro"},groq:{package:"@langchain/groq",className:"ChatGroq",envVars:["GROQ_API_KEY"],defaultModel:"llama-3.1-70b-versatile"}};function x(c){const e=c.split("/");if(e.length!==2)throw new Error(`Invalid LLM string format. Expected 'provider/model', got '${c}'. Examples: 'openai/gpt-4', 'anthropic/claude-3-5-sonnet-20241022', 'google/gemini-pro', 'groq/llama-3.1-70b-versatile'`);const[t,r]=e;if(!t||!r)throw new Error(`Invalid LLM string format. Both provider and model must be non-empty. Got '${c}'`);const n=t.toLowerCase();if(!(n in L)){const s=Object.keys(L).join(", ");throw new Error(`Unsupported LLM provider '${t}'. Supported providers: ${s}`)}return{provider:n,model:r}}d(x,"parseLLMString");function G(c,e){if(e?.apiKey)return e.apiKey;const t=L[c];if(typeof process<"u"&&M)for(const n of t.envVars){const s=M[n];if(s)return a.debug(`Using API key from environment variable ${n} for provider ${c}`),s}const r=t.envVars.join(" or ");throw new Error(`API key not found for provider '${c}'. Set ${r} environment variable or pass apiKey in llmConfig. Example: new MCPAgent({ llm: '${c}/model', llmConfig: { apiKey: 'your-key' } })`)}d(G,"getAPIKey");async function ae(c,e){a.info(`Creating LLM from string: ${c}`);const{provider:t,model:r}=x(c),n=L[t],s=G(t,e);let i;try{a.debug(`Importing package ${n.package}...`),i=await import(n.package)}catch(p){throw p?.code==="MODULE_NOT_FOUND"||p?.message?.includes("Cannot find module")||p?.message?.includes("Cannot find package")?new Error(`Package '${n.package}' is not installed. Install it with: npm install ${n.package} or yarn add ${n.package}`):new Error(`Failed to import ${n.package}: ${p?.message||p}`)}const o=i[n.className];if(!o)throw new Error(`Could not find ${n.className} in package ${n.package}. This might be a version compatibility issue.`);const u={model:r,apiKey:s,...e};e?.apiKey&&(delete u.apiKey,u.apiKey=s),(t==="anthropic"||t==="google"||t==="openai"||t==="groq")&&(u.model=r);try{const p=new o(u);return a.info(`Successfully created ${t} LLM with model ${r}`),p}catch(p){throw new Error(`Failed to instantiate ${n.className} with model '${r}': ${p?.message||p}`)}}d(ae,"createLLMFromString");function ie(c){try{return x(c),!0}catch{return!1}}d(ie,"isValidLLMString");function oe(){return Object.keys(L)}d(oe,"getSupportedProviders");var F={};function h(c){if(typeof process<"u"&&F)return F[c]}d(h,"getEnvVar");var le=h("MCP_USE_LANGFUSE")?.toLowerCase()==="false",$={handler:null,client:null,initPromise:null};async function R(c,e,t,r){try{const n=await O(()=>import("langfuse-langchain"),[]).catch(()=>null);if(!n){a.debug("Langfuse package not installed - tracing disabled. Install with: npm install @langfuse/langchain");return}const{CallbackHandler:s}=n,b=class b extends s{agentId;metadata;metadataProvider;tagsProvider;verbose;constructor(l,g,m,f,y){super(l),this.agentId=g,this.metadata=m,this.metadataProvider=f,this.tagsProvider=y,this.verbose=l?.verbose??!1}async handleChainStart(l,g,m,f,y,v,V,J){a.debug("Langfuse: Chain start intercepted");const D=this.getCustomTags(),B=this.getMetadata(),U=[...y||[],...D],j={...v||{},...B};return this.verbose&&(a.debug(`Langfuse: Chain start with custom tags: ${JSON.stringify(U)}`),a.debug(`Langfuse: Chain start with metadata: ${JSON.stringify(j)}`)),super.handleChainStart(l,g,m,f,U,j,V,J)}getCustomTags(){const l=[],g=this.getEnvironmentTag();if(g&&l.push(`env:${g}`),this.agentId&&l.push(`agent_id:${this.agentId}`),this.tagsProvider){const m=this.tagsProvider();m&&m.length>0&&l.push(...m)}return l}getMetadata(){const l={},g=this.getEnvironmentTag();if(g&&(l.env=g),this.agentId&&(l.agent_id=this.agentId),this.metadata&&Object.assign(l,this.metadata),this.metadataProvider){const m=this.metadataProvider();m&&Object.assign(l,m)}return l}getEnvironmentTag(){const l=h("MCP_USE_AGENT_ENV");if(!l)return"unknown";const g=l.toLowerCase();return g==="local"||g==="development"?"local":g==="production"||g==="prod"?"production":g==="staging"||g==="stage"?"staging":g==="hosted"||g==="cloud"?"hosted":g.replace(/[^a-z0-9_-]/g,"_")}async handleLLMStart(...l){return a.debug("Langfuse: LLM start intercepted"),this.verbose&&a.debug(`Langfuse: LLM start args: ${JSON.stringify(l)}`),super.handleLLMStart(...l)}async handleToolStart(...l){return a.debug("Langfuse: Tool start intercepted"),this.verbose&&a.debug(`Langfuse: Tool start args: ${JSON.stringify(l)}`),super.handleToolStart(...l)}async handleRetrieverStart(...l){return a.debug("Langfuse: Retriever start intercepted"),this.verbose&&a.debug(`Langfuse: Retriever start args: ${JSON.stringify(l)}`),super.handleRetrieverStart(...l)}async handleAgentAction(...l){return a.debug("Langfuse: Agent action intercepted"),this.verbose&&a.debug(`Langfuse: Agent action args: ${JSON.stringify(l)}`),super.handleAgentAction(...l)}async handleAgentEnd(...l){return a.debug("Langfuse: Agent end intercepted"),this.verbose&&a.debug(`Langfuse: Agent end args: ${JSON.stringify(l)}`),super.handleAgentEnd(...l)}};d(b,"LoggingCallbackHandler");let i=b;const o=e||(t?t():{}),u=r?r():[],p={publicKey:h("LANGFUSE_PUBLIC_KEY"),secretKey:h("LANGFUSE_SECRET_KEY"),baseUrl:h("LANGFUSE_HOST")||h("LANGFUSE_BASEURL")||"https://cloud.langfuse.com",flushAt:Number.parseInt(h("LANGFUSE_FLUSH_AT")||"15"),flushInterval:Number.parseInt(h("LANGFUSE_FLUSH_INTERVAL")||"10000"),release:h("LANGFUSE_RELEASE"),requestTimeout:Number.parseInt(h("LANGFUSE_REQUEST_TIMEOUT")||"10000"),enabled:h("LANGFUSE_ENABLED")!=="false",traceName:o.trace_name||h("LANGFUSE_TRACE_NAME")||"mcp-use-agent",sessionId:o.session_id||void 0,userId:o.user_id||void 0,tags:u.length>0?u:void 0,metadata:o||void 0};a.debug("Langfuse handler config:",JSON.stringify({traceName:p.traceName,sessionId:p.sessionId,userId:p.userId,tags:p.tags},null,2)),$.handler=new i(p,c,e,t,r),a.debug("Langfuse observability initialized successfully with logging enabled");try{const S=await O(()=>import("langfuse"),[]).catch(()=>null);if(S){const{Langfuse:l}=S;$.client=new l({publicKey:h("LANGFUSE_PUBLIC_KEY"),secretKey:h("LANGFUSE_SECRET_KEY"),baseUrl:h("LANGFUSE_HOST")||"https://cloud.langfuse.com"}),a.debug("Langfuse client initialized")}}catch(S){a.debug(`Langfuse client initialization failed: ${S}`)}}catch(n){a.debug(`Langfuse initialization error: ${n}`)}}d(R,"initializeLangfuse");le?a.debug("Langfuse tracing disabled via MCP_USE_LANGFUSE environment variable"):!h("LANGFUSE_PUBLIC_KEY")||!h("LANGFUSE_SECRET_KEY")?a.debug("Langfuse API keys not found - tracing disabled. Set LANGFUSE_PUBLIC_KEY and LANGFUSE_SECRET_KEY to enable"):$.initPromise=R();var ce=d(()=>$.handler,"langfuseHandler"),ue=d(()=>$.initPromise,"langfuseInitPromise"),_,de=(_=class{disallowedTools;connectorToolMap=new Map;constructor(e){this.disallowedTools=e??[]}static async createTools(e,t){const r=new this(t);(!e.activeSessions||Object.keys(e.activeSessions).length===0)&&(a.info("No active sessions found, creating new ones..."),await e.createAllSessions());const n=e.getAllActiveSessions(),s=Object.values(n).map(i=>i.connector);return r.createToolsFromConnectors(s)}async loadToolsForConnector(e){if(this.connectorToolMap.has(e)){const n=this.connectorToolMap.get(e);return a.debug(`Returning ${n.length} existing tools for connector`),n}const t=[];if(!await this.ensureConnectorInitialized(e))return[];for(const n of e.tools){const s=this.convertTool(n,e);s&&t.push(s)}return this.connectorToolMap.set(e,t),a.debug(`Loaded ${t.length} new tools for connector: ${t.map(n=>n?.name??String(n)).join(", ")}`),t}async createToolsFromConnectors(e){const t=[];for(const r of e){const n=await this.loadToolsForConnector(r);t.push(...n)}return a.debug(`Available tools: ${t.length}`),t}async loadResourcesForConnector(e){const t=[];if(!await this.ensureConnectorInitialized(e))return[];try{const s=(await e.listAllResources())?.resources||[];if(this.convertResource)for(const i of s){const o=this.convertResource(i,e);o&&t.push(o)}a.debug(`Loaded ${t.length} new resources for connector: ${t.map(i=>i?.name??String(i)).join(", ")}`)}catch(n){a.warn(`Error loading resources for connector: ${n}`)}return t}async loadPromptsForConnector(e){const t=[];if(!await this.ensureConnectorInitialized(e))return[];try{const s=(await e.listPrompts())?.prompts||[];if(this.convertPrompt)for(const i of s){const o=this.convertPrompt(i,e);o&&t.push(o)}a.debug(`Loaded ${t.length} new prompts for connector: ${t.map(i=>i?.name??String(i)).join(", ")}`)}catch(n){a.warn(`Error loading prompts for connector: ${n}`)}return t}async createResourcesFromConnectors(e){const t=[];for(const r of e){const n=await this.loadResourcesForConnector(r);t.push(...n)}return a.debug(`Available resources: ${t.length}`),t}async createPromptsFromConnectors(e){const t=[];for(const r of e){const n=await this.loadPromptsForConnector(r);t.push(...n)}return a.debug(`Available prompts: ${t.length}`),t}checkConnectorInitialized(e){return!!(e.tools&&e.tools.length)}async ensureConnectorInitialized(e){if(!this.checkConnectorInitialized(e)){a.debug("Connector doesn't have tools, initializing it");try{return await e.initialize(),!0}catch(t){return a.error(`Error initializing connector: ${t}`),!1}}return!0}},d(_,"BaseAdapter"),_),P,fe=(P=class{static convert(e){return this.parseSchema(e)}static matchesCondition(e,t){if(!t.properties)return!0;if(typeof e!="object"||e===null||Array.isArray(e))return!1;const r=e;for(const[n,s]of Object.entries(t.properties)){if(!(n in r)){if("const"in s)return!1;continue}const i=r[n];if("const"in s&&i!==s.const||"minimum"in s&&typeof i=="number"&&i<s.minimum||"maximum"in s&&typeof i=="number"&&i>s.maximum)return!1}return!0}static validateConditionalSchema(e,t,r){this.validateRequiredProperties(e,t,r),this.validatePropertyPatterns(e,t,r),this.validateNestedConditions(e,t,r)}static validateRequiredProperties(e,t,r){if(t.required){if(typeof e!="object"||e===null){for(const n of t.required)r.addIssue({code:N.custom,message:`Required property '${n}' is missing`,path:[n]});return}for(const n of t.required)n in e||r.addIssue({code:N.custom,message:`Required property '${n}' is missing`,path:[n]})}}static validatePropertyPatterns(e,t,r){if(!t.properties||typeof e!="object"||e===null||Array.isArray(e))return;const n=e;for(const[s,i]of Object.entries(t.properties)){if(!(s in n))continue;const o=n[s];i.pattern&&typeof o=="string"&&(new RegExp(i.pattern).test(o)||r.addIssue({code:N.custom,message:`String '${o}' does not match pattern '${i.pattern}'`,path:[s]}))}}static validateNestedConditions(e,t,r){if(!t.if||!t.then)return;this.matchesCondition(e,t.if)?this.validateConditionalSchema(e,t.then,r):t.else&&this.validateConditionalSchema(e,t.else,r)}static parseSchema(e){return Array.isArray(e.type)?this.handleTypeArray(e):e.oneOf||e.anyOf||e.allOf?this.parseCombinator(e):e.if&&e.then?this.parseObject(e):e.properties&&(!e.type||e.type==="object")?this.parseObject(e):this.handleSingleType(e)}static handleTypeArray(e){if(!Array.isArray(e.type))throw new Error("Expected schema.type to be an array");return e.type.includes("null")?this.handleNullableType(e):this.createUnionFromTypes(e.type,e)}static handleNullableType(e){if(!Array.isArray(e.type))throw new Error("Expected schema.type to be an array");const t={...e};return t.type=e.type.filter(n=>n!=="null"),t.type.length===1?this.handleSingleType({...e,type:t.type[0]}).nullable():this.parseSchema(t).nullable()}static createUnionFromTypes(e,t){const r=e.map(n=>{const s={...t,type:n};return this.parseSchema(s)});return T(r)}static handleSingleType(e){if(e.type===void 0)return e.oneOf||e.anyOf||e.allOf?this.parseCombinator(e):e.properties?this.parseObject(e):E();switch(e.type){case"string":return this.parseString(e);case"number":case"integer":return this.parseNumberSchema(e);case"boolean":return Z();case"array":return this.parseArray(e);case"object":return this.parseObject(e);default:throw new Error("Unsupported schema type")}}static parseNumberSchema(e){const t=W();let r=t;return r=this.applyNumberBounds(t,e),r=this.applyNumberMultipleOf(t,e),r=this.applyNumberEnum(t,e),r=this.applyIntegerConstraint(t,e),r}static applyNumberBounds(e,t){let r=e;return t.minimum!==void 0&&(r=t.exclusiveMinimum?r.gt(t.minimum):r.gte(t.minimum)),t.maximum!==void 0&&(r=t.exclusiveMaximum?r.lt(t.maximum):r.lte(t.maximum)),r}static applyNumberMultipleOf(e,t){return t.multipleOf===void 0?e:e.refine(r=>r%t.multipleOf===0,{message:`Number must be a multiple of ${t.multipleOf}`})}static applyNumberEnum(e,t){if(!t.enum)return e;const r=t.enum.filter(n=>typeof n=="number");return r.length===0?e:e.refine(n=>r.includes(n),{message:`Number must be one of: ${r.join(", ")}`})}static applyIntegerConstraint(e,t){return t.type!=="integer"?e:e.refine(r=>Number.isInteger(r),{message:"Number must be an integer"})}static parseString(e){const t=z();let r=t;return e.format?this.applyStringFormat(t,e):(r=this.applyStringPattern(t,e),r=this.applyStringLength(t,e),r=this.applyStringEnum(t,e),r)}static applyStringFormat(e,t){if(!t.format)return e;switch(t.format){case"email":return e.email();case"date-time":return e.datetime();case"uri":return e.url();case"uuid":return e.uuid();case"date":return e.date();default:return e}}static applyStringPattern(e,t){if(!t.pattern)return e;const r=new RegExp(t.pattern);return e.regex(r,{message:`String must match pattern: ${t.pattern}`})}static applyStringLength(e,t){const r=e;return t.minLength!==void 0&&(e=e.min(t.minLength)),t.maxLength!==void 0&&(e=e.max(t.maxLength)),r}static applyStringEnum(e,t){return t.enum?e.refine(r=>t.enum?.includes(r),{message:`Value must be one of: ${t.enum?.join(", ")}`}):e}static parseArray(e){if(Array.isArray(e.items)){const s=e.items.map(i=>this.parseSchema(i));return T(s)}const t=e.items?this.parseSchema(e.items):E(),r=Q(t);let n=r;return n=this.applyArrayConstraints(r,e),n}static applyArrayConstraints(e,t){return t.minItems!==void 0&&(e=e.min(t.minItems)),t.maxItems!==void 0&&(e=e.max(t.maxItems)),t.uniqueItems?e.refine(r=>new Set(r).size===r.length,{message:"Array items must be unique"}):e}static parseObject(e){if(e.if&&e.then)return this.parseConditional(e);const t={};return this.processObjectProperties(e,t),this.processAdditionalProperties(e,w(t))}static processObjectProperties(e,t){const r=new Set(e.required||[]);if(e.properties)for(const[n,s]of Object.entries(e.properties)){const i=this.parseSchema(s);t[n]=r.has(n)?i:i.optional()}}static processAdditionalProperties(e,t){if(e.additionalProperties===!0)return t.passthrough();if(e.additionalProperties&&typeof e.additionalProperties=="object"){const r=this.parseSchema(e.additionalProperties);return t.catchall(r)}else return t.strict()}static parseConditional(e){const t=this.createBaseObjectSchema(e),r=e.if,n=e.then,s=e.else;return t.superRefine((i,o)=>{const u=this.applyDefaultValues(i,e);this.matchesCondition(u,r)?this.validateConditionalSchema(u,n,o):s&&this.validateConditionalSchema(u,s,o)})}static createBaseObjectSchema(e){const t={},r=new Set(e.required||[]);for(const[s,i]of Object.entries(e.properties||{})){const o=this.parseSchema(i);t[s]=r.has(s)?o:o.optional()}const n=w(t);return this.processAdditionalProperties(e,n)}static applyDefaultValues(e,t){if(typeof e!="object"||e===null||Array.isArray(e))return e;const n={...e};if(!t.properties)return n;for(const[s,i]of Object.entries(t.properties))!(s in n)&&"default"in i&&(n[s]=i.default);return n}static parseCombinator(e){if(e.oneOf)return this.parseOneOf(e.oneOf);if(e.anyOf)return this.parseAnyOf(e.anyOf);if(e.allOf)return this.parseAllOf(e.allOf);throw new Error("Unsupported schema type")}static parseOneOf(e){return this.createUnionFromSchemas(e)}static parseAnyOf(e){return this.createUnionFromSchemas(e)}static createUnionFromSchemas(e){if(e.length===0)return E();if(e.length===1)return this.parseSchema(e[0]);const t=[];for(const r of e)r.type==="null"?t.push(X()):t.push(this.parseSchema(r));return t.length>=2?T(t):t.length===1?t[0]:E()}static parseAllOf(e){if(e.length===0)return E();if(e.length===1)return this.parseSchema(e[0]);const t=e.reduce((r,n)=>this.mergeSchemas(r,n));return this.parseSchema(t)}static mergeSchemas(e,t){const r={...e,...t};if(e.properties&&t.properties){const n={...e.properties,...t.properties};r.properties=n}if(e.required&&t.required){const n=[...new Set([...e.required,...t.required])];r.required=n}return r}},d(P,"JSONSchemaToZod"),P);function H(c){try{return fe.convert(c)}catch(e){return a.warn(`Failed to convert JSON schema to Zod: ${e}`),E()}}d(H,"schemaToZod");var I;I=class extends de{constructor(e=[]){super(e)}convertTool(e,t){if(this.disallowedTools.includes(e.name))return null;const r=e.inputSchema?H(e.inputSchema):w({}).optional();return new k({name:e.name??"NO NAME",description:e.description??"",schema:r,func:d(async s=>{a.debug(`MCP tool "${e.name}" received input: ${JSON.stringify(s)}`);try{const i=await t.callTool(e.name,s);return JSON.stringify(i)}catch(i){return a.error(`Error executing MCP tool: ${i.message}`),`Error executing MCP tool: ${String(i)}`}},"func")})}convertResource(e,t){const n=d(o=>o.replace(/[^A-Za-z0-9_]+/g,"_").toLowerCase().replace(/^_+|_+$/g,""),"sanitizeName")(e.name||`resource_${e.uri}`),s=e.uri;return new k({name:n,description:e.description||`Return the content of the resource located at URI ${s}.`,schema:w({}).optional(),func:d(async()=>{a.debug(`Resource tool: "${n}" called`);try{const o=await t.readResource(s);return o.contents&&o.contents.length>0?o.contents.map(u=>typeof u=="string"?u:u.text?u.text:u.uri?u.uri:JSON.stringify(u)).join(`
11
+ `):"Resource is empty or unavailable"}catch(o){return a.error(`Error reading resource: ${o.message}`),`Error reading resource: ${String(o)}`}},"func")})}convertPrompt(e,t){let r=w({}).optional();if(e.arguments&&e.arguments.length>0){const s={};for(const i of e.arguments){const o=z();i.required!==!1?s[i.name]=o:s[i.name]=o.optional()}r=Object.keys(s).length>0?w(s):w({}).optional()}return new k({name:e.name,description:e.description||"",schema:r,func:d(async s=>{a.debug(`Prompt tool: "${e.name}" called with args: ${JSON.stringify(s)}`);try{const i=await t.getPrompt(e.name,s);return i.messages&&i.messages.length>0?i.messages.map(o=>typeof o=="string"?o:o.content?typeof o.content=="string"?o.content:JSON.stringify(o.content):JSON.stringify(o)).join(`
12
+ `):"Prompt returned no messages"}catch(i){return a.error(`Error getting prompt: ${i.message}`),`Error getting prompt: ${String(i)}`}},"func")})}},d(I,"LangChainAdapter");const K=Object.freeze(Object.defineProperty({__proto__:null,initializeLangfuse:R,langfuseHandler:ce,langfuseInitPromise:ue},Symbol.toStringTag,{value:"Module"}));export{de as BaseAdapter,ve as BaseConnector,Se as BrowserOAuthClientProvider,we as BrowserTelemetry,Ee as HttpConnector,Ae as Logger,Ce as MCPClient,_e as MCPSession,Pe as Tel,Ie as Telemetry,Le as VERSION,ae as createLLMFromString,te as createReadableStreamFromGenerator,$e as getPackageVersion,oe as getSupportedProviders,ie as isValidLLMString,a as logger,Oe as onMcpAuthorization,x as parseLLMString,Ne as setBrowserTelemetrySource,Te as setTelemetrySource,ee as streamEventsToAISDK,re as streamEventsToAISDKWithTools};
@@ -0,0 +1 @@
1
+ import{_ as e,q as d}from"./base-ZEkF4ver.js";var l={};e(l,{chunkArray:()=>u});const u=(r,n)=>r.reduce((a,o,s)=>{const c=Math.floor(s/n),t=a[c]||[];return a[c]=t.concat([o]),a},[]);var _={};e(_,{Embeddings:()=>h});var h=class{caller;constructor(r){this.caller=new d(r??{})}};
@@ -1,2 +1,2 @@
1
- import{c as at,f as rt,g as mt,O as Ct,h as Ot,J as yt,R as G}from"./index-Zctd0Z8B.js";import{i as ut,y as It,z as vt,B as _t,D as Et,E as Tt,F as wt,H as St,t as lt,I as Rt,J as At,K as x,r as xt,L as kt,M as Nt}from"./index-CR9w_74S.js";import"./embeddings-C0rUXJ5F.js";import"./index-CkHH_UI9.js";import"./index-DRz5BQNA.js";function I(t){if(typeof t=="object"&&t!==null){const e={...t};"additionalProperties"in e&&delete e.additionalProperties,"$schema"in e&&delete e.$schema,"strict"in e&&delete e.strict;for(const n in e)n in e&&(Array.isArray(e[n])?e[n]=e[n].map(I):typeof e[n]=="object"&&e[n]!==null&&(e[n]=I(e[n])));return e}return t}function N(t){const e=I(ut(t)?It(t):t),{$schema:n,...s}=e;return s}function bt(t){const e=I(t),{$schema:n,...s}=e;return s}const h=[];for(let t=0;t<256;++t)h.push((t+256).toString(16).slice(1));function Mt(t,e=0){return(h[t[e+0]]+h[t[e+1]]+h[t[e+2]]+h[t[e+3]]+"-"+h[t[e+4]]+h[t[e+5]]+"-"+h[t[e+6]]+h[t[e+7]]+"-"+h[t[e+8]]+h[t[e+9]]+"-"+h[t[e+10]]+h[t[e+11]]+h[t[e+12]]+h[t[e+13]]+h[t[e+14]]+h[t[e+15]]).toLowerCase()}let k;const Dt=new Uint8Array(16);function Gt(){if(!k){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");k=crypto.getRandomValues.bind(crypto)}return k(Dt)}const Ut=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),U={randomUUID:Ut};function ct(t,e,n){if(U.randomUUID&&!t)return U.randomUUID();t=t||{};const s=t.random??t.rng?.()??Gt();if(s.length<16)throw new Error("Random bytes length must be >= 16");return s[6]=s[6]&15|64,s[8]=s[8]&63|128,Mt(s)}const b="__gemini_function_call_thought_signatures__",Lt="ErYCCrMCAdHtim9kOoOkrPiCNVsmlpMIKd7ZMxgiFbVQOkgp7nlLcDMzVsZwIzvuT7nQROivoXA72ccC2lSDvR0Gh7dkWaGuj7ctv6t7ZceHnecx0QYa+ix8tYpRfjhyWozQ49lWiws6+YGjCt10KRTyWsZ2h6O7iHTYJwKIRwGUHRKy/qK/6kFxJm5ML00gLq4D8s5Z6DBpp2ZlR+uF4G8jJgeWQgyHWVdx2wGYElaceVAc66tZdPQRdOHpWtgYSI1YdaXgVI8KHY3/EfNc2YqqMIulvkDBAnuMhkAjV9xmBa54Tq+ih3Im4+r3DzqhGqYdsSkhS0kZMwte4Hjs65dZzCw9lANxIqYi1DJ639WNPYihp/DCJCos7o+/EeSPJaio5sgWDyUnMGkY1atsJZ+m7pj7DD5tvQ==",Pt=t=>t();function jt(t){return wt.isInstance(t)?t.role:t.type}function Ft(t){switch(t){case"supervisor":case"ai":case"model":return"model";case"system":return"system";case"human":return"user";case"tool":case"function":return"function";default:throw new Error(`Unknown / unsupported author: ${t}`)}}function Kt(t){if("mimeType"in t&&"data"in t)return{inlineData:{mimeType:t.mimeType,data:t.data}};if("mimeType"in t&&"fileUri"in t)return{fileData:{mimeType:t.mimeType,fileUri:t.fileUri}};throw new Error("Invalid media content")}function Ht(t,e){return e.map(n=>lt(n)?n.tool_calls??[]:[]).flat().find(n=>n.id===t.tool_call_id)?.name}function $t(t){return{providerName:"Google Gemini",fromStandardTextBlock(n){return{text:n.text}},fromStandardImageBlock(n){if(!t)throw new Error("This model does not support images");if(n.source_type==="url"){const s=x({dataUrl:n.url});return s?{inlineData:{mimeType:s.mime_type,data:s.data}}:{fileData:{mimeType:n.mime_type??"",fileUri:n.url}}}if(n.source_type==="base64")return{inlineData:{mimeType:n.mime_type??"",data:n.data}};throw new Error(`Unsupported source type: ${n.source_type}`)},fromStandardAudioBlock(n){if(!t)throw new Error("This model does not support audio");if(n.source_type==="url"){const s=x({dataUrl:n.url});return s?{inlineData:{mimeType:s.mime_type,data:s.data}}:{fileData:{mimeType:n.mime_type??"",fileUri:n.url}}}if(n.source_type==="base64")return{inlineData:{mimeType:n.mime_type??"",data:n.data}};throw new Error(`Unsupported source type: ${n.source_type}`)},fromStandardFileBlock(n){if(!t)throw new Error("This model does not support files");if(n.source_type==="text")return{text:n.text};if(n.source_type==="url"){const s=x({dataUrl:n.url});return s?{inlineData:{mimeType:s.mime_type,data:s.data}}:{fileData:{mimeType:n.mime_type??"",fileUri:n.url}}}if(n.source_type==="base64")return{inlineData:{mimeType:n.mime_type??"",data:n.data}};throw new Error(`Unsupported source type: ${n.source_type}`)}}}function L(t,e){if(Rt(t))return At(t,$t(e));if(t.type==="text")return{text:t.text};if(t.type==="executableCode")return{executableCode:t.executableCode};if(t.type==="codeExecutionResult")return{codeExecutionResult:t.codeExecutionResult};if(t.type==="image_url"){if(!e)throw new Error("This model does not support images");let n;if(typeof t.image_url=="string")n=t.image_url;else if(typeof t.image_url=="object"&&"url"in t.image_url)n=t.image_url.url;else throw new Error("Please provide image as base64 encoded data URL");const[s,i]=n.split(",");if(!s.startsWith("data:"))throw new Error("Please provide image as base64 encoded data URL");const[o,a]=s.replace(/^data:/,"").split(";");if(a!=="base64")throw new Error("Please provide image as base64 encoded data URL");return{inlineData:{data:i,mimeType:o}}}else{if(t.type==="media")return Kt(t);if(t.type==="tool_use")return{functionCall:{name:t.name,args:t.input}};if(t.type?.includes("/")&&t.type.split("/").length===2&&"data"in t&&typeof t.data=="string")return{inlineData:{mimeType:t.type,data:t.data}};if("functionCall"in t)return;throw"type"in t?new Error(`Unknown content type ${t.type}`):new Error(`Unknown content ${JSON.stringify(t)}`)}}function Yt(t,e,n,s){if(St(t)){const u=t.name??Ht(t,n);if(u===void 0)throw new Error(`Google requires a tool name for each tool call response, and we could not infer a called tool name for ToolMessage "${t.id}" from your passed messages. Please populate a "name" field on that ToolMessage explicitly.`);const c=Array.isArray(t.content)?t.content.map(p=>L(p,e)).filter(p=>p!==void 0):t.content;return t.status==="error"?[{functionResponse:{name:u,response:{error:{details:c}}}}]:[{functionResponse:{name:u,response:{result:c}}}]}let i=[];const o=[];typeof t.content=="string"&&t.content&&o.push({text:t.content}),Array.isArray(t.content)&&o.push(...t.content.map(u=>L(u,e)).filter(u=>u!==void 0));const a=t.additional_kwargs?.[b];return lt(t)&&t.tool_calls?.length&&(i=t.tool_calls.map(u=>{const c=Pt(()=>{if(u.id){const p=a?.[u.id];if(p)return p}return s?.includes("gemini-3")?Lt:""});return{functionCall:{name:u.name,args:u.args},...c?{thoughtSignature:c}:{}}})),[...o,...i]}function P(t,e,n=!1,s){return t.reduce((i,o,a)=>{if(!vt(o))throw new Error("Unsupported message input");const u=jt(o);if(u==="system"&&a!==0)throw new Error("System message should be the first one");const c=Ft(u),p=i.content[i.content.length];if(!i.mergeWithPreviousContent&&p&&p.role===c)throw new Error("Google Generative AI requires alternate messages between authors");const r=Yt(o,e,t.slice(0,a),s);if(i.mergeWithPreviousContent){const d=i.content[i.content.length-1];if(!d)throw new Error("There was a problem parsing your system message. Please try a prompt without one.");return d.parts.push(...r),{mergeWithPreviousContent:!1,content:i.content}}let l=c;(l==="function"||l==="system"&&!n)&&(l="user");const f={role:l,parts:r};return{mergeWithPreviousContent:u==="system"&&!n,content:[...i.content,f]}},{content:[],mergeWithPreviousContent:!1}).content}function Bt(t,e){if(!t.candidates||t.candidates.length===0||!t.candidates[0])return{generations:[],llmOutput:{filters:t.promptFeedback}};const[n]=t.candidates,{content:s,...i}=n,o=s.parts?.reduce((r,l)=>("functionCall"in l&&l.functionCall&&r.push({...l,id:"id"in l.functionCall&&typeof l.functionCall.id=="string"?l.functionCall.id:ct()}),r),[]);let a;Array.isArray(s?.parts)&&s.parts.length===1&&s.parts[0].text?a=s.parts[0].text:Array.isArray(s?.parts)&&s.parts.length>0?a=s.parts.map(r=>"text"in r?{type:"text",text:r.text}:"inlineData"in r?{type:"inlineData",inlineData:r.inlineData}:"functionCall"in r?{type:"functionCall",functionCall:r.functionCall}:"functionResponse"in r?{type:"functionResponse",functionResponse:r.functionResponse}:"fileData"in r?{type:"fileData",fileData:r.fileData}:"executableCode"in r?{type:"executableCode",executableCode:r.executableCode}:"codeExecutionResult"in r?{type:"codeExecutionResult",codeExecutionResult:r.codeExecutionResult}:r):a=[];const u=o?.reduce((r,l)=>("thoughtSignature"in l&&typeof l.thoughtSignature=="string"&&(r[l.id]=l.thoughtSignature),r),{});let c="";return typeof a=="string"?c=a:Array.isArray(a)&&a.length>0&&(c=a.find(l=>"text"in l)?.text??c),{generations:[{text:c,message:new _t({content:a??"",tool_calls:o?.map(r=>({type:"tool_call",id:r.id,name:r.functionCall.name,args:r.functionCall.args})),additional_kwargs:{...i,[b]:u},usage_metadata:e?.usageMetadata}),generationInfo:i}],llmOutput:{tokenUsage:{promptTokens:e?.usageMetadata?.input_tokens,completionTokens:e?.usageMetadata?.output_tokens,totalTokens:e?.usageMetadata?.total_tokens}}}}function qt(t,e){if(!t.candidates||t.candidates.length===0)return null;const[n]=t.candidates,{content:s,...i}=n,o=s.parts?.reduce((r,l)=>("functionCall"in l&&l.functionCall&&r.push({...l,id:"id"in l.functionCall&&typeof l.functionCall.id=="string"?l.functionCall.id:ct()}),r),[]);let a;Array.isArray(s?.parts)&&s.parts.every(r=>"text"in r)?a=s.parts.map(r=>r.text).join(""):Array.isArray(s?.parts)?a=s.parts.map(r=>"text"in r?{type:"text",text:r.text}:"inlineData"in r?{type:"inlineData",inlineData:r.inlineData}:"functionCall"in r?{type:"functionCall",functionCall:r.functionCall}:"functionResponse"in r?{type:"functionResponse",functionResponse:r.functionResponse}:"fileData"in r?{type:"fileData",fileData:r.fileData}:"executableCode"in r?{type:"executableCode",executableCode:r.executableCode}:"codeExecutionResult"in r?{type:"codeExecutionResult",codeExecutionResult:r.codeExecutionResult}:r):a=[];let u="";a&&typeof a=="string"?u=a:Array.isArray(a)&&(u=a.find(l=>"text"in l)?.text??"");const c=[];o&&c.push(...o.map(r=>({type:"tool_call_chunk",id:r.id,name:r.functionCall.name,args:JSON.stringify(r.functionCall.args)})));const p=o?.reduce((r,l)=>("thoughtSignature"in l&&typeof l.thoughtSignature=="string"&&(r[l.id]=l.thoughtSignature),r),{});return new Et({text:u,message:new Tt({content:a||"",name:s?s.role:void 0,tool_call_chunks:c,additional_kwargs:{[b]:p},response_metadata:{model_provider:"google-genai"},usage_metadata:e.usageMetadata}),generationInfo:i})}function Wt(t){return t.every(e=>"functionDeclarations"in e&&Array.isArray(e.functionDeclarations))?t:[{functionDeclarations:t.map(e=>{if(at(e)){const n=N(e.schema);return n.type==="object"&&"properties"in n&&Object.keys(n.properties).length===0?{name:e.name,description:e.description}:{name:e.name,description:e.description,parameters:n}}return rt(e)?{name:e.function.name,description:e.function.description??"A function available to call.",parameters:bt(e.function.parameters)}:e})}]}function j(t,e){const n={input_tokens:t?.promptTokenCount??0,output_tokens:t?.candidatesTokenCount??0,total_tokens:t?.totalTokenCount??0};if(t?.cachedContentTokenCount&&(n.input_token_details??={},n.input_token_details.cache_read=t.cachedContentTokenCount),e==="gemini-3-pro-preview"){const s=Math.max(0,t?.promptTokenCount??-2e5),i=Math.max(0,t?.cachedContentTokenCount??-2e5);s&&(n.input_token_details={...n.input_token_details,over_200k:s}),i&&(n.input_token_details={...n.input_token_details,cache_read_over_200k:i})}return n}var F=class extends mt{static lc_name(){return"GoogleGenerativeAIToolsOutputParser"}lc_namespace=["langchain","google_genai","output_parsers"];returnId=!1;keyName;returnSingle=!1;zodSchema;constructor(t){super(t),this.keyName=t.keyName,this.returnSingle=t.returnSingle??this.returnSingle,this.zodSchema=t.zodSchema}async _validateResult(t){if(this.zodSchema===void 0)return t;const e=await xt(this.zodSchema,t);if(e.success)return e.data;throw new Ct(`Failed to parse. Text: "${JSON.stringify(t,null,2)}". Error: ${JSON.stringify(e.error.issues)}`,JSON.stringify(t,null,2))}async parseResult(t){const e=t.flatMap(i=>{const{message:o}=i;return!("tool_calls"in o)||!Array.isArray(o.tool_calls)?[]:o.tool_calls});if(e[0]===void 0)throw new Error("No parseable tool calls provided to GoogleGenerativeAIToolsOutputParser.");const[n]=e;return await this._validateResult(n.args)}},K;(function(t){t.STRING="string",t.NUMBER="number",t.INTEGER="integer",t.BOOLEAN="boolean",t.ARRAY="array",t.OBJECT="object"})(K||(K={}));var H;(function(t){t.LANGUAGE_UNSPECIFIED="language_unspecified",t.PYTHON="python"})(H||(H={}));var $;(function(t){t.OUTCOME_UNSPECIFIED="outcome_unspecified",t.OUTCOME_OK="outcome_ok",t.OUTCOME_FAILED="outcome_failed",t.OUTCOME_DEADLINE_EXCEEDED="outcome_deadline_exceeded"})($||($={}));const Y=["user","model","function","system"];var B;(function(t){t.HARM_CATEGORY_UNSPECIFIED="HARM_CATEGORY_UNSPECIFIED",t.HARM_CATEGORY_HATE_SPEECH="HARM_CATEGORY_HATE_SPEECH",t.HARM_CATEGORY_SEXUALLY_EXPLICIT="HARM_CATEGORY_SEXUALLY_EXPLICIT",t.HARM_CATEGORY_HARASSMENT="HARM_CATEGORY_HARASSMENT",t.HARM_CATEGORY_DANGEROUS_CONTENT="HARM_CATEGORY_DANGEROUS_CONTENT",t.HARM_CATEGORY_CIVIC_INTEGRITY="HARM_CATEGORY_CIVIC_INTEGRITY"})(B||(B={}));var q;(function(t){t.HARM_BLOCK_THRESHOLD_UNSPECIFIED="HARM_BLOCK_THRESHOLD_UNSPECIFIED",t.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",t.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",t.BLOCK_ONLY_HIGH="BLOCK_ONLY_HIGH",t.BLOCK_NONE="BLOCK_NONE"})(q||(q={}));var W;(function(t){t.HARM_PROBABILITY_UNSPECIFIED="HARM_PROBABILITY_UNSPECIFIED",t.NEGLIGIBLE="NEGLIGIBLE",t.LOW="LOW",t.MEDIUM="MEDIUM",t.HIGH="HIGH"})(W||(W={}));var V;(function(t){t.BLOCKED_REASON_UNSPECIFIED="BLOCKED_REASON_UNSPECIFIED",t.SAFETY="SAFETY",t.OTHER="OTHER"})(V||(V={}));var T;(function(t){t.FINISH_REASON_UNSPECIFIED="FINISH_REASON_UNSPECIFIED",t.STOP="STOP",t.MAX_TOKENS="MAX_TOKENS",t.SAFETY="SAFETY",t.RECITATION="RECITATION",t.LANGUAGE="LANGUAGE",t.BLOCKLIST="BLOCKLIST",t.PROHIBITED_CONTENT="PROHIBITED_CONTENT",t.SPII="SPII",t.MALFORMED_FUNCTION_CALL="MALFORMED_FUNCTION_CALL",t.OTHER="OTHER"})(T||(T={}));var J;(function(t){t.TASK_TYPE_UNSPECIFIED="TASK_TYPE_UNSPECIFIED",t.RETRIEVAL_QUERY="RETRIEVAL_QUERY",t.RETRIEVAL_DOCUMENT="RETRIEVAL_DOCUMENT",t.SEMANTIC_SIMILARITY="SEMANTIC_SIMILARITY",t.CLASSIFICATION="CLASSIFICATION",t.CLUSTERING="CLUSTERING"})(J||(J={}));var E;(function(t){t.MODE_UNSPECIFIED="MODE_UNSPECIFIED",t.AUTO="AUTO",t.ANY="ANY",t.NONE="NONE"})(E||(E={}));var z;(function(t){t.MODE_UNSPECIFIED="MODE_UNSPECIFIED",t.MODE_DYNAMIC="MODE_DYNAMIC"})(z||(z={}));class m extends Error{constructor(e){super(`[GoogleGenerativeAI Error]: ${e}`)}}class _ extends m{constructor(e,n){super(e),this.response=n}}class dt extends m{constructor(e,n,s,i){super(e),this.status=n,this.statusText=s,this.errorDetails=i}}class y extends m{}class ft extends m{}const Vt="https://generativelanguage.googleapis.com",Jt="v1beta",zt="0.24.1",Zt="genai-js";var v;(function(t){t.GENERATE_CONTENT="generateContent",t.STREAM_GENERATE_CONTENT="streamGenerateContent",t.COUNT_TOKENS="countTokens",t.EMBED_CONTENT="embedContent",t.BATCH_EMBED_CONTENTS="batchEmbedContents"})(v||(v={}));class Qt{constructor(e,n,s,i,o){this.model=e,this.task=n,this.apiKey=s,this.stream=i,this.requestOptions=o}toString(){var e,n;const s=((e=this.requestOptions)===null||e===void 0?void 0:e.apiVersion)||Jt;let o=`${((n=this.requestOptions)===null||n===void 0?void 0:n.baseUrl)||Vt}/${s}/${this.model}:${this.task}`;return this.stream&&(o+="?alt=sse"),o}}function Xt(t){const e=[];return t?.apiClient&&e.push(t.apiClient),e.push(`${Zt}/${zt}`),e.join(" ")}async function te(t){var e;const n=new Headers;n.append("Content-Type","application/json"),n.append("x-goog-api-client",Xt(t.requestOptions)),n.append("x-goog-api-key",t.apiKey);let s=(e=t.requestOptions)===null||e===void 0?void 0:e.customHeaders;if(s){if(!(s instanceof Headers))try{s=new Headers(s)}catch(i){throw new y(`unable to convert customHeaders value ${JSON.stringify(s)} to Headers: ${i.message}`)}for(const[i,o]of s.entries()){if(i==="x-goog-api-key")throw new y(`Cannot set reserved header name ${i}`);if(i==="x-goog-api-client")throw new y(`Header name ${i} can only be set using the apiClient field`);n.append(i,o)}}return n}async function ee(t,e,n,s,i,o){const a=new Qt(t,e,n,s,o);return{url:a.toString(),fetchOptions:Object.assign(Object.assign({},oe(o)),{method:"POST",headers:await te(a),body:i})}}async function R(t,e,n,s,i,o={},a=fetch){const{url:u,fetchOptions:c}=await ee(t,e,n,s,i,o);return ne(u,c,a)}async function ne(t,e,n=fetch){let s;try{s=await n(t,e)}catch(i){se(i,t)}return s.ok||await ie(s,t),s}function se(t,e){let n=t;throw n.name==="AbortError"?(n=new ft(`Request aborted when fetching ${e.toString()}: ${t.message}`),n.stack=t.stack):t instanceof dt||t instanceof y||(n=new m(`Error fetching from ${e.toString()}: ${t.message}`),n.stack=t.stack),n}async function ie(t,e){let n="",s;try{const i=await t.json();n=i.error.message,i.error.details&&(n+=` ${JSON.stringify(i.error.details)}`,s=i.error.details)}catch{}throw new dt(`Error fetching from ${e.toString()}: [${t.status} ${t.statusText}] ${n}`,t.status,t.statusText,s)}function oe(t){const e={};if(t?.signal!==void 0||t?.timeout>=0){const n=new AbortController;t?.timeout>=0&&setTimeout(()=>n.abort(),t.timeout),t?.signal&&t.signal.addEventListener("abort",()=>{n.abort()}),e.signal=n.signal}return e}function M(t){return t.text=()=>{if(t.candidates&&t.candidates.length>0){if(t.candidates.length>1&&console.warn(`This response had ${t.candidates.length} candidates. Returning text from the first candidate only. Access response.candidates directly to use the other candidates.`),A(t.candidates[0]))throw new _(`${O(t)}`,t);return ae(t)}else if(t.promptFeedback)throw new _(`Text not available. ${O(t)}`,t);return""},t.functionCall=()=>{if(t.candidates&&t.candidates.length>0){if(t.candidates.length>1&&console.warn(`This response had ${t.candidates.length} candidates. Returning function calls from the first candidate only. Access response.candidates directly to use the other candidates.`),A(t.candidates[0]))throw new _(`${O(t)}`,t);return console.warn("response.functionCall() is deprecated. Use response.functionCalls() instead."),Z(t)[0]}else if(t.promptFeedback)throw new _(`Function call not available. ${O(t)}`,t)},t.functionCalls=()=>{if(t.candidates&&t.candidates.length>0){if(t.candidates.length>1&&console.warn(`This response had ${t.candidates.length} candidates. Returning function calls from the first candidate only. Access response.candidates directly to use the other candidates.`),A(t.candidates[0]))throw new _(`${O(t)}`,t);return Z(t)}else if(t.promptFeedback)throw new _(`Function call not available. ${O(t)}`,t)},t}function ae(t){var e,n,s,i;const o=[];if(!((n=(e=t.candidates)===null||e===void 0?void 0:e[0].content)===null||n===void 0)&&n.parts)for(const a of(i=(s=t.candidates)===null||s===void 0?void 0:s[0].content)===null||i===void 0?void 0:i.parts)a.text&&o.push(a.text),a.executableCode&&o.push("\n```"+a.executableCode.language+`
2
- `+a.executableCode.code+"\n```\n"),a.codeExecutionResult&&o.push("\n```\n"+a.codeExecutionResult.output+"\n```\n");return o.length>0?o.join(""):""}function Z(t){var e,n,s,i;const o=[];if(!((n=(e=t.candidates)===null||e===void 0?void 0:e[0].content)===null||n===void 0)&&n.parts)for(const a of(i=(s=t.candidates)===null||s===void 0?void 0:s[0].content)===null||i===void 0?void 0:i.parts)a.functionCall&&o.push(a.functionCall);if(o.length>0)return o}const re=[T.RECITATION,T.SAFETY,T.LANGUAGE];function A(t){return!!t.finishReason&&re.includes(t.finishReason)}function O(t){var e,n,s;let i="";if((!t.candidates||t.candidates.length===0)&&t.promptFeedback)i+="Response was blocked",!((e=t.promptFeedback)===null||e===void 0)&&e.blockReason&&(i+=` due to ${t.promptFeedback.blockReason}`),!((n=t.promptFeedback)===null||n===void 0)&&n.blockReasonMessage&&(i+=`: ${t.promptFeedback.blockReasonMessage}`);else if(!((s=t.candidates)===null||s===void 0)&&s[0]){const o=t.candidates[0];A(o)&&(i+=`Candidate was blocked due to ${o.finishReason}`,o.finishMessage&&(i+=`: ${o.finishMessage}`))}return i}function w(t){return this instanceof w?(this.v=t,this):new w(t)}function ue(t,e,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var s=n.apply(t,e||[]),i,o=[];return i={},a("next"),a("throw"),a("return"),i[Symbol.asyncIterator]=function(){return this},i;function a(f){s[f]&&(i[f]=function(d){return new Promise(function(g,C){o.push([f,d,g,C])>1||u(f,d)})})}function u(f,d){try{c(s[f](d))}catch(g){l(o[0][3],g)}}function c(f){f.value instanceof w?Promise.resolve(f.value.v).then(p,r):l(o[0][2],f)}function p(f){u("next",f)}function r(f){u("throw",f)}function l(f,d){f(d),o.shift(),o.length&&u(o[0][0],o[0][1])}}const Q=/^data\: (.*)(?:\n\n|\r\r|\r\n\r\n)/;function le(t){const e=t.body.pipeThrough(new TextDecoderStream("utf8",{fatal:!0})),n=fe(e),[s,i]=n.tee();return{stream:de(s),response:ce(i)}}async function ce(t){const e=[],n=t.getReader();for(;;){const{done:s,value:i}=await n.read();if(s)return M(pe(e));e.push(i)}}function de(t){return ue(this,arguments,function*(){const n=t.getReader();for(;;){const{value:s,done:i}=yield w(n.read());if(i)break;yield yield w(M(s))}})}function fe(t){const e=t.getReader();return new ReadableStream({start(s){let i="";return o();function o(){return e.read().then(({value:a,done:u})=>{if(u){if(i.trim()){s.error(new m("Failed to parse stream"));return}s.close();return}i+=a;let c=i.match(Q),p;for(;c;){try{p=JSON.parse(c[1])}catch{s.error(new m(`Error parsing JSON response: "${c[1]}"`));return}s.enqueue(p),i=i.substring(c[0].length),c=i.match(Q)}return o()}).catch(a=>{let u=a;throw u.stack=a.stack,u.name==="AbortError"?u=new ft("Request aborted when reading from the stream"):u=new m("Error reading from the stream"),u})}}})}function pe(t){const e=t[t.length-1],n={promptFeedback:e?.promptFeedback};for(const s of t){if(s.candidates){let i=0;for(const o of s.candidates)if(n.candidates||(n.candidates=[]),n.candidates[i]||(n.candidates[i]={index:i}),n.candidates[i].citationMetadata=o.citationMetadata,n.candidates[i].groundingMetadata=o.groundingMetadata,n.candidates[i].finishReason=o.finishReason,n.candidates[i].finishMessage=o.finishMessage,n.candidates[i].safetyRatings=o.safetyRatings,o.content&&o.content.parts){n.candidates[i].content||(n.candidates[i].content={role:o.content.role||"user",parts:[]});const a={};for(const u of o.content.parts)u.text&&(a.text=u.text),u.functionCall&&(a.functionCall=u.functionCall),u.executableCode&&(a.executableCode=u.executableCode),u.codeExecutionResult&&(a.codeExecutionResult=u.codeExecutionResult),Object.keys(a).length===0&&(a.text=""),n.candidates[i].content.parts.push(a)}i++}s.usageMetadata&&(n.usageMetadata=s.usageMetadata)}return n}async function pt(t,e,n,s){const i=await R(e,v.STREAM_GENERATE_CONTENT,t,!0,JSON.stringify(n),s);return le(i)}async function gt(t,e,n,s){const o=await(await R(e,v.GENERATE_CONTENT,t,!1,JSON.stringify(n),s)).json();return{response:M(o)}}function ht(t){if(t!=null){if(typeof t=="string")return{role:"system",parts:[{text:t}]};if(t.text)return{role:"system",parts:[t]};if(t.parts)return t.role?t:{role:"system",parts:t.parts}}}function S(t){let e=[];if(typeof t=="string")e=[{text:t}];else for(const n of t)typeof n=="string"?e.push({text:n}):e.push(n);return ge(e)}function ge(t){const e={role:"user",parts:[]},n={role:"function",parts:[]};let s=!1,i=!1;for(const o of t)"functionResponse"in o?(n.parts.push(o),i=!0):(e.parts.push(o),s=!0);if(s&&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(!s&&!i)throw new m("No content is provided for sending chat message.");return s?e:n}function he(t,e){var n;let s={model:e?.model,generationConfig:e?.generationConfig,safetySettings:e?.safetySettings,tools:e?.tools,toolConfig:e?.toolConfig,systemInstruction:e?.systemInstruction,cachedContent:(n=e?.cachedContent)===null||n===void 0?void 0:n.name,contents:[]};const i=t.generateContentRequest!=null;if(t.contents){if(i)throw new y("CountTokensRequest must have one of contents or generateContentRequest, not both.");s.contents=t.contents}else if(i)s=Object.assign(Object.assign({},s),t.generateContentRequest);else{const o=S(t);s.contents=[o]}return{generateContentRequest:s}}function X(t){let e;return t.contents?e=t:e={contents:[S(t)]},t.systemInstruction&&(e.systemInstruction=ht(t.systemInstruction)),e}function me(t){return typeof t=="string"||Array.isArray(t)?{content:S(t)}:t}const tt=["text","inlineData","functionCall","functionResponse","executableCode","codeExecutionResult"],Ce={user:["text","inlineData"],function:["functionResponse"],model:["text","functionCall","executableCode","codeExecutionResult"],system:["text"]};function Oe(t){let e=!1;for(const n of t){const{role:s,parts:i}=n;if(!e&&s!=="user")throw new m(`First content should be with role 'user', got ${s}`);if(!Y.includes(s))throw new m(`Each item should include role field. Got ${s} but valid roles are: ${JSON.stringify(Y)}`);if(!Array.isArray(i))throw new m("Content should have 'parts' property with an array of Parts");if(i.length===0)throw new m("Each Content should have at least one part");const o={text:0,inlineData:0,functionCall:0,functionResponse:0,fileData:0,executableCode:0,codeExecutionResult:0};for(const u of i)for(const c of tt)c in u&&(o[c]+=1);const a=Ce[s];for(const u of tt)if(!a.includes(u)&&o[u]>0)throw new m(`Content with role '${s}' can't contain '${u}' part`);e=!0}}function et(t){var e;if(t.candidates===void 0||t.candidates.length===0)return!1;const n=(e=t.candidates[0])===null||e===void 0?void 0:e.content;if(n===void 0||n.parts===void 0||n.parts.length===0)return!1;for(const s of n.parts)if(s===void 0||Object.keys(s).length===0||s.text!==void 0&&s.text==="")return!1;return!0}const nt="SILENT_ERROR";class ye{constructor(e,n,s,i={}){this.model=n,this.params=s,this._requestOptions=i,this._history=[],this._sendPromise=Promise.resolve(),this._apiKey=e,s?.history&&(Oe(s.history),this._history=s.history)}async getHistory(){return await this._sendPromise,this._history}async sendMessage(e,n={}){var s,i,o,a,u,c;await this._sendPromise;const p=S(e),r={safetySettings:(s=this.params)===null||s===void 0?void 0:s.safetySettings,generationConfig:(i=this.params)===null||i===void 0?void 0:i.generationConfig,tools:(o=this.params)===null||o===void 0?void 0:o.tools,toolConfig:(a=this.params)===null||a===void 0?void 0:a.toolConfig,systemInstruction:(u=this.params)===null||u===void 0?void 0:u.systemInstruction,cachedContent:(c=this.params)===null||c===void 0?void 0:c.cachedContent,contents:[...this._history,p]},l=Object.assign(Object.assign({},this._requestOptions),n);let f;return this._sendPromise=this._sendPromise.then(()=>gt(this._apiKey,this.model,r,l)).then(d=>{var g;if(et(d.response)){this._history.push(p);const C=Object.assign({parts:[],role:"model"},(g=d.response.candidates)===null||g===void 0?void 0:g[0].content);this._history.push(C)}else{const C=O(d.response);C&&console.warn(`sendMessage() was unsuccessful. ${C}. Inspect response object for details.`)}f=d}).catch(d=>{throw this._sendPromise=Promise.resolve(),d}),await this._sendPromise,f}async sendMessageStream(e,n={}){var s,i,o,a,u,c;await this._sendPromise;const p=S(e),r={safetySettings:(s=this.params)===null||s===void 0?void 0:s.safetySettings,generationConfig:(i=this.params)===null||i===void 0?void 0:i.generationConfig,tools:(o=this.params)===null||o===void 0?void 0:o.tools,toolConfig:(a=this.params)===null||a===void 0?void 0:a.toolConfig,systemInstruction:(u=this.params)===null||u===void 0?void 0:u.systemInstruction,cachedContent:(c=this.params)===null||c===void 0?void 0:c.cachedContent,contents:[...this._history,p]},l=Object.assign(Object.assign({},this._requestOptions),n),f=pt(this._apiKey,this.model,r,l);return this._sendPromise=this._sendPromise.then(()=>f).catch(d=>{throw new Error(nt)}).then(d=>d.response).then(d=>{if(et(d)){this._history.push(p);const g=Object.assign({},d.candidates[0].content);g.role||(g.role="model"),this._history.push(g)}else{const g=O(d);g&&console.warn(`sendMessageStream() was unsuccessful. ${g}. Inspect response object for details.`)}}).catch(d=>{d.message!==nt&&console.error(d)}),f}}async function Ie(t,e,n,s){return(await R(e,v.COUNT_TOKENS,t,!1,JSON.stringify(n),s)).json()}async function ve(t,e,n,s){return(await R(e,v.EMBED_CONTENT,t,!1,JSON.stringify(n),s)).json()}async function _e(t,e,n,s){const i=n.requests.map(a=>Object.assign(Object.assign({},a),{model:e}));return(await R(e,v.BATCH_EMBED_CONTENTS,t,!1,JSON.stringify({requests:i}),s)).json()}class st{constructor(e,n,s={}){this.apiKey=e,this._requestOptions=s,n.model.includes("/")?this.model=n.model:this.model=`models/${n.model}`,this.generationConfig=n.generationConfig||{},this.safetySettings=n.safetySettings||[],this.tools=n.tools,this.toolConfig=n.toolConfig,this.systemInstruction=ht(n.systemInstruction),this.cachedContent=n.cachedContent}async generateContent(e,n={}){var s;const i=X(e),o=Object.assign(Object.assign({},this._requestOptions),n);return gt(this.apiKey,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:(s=this.cachedContent)===null||s===void 0?void 0:s.name},i),o)}async generateContentStream(e,n={}){var s;const i=X(e),o=Object.assign(Object.assign({},this._requestOptions),n);return pt(this.apiKey,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:(s=this.cachedContent)===null||s===void 0?void 0:s.name},i),o)}startChat(e){var n;return new ye(this.apiKey,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:(n=this.cachedContent)===null||n===void 0?void 0:n.name},e),this._requestOptions)}async countTokens(e,n={}){const s=he(e,{model:this.model,generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:this.cachedContent}),i=Object.assign(Object.assign({},this._requestOptions),n);return Ie(this.apiKey,this.model,s,i)}async embedContent(e,n={}){const s=me(e),i=Object.assign(Object.assign({},this._requestOptions),n);return ve(this.apiKey,this.model,s,i)}async batchEmbedContents(e,n={}){const s=Object.assign(Object.assign({},this._requestOptions),n);return _e(this.apiKey,this.model,e,s)}}class it{constructor(e){this.apiKey=e}getGenerativeModel(e,n){if(!e.model)throw new m("Must provide a model name. Example: genai.getGenerativeModel({ model: 'my-model-name' })");return new st(this.apiKey,e,n)}getGenerativeModelFromCachedContent(e,n,s){if(!e.name)throw new y("Cached content must contain a `name` field.");if(!e.model)throw new y("Cached content must contain a `model` field.");const i=["model","systemInstruction"];for(const a of i)if(n?.[a]&&e[a]&&n?.[a]!==e[a]){if(a==="model"){const u=n.model.startsWith("models/")?n.model.replace("models/",""):n.model,c=e.model.startsWith("models/")?e.model.replace("models/",""):e.model;if(u===c)continue}throw new y(`Different value for "${a}" specified in modelParams (${n[a]}) and cachedContent (${e[a]})`)}const o=Object.assign(Object.assign({},n),{model:e.model,tools:e.tools,toolConfig:e.toolConfig,systemInstruction:e.systemInstruction,cachedContent:e});return new st(this.apiKey,o,s)}}function ot(t,e){const n=Ee(t),s=we(n,e);return{tools:n,toolConfig:s}}function Ee(t){let e=[];const n=[];return t.forEach(i=>{if(at(i)){const[o]=Wt([i]);o.functionDeclarations&&e.push(...o.functionDeclarations)}else if(rt(i)){const{functionDeclarations:o}=Te(i);if(o)e.push(...o);else throw new Error("Failed to convert OpenAI structured tool to GenerativeAI tool")}else n.push(i)}),n.find(i=>"functionDeclarations"in i)?n.map(i=>{if(e?.length>0&&"functionDeclarations"in i){const o={functionDeclarations:[...i.functionDeclarations||[],...e]};return e=[],o}return i}):[...n,...e.length>0?[{functionDeclarations:e}]:[]]}function Te(t){return{functionDeclarations:[{name:t.function.name,description:t.function.description,parameters:I(t.function.parameters)}]}}function we(t,e){if(!t.length||!e)return;const{toolChoice:n,allowedFunctionNames:s}=e,i={any:E.ANY,auto:E.AUTO,none:E.NONE};if(n&&["any","auto","none"].includes(n))return{functionCallingConfig:{mode:i[n]??"MODE_UNSPECIFIED",allowedFunctionNames:s}};if(typeof n=="string"||s)return{functionCallingConfig:{mode:E.ANY,allowedFunctionNames:[...s??[],...n&&typeof n=="string"?[n]:[]]}}}const Se={"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-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-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-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-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-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-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-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.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-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.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-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-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-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-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-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-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-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-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-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-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-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-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-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}};var Re=Se,Me=class extends Ot{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(t){if(super(t),this.model=t.model.replace(/^models\//,""),this.maxOutputTokens=t.maxOutputTokens??this.maxOutputTokens,this.maxOutputTokens&&this.maxOutputTokens<0)throw new Error("`maxOutputTokens` must be a positive integer");if(this.temperature=t.temperature??this.temperature,this.temperature&&(this.temperature<0||this.temperature>2))throw new Error("`temperature` must be in the range of [0.0,2.0]");if(this.topP=t.topP??this.topP,this.topP&&this.topP<0)throw new Error("`topP` must be a positive integer");if(this.topP&&this.topP>1)throw new Error("`topP` must be below 1.");if(this.topK=t.topK??this.topK,this.topK&&this.topK<0)throw new Error("`topK` must be a positive integer");if(this.stopSequences=t.stopSequences??this.stopSequences,this.apiKey=t.apiKey??kt("GOOGLE_API_KEY"),!this.apiKey)throw new Error("Please set an API key for Google GenerativeAI in the environment variable GOOGLE_API_KEY or in the `apiKey` field of the ChatGoogleGenerativeAI constructor");if(this.safetySettings=t.safetySettings??this.safetySettings,this.safetySettings&&this.safetySettings.length>0&&new Set(this.safetySettings.map(n=>n.category)).size!==this.safetySettings.length)throw new Error("The categories in `safetySettings` array must be unique");this.streaming=t.streaming??this.streaming,this.json=t.json,this.thinkingConfig=t.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:t.apiVersion,baseUrl:t.baseUrl,customHeaders:t.customHeaders}),this.streamUsage=t.streamUsage??this.streamUsage}useCachedContent(t,e,n){this.apiKey&&(this.client=new it(this.apiKey).getGenerativeModelFromCachedContent(t,e,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(t){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:t.stop}}_combineLLMOutput(){return[]}_llmType(){return"googlegenerativeai"}bindTools(t,e){return this.withConfig({tools:ot(t)?.tools,...e})}invocationParams(t){const e=t?.tools?.length?ot(t.tools,{toolChoice:t.tool_choice,allowedFunctionNames:t.allowedFunctionNames}):void 0;return t?.responseSchema?(this.client.generationConfig.responseSchema=t.responseSchema,this.client.generationConfig.responseMimeType="application/json"):(this.client.generationConfig.responseSchema=void 0,this.client.generationConfig.responseMimeType=this.json?"application/json":void 0),{...e?.tools?{tools:e.tools}:{},...e?.toolConfig?{toolConfig:e.toolConfig}:{}}}async _generate(t,e,n){const s=P(t,this._isMultimodalModel,this.useSystemInstruction,this.model);let i=s;if(s[0].role==="system"){const[p]=s;this.client.systemInstruction=p,i=s.slice(1)}const o=this.invocationParams(e);if(this.streaming){const p={},r=this._streamResponseChunks(t,e,n),l={};for await(const d of r){const g=d.generationInfo?.completion??0;l[g]===void 0?l[g]=d:l[g]=l[g].concat(d)}return{generations:Object.entries(l).sort(([d],[g])=>parseInt(d,10)-parseInt(g,10)).map(([d,g])=>g),llmOutput:{estimatedTokenUsage:p}}}const a=await this.completionWithRetry({...o,contents:i});let u;"usageMetadata"in a.response&&(u=j(a.response.usageMetadata,this.model));const c=Bt(a.response,{usageMetadata:u});return c.generations?.length>0&&await n?.handleLLMNewToken(c.generations[0]?.text??""),c}async*_streamResponseChunks(t,e,n){const s=P(t,this._isMultimodalModel,this.useSystemInstruction,this.model);let i=s;if(s[0].role==="system"){const[f]=s;this.client.systemInstruction=f,i=s.slice(1)}const a={...this.invocationParams(e),contents:i},u=await this.caller.callWithOptions({signal:e?.signal},async()=>{const{stream:f}=await this.client.generateContentStream(a);return f});let c,p=0,r=0,l=0;for await(const f of u){if("usageMetadata"in f&&f.usageMetadata!==void 0&&this.streamUsage!==!1&&e.streamUsage!==!1){c=j(f.usageMetadata,this.model);const g=f.usageMetadata.promptTokenCount??0;c.input_tokens=Math.max(0,g-p),p=g;const C=f.usageMetadata.candidatesTokenCount??0;c.output_tokens=Math.max(0,C-r),r=C;const D=f.usageMetadata.totalTokenCount??0;c.total_tokens=Math.max(0,D-l),l=D}const d=qt(f,{usageMetadata:c});d&&(yield d,await n?.handleLLMNewToken(d.text??""))}}async completionWithRetry(t,e){return this.caller.callWithOptions({signal:e?.signal},async()=>{try{return await this.client.generateContent(t)}catch(n){throw n.message?.includes("400 Bad Request")&&(n.status=400),n}})}get profile(){return Re[this.model]??{}}withStructuredOutput(t,e){const n=t,s=e?.name,i=e?.method,o=e?.includeRaw;if(i==="jsonMode")throw new Error('ChatGoogleGenerativeAI only supports "jsonSchema" or "functionCalling" as a method.');let a,u;if(i==="functionCalling"){let l=s??"extract",f;if(ut(n)){const d=N(n);f=[{functionDeclarations:[{name:l,description:d.description??"A function available to call.",parameters:d}]}],u=new F({returnSingle:!0,keyName:l,zodSchema:n})}else{let d;typeof n.name=="string"&&typeof n.parameters=="object"&&n.parameters!=null?(d=n,d.parameters=I(n.parameters),l=n.name):d={name:l,description:n.description??"",parameters:I(n)},f=[{functionDeclarations:[d]}],u=new F({returnSingle:!0,keyName:l})}a=this.bindTools(f).withConfig({allowedFunctionNames:[l]})}else{const l=N(n);a=this.withConfig({responseSchema:l}),u=new yt}if(!o)return a.pipe(u).withConfig({runName:"ChatGoogleGenerativeAIStructuredOutput"});const c=G.assign({parsed:(l,f)=>u.invoke(l.raw,f)}),p=G.assign({parsed:()=>null}),r=c.withFallbacks({fallbacks:[p]});return Nt.from([{raw:a},r]).withConfig({runName:"StructuredOutputRunnable"})}};export{Me as ChatGoogleGenerativeAI};
1
+ import{B as mt,O as Ct,a as Ot,J as yt,R as G}from"./index-DIlJ2WcE.js";import{i as at,aq as It,a8 as vt,E as _t,ar as Et,D as Tt,x as wt,V as St,ab as rt,a5 as Rt,af as At,J as x,as as xt,at as kt,au as Nt}from"./base-ZEkF4ver.js";import"./index-Bfe1ynAS.js";import{c as ut,d as lt}from"./base-Aouj1Yhj.js";import"./embeddings-BTUgP3x_.js";import"./index-CNfmoBX-.js";function I(t){if(typeof t=="object"&&t!==null){const e={...t};"additionalProperties"in e&&delete e.additionalProperties,"$schema"in e&&delete e.$schema,"strict"in e&&delete e.strict;for(const n in e)n in e&&(Array.isArray(e[n])?e[n]=e[n].map(I):typeof e[n]=="object"&&e[n]!==null&&(e[n]=I(e[n])));return e}return t}function N(t){const e=I(at(t)?It(t):t),{$schema:n,...s}=e;return s}function bt(t){const e=I(t),{$schema:n,...s}=e;return s}const h=[];for(let t=0;t<256;++t)h.push((t+256).toString(16).slice(1));function Mt(t,e=0){return(h[t[e+0]]+h[t[e+1]]+h[t[e+2]]+h[t[e+3]]+"-"+h[t[e+4]]+h[t[e+5]]+"-"+h[t[e+6]]+h[t[e+7]]+"-"+h[t[e+8]]+h[t[e+9]]+"-"+h[t[e+10]]+h[t[e+11]]+h[t[e+12]]+h[t[e+13]]+h[t[e+14]]+h[t[e+15]]).toLowerCase()}let k;const Dt=new Uint8Array(16);function Gt(){if(!k){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");k=crypto.getRandomValues.bind(crypto)}return k(Dt)}const Ut=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),U={randomUUID:Ut};function ct(t,e,n){if(U.randomUUID&&!t)return U.randomUUID();t=t||{};const s=t.random??t.rng?.()??Gt();if(s.length<16)throw new Error("Random bytes length must be >= 16");return s[6]=s[6]&15|64,s[8]=s[8]&63|128,Mt(s)}const b="__gemini_function_call_thought_signatures__",Lt="ErYCCrMCAdHtim9kOoOkrPiCNVsmlpMIKd7ZMxgiFbVQOkgp7nlLcDMzVsZwIzvuT7nQROivoXA72ccC2lSDvR0Gh7dkWaGuj7ctv6t7ZceHnecx0QYa+ix8tYpRfjhyWozQ49lWiws6+YGjCt10KRTyWsZ2h6O7iHTYJwKIRwGUHRKy/qK/6kFxJm5ML00gLq4D8s5Z6DBpp2ZlR+uF4G8jJgeWQgyHWVdx2wGYElaceVAc66tZdPQRdOHpWtgYSI1YdaXgVI8KHY3/EfNc2YqqMIulvkDBAnuMhkAjV9xmBa54Tq+ih3Im4+r3DzqhGqYdsSkhS0kZMwte4Hjs65dZzCw9lANxIqYi1DJ639WNPYihp/DCJCos7o+/EeSPJaio5sgWDyUnMGkY1atsJZ+m7pj7DD5tvQ==",Pt=t=>t();function jt(t){return wt.isInstance(t)?t.role:t.type}function Ft(t){switch(t){case"supervisor":case"ai":case"model":return"model";case"system":return"system";case"human":return"user";case"tool":case"function":return"function";default:throw new Error(`Unknown / unsupported author: ${t}`)}}function Kt(t){if("mimeType"in t&&"data"in t)return{inlineData:{mimeType:t.mimeType,data:t.data}};if("mimeType"in t&&"fileUri"in t)return{fileData:{mimeType:t.mimeType,fileUri:t.fileUri}};throw new Error("Invalid media content")}function Ht(t,e){return e.map(n=>rt(n)?n.tool_calls??[]:[]).flat().find(n=>n.id===t.tool_call_id)?.name}function $t(t){return{providerName:"Google Gemini",fromStandardTextBlock(n){return{text:n.text}},fromStandardImageBlock(n){if(!t)throw new Error("This model does not support images");if(n.source_type==="url"){const s=x({dataUrl:n.url});return s?{inlineData:{mimeType:s.mime_type,data:s.data}}:{fileData:{mimeType:n.mime_type??"",fileUri:n.url}}}if(n.source_type==="base64")return{inlineData:{mimeType:n.mime_type??"",data:n.data}};throw new Error(`Unsupported source type: ${n.source_type}`)},fromStandardAudioBlock(n){if(!t)throw new Error("This model does not support audio");if(n.source_type==="url"){const s=x({dataUrl:n.url});return s?{inlineData:{mimeType:s.mime_type,data:s.data}}:{fileData:{mimeType:n.mime_type??"",fileUri:n.url}}}if(n.source_type==="base64")return{inlineData:{mimeType:n.mime_type??"",data:n.data}};throw new Error(`Unsupported source type: ${n.source_type}`)},fromStandardFileBlock(n){if(!t)throw new Error("This model does not support files");if(n.source_type==="text")return{text:n.text};if(n.source_type==="url"){const s=x({dataUrl:n.url});return s?{inlineData:{mimeType:s.mime_type,data:s.data}}:{fileData:{mimeType:n.mime_type??"",fileUri:n.url}}}if(n.source_type==="base64")return{inlineData:{mimeType:n.mime_type??"",data:n.data}};throw new Error(`Unsupported source type: ${n.source_type}`)}}}function L(t,e){if(Rt(t))return At(t,$t(e));if(t.type==="text")return{text:t.text};if(t.type==="executableCode")return{executableCode:t.executableCode};if(t.type==="codeExecutionResult")return{codeExecutionResult:t.codeExecutionResult};if(t.type==="image_url"){if(!e)throw new Error("This model does not support images");let n;if(typeof t.image_url=="string")n=t.image_url;else if(typeof t.image_url=="object"&&"url"in t.image_url)n=t.image_url.url;else throw new Error("Please provide image as base64 encoded data URL");const[s,i]=n.split(",");if(!s.startsWith("data:"))throw new Error("Please provide image as base64 encoded data URL");const[o,a]=s.replace(/^data:/,"").split(";");if(a!=="base64")throw new Error("Please provide image as base64 encoded data URL");return{inlineData:{data:i,mimeType:o}}}else{if(t.type==="media")return Kt(t);if(t.type==="tool_use")return{functionCall:{name:t.name,args:t.input}};if(t.type?.includes("/")&&t.type.split("/").length===2&&"data"in t&&typeof t.data=="string")return{inlineData:{mimeType:t.type,data:t.data}};if("functionCall"in t)return;throw"type"in t?new Error(`Unknown content type ${t.type}`):new Error(`Unknown content ${JSON.stringify(t)}`)}}function Yt(t,e,n,s){if(St(t)){const u=t.name??Ht(t,n);if(u===void 0)throw new Error(`Google requires a tool name for each tool call response, and we could not infer a called tool name for ToolMessage "${t.id}" from your passed messages. Please populate a "name" field on that ToolMessage explicitly.`);const c=Array.isArray(t.content)?t.content.map(p=>L(p,e)).filter(p=>p!==void 0):t.content;return t.status==="error"?[{functionResponse:{name:u,response:{error:{details:c}}}}]:[{functionResponse:{name:u,response:{result:c}}}]}let i=[];const o=[];typeof t.content=="string"&&t.content&&o.push({text:t.content}),Array.isArray(t.content)&&o.push(...t.content.map(u=>L(u,e)).filter(u=>u!==void 0));const a=t.additional_kwargs?.[b];return rt(t)&&t.tool_calls?.length&&(i=t.tool_calls.map(u=>{const c=Pt(()=>{if(u.id){const p=a?.[u.id];if(p)return p}return s?.includes("gemini-3")?Lt:""});return{functionCall:{name:u.name,args:u.args},...c?{thoughtSignature:c}:{}}})),[...o,...i]}function P(t,e,n=!1,s){return t.reduce((i,o,a)=>{if(!vt(o))throw new Error("Unsupported message input");const u=jt(o);if(u==="system"&&a!==0)throw new Error("System message should be the first one");const c=Ft(u),p=i.content[i.content.length];if(!i.mergeWithPreviousContent&&p&&p.role===c)throw new Error("Google Generative AI requires alternate messages between authors");const r=Yt(o,e,t.slice(0,a),s);if(i.mergeWithPreviousContent){const d=i.content[i.content.length-1];if(!d)throw new Error("There was a problem parsing your system message. Please try a prompt without one.");return d.parts.push(...r),{mergeWithPreviousContent:!1,content:i.content}}let l=c;(l==="function"||l==="system"&&!n)&&(l="user");const f={role:l,parts:r};return{mergeWithPreviousContent:u==="system"&&!n,content:[...i.content,f]}},{content:[],mergeWithPreviousContent:!1}).content}function Bt(t,e){if(!t.candidates||t.candidates.length===0||!t.candidates[0])return{generations:[],llmOutput:{filters:t.promptFeedback}};const[n]=t.candidates,{content:s,...i}=n,o=s.parts?.reduce((r,l)=>("functionCall"in l&&l.functionCall&&r.push({...l,id:"id"in l.functionCall&&typeof l.functionCall.id=="string"?l.functionCall.id:ct()}),r),[]);let a;Array.isArray(s?.parts)&&s.parts.length===1&&s.parts[0].text?a=s.parts[0].text:Array.isArray(s?.parts)&&s.parts.length>0?a=s.parts.map(r=>"text"in r?{type:"text",text:r.text}:"inlineData"in r?{type:"inlineData",inlineData:r.inlineData}:"functionCall"in r?{type:"functionCall",functionCall:r.functionCall}:"functionResponse"in r?{type:"functionResponse",functionResponse:r.functionResponse}:"fileData"in r?{type:"fileData",fileData:r.fileData}:"executableCode"in r?{type:"executableCode",executableCode:r.executableCode}:"codeExecutionResult"in r?{type:"codeExecutionResult",codeExecutionResult:r.codeExecutionResult}:r):a=[];const u=o?.reduce((r,l)=>("thoughtSignature"in l&&typeof l.thoughtSignature=="string"&&(r[l.id]=l.thoughtSignature),r),{});let c="";return typeof a=="string"?c=a:Array.isArray(a)&&a.length>0&&(c=a.find(l=>"text"in l)?.text??c),{generations:[{text:c,message:new _t({content:a??"",tool_calls:o?.map(r=>({type:"tool_call",id:r.id,name:r.functionCall.name,args:r.functionCall.args})),additional_kwargs:{...i,[b]:u},usage_metadata:e?.usageMetadata}),generationInfo:i}],llmOutput:{tokenUsage:{promptTokens:e?.usageMetadata?.input_tokens,completionTokens:e?.usageMetadata?.output_tokens,totalTokens:e?.usageMetadata?.total_tokens}}}}function qt(t,e){if(!t.candidates||t.candidates.length===0)return null;const[n]=t.candidates,{content:s,...i}=n,o=s.parts?.reduce((r,l)=>("functionCall"in l&&l.functionCall&&r.push({...l,id:"id"in l.functionCall&&typeof l.functionCall.id=="string"?l.functionCall.id:ct()}),r),[]);let a;Array.isArray(s?.parts)&&s.parts.every(r=>"text"in r)?a=s.parts.map(r=>r.text).join(""):Array.isArray(s?.parts)?a=s.parts.map(r=>"text"in r?{type:"text",text:r.text}:"inlineData"in r?{type:"inlineData",inlineData:r.inlineData}:"functionCall"in r?{type:"functionCall",functionCall:r.functionCall}:"functionResponse"in r?{type:"functionResponse",functionResponse:r.functionResponse}:"fileData"in r?{type:"fileData",fileData:r.fileData}:"executableCode"in r?{type:"executableCode",executableCode:r.executableCode}:"codeExecutionResult"in r?{type:"codeExecutionResult",codeExecutionResult:r.codeExecutionResult}:r):a=[];let u="";a&&typeof a=="string"?u=a:Array.isArray(a)&&(u=a.find(l=>"text"in l)?.text??"");const c=[];o&&c.push(...o.map(r=>({type:"tool_call_chunk",id:r.id,name:r.functionCall.name,args:JSON.stringify(r.functionCall.args)})));const p=o?.reduce((r,l)=>("thoughtSignature"in l&&typeof l.thoughtSignature=="string"&&(r[l.id]=l.thoughtSignature),r),{});return new Et({text:u,message:new Tt({content:a||"",name:s?s.role:void 0,tool_call_chunks:c,additional_kwargs:{[b]:p},response_metadata:{model_provider:"google-genai"},usage_metadata:e.usageMetadata}),generationInfo:i})}function Wt(t){return t.every(e=>"functionDeclarations"in e&&Array.isArray(e.functionDeclarations))?t:[{functionDeclarations:t.map(e=>{if(ut(e)){const n=N(e.schema);return n.type==="object"&&"properties"in n&&Object.keys(n.properties).length===0?{name:e.name,description:e.description}:{name:e.name,description:e.description,parameters:n}}return lt(e)?{name:e.function.name,description:e.function.description??"A function available to call.",parameters:bt(e.function.parameters)}:e})}]}function j(t,e){const n={input_tokens:t?.promptTokenCount??0,output_tokens:t?.candidatesTokenCount??0,total_tokens:t?.totalTokenCount??0};if(t?.cachedContentTokenCount&&(n.input_token_details??={},n.input_token_details.cache_read=t.cachedContentTokenCount),e==="gemini-3-pro-preview"){const s=Math.max(0,t?.promptTokenCount??-2e5),i=Math.max(0,t?.cachedContentTokenCount??-2e5);s&&(n.input_token_details={...n.input_token_details,over_200k:s}),i&&(n.input_token_details={...n.input_token_details,cache_read_over_200k:i})}return n}var F=class extends mt{static lc_name(){return"GoogleGenerativeAIToolsOutputParser"}lc_namespace=["langchain","google_genai","output_parsers"];returnId=!1;keyName;returnSingle=!1;zodSchema;constructor(t){super(t),this.keyName=t.keyName,this.returnSingle=t.returnSingle??this.returnSingle,this.zodSchema=t.zodSchema}async _validateResult(t){if(this.zodSchema===void 0)return t;const e=await xt(this.zodSchema,t);if(e.success)return e.data;throw new Ct(`Failed to parse. Text: "${JSON.stringify(t,null,2)}". Error: ${JSON.stringify(e.error.issues)}`,JSON.stringify(t,null,2))}async parseResult(t){const e=t.flatMap(i=>{const{message:o}=i;return!("tool_calls"in o)||!Array.isArray(o.tool_calls)?[]:o.tool_calls});if(e[0]===void 0)throw new Error("No parseable tool calls provided to GoogleGenerativeAIToolsOutputParser.");const[n]=e;return await this._validateResult(n.args)}},K;(function(t){t.STRING="string",t.NUMBER="number",t.INTEGER="integer",t.BOOLEAN="boolean",t.ARRAY="array",t.OBJECT="object"})(K||(K={}));var H;(function(t){t.LANGUAGE_UNSPECIFIED="language_unspecified",t.PYTHON="python"})(H||(H={}));var $;(function(t){t.OUTCOME_UNSPECIFIED="outcome_unspecified",t.OUTCOME_OK="outcome_ok",t.OUTCOME_FAILED="outcome_failed",t.OUTCOME_DEADLINE_EXCEEDED="outcome_deadline_exceeded"})($||($={}));const Y=["user","model","function","system"];var B;(function(t){t.HARM_CATEGORY_UNSPECIFIED="HARM_CATEGORY_UNSPECIFIED",t.HARM_CATEGORY_HATE_SPEECH="HARM_CATEGORY_HATE_SPEECH",t.HARM_CATEGORY_SEXUALLY_EXPLICIT="HARM_CATEGORY_SEXUALLY_EXPLICIT",t.HARM_CATEGORY_HARASSMENT="HARM_CATEGORY_HARASSMENT",t.HARM_CATEGORY_DANGEROUS_CONTENT="HARM_CATEGORY_DANGEROUS_CONTENT",t.HARM_CATEGORY_CIVIC_INTEGRITY="HARM_CATEGORY_CIVIC_INTEGRITY"})(B||(B={}));var q;(function(t){t.HARM_BLOCK_THRESHOLD_UNSPECIFIED="HARM_BLOCK_THRESHOLD_UNSPECIFIED",t.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",t.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",t.BLOCK_ONLY_HIGH="BLOCK_ONLY_HIGH",t.BLOCK_NONE="BLOCK_NONE"})(q||(q={}));var W;(function(t){t.HARM_PROBABILITY_UNSPECIFIED="HARM_PROBABILITY_UNSPECIFIED",t.NEGLIGIBLE="NEGLIGIBLE",t.LOW="LOW",t.MEDIUM="MEDIUM",t.HIGH="HIGH"})(W||(W={}));var V;(function(t){t.BLOCKED_REASON_UNSPECIFIED="BLOCKED_REASON_UNSPECIFIED",t.SAFETY="SAFETY",t.OTHER="OTHER"})(V||(V={}));var T;(function(t){t.FINISH_REASON_UNSPECIFIED="FINISH_REASON_UNSPECIFIED",t.STOP="STOP",t.MAX_TOKENS="MAX_TOKENS",t.SAFETY="SAFETY",t.RECITATION="RECITATION",t.LANGUAGE="LANGUAGE",t.BLOCKLIST="BLOCKLIST",t.PROHIBITED_CONTENT="PROHIBITED_CONTENT",t.SPII="SPII",t.MALFORMED_FUNCTION_CALL="MALFORMED_FUNCTION_CALL",t.OTHER="OTHER"})(T||(T={}));var J;(function(t){t.TASK_TYPE_UNSPECIFIED="TASK_TYPE_UNSPECIFIED",t.RETRIEVAL_QUERY="RETRIEVAL_QUERY",t.RETRIEVAL_DOCUMENT="RETRIEVAL_DOCUMENT",t.SEMANTIC_SIMILARITY="SEMANTIC_SIMILARITY",t.CLASSIFICATION="CLASSIFICATION",t.CLUSTERING="CLUSTERING"})(J||(J={}));var E;(function(t){t.MODE_UNSPECIFIED="MODE_UNSPECIFIED",t.AUTO="AUTO",t.ANY="ANY",t.NONE="NONE"})(E||(E={}));var z;(function(t){t.MODE_UNSPECIFIED="MODE_UNSPECIFIED",t.MODE_DYNAMIC="MODE_DYNAMIC"})(z||(z={}));class m extends Error{constructor(e){super(`[GoogleGenerativeAI Error]: ${e}`)}}class _ extends m{constructor(e,n){super(e),this.response=n}}class dt extends m{constructor(e,n,s,i){super(e),this.status=n,this.statusText=s,this.errorDetails=i}}class y extends m{}class ft extends m{}const Vt="https://generativelanguage.googleapis.com",Jt="v1beta",zt="0.24.1",Zt="genai-js";var v;(function(t){t.GENERATE_CONTENT="generateContent",t.STREAM_GENERATE_CONTENT="streamGenerateContent",t.COUNT_TOKENS="countTokens",t.EMBED_CONTENT="embedContent",t.BATCH_EMBED_CONTENTS="batchEmbedContents"})(v||(v={}));class Qt{constructor(e,n,s,i,o){this.model=e,this.task=n,this.apiKey=s,this.stream=i,this.requestOptions=o}toString(){var e,n;const s=((e=this.requestOptions)===null||e===void 0?void 0:e.apiVersion)||Jt;let o=`${((n=this.requestOptions)===null||n===void 0?void 0:n.baseUrl)||Vt}/${s}/${this.model}:${this.task}`;return this.stream&&(o+="?alt=sse"),o}}function Xt(t){const e=[];return t?.apiClient&&e.push(t.apiClient),e.push(`${Zt}/${zt}`),e.join(" ")}async function te(t){var e;const n=new Headers;n.append("Content-Type","application/json"),n.append("x-goog-api-client",Xt(t.requestOptions)),n.append("x-goog-api-key",t.apiKey);let s=(e=t.requestOptions)===null||e===void 0?void 0:e.customHeaders;if(s){if(!(s instanceof Headers))try{s=new Headers(s)}catch(i){throw new y(`unable to convert customHeaders value ${JSON.stringify(s)} to Headers: ${i.message}`)}for(const[i,o]of s.entries()){if(i==="x-goog-api-key")throw new y(`Cannot set reserved header name ${i}`);if(i==="x-goog-api-client")throw new y(`Header name ${i} can only be set using the apiClient field`);n.append(i,o)}}return n}async function ee(t,e,n,s,i,o){const a=new Qt(t,e,n,s,o);return{url:a.toString(),fetchOptions:Object.assign(Object.assign({},oe(o)),{method:"POST",headers:await te(a),body:i})}}async function R(t,e,n,s,i,o={},a=fetch){const{url:u,fetchOptions:c}=await ee(t,e,n,s,i,o);return ne(u,c,a)}async function ne(t,e,n=fetch){let s;try{s=await n(t,e)}catch(i){se(i,t)}return s.ok||await ie(s,t),s}function se(t,e){let n=t;throw n.name==="AbortError"?(n=new ft(`Request aborted when fetching ${e.toString()}: ${t.message}`),n.stack=t.stack):t instanceof dt||t instanceof y||(n=new m(`Error fetching from ${e.toString()}: ${t.message}`),n.stack=t.stack),n}async function ie(t,e){let n="",s;try{const i=await t.json();n=i.error.message,i.error.details&&(n+=` ${JSON.stringify(i.error.details)}`,s=i.error.details)}catch{}throw new dt(`Error fetching from ${e.toString()}: [${t.status} ${t.statusText}] ${n}`,t.status,t.statusText,s)}function oe(t){const e={};if(t?.signal!==void 0||t?.timeout>=0){const n=new AbortController;t?.timeout>=0&&setTimeout(()=>n.abort(),t.timeout),t?.signal&&t.signal.addEventListener("abort",()=>{n.abort()}),e.signal=n.signal}return e}function M(t){return t.text=()=>{if(t.candidates&&t.candidates.length>0){if(t.candidates.length>1&&console.warn(`This response had ${t.candidates.length} candidates. Returning text from the first candidate only. Access response.candidates directly to use the other candidates.`),A(t.candidates[0]))throw new _(`${O(t)}`,t);return ae(t)}else if(t.promptFeedback)throw new _(`Text not available. ${O(t)}`,t);return""},t.functionCall=()=>{if(t.candidates&&t.candidates.length>0){if(t.candidates.length>1&&console.warn(`This response had ${t.candidates.length} candidates. Returning function calls from the first candidate only. Access response.candidates directly to use the other candidates.`),A(t.candidates[0]))throw new _(`${O(t)}`,t);return console.warn("response.functionCall() is deprecated. Use response.functionCalls() instead."),Z(t)[0]}else if(t.promptFeedback)throw new _(`Function call not available. ${O(t)}`,t)},t.functionCalls=()=>{if(t.candidates&&t.candidates.length>0){if(t.candidates.length>1&&console.warn(`This response had ${t.candidates.length} candidates. Returning function calls from the first candidate only. Access response.candidates directly to use the other candidates.`),A(t.candidates[0]))throw new _(`${O(t)}`,t);return Z(t)}else if(t.promptFeedback)throw new _(`Function call not available. ${O(t)}`,t)},t}function ae(t){var e,n,s,i;const o=[];if(!((n=(e=t.candidates)===null||e===void 0?void 0:e[0].content)===null||n===void 0)&&n.parts)for(const a of(i=(s=t.candidates)===null||s===void 0?void 0:s[0].content)===null||i===void 0?void 0:i.parts)a.text&&o.push(a.text),a.executableCode&&o.push("\n```"+a.executableCode.language+`
2
+ `+a.executableCode.code+"\n```\n"),a.codeExecutionResult&&o.push("\n```\n"+a.codeExecutionResult.output+"\n```\n");return o.length>0?o.join(""):""}function Z(t){var e,n,s,i;const o=[];if(!((n=(e=t.candidates)===null||e===void 0?void 0:e[0].content)===null||n===void 0)&&n.parts)for(const a of(i=(s=t.candidates)===null||s===void 0?void 0:s[0].content)===null||i===void 0?void 0:i.parts)a.functionCall&&o.push(a.functionCall);if(o.length>0)return o}const re=[T.RECITATION,T.SAFETY,T.LANGUAGE];function A(t){return!!t.finishReason&&re.includes(t.finishReason)}function O(t){var e,n,s;let i="";if((!t.candidates||t.candidates.length===0)&&t.promptFeedback)i+="Response was blocked",!((e=t.promptFeedback)===null||e===void 0)&&e.blockReason&&(i+=` due to ${t.promptFeedback.blockReason}`),!((n=t.promptFeedback)===null||n===void 0)&&n.blockReasonMessage&&(i+=`: ${t.promptFeedback.blockReasonMessage}`);else if(!((s=t.candidates)===null||s===void 0)&&s[0]){const o=t.candidates[0];A(o)&&(i+=`Candidate was blocked due to ${o.finishReason}`,o.finishMessage&&(i+=`: ${o.finishMessage}`))}return i}function w(t){return this instanceof w?(this.v=t,this):new w(t)}function ue(t,e,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var s=n.apply(t,e||[]),i,o=[];return i={},a("next"),a("throw"),a("return"),i[Symbol.asyncIterator]=function(){return this},i;function a(f){s[f]&&(i[f]=function(d){return new Promise(function(g,C){o.push([f,d,g,C])>1||u(f,d)})})}function u(f,d){try{c(s[f](d))}catch(g){l(o[0][3],g)}}function c(f){f.value instanceof w?Promise.resolve(f.value.v).then(p,r):l(o[0][2],f)}function p(f){u("next",f)}function r(f){u("throw",f)}function l(f,d){f(d),o.shift(),o.length&&u(o[0][0],o[0][1])}}const Q=/^data\: (.*)(?:\n\n|\r\r|\r\n\r\n)/;function le(t){const e=t.body.pipeThrough(new TextDecoderStream("utf8",{fatal:!0})),n=fe(e),[s,i]=n.tee();return{stream:de(s),response:ce(i)}}async function ce(t){const e=[],n=t.getReader();for(;;){const{done:s,value:i}=await n.read();if(s)return M(pe(e));e.push(i)}}function de(t){return ue(this,arguments,function*(){const n=t.getReader();for(;;){const{value:s,done:i}=yield w(n.read());if(i)break;yield yield w(M(s))}})}function fe(t){const e=t.getReader();return new ReadableStream({start(s){let i="";return o();function o(){return e.read().then(({value:a,done:u})=>{if(u){if(i.trim()){s.error(new m("Failed to parse stream"));return}s.close();return}i+=a;let c=i.match(Q),p;for(;c;){try{p=JSON.parse(c[1])}catch{s.error(new m(`Error parsing JSON response: "${c[1]}"`));return}s.enqueue(p),i=i.substring(c[0].length),c=i.match(Q)}return o()}).catch(a=>{let u=a;throw u.stack=a.stack,u.name==="AbortError"?u=new ft("Request aborted when reading from the stream"):u=new m("Error reading from the stream"),u})}}})}function pe(t){const e=t[t.length-1],n={promptFeedback:e?.promptFeedback};for(const s of t){if(s.candidates){let i=0;for(const o of s.candidates)if(n.candidates||(n.candidates=[]),n.candidates[i]||(n.candidates[i]={index:i}),n.candidates[i].citationMetadata=o.citationMetadata,n.candidates[i].groundingMetadata=o.groundingMetadata,n.candidates[i].finishReason=o.finishReason,n.candidates[i].finishMessage=o.finishMessage,n.candidates[i].safetyRatings=o.safetyRatings,o.content&&o.content.parts){n.candidates[i].content||(n.candidates[i].content={role:o.content.role||"user",parts:[]});const a={};for(const u of o.content.parts)u.text&&(a.text=u.text),u.functionCall&&(a.functionCall=u.functionCall),u.executableCode&&(a.executableCode=u.executableCode),u.codeExecutionResult&&(a.codeExecutionResult=u.codeExecutionResult),Object.keys(a).length===0&&(a.text=""),n.candidates[i].content.parts.push(a)}i++}s.usageMetadata&&(n.usageMetadata=s.usageMetadata)}return n}async function pt(t,e,n,s){const i=await R(e,v.STREAM_GENERATE_CONTENT,t,!0,JSON.stringify(n),s);return le(i)}async function gt(t,e,n,s){const o=await(await R(e,v.GENERATE_CONTENT,t,!1,JSON.stringify(n),s)).json();return{response:M(o)}}function ht(t){if(t!=null){if(typeof t=="string")return{role:"system",parts:[{text:t}]};if(t.text)return{role:"system",parts:[t]};if(t.parts)return t.role?t:{role:"system",parts:t.parts}}}function S(t){let e=[];if(typeof t=="string")e=[{text:t}];else for(const n of t)typeof n=="string"?e.push({text:n}):e.push(n);return ge(e)}function ge(t){const e={role:"user",parts:[]},n={role:"function",parts:[]};let s=!1,i=!1;for(const o of t)"functionResponse"in o?(n.parts.push(o),i=!0):(e.parts.push(o),s=!0);if(s&&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(!s&&!i)throw new m("No content is provided for sending chat message.");return s?e:n}function he(t,e){var n;let s={model:e?.model,generationConfig:e?.generationConfig,safetySettings:e?.safetySettings,tools:e?.tools,toolConfig:e?.toolConfig,systemInstruction:e?.systemInstruction,cachedContent:(n=e?.cachedContent)===null||n===void 0?void 0:n.name,contents:[]};const i=t.generateContentRequest!=null;if(t.contents){if(i)throw new y("CountTokensRequest must have one of contents or generateContentRequest, not both.");s.contents=t.contents}else if(i)s=Object.assign(Object.assign({},s),t.generateContentRequest);else{const o=S(t);s.contents=[o]}return{generateContentRequest:s}}function X(t){let e;return t.contents?e=t:e={contents:[S(t)]},t.systemInstruction&&(e.systemInstruction=ht(t.systemInstruction)),e}function me(t){return typeof t=="string"||Array.isArray(t)?{content:S(t)}:t}const tt=["text","inlineData","functionCall","functionResponse","executableCode","codeExecutionResult"],Ce={user:["text","inlineData"],function:["functionResponse"],model:["text","functionCall","executableCode","codeExecutionResult"],system:["text"]};function Oe(t){let e=!1;for(const n of t){const{role:s,parts:i}=n;if(!e&&s!=="user")throw new m(`First content should be with role 'user', got ${s}`);if(!Y.includes(s))throw new m(`Each item should include role field. Got ${s} but valid roles are: ${JSON.stringify(Y)}`);if(!Array.isArray(i))throw new m("Content should have 'parts' property with an array of Parts");if(i.length===0)throw new m("Each Content should have at least one part");const o={text:0,inlineData:0,functionCall:0,functionResponse:0,fileData:0,executableCode:0,codeExecutionResult:0};for(const u of i)for(const c of tt)c in u&&(o[c]+=1);const a=Ce[s];for(const u of tt)if(!a.includes(u)&&o[u]>0)throw new m(`Content with role '${s}' can't contain '${u}' part`);e=!0}}function et(t){var e;if(t.candidates===void 0||t.candidates.length===0)return!1;const n=(e=t.candidates[0])===null||e===void 0?void 0:e.content;if(n===void 0||n.parts===void 0||n.parts.length===0)return!1;for(const s of n.parts)if(s===void 0||Object.keys(s).length===0||s.text!==void 0&&s.text==="")return!1;return!0}const nt="SILENT_ERROR";class ye{constructor(e,n,s,i={}){this.model=n,this.params=s,this._requestOptions=i,this._history=[],this._sendPromise=Promise.resolve(),this._apiKey=e,s?.history&&(Oe(s.history),this._history=s.history)}async getHistory(){return await this._sendPromise,this._history}async sendMessage(e,n={}){var s,i,o,a,u,c;await this._sendPromise;const p=S(e),r={safetySettings:(s=this.params)===null||s===void 0?void 0:s.safetySettings,generationConfig:(i=this.params)===null||i===void 0?void 0:i.generationConfig,tools:(o=this.params)===null||o===void 0?void 0:o.tools,toolConfig:(a=this.params)===null||a===void 0?void 0:a.toolConfig,systemInstruction:(u=this.params)===null||u===void 0?void 0:u.systemInstruction,cachedContent:(c=this.params)===null||c===void 0?void 0:c.cachedContent,contents:[...this._history,p]},l=Object.assign(Object.assign({},this._requestOptions),n);let f;return this._sendPromise=this._sendPromise.then(()=>gt(this._apiKey,this.model,r,l)).then(d=>{var g;if(et(d.response)){this._history.push(p);const C=Object.assign({parts:[],role:"model"},(g=d.response.candidates)===null||g===void 0?void 0:g[0].content);this._history.push(C)}else{const C=O(d.response);C&&console.warn(`sendMessage() was unsuccessful. ${C}. Inspect response object for details.`)}f=d}).catch(d=>{throw this._sendPromise=Promise.resolve(),d}),await this._sendPromise,f}async sendMessageStream(e,n={}){var s,i,o,a,u,c;await this._sendPromise;const p=S(e),r={safetySettings:(s=this.params)===null||s===void 0?void 0:s.safetySettings,generationConfig:(i=this.params)===null||i===void 0?void 0:i.generationConfig,tools:(o=this.params)===null||o===void 0?void 0:o.tools,toolConfig:(a=this.params)===null||a===void 0?void 0:a.toolConfig,systemInstruction:(u=this.params)===null||u===void 0?void 0:u.systemInstruction,cachedContent:(c=this.params)===null||c===void 0?void 0:c.cachedContent,contents:[...this._history,p]},l=Object.assign(Object.assign({},this._requestOptions),n),f=pt(this._apiKey,this.model,r,l);return this._sendPromise=this._sendPromise.then(()=>f).catch(d=>{throw new Error(nt)}).then(d=>d.response).then(d=>{if(et(d)){this._history.push(p);const g=Object.assign({},d.candidates[0].content);g.role||(g.role="model"),this._history.push(g)}else{const g=O(d);g&&console.warn(`sendMessageStream() was unsuccessful. ${g}. Inspect response object for details.`)}}).catch(d=>{d.message!==nt&&console.error(d)}),f}}async function Ie(t,e,n,s){return(await R(e,v.COUNT_TOKENS,t,!1,JSON.stringify(n),s)).json()}async function ve(t,e,n,s){return(await R(e,v.EMBED_CONTENT,t,!1,JSON.stringify(n),s)).json()}async function _e(t,e,n,s){const i=n.requests.map(a=>Object.assign(Object.assign({},a),{model:e}));return(await R(e,v.BATCH_EMBED_CONTENTS,t,!1,JSON.stringify({requests:i}),s)).json()}class st{constructor(e,n,s={}){this.apiKey=e,this._requestOptions=s,n.model.includes("/")?this.model=n.model:this.model=`models/${n.model}`,this.generationConfig=n.generationConfig||{},this.safetySettings=n.safetySettings||[],this.tools=n.tools,this.toolConfig=n.toolConfig,this.systemInstruction=ht(n.systemInstruction),this.cachedContent=n.cachedContent}async generateContent(e,n={}){var s;const i=X(e),o=Object.assign(Object.assign({},this._requestOptions),n);return gt(this.apiKey,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:(s=this.cachedContent)===null||s===void 0?void 0:s.name},i),o)}async generateContentStream(e,n={}){var s;const i=X(e),o=Object.assign(Object.assign({},this._requestOptions),n);return pt(this.apiKey,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:(s=this.cachedContent)===null||s===void 0?void 0:s.name},i),o)}startChat(e){var n;return new ye(this.apiKey,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:(n=this.cachedContent)===null||n===void 0?void 0:n.name},e),this._requestOptions)}async countTokens(e,n={}){const s=he(e,{model:this.model,generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:this.cachedContent}),i=Object.assign(Object.assign({},this._requestOptions),n);return Ie(this.apiKey,this.model,s,i)}async embedContent(e,n={}){const s=me(e),i=Object.assign(Object.assign({},this._requestOptions),n);return ve(this.apiKey,this.model,s,i)}async batchEmbedContents(e,n={}){const s=Object.assign(Object.assign({},this._requestOptions),n);return _e(this.apiKey,this.model,e,s)}}class it{constructor(e){this.apiKey=e}getGenerativeModel(e,n){if(!e.model)throw new m("Must provide a model name. Example: genai.getGenerativeModel({ model: 'my-model-name' })");return new st(this.apiKey,e,n)}getGenerativeModelFromCachedContent(e,n,s){if(!e.name)throw new y("Cached content must contain a `name` field.");if(!e.model)throw new y("Cached content must contain a `model` field.");const i=["model","systemInstruction"];for(const a of i)if(n?.[a]&&e[a]&&n?.[a]!==e[a]){if(a==="model"){const u=n.model.startsWith("models/")?n.model.replace("models/",""):n.model,c=e.model.startsWith("models/")?e.model.replace("models/",""):e.model;if(u===c)continue}throw new y(`Different value for "${a}" specified in modelParams (${n[a]}) and cachedContent (${e[a]})`)}const o=Object.assign(Object.assign({},n),{model:e.model,tools:e.tools,toolConfig:e.toolConfig,systemInstruction:e.systemInstruction,cachedContent:e});return new st(this.apiKey,o,s)}}function ot(t,e){const n=Ee(t),s=we(n,e);return{tools:n,toolConfig:s}}function Ee(t){let e=[];const n=[];return t.forEach(i=>{if(ut(i)){const[o]=Wt([i]);o.functionDeclarations&&e.push(...o.functionDeclarations)}else if(lt(i)){const{functionDeclarations:o}=Te(i);if(o)e.push(...o);else throw new Error("Failed to convert OpenAI structured tool to GenerativeAI tool")}else n.push(i)}),n.find(i=>"functionDeclarations"in i)?n.map(i=>{if(e?.length>0&&"functionDeclarations"in i){const o={functionDeclarations:[...i.functionDeclarations||[],...e]};return e=[],o}return i}):[...n,...e.length>0?[{functionDeclarations:e}]:[]]}function Te(t){return{functionDeclarations:[{name:t.function.name,description:t.function.description,parameters:I(t.function.parameters)}]}}function we(t,e){if(!t.length||!e)return;const{toolChoice:n,allowedFunctionNames:s}=e,i={any:E.ANY,auto:E.AUTO,none:E.NONE};if(n&&["any","auto","none"].includes(n))return{functionCallingConfig:{mode:i[n]??"MODE_UNSPECIFIED",allowedFunctionNames:s}};if(typeof n=="string"||s)return{functionCallingConfig:{mode:E.ANY,allowedFunctionNames:[...s??[],...n&&typeof n=="string"?[n]:[]]}}}const Se={"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-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-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-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-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-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-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-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.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-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.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-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-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-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-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-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-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-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-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-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-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-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-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-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}};var Re=Se,De=class extends Ot{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(t){if(super(t),this.model=t.model.replace(/^models\//,""),this.maxOutputTokens=t.maxOutputTokens??this.maxOutputTokens,this.maxOutputTokens&&this.maxOutputTokens<0)throw new Error("`maxOutputTokens` must be a positive integer");if(this.temperature=t.temperature??this.temperature,this.temperature&&(this.temperature<0||this.temperature>2))throw new Error("`temperature` must be in the range of [0.0,2.0]");if(this.topP=t.topP??this.topP,this.topP&&this.topP<0)throw new Error("`topP` must be a positive integer");if(this.topP&&this.topP>1)throw new Error("`topP` must be below 1.");if(this.topK=t.topK??this.topK,this.topK&&this.topK<0)throw new Error("`topK` must be a positive integer");if(this.stopSequences=t.stopSequences??this.stopSequences,this.apiKey=t.apiKey??kt("GOOGLE_API_KEY"),!this.apiKey)throw new Error("Please set an API key for Google GenerativeAI in the environment variable GOOGLE_API_KEY or in the `apiKey` field of the ChatGoogleGenerativeAI constructor");if(this.safetySettings=t.safetySettings??this.safetySettings,this.safetySettings&&this.safetySettings.length>0&&new Set(this.safetySettings.map(n=>n.category)).size!==this.safetySettings.length)throw new Error("The categories in `safetySettings` array must be unique");this.streaming=t.streaming??this.streaming,this.json=t.json,this.thinkingConfig=t.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:t.apiVersion,baseUrl:t.baseUrl,customHeaders:t.customHeaders}),this.streamUsage=t.streamUsage??this.streamUsage}useCachedContent(t,e,n){this.apiKey&&(this.client=new it(this.apiKey).getGenerativeModelFromCachedContent(t,e,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(t){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:t.stop}}_combineLLMOutput(){return[]}_llmType(){return"googlegenerativeai"}bindTools(t,e){return this.withConfig({tools:ot(t)?.tools,...e})}invocationParams(t){const e=t?.tools?.length?ot(t.tools,{toolChoice:t.tool_choice,allowedFunctionNames:t.allowedFunctionNames}):void 0;return t?.responseSchema?(this.client.generationConfig.responseSchema=t.responseSchema,this.client.generationConfig.responseMimeType="application/json"):(this.client.generationConfig.responseSchema=void 0,this.client.generationConfig.responseMimeType=this.json?"application/json":void 0),{...e?.tools?{tools:e.tools}:{},...e?.toolConfig?{toolConfig:e.toolConfig}:{}}}async _generate(t,e,n){const s=P(t,this._isMultimodalModel,this.useSystemInstruction,this.model);let i=s;if(s[0].role==="system"){const[p]=s;this.client.systemInstruction=p,i=s.slice(1)}const o=this.invocationParams(e);if(this.streaming){const p={},r=this._streamResponseChunks(t,e,n),l={};for await(const d of r){const g=d.generationInfo?.completion??0;l[g]===void 0?l[g]=d:l[g]=l[g].concat(d)}return{generations:Object.entries(l).sort(([d],[g])=>parseInt(d,10)-parseInt(g,10)).map(([d,g])=>g),llmOutput:{estimatedTokenUsage:p}}}const a=await this.completionWithRetry({...o,contents:i});let u;"usageMetadata"in a.response&&(u=j(a.response.usageMetadata,this.model));const c=Bt(a.response,{usageMetadata:u});return c.generations?.length>0&&await n?.handleLLMNewToken(c.generations[0]?.text??""),c}async*_streamResponseChunks(t,e,n){const s=P(t,this._isMultimodalModel,this.useSystemInstruction,this.model);let i=s;if(s[0].role==="system"){const[f]=s;this.client.systemInstruction=f,i=s.slice(1)}const a={...this.invocationParams(e),contents:i},u=await this.caller.callWithOptions({signal:e?.signal},async()=>{const{stream:f}=await this.client.generateContentStream(a);return f});let c,p=0,r=0,l=0;for await(const f of u){if("usageMetadata"in f&&f.usageMetadata!==void 0&&this.streamUsage!==!1&&e.streamUsage!==!1){c=j(f.usageMetadata,this.model);const g=f.usageMetadata.promptTokenCount??0;c.input_tokens=Math.max(0,g-p),p=g;const C=f.usageMetadata.candidatesTokenCount??0;c.output_tokens=Math.max(0,C-r),r=C;const D=f.usageMetadata.totalTokenCount??0;c.total_tokens=Math.max(0,D-l),l=D}const d=qt(f,{usageMetadata:c});d&&(yield d,await n?.handleLLMNewToken(d.text??""))}}async completionWithRetry(t,e){return this.caller.callWithOptions({signal:e?.signal},async()=>{try{return await this.client.generateContent(t)}catch(n){throw n.message?.includes("400 Bad Request")&&(n.status=400),n}})}get profile(){return Re[this.model]??{}}withStructuredOutput(t,e){const n=t,s=e?.name,i=e?.method,o=e?.includeRaw;if(i==="jsonMode")throw new Error('ChatGoogleGenerativeAI only supports "jsonSchema" or "functionCalling" as a method.');let a,u;if(i==="functionCalling"){let l=s??"extract",f;if(at(n)){const d=N(n);f=[{functionDeclarations:[{name:l,description:d.description??"A function available to call.",parameters:d}]}],u=new F({returnSingle:!0,keyName:l,zodSchema:n})}else{let d;typeof n.name=="string"&&typeof n.parameters=="object"&&n.parameters!=null?(d=n,d.parameters=I(n.parameters),l=n.name):d={name:l,description:n.description??"",parameters:I(n)},f=[{functionDeclarations:[d]}],u=new F({returnSingle:!0,keyName:l})}a=this.bindTools(f).withConfig({allowedFunctionNames:[l]})}else{const l=N(n);a=this.withConfig({responseSchema:l}),u=new yt}if(!o)return a.pipe(u).withConfig({runName:"ChatGoogleGenerativeAIStructuredOutput"});const c=G.assign({parsed:(l,f)=>u.invoke(l.raw,f)}),p=G.assign({parsed:()=>null}),r=c.withFallbacks({fallbacks:[p]});return Nt.from([{raw:a},r]).withConfig({runName:"StructuredOutputRunnable"})}};export{De as ChatGoogleGenerativeAI};
@@ -1,8 +1,8 @@
1
- import{g as wn,O as Ut,h as bn,c as $t,f as xn,S as Sn,J as kn,R as Bt}from"./index-Zctd0Z8B.js";import{r as Tn,K as xs,t as Lt,ah as jt,I as Mn,J as On,E as N,B as qt,L as vn,y as ie,i as at,D as In,M as Rn}from"./index-CR9w_74S.js";import{o as y,d as Wt,e as An,f as Cn,u as Dt,s as b,l as w,n as E,h as Ze,t as Mt,i as Pn,j as En}from"./index-CkHH_UI9.js";import"./index-DiwCBW8I.js";import"./index-DRz5BQNA.js";var Ft=class extends wn{static lc_name(){return"AnthropicToolsOutputParser"}lc_namespace=["langchain","anthropic","output_parsers"];returnId=!1;keyName;returnSingle=!1;zodSchema;constructor(t){super(t),this.keyName=t.keyName,this.returnSingle=t.returnSingle??this.returnSingle,this.zodSchema=t.zodSchema}async _validateResult(t){let e=t;if(typeof t=="string")try{e=JSON.parse(t)}catch(n){throw new Ut(`Failed to parse. Text: "${JSON.stringify(t,null,2)}". Error: ${JSON.stringify(n.message)}`,t)}else e=t;if(this.zodSchema===void 0)return e;const s=await Tn(this.zodSchema,e);if(s.success)return s.data;throw new Ut(`Failed to parse. Text: "${JSON.stringify(t,null,2)}". Error: ${JSON.stringify(s.error.issues)}`,JSON.stringify(e,null,2))}async parseResult(t){const e=t.flatMap(r=>{const{message:a}=r;return Array.isArray(a.content)?Ss(a.content)[0]:[]});if(e[0]===void 0)throw new Error("No parseable tool calls provided to AnthropicToolsOutputParser.");const[s]=e;return await this._validateResult(s.args)}};function Ss(t){const e=[];for(const s of t)s.type==="tool_use"&&e.push({name:s.name,args:s.input,id:s.id,type:"tool_call"});return e}function Nn(t){if(t)return t==="any"?{type:"any"}:t==="auto"?{type:"auto"}:t==="none"?{type:"none"}:typeof t=="string"?{type:"tool",name:t}:t}const Un=y({cache_control:Cn().optional().nullable(),defer_loading:An().optional(),input_examples:Wt(Dt()).optional(),allowed_callers:Wt(Dt()).optional()}),Ht={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 $n(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="thinking"}function Bn(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="redacted_thinking"}function Ln(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="search_result"}function jn(t){return typeof t!="object"||t==null||!("type"in t)||t.type!=="image"||!("source"in t)||typeof t.source!="object"||t.source==null||!("type"in t.source)?!1:t.source.type==="base64"?!(!("media_type"in t.source)||typeof t.source.media_type!="string"||!("data"in t.source)||typeof t.source.data!="string"):t.source.type==="url"?!(!("url"in t.source)||typeof t.source.url!="string"):!1}const qn={providerName:"anthropic",fromStandardTextBlock(t){return{type:"text",text:t.text,..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}}},fromStandardImageBlock(t){if(t.source_type==="url"){const e=xs({dataUrl:t.url,asTypedArray:!1});return e?{type:"image",source:{type:"base64",data:e.data,media_type:e.mime_type},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}}:{type:"image",source:{type:"url",url:t.url},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}}}else{if(t.source_type==="base64")return{type:"image",source:{type:"base64",data:t.data,media_type:t.mime_type??""},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}};throw new Error(`Unsupported image source type: ${t.source_type}`)}},fromStandardFileBlock(t){const e=(t.mime_type??"").split(";")[0];if(t.source_type==="url"){if(e==="application/pdf"||e==="")return{type:"document",source:{type:"url",url:t.url},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};throw new Error(`Unsupported file mime type for file url source: ${t.mime_type}`)}else if(t.source_type==="text"){if(e==="text/plain"||e==="")return{type:"document",source:{type:"text",data:t.text,media_type:t.mime_type??""},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};throw new Error(`Unsupported file mime type for file text source: ${t.mime_type}`)}else if(t.source_type==="base64"){if(e==="application/pdf"||e==="")return{type:"document",source:{type:"base64",data:t.data,media_type:"application/pdf"},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};if(["image/jpeg","image/png","image/gif","image/webp"].includes(e))return{type:"document",source:{type:"content",content:[{type:"image",source:{type:"base64",data:t.data,media_type:e}}]},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};throw new Error(`Unsupported file mime type for file base64 source: ${t.mime_type}`)}else throw new Error(`Unsupported file source type: ${t.source_type}`)}},Wn=t=>t();function Dn(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="citation"}function Fn(t){function*e(){for(const s of t)Dn(s)&&(s.source==="char"?yield{type:"char_location",file_id:s.url??"",start_char_index:s.startIndex??0,end_char_index:s.endIndex??0,document_title:s.title??null,document_index:0,cited_text:s.citedText??""}:s.source==="page"?yield{type:"page_location",file_id:s.url??"",start_page_number:s.startIndex??0,end_page_number:s.endIndex??0,document_title:s.title??null,document_index:0,cited_text:s.citedText??""}:s.source==="block"?yield{type:"content_block_location",file_id:s.url??"",start_block_index:s.startIndex??0,end_block_index:s.endIndex??0,document_title:s.title??null,document_index:0,cited_text:s.citedText??""}:s.source==="url"?yield{type:"web_search_result_location",url:s.url??"",title:s.title??null,encrypted_index:String(s.startIndex??0),cited_text:s.citedText??""}:s.source==="search"&&(yield{type:"search_result_location",title:s.title??null,start_block_index:s.startIndex??0,end_block_index:s.endIndex??0,search_result_index:0,source:s.source??"",cited_text:s.citedText??""}))}return Array.from(e())}function oe(t){return typeof t=="string"?t:Hn(t)}function Hn(t){const e=[];for(let s=0,{length:n}=t;s<n;s++)e.push(String.fromCharCode(t[s]));return btoa(e.join(""))}function it(t){return(t??"").split(";")[0].toLowerCase()}function ke(t,e){if(t!=null&&typeof t=="object"&&e in t)return t[e]}function Z(t,e){const s=ke(e,"cache_control");s!==void 0&&(t.cache_control=s);const n=ke(e,"citations");n!==void 0&&(t.citations=n);const r=ke(e,"context");r!==void 0&&(t.context=r);const a=ke(e,"title");return a!==void 0&&(t.title=a),t}function ot(t,e){const s=ke(e,"cache_control");return s!==void 0&&(t.cache_control=s),t}function Jt(t){return new Set(["image/jpeg","image/png","image/gif","image/webp"]).has(t)}function Jn(t){const e=[],s=t.response_metadata,n="model_provider"in s&&s?.model_provider==="anthropic";for(const r of t.contentBlocks)if(r.type==="text")r.annotations?e.push({type:"text",text:r.text,citations:Fn(r.annotations)}):e.push({type:"text",text:r.text});else if(r.type==="tool_call")e.push({type:"tool_use",id:r.id??"",name:r.name,input:r.args});else if(r.type==="tool_call_chunk"){const a=Wn(()=>{if(typeof r.args!="string")return r.args;try{return JSON.parse(r.args)}catch{return{}}});e.push({type:"tool_use",id:r.id??"",name:r.name??"",input:a})}else if(r.type==="reasoning"&&n)e.push({type:"thinking",thinking:r.reasoning,signature:String(r.signature)});else if(r.type==="server_tool_call"&&n)r.name==="web_search"?e.push({type:"server_tool_use",name:r.name,id:r.id??"",input:r.args}):r.name==="code_execution"&&e.push({type:"server_tool_use",name:r.name,id:r.id??"",input:r.args});else if(r.type==="server_tool_call_result"&&n)if(r.name==="web_search"&&Array.isArray(r.output.urls)){const a=r.output.urls.map(i=>({type:"web_search_result",title:"",encrypted_content:"",url:i}));e.push({type:"web_search_tool_result",tool_use_id:r.toolCallId??"",content:a})}else r.name==="code_execution"?e.push({type:"code_execution_tool_result",tool_use_id:r.toolCallId??"",content:r.output}):r.name==="mcp_tool_result"&&e.push({type:"mcp_tool_result",tool_use_id:r.toolCallId??"",content:r.output});else{if(r.type==="audio")throw new Error("Anthropic does not support audio content blocks.");if(r.type==="file"){const a=r.metadata;if(r.fileId){e.push(Z({type:"document",source:{type:"file",file_id:r.fileId}},a));continue}if(r.url){const i=it(r.mimeType);if(i==="application/pdf"||i===""){e.push(Z({type:"document",source:{type:"url",url:r.url}},a));continue}}if(r.data){const i=it(r.mimeType);if(i===""||i==="application/pdf")e.push(Z({type:"document",source:{type:"base64",data:oe(r.data),media_type:"application/pdf"}},a));else if(i==="text/plain")e.push(Z({type:"document",source:{type:"text",data:oe(r.data),media_type:"text/plain"}},a));else if(Jt(i))e.push(Z({type:"document",source:{type:"content",content:[{type:"image",source:{type:"base64",data:oe(r.data),media_type:i}}]}},a));else throw new Error(`Unsupported file mime type for Anthropic base64 source: ${i}`);continue}throw new Error("File content block must include a fileId, url, or data property.")}else if(r.type==="image"){const a=r.metadata;if(r.fileId){e.push(ot({type:"image",source:{type:"file",file_id:r.fileId}},a));continue}if(r.url){e.push(ot({type:"image",source:{type:"url",url:r.url}},a));continue}if(r.data){const i=it(r.mimeType)||"image/png";Jt(i)&&e.push(ot({type:"image",source:{type:"base64",data:oe(r.data),media_type:i}},a));continue}throw new Error("Image content block must include a fileId, url, or data property.")}else r.type==="video"||(r.type==="text-plain"?r.data&&e.push(Z({type:"document",source:{type:"text",data:oe(r.data),media_type:"text/plain"}},r.metadata)):r.type==="non_standard"&&n&&e.push(r.value))}return e}function Kt(t){const e=xs({dataUrl:t});if(e)return{type:"base64",media_type:e.mime_type,data:e.data};let s;try{s=new URL(t)}catch{throw new Error([`Malformed image URL: ${JSON.stringify(t)}. Content blocks of type 'image_url' must be a valid http, https, or base64-encoded data URL.`,"Example: data:image/png;base64,/9j/4AAQSk...","Example: https://example.com/image.jpg"].join(`
1
+ import{B as wn,O as Ut,a as bn,S as xn,J as Sn,R as $t}from"./index-DIlJ2WcE.js";import{as as kn,J as xs,ab as Bt,G as Lt,a5 as Tn,af as Mn,D as N,E as jt,at as On,aq as ie,i as at,ar as vn,au as In}from"./base-ZEkF4ver.js";import{o as y,b as qt,c as Rn,d as An,u as Wt,s as b,l as w,n as E,e as Ze,t as Mt,_ as Cn,f as Pn}from"./index-CNfmoBX-.js";import"./index-Bfe1ynAS.js";import{c as Dt,d as En}from"./base-Aouj1Yhj.js";import"./index-CtWrgdCi.js";var Ft=class extends wn{static lc_name(){return"AnthropicToolsOutputParser"}lc_namespace=["langchain","anthropic","output_parsers"];returnId=!1;keyName;returnSingle=!1;zodSchema;constructor(t){super(t),this.keyName=t.keyName,this.returnSingle=t.returnSingle??this.returnSingle,this.zodSchema=t.zodSchema}async _validateResult(t){let e=t;if(typeof t=="string")try{e=JSON.parse(t)}catch(n){throw new Ut(`Failed to parse. Text: "${JSON.stringify(t,null,2)}". Error: ${JSON.stringify(n.message)}`,t)}else e=t;if(this.zodSchema===void 0)return e;const s=await kn(this.zodSchema,e);if(s.success)return s.data;throw new Ut(`Failed to parse. Text: "${JSON.stringify(t,null,2)}". Error: ${JSON.stringify(s.error.issues)}`,JSON.stringify(e,null,2))}async parseResult(t){const e=t.flatMap(r=>{const{message:a}=r;return Array.isArray(a.content)?Ss(a.content)[0]:[]});if(e[0]===void 0)throw new Error("No parseable tool calls provided to AnthropicToolsOutputParser.");const[s]=e;return await this._validateResult(s.args)}};function Ss(t){const e=[];for(const s of t)s.type==="tool_use"&&e.push({name:s.name,args:s.input,id:s.id,type:"tool_call"});return e}function Nn(t){if(t)return t==="any"?{type:"any"}:t==="auto"?{type:"auto"}:t==="none"?{type:"none"}:typeof t=="string"?{type:"tool",name:t}:t}const Un=y({cache_control:An().optional().nullable(),defer_loading:Rn().optional(),input_examples:qt(Wt()).optional(),allowed_callers:qt(Wt()).optional()}),Ht={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 $n(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="thinking"}function Bn(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="redacted_thinking"}function Ln(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="search_result"}function jn(t){return typeof t!="object"||t==null||!("type"in t)||t.type!=="image"||!("source"in t)||typeof t.source!="object"||t.source==null||!("type"in t.source)?!1:t.source.type==="base64"?!(!("media_type"in t.source)||typeof t.source.media_type!="string"||!("data"in t.source)||typeof t.source.data!="string"):t.source.type==="url"?!(!("url"in t.source)||typeof t.source.url!="string"):!1}const qn={providerName:"anthropic",fromStandardTextBlock(t){return{type:"text",text:t.text,..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}}},fromStandardImageBlock(t){if(t.source_type==="url"){const e=xs({dataUrl:t.url,asTypedArray:!1});return e?{type:"image",source:{type:"base64",data:e.data,media_type:e.mime_type},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}}:{type:"image",source:{type:"url",url:t.url},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}}}else{if(t.source_type==="base64")return{type:"image",source:{type:"base64",data:t.data,media_type:t.mime_type??""},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}};throw new Error(`Unsupported image source type: ${t.source_type}`)}},fromStandardFileBlock(t){const e=(t.mime_type??"").split(";")[0];if(t.source_type==="url"){if(e==="application/pdf"||e==="")return{type:"document",source:{type:"url",url:t.url},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};throw new Error(`Unsupported file mime type for file url source: ${t.mime_type}`)}else if(t.source_type==="text"){if(e==="text/plain"||e==="")return{type:"document",source:{type:"text",data:t.text,media_type:t.mime_type??""},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};throw new Error(`Unsupported file mime type for file text source: ${t.mime_type}`)}else if(t.source_type==="base64"){if(e==="application/pdf"||e==="")return{type:"document",source:{type:"base64",data:t.data,media_type:"application/pdf"},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};if(["image/jpeg","image/png","image/gif","image/webp"].includes(e))return{type:"document",source:{type:"content",content:[{type:"image",source:{type:"base64",data:t.data,media_type:e}}]},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};throw new Error(`Unsupported file mime type for file base64 source: ${t.mime_type}`)}else throw new Error(`Unsupported file source type: ${t.source_type}`)}},Wn=t=>t();function Dn(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="citation"}function Fn(t){function*e(){for(const s of t)Dn(s)&&(s.source==="char"?yield{type:"char_location",file_id:s.url??"",start_char_index:s.startIndex??0,end_char_index:s.endIndex??0,document_title:s.title??null,document_index:0,cited_text:s.citedText??""}:s.source==="page"?yield{type:"page_location",file_id:s.url??"",start_page_number:s.startIndex??0,end_page_number:s.endIndex??0,document_title:s.title??null,document_index:0,cited_text:s.citedText??""}:s.source==="block"?yield{type:"content_block_location",file_id:s.url??"",start_block_index:s.startIndex??0,end_block_index:s.endIndex??0,document_title:s.title??null,document_index:0,cited_text:s.citedText??""}:s.source==="url"?yield{type:"web_search_result_location",url:s.url??"",title:s.title??null,encrypted_index:String(s.startIndex??0),cited_text:s.citedText??""}:s.source==="search"&&(yield{type:"search_result_location",title:s.title??null,start_block_index:s.startIndex??0,end_block_index:s.endIndex??0,search_result_index:0,source:s.source??"",cited_text:s.citedText??""}))}return Array.from(e())}function oe(t){return typeof t=="string"?t:Hn(t)}function Hn(t){const e=[];for(let s=0,{length:n}=t;s<n;s++)e.push(String.fromCharCode(t[s]));return btoa(e.join(""))}function it(t){return(t??"").split(";")[0].toLowerCase()}function ke(t,e){if(t!=null&&typeof t=="object"&&e in t)return t[e]}function Z(t,e){const s=ke(e,"cache_control");s!==void 0&&(t.cache_control=s);const n=ke(e,"citations");n!==void 0&&(t.citations=n);const r=ke(e,"context");r!==void 0&&(t.context=r);const a=ke(e,"title");return a!==void 0&&(t.title=a),t}function ot(t,e){const s=ke(e,"cache_control");return s!==void 0&&(t.cache_control=s),t}function Jt(t){return new Set(["image/jpeg","image/png","image/gif","image/webp"]).has(t)}function Jn(t){const e=[],s=t.response_metadata,n="model_provider"in s&&s?.model_provider==="anthropic";for(const r of t.contentBlocks)if(r.type==="text")r.annotations?e.push({type:"text",text:r.text,citations:Fn(r.annotations)}):e.push({type:"text",text:r.text});else if(r.type==="tool_call")e.push({type:"tool_use",id:r.id??"",name:r.name,input:r.args});else if(r.type==="tool_call_chunk"){const a=Wn(()=>{if(typeof r.args!="string")return r.args;try{return JSON.parse(r.args)}catch{return{}}});e.push({type:"tool_use",id:r.id??"",name:r.name??"",input:a})}else if(r.type==="reasoning"&&n)e.push({type:"thinking",thinking:r.reasoning,signature:String(r.signature)});else if(r.type==="server_tool_call"&&n)r.name==="web_search"?e.push({type:"server_tool_use",name:r.name,id:r.id??"",input:r.args}):r.name==="code_execution"&&e.push({type:"server_tool_use",name:r.name,id:r.id??"",input:r.args});else if(r.type==="server_tool_call_result"&&n)if(r.name==="web_search"&&Array.isArray(r.output.urls)){const a=r.output.urls.map(i=>({type:"web_search_result",title:"",encrypted_content:"",url:i}));e.push({type:"web_search_tool_result",tool_use_id:r.toolCallId??"",content:a})}else r.name==="code_execution"?e.push({type:"code_execution_tool_result",tool_use_id:r.toolCallId??"",content:r.output}):r.name==="mcp_tool_result"&&e.push({type:"mcp_tool_result",tool_use_id:r.toolCallId??"",content:r.output});else{if(r.type==="audio")throw new Error("Anthropic does not support audio content blocks.");if(r.type==="file"){const a=r.metadata;if(r.fileId){e.push(Z({type:"document",source:{type:"file",file_id:r.fileId}},a));continue}if(r.url){const i=it(r.mimeType);if(i==="application/pdf"||i===""){e.push(Z({type:"document",source:{type:"url",url:r.url}},a));continue}}if(r.data){const i=it(r.mimeType);if(i===""||i==="application/pdf")e.push(Z({type:"document",source:{type:"base64",data:oe(r.data),media_type:"application/pdf"}},a));else if(i==="text/plain")e.push(Z({type:"document",source:{type:"text",data:oe(r.data),media_type:"text/plain"}},a));else if(Jt(i))e.push(Z({type:"document",source:{type:"content",content:[{type:"image",source:{type:"base64",data:oe(r.data),media_type:i}}]}},a));else throw new Error(`Unsupported file mime type for Anthropic base64 source: ${i}`);continue}throw new Error("File content block must include a fileId, url, or data property.")}else if(r.type==="image"){const a=r.metadata;if(r.fileId){e.push(ot({type:"image",source:{type:"file",file_id:r.fileId}},a));continue}if(r.url){e.push(ot({type:"image",source:{type:"url",url:r.url}},a));continue}if(r.data){const i=it(r.mimeType)||"image/png";Jt(i)&&e.push(ot({type:"image",source:{type:"base64",data:oe(r.data),media_type:i}},a));continue}throw new Error("Image content block must include a fileId, url, or data property.")}else r.type==="video"||(r.type==="text-plain"?r.data&&e.push(Z({type:"document",source:{type:"text",data:oe(r.data),media_type:"text/plain"}},r.metadata)):r.type==="non_standard"&&n&&e.push(r.value))}return e}function Kt(t){const e=xs({dataUrl:t});if(e)return{type:"base64",media_type:e.mime_type,data:e.data};let s;try{s=new URL(t)}catch{throw new Error([`Malformed image URL: ${JSON.stringify(t)}. Content blocks of type 'image_url' must be a valid http, https, or base64-encoded data URL.`,"Example: data:image/png;base64,/9j/4AAQSk...","Example: https://example.com/image.jpg"].join(`
2
2
 
3
3
  `))}if(s.protocol==="http:"||s.protocol==="https:")return{type:"url",url:t};throw new Error([`Invalid image URL protocol: ${JSON.stringify(s.protocol)}. Anthropic only supports images as http, https, or base64-encoded data URLs on 'image_url' content blocks.`,"Example: data:image/png;base64,/9j/4AAQSk...","Example: https://example.com/image.jpg"].join(`
4
4
 
5
- `))}function Kn(t){const e=[];for(const s of t)if(s._getType()==="tool")if(typeof s.content=="string"){const n=e[e.length-1];n?._getType()==="human"&&Array.isArray(n.content)&&"type"in n.content[0]&&n.content[0].type==="tool_result"?n.content.push({type:"tool_result",content:s.content,tool_use_id:s.tool_call_id}):e.push(new jt({content:[{type:"tool_result",content:s.content,tool_use_id:s.tool_call_id}]}))}else e.push(new jt({content:[{type:"tool_result",...s.content!=null?{content:_t(s)}:{},tool_use_id:s.tool_call_id}]}));else e.push(s);return e}function Xt(t){if(t.id===void 0)throw new Error('Anthropic requires all tool calls to have an "id".');return{type:"tool_use",id:t.id,name:t.name,input:t.args}}function*Xn(t){const e=["bash_code_execution_tool_result","input_json_delta","server_tool_use","text_editor_code_execution_tool_result","tool_result","tool_use","web_search_result","web_search_tool_result"],s=["text","text_delta"];for(const n of t){Mn(n)&&(yield On(n,qn));const r="cache_control"in n?n.cache_control:void 0;if(n.type==="image_url"){let a;typeof n.image_url=="string"?a=Kt(n.image_url):typeof n.image_url=="object"&&n.image_url!==null&&"url"in n.image_url&&typeof n.image_url.url=="string"&&(a=Kt(n.image_url.url)),a&&(yield{type:"image",source:a,...r?{cache_control:r}:{}})}else{if(jn(n))return n;if(n.type==="document")yield{...n,...r?{cache_control:r}:{}};else if($n(n))yield{type:"thinking",thinking:n.thinking,signature:n.signature,...r?{cache_control:r}:{}};else if(Bn(n))yield{type:"redacted_thinking",data:n.data,...r?{cache_control:r}:{}};else if(Ln(n))yield{type:"search_result",title:n.title,source:n.source,..."cache_control"in n&&n.cache_control?{cache_control:n.cache_control}:{},..."citations"in n&&n.citations?{citations:n.citations}:{},content:n.content};else if(s.find(a=>a===n.type)&&"text"in n)yield{type:"text",text:n.text,...r?{cache_control:r}:{},..."citations"in n&&n.citations?{citations:n.citations}:{}};else if(e.find(a=>a===n.type)){const a={...n};if("index"in a&&delete a.index,a.type==="input_json_delta"&&(a.type="tool_use"),"input"in a&&typeof a.input=="string")try{a.input=JSON.parse(a.input)}catch{a.input={}}yield{...a,...r?{cache_control:r}:{}}}else n.type==="container_upload"&&(yield{...n,...r?{cache_control:r}:{}})}}}function _t(t){const{content:e}=t;return typeof e=="string"?e:Array.from(Xn(e))}function zt(t){const e=Kn(t);let s;e.length>0&&e[0]._getType()==="system"&&(s=t[0].content);const r=(s!==void 0?e.slice(1):e).map(a=>{let i;if(a._getType()==="human")i="user";else if(a._getType()==="ai")i="assistant";else if(a._getType()==="tool")i="user";else throw a._getType()==="system"?new Error("System messages are only permitted as the first passed message."):new Error(`Message type "${a.type}" is not supported.`);if(Lt(a)&&a.response_metadata?.output_version==="v1")return{role:i,content:Jn(a)};if(Lt(a)&&a.tool_calls?.length){if(typeof a.content=="string")return a.content===""?{role:i,content:a.tool_calls.map(Xt)}:{role:i,content:[{type:"text",text:a.content},...a.tool_calls.map(Xt)]};{const{content:u}=a;return!a.tool_calls.every(h=>u.find(p=>(p.type==="tool_use"||p.type==="input_json_delta"||p.type==="server_tool_use")&&p.id===h.id))&&console.warn('The "tool_calls" field on a message is only respected if content is a string.'),{role:i,content:_t(a)}}}else return{role:i,content:_t(a)}});return{messages:zn(r),system:s}}function zn(t){if(!t||t.length<=1)return t;const e=[];let s=t[0];const n=a=>typeof a=="string"?[{type:"text",text:a}]:a,r=a=>a.role!=="user"||typeof a.content=="string"?!1:Array.isArray(a.content)&&a.content.every(i=>i.type==="tool_result");for(let a=1;a<t.length;a+=1){const i=t[a];r(s)&&r(i)?s={...s,content:[...n(s.content),...n(i.content)]}:(e.push(s),s=i)}return e.push(s),e}function Vn(t,e){const s={model_provider:"anthropic"};if(t.type==="message_start"){const{content:n,usage:r,...a}=t.message,i={};for(const[_,d]of Object.entries(a))d!=null&&(i[_]=d);const{input_tokens:u,output_tokens:c,...h}=r??{},p=u+h.cache_creation_input_tokens+h.cache_read_input_tokens,f={input_tokens:p,output_tokens:c,total_tokens:p+c,input_token_details:{cache_creation:h.cache_creation_input_tokens,cache_read:h.cache_read_input_tokens}};return{chunk:new N({content:e.coerceContentToString?"":[],additional_kwargs:i,usage_metadata:e.streamUsage?f:void 0,response_metadata:{...s,usage:{...h}},id:t.message.id})}}else if(t.type==="message_delta"){const n={input_tokens:0,output_tokens:t.usage.output_tokens,total_tokens:t.usage.output_tokens,input_token_details:{cache_creation:t.usage.cache_creation_input_tokens,cache_read:t.usage.cache_read_input_tokens}},r="context_management"in t.delta?{context_management:t.delta.context_management}:void 0;return{chunk:new N({content:e.coerceContentToString?"":[],response_metadata:r,additional_kwargs:{...t.delta},usage_metadata:e.streamUsage?n:void 0})}}else if(t.type==="content_block_start"&&["tool_use","document","server_tool_use","web_search_tool_result"].includes(t.content_block.type)){const n=t.content_block;let r;return n.type==="tool_use"?r=[{id:n.id,index:t.index,name:n.name,args:""}]:r=[],{chunk:new N({content:e.coerceContentToString?"":[{index:t.index,...t.content_block,input:n.type==="server_tool_use"||n.type==="tool_use"?"":void 0}],response_metadata:s,additional_kwargs:{},tool_call_chunks:r})}}else if(t.type==="content_block_delta"&&["text_delta","citations_delta","thinking_delta","signature_delta"].includes(t.delta.type)){if(e.coerceContentToString&&"text"in t.delta)return{chunk:new N({content:t.delta.text})};{const n=t.delta;return"citation"in n&&(n.citations=[n.citation],delete n.citation),n.type==="thinking_delta"||n.type==="signature_delta"?{chunk:new N({content:[{index:t.index,...n,type:"thinking"}],response_metadata:s})}:{chunk:new N({content:[{index:t.index,...n,type:"text"}],response_metadata:s})}}}else{if(t.type==="content_block_delta"&&t.delta.type==="input_json_delta")return{chunk:new N({content:e.coerceContentToString?"":[{index:t.index,input:t.delta.partial_json,type:t.delta.type}],response_metadata:s,additional_kwargs:{},tool_call_chunks:[{index:t.index,args:t.delta.partial_json}]})};if(t.type==="content_block_start"&&t.content_block.type==="text"){const n=t.content_block?.text;if(n!==void 0)return{chunk:new N({content:e.coerceContentToString?n:[{index:t.index,...t.content_block}],response_metadata:s,additional_kwargs:{}})}}else{if(t.type==="content_block_start"&&t.content_block.type==="redacted_thinking")return{chunk:new N({content:e.coerceContentToString?"":[{index:t.index,...t.content_block}],response_metadata:s})};if(t.type==="content_block_start"&&t.content_block.type==="thinking"){const n=t.content_block.thinking;return{chunk:new N({content:e.coerceContentToString?n:[{index:t.index,...t.content_block}],response_metadata:s})}}}}return null}function Qn(t,e){const s={...e,model_provider:"anthropic"},n=e.usage,r=n!=null?{input_tokens:n.input_tokens??0,output_tokens:n.output_tokens??0,total_tokens:(n.input_tokens??0)+(n.output_tokens??0),input_token_details:{cache_creation:n.cache_creation_input_tokens,cache_read:n.cache_read_input_tokens}}:void 0;if(t.length===1&&t[0].type==="text")return[{text:t[0].text,message:new qt({content:t[0].text,additional_kwargs:e,usage_metadata:r,response_metadata:s,id:e.id})}];{const a=Ss(t);return[{text:"",message:new qt({content:t,additional_kwargs:e,tool_calls:a,usage_metadata:r,response_metadata:s,id:e.id})}]}}function Ce(t,e){return t.lc_error_code=e,t.message=`${t.message}
5
+ `))}function Kn(t){const e=[];for(const s of t)if(s._getType()==="tool")if(typeof s.content=="string"){const n=e[e.length-1];n?._getType()==="human"&&Array.isArray(n.content)&&"type"in n.content[0]&&n.content[0].type==="tool_result"?n.content.push({type:"tool_result",content:s.content,tool_use_id:s.tool_call_id}):e.push(new Lt({content:[{type:"tool_result",content:s.content,tool_use_id:s.tool_call_id}]}))}else e.push(new Lt({content:[{type:"tool_result",...s.content!=null?{content:_t(s)}:{},tool_use_id:s.tool_call_id}]}));else e.push(s);return e}function Xt(t){if(t.id===void 0)throw new Error('Anthropic requires all tool calls to have an "id".');return{type:"tool_use",id:t.id,name:t.name,input:t.args}}function*Xn(t){const e=["bash_code_execution_tool_result","input_json_delta","server_tool_use","text_editor_code_execution_tool_result","tool_result","tool_use","web_search_result","web_search_tool_result"],s=["text","text_delta"];for(const n of t){Tn(n)&&(yield Mn(n,qn));const r="cache_control"in n?n.cache_control:void 0;if(n.type==="image_url"){let a;typeof n.image_url=="string"?a=Kt(n.image_url):typeof n.image_url=="object"&&n.image_url!==null&&"url"in n.image_url&&typeof n.image_url.url=="string"&&(a=Kt(n.image_url.url)),a&&(yield{type:"image",source:a,...r?{cache_control:r}:{}})}else{if(jn(n))return n;if(n.type==="document")yield{...n,...r?{cache_control:r}:{}};else if($n(n))yield{type:"thinking",thinking:n.thinking,signature:n.signature,...r?{cache_control:r}:{}};else if(Bn(n))yield{type:"redacted_thinking",data:n.data,...r?{cache_control:r}:{}};else if(Ln(n))yield{type:"search_result",title:n.title,source:n.source,..."cache_control"in n&&n.cache_control?{cache_control:n.cache_control}:{},..."citations"in n&&n.citations?{citations:n.citations}:{},content:n.content};else if(s.find(a=>a===n.type)&&"text"in n)yield{type:"text",text:n.text,...r?{cache_control:r}:{},..."citations"in n&&n.citations?{citations:n.citations}:{}};else if(e.find(a=>a===n.type)){const a={...n};if("index"in a&&delete a.index,a.type==="input_json_delta"&&(a.type="tool_use"),"input"in a&&typeof a.input=="string")try{a.input=JSON.parse(a.input)}catch{a.input={}}yield{...a,...r?{cache_control:r}:{}}}else n.type==="container_upload"&&(yield{...n,...r?{cache_control:r}:{}})}}}function _t(t){const{content:e}=t;return typeof e=="string"?e:Array.from(Xn(e))}function zt(t){const e=Kn(t);let s;e.length>0&&e[0]._getType()==="system"&&(s=t[0].content);const r=(s!==void 0?e.slice(1):e).map(a=>{let i;if(a._getType()==="human")i="user";else if(a._getType()==="ai")i="assistant";else if(a._getType()==="tool")i="user";else throw a._getType()==="system"?new Error("System messages are only permitted as the first passed message."):new Error(`Message type "${a.type}" is not supported.`);if(Bt(a)&&a.response_metadata?.output_version==="v1")return{role:i,content:Jn(a)};if(Bt(a)&&a.tool_calls?.length){if(typeof a.content=="string")return a.content===""?{role:i,content:a.tool_calls.map(Xt)}:{role:i,content:[{type:"text",text:a.content},...a.tool_calls.map(Xt)]};{const{content:u}=a;return!a.tool_calls.every(h=>u.find(p=>(p.type==="tool_use"||p.type==="input_json_delta"||p.type==="server_tool_use")&&p.id===h.id))&&console.warn('The "tool_calls" field on a message is only respected if content is a string.'),{role:i,content:_t(a)}}}else return{role:i,content:_t(a)}});return{messages:zn(r),system:s}}function zn(t){if(!t||t.length<=1)return t;const e=[];let s=t[0];const n=a=>typeof a=="string"?[{type:"text",text:a}]:a,r=a=>a.role!=="user"||typeof a.content=="string"?!1:Array.isArray(a.content)&&a.content.every(i=>i.type==="tool_result");for(let a=1;a<t.length;a+=1){const i=t[a];r(s)&&r(i)?s={...s,content:[...n(s.content),...n(i.content)]}:(e.push(s),s=i)}return e.push(s),e}function Vn(t,e){const s={model_provider:"anthropic"};if(t.type==="message_start"){const{content:n,usage:r,...a}=t.message,i={};for(const[_,d]of Object.entries(a))d!=null&&(i[_]=d);const{input_tokens:u,output_tokens:c,...h}=r??{},p=u+h.cache_creation_input_tokens+h.cache_read_input_tokens,f={input_tokens:p,output_tokens:c,total_tokens:p+c,input_token_details:{cache_creation:h.cache_creation_input_tokens,cache_read:h.cache_read_input_tokens}};return{chunk:new N({content:e.coerceContentToString?"":[],additional_kwargs:i,usage_metadata:e.streamUsage?f:void 0,response_metadata:{...s,usage:{...h}},id:t.message.id})}}else if(t.type==="message_delta"){const n={input_tokens:0,output_tokens:t.usage.output_tokens,total_tokens:t.usage.output_tokens,input_token_details:{cache_creation:t.usage.cache_creation_input_tokens,cache_read:t.usage.cache_read_input_tokens}},r="context_management"in t.delta?{context_management:t.delta.context_management}:void 0;return{chunk:new N({content:e.coerceContentToString?"":[],response_metadata:r,additional_kwargs:{...t.delta},usage_metadata:e.streamUsage?n:void 0})}}else if(t.type==="content_block_start"&&["tool_use","document","server_tool_use","web_search_tool_result"].includes(t.content_block.type)){const n=t.content_block;let r;return n.type==="tool_use"?r=[{id:n.id,index:t.index,name:n.name,args:""}]:r=[],{chunk:new N({content:e.coerceContentToString?"":[{index:t.index,...t.content_block,input:n.type==="server_tool_use"||n.type==="tool_use"?"":void 0}],response_metadata:s,additional_kwargs:{},tool_call_chunks:r})}}else if(t.type==="content_block_delta"&&["text_delta","citations_delta","thinking_delta","signature_delta"].includes(t.delta.type)){if(e.coerceContentToString&&"text"in t.delta)return{chunk:new N({content:t.delta.text})};{const n=t.delta;return"citation"in n&&(n.citations=[n.citation],delete n.citation),n.type==="thinking_delta"||n.type==="signature_delta"?{chunk:new N({content:[{index:t.index,...n,type:"thinking"}],response_metadata:s})}:{chunk:new N({content:[{index:t.index,...n,type:"text"}],response_metadata:s})}}}else{if(t.type==="content_block_delta"&&t.delta.type==="input_json_delta")return{chunk:new N({content:e.coerceContentToString?"":[{index:t.index,input:t.delta.partial_json,type:t.delta.type}],response_metadata:s,additional_kwargs:{},tool_call_chunks:[{index:t.index,args:t.delta.partial_json}]})};if(t.type==="content_block_start"&&t.content_block.type==="text"){const n=t.content_block?.text;if(n!==void 0)return{chunk:new N({content:e.coerceContentToString?n:[{index:t.index,...t.content_block}],response_metadata:s,additional_kwargs:{}})}}else{if(t.type==="content_block_start"&&t.content_block.type==="redacted_thinking")return{chunk:new N({content:e.coerceContentToString?"":[{index:t.index,...t.content_block}],response_metadata:s})};if(t.type==="content_block_start"&&t.content_block.type==="thinking"){const n=t.content_block.thinking;return{chunk:new N({content:e.coerceContentToString?n:[{index:t.index,...t.content_block}],response_metadata:s})}}}}return null}function Qn(t,e){const s={...e,model_provider:"anthropic"},n=e.usage,r=n!=null?{input_tokens:n.input_tokens??0,output_tokens:n.output_tokens??0,total_tokens:(n.input_tokens??0)+(n.output_tokens??0),input_token_details:{cache_creation:n.cache_creation_input_tokens,cache_read:n.cache_read_input_tokens}}:void 0;if(t.length===1&&t[0].type==="text")return[{text:t[0].text,message:new jt({content:t[0].text,additional_kwargs:e,usage_metadata:r,response_metadata:s,id:e.id})}];{const a=Ss(t);return[{text:"",message:new jt({content:t,additional_kwargs:e,tool_calls:a,usage_metadata:r,response_metadata:s,id:e.id})}]}}function Ce(t,e){return t.lc_error_code=e,t.message=`${t.message}
6
6
 
7
7
  Troubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${e}/
8
8
  `,t}function Vt(t){let e;return t.status===400&&t.message.includes("tool")?e=Ce(t,"INVALID_TOOL_RESULTS"):t.status===401?e=Ce(t,"MODEL_AUTHENTICATION"):t.status===404?e=Ce(t,"MODEL_NOT_FOUND"):t.status===429?e=Ce(t,"MODEL_RATE_LIMIT"):e=t,e}const Yn={"claude-opus-4-0":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-3-5-sonnet-20241022":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-opus-4-1":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-haiku-4-5":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:64e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-3-5-sonnet-20240620":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-3-5-haiku-latest":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-3-opus-20240229":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:4096,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-sonnet-4-5":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:64e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-sonnet-4-5-20250929":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:64e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-sonnet-4-20250514":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:64e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-opus-4-20250514":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-3-5-haiku-20241022":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-3-haiku-20240307":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:4096,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-3-7-sonnet-20250219":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:64e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-3-7-sonnet-latest":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:64e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-sonnet-4-0":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:64e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-opus-4-1-20250805":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-3-sonnet-20240229":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:4096,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-haiku-4-5-20251001":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:64e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0}};var Gn=Yn;function l(t,e,s,n,r){if(typeof e=="function"?t!==e||!0:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(t,s),s}function o(t,e,s,n){if(s==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return s==="m"?n:s==="a"?n.call(t):n?n.value:e.get(t)}let ks=function(){const{crypto:t}=globalThis;if(t?.randomUUID)return ks=t.randomUUID.bind(t),t.randomUUID();const e=new Uint8Array(1),s=t?()=>t.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,n=>(+n^s()&15>>+n/4).toString(16))};function Oe(t){return typeof t=="object"&&t!==null&&("name"in t&&t.name==="AbortError"||"message"in t&&String(t.message).includes("FetchRequestCanceledException"))}const yt=t=>{if(t instanceof Error)return t;if(typeof t=="object"&&t!==null){try{if(Object.prototype.toString.call(t)==="[object Error]"){const e=new Error(t.message,t.cause?{cause:t.cause}:{});return t.stack&&(e.stack=t.stack),t.cause&&!e.cause&&(e.cause=t.cause),t.name&&(e.name=t.name),e}}catch{}try{return new Error(JSON.stringify(t))}catch{}}return new Error(t)};class m extends Error{}class T extends m{constructor(e,s,n,r){super(`${T.makeMessage(e,s,n)}`),this.status=e,this.headers=r,this.requestID=r?.get("request-id"),this.error=s}static makeMessage(e,s,n){const r=s?.message?typeof s.message=="string"?s.message:JSON.stringify(s.message):s?JSON.stringify(s):n;return e&&r?`${e} ${r}`:e?`${e} status code (no body)`:r||"(no status code or body)"}static generate(e,s,n,r){if(!e||!r)return new et({message:n,cause:yt(s)});const a=s;return e===400?new Ms(e,a,n,r):e===401?new Os(e,a,n,r):e===403?new vs(e,a,n,r):e===404?new Is(e,a,n,r):e===409?new Rs(e,a,n,r):e===422?new As(e,a,n,r):e===429?new Cs(e,a,n,r):e>=500?new Ps(e,a,n,r):new T(e,a,n,r)}}class U extends T{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class et extends T{constructor({message:e,cause:s}){super(void 0,void 0,e||"Connection error.",void 0),s&&(this.cause=s)}}class Ts extends et{constructor({message:e}={}){super({message:e??"Request timed out."})}}class Ms extends T{}class Os extends T{}class vs extends T{}class Is extends T{}class Rs extends T{}class As extends T{}class Cs extends T{}class Ps extends T{}const Zn=/^[a-z][a-z0-9+.-]*:/i,er=t=>Zn.test(t);let wt=t=>(wt=Array.isArray,wt(t)),Qt=wt;function bt(t){return typeof t!="object"?{}:t??{}}function tr(t){if(!t)return!0;for(const e in t)return!1;return!0}function sr(t,e){return Object.prototype.hasOwnProperty.call(t,e)}const nr=(t,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new m(`${t} must be an integer`);if(e<0)throw new m(`${t} must be a positive integer`);return e},Es=t=>{try{return JSON.parse(t)}catch{return}},O=(t,e)=>{const s=t[e];return delete t[e],s},rr=t=>new Promise(e=>setTimeout(e,t)),se="0.71.2",ar=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function ir(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}const or=()=>{const t=ir();if(t==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":se,"X-Stainless-OS":Gt(Deno.build.os),"X-Stainless-Arch":Yt(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":se,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(t==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":se,"X-Stainless-OS":Gt(globalThis.process.platform??"unknown"),"X-Stainless-Arch":Yt(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};const e=ur();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":se,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":se,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function ur(){if(typeof navigator>"u"||!navigator)return null;const t=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(const{key:e,pattern:s}of t){const n=s.exec(navigator.userAgent);if(n){const r=n[1]||0,a=n[2]||0,i=n[3]||0;return{browser:e,version:`${r}.${a}.${i}`}}}return null}const Yt=t=>t==="x32"?"x32":t==="x86_64"||t==="x64"?"x64":t==="arm"?"arm":t==="aarch64"||t==="arm64"?"arm64":t?`other:${t}`:"unknown",Gt=t=>(t=t.toLowerCase(),t.includes("ios")?"iOS":t==="android"?"Android":t==="darwin"?"MacOS":t==="win32"?"Windows":t==="freebsd"?"FreeBSD":t==="openbsd"?"OpenBSD":t==="linux"?"Linux":t?`Other:${t}`:"Unknown");let Zt;const cr=()=>Zt??(Zt=or());function lr(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Anthropic({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function Ns(...t){const e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...t)}function Us(t){let e=Symbol.asyncIterator in t?t[Symbol.asyncIterator]():t[Symbol.iterator]();return Ns({start(){},async pull(s){const{done:n,value:r}=await e.next();n?s.close():s.enqueue(r)},async cancel(){await e.return?.()}})}function Ot(t){if(t[Symbol.asyncIterator])return t;const e=t.getReader();return{async next(){try{const s=await e.read();return s?.done&&e.releaseLock(),s}catch(s){throw e.releaseLock(),s}},async return(){const s=e.cancel();return e.releaseLock(),await s,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function dr(t){if(t===null||typeof t!="object")return;if(t[Symbol.asyncIterator]){await t[Symbol.asyncIterator]().return?.();return}const e=t.getReader(),s=e.cancel();e.releaseLock(),await s}const hr=({headers:t,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});function pr(t){let e=0;for(const r of t)e+=r.length;const s=new Uint8Array(e);let n=0;for(const r of t)s.set(r,n),n+=r.length;return s}let es;function vt(t){let e;return(es??(e=new globalThis.TextEncoder,es=e.encode.bind(e)))(t)}let ts;function ss(t){let e;return(ts??(e=new globalThis.TextDecoder,ts=e.decode.bind(e)))(t)}var R,A;class ve{constructor(){R.set(this,void 0),A.set(this,void 0),l(this,R,new Uint8Array),l(this,A,null)}decode(e){if(e==null)return[];const s=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?vt(e):e;l(this,R,pr([o(this,R,"f"),s]));const n=[];let r;for(;(r=fr(o(this,R,"f"),o(this,A,"f")))!=null;){if(r.carriage&&o(this,A,"f")==null){l(this,A,r.index);continue}if(o(this,A,"f")!=null&&(r.index!==o(this,A,"f")+1||r.carriage)){n.push(ss(o(this,R,"f").subarray(0,o(this,A,"f")-1))),l(this,R,o(this,R,"f").subarray(o(this,A,"f"))),l(this,A,null);continue}const a=o(this,A,"f")!==null?r.preceding-1:r.preceding,i=ss(o(this,R,"f").subarray(0,a));n.push(i),l(this,R,o(this,R,"f").subarray(r.index)),l(this,A,null)}return n}flush(){return o(this,R,"f").length?this.decode(`
@@ -46,4 +46,4 @@ you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
46
46
  new Anthropic({ apiKey, dangerouslyAllowBrowser: true });
47
47
  `);this.baseURL=a.baseURL,this.timeout=a.timeout??Ct.DEFAULT_TIMEOUT,this.logger=a.logger??console;const i="warn";this.logLevel=i,this.logLevel=ns(a.logLevel,"ClientOptions.logLevel",this)??ns(Xe("ANTHROPIC_LOG"),"process.env['ANTHROPIC_LOG']",this)??i,this.fetchOptions=a.fetchOptions,this.maxRetries=a.maxRetries??2,this.fetch=a.fetch??lr(),l(this,Ve,hr),this._options=a,this.apiKey=typeof s=="string"?s:null,this.authToken=n}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,authToken:this.authToken,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:s}){if(!(e.get("x-api-key")||e.get("authorization"))&&!(this.apiKey&&e.get("x-api-key"))&&!s.has("x-api-key")&&!(this.authToken&&e.get("authorization"))&&!s.has("authorization"))throw new Error('Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted')}async authHeaders(e){return g([await this.apiKeyAuth(e),await this.bearerAuth(e)])}async apiKeyAuth(e){if(this.apiKey!=null)return g([{"X-Api-Key":this.apiKey}])}async bearerAuth(e){if(this.authToken!=null)return g([{Authorization:`Bearer ${this.authToken}`}])}stringifyQuery(e){return Object.entries(e).filter(([s,n])=>typeof n<"u").map(([s,n])=>{if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")return`${encodeURIComponent(s)}=${encodeURIComponent(n)}`;if(n===null)return`${encodeURIComponent(s)}=`;throw new m(`Cannot stringify type ${typeof n}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}getUserAgent(){return`${this.constructor.name}/JS ${se}`}defaultIdempotencyKey(){return`stainless-node-retry-${ks()}`}makeStatusError(e,s,n,r){return T.generate(e,s,n,r)}buildURL(e,s,n){const r=!o(this,Tt,"m",sn).call(this)&&n||this.baseURL,a=er(e)?new URL(e):new URL(r+(r.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),i=this.defaultQuery();return tr(i)||(s={...i,...s}),typeof s=="object"&&s&&!Array.isArray(s)&&(a.search=this.stringifyQuery(s)),a.toString()}_calculateNonstreamingTimeout(e){if(3600*e/128e3>600)throw new m("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details");return 600*1e3}async prepareOptions(e){}async prepareRequest(e,{url:s,options:n}){}get(e,s){return this.methodRequest("get",e,s)}post(e,s){return this.methodRequest("post",e,s)}patch(e,s){return this.methodRequest("patch",e,s)}put(e,s){return this.methodRequest("put",e,s)}delete(e,s){return this.methodRequest("delete",e,s)}methodRequest(e,s,n){return this.request(Promise.resolve(n).then(r=>({method:e,path:s,...r})))}request(e,s=null){return new tt(this,this.makeRequest(e,s,void 0))}async makeRequest(e,s,n){const r=await e,a=r.maxRetries??this.maxRetries;s==null&&(s=a),await this.prepareOptions(r);const{req:i,url:u,timeout:c}=await this.buildRequest(r,{retryCount:a-s});await this.prepareRequest(i,{url:u,options:r});const h="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),p=n===void 0?"":`, retryOf: ${n}`,f=Date.now();if(M(this).debug(`[${h}] sending request`,Y({retryOfRequestLogID:n,method:r.method,url:u,options:r,headers:i.headers})),r.signal?.aborted)throw new U;const _=new AbortController,d=await this.fetchWithTimeout(u,i,c,_).catch(yt),v=Date.now();if(d instanceof globalThis.Error){const q=`retrying, ${s} attempts remaining`;if(r.signal?.aborted)throw new U;const L=Oe(d)||/timed? ?out/i.test(String(d)+("cause"in d?String(d.cause):""));if(s)return M(this).info(`[${h}] connection ${L?"timed out":"failed"} - ${q}`),M(this).debug(`[${h}] connection ${L?"timed out":"failed"} (${q})`,Y({retryOfRequestLogID:n,url:u,durationMs:v-f,message:d.message})),this.retryRequest(r,s,n??h);throw M(this).info(`[${h}] connection ${L?"timed out":"failed"} - error; no more retries left`),M(this).debug(`[${h}] connection ${L?"timed out":"failed"} (error; no more retries left)`,Y({retryOfRequestLogID:n,url:u,durationMs:v-f,message:d.message})),L?new Ts:new et({cause:d})}const X=[...d.headers.entries()].filter(([q])=>q==="request-id").map(([q,L])=>", "+q+": "+JSON.stringify(L)).join(""),rt=`[${h}${p}${X}] ${i.method} ${u} ${d.ok?"succeeded":"failed"} with status ${d.status} in ${v-f}ms`;if(!d.ok){const q=await this.shouldRetry(d);if(s&&q){const Ae=`retrying, ${s} attempts remaining`;return await dr(d.body),M(this).info(`${rt} - ${Ae}`),M(this).debug(`[${h}] response error (${Ae})`,Y({retryOfRequestLogID:n,url:d.url,status:d.status,headers:d.headers,durationMs:v-f})),this.retryRequest(r,s,n??h,d.headers)}const L=q?"error; no more retries left":"error; not retryable";M(this).info(`${rt} - ${L}`);const Pt=await d.text().catch(Ae=>yt(Ae).message),Et=Es(Pt),Nt=Et?void 0:Pt;throw M(this).debug(`[${h}] response error (${L})`,Y({retryOfRequestLogID:n,url:d.url,status:d.status,headers:d.headers,message:Nt,durationMs:Date.now()-f})),this.makeStatusError(d.status,Et,Nt,d.headers)}return M(this).info(rt),M(this).debug(`[${h}] response start`,Y({retryOfRequestLogID:n,url:d.url,status:d.status,headers:d.headers,durationMs:v-f})),{response:d,options:r,controller:_,requestLogID:h,retryOfRequestLogID:n,startTime:f}}getAPIList(e,s,n){return this.requestAPIList(s,{method:"get",path:e,...n})}requestAPIList(e,s){const n=this.makeRequest(s,null,void 0);return new xr(this,n,e)}async fetchWithTimeout(e,s,n,r){const{signal:a,method:i,...u}=s||{};a&&a.addEventListener("abort",()=>r.abort());const c=setTimeout(()=>r.abort(),n),h=globalThis.ReadableStream&&u.body instanceof globalThis.ReadableStream||typeof u.body=="object"&&u.body!==null&&Symbol.asyncIterator in u.body,p={signal:r.signal,...h?{duplex:"half"}:{},method:"GET",...u};i&&(p.method=i.toUpperCase());try{return await this.fetch.call(void 0,e,p)}finally{clearTimeout(c)}}async shouldRetry(e){const s=e.headers.get("x-should-retry");return s==="true"?!0:s==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,s,n,r){let a;const i=r?.get("retry-after-ms");if(i){const c=parseFloat(i);Number.isNaN(c)||(a=c)}const u=r?.get("retry-after");if(u&&!a){const c=parseFloat(u);Number.isNaN(c)?a=Date.parse(u)-Date.now():a=c*1e3}if(!(a&&0<=a&&a<60*1e3)){const c=e.maxRetries??this.maxRetries;a=this.calculateDefaultRetryTimeoutMillis(s,c)}return await rr(a),this.makeRequest(e,s-1,n)}calculateDefaultRetryTimeoutMillis(e,s){const a=s-e,i=Math.min(.5*Math.pow(2,a),8),u=1-Math.random()*.25;return i*u*1e3}calculateNonstreamingTimeout(e,s){if(36e5*e/128e3>6e5||s!=null&&e>s)throw new m("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#long-requests for more details");return 6e5}async buildRequest(e,{retryCount:s=0}={}){const n={...e},{method:r,path:a,query:i,defaultBaseURL:u}=n,c=this.buildURL(a,i,u);"timeout"in n&&nr("timeout",n.timeout),n.timeout=n.timeout??this.timeout;const{bodyHeaders:h,body:p}=this.buildBody({options:n}),f=await this.buildHeaders({options:e,method:r,bodyHeaders:h,retryCount:s});return{req:{method:r,headers:f,...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&p instanceof globalThis.ReadableStream&&{duplex:"half"},...p&&{body:p},...this.fetchOptions??{},...n.fetchOptions??{}},url:c,timeout:n.timeout}}async buildHeaders({options:e,method:s,bodyHeaders:n,retryCount:r}){let a={};this.idempotencyHeader&&s!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),a[this.idempotencyHeader]=e.idempotencyKey);const i=g([a,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(r),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...cr(),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":"true"}:void 0,"anthropic-version":"2023-06-01"},await this.authHeaders(e),this._options.defaultHeaders,n,e.headers]);return this.validateHeaders(i),i.values}buildBody({options:{body:e,headers:s}}){if(!e)return{bodyHeaders:void 0,body:void 0};const n=g([s]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&n.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:Us(e)}:o(this,Ve,"f").call(this,{body:e,headers:n})}}Ct=x,Ve=new WeakMap,Tt=new WeakSet,sn=function(){return this.baseURL!=="https://api.anthropic.com"};x.Anthropic=Ct;x.HUMAN_PROMPT=jr;x.AI_PROMPT=qr;x.DEFAULT_TIMEOUT=6e5;x.AnthropicError=m;x.APIError=T;x.APIConnectionError=et;x.APIConnectionTimeoutError=Ts;x.APIUserAbortError=U;x.NotFoundError=Is;x.ConflictError=Rs;x.RateLimitError=Cs;x.BadRequestError=Ms;x.AuthenticationError=Os;x.InternalServerError=Ps;x.PermissionDeniedError=vs;x.UnprocessableEntityError=As;x.toFile=vr;class Re extends x{constructor(){super(...arguments),this.completions=new Zs(this),this.messages=new At(this),this.models=new tn(this),this.beta=new ae(this)}}Re.Completions=Zs;Re.Messages=At;Re.Models=tn;Re.Beta=ae;const Wr=new Set(["date-time","time","date","duration","email","hostname","uri","ipv4","ipv6","uuid"]);function Dr(t){return JSON.parse(JSON.stringify(t))}function Fr(t){const e=Dr(t);return G(e)}function G(t){const e={},s=O(t,"$ref");if(s!==void 0)return e.$ref=s,e;const n=O(t,"$defs");if(n!==void 0){const p={};e.$defs=p;for(const[f,_]of Object.entries(n))p[f]=G(_)}const r=O(t,"type"),a=O(t,"anyOf"),i=O(t,"oneOf"),u=O(t,"allOf");if(Array.isArray(a))e.anyOf=a.map(p=>G(p));else if(Array.isArray(i))e.anyOf=i.map(p=>G(p));else if(Array.isArray(u))e.allOf=u.map(p=>G(p));else{if(r===void 0)throw new Error("JSON schema must have a type defined if anyOf/oneOf/allOf are not used");e.type=r}const c=O(t,"description");c!==void 0&&(e.description=c);const h=O(t,"title");if(h!==void 0&&(e.title=h),r==="object"){const p=O(t,"properties")||{};e.properties=Object.fromEntries(Object.entries(p).map(([_,d])=>[_,G(d)])),O(t,"additionalProperties"),e.additionalProperties=!1;const f=O(t,"required");f!==void 0&&(e.required=f)}else if(r==="string"){const p=O(t,"format");p!==void 0&&Wr.has(p)?e.format=p:p!==void 0&&(t.format=p)}else if(r==="array"){const p=O(t,"items");p!==void 0&&(e.items=G(p));const f=O(t,"minItems");f!==void 0&&(f===0||f===1)?e.minItems=f:f!==void 0&&(t.minItems=f)}if(Object.keys(t).length>0){const p=e.description;e.description=(p?p+`
48
48
 
49
- `:"")+"{"+Object.entries(t).map(([f,_])=>`${f}: ${JSON.stringify(_)}`).join(", ")+"}"}return e}const Hr={"claude-opus-4-1":8192,"claude-opus-4":8192,"claude-sonnet-4":8192,"claude-sonnet-3-7-sonnet":8192,"claude-3-5-sonnet":4096,"claude-3-5-haiku":4096,"claude-3-haiku":2048},bs=2048;function Jr(t){return t?Object.entries(Hr).find(([s])=>t.startsWith(s))?.[1]??bs:bs}function Kr(t){return!!(t.tools&&t.tools.length>0)}function Xr(t){for(const e of t.messages??[])if(typeof e.content!="string"){for(const s of e.content??[])if(typeof s=="object"&&s!=null&&s.type==="document"&&typeof s.citations=="object"&&s.citations?.enabled)return!0}return!1}function zr(t){return!!(t.thinking&&t.thinking.type==="enabled")}function Vr(t){return"input_schema"in t}function Qr(t){const e=["text_editor_","computer_","bash_","web_search_","web_fetch_","str_replace_editor_","str_replace_based_edit_tool_","code_execution_","memory_","tool_search_","mcp_toolset"];return typeof t=="object"&&t!==null&&"type"in t&&("name"in t||"mcp_server_name"in t)&&typeof t.type=="string"&&e.some(s=>typeof t.type=="string"&&t.type.startsWith(s))}function Yr(t,e,...s){return Array.from(new Set([...t??[],...e??[],...s.flatMap(n=>Array.from(n))]))}function Gr(t){if(typeof t.content=="string")return t.content;if(Array.isArray(t.content)&&t.content.length>=1&&"input"in t.content[0])return typeof t.content[0].input=="string"?t.content[0].input:JSON.stringify(t.content[0].input);if(Array.isArray(t.content)&&t.content.length>=1&&"text"in t.content[0]&&typeof t.content[0].text=="string")return t.content[0].text}var Zr=class extends bn{static lc_name(){return"ChatAnthropic"}get lc_secrets(){return{anthropicApiKey:"ANTHROPIC_API_KEY",apiKey:"ANTHROPIC_API_KEY"}}get lc_aliases(){return{modelName:"model"}}lc_serializable=!0;anthropicApiKey;apiKey;apiUrl;temperature;topK;topP;maxTokens;modelName="claude-3-5-sonnet-latest";model="claude-3-5-sonnet-latest";invocationKwargs;stopSequences;streaming=!1;clientOptions;thinking={type:"disabled"};contextManagement;batchClient;streamingClient;streamUsage=!0;betas;createClient;constructor(t){if(super(t??{}),this.anthropicApiKey=t?.apiKey??t?.anthropicApiKey??vn("ANTHROPIC_API_KEY"),!this.anthropicApiKey&&!t?.createClient)throw new Error("Anthropic API key not found");this.clientOptions=t?.clientOptions??{},this.apiKey=this.anthropicApiKey,this.apiUrl=t?.anthropicApiUrl,this.modelName=t?.model??t?.modelName??this.model,this.model=this.modelName,this.invocationKwargs=t?.invocationKwargs??{},this.topP=t?.topP??this.topP,this.temperature=t?.temperature??this.temperature,this.topK=t?.topK??this.topK,this.maxTokens=t?.maxTokens??Jr(this.model),this.stopSequences=t?.stopSequences??this.stopSequences,this.streaming=t?.streaming??!1,this.streamUsage=t?.streamUsage??this.streamUsage,this.thinking=t?.thinking??this.thinking,this.contextManagement=t?.contextManagement??this.contextManagement,this.betas=t?.betas??this.betas,this.createClient=t?.createClient??(e=>new Re(e))}getLsParams(t){const e=this.invocationParams(t);return{ls_provider:"anthropic",ls_model_name:this.model,ls_model_type:"chat",ls_temperature:e.temperature??void 0,ls_max_tokens:e.max_tokens??void 0,ls_stop:t.stop}}formatStructuredToolToAnthropic(t){if(!(!t||!t.length))return t.map(e=>{if($t(e)&&e.extras?.providerToolDefinition)return e.extras.providerToolDefinition;if(Qr(e)||Vr(e))return e;if(xn(e))return{name:e.function.name,description:e.function.description,input_schema:e.function.parameters};if($t(e))return{name:e.name,description:e.description,input_schema:at(e.schema)?ie(e.schema):e.schema,...e.extras?Un.parse(e.extras):{}};throw new Error(`Unknown tool type passed to ChatAnthropic: ${JSON.stringify(e,null,2)}`)})}bindTools(t,e){return this.withConfig({tools:this.formatStructuredToolToAnthropic(t),...e})}invocationParams(t){const e=Nn(t?.tool_choice),s=t?.tools?.reduce((r,a)=>{if(typeof a=="object"&&"type"in a&&a.type in Ht){const i=Ht[a.type];if(!r.includes(i))return[...r,i]}return r},[]),n={model:this.model,stop_sequences:t?.stop??this.stopSequences,stream:this.streaming,max_tokens:this.maxTokens,tools:this.formatStructuredToolToAnthropic(t?.tools),tool_choice:e,thinking:this.thinking,context_management:this.contextManagement,...this.invocationKwargs,container:t?.container,betas:Yr(this.betas,t?.betas,s??[]),output_format:t?.output_format,mcp_servers:t?.mcp_servers};if(this.thinking.type==="enabled"){if(this.topP!==void 0&&this.topK!==-1)throw new Error("topK is not supported when thinking is enabled");if(this.temperature!==void 0&&this.temperature!==1)throw new Error("temperature is not supported when thinking is enabled")}else n.temperature=this.temperature,n.top_k=this.topK,n.top_p=this.topP;return n}_identifyingParams(){return{model_name:this.model,...this.invocationParams()}}identifyingParams(){return{model_name:this.model,...this.invocationParams()}}async*_streamResponseChunks(t,e,s){const n=this.invocationParams(e),r=zt(t),a={...n,...r,stream:!0},i=!Kr(a)&&!Xr(a)&&!zr(a),u=await this.createStreamWithRetry(a,{headers:e.headers});for await(const c of u){if(e.signal?.aborted)throw u.controller.abort(),new Error("AbortError: User aborted the request.");const h=this.streamUsage??e.streamUsage,p=Vn(c,{streamUsage:h,coerceContentToString:i});if(!p)continue;const{chunk:f}=p,_=Gr(f),d=new In({message:new N({content:f.content,additional_kwargs:f.additional_kwargs,tool_call_chunks:f.tool_call_chunks,usage_metadata:h?f.usage_metadata:void 0,response_metadata:f.response_metadata,id:f.id}),text:_??""});yield d,await s?.handleLLMNewToken(_??"",void 0,void 0,void 0,void 0,{chunk:d})}}async _generateNonStreaming(t,e,s){const n=await this.completionWithRetry({...e,stream:!1,...zt(t)},s),{content:r,...a}=n,i=Qn(r,a),{role:u,type:c,...h}=a;return{generations:i,llmOutput:h}}async _generate(t,e,s){if(this.stopSequences&&e.stop)throw new Error('"stopSequence" parameter found in input and default params');const n=this.invocationParams(e);if(n.stream){let r;const a=this._streamResponseChunks(t,e,s);for await(const i of a)r===void 0?r=i:r=r.concat(i);if(r===void 0)throw new Error("No chunks returned from Anthropic API.");return{generations:[{text:r.text,message:r.message}]}}else return this._generateNonStreaming(t,n,{signal:e.signal,headers:e.headers})}async createStreamWithRetry(t,e){if(!this.streamingClient){const a=this.apiUrl?{baseURL:this.apiUrl}:void 0;this.streamingClient=this.createClient({dangerouslyAllowBrowser:!0,...this.clientOptions,...a,apiKey:this.apiKey,maxRetries:0})}const{betas:s,...n}=t,r=async()=>{try{return t?.betas?.length?await this.streamingClient.beta.messages.create({...n,betas:s,...this.invocationKwargs,stream:!0},e):await this.streamingClient.messages.create({...n,...this.invocationKwargs,stream:!0},e)}catch(a){throw Vt(a)}};return this.caller.call(r)}async completionWithRetry(t,e){if(!this.batchClient){const a=this.apiUrl?{baseURL:this.apiUrl}:void 0;this.batchClient=this.createClient({dangerouslyAllowBrowser:!0,...this.clientOptions,...a,apiKey:this.apiKey,maxRetries:0})}const{betas:s,...n}=t,r=async()=>{try{return t?.betas?.length?await this.batchClient.beta.messages.create({...n,...this.invocationKwargs,betas:s},e):await this.batchClient.messages.create({...n,...this.invocationKwargs},e)}catch(a){throw Vt(a)}};return this.caller.callWithOptions({signal:e.signal??void 0},r)}_llmType(){return"anthropic"}get profile(){return Gn[this.model]??{}}withStructuredOutput(t,e){let s,n;const{schema:r,name:a,includeRaw:i}={...e,schema:t};let u=e?.method??"functionCalling";if(u==="jsonMode"&&(console.warn('"jsonMode" is not supported for Anthropic models. Falling back to "jsonSchema".'),u="jsonSchema"),u==="jsonSchema"){n=at(r)?Sn.fromZodSchema(r):new kn;const f=Fr(ie(r));s=this.withConfig({outputVersion:"v0",output_format:{type:"json_schema",schema:f},betas:["structured-outputs-2025-11-13"],ls_structured_output_format:{kwargs:{method:"json_schema"},schema:f}})}else if(u==="functionCalling"){let f=a??"extract",_;if(at(r)){const d=ie(r);_=[{name:f,description:d.description??"A function available to call.",input_schema:d}],n=new Ft({returnSingle:!0,keyName:f,zodSchema:r})}else{let d;typeof r.name=="string"&&typeof r.description=="string"&&typeof r.input_schema=="object"&&r.input_schema!=null?(d=r,f=r.name):d={name:f,description:r.description??"",input_schema:r},_=[d],n=new Ft({returnSingle:!0,keyName:f})}if(this.thinking?.type==="enabled"){const d="Anthropic structured output relies on forced tool calling, which is not supported when `thinking` is enabled. This method will raise OutputParserException if tool calls are not generated. Consider disabling `thinking` or adjust your prompt to ensure the tool is called.";console.warn(d),s=this.withConfig({outputVersion:"v0",tools:_,ls_structured_output_format:{kwargs:{method:"functionCalling"},schema:ie(r)}});const v=X=>{if(!X.tool_calls||X.tool_calls.length===0)throw new Error(d);return X};s=s.pipe(v)}else s=this.withConfig({outputVersion:"v0",tools:_,tool_choice:{type:"tool",name:f},ls_structured_output_format:{kwargs:{method:"functionCalling"},schema:ie(r)}})}else throw new TypeError(`Unrecognized structured output method '${u}'. Expected 'functionCalling' or 'jsonSchema'`);if(!i)return s.pipe(n).withConfig({runName:"ChatAnthropicStructuredOutput"});const c=Bt.assign({parsed:(f,_)=>n.invoke(f.raw,_)}),h=Bt.assign({parsed:()=>null}),p=c.withFallbacks({fallbacks:[h]});return Rn.from([{raw:s},p]).withConfig({runName:"StructuredOutputRunnable"})}},Sa=class extends Zr{};const ea=y({command:w("view"),path:b()}),ta=y({command:w("create"),path:b(),file_text:b()}),sa=y({command:w("str_replace"),path:b(),old_str:b(),new_str:b()}),na=y({command:w("insert"),path:b(),insert_line:E(),insert_text:b()}),ra=y({command:w("delete"),path:b()}),aa=y({command:w("rename"),old_path:b(),new_path:b()});Ze("command",[ea,ta,sa,na,ra,aa]);const ia=y({command:w("view"),path:b(),view_range:Mt([E(),E()]).optional()}),oa=y({command:w("str_replace"),path:b(),old_str:b(),new_str:b()}),ua=y({command:w("create"),path:b(),file_text:b()}),ca=y({command:w("insert"),path:b(),insert_line:E(),new_str:b()});Ze("command",[ia,oa,ua,ca]);const $=Mt([E(),E()]),nn=y({action:w("screenshot")}),rn=y({action:w("left_click"),coordinate:$}),an=y({action:w("right_click"),coordinate:$}),on=y({action:w("middle_click"),coordinate:$}),un=y({action:w("double_click"),coordinate:$}),cn=y({action:w("triple_click"),coordinate:$}),ln=y({action:w("left_click_drag"),start_coordinate:$,end_coordinate:$}),dn=y({action:w("left_mouse_down"),coordinate:$}),hn=y({action:w("left_mouse_up"),coordinate:$}),pn=y({action:w("scroll"),coordinate:$,scroll_direction:Pn(["up","down","left","right"]),scroll_amount:E()}),fn=y({action:w("type"),text:b()}),mn=y({action:w("key"),key:b()}),gn=y({action:w("mouse_move"),coordinate:$}),_n=y({action:w("hold_key"),key:b()}),yn=y({action:w("wait"),duration:E().optional()}),la=y({action:w("zoom"),region:Mt([E(),E(),E(),E()])});Ze("action",[nn,rn,an,on,un,cn,ln,dn,hn,pn,fn,mn,gn,_n,yn]);Ze("action",[nn,rn,an,on,un,cn,ln,dn,hn,pn,fn,mn,gn,_n,yn,la]);const da=y({command:b().describe("The bash command to run")}),ha=y({restart:w(!0).describe("Set to true to restart the bash session")});En([da,ha]);export{Sa as ChatAnthropic,Zr as ChatAnthropicMessages};
49
+ `:"")+"{"+Object.entries(t).map(([f,_])=>`${f}: ${JSON.stringify(_)}`).join(", ")+"}"}return e}const Hr={"claude-opus-4-1":8192,"claude-opus-4":8192,"claude-sonnet-4":8192,"claude-sonnet-3-7-sonnet":8192,"claude-3-5-sonnet":4096,"claude-3-5-haiku":4096,"claude-3-haiku":2048},bs=2048;function Jr(t){return t?Object.entries(Hr).find(([s])=>t.startsWith(s))?.[1]??bs:bs}function Kr(t){return!!(t.tools&&t.tools.length>0)}function Xr(t){for(const e of t.messages??[])if(typeof e.content!="string"){for(const s of e.content??[])if(typeof s=="object"&&s!=null&&s.type==="document"&&typeof s.citations=="object"&&s.citations?.enabled)return!0}return!1}function zr(t){return!!(t.thinking&&t.thinking.type==="enabled")}function Vr(t){return"input_schema"in t}function Qr(t){const e=["text_editor_","computer_","bash_","web_search_","web_fetch_","str_replace_editor_","str_replace_based_edit_tool_","code_execution_","memory_","tool_search_","mcp_toolset"];return typeof t=="object"&&t!==null&&"type"in t&&("name"in t||"mcp_server_name"in t)&&typeof t.type=="string"&&e.some(s=>typeof t.type=="string"&&t.type.startsWith(s))}function Yr(t,e,...s){return Array.from(new Set([...t??[],...e??[],...s.flatMap(n=>Array.from(n))]))}function Gr(t){if(typeof t.content=="string")return t.content;if(Array.isArray(t.content)&&t.content.length>=1&&"input"in t.content[0])return typeof t.content[0].input=="string"?t.content[0].input:JSON.stringify(t.content[0].input);if(Array.isArray(t.content)&&t.content.length>=1&&"text"in t.content[0]&&typeof t.content[0].text=="string")return t.content[0].text}var Zr=class extends bn{static lc_name(){return"ChatAnthropic"}get lc_secrets(){return{anthropicApiKey:"ANTHROPIC_API_KEY",apiKey:"ANTHROPIC_API_KEY"}}get lc_aliases(){return{modelName:"model"}}lc_serializable=!0;anthropicApiKey;apiKey;apiUrl;temperature;topK;topP;maxTokens;modelName="claude-3-5-sonnet-latest";model="claude-3-5-sonnet-latest";invocationKwargs;stopSequences;streaming=!1;clientOptions;thinking={type:"disabled"};contextManagement;batchClient;streamingClient;streamUsage=!0;betas;createClient;constructor(t){if(super(t??{}),this.anthropicApiKey=t?.apiKey??t?.anthropicApiKey??On("ANTHROPIC_API_KEY"),!this.anthropicApiKey&&!t?.createClient)throw new Error("Anthropic API key not found");this.clientOptions=t?.clientOptions??{},this.apiKey=this.anthropicApiKey,this.apiUrl=t?.anthropicApiUrl,this.modelName=t?.model??t?.modelName??this.model,this.model=this.modelName,this.invocationKwargs=t?.invocationKwargs??{},this.topP=t?.topP??this.topP,this.temperature=t?.temperature??this.temperature,this.topK=t?.topK??this.topK,this.maxTokens=t?.maxTokens??Jr(this.model),this.stopSequences=t?.stopSequences??this.stopSequences,this.streaming=t?.streaming??!1,this.streamUsage=t?.streamUsage??this.streamUsage,this.thinking=t?.thinking??this.thinking,this.contextManagement=t?.contextManagement??this.contextManagement,this.betas=t?.betas??this.betas,this.createClient=t?.createClient??(e=>new Re(e))}getLsParams(t){const e=this.invocationParams(t);return{ls_provider:"anthropic",ls_model_name:this.model,ls_model_type:"chat",ls_temperature:e.temperature??void 0,ls_max_tokens:e.max_tokens??void 0,ls_stop:t.stop}}formatStructuredToolToAnthropic(t){if(!(!t||!t.length))return t.map(e=>{if(Dt(e)&&e.extras?.providerToolDefinition)return e.extras.providerToolDefinition;if(Qr(e)||Vr(e))return e;if(En(e))return{name:e.function.name,description:e.function.description,input_schema:e.function.parameters};if(Dt(e))return{name:e.name,description:e.description,input_schema:at(e.schema)?ie(e.schema):e.schema,...e.extras?Un.parse(e.extras):{}};throw new Error(`Unknown tool type passed to ChatAnthropic: ${JSON.stringify(e,null,2)}`)})}bindTools(t,e){return this.withConfig({tools:this.formatStructuredToolToAnthropic(t),...e})}invocationParams(t){const e=Nn(t?.tool_choice),s=t?.tools?.reduce((r,a)=>{if(typeof a=="object"&&"type"in a&&a.type in Ht){const i=Ht[a.type];if(!r.includes(i))return[...r,i]}return r},[]),n={model:this.model,stop_sequences:t?.stop??this.stopSequences,stream:this.streaming,max_tokens:this.maxTokens,tools:this.formatStructuredToolToAnthropic(t?.tools),tool_choice:e,thinking:this.thinking,context_management:this.contextManagement,...this.invocationKwargs,container:t?.container,betas:Yr(this.betas,t?.betas,s??[]),output_format:t?.output_format,mcp_servers:t?.mcp_servers};if(this.thinking.type==="enabled"){if(this.topP!==void 0&&this.topK!==-1)throw new Error("topK is not supported when thinking is enabled");if(this.temperature!==void 0&&this.temperature!==1)throw new Error("temperature is not supported when thinking is enabled")}else n.temperature=this.temperature,n.top_k=this.topK,n.top_p=this.topP;return n}_identifyingParams(){return{model_name:this.model,...this.invocationParams()}}identifyingParams(){return{model_name:this.model,...this.invocationParams()}}async*_streamResponseChunks(t,e,s){const n=this.invocationParams(e),r=zt(t),a={...n,...r,stream:!0},i=!Kr(a)&&!Xr(a)&&!zr(a),u=await this.createStreamWithRetry(a,{headers:e.headers});for await(const c of u){if(e.signal?.aborted)throw u.controller.abort(),new Error("AbortError: User aborted the request.");const h=this.streamUsage??e.streamUsage,p=Vn(c,{streamUsage:h,coerceContentToString:i});if(!p)continue;const{chunk:f}=p,_=Gr(f),d=new vn({message:new N({content:f.content,additional_kwargs:f.additional_kwargs,tool_call_chunks:f.tool_call_chunks,usage_metadata:h?f.usage_metadata:void 0,response_metadata:f.response_metadata,id:f.id}),text:_??""});yield d,await s?.handleLLMNewToken(_??"",void 0,void 0,void 0,void 0,{chunk:d})}}async _generateNonStreaming(t,e,s){const n=await this.completionWithRetry({...e,stream:!1,...zt(t)},s),{content:r,...a}=n,i=Qn(r,a),{role:u,type:c,...h}=a;return{generations:i,llmOutput:h}}async _generate(t,e,s){if(this.stopSequences&&e.stop)throw new Error('"stopSequence" parameter found in input and default params');const n=this.invocationParams(e);if(n.stream){let r;const a=this._streamResponseChunks(t,e,s);for await(const i of a)r===void 0?r=i:r=r.concat(i);if(r===void 0)throw new Error("No chunks returned from Anthropic API.");return{generations:[{text:r.text,message:r.message}]}}else return this._generateNonStreaming(t,n,{signal:e.signal,headers:e.headers})}async createStreamWithRetry(t,e){if(!this.streamingClient){const a=this.apiUrl?{baseURL:this.apiUrl}:void 0;this.streamingClient=this.createClient({dangerouslyAllowBrowser:!0,...this.clientOptions,...a,apiKey:this.apiKey,maxRetries:0})}const{betas:s,...n}=t,r=async()=>{try{return t?.betas?.length?await this.streamingClient.beta.messages.create({...n,betas:s,...this.invocationKwargs,stream:!0},e):await this.streamingClient.messages.create({...n,...this.invocationKwargs,stream:!0},e)}catch(a){throw Vt(a)}};return this.caller.call(r)}async completionWithRetry(t,e){if(!this.batchClient){const a=this.apiUrl?{baseURL:this.apiUrl}:void 0;this.batchClient=this.createClient({dangerouslyAllowBrowser:!0,...this.clientOptions,...a,apiKey:this.apiKey,maxRetries:0})}const{betas:s,...n}=t,r=async()=>{try{return t?.betas?.length?await this.batchClient.beta.messages.create({...n,...this.invocationKwargs,betas:s},e):await this.batchClient.messages.create({...n,...this.invocationKwargs},e)}catch(a){throw Vt(a)}};return this.caller.callWithOptions({signal:e.signal??void 0},r)}_llmType(){return"anthropic"}get profile(){return Gn[this.model]??{}}withStructuredOutput(t,e){let s,n;const{schema:r,name:a,includeRaw:i}={...e,schema:t};let u=e?.method??"functionCalling";if(u==="jsonMode"&&(console.warn('"jsonMode" is not supported for Anthropic models. Falling back to "jsonSchema".'),u="jsonSchema"),u==="jsonSchema"){n=at(r)?xn.fromZodSchema(r):new Sn;const f=Fr(ie(r));s=this.withConfig({outputVersion:"v0",output_format:{type:"json_schema",schema:f},betas:["structured-outputs-2025-11-13"],ls_structured_output_format:{kwargs:{method:"json_schema"},schema:f}})}else if(u==="functionCalling"){let f=a??"extract",_;if(at(r)){const d=ie(r);_=[{name:f,description:d.description??"A function available to call.",input_schema:d}],n=new Ft({returnSingle:!0,keyName:f,zodSchema:r})}else{let d;typeof r.name=="string"&&typeof r.description=="string"&&typeof r.input_schema=="object"&&r.input_schema!=null?(d=r,f=r.name):d={name:f,description:r.description??"",input_schema:r},_=[d],n=new Ft({returnSingle:!0,keyName:f})}if(this.thinking?.type==="enabled"){const d="Anthropic structured output relies on forced tool calling, which is not supported when `thinking` is enabled. This method will raise OutputParserException if tool calls are not generated. Consider disabling `thinking` or adjust your prompt to ensure the tool is called.";console.warn(d),s=this.withConfig({outputVersion:"v0",tools:_,ls_structured_output_format:{kwargs:{method:"functionCalling"},schema:ie(r)}});const v=X=>{if(!X.tool_calls||X.tool_calls.length===0)throw new Error(d);return X};s=s.pipe(v)}else s=this.withConfig({outputVersion:"v0",tools:_,tool_choice:{type:"tool",name:f},ls_structured_output_format:{kwargs:{method:"functionCalling"},schema:ie(r)}})}else throw new TypeError(`Unrecognized structured output method '${u}'. Expected 'functionCalling' or 'jsonSchema'`);if(!i)return s.pipe(n).withConfig({runName:"ChatAnthropicStructuredOutput"});const c=$t.assign({parsed:(f,_)=>n.invoke(f.raw,_)}),h=$t.assign({parsed:()=>null}),p=c.withFallbacks({fallbacks:[h]});return In.from([{raw:s},p]).withConfig({runName:"StructuredOutputRunnable"})}},ka=class extends Zr{};const ea=y({command:w("view"),path:b()}),ta=y({command:w("create"),path:b(),file_text:b()}),sa=y({command:w("str_replace"),path:b(),old_str:b(),new_str:b()}),na=y({command:w("insert"),path:b(),insert_line:E(),insert_text:b()}),ra=y({command:w("delete"),path:b()}),aa=y({command:w("rename"),old_path:b(),new_path:b()});Ze("command",[ea,ta,sa,na,ra,aa]);const ia=y({command:w("view"),path:b(),view_range:Mt([E(),E()]).optional()}),oa=y({command:w("str_replace"),path:b(),old_str:b(),new_str:b()}),ua=y({command:w("create"),path:b(),file_text:b()}),ca=y({command:w("insert"),path:b(),insert_line:E(),new_str:b()});Ze("command",[ia,oa,ua,ca]);const $=Mt([E(),E()]),nn=y({action:w("screenshot")}),rn=y({action:w("left_click"),coordinate:$}),an=y({action:w("right_click"),coordinate:$}),on=y({action:w("middle_click"),coordinate:$}),un=y({action:w("double_click"),coordinate:$}),cn=y({action:w("triple_click"),coordinate:$}),ln=y({action:w("left_click_drag"),start_coordinate:$,end_coordinate:$}),dn=y({action:w("left_mouse_down"),coordinate:$}),hn=y({action:w("left_mouse_up"),coordinate:$}),pn=y({action:w("scroll"),coordinate:$,scroll_direction:Cn(["up","down","left","right"]),scroll_amount:E()}),fn=y({action:w("type"),text:b()}),mn=y({action:w("key"),key:b()}),gn=y({action:w("mouse_move"),coordinate:$}),_n=y({action:w("hold_key"),key:b()}),yn=y({action:w("wait"),duration:E().optional()}),la=y({action:w("zoom"),region:Mt([E(),E(),E(),E()])});Ze("action",[nn,rn,an,on,un,cn,ln,dn,hn,pn,fn,mn,gn,_n,yn]);Ze("action",[nn,rn,an,on,un,cn,ln,dn,hn,pn,fn,mn,gn,_n,yn,la]);const da=y({command:b().describe("The bash command to run")}),ha=y({restart:w(!0).describe("Set to true to restart the bash session")});Pn([da,ha]);export{ka as ChatAnthropic,Zr as ChatAnthropicMessages};