@mcp-use/inspector 0.4.12-canary.0 → 0.4.12
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/client/assets/__vite-browser-external-DFygW7-s.js +1 -0
- package/dist/client/assets/chunk-VL2OQCWN-B6188h-8.js +8 -0
- package/dist/client/assets/{embeddings-YBqRlE4m.js → embeddings-CmTKipI3.js} +1 -1
- package/dist/client/assets/{index-DbqanY6c.js → index-B2AaM8iX.js} +3 -3
- package/dist/client/assets/index-CvPVR03j.js +4 -0
- package/dist/client/assets/{index-D-_HYYNB.js → index-DI2GdDtn.js} +1 -1
- package/dist/client/assets/index-DRz5BQNA.js +1 -0
- package/dist/client/assets/{index-BPuwotMA.js → index-Dhd81mGH.js} +2 -2
- package/dist/client/assets/index-LZZ02vm2.js +1734 -0
- package/dist/client/assets/{index-zX0NhVAe.js → index-azKdcp4V.js} +2 -2
- package/dist/client/assets/index-x_xzGcAx.js +1 -0
- package/dist/client/assets/{langfuse-LCJ6VJEP-DVie-pDz.js → langfuse-C4HKZ3NL-DdY799py.js} +12 -12
- package/dist/client/assets/path-C9FudP8b.js +1 -0
- package/dist/client/assets/winston-BxLvA24A.js +42 -0
- package/dist/client/index.html +2 -2
- package/package.json +2 -2
- package/dist/client/assets/chunk-VL2OQCWN-DDPfe4wt.js +0 -8
- package/dist/client/assets/index-Ah_aViv6.js +0 -1
- package/dist/client/assets/index-B7oaWPow.js +0 -1775
- package/dist/client/assets/index-DGitogYY.js +0 -4
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import{Langfuse as T}from"./index-x_xzGcAx.js";import{B as I,a as v,A as g,b as y,H as M,C as S,S as w,F as D,T as b}from"./langfuse-C4HKZ3NL-DdY799py.js";import"./index-LZZ02vm2.js";import"./chunk-VL2OQCWN-B6188h-8.js";import"./index-DRz5BQNA.js";import"./__vite-browser-external-DFygW7-s.js";import"./path-C9FudP8b.js";const u="langsmith:hidden";class k extends I{constructor(t){super(),this.name="CallbackHandler",this.rootProvided=!1,this.updateRoot=!1,this.debugEnabled=!1,this.completionStartTimes={},t&&"root"in t?(this.langfuse=t.root.client,this.rootObservationId=t.root.observationId??void 0,this.traceId=t.root.traceId,this.rootProvided=!0,this.updateRoot=t.updateRoot??!1,this.metadata=t.metadata):(this.langfuse=new T({...t,persistence:"memory",sdkIntegration:t?.sdkIntegration??"LANGCHAIN"}),this.sessionId=t?.sessionId,this.userId=t?.userId,this.metadata=t?.metadata,this.tags=t?.tags),this.version=t?.version,this.promptToParentRunMap=new Map,this.traceUpdates=new Map}async flushAsync(){return this.langfuse.flushAsync()}async shutdownAsync(){return this.langfuse.shutdownAsync()}debug(t=!0){this.langfuse.debug(t),this.debugEnabled=t}_log(t){this.debugEnabled&&console.log(t)}async handleNewToken(t,e){return e&&!(e in this.completionStartTimes)&&(this._log(`LLM first streaming token: ${e}`),this.completionStartTimes[e]=new Date),Promise.resolve()}async handleLLMNewToken(t,e,s,i,n,a){return s&&!(s in this.completionStartTimes)&&(this._log(`LLM first streaming token: ${s}`),this.completionStartTimes[s]=new Date),Promise.resolve()}getTraceId(){return this.traceId}getTraceUrl(){return this.traceId?`${this.langfuse.baseUrl}/trace/${this.traceId}`:void 0}getLangchainRunId(){return this.topLevelObservationId}async handleRetrieverError(t,e,s){try{this._log(`Retriever error: ${t} with ID: ${e}`),this.langfuse._updateSpan({id:e,traceId:this.traceId,level:"ERROR",statusMessage:t.toString(),endTime:new Date,version:this.version}),this.updateTrace(e,s,t.toString())}catch(i){this._log(i)}}async handleChainStart(t,e,s,i,n,a,o,h){try{this._log(`Chain start with Id: ${s}`);const d=h??t.id.at(-1)?.toString()??"Langchain Run";this.registerLangfusePrompt(i,a);let r=e;typeof e=="object"&&"input"in e&&Array.isArray(e.input)&&e.input.every(l=>l instanceof v)?r=e.input.map(l=>this.extractChatMessageContent(l)):typeof e=="object"&&"content"in e&&typeof e.content=="string"&&(r=e.content),this.generateTrace(d,s,i,n,a,r),this.langfuse.span({id:s,traceId:this.traceId,parentObservationId:i??this.rootObservationId,name:d,metadata:this.joinTagsAndMetaData(n,a),input:r,version:this.version,level:n&&n.includes(u)?"DEBUG":void 0}),i||this.traceUpdates.set(s,{tags:n,userId:a&&"langfuseUserId"in a&&typeof a.langfuseUserId=="string"?a.langfuseUserId:void 0,sessionId:a&&"langfuseSessionId"in a&&typeof a.langfuseSessionId=="string"?a.langfuseSessionId:void 0})}catch(d){this._log(d)}}registerLangfusePrompt(t,e){e&&"langfusePrompt"in e&&t&&this.promptToParentRunMap.set(t,e.langfusePrompt)}deregisterLangfusePrompt(t){this.promptToParentRunMap.delete(t)}async handleAgentAction(t,e,s){try{this._log(`Agent action with ID: ${e}`),this.langfuse.span({id:e,parentObservationId:s,traceId:this.traceId,endTime:new Date,input:t,version:this.version})}catch(i){this._log(i)}}async handleAgentEnd(t,e,s){try{this._log(`Agent finish with ID: ${e}`),this.langfuse._updateSpan({id:e,traceId:this.traceId,endTime:new Date,output:t,version:this.version}),this.updateTrace(e,s,t)}catch(i){this._log(i)}}async handleChainError(t,e,s){try{this._log(`Chain error: ${t} with ID: ${e}`);const i=this.parseAzureRefusalError(t);this.langfuse._updateSpan({id:e,traceId:this.traceId,level:"ERROR",statusMessage:t.toString()+i,endTime:new Date,version:this.version}),this.updateTrace(e,s,t.toString()+i)}catch(i){this._log(i)}}generateTrace(t,e,s,i,n,a){this.traceId&&!s&&!this.rootProvided&&(this.traceId=void 0,this.topLevelObservationId=void 0);const o={name:t,metadata:this.joinTagsAndMetaData(i,n,this.metadata),userId:this.userId,version:this.version,sessionId:this.sessionId,input:a,tags:this.tags};this.traceId||(this.langfuse.trace({id:e,...o}),this.traceId=e),this.rootProvided&&this.updateRoot&&(this.rootObservationId?this.langfuse._updateSpan({id:this.rootObservationId,traceId:this.traceId,...o}):this.langfuse.trace({id:this.traceId,...o})),this.topLevelObservationId=s?this.topLevelObservationId:e}async handleGenerationStart(t,e,s,i,n,a,o,h){this._log(`Generation start with ID: ${s}`);const d=h??t.id.at(-1)?.toString()??"Langchain Generation";this.generateTrace(d,s,i,a,o,e);const r={},l=n?.invocation_params;for(const[f,c]of Object.entries({temperature:l?.temperature,max_tokens:l?.max_tokens,top_p:l?.top_p,frequency_penalty:l?.frequency_penalty,presence_penalty:l?.presence_penalty,request_timeout:l?.request_timeout}))c!=null&&(r[f]=c);let _;if(n){const f=n.invocation_params.model,c=o&&"ls_model_name"in o?o.ls_model_name:void 0;_=f??c}const m=this.promptToParentRunMap.get(i??"root");m&&i&&this.deregisterLangfusePrompt(i),this.langfuse.generation({id:s,traceId:this.traceId,name:h??t.id.at(-1)?.toString(),metadata:this.joinTagsAndMetaData(a,o),parentObservationId:i??this.rootObservationId,input:e,model:_,modelParameters:r,version:this.version,prompt:m,level:a&&a.includes(u)?"DEBUG":void 0})}async handleChatModelStart(t,e,s,i,n,a,o,h){try{this._log(`Chat model start with ID: ${s}`);const d=e.flatMap(r=>r.map(l=>this.extractChatMessageContent(l)));this.handleGenerationStart(t,d,s,i,n,a,o,h)}catch(d){this._log(d)}}async handleChainEnd(t,e,s){try{this._log(`Chain end with ID: ${e}`);let i=t;typeof t=="object"&&"output"in t&&typeof t.output=="string"&&(i=t.output),this.langfuse._updateSpan({id:e,traceId:this.traceId,output:i,endTime:new Date,version:this.version}),this.updateTrace(e,s,i),this.deregisterLangfusePrompt(e)}catch(i){this._log(i)}}async handleLLMStart(t,e,s,i,n,a,o,h){try{this._log(`LLM start with ID: ${s}`),this.handleGenerationStart(t,e,s,i,n,a,o,h)}catch(d){this._log(d)}}async handleToolStart(t,e,s,i,n,a,o){try{this._log(`Tool start with ID: ${s}`),this.langfuse.span({id:s,parentObservationId:i,traceId:this.traceId,name:o??t.id.at(-1)?.toString(),input:e,metadata:this.joinTagsAndMetaData(n,a),version:this.version,level:n&&n.includes(u)?"DEBUG":void 0})}catch(h){this._log(h)}}async handleRetrieverStart(t,e,s,i,n,a,o){try{this._log(`Retriever start with ID: ${s}`),this.langfuse.span({id:s,parentObservationId:i,traceId:this.traceId,name:o??t.id.at(-1)?.toString(),input:e,metadata:this.joinTagsAndMetaData(n,a),version:this.version,level:n&&n.includes(u)?"DEBUG":void 0})}catch(h){this._log(h)}}async handleRetrieverEnd(t,e,s){try{this._log(`Retriever end with ID: ${e}`),this.langfuse._updateSpan({id:e,traceId:this.traceId,output:t,endTime:new Date,version:this.version}),this.updateTrace(e,s,t)}catch(i){this._log(i)}}async handleToolEnd(t,e,s){try{this._log(`Tool end with ID: ${e}`),this.langfuse._updateSpan({id:e,traceId:this.traceId,output:t,endTime:new Date,version:this.version}),this.updateTrace(e,s,t)}catch(i){this._log(i)}}async handleToolError(t,e,s){try{this._log(`Tool error ${t} with ID: ${e}`),this.langfuse._updateSpan({id:e,traceId:this.traceId,level:"ERROR",statusMessage:t.toString(),endTime:new Date,version:this.version}),this.updateTrace(e,s,t.toString())}catch(i){this._log(i)}}async handleLLMEnd(t,e,s){try{this._log(`LLM end with ID: ${e}`);const i=t.generations[t.generations.length-1][t.generations[t.generations.length-1].length-1],n=this.extractUsageMetadata(i)??t.llmOutput?.tokenUsage,a=this.extractModelNameFromMetadata(i),o={input:n?.input_tokens??("promptTokens"in n?n?.promptTokens:void 0),output:n?.output_tokens??("completionTokens"in n?n?.completionTokens:void 0),total:n?.total_tokens??("totalTokens"in n?n?.totalTokens:void 0)};if(n&&"input_token_details"in n)for(const[d,r]of Object.entries(n.input_token_details??{}))o[`input_${d}`]=r,"input"in o&&typeof r=="number"&&(o.input=Math.max(0,o.input-r));if(n&&"output_token_details"in n)for(const[d,r]of Object.entries(n.output_token_details??{}))o[`output_${d}`]=r,"output"in o&&typeof r=="number"&&(o.output=Math.max(0,o.output-r));const h="message"in i&&i.message instanceof v?this.extractChatMessageContent(i.message):i.text;this.langfuse._updateGeneration({id:e,model:a,traceId:this.traceId,output:h,endTime:new Date,completionStartTime:e in this.completionStartTimes?this.completionStartTimes[e]:void 0,usage:o,usageDetails:o,version:this.version}),e in this.completionStartTimes&&delete this.completionStartTimes[e],this.updateTrace(e,s,h)}catch(i){this._log(i)}}extractUsageMetadata(t){try{return"message"in t&&(t.message instanceof g||t.message instanceof y)?t.message.usage_metadata:void 0}catch(e){this._log(`Error extracting usage metadata: ${e}`);return}}extractModelNameFromMetadata(t){try{return"message"in t&&(t.message instanceof g||t.message instanceof y)?t.message.response_metadata.model_name:void 0}catch{}}extractChatMessageContent(t){let e;return t instanceof M?e={content:t.content,role:"user"}:t instanceof S?e={content:t.content,role:t.role}:t instanceof g?e={content:t.content,role:"assistant"}:t instanceof w?e={content:t.content,role:"system"}:t instanceof D?e={content:t.content,additional_kwargs:t.additional_kwargs,role:t.name}:t instanceof b?e={content:t.content,additional_kwargs:t.additional_kwargs,role:t.name}:t.name?e={role:t.name,content:t.content}:e={content:t.content},t.additional_kwargs.function_call||t.additional_kwargs.tool_calls?{...e,additional_kwargs:t.additional_kwargs}:e}async handleLLMError(t,e,s){try{this._log(`LLM error ${t} with ID: ${e}`);const i=this.parseAzureRefusalError(t);this.langfuse._updateGeneration({id:e,traceId:this.traceId,level:"ERROR",statusMessage:t.toString()+i,endTime:new Date,version:this.version}),this.updateTrace(e,s,t.toString()+i)}catch(i){this._log(i)}}parseAzureRefusalError(t){let e="";if(typeof t=="object"&&"error"in t)try{e=`
|
|
2
|
+
|
|
3
|
+
Error details:
|
|
4
|
+
`+JSON.stringify(t.error,null,2)}catch{}return e}updateTrace(t,e,s){const i=this.traceUpdates.get(t);this.traceUpdates.delete(t),!e&&this.traceId&&this.traceId===t&&this.langfuse.trace({id:this.traceId,output:s,...i}),!e&&this.traceId&&this.rootProvided&&this.updateRoot&&(this.rootObservationId?this.langfuse._updateSpan({id:this.rootObservationId,traceId:this.traceId,output:s}):this.langfuse.trace({id:this.traceId,output:s,...i}))}joinTagsAndMetaData(t,e,s){const i={};return t&&t.length>0&&(i.tags=t),e&&Object.assign(i,e),s&&Object.assign(i,s),this.stripLangfuseKeysFromMetadata(i)}stripLangfuseKeysFromMetadata(t){if(!t)return;const e=["langfusePrompt","langfuseUserId","langfuseSessionId"];return Object.fromEntries(Object.entries(t).filter(([s,i])=>!e.includes(s)))}}const P=async p=>{const{runName:t,item:e,langfuseClient:s,options:i}=p,n={dataset_item_id:e.id,dataset_id:e.datasetId,dataset_run_name:t},a=s.trace();return await e.link(a,t,{description:i?.runDescription,metadata:i?.runMetadata}),{handler:new k({root:a,updateRoot:!0,metadata:n}),trace:a}};export{k as CallbackHandler,T as Langfuse,P as createDatasetItemHandler,k as default};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{s as Oi,v as se,P as Pe,p as Ht,a as Ga,b as Nr,g as he,c as kr,d as Ke,_ as Ci,$ as xi,e as Ni,f as ki,h as Rr,i as ca,j as Ri,k as Pi,t as Va,l as Pr,V as Mi,m as Li,n as Ut,o as $i,T as ji}from"./chunk-VL2OQCWN-DDPfe4wt.js";import{Z as P,a as Za,o as la,s as ua}from"./index-B7oaWPow.js";var Di=Object.defineProperty,F=(e,t)=>{for(var n in t)Di(e,n,{get:t[n],enumerable:!0})};function Ue(e){return typeof e=="object"&&e!==null&&"type"in e&&typeof e.type=="string"&&"source_type"in e&&(e.source_type==="url"||e.source_type==="base64"||e.source_type==="text"||e.source_type==="id")}function da(e){return Ue(e)&&e.source_type==="url"&&"url"in e&&typeof e.url=="string"}function ha(e){return Ue(e)&&e.source_type==="base64"&&"data"in e&&typeof e.data=="string"}function Fi(e){return Ue(e)&&e.source_type==="text"&&"text"in e&&typeof e.text=="string"}function Mr(e){return Ue(e)&&e.source_type==="id"&&"id"in e&&typeof e.id=="string"}function Lr(e){if(Ue(e)){if(e.source_type==="url")return{type:"image_url",image_url:{url:e.url}};if(e.source_type==="base64"){if(!e.mime_type)throw new Error("mime_type key is required for base64 data.");return{type:"image_url",image_url:{url:`data:${e.mime_type};base64,${e.data}`}}}}throw new Error("Unsupported source type. Only 'url' and 'base64' are supported.")}function Ui(e){const t=e.split(";")[0].split("/");if(t.length!==2)throw new Error(`Invalid mime type: "${e}" - does not match type/subtype format.`);const n=t[0].trim(),a=t[1].trim();if(n===""||a==="")throw new Error(`Invalid mime type: "${e}" - type or subtype is empty.`);const r={};for(const s of e.split(";").slice(1)){const i=s.split("=");if(i.length!==2)throw new Error(`Invalid parameter syntax in mime type: "${e}".`);const o=i[0].trim(),c=i[1].trim();if(o==="")throw new Error(`Invalid parameter syntax in mime type: "${e}".`);r[o]=c}return{type:n,subtype:a,parameters:r}}function $n({dataUrl:e,asTypedArray:t=!1}){const n=e.match(/^data:(\w+\/\w+);base64,([A-Za-z0-9+/]+=*)$/);let a;if(n){a=n[1].toLowerCase();const r=t?Uint8Array.from(atob(n[2]),s=>s.charCodeAt(0)):n[2];return{mime_type:a,data:r}}}function Bi(e,t){if(e.type==="text"){if(!t.fromStandardTextBlock)throw new Error(`Converter for ${t.providerName} does not implement \`fromStandardTextBlock\` method.`);return t.fromStandardTextBlock(e)}if(e.type==="image"){if(!t.fromStandardImageBlock)throw new Error(`Converter for ${t.providerName} does not implement \`fromStandardImageBlock\` method.`);return t.fromStandardImageBlock(e)}if(e.type==="audio"){if(!t.fromStandardAudioBlock)throw new Error(`Converter for ${t.providerName} does not implement \`fromStandardAudioBlock\` method.`);return t.fromStandardAudioBlock(e)}if(e.type==="file"){if(!t.fromStandardFileBlock)throw new Error(`Converter for ${t.providerName} does not implement \`fromStandardFileBlock\` method.`);return t.fromStandardFileBlock(e)}throw new Error(`Unable to convert content block type '${e.type}' to provider-specific format: not recognized.`)}function $r(e){return typeof e=="object"&&e!==null&&"type"in e&&"content"in e&&(typeof e.content=="string"||Array.isArray(e.content))}function zi(e,t){return t?.[e]||Oi(e)}function Hi(e,t,n){const a={};for(const r in e)Object.hasOwn(e,r)&&(a[t(r,n)]=e[r]);return a}var Gi={};F(Gi,{Serializable:()=>lt,get_lc_unique_name:()=>pa});function qa(e){return Array.isArray(e)?[...e]:{...e}}function Vi(e,t){const n=qa(e);for(const[a,r]of Object.entries(t)){const[s,...i]=a.split(".").reverse();let o=n;for(const c of i.reverse()){if(o[c]===void 0)break;o[c]=qa(o[c]),o=o[c]}o[s]!==void 0&&(o[s]={lc:1,type:"secret",id:[r]})}return n}function pa(e){const t=Object.getPrototypeOf(e);return typeof e.lc_name=="function"&&(typeof t.lc_name!="function"||e.lc_name()!==t.lc_name())?e.lc_name():e.name}var lt=class jr{lc_serializable=!1;lc_kwargs;static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,pa(this.constructor)]}get lc_secrets(){}get lc_attributes(){}get lc_aliases(){}get lc_serializable_keys(){}constructor(t,...n){this.lc_serializable_keys!==void 0?this.lc_kwargs=Object.fromEntries(Object.entries(t||{}).filter(([a])=>this.lc_serializable_keys?.includes(a))):this.lc_kwargs=t??{}}toJSON(){if(!this.lc_serializable)return this.toJSONNotImplemented();if(this.lc_kwargs instanceof jr||typeof this.lc_kwargs!="object"||Array.isArray(this.lc_kwargs))return this.toJSONNotImplemented();const t={},n={},a=Object.keys(this.lc_kwargs).reduce((r,s)=>(r[s]=s in this?this[s]:this.lc_kwargs[s],r),{});for(let r=Object.getPrototypeOf(this);r;r=Object.getPrototypeOf(r))Object.assign(t,Reflect.get(r,"lc_aliases",this)),Object.assign(n,Reflect.get(r,"lc_secrets",this)),Object.assign(a,Reflect.get(r,"lc_attributes",this));return Object.keys(n).forEach(r=>{let s=this,i=a;const[o,...c]=r.split(".").reverse();for(const l of c.reverse()){if(!(l in s)||s[l]===void 0)return;(!(l in i)||i[l]===void 0)&&(typeof s[l]=="object"&&s[l]!=null?i[l]={}:Array.isArray(s[l])&&(i[l]=[])),s=s[l],i=i[l]}o in s&&s[o]!==void 0&&(i[o]=i[o]||s[o])}),{lc:1,type:"constructor",id:this.lc_id,kwargs:Hi(Object.keys(n).length?Vi(a,n):a,zi,t)}}toJSONNotImplemented(){return{lc:1,type:"not_implemented",id:this.lc_id}}};function C(e,t){return k(e)&&e.type===t}function k(e){return typeof e=="object"&&e!==null}function Ie(e){return Array.isArray(e)}function S(e){return typeof e=="string"}function we(e){return typeof e=="number"}function fa(e){return e instanceof Uint8Array}function Ja(e){try{return JSON.parse(e)}catch{return}}const vt=e=>e();function Zi(e){if(e.type==="char_location"&&S(e.document_title)&&we(e.start_char_index)&&we(e.end_char_index)&&S(e.cited_text)){const{document_title:t,start_char_index:n,end_char_index:a,cited_text:r,...s}=e;return{...s,type:"citation",source:"char",title:t??void 0,startIndex:n,endIndex:a,citedText:r}}if(e.type==="page_location"&&S(e.document_title)&&we(e.start_page_number)&&we(e.end_page_number)&&S(e.cited_text)){const{document_title:t,start_page_number:n,end_page_number:a,cited_text:r,...s}=e;return{...s,type:"citation",source:"page",title:t??void 0,startIndex:n,endIndex:a,citedText:r}}if(e.type==="content_block_location"&&S(e.document_title)&&we(e.start_block_index)&&we(e.end_block_index)&&S(e.cited_text)){const{document_title:t,start_block_index:n,end_block_index:a,cited_text:r,...s}=e;return{...s,type:"citation",source:"block",title:t??void 0,startIndex:n,endIndex:a,citedText:r}}if(e.type==="web_search_result_location"&&S(e.url)&&S(e.title)&&S(e.encrypted_index)&&S(e.cited_text)){const{url:t,title:n,encrypted_index:a,cited_text:r,...s}=e;return{...s,type:"citation",source:"url",url:t,title:n,startIndex:Number(a),endIndex:Number(a),citedText:r}}if(e.type==="search_result_location"&&S(e.source)&&S(e.title)&&we(e.start_block_index)&&we(e.end_block_index)&&S(e.cited_text)){const{source:t,title:n,start_block_index:a,end_block_index:r,cited_text:s,...i}=e;return{...i,type:"citation",source:"search",url:t,title:n??void 0,startIndex:a,endIndex:r,citedText:s}}}function Dr(e){if(C(e,"document")&&k(e.source)&&"type"in e.source){if(e.source.type==="base64"&&S(e.source.media_type)&&S(e.source.data))return{type:"file",mimeType:e.source.media_type,data:e.source.data};if(e.source.type==="url"&&S(e.source.url))return{type:"file",url:e.source.url};if(e.source.type==="file"&&S(e.source.file_id))return{type:"file",fileId:e.source.file_id};if(e.source.type==="text"&&S(e.source.data))return{type:"file",mimeType:String(e.source.media_type??"text/plain"),data:e.source.data}}else if(C(e,"image")&&k(e.source)&&"type"in e.source){if(e.source.type==="base64"&&S(e.source.media_type)&&S(e.source.data))return{type:"image",mimeType:e.source.media_type,data:e.source.data};if(e.source.type==="url"&&S(e.source.url))return{type:"image",url:e.source.url};if(e.source.type==="file"&&S(e.source.file_id))return{type:"image",fileId:e.source.file_id}}}function qi(e){function*t(){for(const n of e){const a=Dr(n);a?yield a:yield n}}return Array.from(t())}function Wa(e){function*t(){const n=typeof e.content=="string"?[{type:"text",text:e.content}]:e.content;for(const a of n){if(C(a,"text")&&S(a.text)){const{text:r,citations:s,...i}=a;if(Ie(s)&&s.length){const o=s.reduce((c,l)=>{const d=Zi(l);return d?[...c,d]:c},[]);yield{...i,type:"text",text:r,annotations:o};continue}else{yield{...i,type:"text",text:r};continue}}else if(C(a,"thinking")&&S(a.thinking)){const{thinking:r,signature:s,...i}=a;yield{...i,type:"reasoning",reasoning:r,signature:s};continue}else if(C(a,"redacted_thinking")){yield{type:"non_standard",value:a};continue}else if(C(a,"tool_use")&&S(a.name)&&S(a.id)){yield{type:"tool_call",id:a.id,name:a.name,args:a.input};continue}else if(C(a,"input_json_delta")){if(Wi(e)&&e.tool_call_chunks?.length){const r=e.tool_call_chunks[0];yield{type:"tool_call_chunk",id:r.id,name:r.name,args:r.args,index:r.index};continue}}else if(C(a,"server_tool_use")&&S(a.name)&&S(a.id)){const{name:r,id:s}=a;if(r==="web_search"){const i=vt(()=>{if(typeof a.input=="string")return a.input;if(k(a.input)&&S(a.input.query))return a.input.query;if(S(a.partial_json)){const o=Ja(a.partial_json);if(o?.query)return o.query}return""});yield{id:s,type:"server_tool_call",name:"web_search",args:{query:i}};continue}else if(a.name==="code_execution"){const i=vt(()=>{if(typeof a.input=="string")return a.input;if(k(a.input)&&S(a.input.code))return a.input.code;if(S(a.partial_json)){const o=Ja(a.partial_json);if(o?.code)return o.code}return""});yield{id:s,type:"server_tool_call",name:"code_execution",args:{code:i}};continue}}else if(C(a,"web_search_tool_result")&&S(a.tool_use_id)&&Ie(a.content)){const{content:r,tool_use_id:s}=a,i=r.reduce((o,c)=>C(c,"web_search_result")?[...o,c.url]:o,[]);yield{type:"server_tool_call_result",name:"web_search",toolCallId:s,status:"success",output:{urls:i}};continue}else if(C(a,"code_execution_tool_result")&&S(a.tool_use_id)&&k(a.content)){yield{type:"server_tool_call_result",name:"code_execution",toolCallId:a.tool_use_id,status:"success",output:a.content};continue}else if(C(a,"mcp_tool_use")){yield{id:a.id,type:"server_tool_call",name:"mcp_tool_use",args:a.input};continue}else if(C(a,"mcp_tool_result")&&S(a.tool_use_id)&&k(a.content)){yield{type:"server_tool_call_result",name:"mcp_tool_use",toolCallId:a.tool_use_id,status:"success",output:a.content};continue}else if(C(a,"container_upload")){yield{type:"server_tool_call",name:"container_upload",args:a.input};continue}else if(C(a,"search_result")){yield{id:a.id,type:"non_standard",value:a};continue}else if(C(a,"tool_result")){yield{id:a.id,type:"non_standard",value:a};continue}else{const r=Dr(a);if(r){yield r;continue}}yield{type:"non_standard",value:a}}}return Array.from(t())}const Ji={translateContent:Wa,translateContentChunk:Wa};function Wi(e){return typeof e?._getType=="function"&&typeof e.concat=="function"&&e._getType()==="ai"}function Ki(e){return da(e)?{type:e.type,mimeType:e.mime_type,url:e.url,metadata:e.metadata}:ha(e)?{type:e.type,mimeType:e.mime_type??"application/octet-stream",data:e.data,metadata:e.metadata}:Mr(e)?{type:e.type,mimeType:e.mime_type,fileId:e.id,metadata:e.metadata}:e}function Yi(e){return e.map(Ki)}function Qi(e){return!!(C(e,"image_url")&&k(e.image_url)||C(e,"input_audio")&&k(e.input_audio)||C(e,"file")&&k(e.file))}function Xi(e){if(C(e,"image_url")&&k(e.image_url)&&S(e.image_url.url)){const t=$n({dataUrl:e.image_url.url});return t?{type:"image",mimeType:t.mime_type,data:t.data}:{type:"image",url:e.image_url.url}}else{if(C(e,"input_audio")&&k(e.input_audio)&&S(e.input_audio.data)&&S(e.input_audio.format))return{type:"audio",data:e.input_audio.data,mimeType:`audio/${e.input_audio.format}`};if(C(e,"file")&&k(e.file)&&S(e.file.data)){const t=$n({dataUrl:e.file.data});if(t)return{type:"file",data:t.data,mimeType:t.mime_type};if(S(e.file.file_id))return{type:"file",fileId:e.file.file_id}}}return e}function eo(e){const t=[];typeof e.content=="string"?t.push({type:"text",text:e.content}):t.push(...ma(e.content));for(const n of e.tool_calls??[])t.push({type:"tool_call",id:n.id,name:n.name,args:n.args});return t}function to(e){const t=[];typeof e.content=="string"?t.push({type:"text",text:e.content}):t.push(...ma(e.content));for(const n of e.tool_calls??[])t.push({type:"tool_call",id:n.id,name:n.name,args:n.args});return t}function ma(e){const t=[];for(const n of e)Qi(n)?t.push(Xi(n)):t.push(n);return t}function no(e){if(e.type==="url_citation"){const{url:t,title:n,start_index:a,end_index:r}=e;return{type:"citation",url:t,title:n,startIndex:a,endIndex:r}}if(e.type==="file_citation"){const{file_id:t,filename:n,index:a}=e;return{type:"citation",title:n,startIndex:a,endIndex:a,fileId:t}}return e}function Fr(e){function*t(){k(e.additional_kwargs?.reasoning)&&Ie(e.additional_kwargs.reasoning.summary)&&(yield{type:"reasoning",reasoning:e.additional_kwargs.reasoning.summary.reduce((r,s)=>k(s)&&S(s.text)?`${r}${s.text}`:r,"")});const n=typeof e.content=="string"?[{type:"text",text:e.content}]:e.content;for(const a of n)if(C(a,"text")){const{text:r,annotations:s,...i}=a;Array.isArray(s)?yield{...i,type:"text",text:String(r),annotations:s.map(no)}:yield{...i,type:"text",text:String(r)}}for(const a of e.tool_calls??[])yield{type:"tool_call",id:a.id,name:a.name,args:a.args};if(k(e.additional_kwargs)&&Ie(e.additional_kwargs.tool_outputs))for(const a of e.additional_kwargs.tool_outputs){if(C(a,"web_search_call")){yield{id:a.id,type:"server_tool_call",name:"web_search",args:{query:a.query}};continue}else if(C(a,"file_search_call")){yield{id:a.id,type:"server_tool_call",name:"file_search",args:{query:a.query}};continue}else if(C(a,"computer_call")){yield{type:"non_standard",value:a};continue}else if(C(a,"code_interpreter_call")){if(S(a.code)&&(yield{id:a.id,type:"server_tool_call",name:"code_interpreter",args:{code:a.code}}),Ie(a.outputs)){const r=vt(()=>{if(a.status!=="in_progress"){if(a.status==="completed")return 0;if(a.status==="incomplete")return 127;if(a.status!=="interpreting"&&a.status==="failed")return 1}});for(const s of a.outputs)if(C(s,"logs")){yield{type:"server_tool_call_result",toolCallId:a.id??"",status:"success",output:{type:"code_interpreter_output",returnCode:r??0,stderr:[0,void 0].includes(r)?void 0:String(s.logs),stdout:[0,void 0].includes(r)?String(s.logs):void 0}};continue}}continue}else if(C(a,"mcp_call")){yield{id:a.id,type:"server_tool_call",name:"mcp_call",args:a.input};continue}else if(C(a,"mcp_list_tools")){yield{id:a.id,type:"server_tool_call",name:"mcp_list_tools",args:a.input};continue}else if(C(a,"mcp_approval_request")){yield{type:"non_standard",value:a};continue}else if(C(a,"image_generation_call")){yield{type:"non_standard",value:a};continue}k(a)&&(yield{type:"non_standard",value:a})}}return Array.from(t())}function ao(e){function*t(){yield*Fr(e);for(const n of e.tool_call_chunks??[])yield{type:"tool_call_chunk",id:n.id,name:n.name,args:n.args}}return Array.from(t())}const ro={translateContent:e=>typeof e.content=="string"?eo(e):Fr(e),translateContentChunk:e=>typeof e.content=="string"?to(e):ao(e)};function so(e,t="pretty"){return t==="pretty"?io(e):JSON.stringify(e)}function io(e){const t=[],n=` ${e.type.charAt(0).toUpperCase()+e.type.slice(1)} Message `,a=Math.floor((80-n.length)/2),r="=".repeat(a),s=n.length%2===0?r:`${r}=`;if(t.push(`${r}${n}${s}`),e.type==="ai"){const i=e;if(i.tool_calls&&i.tool_calls.length>0){t.push("Tool Calls:");for(const o of i.tool_calls){t.push(` ${o.name} (${o.id})`),t.push(` Call ID: ${o.id}`),t.push(" Args:");for(const[c,l]of Object.entries(o.args))t.push(` ${c}: ${l}`)}}}if(e.type==="tool"){const i=e;i.name&&t.push(`Name: ${i.name}`)}return typeof e.content=="string"&&e.content.trim()&&(t.length>1&&t.push(""),t.push(e.content)),t.join(`
|
|
1
|
+
import{s as Oi,v as se,P as Pe,p as Ht,a as Ga,b as Nr,g as he,c as kr,d as Ke,_ as Ci,$ as xi,e as Ni,f as ki,h as Rr,i as ca,j as Ri,k as Pi,t as Va,l as Pr,V as Mi,m as Li,n as Ut,o as $i,T as ji}from"./chunk-VL2OQCWN-B6188h-8.js";import{Z as P,a as Za,o as la,s as ua}from"./index-LZZ02vm2.js";var Di=Object.defineProperty,F=(e,t)=>{for(var n in t)Di(e,n,{get:t[n],enumerable:!0})};function Ue(e){return typeof e=="object"&&e!==null&&"type"in e&&typeof e.type=="string"&&"source_type"in e&&(e.source_type==="url"||e.source_type==="base64"||e.source_type==="text"||e.source_type==="id")}function da(e){return Ue(e)&&e.source_type==="url"&&"url"in e&&typeof e.url=="string"}function ha(e){return Ue(e)&&e.source_type==="base64"&&"data"in e&&typeof e.data=="string"}function Fi(e){return Ue(e)&&e.source_type==="text"&&"text"in e&&typeof e.text=="string"}function Mr(e){return Ue(e)&&e.source_type==="id"&&"id"in e&&typeof e.id=="string"}function Lr(e){if(Ue(e)){if(e.source_type==="url")return{type:"image_url",image_url:{url:e.url}};if(e.source_type==="base64"){if(!e.mime_type)throw new Error("mime_type key is required for base64 data.");return{type:"image_url",image_url:{url:`data:${e.mime_type};base64,${e.data}`}}}}throw new Error("Unsupported source type. Only 'url' and 'base64' are supported.")}function Ui(e){const t=e.split(";")[0].split("/");if(t.length!==2)throw new Error(`Invalid mime type: "${e}" - does not match type/subtype format.`);const n=t[0].trim(),a=t[1].trim();if(n===""||a==="")throw new Error(`Invalid mime type: "${e}" - type or subtype is empty.`);const r={};for(const s of e.split(";").slice(1)){const i=s.split("=");if(i.length!==2)throw new Error(`Invalid parameter syntax in mime type: "${e}".`);const o=i[0].trim(),c=i[1].trim();if(o==="")throw new Error(`Invalid parameter syntax in mime type: "${e}".`);r[o]=c}return{type:n,subtype:a,parameters:r}}function $n({dataUrl:e,asTypedArray:t=!1}){const n=e.match(/^data:(\w+\/\w+);base64,([A-Za-z0-9+/]+=*)$/);let a;if(n){a=n[1].toLowerCase();const r=t?Uint8Array.from(atob(n[2]),s=>s.charCodeAt(0)):n[2];return{mime_type:a,data:r}}}function Bi(e,t){if(e.type==="text"){if(!t.fromStandardTextBlock)throw new Error(`Converter for ${t.providerName} does not implement \`fromStandardTextBlock\` method.`);return t.fromStandardTextBlock(e)}if(e.type==="image"){if(!t.fromStandardImageBlock)throw new Error(`Converter for ${t.providerName} does not implement \`fromStandardImageBlock\` method.`);return t.fromStandardImageBlock(e)}if(e.type==="audio"){if(!t.fromStandardAudioBlock)throw new Error(`Converter for ${t.providerName} does not implement \`fromStandardAudioBlock\` method.`);return t.fromStandardAudioBlock(e)}if(e.type==="file"){if(!t.fromStandardFileBlock)throw new Error(`Converter for ${t.providerName} does not implement \`fromStandardFileBlock\` method.`);return t.fromStandardFileBlock(e)}throw new Error(`Unable to convert content block type '${e.type}' to provider-specific format: not recognized.`)}function $r(e){return typeof e=="object"&&e!==null&&"type"in e&&"content"in e&&(typeof e.content=="string"||Array.isArray(e.content))}function zi(e,t){return t?.[e]||Oi(e)}function Hi(e,t,n){const a={};for(const r in e)Object.hasOwn(e,r)&&(a[t(r,n)]=e[r]);return a}var Gi={};F(Gi,{Serializable:()=>lt,get_lc_unique_name:()=>pa});function qa(e){return Array.isArray(e)?[...e]:{...e}}function Vi(e,t){const n=qa(e);for(const[a,r]of Object.entries(t)){const[s,...i]=a.split(".").reverse();let o=n;for(const c of i.reverse()){if(o[c]===void 0)break;o[c]=qa(o[c]),o=o[c]}o[s]!==void 0&&(o[s]={lc:1,type:"secret",id:[r]})}return n}function pa(e){const t=Object.getPrototypeOf(e);return typeof e.lc_name=="function"&&(typeof t.lc_name!="function"||e.lc_name()!==t.lc_name())?e.lc_name():e.name}var lt=class jr{lc_serializable=!1;lc_kwargs;static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,pa(this.constructor)]}get lc_secrets(){}get lc_attributes(){}get lc_aliases(){}get lc_serializable_keys(){}constructor(t,...n){this.lc_serializable_keys!==void 0?this.lc_kwargs=Object.fromEntries(Object.entries(t||{}).filter(([a])=>this.lc_serializable_keys?.includes(a))):this.lc_kwargs=t??{}}toJSON(){if(!this.lc_serializable)return this.toJSONNotImplemented();if(this.lc_kwargs instanceof jr||typeof this.lc_kwargs!="object"||Array.isArray(this.lc_kwargs))return this.toJSONNotImplemented();const t={},n={},a=Object.keys(this.lc_kwargs).reduce((r,s)=>(r[s]=s in this?this[s]:this.lc_kwargs[s],r),{});for(let r=Object.getPrototypeOf(this);r;r=Object.getPrototypeOf(r))Object.assign(t,Reflect.get(r,"lc_aliases",this)),Object.assign(n,Reflect.get(r,"lc_secrets",this)),Object.assign(a,Reflect.get(r,"lc_attributes",this));return Object.keys(n).forEach(r=>{let s=this,i=a;const[o,...c]=r.split(".").reverse();for(const l of c.reverse()){if(!(l in s)||s[l]===void 0)return;(!(l in i)||i[l]===void 0)&&(typeof s[l]=="object"&&s[l]!=null?i[l]={}:Array.isArray(s[l])&&(i[l]=[])),s=s[l],i=i[l]}o in s&&s[o]!==void 0&&(i[o]=i[o]||s[o])}),{lc:1,type:"constructor",id:this.lc_id,kwargs:Hi(Object.keys(n).length?Vi(a,n):a,zi,t)}}toJSONNotImplemented(){return{lc:1,type:"not_implemented",id:this.lc_id}}};function C(e,t){return k(e)&&e.type===t}function k(e){return typeof e=="object"&&e!==null}function Ie(e){return Array.isArray(e)}function S(e){return typeof e=="string"}function we(e){return typeof e=="number"}function fa(e){return e instanceof Uint8Array}function Ja(e){try{return JSON.parse(e)}catch{return}}const vt=e=>e();function Zi(e){if(e.type==="char_location"&&S(e.document_title)&&we(e.start_char_index)&&we(e.end_char_index)&&S(e.cited_text)){const{document_title:t,start_char_index:n,end_char_index:a,cited_text:r,...s}=e;return{...s,type:"citation",source:"char",title:t??void 0,startIndex:n,endIndex:a,citedText:r}}if(e.type==="page_location"&&S(e.document_title)&&we(e.start_page_number)&&we(e.end_page_number)&&S(e.cited_text)){const{document_title:t,start_page_number:n,end_page_number:a,cited_text:r,...s}=e;return{...s,type:"citation",source:"page",title:t??void 0,startIndex:n,endIndex:a,citedText:r}}if(e.type==="content_block_location"&&S(e.document_title)&&we(e.start_block_index)&&we(e.end_block_index)&&S(e.cited_text)){const{document_title:t,start_block_index:n,end_block_index:a,cited_text:r,...s}=e;return{...s,type:"citation",source:"block",title:t??void 0,startIndex:n,endIndex:a,citedText:r}}if(e.type==="web_search_result_location"&&S(e.url)&&S(e.title)&&S(e.encrypted_index)&&S(e.cited_text)){const{url:t,title:n,encrypted_index:a,cited_text:r,...s}=e;return{...s,type:"citation",source:"url",url:t,title:n,startIndex:Number(a),endIndex:Number(a),citedText:r}}if(e.type==="search_result_location"&&S(e.source)&&S(e.title)&&we(e.start_block_index)&&we(e.end_block_index)&&S(e.cited_text)){const{source:t,title:n,start_block_index:a,end_block_index:r,cited_text:s,...i}=e;return{...i,type:"citation",source:"search",url:t,title:n??void 0,startIndex:a,endIndex:r,citedText:s}}}function Dr(e){if(C(e,"document")&&k(e.source)&&"type"in e.source){if(e.source.type==="base64"&&S(e.source.media_type)&&S(e.source.data))return{type:"file",mimeType:e.source.media_type,data:e.source.data};if(e.source.type==="url"&&S(e.source.url))return{type:"file",url:e.source.url};if(e.source.type==="file"&&S(e.source.file_id))return{type:"file",fileId:e.source.file_id};if(e.source.type==="text"&&S(e.source.data))return{type:"file",mimeType:String(e.source.media_type??"text/plain"),data:e.source.data}}else if(C(e,"image")&&k(e.source)&&"type"in e.source){if(e.source.type==="base64"&&S(e.source.media_type)&&S(e.source.data))return{type:"image",mimeType:e.source.media_type,data:e.source.data};if(e.source.type==="url"&&S(e.source.url))return{type:"image",url:e.source.url};if(e.source.type==="file"&&S(e.source.file_id))return{type:"image",fileId:e.source.file_id}}}function qi(e){function*t(){for(const n of e){const a=Dr(n);a?yield a:yield n}}return Array.from(t())}function Wa(e){function*t(){const n=typeof e.content=="string"?[{type:"text",text:e.content}]:e.content;for(const a of n){if(C(a,"text")&&S(a.text)){const{text:r,citations:s,...i}=a;if(Ie(s)&&s.length){const o=s.reduce((c,l)=>{const d=Zi(l);return d?[...c,d]:c},[]);yield{...i,type:"text",text:r,annotations:o};continue}else{yield{...i,type:"text",text:r};continue}}else if(C(a,"thinking")&&S(a.thinking)){const{thinking:r,signature:s,...i}=a;yield{...i,type:"reasoning",reasoning:r,signature:s};continue}else if(C(a,"redacted_thinking")){yield{type:"non_standard",value:a};continue}else if(C(a,"tool_use")&&S(a.name)&&S(a.id)){yield{type:"tool_call",id:a.id,name:a.name,args:a.input};continue}else if(C(a,"input_json_delta")){if(Wi(e)&&e.tool_call_chunks?.length){const r=e.tool_call_chunks[0];yield{type:"tool_call_chunk",id:r.id,name:r.name,args:r.args,index:r.index};continue}}else if(C(a,"server_tool_use")&&S(a.name)&&S(a.id)){const{name:r,id:s}=a;if(r==="web_search"){const i=vt(()=>{if(typeof a.input=="string")return a.input;if(k(a.input)&&S(a.input.query))return a.input.query;if(S(a.partial_json)){const o=Ja(a.partial_json);if(o?.query)return o.query}return""});yield{id:s,type:"server_tool_call",name:"web_search",args:{query:i}};continue}else if(a.name==="code_execution"){const i=vt(()=>{if(typeof a.input=="string")return a.input;if(k(a.input)&&S(a.input.code))return a.input.code;if(S(a.partial_json)){const o=Ja(a.partial_json);if(o?.code)return o.code}return""});yield{id:s,type:"server_tool_call",name:"code_execution",args:{code:i}};continue}}else if(C(a,"web_search_tool_result")&&S(a.tool_use_id)&&Ie(a.content)){const{content:r,tool_use_id:s}=a,i=r.reduce((o,c)=>C(c,"web_search_result")?[...o,c.url]:o,[]);yield{type:"server_tool_call_result",name:"web_search",toolCallId:s,status:"success",output:{urls:i}};continue}else if(C(a,"code_execution_tool_result")&&S(a.tool_use_id)&&k(a.content)){yield{type:"server_tool_call_result",name:"code_execution",toolCallId:a.tool_use_id,status:"success",output:a.content};continue}else if(C(a,"mcp_tool_use")){yield{id:a.id,type:"server_tool_call",name:"mcp_tool_use",args:a.input};continue}else if(C(a,"mcp_tool_result")&&S(a.tool_use_id)&&k(a.content)){yield{type:"server_tool_call_result",name:"mcp_tool_use",toolCallId:a.tool_use_id,status:"success",output:a.content};continue}else if(C(a,"container_upload")){yield{type:"server_tool_call",name:"container_upload",args:a.input};continue}else if(C(a,"search_result")){yield{id:a.id,type:"non_standard",value:a};continue}else if(C(a,"tool_result")){yield{id:a.id,type:"non_standard",value:a};continue}else{const r=Dr(a);if(r){yield r;continue}}yield{type:"non_standard",value:a}}}return Array.from(t())}const Ji={translateContent:Wa,translateContentChunk:Wa};function Wi(e){return typeof e?._getType=="function"&&typeof e.concat=="function"&&e._getType()==="ai"}function Ki(e){return da(e)?{type:e.type,mimeType:e.mime_type,url:e.url,metadata:e.metadata}:ha(e)?{type:e.type,mimeType:e.mime_type??"application/octet-stream",data:e.data,metadata:e.metadata}:Mr(e)?{type:e.type,mimeType:e.mime_type,fileId:e.id,metadata:e.metadata}:e}function Yi(e){return e.map(Ki)}function Qi(e){return!!(C(e,"image_url")&&k(e.image_url)||C(e,"input_audio")&&k(e.input_audio)||C(e,"file")&&k(e.file))}function Xi(e){if(C(e,"image_url")&&k(e.image_url)&&S(e.image_url.url)){const t=$n({dataUrl:e.image_url.url});return t?{type:"image",mimeType:t.mime_type,data:t.data}:{type:"image",url:e.image_url.url}}else{if(C(e,"input_audio")&&k(e.input_audio)&&S(e.input_audio.data)&&S(e.input_audio.format))return{type:"audio",data:e.input_audio.data,mimeType:`audio/${e.input_audio.format}`};if(C(e,"file")&&k(e.file)&&S(e.file.data)){const t=$n({dataUrl:e.file.data});if(t)return{type:"file",data:t.data,mimeType:t.mime_type};if(S(e.file.file_id))return{type:"file",fileId:e.file.file_id}}}return e}function eo(e){const t=[];typeof e.content=="string"?t.push({type:"text",text:e.content}):t.push(...ma(e.content));for(const n of e.tool_calls??[])t.push({type:"tool_call",id:n.id,name:n.name,args:n.args});return t}function to(e){const t=[];typeof e.content=="string"?t.push({type:"text",text:e.content}):t.push(...ma(e.content));for(const n of e.tool_calls??[])t.push({type:"tool_call",id:n.id,name:n.name,args:n.args});return t}function ma(e){const t=[];for(const n of e)Qi(n)?t.push(Xi(n)):t.push(n);return t}function no(e){if(e.type==="url_citation"){const{url:t,title:n,start_index:a,end_index:r}=e;return{type:"citation",url:t,title:n,startIndex:a,endIndex:r}}if(e.type==="file_citation"){const{file_id:t,filename:n,index:a}=e;return{type:"citation",title:n,startIndex:a,endIndex:a,fileId:t}}return e}function Fr(e){function*t(){k(e.additional_kwargs?.reasoning)&&Ie(e.additional_kwargs.reasoning.summary)&&(yield{type:"reasoning",reasoning:e.additional_kwargs.reasoning.summary.reduce((r,s)=>k(s)&&S(s.text)?`${r}${s.text}`:r,"")});const n=typeof e.content=="string"?[{type:"text",text:e.content}]:e.content;for(const a of n)if(C(a,"text")){const{text:r,annotations:s,...i}=a;Array.isArray(s)?yield{...i,type:"text",text:String(r),annotations:s.map(no)}:yield{...i,type:"text",text:String(r)}}for(const a of e.tool_calls??[])yield{type:"tool_call",id:a.id,name:a.name,args:a.args};if(k(e.additional_kwargs)&&Ie(e.additional_kwargs.tool_outputs))for(const a of e.additional_kwargs.tool_outputs){if(C(a,"web_search_call")){yield{id:a.id,type:"server_tool_call",name:"web_search",args:{query:a.query}};continue}else if(C(a,"file_search_call")){yield{id:a.id,type:"server_tool_call",name:"file_search",args:{query:a.query}};continue}else if(C(a,"computer_call")){yield{type:"non_standard",value:a};continue}else if(C(a,"code_interpreter_call")){if(S(a.code)&&(yield{id:a.id,type:"server_tool_call",name:"code_interpreter",args:{code:a.code}}),Ie(a.outputs)){const r=vt(()=>{if(a.status!=="in_progress"){if(a.status==="completed")return 0;if(a.status==="incomplete")return 127;if(a.status!=="interpreting"&&a.status==="failed")return 1}});for(const s of a.outputs)if(C(s,"logs")){yield{type:"server_tool_call_result",toolCallId:a.id??"",status:"success",output:{type:"code_interpreter_output",returnCode:r??0,stderr:[0,void 0].includes(r)?void 0:String(s.logs),stdout:[0,void 0].includes(r)?String(s.logs):void 0}};continue}}continue}else if(C(a,"mcp_call")){yield{id:a.id,type:"server_tool_call",name:"mcp_call",args:a.input};continue}else if(C(a,"mcp_list_tools")){yield{id:a.id,type:"server_tool_call",name:"mcp_list_tools",args:a.input};continue}else if(C(a,"mcp_approval_request")){yield{type:"non_standard",value:a};continue}else if(C(a,"image_generation_call")){yield{type:"non_standard",value:a};continue}k(a)&&(yield{type:"non_standard",value:a})}}return Array.from(t())}function ao(e){function*t(){yield*Fr(e);for(const n of e.tool_call_chunks??[])yield{type:"tool_call_chunk",id:n.id,name:n.name,args:n.args}}return Array.from(t())}const ro={translateContent:e=>typeof e.content=="string"?eo(e):Fr(e),translateContentChunk:e=>typeof e.content=="string"?to(e):ao(e)};function so(e,t="pretty"){return t==="pretty"?io(e):JSON.stringify(e)}function io(e){const t=[],n=` ${e.type.charAt(0).toUpperCase()+e.type.slice(1)} Message `,a=Math.floor((80-n.length)/2),r="=".repeat(a),s=n.length%2===0?r:`${r}=`;if(t.push(`${r}${n}${s}`),e.type==="ai"){const i=e;if(i.tool_calls&&i.tool_calls.length>0){t.push("Tool Calls:");for(const o of i.tool_calls){t.push(` ${o.name} (${o.id})`),t.push(` Call ID: ${o.id}`),t.push(" Args:");for(const[c,l]of Object.entries(o.args))t.push(` ${c}: ${l}`)}}}if(e.type==="tool"){const i=e;i.name&&t.push(`Name: ${i.name}`)}return typeof e.content=="string"&&e.content.trim()&&(t.length>1&&t.push(""),t.push(e.content)),t.join(`
|
|
2
2
|
`)}const yn=Symbol.for("langchain.message");function Xe(e,t){return typeof e=="string"?e===""?t:typeof t=="string"?e+t:Array.isArray(t)&&t.some(n=>Ue(n))?[{type:"text",source_type:"text",text:e},...t]:[{type:"text",text:e},...t]:Array.isArray(t)?Ot(e,t)??[...e,...t]:t===""?e:Array.isArray(e)&&e.some(n=>Ue(n))?[...e,{type:"file",source_type:"text",text:t}]:[...e,{type:"text",text:t}]}function Ur(e,t){return e==="error"||t==="error"?"error":"success"}function oo(e,t){function n(a,r){if(typeof a!="object"||a===null||a===void 0)return a;if(r>=t)return Array.isArray(a)?"[Array]":"[Object]";if(Array.isArray(a))return a.map(i=>n(i,r+1));const s={};for(const i of Object.keys(a))s[i]=n(a[i],r+1);return s}return JSON.stringify(n(e,0),null,2)}var Le=class extends lt{lc_namespace=["langchain_core","messages"];lc_serializable=!0;get lc_aliases(){return{additional_kwargs:"additional_kwargs",response_metadata:"response_metadata"}}[yn]=!0;id;name;content;additional_kwargs;response_metadata;_getType(){return this.type}getType(){return this._getType()}constructor(e){const t=typeof e=="string"||Array.isArray(e)?{content:e}:e;t.additional_kwargs||(t.additional_kwargs={}),t.response_metadata||(t.response_metadata={}),super(t),this.name=t.name,t.content===void 0&&t.contentBlocks!==void 0?(this.content=t.contentBlocks,this.response_metadata={output_version:"v1",...t.response_metadata}):t.content!==void 0?(this.content=t.content??[],this.response_metadata=t.response_metadata):(this.content=[],this.response_metadata=t.response_metadata),this.additional_kwargs=t.additional_kwargs,this.id=t.id}get text(){return typeof this.content=="string"?this.content:Array.isArray(this.content)?this.content.map(e=>typeof e=="string"?e:e.type==="text"?e.text:"").join(""):""}get contentBlocks(){const e=typeof this.content=="string"?[{type:"text",text:this.content}]:this.content;return[Yi,ma,qi].reduce((a,r)=>r(a),e)}toDict(){return{type:this.getType(),data:this.toJSON().kwargs}}static lc_name(){return"BaseMessage"}get _printableFields(){return{id:this.id,content:this.content,name:this.name,additional_kwargs:this.additional_kwargs,response_metadata:this.response_metadata}}static isInstance(e){return typeof e=="object"&&e!==null&&yn in e&&e[yn]===!0&&$r(e)}_updateId(e){this.id=e,this.lc_kwargs.id=e}get[Symbol.toStringTag](){return this.constructor.lc_name()}[Symbol.for("nodejs.util.inspect.custom")](e){if(e===null)return this;const t=oo(this._printableFields,Math.max(4,e));return`${this.constructor.lc_name()} ${t}`}toFormattedString(e="pretty"){return so(this,e)}};function co(e){return Array.isArray(e)&&e.every(t=>typeof t.index=="number")}function ee(e={},t={}){const n={...e};for(const[a,r]of Object.entries(t))if(n[a]==null)n[a]=r;else{if(r==null)continue;if(typeof n[a]!=typeof r||Array.isArray(n[a])!==Array.isArray(r))throw new Error(`field[${a}] already exists in the message chunk, but with a different type.`);if(typeof n[a]=="string"){if(a==="type")continue;["id","name","output_version","model_provider"].includes(a)?n[a]=r:n[a]+=r}else if(typeof n[a]=="object"&&!Array.isArray(n[a]))n[a]=ee(n[a],r);else if(Array.isArray(n[a]))n[a]=Ot(n[a],r);else{if(n[a]===r)continue;console.warn(`field[${a}] already exists in this message chunk and value has unsupported type.`)}}return n}function Ot(e,t){if(!(e===void 0&&t===void 0)){if(e===void 0||t===void 0)return e||t;{const n=[...e];for(const a of t)if(typeof a=="object"&&a!==null&&"index"in a&&typeof a.index=="number"){const r=n.findIndex(s=>{const i=typeof s=="object",o="index"in s&&s.index===a.index,c="id"in s&&"id"in a&&s?.id===a?.id,l=!("id"in s)||!s?.id||!("id"in a)||!a?.id;return i&&o&&(c||l)});r!==-1&&typeof n[r]=="object"&&n[r]!==null?n[r]=ee(n[r],a):n.push(a)}else{if(typeof a=="object"&&a!==null&&"text"in a&&a.text==="")continue;n.push(a)}return n}}}function Br(e,t){if(!e&&!t)throw new Error("Cannot merge two undefined objects.");if(!e||!t)return e||t;if(typeof e!=typeof t)throw new Error(`Cannot merge objects of different types.
|
|
3
3
|
Left ${typeof e}
|
|
4
4
|
Right ${typeof t}`);if(typeof e=="string"&&typeof t=="string")return e+t;if(Array.isArray(e)&&Array.isArray(t))return Ot(e,t);if(typeof e=="object"&&typeof t=="object")return ee(e,t);if(e===t)return e;throw new Error(`Can not merge objects of different types.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var u={},A;function m(){if(A)return u;A=1,u.byteLength=y,u.toByteArray=i,u.fromByteArray=B;for(var f=[],o=[],l=typeof Uint8Array<"u"?Uint8Array:Array,s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",F=0,p=s.length;F<p;++F)f[F]=s[F],o[s.charCodeAt(F)]=F;o[45]=62,o[95]=63;function x(r){var e=r.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var a=r.indexOf("=");a===-1&&(a=e);var n=a===e?0:4-a%4;return[a,n]}function y(r){var e=x(r),a=e[0],n=e[1];return(a+n)*3/4-n}function C(r,e,a){return(e+a)*3/4-a}function i(r){var e,a=x(r),n=a[0],v=a[1],t=new l(C(r,n,v)),h=0,d=v>0?n-4:n,c;for(c=0;c<d;c+=4)e=o[r.charCodeAt(c)]<<18|o[r.charCodeAt(c+1)]<<12|o[r.charCodeAt(c+2)]<<6|o[r.charCodeAt(c+3)],t[h++]=e>>16&255,t[h++]=e>>8&255,t[h++]=e&255;return v===2&&(e=o[r.charCodeAt(c)]<<2|o[r.charCodeAt(c+1)]>>4,t[h++]=e&255),v===1&&(e=o[r.charCodeAt(c)]<<10|o[r.charCodeAt(c+1)]<<4|o[r.charCodeAt(c+2)]>>2,t[h++]=e>>8&255,t[h++]=e&255),t}function L(r){return f[r>>18&63]+f[r>>12&63]+f[r>>6&63]+f[r&63]}function g(r,e,a){for(var n,v=[],t=e;t<a;t+=3)n=(r[t]<<16&16711680)+(r[t+1]<<8&65280)+(r[t+2]&255),v.push(L(n));return v.join("")}function B(r){for(var e,a=r.length,n=a%3,v=[],t=16383,h=0,d=a-n;h<d;h+=t)v.push(g(r,h,h+t>d?d:h+t));return n===1?(e=r[a-1],v.push(f[e>>2]+f[e<<4&63]+"==")):n===2&&(e=(r[a-2]<<8)+r[a-1],v.push(f[e>>10]+f[e>>4&63]+f[e<<2&63]+"=")),v.join("")}return u}export{m as r};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{B as $n,O as bt,l as jn,p as nn,f as xt,H as St,j as Bn,k as Ln,c as A,b as kt,m as Un,n as qn,h as Wn,g as Fn,t as be,i as Mt,C as Dn,R as Tt,o as Hn}from"./index-D-_HYYNB.js";import"./chunk-VL2OQCWN-DDPfe4wt.js";import"./index-B7oaWPow.js";var Rt=class extends $n{static lc_name(){return"AnthropicToolsOutputParser"}lc_namespace=["langchain","anthropic","output_parsers"];returnId=!1;keyName;returnSingle=!1;zodSchema;constructor(t){super(t),this.keyName=t.keyName,this.returnSingle=t.returnSingle??this.returnSingle,this.zodSchema=t.zodSchema}async _validateResult(t){let e=t;if(typeof t=="string")try{e=JSON.parse(t)}catch(s){throw new bt(`Failed to parse. Text: "${JSON.stringify(t,null,2)}". Error: ${JSON.stringify(s.message)}`,t)}else e=t;if(this.zodSchema===void 0)return e;const n=await jn(this.zodSchema,e);if(n.success)return n.data;throw new bt(`Failed to parse. Text: "${JSON.stringify(t,null,2)}". Error: ${JSON.stringify(n.error.issues)}`,JSON.stringify(e,null,2))}async parseResult(t){const e=t.flatMap(r=>{const{message:i}=r;return Array.isArray(i.content)?sn(i.content)[0]:[]});if(e[0]===void 0)throw new Error("No parseable tool calls provided to AnthropicToolsOutputParser.");const[n]=e;return await this._validateResult(n.args)}};function sn(t){const e=[];for(const n of t)n.type==="tool_use"&&e.push({name:n.name,args:n.input,id:n.id,type:"tool_call"});return e}function Kn(t){if(t)return t==="any"?{type:"any"}:t==="auto"?{type:"auto"}:t==="none"?{type:"none"}:typeof t=="string"?{type:"tool",name:t}:t}function Jn(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="thinking"}function Xn(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="redacted_thinking"}function zn(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="search_result"}function Vn(t){return typeof t!="object"||t==null||!("type"in t)||t.type!=="image"||!("source"in t)||typeof t.source!="object"||t.source==null||!("type"in t.source)?!1:t.source.type==="base64"?!(!("media_type"in t.source)||typeof t.source.media_type!="string"||!("data"in t.source)||typeof t.source.data!="string"):t.source.type==="url"?!(!("url"in t.source)||typeof t.source.url!="string"):!1}const Qn={providerName:"anthropic",fromStandardTextBlock(t){return{type:"text",text:t.text,..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}}},fromStandardImageBlock(t){if(t.source_type==="url"){const e=nn({dataUrl:t.url,asTypedArray:!1});return e?{type:"image",source:{type:"base64",data:e.data,media_type:e.mime_type},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}}:{type:"image",source:{type:"url",url:t.url},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}}}else{if(t.source_type==="base64")return{type:"image",source:{type:"base64",data:t.data,media_type:t.mime_type??""},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}};throw new Error(`Unsupported image source type: ${t.source_type}`)}},fromStandardFileBlock(t){const e=(t.mime_type??"").split(";")[0];if(t.source_type==="url"){if(e==="application/pdf"||e==="")return{type:"document",source:{type:"url",url:t.url},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};throw new Error(`Unsupported file mime type for file url source: ${t.mime_type}`)}else if(t.source_type==="text"){if(e==="text/plain"||e==="")return{type:"document",source:{type:"text",data:t.text,media_type:t.mime_type??""},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};throw new Error(`Unsupported file mime type for file text source: ${t.mime_type}`)}else if(t.source_type==="base64"){if(e==="application/pdf"||e==="")return{type:"document",source:{type:"base64",data:t.data,media_type:"application/pdf"},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};if(["image/jpeg","image/png","image/gif","image/webp"].includes(e))return{type:"document",source:{type:"content",content:[{type:"image",source:{type:"base64",data:t.data,media_type:e}}]},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};throw new Error(`Unsupported file mime type for file base64 source: ${t.mime_type}`)}else throw new Error(`Unsupported file source type: ${t.source_type}`)}},Gn=t=>t();function Yn(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="citation"}function Zn(t){function*e(){for(const n of t)Yn(n)&&(n.source==="char"?yield{type:"char_location",file_id:n.url??"",start_char_index:n.startIndex??0,end_char_index:n.endIndex??0,document_title:n.title??null,document_index:0,cited_text:n.citedText??""}:n.source==="page"?yield{type:"page_location",file_id:n.url??"",start_page_number:n.startIndex??0,end_page_number:n.endIndex??0,document_title:n.title??null,document_index:0,cited_text:n.citedText??""}:n.source==="block"?yield{type:"content_block_location",file_id:n.url??"",start_block_index:n.startIndex??0,end_block_index:n.endIndex??0,document_title:n.title??null,document_index:0,cited_text:n.citedText??""}:n.source==="url"?yield{type:"web_search_result_location",url:n.url??"",title:n.title??null,encrypted_index:String(n.startIndex??0),cited_text:n.citedText??""}:n.source==="search"&&(yield{type:"search_result_location",title:n.title??null,start_block_index:n.startIndex??0,end_block_index:n.endIndex??0,search_result_index:0,source:n.source??"",cited_text:n.citedText??""}))}return Array.from(e())}function G(t){return typeof t=="string"?t:es(t)}function es(t){const e=[];for(let n=0,{length:s}=t;n<s;n++)e.push(String.fromCharCode(t[n]));return btoa(e.join(""))}function Ve(t){return(t??"").split(";")[0].toLowerCase()}function he(t,e){if(t!=null&&typeof t=="object"&&e in t)return t[e]}function H(t,e){const n=he(e,"cache_control");n!==void 0&&(t.cache_control=n);const s=he(e,"citations");s!==void 0&&(t.citations=s);const r=he(e,"context");r!==void 0&&(t.context=r);const i=he(e,"title");return i!==void 0&&(t.title=i),t}function Qe(t,e){const n=he(e,"cache_control");return n!==void 0&&(t.cache_control=n),t}function At(t){return new Set(["image/jpeg","image/png","image/gif","image/webp"]).has(t)}function ts(t){const e=[],n=t.response_metadata,s="model_provider"in n&&n?.model_provider==="anthropic";for(const r of t.contentBlocks)if(r.type==="text")r.annotations?e.push({type:"text",text:r.text,citations:Zn(r.annotations)}):e.push({type:"text",text:r.text});else if(r.type==="tool_call")e.push({type:"tool_use",id:r.id??"",name:r.name,input:r.args});else if(r.type==="tool_call_chunk"){const i=Gn(()=>{if(typeof r.args!="string")return r.args;try{return JSON.parse(r.args)}catch{return{}}});e.push({type:"tool_use",id:r.id??"",name:r.name??"",input:i})}else if(r.type==="reasoning"&&s)e.push({type:"thinking",thinking:r.reasoning,signature:String(r.signature)});else if(r.type==="server_tool_call"&&s)r.name==="web_search"?e.push({type:"server_tool_use",name:r.name,id:r.id??"",input:r.args}):r.name==="code_execution"&&e.push({type:"server_tool_use",name:r.name,id:r.id??"",input:r.args});else if(r.type==="server_tool_call_result"&&s)if(r.name==="web_search"&&Array.isArray(r.output.urls)){const i=r.output.urls.map(a=>({type:"web_search_result",title:"",encrypted_content:"",url:a}));e.push({type:"web_search_tool_result",tool_use_id:r.toolCallId??"",content:i})}else r.name==="code_execution"?e.push({type:"code_execution_tool_result",tool_use_id:r.toolCallId??"",content:r.output}):r.name==="mcp_tool_result"&&e.push({type:"mcp_tool_result",tool_use_id:r.toolCallId??"",content:r.output});else{if(r.type==="audio")throw new Error("Anthropic does not support audio content blocks.");if(r.type==="file"){const i=r.metadata;if(r.fileId){e.push(H({type:"document",source:{type:"file",file_id:r.fileId}},i));continue}if(r.url){const a=Ve(r.mimeType);if(a==="application/pdf"||a===""){e.push(H({type:"document",source:{type:"url",url:r.url}},i));continue}}if(r.data){const a=Ve(r.mimeType);if(a===""||a==="application/pdf")e.push(H({type:"document",source:{type:"base64",data:G(r.data),media_type:"application/pdf"}},i));else if(a==="text/plain")e.push(H({type:"document",source:{type:"text",data:G(r.data),media_type:"text/plain"}},i));else if(At(a))e.push(H({type:"document",source:{type:"content",content:[{type:"image",source:{type:"base64",data:G(r.data),media_type:a}}]}},i));else throw new Error(`Unsupported file mime type for Anthropic base64 source: ${a}`);continue}throw new Error("File content block must include a fileId, url, or data property.")}else if(r.type==="image"){const i=r.metadata;if(r.fileId){e.push(Qe({type:"image",source:{type:"file",file_id:r.fileId}},i));continue}if(r.url){e.push(Qe({type:"image",source:{type:"url",url:r.url}},i));continue}if(r.data){const a=Ve(r.mimeType)||"image/png";At(a)&&e.push(Qe({type:"image",source:{type:"base64",data:G(r.data),media_type:a}},i));continue}throw new Error("Image content block must include a fileId, url, or data property.")}else r.type==="video"||(r.type==="text-plain"?r.data&&e.push(H({type:"document",source:{type:"text",data:G(r.data),media_type:"text/plain"}},r.metadata)):r.type==="non_standard"&&s&&e.push(r.value))}return e}function vt(t){const e=nn({dataUrl:t});if(e)return{type:"base64",media_type:e.mime_type,data:e.data};let n;try{n=new URL(t)}catch{throw new Error([`Malformed image URL: ${JSON.stringify(t)}. Content blocks of type 'image_url' must be a valid http, https, or base64-encoded data URL.`,"Example: data:image/png;base64,/9j/4AAQSk...","Example: https://example.com/image.jpg"].join(`
|
|
1
|
+
import{B as $n,O as bt,l as jn,p as nn,f as xt,H as St,j as Bn,k as Ln,c as A,b as kt,m as Un,n as qn,h as Wn,g as Fn,t as be,i as Mt,C as Dn,R as Tt,o as Hn}from"./index-DI2GdDtn.js";import"./chunk-VL2OQCWN-B6188h-8.js";import"./index-LZZ02vm2.js";import"./index-DRz5BQNA.js";var Rt=class extends $n{static lc_name(){return"AnthropicToolsOutputParser"}lc_namespace=["langchain","anthropic","output_parsers"];returnId=!1;keyName;returnSingle=!1;zodSchema;constructor(t){super(t),this.keyName=t.keyName,this.returnSingle=t.returnSingle??this.returnSingle,this.zodSchema=t.zodSchema}async _validateResult(t){let e=t;if(typeof t=="string")try{e=JSON.parse(t)}catch(s){throw new bt(`Failed to parse. Text: "${JSON.stringify(t,null,2)}". Error: ${JSON.stringify(s.message)}`,t)}else e=t;if(this.zodSchema===void 0)return e;const n=await jn(this.zodSchema,e);if(n.success)return n.data;throw new bt(`Failed to parse. Text: "${JSON.stringify(t,null,2)}". Error: ${JSON.stringify(n.error.issues)}`,JSON.stringify(e,null,2))}async parseResult(t){const e=t.flatMap(r=>{const{message:i}=r;return Array.isArray(i.content)?sn(i.content)[0]:[]});if(e[0]===void 0)throw new Error("No parseable tool calls provided to AnthropicToolsOutputParser.");const[n]=e;return await this._validateResult(n.args)}};function sn(t){const e=[];for(const n of t)n.type==="tool_use"&&e.push({name:n.name,args:n.input,id:n.id,type:"tool_call"});return e}function Kn(t){if(t)return t==="any"?{type:"any"}:t==="auto"?{type:"auto"}:t==="none"?{type:"none"}:typeof t=="string"?{type:"tool",name:t}:t}function Jn(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="thinking"}function Xn(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="redacted_thinking"}function zn(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="search_result"}function Vn(t){return typeof t!="object"||t==null||!("type"in t)||t.type!=="image"||!("source"in t)||typeof t.source!="object"||t.source==null||!("type"in t.source)?!1:t.source.type==="base64"?!(!("media_type"in t.source)||typeof t.source.media_type!="string"||!("data"in t.source)||typeof t.source.data!="string"):t.source.type==="url"?!(!("url"in t.source)||typeof t.source.url!="string"):!1}const Qn={providerName:"anthropic",fromStandardTextBlock(t){return{type:"text",text:t.text,..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}}},fromStandardImageBlock(t){if(t.source_type==="url"){const e=nn({dataUrl:t.url,asTypedArray:!1});return e?{type:"image",source:{type:"base64",data:e.data,media_type:e.mime_type},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}}:{type:"image",source:{type:"url",url:t.url},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}}}else{if(t.source_type==="base64")return{type:"image",source:{type:"base64",data:t.data,media_type:t.mime_type??""},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}};throw new Error(`Unsupported image source type: ${t.source_type}`)}},fromStandardFileBlock(t){const e=(t.mime_type??"").split(";")[0];if(t.source_type==="url"){if(e==="application/pdf"||e==="")return{type:"document",source:{type:"url",url:t.url},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};throw new Error(`Unsupported file mime type for file url source: ${t.mime_type}`)}else if(t.source_type==="text"){if(e==="text/plain"||e==="")return{type:"document",source:{type:"text",data:t.text,media_type:t.mime_type??""},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};throw new Error(`Unsupported file mime type for file text source: ${t.mime_type}`)}else if(t.source_type==="base64"){if(e==="application/pdf"||e==="")return{type:"document",source:{type:"base64",data:t.data,media_type:"application/pdf"},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};if(["image/jpeg","image/png","image/gif","image/webp"].includes(e))return{type:"document",source:{type:"content",content:[{type:"image",source:{type:"base64",data:t.data,media_type:e}}]},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};throw new Error(`Unsupported file mime type for file base64 source: ${t.mime_type}`)}else throw new Error(`Unsupported file source type: ${t.source_type}`)}},Gn=t=>t();function Yn(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="citation"}function Zn(t){function*e(){for(const n of t)Yn(n)&&(n.source==="char"?yield{type:"char_location",file_id:n.url??"",start_char_index:n.startIndex??0,end_char_index:n.endIndex??0,document_title:n.title??null,document_index:0,cited_text:n.citedText??""}:n.source==="page"?yield{type:"page_location",file_id:n.url??"",start_page_number:n.startIndex??0,end_page_number:n.endIndex??0,document_title:n.title??null,document_index:0,cited_text:n.citedText??""}:n.source==="block"?yield{type:"content_block_location",file_id:n.url??"",start_block_index:n.startIndex??0,end_block_index:n.endIndex??0,document_title:n.title??null,document_index:0,cited_text:n.citedText??""}:n.source==="url"?yield{type:"web_search_result_location",url:n.url??"",title:n.title??null,encrypted_index:String(n.startIndex??0),cited_text:n.citedText??""}:n.source==="search"&&(yield{type:"search_result_location",title:n.title??null,start_block_index:n.startIndex??0,end_block_index:n.endIndex??0,search_result_index:0,source:n.source??"",cited_text:n.citedText??""}))}return Array.from(e())}function G(t){return typeof t=="string"?t:es(t)}function es(t){const e=[];for(let n=0,{length:s}=t;n<s;n++)e.push(String.fromCharCode(t[n]));return btoa(e.join(""))}function Ve(t){return(t??"").split(";")[0].toLowerCase()}function he(t,e){if(t!=null&&typeof t=="object"&&e in t)return t[e]}function H(t,e){const n=he(e,"cache_control");n!==void 0&&(t.cache_control=n);const s=he(e,"citations");s!==void 0&&(t.citations=s);const r=he(e,"context");r!==void 0&&(t.context=r);const i=he(e,"title");return i!==void 0&&(t.title=i),t}function Qe(t,e){const n=he(e,"cache_control");return n!==void 0&&(t.cache_control=n),t}function At(t){return new Set(["image/jpeg","image/png","image/gif","image/webp"]).has(t)}function ts(t){const e=[],n=t.response_metadata,s="model_provider"in n&&n?.model_provider==="anthropic";for(const r of t.contentBlocks)if(r.type==="text")r.annotations?e.push({type:"text",text:r.text,citations:Zn(r.annotations)}):e.push({type:"text",text:r.text});else if(r.type==="tool_call")e.push({type:"tool_use",id:r.id??"",name:r.name,input:r.args});else if(r.type==="tool_call_chunk"){const i=Gn(()=>{if(typeof r.args!="string")return r.args;try{return JSON.parse(r.args)}catch{return{}}});e.push({type:"tool_use",id:r.id??"",name:r.name??"",input:i})}else if(r.type==="reasoning"&&s)e.push({type:"thinking",thinking:r.reasoning,signature:String(r.signature)});else if(r.type==="server_tool_call"&&s)r.name==="web_search"?e.push({type:"server_tool_use",name:r.name,id:r.id??"",input:r.args}):r.name==="code_execution"&&e.push({type:"server_tool_use",name:r.name,id:r.id??"",input:r.args});else if(r.type==="server_tool_call_result"&&s)if(r.name==="web_search"&&Array.isArray(r.output.urls)){const i=r.output.urls.map(a=>({type:"web_search_result",title:"",encrypted_content:"",url:a}));e.push({type:"web_search_tool_result",tool_use_id:r.toolCallId??"",content:i})}else r.name==="code_execution"?e.push({type:"code_execution_tool_result",tool_use_id:r.toolCallId??"",content:r.output}):r.name==="mcp_tool_result"&&e.push({type:"mcp_tool_result",tool_use_id:r.toolCallId??"",content:r.output});else{if(r.type==="audio")throw new Error("Anthropic does not support audio content blocks.");if(r.type==="file"){const i=r.metadata;if(r.fileId){e.push(H({type:"document",source:{type:"file",file_id:r.fileId}},i));continue}if(r.url){const a=Ve(r.mimeType);if(a==="application/pdf"||a===""){e.push(H({type:"document",source:{type:"url",url:r.url}},i));continue}}if(r.data){const a=Ve(r.mimeType);if(a===""||a==="application/pdf")e.push(H({type:"document",source:{type:"base64",data:G(r.data),media_type:"application/pdf"}},i));else if(a==="text/plain")e.push(H({type:"document",source:{type:"text",data:G(r.data),media_type:"text/plain"}},i));else if(At(a))e.push(H({type:"document",source:{type:"content",content:[{type:"image",source:{type:"base64",data:G(r.data),media_type:a}}]}},i));else throw new Error(`Unsupported file mime type for Anthropic base64 source: ${a}`);continue}throw new Error("File content block must include a fileId, url, or data property.")}else if(r.type==="image"){const i=r.metadata;if(r.fileId){e.push(Qe({type:"image",source:{type:"file",file_id:r.fileId}},i));continue}if(r.url){e.push(Qe({type:"image",source:{type:"url",url:r.url}},i));continue}if(r.data){const a=Ve(r.mimeType)||"image/png";At(a)&&e.push(Qe({type:"image",source:{type:"base64",data:G(r.data),media_type:a}},i));continue}throw new Error("Image content block must include a fileId, url, or data property.")}else r.type==="video"||(r.type==="text-plain"?r.data&&e.push(H({type:"document",source:{type:"text",data:G(r.data),media_type:"text/plain"}},r.metadata)):r.type==="non_standard"&&s&&e.push(r.value))}return e}function vt(t){const e=nn({dataUrl:t});if(e)return{type:"base64",media_type:e.mime_type,data:e.data};let n;try{n=new URL(t)}catch{throw new Error([`Malformed image URL: ${JSON.stringify(t)}. Content blocks of type 'image_url' must be a valid http, https, or base64-encoded data URL.`,"Example: data:image/png;base64,/9j/4AAQSk...","Example: https://example.com/image.jpg"].join(`
|
|
2
2
|
|
|
3
3
|
`))}if(n.protocol==="http:"||n.protocol==="https:")return{type:"url",url:t};throw new Error([`Invalid image URL protocol: ${JSON.stringify(n.protocol)}. Anthropic only supports images as http, https, or base64-encoded data URLs on 'image_url' content blocks.`,"Example: data:image/png;base64,/9j/4AAQSk...","Example: https://example.com/image.jpg"].join(`
|
|
4
4
|
|
|
@@ -22,4 +22,4 @@ If you understand the risks and have appropriate mitigations in place,
|
|
|
22
22
|
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
|
|
23
23
|
|
|
24
24
|
new Anthropic({ apiKey, dangerouslyAllowBrowser: true });
|
|
25
|
-
`);this.baseURL=i.baseURL,this.timeout=i.timeout??gt.DEFAULT_TIMEOUT,this.logger=i.logger??console;const a="warn";this.logLevel=a,this.logLevel=qt(i.logLevel,"ClientOptions.logLevel",this)??qt(Le("ANTHROPIC_LOG"),"process.env['ANTHROPIC_LOG']",this)??a,this.fetchOptions=i.fetchOptions,this.maxRetries=i.maxRetries??2,this.fetch=i.fetch??ys(),u(this,qe,bs),this._options=i,this.apiKey=n,this.authToken=s}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,authToken:this.authToken,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:n}){if(!(this.apiKey&&e.get("x-api-key"))&&!n.has("x-api-key")&&!(this.authToken&&e.get("authorization"))&&!n.has("authorization"))throw new Error('Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted')}async authHeaders(e){return g([await this.apiKeyAuth(e),await this.bearerAuth(e)])}async apiKeyAuth(e){if(this.apiKey!=null)return g([{"X-Api-Key":this.apiKey}])}async bearerAuth(e){if(this.authToken!=null)return g([{Authorization:`Bearer ${this.authToken}`}])}stringifyQuery(e){return Object.entries(e).filter(([n,s])=>typeof s<"u").map(([n,s])=>{if(typeof s=="string"||typeof s=="number"||typeof s=="boolean")return`${encodeURIComponent(n)}=${encodeURIComponent(s)}`;if(s===null)return`${encodeURIComponent(n)}=`;throw new p(`Cannot stringify type ${typeof s}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}getUserAgent(){return`${this.constructor.name}/JS ${z}`}defaultIdempotencyKey(){return`stainless-node-retry-${rn()}`}makeStatusError(e,n,s,r){return w.generate(e,n,s,r)}buildURL(e,n,s){const r=!o(this,dt,"m",Nn).call(this)&&s||this.baseURL,i=cs(e)?new URL(e):new URL(r+(r.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),a=this.defaultQuery();return ls(a)||(n={...a,...n}),typeof n=="object"&&n&&!Array.isArray(n)&&(i.search=this.stringifyQuery(n)),i.toString()}_calculateNonstreamingTimeout(e){if(3600*e/128e3>600)throw new p("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details");return 600*1e3}async prepareOptions(e){}async prepareRequest(e,{url:n,options:s}){}get(e,n){return this.methodRequest("get",e,n)}post(e,n){return this.methodRequest("post",e,n)}patch(e,n){return this.methodRequest("patch",e,n)}put(e,n){return this.methodRequest("put",e,n)}delete(e,n){return this.methodRequest("delete",e,n)}methodRequest(e,n,s){return this.request(Promise.resolve(s).then(r=>({method:e,path:n,...r})))}request(e,n=null){return new Ke(this,this.makeRequest(e,n,void 0))}async makeRequest(e,n,s){const r=await e,i=r.maxRetries??this.maxRetries;n==null&&(n=i),await this.prepareOptions(r);const{req:a,url:c,timeout:l}=await this.buildRequest(r,{retryCount:i-n});await this.prepareRequest(a,{url:c,options:r});const d="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),f=s===void 0?"":`, retryOf: ${s}`,m=Date.now();if(x(this).debug(`[${d}] sending request`,D({retryOfRequestLogID:s,method:r.method,url:c,options:r,headers:a.headers})),r.signal?.aborted)throw new v;const _=new AbortController,h=await this.fetchWithTimeout(c,a,l,_).catch(ot),b=Date.now();if(h instanceof globalThis.Error){const I=`retrying, ${n} attempts remaining`;if(r.signal?.aborted)throw new v;const P=fe(h)||/timed? ?out/i.test(String(h)+("cause"in h?String(h.cause):""));if(n)return x(this).info(`[${d}] connection ${P?"timed out":"failed"} - ${I}`),x(this).debug(`[${d}] connection ${P?"timed out":"failed"} (${I})`,D({retryOfRequestLogID:s,url:c,durationMs:b-m,message:h.message})),this.retryRequest(r,n,s??d);throw x(this).info(`[${d}] connection ${P?"timed out":"failed"} - error; no more retries left`),x(this).debug(`[${d}] connection ${P?"timed out":"failed"} (error; no more retries left)`,D({retryOfRequestLogID:s,url:c,durationMs:b-m,message:h.message})),P?new an:new He({cause:h})}const W=[...h.headers.entries()].filter(([I])=>I==="request-id").map(([I,P])=>", "+I+": "+JSON.stringify(P)).join(""),ze=`[${d}${f}${W}] ${a.method} ${c} ${h.ok?"succeeded":"failed"} with status ${h.status} in ${b-m}ms`;if(!h.ok){const I=await this.shouldRetry(h);if(n&&I){const we=`retrying, ${n} attempts remaining`;return await ws(h.body),x(this).info(`${ze} - ${we}`),x(this).debug(`[${d}] response error (${we})`,D({retryOfRequestLogID:s,url:h.url,status:h.status,headers:h.headers,durationMs:b-m})),this.retryRequest(r,n,s??d,h.headers)}const P=I?"error; no more retries left":"error; not retryable";x(this).info(`${ze} - ${P}`);const _t=await h.text().catch(we=>ot(we).message),yt=mn(_t),wt=yt?void 0:_t;throw x(this).debug(`[${d}] response error (${P})`,D({retryOfRequestLogID:s,url:h.url,status:h.status,headers:h.headers,message:wt,durationMs:Date.now()-m})),this.makeStatusError(h.status,yt,wt,h.headers)}return x(this).info(ze),x(this).debug(`[${d}] response start`,D({retryOfRequestLogID:s,url:h.url,status:h.status,headers:h.headers,durationMs:b-m})),{response:h,options:r,controller:_,requestLogID:d,retryOfRequestLogID:s,startTime:m}}getAPIList(e,n,s){return this.requestAPIList(n,{method:"get",path:e,...s})}requestAPIList(e,n){const s=this.makeRequest(n,null,void 0);return new Ps(this,s,e)}async fetchWithTimeout(e,n,s,r){const{signal:i,method:a,...c}=n||{};i&&i.addEventListener("abort",()=>r.abort());const l=setTimeout(()=>r.abort(),s),d=globalThis.ReadableStream&&c.body instanceof globalThis.ReadableStream||typeof c.body=="object"&&c.body!==null&&Symbol.asyncIterator in c.body,f={signal:r.signal,...d?{duplex:"half"}:{},method:"GET",...c};a&&(f.method=a.toUpperCase());try{return await this.fetch.call(void 0,e,f)}finally{clearTimeout(l)}}async shouldRetry(e){const n=e.headers.get("x-should-retry");return n==="true"?!0:n==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,n,s,r){let i;const a=r?.get("retry-after-ms");if(a){const l=parseFloat(a);Number.isNaN(l)||(i=l)}const c=r?.get("retry-after");if(c&&!i){const l=parseFloat(c);Number.isNaN(l)?i=Date.parse(c)-Date.now():i=l*1e3}if(!(i&&0<=i&&i<60*1e3)){const l=e.maxRetries??this.maxRetries;i=this.calculateDefaultRetryTimeoutMillis(n,l)}return await ds(i),this.makeRequest(e,n-1,s)}calculateDefaultRetryTimeoutMillis(e,n){const i=n-e,a=Math.min(.5*Math.pow(2,i),8),c=1-Math.random()*.25;return a*c*1e3}calculateNonstreamingTimeout(e,n){if(36e5*e/128e3>6e5||n!=null&&e>n)throw new p("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#long-requests for more details");return 6e5}async buildRequest(e,{retryCount:n=0}={}){const s={...e},{method:r,path:i,query:a,defaultBaseURL:c}=s,l=this.buildURL(i,a,c);"timeout"in s&&hs("timeout",s.timeout),s.timeout=s.timeout??this.timeout;const{bodyHeaders:d,body:f}=this.buildBody({options:s}),m=await this.buildHeaders({options:e,method:r,bodyHeaders:d,retryCount:n});return{req:{method:r,headers:m,...s.signal&&{signal:s.signal},...globalThis.ReadableStream&&f instanceof globalThis.ReadableStream&&{duplex:"half"},...f&&{body:f},...this.fetchOptions??{},...s.fetchOptions??{}},url:l,timeout:s.timeout}}async buildHeaders({options:e,method:n,bodyHeaders:s,retryCount:r}){let i={};this.idempotencyHeader&&n!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),i[this.idempotencyHeader]=e.idempotencyKey);const a=g([i,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(r),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},..._s(),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":"true"}:void 0,"anthropic-version":"2023-06-01"},await this.authHeaders(e),this._options.defaultHeaders,s,e.headers]);return this.validateHeaders(a),a.values}buildBody({options:{body:e,headers:n}}){if(!e)return{bodyHeaders:void 0,body:void 0};const s=g([n]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&s.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:_n(e)}:o(this,qe,"f").call(this,{body:e,headers:s})}}gt=y,qe=new WeakMap,dt=new WeakSet,Nn=function(){return this.baseURL!=="https://api.anthropic.com"};y.Anthropic=gt;y.HUMAN_PROMPT=Js;y.AI_PROMPT=Xs;y.DEFAULT_TIMEOUT=6e5;y.AnthropicError=p;y.APIError=w;y.APIConnectionError=He;y.APIConnectionTimeoutError=an;y.APIUserAbortError=v;y.NotFoundError=un;y.ConflictError=hn;y.RateLimitError=pn;y.BadRequestError=on;y.AuthenticationError=cn;y.InternalServerError=fn;y.PermissionDeniedError=ln;y.UnprocessableEntityError=dn;y.toFile=Bs;class ye extends y{constructor(){super(...arguments),this.completions=new On(this),this.messages=new mt(this),this.models=new In(this),this.beta=new _e(this)}}ye.Completions=On;ye.Messages=mt;ye.Models=In;ye.Beta=_e;const zs={"claude-opus-4-1":8192,"claude-opus-4":8192,"claude-sonnet-4":8192,"claude-sonnet-3-7-sonnet":8192,"claude-3-5-sonnet":4096,"claude-3-5-haiku":4096,"claude-3-haiku":2048},tn=2048;function Vs(t){return t?Object.entries(zs).find(([n])=>t.startsWith(n))?.[1]??tn:tn}function Qs(t){return!!(t.tools&&t.tools.length>0)}function Gs(t){for(const e of t.messages??[])if(typeof e.content!="string"){for(const n of e.content??[])if(typeof n=="object"&&n!=null&&n.type==="document"&&typeof n.citations=="object"&&n.citations?.enabled)return!0}return!1}function Ys(t){return!!(t.thinking&&t.thinking.type==="enabled")}function Zs(t){return"input_schema"in t}function er(t){const e=["text_editor_","computer_","bash_","web_search_","web_fetch_","str_replace_editor_","str_replace_based_edit_tool_","code_execution_","memory_"];return typeof t=="object"&&t!==null&&"type"in t&&"name"in t&&typeof t.type=="string"&&e.some(n=>typeof t.type=="string"&&t.type.startsWith(n))}function tr(t){if(typeof t.content=="string")return t.content;if(Array.isArray(t.content)&&t.content.length>=1&&"input"in t.content[0])return typeof t.content[0].input=="string"?t.content[0].input:JSON.stringify(t.content[0].input);if(Array.isArray(t.content)&&t.content.length>=1&&"text"in t.content[0]&&typeof t.content[0].text=="string")return t.content[0].text}var nr=class extends Un{static lc_name(){return"ChatAnthropic"}get lc_secrets(){return{anthropicApiKey:"ANTHROPIC_API_KEY",apiKey:"ANTHROPIC_API_KEY"}}get lc_aliases(){return{modelName:"model"}}lc_serializable=!0;anthropicApiKey;apiKey;apiUrl;temperature;topK;topP;maxTokens;modelName="claude-3-5-sonnet-latest";model="claude-3-5-sonnet-latest";invocationKwargs;stopSequences;streaming=!1;clientOptions;thinking={type:"disabled"};contextManagement;batchClient;streamingClient;streamUsage=!0;createClient;constructor(t){if(super(t??{}),this.anthropicApiKey=t?.apiKey??t?.anthropicApiKey??qn("ANTHROPIC_API_KEY"),!this.anthropicApiKey&&!t?.createClient)throw new Error("Anthropic API key not found");this.clientOptions=t?.clientOptions??{},this.apiKey=this.anthropicApiKey,this.apiUrl=t?.anthropicApiUrl,this.modelName=t?.model??t?.modelName??this.model,this.model=this.modelName,this.invocationKwargs=t?.invocationKwargs??{},this.topP=t?.topP??this.topP,this.temperature=t?.temperature??this.temperature,this.topK=t?.topK??this.topK,this.maxTokens=t?.maxTokens??Vs(this.model),this.stopSequences=t?.stopSequences??this.stopSequences,this.streaming=t?.streaming??!1,this.streamUsage=t?.streamUsage??this.streamUsage,this.thinking=t?.thinking??this.thinking,this.contextManagement=t?.contextManagement??this.contextManagement,this.createClient=t?.createClient??(e=>new ye(e))}getLsParams(t){const e=this.invocationParams(t);return{ls_provider:"anthropic",ls_model_name:this.model,ls_model_type:"chat",ls_temperature:e.temperature??void 0,ls_max_tokens:e.max_tokens??void 0,ls_stop:t.stop}}formatStructuredToolToAnthropic(t){if(!(!t||!t.length))return t.map(e=>{if(er(e)||Zs(e))return e;if(Wn(e))return{name:e.function.name,description:e.function.description,input_schema:e.function.parameters};if(Fn(e))return{name:e.name,description:e.description,input_schema:Mt(e.schema)?be(e.schema):e.schema};throw new Error(`Unknown tool type passed to ChatAnthropic: ${JSON.stringify(e,null,2)}`)})}bindTools(t,e){return this.withConfig({tools:this.formatStructuredToolToAnthropic(t),...e})}invocationParams(t){const e=Kn(t?.tool_choice);if(this.thinking.type==="enabled"){if(this.topP!==void 0&&this.topK!==-1)throw new Error("topK is not supported when thinking is enabled");if(this.temperature!==void 0&&this.temperature!==1)throw new Error("temperature is not supported when thinking is enabled");return{model:this.model,stop_sequences:t?.stop??this.stopSequences,stream:this.streaming,max_tokens:this.maxTokens,tools:this.formatStructuredToolToAnthropic(t?.tools),tool_choice:e,thinking:this.thinking,context_management:this.contextManagement,...this.invocationKwargs,container:t?.container}}return{model:this.model,temperature:this.temperature,top_k:this.topK,top_p:this.topP,stop_sequences:t?.stop??this.stopSequences,stream:this.streaming,max_tokens:this.maxTokens,tools:this.formatStructuredToolToAnthropic(t?.tools),tool_choice:e,thinking:this.thinking,context_management:this.contextManagement,...this.invocationKwargs,container:t?.container}}_identifyingParams(){return{model_name:this.model,...this.invocationParams()}}identifyingParams(){return{model_name:this.model,...this.invocationParams()}}async*_streamResponseChunks(t,e,n){const s=this.invocationParams(e),r=Pt(t),i={...s,...r,stream:!0},a=!Qs(i)&&!Gs(i)&&!Ys(i),c=await this.createStreamWithRetry(i,{headers:e.headers});for await(const l of c){if(e.signal?.aborted)throw c.controller.abort(),new Error("AbortError: User aborted the request.");const d=this.streamUsage??e.streamUsage,f=is(l,{streamUsage:d,coerceContentToString:a});if(!f)continue;const{chunk:m}=f,_=tr(m),h=new Dn({message:new A({content:m.content,additional_kwargs:m.additional_kwargs,tool_call_chunks:m.tool_call_chunks,usage_metadata:d?m.usage_metadata:void 0,response_metadata:m.response_metadata,id:m.id}),text:_??""});yield h,await n?.handleLLMNewToken(_??"",void 0,void 0,void 0,void 0,{chunk:h})}}async _generateNonStreaming(t,e,n){const s=await this.completionWithRetry({...e,stream:!1,...Pt(t)},n),{content:r,...i}=s,a=as(r,i),{role:c,type:l,...d}=i;return{generations:a,llmOutput:d}}async _generate(t,e,n){if(this.stopSequences&&e.stop)throw new Error('"stopSequence" parameter found in input and default params');const s=this.invocationParams(e);if(s.stream){let r;const i=this._streamResponseChunks(t,e,n);for await(const a of i)r===void 0?r=a:r=r.concat(a);if(r===void 0)throw new Error("No chunks returned from Anthropic API.");return{generations:[{text:r.text,message:r.message}]}}else return this._generateNonStreaming(t,s,{signal:e.signal,headers:e.headers})}async createStreamWithRetry(t,e){if(!this.streamingClient){const s=this.apiUrl?{baseURL:this.apiUrl}:void 0;this.streamingClient=this.createClient({dangerouslyAllowBrowser:!0,...this.clientOptions,...s,apiKey:this.apiKey,maxRetries:0})}const n=async()=>{try{return await this.streamingClient.messages.create({...t,...this.invocationKwargs,stream:!0},e)}catch(s){throw Ot(s)}};return this.caller.call(n)}async completionWithRetry(t,e){if(!this.batchClient){const s=this.apiUrl?{baseURL:this.apiUrl}:void 0;this.batchClient=this.createClient({dangerouslyAllowBrowser:!0,...this.clientOptions,...s,apiKey:this.apiKey,maxRetries:0})}const n=async()=>{try{return await this.batchClient.messages.create({...t,...this.invocationKwargs},e)}catch(s){throw Ot(s)}};return this.caller.callWithOptions({signal:e.signal??void 0},n)}_llmType(){return"anthropic"}withStructuredOutput(t,e){const n=t,s=e?.name,r=e?.method,i=e?.includeRaw;if(r==="jsonMode")throw new Error('Anthropic only supports "functionCalling" as a method.');let a=s??"extract",c,l;if(Mt(n)){const h=be(n);l=[{name:a,description:h.description??"A function available to call.",input_schema:h}],c=new Rt({returnSingle:!0,keyName:a,zodSchema:n})}else{let h;typeof n.name=="string"&&typeof n.description=="string"&&typeof n.input_schema=="object"&&n.input_schema!=null?(h=n,a=n.name):h={name:a,description:n.description??"",input_schema:n},l=[h],c=new Rt({returnSingle:!0,keyName:a})}let d;if(this.thinking?.type==="enabled"){const h="Anthropic structured output relies on forced tool calling, which is not supported when `thinking` is enabled. This method will raise OutputParserException if tool calls are not generated. Consider disabling `thinking` or adjust your prompt to ensure the tool is called.";console.warn(h),d=this.withConfig({outputVersion:"v0",tools:l,ls_structured_output_format:{kwargs:{method:"functionCalling"},schema:be(n)}});const b=W=>{if(!W.tool_calls||W.tool_calls.length===0)throw new Error(h);return W};d=d.pipe(b)}else d=this.withConfig({outputVersion:"v0",tools:l,tool_choice:{type:"tool",name:a},ls_structured_output_format:{kwargs:{method:"functionCalling"},schema:be(n)}});if(!i)return d.pipe(c).withConfig({runName:"ChatAnthropicStructuredOutput"});const f=Tt.assign({parsed:(h,b)=>c.invoke(h.raw,b)}),m=Tt.assign({parsed:()=>null}),_=f.withFallbacks({fallbacks:[m]});return Hn.from([{raw:d},_]).withConfig({runName:"StructuredOutputRunnable"})}},ur=class extends nr{};export{ur as ChatAnthropic,nr as ChatAnthropicMessages};
|
|
25
|
+
`);this.baseURL=i.baseURL,this.timeout=i.timeout??gt.DEFAULT_TIMEOUT,this.logger=i.logger??console;const a="warn";this.logLevel=a,this.logLevel=qt(i.logLevel,"ClientOptions.logLevel",this)??qt(Le("ANTHROPIC_LOG"),"process.env['ANTHROPIC_LOG']",this)??a,this.fetchOptions=i.fetchOptions,this.maxRetries=i.maxRetries??2,this.fetch=i.fetch??ys(),u(this,qe,bs),this._options=i,this.apiKey=n,this.authToken=s}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,authToken:this.authToken,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:n}){if(!(this.apiKey&&e.get("x-api-key"))&&!n.has("x-api-key")&&!(this.authToken&&e.get("authorization"))&&!n.has("authorization"))throw new Error('Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted')}async authHeaders(e){return g([await this.apiKeyAuth(e),await this.bearerAuth(e)])}async apiKeyAuth(e){if(this.apiKey!=null)return g([{"X-Api-Key":this.apiKey}])}async bearerAuth(e){if(this.authToken!=null)return g([{Authorization:`Bearer ${this.authToken}`}])}stringifyQuery(e){return Object.entries(e).filter(([n,s])=>typeof s<"u").map(([n,s])=>{if(typeof s=="string"||typeof s=="number"||typeof s=="boolean")return`${encodeURIComponent(n)}=${encodeURIComponent(s)}`;if(s===null)return`${encodeURIComponent(n)}=`;throw new p(`Cannot stringify type ${typeof s}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}getUserAgent(){return`${this.constructor.name}/JS ${z}`}defaultIdempotencyKey(){return`stainless-node-retry-${rn()}`}makeStatusError(e,n,s,r){return w.generate(e,n,s,r)}buildURL(e,n,s){const r=!o(this,dt,"m",Nn).call(this)&&s||this.baseURL,i=cs(e)?new URL(e):new URL(r+(r.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),a=this.defaultQuery();return ls(a)||(n={...a,...n}),typeof n=="object"&&n&&!Array.isArray(n)&&(i.search=this.stringifyQuery(n)),i.toString()}_calculateNonstreamingTimeout(e){if(3600*e/128e3>600)throw new p("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details");return 600*1e3}async prepareOptions(e){}async prepareRequest(e,{url:n,options:s}){}get(e,n){return this.methodRequest("get",e,n)}post(e,n){return this.methodRequest("post",e,n)}patch(e,n){return this.methodRequest("patch",e,n)}put(e,n){return this.methodRequest("put",e,n)}delete(e,n){return this.methodRequest("delete",e,n)}methodRequest(e,n,s){return this.request(Promise.resolve(s).then(r=>({method:e,path:n,...r})))}request(e,n=null){return new Ke(this,this.makeRequest(e,n,void 0))}async makeRequest(e,n,s){const r=await e,i=r.maxRetries??this.maxRetries;n==null&&(n=i),await this.prepareOptions(r);const{req:a,url:c,timeout:l}=await this.buildRequest(r,{retryCount:i-n});await this.prepareRequest(a,{url:c,options:r});const d="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),f=s===void 0?"":`, retryOf: ${s}`,m=Date.now();if(x(this).debug(`[${d}] sending request`,D({retryOfRequestLogID:s,method:r.method,url:c,options:r,headers:a.headers})),r.signal?.aborted)throw new v;const _=new AbortController,h=await this.fetchWithTimeout(c,a,l,_).catch(ot),b=Date.now();if(h instanceof globalThis.Error){const I=`retrying, ${n} attempts remaining`;if(r.signal?.aborted)throw new v;const P=fe(h)||/timed? ?out/i.test(String(h)+("cause"in h?String(h.cause):""));if(n)return x(this).info(`[${d}] connection ${P?"timed out":"failed"} - ${I}`),x(this).debug(`[${d}] connection ${P?"timed out":"failed"} (${I})`,D({retryOfRequestLogID:s,url:c,durationMs:b-m,message:h.message})),this.retryRequest(r,n,s??d);throw x(this).info(`[${d}] connection ${P?"timed out":"failed"} - error; no more retries left`),x(this).debug(`[${d}] connection ${P?"timed out":"failed"} (error; no more retries left)`,D({retryOfRequestLogID:s,url:c,durationMs:b-m,message:h.message})),P?new an:new He({cause:h})}const W=[...h.headers.entries()].filter(([I])=>I==="request-id").map(([I,P])=>", "+I+": "+JSON.stringify(P)).join(""),ze=`[${d}${f}${W}] ${a.method} ${c} ${h.ok?"succeeded":"failed"} with status ${h.status} in ${b-m}ms`;if(!h.ok){const I=await this.shouldRetry(h);if(n&&I){const we=`retrying, ${n} attempts remaining`;return await ws(h.body),x(this).info(`${ze} - ${we}`),x(this).debug(`[${d}] response error (${we})`,D({retryOfRequestLogID:s,url:h.url,status:h.status,headers:h.headers,durationMs:b-m})),this.retryRequest(r,n,s??d,h.headers)}const P=I?"error; no more retries left":"error; not retryable";x(this).info(`${ze} - ${P}`);const _t=await h.text().catch(we=>ot(we).message),yt=mn(_t),wt=yt?void 0:_t;throw x(this).debug(`[${d}] response error (${P})`,D({retryOfRequestLogID:s,url:h.url,status:h.status,headers:h.headers,message:wt,durationMs:Date.now()-m})),this.makeStatusError(h.status,yt,wt,h.headers)}return x(this).info(ze),x(this).debug(`[${d}] response start`,D({retryOfRequestLogID:s,url:h.url,status:h.status,headers:h.headers,durationMs:b-m})),{response:h,options:r,controller:_,requestLogID:d,retryOfRequestLogID:s,startTime:m}}getAPIList(e,n,s){return this.requestAPIList(n,{method:"get",path:e,...s})}requestAPIList(e,n){const s=this.makeRequest(n,null,void 0);return new Ps(this,s,e)}async fetchWithTimeout(e,n,s,r){const{signal:i,method:a,...c}=n||{};i&&i.addEventListener("abort",()=>r.abort());const l=setTimeout(()=>r.abort(),s),d=globalThis.ReadableStream&&c.body instanceof globalThis.ReadableStream||typeof c.body=="object"&&c.body!==null&&Symbol.asyncIterator in c.body,f={signal:r.signal,...d?{duplex:"half"}:{},method:"GET",...c};a&&(f.method=a.toUpperCase());try{return await this.fetch.call(void 0,e,f)}finally{clearTimeout(l)}}async shouldRetry(e){const n=e.headers.get("x-should-retry");return n==="true"?!0:n==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,n,s,r){let i;const a=r?.get("retry-after-ms");if(a){const l=parseFloat(a);Number.isNaN(l)||(i=l)}const c=r?.get("retry-after");if(c&&!i){const l=parseFloat(c);Number.isNaN(l)?i=Date.parse(c)-Date.now():i=l*1e3}if(!(i&&0<=i&&i<60*1e3)){const l=e.maxRetries??this.maxRetries;i=this.calculateDefaultRetryTimeoutMillis(n,l)}return await ds(i),this.makeRequest(e,n-1,s)}calculateDefaultRetryTimeoutMillis(e,n){const i=n-e,a=Math.min(.5*Math.pow(2,i),8),c=1-Math.random()*.25;return a*c*1e3}calculateNonstreamingTimeout(e,n){if(36e5*e/128e3>6e5||n!=null&&e>n)throw new p("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#long-requests for more details");return 6e5}async buildRequest(e,{retryCount:n=0}={}){const s={...e},{method:r,path:i,query:a,defaultBaseURL:c}=s,l=this.buildURL(i,a,c);"timeout"in s&&hs("timeout",s.timeout),s.timeout=s.timeout??this.timeout;const{bodyHeaders:d,body:f}=this.buildBody({options:s}),m=await this.buildHeaders({options:e,method:r,bodyHeaders:d,retryCount:n});return{req:{method:r,headers:m,...s.signal&&{signal:s.signal},...globalThis.ReadableStream&&f instanceof globalThis.ReadableStream&&{duplex:"half"},...f&&{body:f},...this.fetchOptions??{},...s.fetchOptions??{}},url:l,timeout:s.timeout}}async buildHeaders({options:e,method:n,bodyHeaders:s,retryCount:r}){let i={};this.idempotencyHeader&&n!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),i[this.idempotencyHeader]=e.idempotencyKey);const a=g([i,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(r),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},..._s(),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":"true"}:void 0,"anthropic-version":"2023-06-01"},await this.authHeaders(e),this._options.defaultHeaders,s,e.headers]);return this.validateHeaders(a),a.values}buildBody({options:{body:e,headers:n}}){if(!e)return{bodyHeaders:void 0,body:void 0};const s=g([n]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&s.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:_n(e)}:o(this,qe,"f").call(this,{body:e,headers:s})}}gt=y,qe=new WeakMap,dt=new WeakSet,Nn=function(){return this.baseURL!=="https://api.anthropic.com"};y.Anthropic=gt;y.HUMAN_PROMPT=Js;y.AI_PROMPT=Xs;y.DEFAULT_TIMEOUT=6e5;y.AnthropicError=p;y.APIError=w;y.APIConnectionError=He;y.APIConnectionTimeoutError=an;y.APIUserAbortError=v;y.NotFoundError=un;y.ConflictError=hn;y.RateLimitError=pn;y.BadRequestError=on;y.AuthenticationError=cn;y.InternalServerError=fn;y.PermissionDeniedError=ln;y.UnprocessableEntityError=dn;y.toFile=Bs;class ye extends y{constructor(){super(...arguments),this.completions=new On(this),this.messages=new mt(this),this.models=new In(this),this.beta=new _e(this)}}ye.Completions=On;ye.Messages=mt;ye.Models=In;ye.Beta=_e;const zs={"claude-opus-4-1":8192,"claude-opus-4":8192,"claude-sonnet-4":8192,"claude-sonnet-3-7-sonnet":8192,"claude-3-5-sonnet":4096,"claude-3-5-haiku":4096,"claude-3-haiku":2048},tn=2048;function Vs(t){return t?Object.entries(zs).find(([n])=>t.startsWith(n))?.[1]??tn:tn}function Qs(t){return!!(t.tools&&t.tools.length>0)}function Gs(t){for(const e of t.messages??[])if(typeof e.content!="string"){for(const n of e.content??[])if(typeof n=="object"&&n!=null&&n.type==="document"&&typeof n.citations=="object"&&n.citations?.enabled)return!0}return!1}function Ys(t){return!!(t.thinking&&t.thinking.type==="enabled")}function Zs(t){return"input_schema"in t}function er(t){const e=["text_editor_","computer_","bash_","web_search_","web_fetch_","str_replace_editor_","str_replace_based_edit_tool_","code_execution_","memory_"];return typeof t=="object"&&t!==null&&"type"in t&&"name"in t&&typeof t.type=="string"&&e.some(n=>typeof t.type=="string"&&t.type.startsWith(n))}function tr(t){if(typeof t.content=="string")return t.content;if(Array.isArray(t.content)&&t.content.length>=1&&"input"in t.content[0])return typeof t.content[0].input=="string"?t.content[0].input:JSON.stringify(t.content[0].input);if(Array.isArray(t.content)&&t.content.length>=1&&"text"in t.content[0]&&typeof t.content[0].text=="string")return t.content[0].text}var nr=class extends Un{static lc_name(){return"ChatAnthropic"}get lc_secrets(){return{anthropicApiKey:"ANTHROPIC_API_KEY",apiKey:"ANTHROPIC_API_KEY"}}get lc_aliases(){return{modelName:"model"}}lc_serializable=!0;anthropicApiKey;apiKey;apiUrl;temperature;topK;topP;maxTokens;modelName="claude-3-5-sonnet-latest";model="claude-3-5-sonnet-latest";invocationKwargs;stopSequences;streaming=!1;clientOptions;thinking={type:"disabled"};contextManagement;batchClient;streamingClient;streamUsage=!0;createClient;constructor(t){if(super(t??{}),this.anthropicApiKey=t?.apiKey??t?.anthropicApiKey??qn("ANTHROPIC_API_KEY"),!this.anthropicApiKey&&!t?.createClient)throw new Error("Anthropic API key not found");this.clientOptions=t?.clientOptions??{},this.apiKey=this.anthropicApiKey,this.apiUrl=t?.anthropicApiUrl,this.modelName=t?.model??t?.modelName??this.model,this.model=this.modelName,this.invocationKwargs=t?.invocationKwargs??{},this.topP=t?.topP??this.topP,this.temperature=t?.temperature??this.temperature,this.topK=t?.topK??this.topK,this.maxTokens=t?.maxTokens??Vs(this.model),this.stopSequences=t?.stopSequences??this.stopSequences,this.streaming=t?.streaming??!1,this.streamUsage=t?.streamUsage??this.streamUsage,this.thinking=t?.thinking??this.thinking,this.contextManagement=t?.contextManagement??this.contextManagement,this.createClient=t?.createClient??(e=>new ye(e))}getLsParams(t){const e=this.invocationParams(t);return{ls_provider:"anthropic",ls_model_name:this.model,ls_model_type:"chat",ls_temperature:e.temperature??void 0,ls_max_tokens:e.max_tokens??void 0,ls_stop:t.stop}}formatStructuredToolToAnthropic(t){if(!(!t||!t.length))return t.map(e=>{if(er(e)||Zs(e))return e;if(Wn(e))return{name:e.function.name,description:e.function.description,input_schema:e.function.parameters};if(Fn(e))return{name:e.name,description:e.description,input_schema:Mt(e.schema)?be(e.schema):e.schema};throw new Error(`Unknown tool type passed to ChatAnthropic: ${JSON.stringify(e,null,2)}`)})}bindTools(t,e){return this.withConfig({tools:this.formatStructuredToolToAnthropic(t),...e})}invocationParams(t){const e=Kn(t?.tool_choice);if(this.thinking.type==="enabled"){if(this.topP!==void 0&&this.topK!==-1)throw new Error("topK is not supported when thinking is enabled");if(this.temperature!==void 0&&this.temperature!==1)throw new Error("temperature is not supported when thinking is enabled");return{model:this.model,stop_sequences:t?.stop??this.stopSequences,stream:this.streaming,max_tokens:this.maxTokens,tools:this.formatStructuredToolToAnthropic(t?.tools),tool_choice:e,thinking:this.thinking,context_management:this.contextManagement,...this.invocationKwargs,container:t?.container}}return{model:this.model,temperature:this.temperature,top_k:this.topK,top_p:this.topP,stop_sequences:t?.stop??this.stopSequences,stream:this.streaming,max_tokens:this.maxTokens,tools:this.formatStructuredToolToAnthropic(t?.tools),tool_choice:e,thinking:this.thinking,context_management:this.contextManagement,...this.invocationKwargs,container:t?.container}}_identifyingParams(){return{model_name:this.model,...this.invocationParams()}}identifyingParams(){return{model_name:this.model,...this.invocationParams()}}async*_streamResponseChunks(t,e,n){const s=this.invocationParams(e),r=Pt(t),i={...s,...r,stream:!0},a=!Qs(i)&&!Gs(i)&&!Ys(i),c=await this.createStreamWithRetry(i,{headers:e.headers});for await(const l of c){if(e.signal?.aborted)throw c.controller.abort(),new Error("AbortError: User aborted the request.");const d=this.streamUsage??e.streamUsage,f=is(l,{streamUsage:d,coerceContentToString:a});if(!f)continue;const{chunk:m}=f,_=tr(m),h=new Dn({message:new A({content:m.content,additional_kwargs:m.additional_kwargs,tool_call_chunks:m.tool_call_chunks,usage_metadata:d?m.usage_metadata:void 0,response_metadata:m.response_metadata,id:m.id}),text:_??""});yield h,await n?.handleLLMNewToken(_??"",void 0,void 0,void 0,void 0,{chunk:h})}}async _generateNonStreaming(t,e,n){const s=await this.completionWithRetry({...e,stream:!1,...Pt(t)},n),{content:r,...i}=s,a=as(r,i),{role:c,type:l,...d}=i;return{generations:a,llmOutput:d}}async _generate(t,e,n){if(this.stopSequences&&e.stop)throw new Error('"stopSequence" parameter found in input and default params');const s=this.invocationParams(e);if(s.stream){let r;const i=this._streamResponseChunks(t,e,n);for await(const a of i)r===void 0?r=a:r=r.concat(a);if(r===void 0)throw new Error("No chunks returned from Anthropic API.");return{generations:[{text:r.text,message:r.message}]}}else return this._generateNonStreaming(t,s,{signal:e.signal,headers:e.headers})}async createStreamWithRetry(t,e){if(!this.streamingClient){const s=this.apiUrl?{baseURL:this.apiUrl}:void 0;this.streamingClient=this.createClient({dangerouslyAllowBrowser:!0,...this.clientOptions,...s,apiKey:this.apiKey,maxRetries:0})}const n=async()=>{try{return await this.streamingClient.messages.create({...t,...this.invocationKwargs,stream:!0},e)}catch(s){throw Ot(s)}};return this.caller.call(n)}async completionWithRetry(t,e){if(!this.batchClient){const s=this.apiUrl?{baseURL:this.apiUrl}:void 0;this.batchClient=this.createClient({dangerouslyAllowBrowser:!0,...this.clientOptions,...s,apiKey:this.apiKey,maxRetries:0})}const n=async()=>{try{return await this.batchClient.messages.create({...t,...this.invocationKwargs},e)}catch(s){throw Ot(s)}};return this.caller.callWithOptions({signal:e.signal??void 0},n)}_llmType(){return"anthropic"}withStructuredOutput(t,e){const n=t,s=e?.name,r=e?.method,i=e?.includeRaw;if(r==="jsonMode")throw new Error('Anthropic only supports "functionCalling" as a method.');let a=s??"extract",c,l;if(Mt(n)){const h=be(n);l=[{name:a,description:h.description??"A function available to call.",input_schema:h}],c=new Rt({returnSingle:!0,keyName:a,zodSchema:n})}else{let h;typeof n.name=="string"&&typeof n.description=="string"&&typeof n.input_schema=="object"&&n.input_schema!=null?(h=n,a=n.name):h={name:a,description:n.description??"",input_schema:n},l=[h],c=new Rt({returnSingle:!0,keyName:a})}let d;if(this.thinking?.type==="enabled"){const h="Anthropic structured output relies on forced tool calling, which is not supported when `thinking` is enabled. This method will raise OutputParserException if tool calls are not generated. Consider disabling `thinking` or adjust your prompt to ensure the tool is called.";console.warn(h),d=this.withConfig({outputVersion:"v0",tools:l,ls_structured_output_format:{kwargs:{method:"functionCalling"},schema:be(n)}});const b=W=>{if(!W.tool_calls||W.tool_calls.length===0)throw new Error(h);return W};d=d.pipe(b)}else d=this.withConfig({outputVersion:"v0",tools:l,tool_choice:{type:"tool",name:a},ls_structured_output_format:{kwargs:{method:"functionCalling"},schema:be(n)}});if(!i)return d.pipe(c).withConfig({runName:"ChatAnthropicStructuredOutput"});const f=Tt.assign({parsed:(h,b)=>c.invoke(h.raw,b)}),m=Tt.assign({parsed:()=>null}),_=f.withFallbacks({fallbacks:[m]});return Hn.from([{raw:d},_]).withConfig({runName:"StructuredOutputRunnable"})}},hr=class extends nr{};export{hr as ChatAnthropic,nr as ChatAnthropicMessages};
|