@mcp-use/inspector 0.6.1 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/dist/cli.js +295 -19
  2. package/dist/client/assets/__vite-browser-external-CHS79mP1.js +8 -0
  3. package/dist/client/assets/browser-BdCJ_qyB.js +38211 -0
  4. package/dist/client/assets/chunk-VL2OQCWN-CxD8xDNw.js +6475 -0
  5. package/dist/client/assets/display-YIYC6WJE-B6ZSv77R.js +44742 -0
  6. package/dist/client/assets/embeddings-DlCMB9po.js +21 -0
  7. package/dist/client/assets/index-B0NYybvW.js +5371 -0
  8. package/dist/client/assets/index-CKXUnlZB.js +94617 -0
  9. package/dist/client/assets/index-Cb09SlUY.js +17535 -0
  10. package/dist/client/assets/index-CsP5AdwX.js +10699 -0
  11. package/dist/client/assets/index-DX0TIfSM.js +102 -0
  12. package/dist/client/assets/index-Q_pqNaNk.js +1780 -0
  13. package/dist/client/assets/index-kVFYovMy.css +5752 -0
  14. package/dist/client/assets/path-QsnVvLoj.js +62 -0
  15. package/dist/client/assets/transport-wrapper-browser-ChPHVnHg.js +165 -0
  16. package/dist/client/assets/winston-qgF6niUt.js +12326 -0
  17. package/dist/client/index.html +3 -3
  18. package/dist/server/{chunk-37X7HLUV.js → chunk-3T2VCYG6.js} +87 -13
  19. package/dist/server/chunk-CVECQ7BJ.js +78 -0
  20. package/dist/server/{chunk-555LGZ3I.js → chunk-FS77NTZN.js} +133 -10
  21. package/dist/server/chunk-PKBMQBKP.js +7 -0
  22. package/dist/server/{chunk-WYBXXYSP.js → chunk-RRPLH7DL.js} +1 -1
  23. package/dist/server/{chunk-PYGYQT2G.js → chunk-S7NOZBMG.js} +3 -3
  24. package/dist/server/{chunk-DGUMOD7P.js → chunk-ZONLXYBO.js} +92 -10
  25. package/dist/server/cli.js +6 -4
  26. package/dist/server/index.js +7 -5
  27. package/dist/server/middleware.js +7 -5
  28. package/dist/server/rpc-log-bus.d.ts +17 -0
  29. package/dist/server/rpc-log-bus.d.ts.map +1 -0
  30. package/dist/server/rpc-log-bus.js +7 -0
  31. package/dist/server/server.js +6 -4
  32. package/dist/server/shared-routes.d.ts.map +1 -1
  33. package/dist/server/shared-routes.js +4 -2
  34. package/dist/server/shared-static.js +3 -2
  35. package/dist/server/shared-utils-browser.d.ts +2 -1
  36. package/dist/server/shared-utils-browser.d.ts.map +1 -1
  37. package/dist/server/shared-utils-browser.js +2 -1
  38. package/dist/server/shared-utils.d.ts +4 -1
  39. package/dist/server/shared-utils.d.ts.map +1 -1
  40. package/dist/server/shared-utils.js +2 -1
  41. package/dist/server/transport-wrapper.d.ts +6 -0
  42. package/dist/server/transport-wrapper.d.ts.map +1 -0
  43. package/dist/server/transport-wrapper.js +68 -0
  44. package/dist/server/utils.js +1 -0
  45. package/package.json +12 -3
  46. package/dist/client/assets/__vite-browser-external-DFygW7-s.js +0 -1
  47. package/dist/client/assets/chunk-VL2OQCWN-iRVOQjqe.js +0 -8
  48. package/dist/client/assets/display-LIYVTGEU-D2dm8q2H.js +0 -30
  49. package/dist/client/assets/embeddings-Dcyp0Vlp.js +0 -1
  50. package/dist/client/assets/index-6zrNEwtM.js +0 -4
  51. package/dist/client/assets/index-CAnbiFOL.css +0 -1
  52. package/dist/client/assets/index-CB1s6Wr6.js +0 -146
  53. package/dist/client/assets/index-CoMldIFv.js +0 -2
  54. package/dist/client/assets/index-DRz5BQNA.js +0 -1
  55. package/dist/client/assets/index-DUf1336L.js +0 -1559
  56. package/dist/client/assets/index-DmIKR5St.js +0 -1
  57. package/dist/client/assets/index-DpUpZFq2.js +0 -25
  58. package/dist/client/assets/index-DzegZXPW.js +0 -40
  59. package/dist/client/assets/langfuse-C4HKZ3NL-vCtAvQQV.js +0 -564
  60. package/dist/client/assets/path-C9FudP8b.js +0 -1
  61. package/dist/client/assets/winston-BVJ8PyEn.js +0 -37
@@ -1 +0,0 @@
1
- import{m as B}from"./langfuse-C4HKZ3NL-vCtAvQQV.js";import"./index-DUf1336L.js";import"./chunk-VL2OQCWN-iRVOQjqe.js";import"./index-DRz5BQNA.js";import"./__vite-browser-external-DFygW7-s.js";import"./path-C9FudP8b.js";var J={};class ge{constructor(){this.events={},this.events={}}on(e,t){return this.events[e]||(this.events[e]=[]),this.events[e].push(t),()=>{this.events[e]=this.events[e].filter(s=>s!==t)}}emit(e,t){for(const s of this.events[e]||[])s(t);for(const s of this.events["*"]||[])s(e,t)}}const ye=60;class be{constructor(e,t){this.value=e,this._expiry=Date.now()+t*1e3}get isExpired(){return Date.now()>this._expiry}}class _e{constructor(){this._cache=new Map,this._defaultTtlSeconds=ye,this._refreshingKeys=new Map}getIncludingExpired(e){return this._cache.get(e)??null}set(e,t,s){const n=s??this._defaultTtlSeconds;this._cache.set(e,new be(t,n))}addRefreshingPromise(e,t){this._refreshingKeys.set(e,t),t.then(()=>{this._refreshingKeys.delete(e)}).catch(()=>{this._refreshingKeys.delete(e)})}isRefreshing(e){return this._refreshingKeys.has(e)}invalidate(e){console.log("invalidating",e,this._cache.keys());for(const t of this._cache.keys())t.startsWith(e)&&this._cache.delete(t)}}var I;(function(r){r.Props="props",r.Queue="queue",r.OptedOut="opted_out"})(I||(I={}));var b;(function(r){r.ChatMessage="chatmessage",r.Placeholder="placeholder"})(b||(b={}));B.escape=function(r){return r};class ee{constructor(e,t=!1,s){this.name=e.name,this.version=e.version,this.config=e.config,this.labels=e.labels,this.tags=e.tags,this.isFallback=t,this.type=s,this.commitMessage=e.commitMessage}_transformToLangchainVariables(e){return this.escapeJsonForLangchain(e).replace(/\{\{(\w+)\}\}/g,"{$1}")}escapeJsonForLangchain(e){const t=[],s=[];let n=0;const o=e.length;for(;n<o;){const a=e[n];if(a==="{"){if(n+1<o&&e[n+1]==="{"){t.push("{{"),n+=2;continue}let c=n+1;for(;c<o&&/\s/.test(e[c]);)c++;const i=c<o&&(e[c]==="'"||e[c]==='"');t.push(i?"{{":"{"),s.push(i),n+=1;continue}if(a==="}"){if(n+1<o&&e[n+1]==="}"){t.push("}}"),n+=2;continue}const c=s.pop()??!1;t.push(c?"}}":"}"),n+=1;continue}t.push(a),n+=1}return t.join("")}}class k extends ee{constructor(e,t=!1){super(e,t,"text"),this.promptResponse=e,this.prompt=e.prompt}compile(e,t){return B.render(this.promptResponse.prompt,e??{})}getLangchainPrompt(e){return this._transformToLangchainVariables(this.prompt)}toJSON(){return JSON.stringify({name:this.name,prompt:this.prompt,version:this.version,isFallback:this.isFallback,tags:this.tags,labels:this.labels,type:this.type,config:this.config})}}class O extends ee{constructor(e,t=!1){const s=O.normalizePrompt(e.prompt),n={...e,prompt:s};super(n,t,"chat"),this.promptResponse=n,this.prompt=s}static normalizePrompt(e){return e.map(t=>"type"in t?t:{type:b.ChatMessage,...t})}compile(e,t){const s=[],n=t??{};for(const o of this.prompt)if("type"in o&&o.type===b.Placeholder){const a=n[o.name];Array.isArray(a)&&a.length>0&&a.every(c=>typeof c=="object"&&"role"in c&&"content"in c)?s.push(...a):Array.isArray(a)&&a.length===0||(a!==void 0?s.push(JSON.stringify(a)):s.push(o))}else"role"in o&&"content"in o&&o.type===b.ChatMessage&&s.push({role:o.role,content:o.content});return s.map(o=>typeof o=="object"&&o!==null&&"role"in o&&"content"in o?{...o,content:B.render(o.content,e??{})}:o)}getLangchainPrompt(e){const t=[],s=e?.placeholders??{};for(const n of this.prompt)if("type"in n&&n.type===b.Placeholder){const o=s[n.name];Array.isArray(o)&&o.length>0&&o.every(a=>typeof a=="object"&&"role"in a&&"content"in a)?t.push(...o.map(a=>({role:a.role,content:this._transformToLangchainVariables(a.content)}))):Array.isArray(o)&&o.length===0||(o!==void 0?t.push(JSON.stringify(o)):t.push({variableName:n.name,optional:!1}))}else"role"in n&&"content"in n&&n.type===b.ChatMessage&&t.push({role:n.role,content:this._transformToLangchainVariables(n.content)});return t}toJSON(){return JSON.stringify({name:this.name,prompt:this.promptResponse.prompt.map(e=>{if("type"in e&&e.type===b.ChatMessage){const{type:t,...s}=e;return s}return e}),version:this.version,isFallback:this.isFallback,tags:this.tags,labels:this.labels,type:this.type,config:this.config})}}function Ee(r,e){if(!r)throw new Error(e)}function te(r){return r?.replace(/\/+$/,"")}async function F(r,e={},t){const{retryCount:s=3,retryDelay:n=5e3,retryCheck:o=()=>!0}=e;let a=null;for(let c=0;c<s+1;c++){c>0&&(await new Promise(i=>setTimeout(i,n)),t(`Retrying ${c+1} of ${s+1}`));try{return await r()}catch(i){if(a=i,!o(i))throw i;t(`Retriable error: ${JSON.stringify(i)}`)}}throw a}function w(r){let e=new Date().getTime(),t=r&&r.performance&&r.performance.now&&r.performance.now()*1e3||0;return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(s){let n=Math.random()*16;return e>0?(n=(e+n)%16|0,e=Math.floor(e/16)):(n=(t+n)%16|0,t=Math.floor(t/16)),(s==="x"?n:n&3|8).toString(16)})}function we(){return new Date().getTime()}function se(){return new Date().toISOString()}function re(r,e){const t=setTimeout(r,e);return t?.unref&&t?.unref(),t}function g(r){if(typeof process<"u"&&J[r])return J[r];if(typeof globalThis<"u")return globalThis[r]}function Se(r,e=!0){const{publicKey:t,secretKey:s,...n}=r??{},o=t??g("LANGFUSE_PUBLIC_KEY"),a=e?s??g("LANGFUSE_SECRET_KEY"):void 0,c=n.baseUrl??g("LANGFUSE_BASEURL"),i={...n,baseUrl:c};return{publicKey:o,...e?{secretKey:a}:void 0,...i}}const C=r=>{const e=new URLSearchParams;return Object.entries(r??{}).forEach(([t,s])=>{s!=null&&(s instanceof Date?e.append(t,s.toISOString()):e.append(t,s.toString()))}),e.toString()};var ne=Object.freeze({__proto__:null,assert:Ee,configLangfuseSDK:Se,currentISOTime:se,currentTimestamp:we,encodeQueryParams:C,generateUUID:w,getEnv:g,removeTrailingSlash:te,retriable:F,safeSetTimeout:re});const ve=["VERCEL_GIT_COMMIT_SHA","NEXT_PUBLIC_VERCEL_GIT_COMMIT_SHA","COMMIT_REF","RENDER_GIT_COMMIT","CI_COMMIT_SHA","CIRCLE_SHA1","CF_PAGES_COMMIT_SHA","REACT_APP_GIT_SHA","SOURCE_VERSION","TRIGGER_DEPLOYMENT_ID"];function Te(){for(const r of ve){const e=g(r);if(e)return e}}let P=null,$=null;const j=r=>import(r);typeof globalThis.Deno<"u"?Promise.all([j("node:fs"),j("node:crypto")]).then(([r,e])=>{P=r,$=e}).catch():typeof process<"u"&&process.versions?.node?Promise.all([j("fs"),j("crypto")]).then(([r,e])=>{P=r,$=e}).catch():typeof crypto<"u"&&($=crypto);class v{constructor(e){const{obj:t,base64DataUri:s,contentType:n,contentBytes:o,filePath:a}=e;if(this.obj=t,this._mediaId=void 0,s){const[c,i]=this.parseBase64DataUri(s);this._contentBytes=c,this._contentType=i,this._source="base64_data_uri"}else if(o&&n)this._contentBytes=o,this._contentType=n,this._source="bytes";else if(a&&n){if(!P)throw new Error("File system support is not available in this environment");if(!P.existsSync(a))throw new Error(`File at path ${a} does not exist`);this._contentBytes=this.readFile(a),this._contentType=this._contentBytes?n:void 0,this._source=this._contentBytes?"file":void 0}else console.error("base64DataUri, or contentBytes and contentType, or filePath must be provided to LangfuseMedia")}readFile(e){try{if(!P)throw new Error("File system support is not available in this environment");return P.readFileSync(e)}catch(t){console.error(`Error reading file at path ${e}`,t);return}}parseBase64DataUri(e){try{if(!e||typeof e!="string")throw new Error("Data URI is not a string");if(!e.startsWith("data:"))throw new Error("Data URI does not start with 'data:'");const[t,s]=e.slice(5).split(",",2);if(!t||!s)throw new Error("Invalid URI");const n=t.split(";");if(!n.includes("base64"))throw new Error("Data is not base64 encoded");const o=n[0];if(!o)throw new Error("Content type is empty");return[Buffer.from(s,"base64"),o]}catch(t){return console.error("Error parsing base64 data URI",t),[void 0,void 0]}}get contentLength(){return this._contentBytes?.length}get contentSha256Hash(){if(!this._contentBytes)return;if(!$){console.error("Crypto support is not available in this environment");return}return $.createHash("sha256").update(this._contentBytes).digest("base64")}toJSON(){return!this._contentType||!this._source||!this._mediaId?`<Upload handling failed for LangfuseMedia of type ${this._contentType}>`:`@@@langfuseMedia:type=${this._contentType}|id=${this._mediaId}|source=${this._source}@@@`}static parseReferenceString(e){const t="@@@langfuseMedia:";if(!e.startsWith(t))throw new Error("Reference string does not start with '@@@langfuseMedia:type='");if(!e.endsWith("@@@"))throw new Error("Reference string does not end with '@@@'");const o=e.slice(t.length,-3).split("|"),a={};for(const c of o){const[i,u]=c.split("=",2);a[i]=u}if(!("type"in a&&"id"in a&&"source"in a))throw new Error("Missing required fields in reference string");return{mediaId:a.id,source:a.source,contentType:a.type}}static async resolveMediaReferences(e){const{obj:t,langfuseClient:s,maxDepth:n=10}=e;async function o(a,c){if(c>n)return a;if(typeof a=="string"){const i=/@@@langfuseMedia:.+?@@@/g,u=a.match(i);if(!u)return a;let h=a;const l=new Map;await Promise.all(u.map(async p=>{try{const m=v.parseReferenceString(p),y=await s.fetchMedia(m.mediaId),_=await s.fetch(y.url,{method:"GET",headers:{}});if(_.status!==200)throw new Error("Failed to fetch media content");const E=Buffer.from(await _.arrayBuffer()).toString("base64"),f=`data:${y.contentType};base64,${E}`;l.set(p,f)}catch(m){console.warn("Error fetching media content for reference string",p,m)}}));for(const[p,m]of l.entries())h=h.replaceAll(p,m);return h}return Array.isArray(a)?Promise.all(a.map(async i=>await o(i,c+1))):typeof a=="object"&&a!==null?Object.fromEntries(await Promise.all(Object.entries(a).map(async([i,u])=>[i,await o(u,c+1)]))):a}return o(t,0)}}function Ie(r,e){return e===void 0?!0:e===0?!1:e<0||e>1||isNaN(e)?(console.warn("Sample rate must be between 0 and 1. Ignoring setting."),!0):Pe(r)<e}function Pe(r){let e=0;const t=31;for(let s=0;s<r.length;s++)e=e*t+r.charCodeAt(s)>>>0;return e=(e>>>16^e)*73244475,e=(e>>>16^e)*73244475,e=e>>>16^e,Math.abs(e)/2147483647}const z=g("LANGFUSE_MAX_EVENT_SIZE_BYTES")?Number(g("LANGFUSE_MAX_EVENT_SIZE_BYTES")):1e6,Le=g("LANGFUSE_MAX_BATCH_SIZE_BYTES")?Number(g("LANGFUSE_MAX_BATCH_SIZE_BYTES")):25e5,H=/^(?!langfuse)[a-z0-9_-]+$/,Ae=["langfuse-prompt-experiment"];class U extends Error{constructor(e,t){super("HTTP error while fetching Langfuse: "+e.status+" and body: "+t),this.response=e,this.name="LangfuseFetchHttpError"}}class M extends Error{constructor(e){super("Network error while fetching Langfuse",e instanceof Error?{cause:e}:{}),this.error=e,this.name="LangfuseFetchNetworkError"}}function oe(r){return typeof r=="object"&&r.name==="LangfuseFetchHttpError"}function ae(r){return typeof r=="object"&&r.name==="LangfuseFetchNetworkError"}function Ce(r){return oe(r)||ae(r)}const D="https://langfuse.com/support",Oe="https://api.reference.langfuse.com",$e="https://langfuse.com/docs/rbac",Re="https://langfuse.com/docs/sdk/typescript/guide",je="https://langfuse.com/faq/all/api-limits",Ue="https://www.npmjs.com/package/langfuse",Q=`Make sure to keep your SDK updated, refer to ${Ue} for details.`,x=`This is an unusual occurrence and we are monitoring it closely. For help, please contact support: ${D}.`,V=`Unexpected error occurred. Please check your request and contact support: ${D}.`,xe=new Map([[500,`Internal server error occurred. For help, please contact support: ${D}`],[501,`Not implemented. Please check your request and contact support for help: ${D}.`],[502,`Bad gateway. ${x}`],[503,`Service unavailable. ${x}`],[504,`Gateway timeout. ${x}`],[404,`Internal error occurred. ${x}`],[400,`Bad request. Please check your request for any missing or incorrect parameters. Refer to our API docs: ${Oe} for details.`],[401,`Unauthorized. Please check your public/private host settings. Refer to our installation and setup guide: ${Re} for details on SDK configuration.`],[403,`Forbidden. Please check your access control settings. Refer to our RBAC docs: ${$e} for details.`],[429,`Rate limit exceeded. For more information on rate limits please see: ${je}`]]);function De(r){if(!r)return`${V} ${Q}`;const e=xe.get(r)||V;return`${r}: ${e} ${Q}`}function G(r){if(oe(r)){const e=r.response.status,t=De(e);console.error("[Langfuse SDK]",t,`Error details: ${r}`)}else ae(r)?console.error("[Langfuse SDK] Network error: ",r):console.error("[Langfuse SDK] Unknown error:",r)}class ie{constructor(e){this.additionalHeaders={},this.debugMode=!1,this.pendingEventProcessingPromises={},this.pendingIngestionPromises={},this.localEventExportMap=new Map,this._events=new ge;const{publicKey:t,secretKey:s,enabled:n,_projectId:o,_isLocalEventExportEnabled:a,...c}=e;if(this._events.on("error",i=>{console.error(`[Langfuse SDK] ${typeof i=="string"?i:JSON.stringify(i)}`)}),this.enabled=n!==!1,this.publicKey=t??"",this.secretKey=s,this.baseUrl=te(c?.baseUrl||"https://cloud.langfuse.com"),this.additionalHeaders=c?.additionalHeaders||{},this.flushAt=c?.flushAt?Math.max(c?.flushAt,1):15,this.flushInterval=c?.flushInterval??1e4,this.release=c?.release??g("LANGFUSE_RELEASE")??Te()??void 0,this.mask=c?.mask,this.sampleRate=c?.sampleRate??(g("LANGFUSE_SAMPLE_RATE")?Number(g("LANGFUSE_SAMPLE_RATE")):void 0),this.sampleRate&&this._events.emit("debug",`Langfuse trace sampling enabled with sampleRate ${this.sampleRate}.`),this.environment=c?.environment??g("LANGFUSE_TRACING_ENVIRONMENT"),this.environment&&!(H.test(this.environment)||Ae.includes(this.environment))&&!a&&this._events.emit("error",`Invalid tracing environment set: ${this.environment} . Environment must match regex ${H}. Events will be rejected by Langfuse server.`),this._retryOptions={retryCount:c?.fetchRetryCount??3,retryDelay:c?.fetchRetryDelay??3e3,retryCheck:Ce},this.requestTimeout=c?.requestTimeout??5e3,this.sdkIntegration=c?.sdkIntegration??"DEFAULT",this.isLocalEventExportEnabled=a??!1,this.isLocalEventExportEnabled&&!o){this._events.emit("error","Local event export is enabled, but no project ID was provided. Disabling local export."),this.isLocalEventExportEnabled=!1;return}else if(!this.isLocalEventExportEnabled&&o){this._events.emit("error","Local event export is disabled, but a project ID was provided. Disabling local export."),this.isLocalEventExportEnabled=!1;return}else this.projectId=o}getSdkIntegration(){return this.sdkIntegration}getCommonEventProperties(){return{$lib:this.getLibraryId(),$lib_version:this.getLibraryVersion()}}on(e,t){return this._events.on(e,t)}debug(e=!0){this.removeDebugCallback?.(),this.debugMode=e,e&&(this.removeDebugCallback=this.on("*",(t,s)=>{t!=="error"&&console.log("[Langfuse Debug]",t,JSON.stringify(s))}))}traceStateless(e){const{id:t,timestamp:s,release:n,...o}=e,a=t??w(),c=n??this.release,i={id:a,release:c,timestamp:s??new Date,environment:this.environment,...o};return this.enqueue("trace-create",i),a}eventStateless(e){const{id:t,startTime:s,...n}=e,o=t??w(),a={id:o,startTime:s??new Date,environment:this.environment,...n};return this.enqueue("event-create",a),o}spanStateless(e){const{id:t,startTime:s,...n}=e,o=t||w(),a={id:o,startTime:s??new Date,environment:this.environment,...n};return this.enqueue("span-create",a),o}generationStateless(e){const{id:t,startTime:s,prompt:n,...o}=e,a=n&&!n.isFallback?{promptName:n.name,promptVersion:n.version}:{},c=t||w(),i={id:c,startTime:s??new Date,environment:this.environment,...a,...o};return this.enqueue("generation-create",i),c}scoreStateless(e){const{id:t,...s}=e,n=t||w(),o={id:n,environment:this.environment,...s};return this.enqueue("score-create",o),n}updateSpanStateless(e){return this.enqueue("span-update",e),e.id}updateGenerationStateless(e){const{prompt:t,...s}=e,o={...t&&!t.isFallback?{promptName:t.name,promptVersion:t.version}:{},...s};return this.enqueue("generation-update",o),e.id}async _getDataset(e){const t=encodeURIComponent(e);return this.fetchAndLogErrors(`${this.baseUrl}/api/public/v2/datasets/${t}`,this._getFetchOptions({method:"GET"}))}async _getDatasetItems(e){const t=new URLSearchParams;return Object.entries(e??{}).forEach(([s,n])=>{n!=null&&t.append(s,n.toString())}),this.fetchAndLogErrors(`${this.baseUrl}/api/public/dataset-items?${t}`,this._getFetchOptions({method:"GET"}))}async _fetchMedia(e){return this.fetchAndLogErrors(`${this.baseUrl}/api/public/media/${e}`,this._getFetchOptions({method:"GET"}))}async fetchTraces(e){const{data:t,meta:s}=await this.fetchAndLogErrors(`${this.baseUrl}/api/public/traces?${C(e)}`,this._getFetchOptions({method:"GET"}));return{data:t,meta:s}}async fetchTrace(e){return{data:await this.fetchAndLogErrors(`${this.baseUrl}/api/public/traces/${e}`,this._getFetchOptions({method:"GET"}))}}async fetchObservations(e){const{data:t,meta:s}=await this.fetchAndLogErrors(`${this.baseUrl}/api/public/observations?${C(e)}`,this._getFetchOptions({method:"GET"}));return{data:t,meta:s}}async fetchObservation(e){return{data:await this.fetchAndLogErrors(`${this.baseUrl}/api/public/observations/${e}`,this._getFetchOptions({method:"GET"}))}}async fetchSessions(e){const{data:t,meta:s}=await this.fetchAndLogErrors(`${this.baseUrl}/api/public/sessions?${C(e)}`,this._getFetchOptions({method:"GET"}));return{data:t,meta:s}}async getDatasetRun(e){const t=encodeURIComponent(e.datasetName),s=encodeURIComponent(e.runName);return this.fetchAndLogErrors(`${this.baseUrl}/api/public/datasets/${t}/runs/${s}`,this._getFetchOptions({method:"GET"}))}async getDatasetRuns(e,t){return this.fetchAndLogErrors(`${this.baseUrl}/api/public/datasets/${encodeURIComponent(e)}/runs?${C(t)}`,this._getFetchOptions({method:"GET"}))}async createDatasetRunItem(e){return this.fetchAndLogErrors(`${this.baseUrl}/api/public/dataset-run-items`,this._getFetchOptions({method:"POST",body:JSON.stringify(e)}))}async createDataset(e){const t=typeof e=="string"?{name:e}:e;return this.fetchAndLogErrors(`${this.baseUrl}/api/public/datasets`,this._getFetchOptions({method:"POST",body:JSON.stringify(t)}))}async createDatasetItem(e){return this.fetchAndLogErrors(`${this.baseUrl}/api/public/dataset-items`,this._getFetchOptions({method:"POST",body:JSON.stringify(e)}))}async getDatasetItem(e){return this.fetchAndLogErrors(`${this.baseUrl}/api/public/dataset-items/${e}`,this._getFetchOptions({method:"GET"}))}_parsePayload(e){try{return JSON.parse(e)}catch{return e}}async createPromptStateless(e){return this.fetchAndLogErrors(`${this.baseUrl}/api/public/v2/prompts`,this._getFetchOptions({method:"POST",body:JSON.stringify(e)}))}async updatePromptStateless(e){return this.fetchAndLogErrors(`${this.baseUrl}/api/public/v2/prompts/${encodeURIComponent(e.name)}/versions/${encodeURIComponent(e.version)}`,this._getFetchOptions({method:"PATCH",body:JSON.stringify(e)}))}async getPromptStateless(e,t,s,n,o){const a=encodeURIComponent(e),c=new URLSearchParams;if(t&&s)throw new Error("Provide either version or label, not both.");t&&c.append("version",t.toString()),s&&c.append("label",s);const i=`${this.baseUrl}/api/public/v2/prompts/${a}${c.size?"?"+c:""}`,u=this._getBoundedMaxRetries({maxRetries:n,defaultMaxRetries:2,maxRetriesUpperBound:4}),h={...this._retryOptions,retryCount:u,retryDelay:500};return F(async()=>{const p=await this.fetch(i,this._getFetchOptions({method:"GET",fetchTimeout:o??this.requestTimeout})).catch(y=>{throw y.name==="AbortError"?new M("Fetch request timed out"):new M(y)});if(p.status>=500)throw new U(p,await p.text());const m=await p.json();return{fetchResult:p.status===200?"success":"failure",data:m}},h,p=>this._events.emit("retry",p+", "+i+", "+JSON.stringify(h)))}_getBoundedMaxRetries(e){const t=Math.max(e.defaultMaxRetries??2,0),s=Math.max(e.maxRetriesUpperBound??4,0);return e.maxRetries===void 0?t:Math.min(Math.max(e.maxRetries,0),s)}enqueue(e,t){if(!this.enabled)return;const s=this.parseTraceId(e,t);if(!s)this._events.emit("warning","Failed to parse traceID for sampling. Please open a Github issue in https://github.com/langfuse/langfuse/issues/new/choose");else if(!Ie(s,this.sampleRate)){this._events.emit("debug",`Event with trace ID ${s} is out of sample. Skipping.`);return}const n=this.processEnqueueEvent(e,t),o=w();this.pendingEventProcessingPromises[o]=n,n.catch(a=>{this._events.emit("error",a)}).finally(()=>{delete this.pendingEventProcessingPromises[o]})}async processEnqueueEvent(e,t){this.maskEventBodyInPlace(t),await this.processMediaInEvent(e,t);const s=this.truncateEventBody(t,z);try{JSON.stringify(s)}catch(o){this._events.emit("error",`Event Body for ${e} is not JSON-serializable: ${o}`);return}const n=this.getPersistedProperty(I.Queue)||[];n.push({id:w(),type:e,timestamp:se(),body:s,metadata:void 0}),this.setPersistedProperty(I.Queue,n),this._events.emit(e,s),n.length>=this.flushAt&&this.flush(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=re(()=>this.flush(),this.flushInterval))}maskEventBodyInPlace(e){if(!this.mask)return;const t=["input","output"];for(const s of t)if(s in e)try{e[s]=this.mask({data:e[s]})}catch(n){this._events.emit("error",`Error masking ${s}: ${n}`),e[s]="<fully masked due to failed mask function>"}}truncateEventBody(e,t){const s=this.getByteSize(e);if(s<=t)return e;this._events.emit("warning",`Event Body is too large (${s} bytes) and will be truncated`);const o=["input","output","metadata"].map(i=>({key:i,size:i in e?this.getByteSize(e[i]):0})).sort((i,u)=>u.size-i.size);let a={...e},c=s;for(const{key:i,size:u}of o)c>t&&Object.prototype.hasOwnProperty.call(a,i)&&(a={...a,[i]:"<truncated due to size exceeding limit>"},this._events.emit("warning",`Truncated ${i} due to total size exceeding limit`),c-=u);return a}getByteSize(e){const t=JSON.stringify(e);return typeof TextEncoder<"u"?new TextEncoder().encode(t).length:encodeURIComponent(t).replace(/%[A-F\d]{2}/g,"U").length}async processMediaInEvent(e,t){if(!t)return;const s=this.parseTraceId(e,t);if(!s){this._events.emit("warning","traceId is required for media upload");return}const n=(e.includes("generation")||e.includes("span"))&&t.id?t.id:void 0;await Promise.all(["input","output","metadata"].map(async o=>{t[o]&&(t[o]=await this.findAndProcessMedia({data:t[o],traceId:s,observationId:n,field:o}).catch(a=>{this._events.emit("error",`Error processing multimodal event: ${a}`)})??t[o])}))}parseTraceId(e,t){return"traceId"in t?t.traceId:e.includes("trace")?t.id:void 0}async findAndProcessMedia({data:e,traceId:t,observationId:s,field:n}){const o=new WeakMap,a=10,c=async(i,u)=>{if(typeof i=="string"&&i.startsWith("data:")){const h=new v({base64DataUri:i});return await this.processMediaItem({media:h,traceId:t,observationId:s,field:n}),h}if(typeof i!="object"||i===null||o.has(i)||u>a)return i;if(o.set(i,!0),i instanceof v||Object.prototype.toString.call(i)==="[object LangfuseMedia]")return await this.processMediaItem({media:i,traceId:t,observationId:s,field:n}),i;if(Array.isArray(i))return await Promise.all(i.map(h=>c(h,u+1)));if(typeof i=="object"&&i!==null){if("input_audio"in i&&typeof i.input_audio=="object"&&"data"in i.input_audio){const h=new v({base64DataUri:`data:audio/${i.input_audio.format||"wav"};base64,${i.input_audio.data}`});return await this.processMediaItem({media:h,traceId:t,observationId:s,field:n}),{...i,input_audio:{...i.input_audio,data:h}}}if("audio"in i&&typeof i.audio=="object"&&"data"in i.audio){const h=new v({base64DataUri:`data:audio/${i.audio.format||"wav"};base64,${i.audio.data}`});return await this.processMediaItem({media:h,traceId:t,observationId:s,field:n}),{...i,audio:{...i.audio,data:h}}}return Object.fromEntries(await Promise.all(Object.entries(i).map(async([h,l])=>[h,await c(l,u+1)])))}return i};return await c(e,1)}async processMediaItem({media:e,traceId:t,observationId:s,field:n}){try{if(!e.contentLength||!e._contentType||!e.contentSha256Hash||!e._contentBytes)return;const o={contentLength:e.contentLength,traceId:t,observationId:s,field:n,contentType:e._contentType,sha256Hash:e.contentSha256Hash},c=await(await this.fetch(`${this.baseUrl}/api/public/media`,this._getFetchOptions({method:"POST",body:JSON.stringify(o)}))).json(),{uploadUrl:i,mediaId:u}=c;if(e._mediaId=u,i){this._events.emit("debug",`Uploading media ${u}`);const h=Date.now(),l=await this.uploadMediaWithBackoff({uploadUrl:i,contentBytes:e._contentBytes,contentType:e._contentType,contentSha256Hash:e.contentSha256Hash,maxRetries:3,baseDelay:1e3});if(!l)throw Error("Media upload process failed");const p={uploadedAt:new Date().toISOString(),uploadHttpStatus:l.status,uploadHttpError:await l.text(),uploadTimeMs:Date.now()-h};await this.fetch(`${this.baseUrl}/api/public/media/${u}`,this._getFetchOptions({method:"PATCH",body:JSON.stringify(p)})),this._events.emit("debug",`Media upload status reported for ${u}`)}else this._events.emit("debug",`Media ${u} already uploaded`)}catch(o){this._events.emit("error",`Error processing media item: ${o}`)}}async uploadMediaWithBackoff(e){const{uploadUrl:t,contentType:s,contentSha256Hash:n,contentBytes:o,maxRetries:a,baseDelay:c}=e;for(let i=0;i<=a;i++)try{const u=await this.fetch(t,{method:"PUT",body:o,headers:{"Content-Type":s,"x-amz-checksum-sha256":n,"x-ms-blob-type":"BlockBlob"}});if(i<a&&u.status!==200&&u.status!==201)throw new Error(`Upload failed with status ${u.status}`);return u}catch(u){if(i===a)throw u;const h=c*Math.pow(2,i),l=Math.random()*1e3;await new Promise(p=>setTimeout(p,h+l))}}async flushAsync(){return await Promise.all(Object.values(this.pendingEventProcessingPromises)).catch(e=>{G(e)}),new Promise((e,t)=>{try{this.flush((s,n)=>{s?(G(s),e()):e(n)})}catch(s){console.error("[Langfuse SDK] Error while flushing Langfuse",s)}})}flush(e){this._flushTimer&&(clearTimeout(this._flushTimer),this._flushTimer=null);const t=this.getPersistedProperty(I.Queue)||[];if(!t.length)return e?.();const s=t.splice(0,this.flushAt),{processedItems:n,remainingItems:o}=this.processQueueItems(s,z,Le);this.setPersistedProperty(I.Queue,[...o,...t]);const a=w(),c=p=>{p&&this._events.emit("warning",p),e?.(p,s),this._events.emit("flush",s)};if(this.isLocalEventExportEnabled&&this.projectId){this.localEventExportMap.has(this.projectId)?this.localEventExportMap.get(this.projectId)?.push(...s):this.localEventExportMap.set(this.projectId,[...s]),c();return}const i=JSON.stringify({batch:n,metadata:{batch_size:n.length,sdk_integration:this.sdkIntegration,sdk_version:this.getLibraryVersion(),sdk_variant:this.getLibraryId(),public_key:this.publicKey,sdk_name:"langfuse-js"}}),u=`${this.baseUrl}/api/public/ingestion`,h=this._getFetchOptions({method:"POST",body:i}),l=this.fetchWithRetry(u,h).then(()=>c()).catch(p=>{c(p)});this.pendingIngestionPromises[a]=l,l.finally(()=>{delete this.pendingIngestionPromises[a]})}processQueueItems(e,t,s){let n=0;const o=[],a=[];for(let c=0;c<e.length;c++)try{const i=new Blob([JSON.stringify(e[c])]).size;if(i>t){console.warn(`Item exceeds size limit (size: ${i}), dropping item.`);continue}if(n+i>=s){console.debug(`hit batch size limit (size: ${n+i})`),a.push(...e.slice(c)),console.log(`Remaining items: ${a.length}`),console.log(`processes items: ${o.length}`);break}n+=i,o.push(e[c])}catch(i){this._events.emit("error",i),a.push(...e.slice(c));break}return{processedItems:o,remainingItems:a}}_getFetchOptions(e){return{method:e.method,headers:{"Content-Type":"application/json","X-Langfuse-Sdk-Name":"langfuse-js","X-Langfuse-Sdk-Version":this.getLibraryVersion(),"X-Langfuse-Sdk-Variant":this.getLibraryId(),"X-Langfuse-Sdk-Integration":this.sdkIntegration,"X-Langfuse-Public-Key":this.publicKey,...this.additionalHeaders,...this.constructAuthorizationHeader(this.publicKey,this.secretKey)},body:e.body,...e.fetchTimeout!==void 0?{signal:AbortSignal.timeout(e.fetchTimeout)}:{}}}constructAuthorizationHeader(e,t){return t===void 0?{Authorization:"Bearer "+e}:{Authorization:"Basic "+(typeof btoa=="function"?btoa(e+":"+t):Buffer.from(e+":"+t).toString("base64"))}}async fetchWithRetry(e,t,s){return AbortSignal.timeout??=function(o){const a=new AbortController;return setTimeout(()=>a.abort(),o),a.signal},await F(async()=>{let n=null;try{n=await this.fetch(e,{signal:AbortSignal.timeout(this.requestTimeout),...t})}catch(a){throw new M(a)}if(n.status<200||n.status>=400){const a=await n.json();throw new U(n,JSON.stringify(a))}const o=await n.json();if(n.status===207&&o.errors.length>0)throw new U(n,JSON.stringify(o.errors));return n},{...this._retryOptions,...s},n=>this._events.emit("retry",n+", "+e+", "+JSON.stringify(t)))}async fetchAndLogErrors(e,t){const s=await this.fetch(e,t),n=s.status===429?await s.text():await s.json();return(s.status<200||s.status>=400)&&G(new U(s,JSON.stringify(n))),n}async shutdownAsync(){clearTimeout(this._flushTimer);try{await this.flushAsync(),await Promise.all(Object.values(this.pendingIngestionPromises).map(e=>e.catch(()=>{}))),await this.flushAsync()}catch(e){console.error("[Langfuse SDK] Error while shutting down Langfuse",e)}}async _exportLocalEvents(e){if(this.isLocalEventExportEnabled){clearTimeout(this._flushTimer),await this.flushAsync();const t=this.localEventExportMap.get(e)??[];return this.localEventExportMap.delete(e),t}else return this._events.emit("error","Local event exports are disabled, but _exportLocalEvents() was called."),[]}shutdown(){console.warn("shutdown() is deprecated. It does not wait for all events to be processed. Please use shutdownAsync() instead."),this.shutdownAsync()}async awaitAllQueuedAndPendingRequests(){clearTimeout(this._flushTimer),await this.flushAsync(),await Promise.all(Object.values(this.pendingIngestionPromises))}}class qe extends ie{constructor(e){const{flushAt:t,flushInterval:s,publicKey:n,enabled:o,...a}=e;let c=o!==!1;c&&!n&&(c=!1,console.warn("Langfuse public key not passed to constructor and not set as 'LANGFUSE_PUBLIC_KEY' environment variable. No observability data will be sent to Langfuse.")),super({...a,publicKey:n,flushAt:t??1,flushInterval:s??0,enabled:c})}async score(e){return this.scoreStateless(e),await this.awaitAllQueuedAndPendingRequests(),this}}class ke extends ie{constructor(e){const{publicKey:t,secretKey:s,enabled:n,_isLocalEventExportEnabled:o}=e;let a=n!==!1;o?a=!0:s?t||(a=!1,n!==!1&&console.warn("Langfuse public key was not passed to constructor or not set as 'LANGFUSE_PUBLIC_KEY' environment variable. No observability data will be sent to Langfuse.")):(a=!1,n!==!1&&console.warn("Langfuse secret key was not passed to constructor or not set as 'LANGFUSE_SECRET_KEY' environment variable. No observability data will be sent to Langfuse.")),super({...e,enabled:a}),this._promptCache=new _e}trace(e){const t=this.traceStateless(e??{}),s=new Me(this,t);if(g("DEFER")&&e)try{const n=g("__deferRuntime");n&&n.langfuseTraces([{id:t,name:e.name||"",url:s.getTraceUrl()}])}catch{}return s}span(e){const t=e.traceId||this.traceStateless({name:e.name}),s=this.spanStateless({...e,traceId:t});return new Ge(this,s,t)}generation(e){const t=e.traceId||this.traceStateless({name:e.name}),s=this.generationStateless({...e,traceId:t});return new Ne(this,s,t)}event(e){const t=e.traceId||this.traceStateless({name:e.name}),s=this.eventStateless({...e,traceId:t});return new Fe(this,s,t)}score(e){return this.scoreStateless(e),this}async getDataset(e,t){const s=await this._getDataset(e),n=[];let o=1;for(;;){const c=await this._getDatasetItems({datasetName:e,limit:t?.fetchItemsPageSize??50,page:o});if(n.push(...c.data),c.meta.totalPages<=o)break;o++}return{...s,description:s.description??void 0,metadata:s.metadata??void 0,items:n.map(c=>({...c,link:async(i,u,h)=>(await this.awaitAllQueuedAndPendingRequests(),await this.createDatasetRunItem({runName:u,datasetItemId:c.id,observationId:i.observationId,traceId:i.traceId,runDescription:h?.description,metadata:h?.metadata}))}))}}async createPrompt(e){const t=e.labels??[],s=e.type==="chat"?await this.createPromptStateless({...e,prompt:e.prompt.map(n=>"type"in n&&n.type===b.Placeholder?{type:b.Placeholder,name:n.name}:{type:b.ChatMessage,...n}),labels:e.isActive?[...new Set([...t,"production"])]:t}):await this.createPromptStateless({...e,type:e.type??"text",labels:e.isActive?[...new Set([...t,"production"])]:t});return s.type==="chat"?new O(s):new k(s)}async updatePrompt(e){const t=await this.updatePromptStateless(e);return this._promptCache.invalidate(e.name),t}async getPrompt(e,t,s){const n=this._getPromptCacheKey({name:e,version:t,label:s?.label}),o=this._promptCache.getIncludingExpired(n);if(!o||s?.cacheTtlSeconds===0)try{return await this._fetchPromptAndUpdateCache({name:e,version:t,label:s?.label,cacheTtlSeconds:s?.cacheTtlSeconds,maxRetries:s?.maxRetries,fetchTimeout:s?.fetchTimeoutMs})}catch(a){if(s?.fallback){const c={name:e,version:t??0,labels:s.label?[s.label]:[],cacheTtlSeconds:s?.cacheTtlSeconds,config:{},tags:[]};return s.type==="chat"?new O({...c,type:"chat",prompt:s.fallback.map(i=>({type:b.ChatMessage,...i}))},!0):new k({...c,type:"text",prompt:s.fallback},!0)}throw a}if(o.isExpired){if(!this._promptCache.isRefreshing(n)){const a=this._fetchPromptAndUpdateCache({name:e,version:t,label:s?.label,cacheTtlSeconds:s?.cacheTtlSeconds,maxRetries:s?.maxRetries,fetchTimeout:s?.fetchTimeoutMs}).catch(()=>{console.warn(`Failed to refresh prompt cache '${n}', stale cache will be used until next refresh succeeds.`)});this._promptCache.addRefreshingPromise(n,a)}return o.value}return o.value}_getPromptCacheKey(e){const{name:t,version:s,label:n}=e,o=[t];return s!==void 0?o.push("version:"+s.toString()):n!==void 0?o.push("label:"+n):o.push("label:production"),o.join("-")}async _fetchPromptAndUpdateCache(e){const t=this._getPromptCacheKey(e);try{const{name:s,version:n,cacheTtlSeconds:o,label:a,maxRetries:c,fetchTimeout:i}=e,{data:u,fetchResult:h}=await this.getPromptStateless(s,n,a,c,i);if(h==="failure")throw Error(u.message??"Internal error while fetching prompt");let l;return u.type==="chat"?l=new O(u):l=new k(u),this._promptCache.set(t,l,o),l}catch(s){throw console.error(`[Langfuse SDK] Error while fetching prompt '${t}':`,s),s}}async fetchMedia(e){return await this._fetchMedia(e)}async resolveMediaReferences(e){const{obj:t,...s}=e;return v.resolveMediaReferences({...s,langfuseClient:this,obj:t})}_updateSpan(e){return this.updateSpanStateless(e),this}_updateGeneration(e){return this.updateGenerationStateless(e),this}}class ce{constructor({client:e,id:t,traceId:s,observationId:n}){this.client=e,this.id=t,this.traceId=s,this.observationId=n}event(e){return this.client.event({...e,traceId:this.traceId,parentObservationId:this.observationId})}span(e){return this.client.span({...e,traceId:this.traceId,parentObservationId:this.observationId})}generation(e){return this.client.generation({...e,traceId:this.traceId,parentObservationId:this.observationId})}score(e){return this.client.score({...e,traceId:this.traceId,observationId:this.observationId}),this}getTraceUrl(){return`${this.client.baseUrl}/trace/${this.traceId}`}}class Me extends ce{constructor(e,t){super({client:e,id:t,traceId:t,observationId:null})}update(e){return this.client.trace({...e,id:this.id}),this}}class K extends ce{constructor(e,t,s){super({client:e,id:t,traceId:s,observationId:t})}}class Ge extends K{constructor(e,t,s){super(e,t,s)}update(e){return this.client._updateSpan({...e,id:this.id,traceId:this.traceId}),this}end(e){return this.client._updateSpan({...e,id:this.id,traceId:this.traceId,endTime:new Date}),this}}class Ne extends K{constructor(e,t,s){super(e,t,s)}update(e){return this.client._updateGeneration({...e,id:this.id,traceId:this.traceId}),this}end(e){return this.client._updateGeneration({...e,id:this.id,traceId:this.traceId,endTime:new Date}),this}}class Fe extends K{constructor(e,t,s){super(e,t,s)}}const ue={getItem(r){try{const e=r+"=",t=document.cookie.split(";");for(let s=0;s<t.length;s++){let n=t[s];for(;n.charAt(0)==" ";)n=n.substring(1,n.length);if(n.indexOf(e)===0)return decodeURIComponent(n.substring(e.length,n.length))}}catch{}return null},setItem(r,e){try{const o=r+"="+encodeURIComponent(e)+"; path=/";document.cookie=o}catch{return}},removeItem(r){try{ue.setItem(r,"")}catch{return}},clear(){document.cookie=""},getAllKeys(){const r=document.cookie.split(";"),e=[];for(let t=0;t<r.length;t++){let s=r[t];for(;s.charAt(0)==" ";)s=s.substring(1,s.length);e.push(s.split("=")[0])}return e}},W=r=>({getItem(e){return r.getItem(e)},setItem(e,t){r.setItem(e,t)},removeItem(e){r.removeItem(e)},clear(){r.clear()},getAllKeys(){const e=[];for(const t in localStorage)e.push(t);return e}}),X=(r,e="__mplssupport__")=>{if(!window)return!1;try{return r.setItem(e,"xyz"),r.getItem(e)!=="xyz"?!1:(r.removeItem(e),!0)}catch{return!1}};let N,L;const A=()=>{const r={};return{getItem(t){return r[t]},setItem(t,s){r[t]=s!==null?s:void 0},removeItem(t){delete r[t]},clear(){for(const t in r)delete r[t]},getAllKeys(){const t=[];for(const s in r)t.push(s);return t}}},q=(r,e)=>{if(typeof e!==void 0&&e){if(!localStorage){const t=W(e.localStorage);N=X(t)?t:void 0}if(!L){const t=W(e.sessionStorage);L=X(t)?t:void 0}}switch(r){case"cookie":return ue||N||L||A();case"localStorage":return N||L||A();case"sessionStorage":return L||A();case"memory":return A();default:return A()}};var d;(function(r){r.Json="application/json",r.FormData="multipart/form-data",r.UrlEncoded="application/x-www-form-urlencoded",r.Text="text/plain"})(d||(d={}));class Be{constructor(e={}){this.baseUrl="",this.securityData=null,this.abortControllers=new Map,this.customFetch=(...t)=>fetch(...t),this.baseApiParams={credentials:"same-origin",headers:{},redirect:"follow",referrerPolicy:"no-referrer"},this.setSecurityData=t=>{this.securityData=t},this.contentFormatters={[d.Json]:t=>t!==null&&(typeof t=="object"||typeof t=="string")?JSON.stringify(t):t,[d.Text]:t=>t!==null&&typeof t!="string"?JSON.stringify(t):t,[d.FormData]:t=>Object.keys(t||{}).reduce((s,n)=>{const o=t[n];return s.append(n,o instanceof Blob?o:typeof o=="object"&&o!==null?JSON.stringify(o):`${o}`),s},new FormData),[d.UrlEncoded]:t=>this.toQueryString(t)},this.createAbortSignal=t=>{if(this.abortControllers.has(t)){const n=this.abortControllers.get(t);return n?n.signal:void 0}const s=new AbortController;return this.abortControllers.set(t,s),s.signal},this.abortRequest=t=>{const s=this.abortControllers.get(t);s&&(s.abort(),this.abortControllers.delete(t))},this.request=async({body:t,secure:s,path:n,type:o,query:a,format:c,baseUrl:i,cancelToken:u,...h})=>{const l=(typeof s=="boolean"?s:this.baseApiParams.secure)&&this.securityWorker&&await this.securityWorker(this.securityData)||{},p=this.mergeRequestParams(h,l),m=a&&this.toQueryString(a),y=this.contentFormatters[o||d.Json],_=c||p.format;return this.customFetch(`${i||this.baseUrl||""}${n}${m?`?${m}`:""}`,{...p,headers:{...p.headers||{},...o&&o!==d.FormData?{"Content-Type":o}:{}},signal:(u?this.createAbortSignal(u):p.signal)||null,body:typeof t>"u"||t===null?null:y(t)}).then(async E=>{const f=E.clone();f.data=null,f.error=null;const R=_?await E[_]().then(T=>(f.ok?f.data=T:f.error=T,f)).catch(T=>(f.error=T,f)):f;if(u&&this.abortControllers.delete(u),!E.ok)throw R;return R.data})},Object.assign(this,e)}encodeQueryParam(e,t){return`${encodeURIComponent(e)}=${encodeURIComponent(typeof t=="number"?t:`${t}`)}`}addQueryParam(e,t){return this.encodeQueryParam(t,e[t])}addArrayQueryParam(e,t){return e[t].map(n=>this.encodeQueryParam(t,n)).join("&")}toQueryString(e){const t=e||{};return Object.keys(t).filter(n=>typeof t[n]<"u").map(n=>Array.isArray(t[n])?this.addArrayQueryParam(t,n):this.addQueryParam(t,n)).join("&")}addQueryParams(e){const t=this.toQueryString(e);return t?`?${t}`:""}mergeRequestParams(e,t){return{...this.baseApiParams,...e,...t||{},headers:{...this.baseApiParams.headers||{},...e.headers||{},...t&&t.headers||{}}}}}class Ke extends Be{constructor(){super(...arguments),this.api={annotationQueuesCreateQueueItem:(e,t,s={})=>this.request({path:`/api/public/annotation-queues/${e}/items`,method:"POST",body:t,secure:!0,type:d.Json,format:"json",...s}),annotationQueuesDeleteQueueItem:(e,t,s={})=>this.request({path:`/api/public/annotation-queues/${e}/items/${t}`,method:"DELETE",secure:!0,format:"json",...s}),annotationQueuesGetQueue:(e,t={})=>this.request({path:`/api/public/annotation-queues/${e}`,method:"GET",secure:!0,format:"json",...t}),annotationQueuesGetQueueItem:(e,t,s={})=>this.request({path:`/api/public/annotation-queues/${e}/items/${t}`,method:"GET",secure:!0,format:"json",...s}),annotationQueuesListQueueItems:({queueId:e,...t},s={})=>this.request({path:`/api/public/annotation-queues/${e}/items`,method:"GET",query:t,secure:!0,format:"json",...s}),annotationQueuesListQueues:(e,t={})=>this.request({path:"/api/public/annotation-queues",method:"GET",query:e,secure:!0,format:"json",...t}),annotationQueuesUpdateQueueItem:(e,t,s,n={})=>this.request({path:`/api/public/annotation-queues/${e}/items/${t}`,method:"PATCH",body:s,secure:!0,type:d.Json,format:"json",...n}),commentsCreate:(e,t={})=>this.request({path:"/api/public/comments",method:"POST",body:e,secure:!0,type:d.Json,format:"json",...t}),commentsGet:(e,t={})=>this.request({path:"/api/public/comments",method:"GET",query:e,secure:!0,format:"json",...t}),commentsGetById:(e,t={})=>this.request({path:`/api/public/comments/${e}`,method:"GET",secure:!0,format:"json",...t}),datasetItemsCreate:(e,t={})=>this.request({path:"/api/public/dataset-items",method:"POST",body:e,secure:!0,type:d.Json,format:"json",...t}),datasetItemsDelete:(e,t={})=>this.request({path:`/api/public/dataset-items/${e}`,method:"DELETE",secure:!0,format:"json",...t}),datasetItemsGet:(e,t={})=>this.request({path:`/api/public/dataset-items/${e}`,method:"GET",secure:!0,format:"json",...t}),datasetItemsList:(e,t={})=>this.request({path:"/api/public/dataset-items",method:"GET",query:e,secure:!0,format:"json",...t}),datasetRunItemsCreate:(e,t={})=>this.request({path:"/api/public/dataset-run-items",method:"POST",body:e,secure:!0,type:d.Json,format:"json",...t}),datasetRunItemsList:(e,t={})=>this.request({path:"/api/public/dataset-run-items",method:"GET",query:e,secure:!0,...t}),datasetsCreate:(e,t={})=>this.request({path:"/api/public/v2/datasets",method:"POST",body:e,secure:!0,type:d.Json,format:"json",...t}),datasetsDeleteRun:(e,t,s={})=>this.request({path:`/api/public/datasets/${e}/runs/${t}`,method:"DELETE",secure:!0,format:"json",...s}),datasetsGet:(e,t={})=>this.request({path:`/api/public/v2/datasets/${e}`,method:"GET",secure:!0,format:"json",...t}),datasetsGetRun:(e,t,s={})=>this.request({path:`/api/public/datasets/${e}/runs/${t}`,method:"GET",secure:!0,format:"json",...s}),datasetsGetRuns:({datasetName:e,...t},s={})=>this.request({path:`/api/public/datasets/${e}/runs`,method:"GET",query:t,secure:!0,format:"json",...s}),datasetsList:(e,t={})=>this.request({path:"/api/public/v2/datasets",method:"GET",query:e,secure:!0,format:"json",...t}),healthHealth:(e={})=>this.request({path:"/api/public/health",method:"GET",format:"json",...e}),ingestionBatch:(e,t={})=>this.request({path:"/api/public/ingestion",method:"POST",body:e,secure:!0,type:d.Json,format:"json",...t}),mediaGet:(e,t={})=>this.request({path:`/api/public/media/${e}`,method:"GET",secure:!0,format:"json",...t}),mediaGetUploadUrl:(e,t={})=>this.request({path:"/api/public/media",method:"POST",body:e,secure:!0,type:d.Json,format:"json",...t}),mediaPatch:(e,t,s={})=>this.request({path:`/api/public/media/${e}`,method:"PATCH",body:t,secure:!0,type:d.Json,...s}),metricsMetrics:(e,t={})=>this.request({path:"/api/public/metrics",method:"GET",query:e,secure:!0,format:"json",...t}),modelsCreate:(e,t={})=>this.request({path:"/api/public/models",method:"POST",body:e,secure:!0,type:d.Json,format:"json",...t}),modelsDelete:(e,t={})=>this.request({path:`/api/public/models/${e}`,method:"DELETE",secure:!0,...t}),modelsGet:(e,t={})=>this.request({path:`/api/public/models/${e}`,method:"GET",secure:!0,format:"json",...t}),modelsList:(e,t={})=>this.request({path:"/api/public/models",method:"GET",query:e,secure:!0,format:"json",...t}),observationsGet:(e,t={})=>this.request({path:`/api/public/observations/${e}`,method:"GET",secure:!0,format:"json",...t}),observationsGetMany:(e,t={})=>this.request({path:"/api/public/observations",method:"GET",query:e,secure:!0,format:"json",...t}),organizationsGetOrganizationMemberships:(e={})=>this.request({path:"/api/public/organizations/memberships",method:"GET",secure:!0,format:"json",...e}),organizationsGetOrganizationProjects:(e={})=>this.request({path:"/api/public/organizations/projects",method:"GET",secure:!0,format:"json",...e}),organizationsGetProjectMemberships:(e,t={})=>this.request({path:`/api/public/projects/${e}/memberships`,method:"GET",secure:!0,format:"json",...t}),organizationsUpdateOrganizationMembership:(e,t={})=>this.request({path:"/api/public/organizations/memberships",method:"PUT",body:e,secure:!0,type:d.Json,format:"json",...t}),organizationsUpdateProjectMembership:(e,t,s={})=>this.request({path:`/api/public/projects/${e}/memberships`,method:"PUT",body:t,secure:!0,type:d.Json,format:"json",...s}),projectsCreate:(e,t={})=>this.request({path:"/api/public/projects",method:"POST",body:e,secure:!0,type:d.Json,format:"json",...t}),projectsCreateApiKey:(e,t,s={})=>this.request({path:`/api/public/projects/${e}/apiKeys`,method:"POST",body:t,secure:!0,type:d.Json,format:"json",...s}),projectsDelete:(e,t={})=>this.request({path:`/api/public/projects/${e}`,method:"DELETE",secure:!0,format:"json",...t}),projectsDeleteApiKey:(e,t,s={})=>this.request({path:`/api/public/projects/${e}/apiKeys/${t}`,method:"DELETE",secure:!0,format:"json",...s}),projectsGet:(e={})=>this.request({path:"/api/public/projects",method:"GET",secure:!0,format:"json",...e}),projectsGetApiKeys:(e,t={})=>this.request({path:`/api/public/projects/${e}/apiKeys`,method:"GET",secure:!0,format:"json",...t}),projectsUpdate:(e,t,s={})=>this.request({path:`/api/public/projects/${e}`,method:"PUT",body:t,secure:!0,type:d.Json,format:"json",...s}),promptsCreate:(e,t={})=>this.request({path:"/api/public/v2/prompts",method:"POST",body:e,secure:!0,type:d.Json,format:"json",...t}),promptsGet:({promptName:e,...t},s={})=>this.request({path:`/api/public/v2/prompts/${e}`,method:"GET",query:t,secure:!0,format:"json",...s}),promptsList:(e,t={})=>this.request({path:"/api/public/v2/prompts",method:"GET",query:e,secure:!0,format:"json",...t}),promptVersionUpdate:(e,t,s,n={})=>this.request({path:`/api/public/v2/prompts/${e}/versions/${t}`,method:"PATCH",body:s,secure:!0,type:d.Json,format:"json",...n}),scimCreateUser:(e,t={})=>this.request({path:"/api/public/scim/Users",method:"POST",body:e,secure:!0,type:d.Json,format:"json",...t}),scimDeleteUser:(e,t={})=>this.request({path:`/api/public/scim/Users/${e}`,method:"DELETE",secure:!0,format:"json",...t}),scimGetResourceTypes:(e={})=>this.request({path:"/api/public/scim/ResourceTypes",method:"GET",secure:!0,format:"json",...e}),scimGetSchemas:(e={})=>this.request({path:"/api/public/scim/Schemas",method:"GET",secure:!0,format:"json",...e}),scimGetServiceProviderConfig:(e={})=>this.request({path:"/api/public/scim/ServiceProviderConfig",method:"GET",secure:!0,format:"json",...e}),scimGetUser:(e,t={})=>this.request({path:`/api/public/scim/Users/${e}`,method:"GET",secure:!0,format:"json",...t}),scimListUsers:(e,t={})=>this.request({path:"/api/public/scim/Users",method:"GET",query:e,secure:!0,format:"json",...t}),scoreConfigsCreate:(e,t={})=>this.request({path:"/api/public/score-configs",method:"POST",body:e,secure:!0,type:d.Json,format:"json",...t}),scoreConfigsGet:(e,t={})=>this.request({path:"/api/public/score-configs",method:"GET",query:e,secure:!0,format:"json",...t}),scoreConfigsGetById:(e,t={})=>this.request({path:`/api/public/score-configs/${e}`,method:"GET",secure:!0,format:"json",...t}),scoreCreate:(e,t={})=>this.request({path:"/api/public/scores",method:"POST",body:e,secure:!0,type:d.Json,format:"json",...t}),scoreDelete:(e,t={})=>this.request({path:`/api/public/scores/${e}`,method:"DELETE",secure:!0,...t}),scoreV2Get:(e,t={})=>this.request({path:"/api/public/v2/scores",method:"GET",query:e,secure:!0,format:"json",...t}),scoreV2GetById:(e,t={})=>this.request({path:`/api/public/v2/scores/${e}`,method:"GET",secure:!0,format:"json",...t}),sessionsGet:(e,t={})=>this.request({path:`/api/public/sessions/${e}`,method:"GET",secure:!0,format:"json",...t}),sessionsList:(e,t={})=>this.request({path:"/api/public/sessions",method:"GET",query:e,secure:!0,format:"json",...t}),traceDelete:(e,t={})=>this.request({path:`/api/public/traces/${e}`,method:"DELETE",secure:!0,format:"json",...t}),traceDeleteMultiple:(e,t={})=>this.request({path:"/api/public/traces",method:"DELETE",body:e,secure:!0,type:d.Json,format:"json",...t}),traceGet:(e,t={})=>this.request({path:`/api/public/traces/${e}`,method:"GET",secure:!0,format:"json",...t}),traceList:(e,t={})=>this.request({path:"/api/public/traces",method:"GET",query:e,secure:!0,format:"json",...t})}}}var le="3.38.6";class Je extends ke{constructor(e){const t=ne.configLangfuseSDK(e);super(t),typeof window<"u"&&!("Deno"in window)?(this._storageKey=e?.persistence_name?`lf_${e.persistence_name}`:`lf_${t.publicKey}_langfuse`,this._storage=q(e?.persistence||"localStorage",window)):(this._storageKey=`lf_${t.publicKey}_langfuse`,this._storage=q("memory",void 0)),this.api=new Ke({baseUrl:this.baseUrl,baseApiParams:{headers:{"X-Langfuse-Sdk-Name":"langfuse-js","X-Langfuse-Sdk-Version":this.getLibraryVersion(),"X-Langfuse-Sdk-Variant":this.getLibraryId(),"X-Langfuse-Sdk-Integration":this.sdkIntegration,"X-Langfuse-Public-Key":this.publicKey,...this.additionalHeaders,...this.constructAuthorizationHeader(this.publicKey,this.secretKey)}}}).api}getPersistedProperty(e){return this._storageCache||(this._storageCache=JSON.parse(this._storage.getItem(this._storageKey)||"{}")||{}),this._storageCache[e]}setPersistedProperty(e,t){this._storageCache||(this._storageCache=JSON.parse(this._storage.getItem(this._storageKey)||"{}")||{}),t===null?delete this._storageCache[e]:this._storageCache[e]=t,this._storage.setItem(this._storageKey,JSON.stringify(this._storageCache))}fetch(e,t){return fetch(e,t)}getLibraryId(){return"langfuse"}getLibraryVersion(){return le}getCustomUserAgent(){}}class ot extends qe{constructor(e){const t=ne.configLangfuseSDK(e,!1);super(t),typeof window<"u"?(this._storageKey=e?.persistence_name?`lf_${e.persistence_name}`:`lf_${t.publicKey}_langfuse`,this._storage=q(e?.persistence||"localStorage",window)):(this._storageKey=`lf_${t.publicKey}_langfuse`,this._storage=q("memory",void 0))}getPersistedProperty(e){return this._storageCache||(this._storageCache=JSON.parse(this._storage.getItem(this._storageKey)||"{}")||{}),this._storageCache[e]}setPersistedProperty(e,t){this._storageCache||(this._storageCache=JSON.parse(this._storage.getItem(this._storageKey)||"{}")||{}),t===null?delete this._storageCache[e]:this._storageCache[e]=t,this._storage.setItem(this._storageKey,JSON.stringify(this._storageCache))}fetch(e,t){return fetch(e,t)}getLibraryId(){return"langfuse-frontend"}getLibraryVersion(){return le}getCustomUserAgent(){}}class S{static getInstance(e){return S.instance||(S.instance=new Je(e)),S.instance}}S.instance=null;const ze=r=>{let e={};e={frequency_penalty:r.frequency_penalty,logit_bias:r.logit_bias,logprobs:r.logprobs,max_tokens:r.max_tokens,n:r.n,presence_penalty:r.presence_penalty,seed:r.seed,stop:r.stop,stream:r.stream,temperature:r.temperature,top_p:r.top_p,user:r.user,response_format:r.response_format,top_logprobs:r.top_logprobs};let t=r.input;return r&&typeof r=="object"&&!Array.isArray(r)&&"messages"in r?(t={},t.messages=r.messages,"function_call"in r&&(t.function_call=r.function_call),"functions"in r&&(t.functions=r.functions),"tools"in r&&(t.tools=r.tools),"tool_choice"in r&&(t.tool_choice=r.tool_choice)):t||(t=r.prompt),{model:r.model,input:t,modelParameters:e}},he=r=>{if(r instanceof Object&&"output_text"in r&&r.output_text!=="")return r.output_text;if(typeof r=="object"&&r&&"output"in r&&Array.isArray(r.output)){const e=r.output;return e.length>1?e:e.length===1?e[0]:null}return r instanceof Object&&"choices"in r&&Array.isArray(r.choices)?"message"in r.choices[0]?r.choices[0].message:r.choices[0].text??"":""},He=r=>{if(me(r)){const{prompt_tokens:e,completion_tokens:t,total_tokens:s}=r.usage;return{input:e,output:t,total:s}}},pe=r=>{if("prompt_tokens"in r){const{prompt_tokens:e,completion_tokens:t,total_tokens:s,completion_tokens_details:n,prompt_tokens_details:o}=r;return{input:e,output:t,total:s,...Object.fromEntries(Object.entries(o??{}).map(([a,c])=>[`input_${a}`,c])),...Object.fromEntries(Object.entries(n??{}).map(([a,c])=>[`output_${a}`,c]))}}else if("input_tokens"in r){const{input_tokens:e,output_tokens:t,total_tokens:s,input_tokens_details:n,output_tokens_details:o}=r;return{input:e,output:t,total:s,...Object.fromEntries(Object.entries(n??{}).map(([a,c])=>[`input_${a}`,c])),...Object.fromEntries(Object.entries(o??{}).map(([a,c])=>[`output_${a}`,c]))}}},de=r=>{if(me(r))return pe(r.usage)},Qe=r=>{let e=!1;const s=r?.choices?.[0];try{if("delta"in s&&"tool_calls"in s.delta&&Array.isArray(s.delta.tool_calls))return e=!0,{isToolCall:e,data:s.delta.tool_calls[0]};if("delta"in s)return{isToolCall:e,data:s.delta?.content||""};if("text"in s)return{isToolCall:e,data:s.text||""}}catch{}return{isToolCall:!1,data:""}};function me(r){return r instanceof Object&&"usage"in r&&r.usage instanceof Object&&(typeof r.usage.prompt_tokens=="number"&&typeof r.usage.completion_tokens=="number"&&typeof r.usage.total_tokens=="number"||typeof r.usage.input_tokens=="number"&&typeof r.usage.output_tokens=="number"&&typeof r.usage.total_tokens=="number")}const Ve=r=>{let e="",t="";for(const s of r)e=s.function?.name||e,t+=s.function?.arguments||"";return{tool_calls:[{function:{name:e,arguments:t}}]}},fe=r=>{if(typeof r!="object"||r===null)return{model:void 0,modelParameters:void 0,metadata:void 0};const e="model"in r?r.model:void 0,t={},s=["max_output_tokens","parallel_tool_calls","store","temperature","tool_choice","top_p","truncation","user"],n={},o=["reasoning","incomplete_details","instructions","previous_response_id","tools","metadata","status","error"];for(const a of s){const c=a in r?r[a]:null;c!=null&&(t[a]=c)}for(const a of o){const c=a in r?r[a]:null;c&&(n[a]=c)}return{model:e,modelParameters:Object.keys(t).length>0?t:void 0,metadata:Object.keys(n).length>0?n:void 0}},Y=r=>r!=null&&typeof r=="object"&&typeof r[Symbol.asyncIterator]=="function",We=(r,e)=>(...t)=>Xe(r,e,...t),Xe=(r,e,...t)=>{const{model:s,input:n,modelParameters:o}=ze(t[0]??{}),a={...o,response_format:null},c={...e?.metadata,response_format:"response_format"in o?o.response_format:void 0};let i={model:s,input:n,modelParameters:a,name:e?.generationName,startTime:new Date,promptName:e?.langfusePrompt?.name,promptVersion:e?.langfusePrompt?.version,metadata:c},u;const h=e&&"parent"in e;h?(u=e.parent,i={...{...e,parent:void 0},...i,promptName:e?.promptName??e?.langfusePrompt?.name,promptVersion:e?.promptVersion??e?.langfusePrompt?.version}):u=S.getInstance(e?.clientInitParams).trace({...e,...i,id:e?.traceId,name:e?.traceName,timestamp:i.startTime});try{const l=r(...t);return Y(l)?Z(l,u,h,i):l instanceof Promise?l.then(m=>{if(Y(m))return Z(m,u,h,i);const y=he(m),_=He(m),E=de(m),{model:f,modelParameters:R,metadata:T}=fe(m);return u.generation({...i,output:y,endTime:new Date,usage:_,usageDetails:E,model:f||i.model,modelParameters:{...i.modelParameters,...R},metadata:{...i.metadata,...T}}),h||u.update({output:y}),m}).catch(m=>{throw u.generation({...i,endTime:new Date,statusMessage:String(m),level:"ERROR",usage:{inputCost:0,outputCost:0,totalCost:0},costDetails:{input:0,output:0,total:0}}),m}):l}catch(l){throw u.generation({...i,endTime:new Date,statusMessage:String(l),level:"ERROR",usage:{inputCost:0,outputCost:0,totalCost:0},costDetails:{input:0,output:0,total:0}}),l}};function Z(r,e,t,s){async function*n(){const o=r,a=[],c=[];let i=null,u=null,h,l=null;for await(const p of o){if(i=i??new Date,typeof p=="object"&&p&&"response"in p){const y=p.response;l=he(y),h=de(y);const{model:_,modelParameters:E,metadata:f}=fe(y);s.model=_??s.model,s.modelParameters={...s.modelParameters,...E},s.metadata={...s.metadata,...f}}typeof p=="object"&&p!=null&&"usage"in p&&(u=p.usage);const m=Qe(p);m.isToolCall?c.push(m.data):a.push(m.data),yield p}l=l??(c.length>0?Ve(c):a.join("")),e.generation({...s,output:l,endTime:new Date,completionStartTime:i,usage:u?{input:"prompt_tokens"in u?u.prompt_tokens:void 0,output:"completion_tokens"in u?u.completion_tokens:void 0,total:"total_tokens"in u?u.total_tokens:void 0}:void 0,usageDetails:h??(u?pe(u):void 0)}),t||e.update({output:l})}return n()}const Ye=(r,e)=>new Proxy(r,{get(t,s,n){const o=t[s],a=`${r.constructor?.name}.${s.toString()}`,c=e?.generationName??a,i=e&&"traceName"in e?e.traceName:c,u={...e,generationName:c,traceName:i};if(s==="flushAsync"){let l;return e&&"parent"in e?l=e.parent.client:l=S.getInstance(),l.flushAsync.bind(l)}if(s==="shutdownAsync"){let l;return e&&"parent"in e?l=e.parent.client:l=S.getInstance(),l.shutdownAsync.bind(l)}return typeof o=="function"?We(o.bind(t),u):o&&!Array.isArray(o)&&!(o instanceof Date)&&typeof o=="object"?Ye(o,u):Reflect.get(t,s,n)}});export{Je as Langfuse,v as LangfuseMedia,ot as LangfuseWeb,Je as default,Ye as observeOpenAI};
@@ -1,25 +0,0 @@
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-CB1s6Wr6.js";import"./chunk-VL2OQCWN-iRVOQjqe.js";import"./index-DUf1336L.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
-
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
-
5
- `))}function ns(t){const e=[];for(const n of t)if(n._getType()==="tool")if(typeof n.content=="string"){const s=e[e.length-1];s?._getType()==="human"&&Array.isArray(s.content)&&"type"in s.content[0]&&s.content[0].type==="tool_result"?s.content.push({type:"tool_result",content:n.content,tool_use_id:n.tool_call_id}):e.push(new St({content:[{type:"tool_result",content:n.content,tool_use_id:n.tool_call_id}]}))}else e.push(new St({content:[{type:"tool_result",...n.content!=null?{content:at(n)}:{},tool_use_id:n.tool_call_id}]}));else e.push(n);return e}function Et(t){if(t.id===void 0)throw new Error('Anthropic requires all tool calls to have an "id".');return{type:"tool_use",id:t.id,name:t.name,input:t.args}}function*ss(t){const e=["bash_code_execution_tool_result","input_json_delta","server_tool_use","text_editor_code_execution_tool_result","tool_result","tool_use","web_search_result","web_search_tool_result"],n=["text","text_delta"];for(const s of t){Bn(s)&&(yield Ln(s,Qn));const r="cache_control"in s?s.cache_control:void 0;if(s.type==="image_url"){let i;typeof s.image_url=="string"?i=vt(s.image_url):typeof s.image_url=="object"&&s.image_url!==null&&"url"in s.image_url&&typeof s.image_url.url=="string"&&(i=vt(s.image_url.url)),i&&(yield{type:"image",source:i,...r?{cache_control:r}:{}})}else{if(Vn(s))return s;if(s.type==="document")yield{...s,...r?{cache_control:r}:{}};else if(Jn(s))yield{type:"thinking",thinking:s.thinking,signature:s.signature,...r?{cache_control:r}:{}};else if(Xn(s))yield{type:"redacted_thinking",data:s.data,...r?{cache_control:r}:{}};else if(zn(s))yield{type:"search_result",title:s.title,source:s.source,..."cache_control"in s&&s.cache_control?{cache_control:s.cache_control}:{},..."citations"in s&&s.citations?{citations:s.citations}:{},content:s.content};else if(n.find(i=>i===s.type)&&"text"in s)yield{type:"text",text:s.text,...r?{cache_control:r}:{},..."citations"in s&&s.citations?{citations:s.citations}:{}};else if(e.find(i=>i===s.type)){const i={...s};if("index"in i&&delete i.index,i.type==="input_json_delta"&&(i.type="tool_use"),"input"in i&&typeof i.input=="string")try{i.input=JSON.parse(i.input)}catch{i.input={}}yield{...i,...r?{cache_control:r}:{}}}else s.type==="container_upload"&&(yield{...s,...r?{cache_control:r}:{}})}}}function at(t){const{content:e}=t;return typeof e=="string"?e:Array.from(ss(e))}function Pt(t){const e=ns(t);let n;e.length>0&&e[0]._getType()==="system"&&(n=t[0].content);const r=(n!==void 0?e.slice(1):e).map(i=>{let a;if(i._getType()==="human")a="user";else if(i._getType()==="ai")a="assistant";else if(i._getType()==="tool")a="user";else throw i._getType()==="system"?new Error("System messages are only permitted as the first passed message."):new Error(`Message type "${i.type}" is not supported.`);if(xt(i)&&i.response_metadata?.output_version==="v1")return{role:a,content:ts(i)};if(xt(i)&&i.tool_calls?.length){if(typeof i.content=="string")return i.content===""?{role:a,content:i.tool_calls.map(Et)}:{role:a,content:[{type:"text",text:i.content},...i.tool_calls.map(Et)]};{const{content:c}=i;return!i.tool_calls.every(d=>c.find(f=>(f.type==="tool_use"||f.type==="input_json_delta"||f.type==="server_tool_use")&&f.id===d.id))&&console.warn('The "tool_calls" field on a message is only respected if content is a string.'),{role:a,content:at(i)}}}else return{role:a,content:at(i)}});return{messages:rs(r),system:n}}function rs(t){if(!t||t.length<=1)return t;const e=[];let n=t[0];const s=i=>typeof i=="string"?[{type:"text",text:i}]:i,r=i=>i.role!=="user"||typeof i.content=="string"?!1:Array.isArray(i.content)&&i.content.every(a=>a.type==="tool_result");for(let i=1;i<t.length;i+=1){const a=t[i];r(n)&&r(a)?n={...n,content:[...s(n.content),...s(a.content)]}:(e.push(n),n=a)}return e.push(n),e}function is(t,e){const n={model_provider:"anthropic"};if(t.type==="message_start"){const{content:s,usage:r,...i}=t.message,a={};for(const[m,_]of Object.entries(i))_!=null&&(a[m]=_);const{input_tokens:c,output_tokens:l,...d}=r??{},f={input_tokens:c,output_tokens:l,total_tokens:c+l,input_token_details:{cache_creation:d.cache_creation_input_tokens,cache_read:d.cache_read_input_tokens}};return{chunk:new A({content:e.coerceContentToString?"":[],additional_kwargs:a,usage_metadata:e.streamUsage?f:void 0,response_metadata:{...n,usage:{...d}},id:t.message.id})}}else if(t.type==="message_delta"){const s={input_tokens:0,output_tokens:t.usage.output_tokens,total_tokens:t.usage.output_tokens,input_token_details:{cache_creation:t.usage.cache_creation_input_tokens,cache_read:t.usage.cache_read_input_tokens}},r="context_management"in t.delta?{context_management:t.delta.context_management}:void 0;return{chunk:new A({content:e.coerceContentToString?"":[],response_metadata:r,additional_kwargs:{...t.delta},usage_metadata:e.streamUsage?s:void 0})}}else if(t.type==="content_block_start"&&["tool_use","document","server_tool_use","web_search_tool_result"].includes(t.content_block.type)){const s=t.content_block;let r;return s.type==="tool_use"?r=[{id:s.id,index:t.index,name:s.name,args:""}]:r=[],{chunk:new A({content:e.coerceContentToString?"":[{index:t.index,...t.content_block,input:s.type==="server_tool_use"||s.type==="tool_use"?"":void 0}],response_metadata:n,additional_kwargs:{},tool_call_chunks:r})}}else if(t.type==="content_block_delta"&&["text_delta","citations_delta","thinking_delta","signature_delta"].includes(t.delta.type)){if(e.coerceContentToString&&"text"in t.delta)return{chunk:new A({content:t.delta.text})};{const s=t.delta;return"citation"in s&&(s.citations=[s.citation],delete s.citation),s.type==="thinking_delta"||s.type==="signature_delta"?{chunk:new A({content:[{index:t.index,...s,type:"thinking"}],response_metadata:n})}:{chunk:new A({content:[{index:t.index,...s,type:"text"}],response_metadata:n})}}}else{if(t.type==="content_block_delta"&&t.delta.type==="input_json_delta")return{chunk:new A({content:e.coerceContentToString?"":[{index:t.index,input:t.delta.partial_json,type:t.delta.type}],response_metadata:n,additional_kwargs:{},tool_call_chunks:[{index:t.index,args:t.delta.partial_json}]})};if(t.type==="content_block_start"&&t.content_block.type==="text"){const s=t.content_block?.text;if(s!==void 0)return{chunk:new A({content:e.coerceContentToString?s:[{index:t.index,...t.content_block}],response_metadata:n,additional_kwargs:{}})}}else{if(t.type==="content_block_start"&&t.content_block.type==="redacted_thinking")return{chunk:new A({content:e.coerceContentToString?"":[{index:t.index,...t.content_block}],response_metadata:n})};if(t.type==="content_block_start"&&t.content_block.type==="thinking"){const s=t.content_block.thinking;return{chunk:new A({content:e.coerceContentToString?s:[{index:t.index,...t.content_block}],response_metadata:n})}}}}return null}function as(t,e){const n={...e,model_provider:"anthropic"},s=e.usage,r=s!=null?{input_tokens:s.input_tokens??0,output_tokens:s.output_tokens??0,total_tokens:(s.input_tokens??0)+(s.output_tokens??0),input_token_details:{cache_creation:s.cache_creation_input_tokens,cache_read:s.cache_read_input_tokens}}:void 0;if(t.length===1&&t[0].type==="text")return[{text:t[0].text,message:new kt({content:t[0].text,additional_kwargs:e,usage_metadata:r,response_metadata:n,id:e.id})}];{const i=sn(t);return[{text:"",message:new kt({content:t,additional_kwargs:e,tool_calls:i,usage_metadata:r,response_metadata:n,id:e.id})}]}}function xe(t,e){return t.lc_error_code=e,t.message=`${t.message}
6
-
7
- Troubleshooting URL: https://js.langchain.com/docs/troubleshooting/errors/${e}/
8
- `,t}function Ot(t){let e;return t.status===400&&t.message.includes("tool")?e=xe(t,"INVALID_TOOL_RESULTS"):t.status===401?e=xe(t,"MODEL_AUTHENTICATION"):t.status===404?e=xe(t,"MODEL_NOT_FOUND"):t.status===429?e=xe(t,"MODEL_RATE_LIMIT"):e=t,e}function u(t,e,n,s,r){if(typeof e=="function"?t!==e||!0:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(t,n),n}function o(t,e,n,s){if(n==="a"&&!s)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!s:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return n==="m"?s:n==="a"?s.call(t):s?s.value:e.get(t)}let rn=function(){const{crypto:t}=globalThis;if(t?.randomUUID)return rn=t.randomUUID.bind(t),t.randomUUID();const e=new Uint8Array(1),n=t?()=>t.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,s=>(+s^n()&15>>+s/4).toString(16))};function fe(t){return typeof t=="object"&&t!==null&&("name"in t&&t.name==="AbortError"||"message"in t&&String(t.message).includes("FetchRequestCanceledException"))}const ot=t=>{if(t instanceof Error)return t;if(typeof t=="object"&&t!==null){try{if(Object.prototype.toString.call(t)==="[object Error]"){const e=new Error(t.message,t.cause?{cause:t.cause}:{});return t.stack&&(e.stack=t.stack),t.cause&&!e.cause&&(e.cause=t.cause),t.name&&(e.name=t.name),e}}catch{}try{return new Error(JSON.stringify(t))}catch{}}return new Error(t)};class p extends Error{}class w extends p{constructor(e,n,s,r){super(`${w.makeMessage(e,n,s)}`),this.status=e,this.headers=r,this.requestID=r?.get("request-id"),this.error=n}static makeMessage(e,n,s){const r=n?.message?typeof n.message=="string"?n.message:JSON.stringify(n.message):n?JSON.stringify(n):s;return e&&r?`${e} ${r}`:e?`${e} status code (no body)`:r||"(no status code or body)"}static generate(e,n,s,r){if(!e||!r)return new He({message:s,cause:ot(n)});const i=n;return e===400?new on(e,i,s,r):e===401?new cn(e,i,s,r):e===403?new ln(e,i,s,r):e===404?new un(e,i,s,r):e===409?new hn(e,i,s,r):e===422?new dn(e,i,s,r):e===429?new pn(e,i,s,r):e>=500?new fn(e,i,s,r):new w(e,i,s,r)}}class v extends w{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class He extends w{constructor({message:e,cause:n}){super(void 0,void 0,e||"Connection error.",void 0),n&&(this.cause=n)}}class an extends He{constructor({message:e}={}){super({message:e??"Request timed out."})}}class on extends w{}class cn extends w{}class ln extends w{}class un extends w{}class hn extends w{}class dn extends w{}class pn extends w{}class fn extends w{}const os=/^[a-z][a-z0-9+.-]*:/i,cs=t=>os.test(t);let ct=t=>(ct=Array.isArray,ct(t)),Ct=ct;function It(t){return typeof t!="object"?{}:t??{}}function ls(t){if(!t)return!0;for(const e in t)return!1;return!0}function us(t,e){return Object.prototype.hasOwnProperty.call(t,e)}const hs=(t,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new p(`${t} must be an integer`);if(e<0)throw new p(`${t} must be a positive integer`);return e},mn=t=>{try{return JSON.parse(t)}catch{return}},ds=t=>new Promise(e=>setTimeout(e,t)),z="0.65.0",ps=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function fs(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}const ms=()=>{const t=fs();if(t==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":z,"X-Stainless-OS":$t(Deno.build.os),"X-Stainless-Arch":Nt(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":z,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(t==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":z,"X-Stainless-OS":$t(globalThis.process.platform??"unknown"),"X-Stainless-Arch":Nt(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};const e=gs();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":z,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":z,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function gs(){if(typeof navigator>"u"||!navigator)return null;const t=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(const{key:e,pattern:n}of t){const s=n.exec(navigator.userAgent);if(s){const r=s[1]||0,i=s[2]||0,a=s[3]||0;return{browser:e,version:`${r}.${i}.${a}`}}}return null}const Nt=t=>t==="x32"?"x32":t==="x86_64"||t==="x64"?"x64":t==="arm"?"arm":t==="aarch64"||t==="arm64"?"arm64":t?`other:${t}`:"unknown",$t=t=>(t=t.toLowerCase(),t.includes("ios")?"iOS":t==="android"?"Android":t==="darwin"?"MacOS":t==="win32"?"Windows":t==="freebsd"?"FreeBSD":t==="openbsd"?"OpenBSD":t==="linux"?"Linux":t?`Other:${t}`:"Unknown");let jt;const _s=()=>jt??(jt=ms());function ys(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Anthropic({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function gn(...t){const e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...t)}function _n(t){let e=Symbol.asyncIterator in t?t[Symbol.asyncIterator]():t[Symbol.iterator]();return gn({start(){},async pull(n){const{done:s,value:r}=await e.next();s?n.close():n.enqueue(r)},async cancel(){await e.return?.()}})}function pt(t){if(t[Symbol.asyncIterator])return t;const e=t.getReader();return{async next(){try{const n=await e.read();return n?.done&&e.releaseLock(),n}catch(n){throw e.releaseLock(),n}},async return(){const n=e.cancel();return e.releaseLock(),await n,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function ws(t){if(t===null||typeof t!="object")return;if(t[Symbol.asyncIterator]){await t[Symbol.asyncIterator]().return?.();return}const e=t.getReader(),n=e.cancel();e.releaseLock(),await n}const bs=({headers:t,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});function xs(t){let e=0;for(const r of t)e+=r.length;const n=new Uint8Array(e);let s=0;for(const r of t)n.set(r,s),s+=r.length;return n}let Bt;function ft(t){let e;return(Bt??(e=new globalThis.TextEncoder,Bt=e.encode.bind(e)))(t)}let Lt;function Ut(t){let e;return(Lt??(e=new globalThis.TextDecoder,Lt=e.decode.bind(e)))(t)}var k,M;class me{constructor(){k.set(this,void 0),M.set(this,void 0),u(this,k,new Uint8Array),u(this,M,null)}decode(e){if(e==null)return[];const n=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?ft(e):e;u(this,k,xs([o(this,k,"f"),n]));const s=[];let r;for(;(r=Ss(o(this,k,"f"),o(this,M,"f")))!=null;){if(r.carriage&&o(this,M,"f")==null){u(this,M,r.index);continue}if(o(this,M,"f")!=null&&(r.index!==o(this,M,"f")+1||r.carriage)){s.push(Ut(o(this,k,"f").subarray(0,o(this,M,"f")-1))),u(this,k,o(this,k,"f").subarray(o(this,M,"f"))),u(this,M,null);continue}const i=o(this,M,"f")!==null?r.preceding-1:r.preceding,a=Ut(o(this,k,"f").subarray(0,i));s.push(a),u(this,k,o(this,k,"f").subarray(r.index)),u(this,M,null)}return s}flush(){return o(this,k,"f").length?this.decode(`
9
- `):[]}}k=new WeakMap,M=new WeakMap;me.NEWLINE_CHARS=new Set([`
10
- `,"\r"]);me.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function Ss(t,e){for(let r=e??0;r<t.length;r++){if(t[r]===10)return{preceding:r,index:r+1,carriage:!1};if(t[r]===13)return{preceding:r,index:r+1,carriage:!0}}return null}function ks(t){for(let s=0;s<t.length-1;s++){if(t[s]===10&&t[s+1]===10||t[s]===13&&t[s+1]===13)return s+2;if(t[s]===13&&t[s+1]===10&&s+3<t.length&&t[s+2]===13&&t[s+3]===10)return s+4}return-1}const We={off:0,error:200,warn:300,info:400,debug:500},qt=(t,e,n)=>{if(t){if(us(We,t))return t;x(n).warn(`${e} was set to ${JSON.stringify(t)}, expected one of ${JSON.stringify(Object.keys(We))}`)}};function de(){}function Se(t,e,n){return!e||We[t]>We[n]?de:e[t].bind(e)}const Ms={error:de,warn:de,info:de,debug:de};let Wt=new WeakMap;function x(t){const e=t.logger,n=t.logLevel??"off";if(!e)return Ms;const s=Wt.get(e);if(s&&s[0]===n)return s[1];const r={error:Se("error",e,n),warn:Se("warn",e,n),info:Se("info",e,n),debug:Se("debug",e,n)};return Wt.set(e,[n,r]),r}const D=t=>(t.options&&(t.options={...t.options},delete t.options.headers),t.headers&&(t.headers=Object.fromEntries((t.headers instanceof Headers?[...t.headers]:Object.entries(t.headers)).map(([e,n])=>[e,e.toLowerCase()==="x-api-key"||e.toLowerCase()==="authorization"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":n]))),"retryOfRequestLogID"in t&&(t.retryOfRequestLogID&&(t.retryOf=t.retryOfRequestLogID),delete t.retryOfRequestLogID),t);var Y;class C{constructor(e,n,s){this.iterator=e,Y.set(this,void 0),this.controller=n,u(this,Y,s)}static fromSSEResponse(e,n,s){let r=!1;const i=s?x(s):console;async function*a(){if(r)throw new p("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");r=!0;let c=!1;try{for await(const l of Ts(e,n)){if(l.event==="completion")try{yield JSON.parse(l.data)}catch(d){throw i.error("Could not parse message into JSON:",l.data),i.error("From chunk:",l.raw),d}if(l.event==="message_start"||l.event==="message_delta"||l.event==="message_stop"||l.event==="content_block_start"||l.event==="content_block_delta"||l.event==="content_block_stop")try{yield JSON.parse(l.data)}catch(d){throw i.error("Could not parse message into JSON:",l.data),i.error("From chunk:",l.raw),d}if(l.event!=="ping"&&l.event==="error")throw new w(void 0,mn(l.data)??l.data,void 0,e.headers)}c=!0}catch(l){if(fe(l))return;throw l}finally{c||n.abort()}}return new C(a,n,s)}static fromReadableStream(e,n,s){let r=!1;async function*i(){const c=new me,l=pt(e);for await(const d of l)for(const f of c.decode(d))yield f;for(const d of c.flush())yield d}async function*a(){if(r)throw new p("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");r=!0;let c=!1;try{for await(const l of i())c||l&&(yield JSON.parse(l));c=!0}catch(l){if(fe(l))return;throw l}finally{c||n.abort()}}return new C(a,n,s)}[(Y=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){const e=[],n=[],s=this.iterator(),r=i=>({next:()=>{if(i.length===0){const a=s.next();e.push(a),n.push(a)}return i.shift()}});return[new C(()=>r(e),this.controller,o(this,Y,"f")),new C(()=>r(n),this.controller,o(this,Y,"f"))]}toReadableStream(){const e=this;let n;return gn({async start(){n=e[Symbol.asyncIterator]()},async pull(s){try{const{value:r,done:i}=await n.next();if(i)return s.close();const a=ft(JSON.stringify(r)+`
11
- `);s.enqueue(a)}catch(r){s.error(r)}},async cancel(){await n.return?.()}})}}async function*Ts(t,e){if(!t.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new p("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new p("Attempted to iterate over a response with no body");const n=new As,s=new me,r=pt(t.body);for await(const i of Rs(r))for(const a of s.decode(i)){const c=n.decode(a);c&&(yield c)}for(const i of s.flush()){const a=n.decode(i);a&&(yield a)}}async function*Rs(t){let e=new Uint8Array;for await(const n of t){if(n==null)continue;const s=n instanceof ArrayBuffer?new Uint8Array(n):typeof n=="string"?ft(n):n;let r=new Uint8Array(e.length+s.length);r.set(e),r.set(s,e.length),e=r;let i;for(;(i=ks(e))!==-1;)yield e.slice(0,i),e=e.slice(i)}e.length>0&&(yield e)}class As{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;const i={event:this.event,data:this.data.join(`
12
- `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],i}if(this.chunks.push(e),e.startsWith(":"))return null;let[n,s,r]=vs(e,":");return r.startsWith(" ")&&(r=r.substring(1)),n==="event"?this.event=r:n==="data"&&this.data.push(r),null}}function vs(t,e){const n=t.indexOf(e);return n!==-1?[t.substring(0,n),e,t.substring(n+e.length)]:[t,"",""]}async function yn(t,e){const{response:n,requestLogID:s,retryOfRequestLogID:r,startTime:i}=e,a=await(async()=>{if(e.options.stream)return x(t).debug("response",n.status,n.url,n.headers,n.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(n,e.controller):C.fromSSEResponse(n,e.controller);if(n.status===204)return null;if(e.options.__binaryResponse)return n;const l=n.headers.get("content-type")?.split(";")[0]?.trim();if(l?.includes("application/json")||l?.endsWith("+json")){const m=await n.json();return wn(m,n)}return await n.text()})();return x(t).debug(`[${s}] response parsed`,D({retryOfRequestLogID:r,url:n.url,status:n.status,body:a,durationMs:Date.now()-i})),a}function wn(t,e){return!t||typeof t!="object"||Array.isArray(t)?t:Object.defineProperty(t,"_request_id",{value:e.headers.get("request-id"),enumerable:!1})}var pe;class Ke extends Promise{constructor(e,n,s=yn){super(r=>{r(null)}),this.responsePromise=n,this.parseResponse=s,pe.set(this,void 0),u(this,pe,e)}_thenUnwrap(e){return new Ke(o(this,pe,"f"),this.responsePromise,async(n,s)=>wn(e(await this.parseResponse(n,s),s),s.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){const[e,n]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:n,request_id:n.headers.get("request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(o(this,pe,"f"),e))),this.parsedPromise}then(e,n){return this.parse().then(e,n)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}}pe=new WeakMap;var ke;class Es{constructor(e,n,s,r){ke.set(this,void 0),u(this,ke,e),this.options=r,this.response=n,this.body=s}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){const e=this.nextPageRequestOptions();if(!e)throw new p("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await o(this,ke,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(ke=new WeakMap,Symbol.asyncIterator)](){for await(const e of this.iterPages())for(const n of e.getPaginatedItems())yield n}}class Ps extends Ke{constructor(e,n,s){super(e,n,async(r,i)=>new s(r,i.response,await yn(r,i),i.options))}async*[Symbol.asyncIterator](){const e=await this;for await(const n of e)yield n}}class ge extends Es{constructor(e,n,s,r){super(e,n,s,r),this.data=s.data||[],this.has_more=s.has_more||!1,this.first_id=s.first_id||null,this.last_id=s.last_id||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){if(this.options.query?.before_id){const n=this.first_id;return n?{...this.options,query:{...It(this.options.query),before_id:n}}:null}const e=this.last_id;return e?{...this.options,query:{...It(this.options.query),after_id:e}}:null}}const bn=()=>{if(typeof File>"u"){const{process:t}=globalThis,e=typeof t?.versions?.node=="string"&&parseInt(t.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(e?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function Q(t,e,n){return bn(),new File(t,e??"unknown_file",n)}function Ue(t){return(typeof t=="object"&&t!==null&&("name"in t&&t.name&&String(t.name)||"url"in t&&t.url&&String(t.url)||"filename"in t&&t.filename&&String(t.filename)||"path"in t&&t.path&&String(t.path))||"").split(/[\\/]/).pop()||void 0}const xn=t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function",Os=async(t,e)=>({...t,body:await Is(t.body,e)}),Ft=new WeakMap;function Cs(t){const e=typeof t=="function"?t:t.fetch,n=Ft.get(e);if(n)return n;const s=(async()=>{try{const r="Response"in e?e.Response:(await e("data:,")).constructor,i=new FormData;return i.toString()!==await new r(i).text()}catch{return!0}})();return Ft.set(e,s),s}const Is=async(t,e)=>{if(!await Cs(e))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");const n=new FormData;return await Promise.all(Object.entries(t||{}).map(([s,r])=>lt(n,s,r))),n},Ns=t=>t instanceof Blob&&"name"in t,lt=async(t,e,n)=>{if(n!==void 0){if(n==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")t.append(e,String(n));else if(n instanceof Response){let s={};const r=n.headers.get("Content-Type");r&&(s={type:r}),t.append(e,Q([await n.blob()],Ue(n),s))}else if(xn(n))t.append(e,Q([await new Response(_n(n)).blob()],Ue(n)));else if(Ns(n))t.append(e,Q([n],Ue(n),{type:n.type}));else if(Array.isArray(n))await Promise.all(n.map(s=>lt(t,e+"[]",s)));else if(typeof n=="object")await Promise.all(Object.entries(n).map(([s,r])=>lt(t,`${e}[${s}]`,r)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${n} instead`)}},Sn=t=>t!=null&&typeof t=="object"&&typeof t.size=="number"&&typeof t.type=="string"&&typeof t.text=="function"&&typeof t.slice=="function"&&typeof t.arrayBuffer=="function",$s=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&Sn(t),js=t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function";async function Bs(t,e,n){if(bn(),t=await t,e||(e=Ue(t)),$s(t))return t instanceof File&&e==null&&n==null?t:Q([await t.arrayBuffer()],e??t.name,{type:t.type,lastModified:t.lastModified,...n});if(js(t)){const r=await t.blob();return e||(e=new URL(t.url).pathname.split(/[\\/]/).pop()),Q(await ut(r),e,n)}const s=await ut(t);if(!n?.type){const r=s.find(i=>typeof i=="object"&&"type"in i&&i.type);typeof r=="string"&&(n={...n,type:r})}return Q(s,e,n)}async function ut(t){let e=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)e.push(t);else if(Sn(t))e.push(t instanceof Blob?t:await t.arrayBuffer());else if(xn(t))for await(const n of t)e.push(...await ut(n));else{const n=t?.constructor?.name;throw new Error(`Unexpected data type: ${typeof t}${n?`; constructor: ${n}`:""}${Ls(t)}`)}return e}function Ls(t){return typeof t!="object"||t===null?"":`; props: [${Object.getOwnPropertyNames(t).map(n=>`"${n}"`).join(", ")}]`}class B{constructor(e){this._client=e}}const kn=Symbol.for("brand.privateNullableHeaders");function*Us(t){if(!t)return;if(kn in t){const{values:s,nulls:r}=t;yield*s.entries();for(const i of r)yield[i,null];return}let e=!1,n;t instanceof Headers?n=t.entries():Ct(t)?n=t:(e=!0,n=Object.entries(t??{}));for(let s of n){const r=s[0];if(typeof r!="string")throw new TypeError("expected header name to be a string");const i=Ct(s[1])?s[1]:[s[1]];let a=!1;for(const c of i)c!==void 0&&(e&&!a&&(a=!0,yield[r,null]),yield[r,c])}}const g=t=>{const e=new Headers,n=new Set;for(const s of t){const r=new Set;for(const[i,a]of Us(s)){const c=i.toLowerCase();r.has(c)||(e.delete(i),r.add(c)),a===null?(e.delete(i),n.add(c)):(e.append(i,a),n.delete(c))}}return{[kn]:!0,values:e,nulls:n}};function Mn(t){return t.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}const Dt=Object.freeze(Object.create(null)),qs=(t=Mn)=>function(n,...s){if(n.length===1)return n[0];let r=!1;const i=[],a=n.reduce((f,m,_)=>{/[?#]/.test(m)&&(r=!0);const h=s[_];let b=(r?encodeURIComponent:t)(""+h);return _!==s.length&&(h==null||typeof h=="object"&&h.toString===Object.getPrototypeOf(Object.getPrototypeOf(h.hasOwnProperty??Dt)??Dt)?.toString)&&(b=h+"",i.push({start:f.length+m.length,length:b.length,error:`Value of type ${Object.prototype.toString.call(h).slice(8,-1)} is not a valid path parameter`})),f+m+(_===s.length?"":b)},""),c=a.split(/[?#]/,1)[0],l=new RegExp("(?<=^|\\/)(?:\\.|%2e){1,2}(?=\\/|$)","gi");let d;for(;(d=l.exec(c))!==null;)i.push({start:d.index,length:d[0].length,error:`Value "${d[0]}" can't be safely passed as a path parameter`});if(i.sort((f,m)=>f.start-m.start),i.length>0){let f=0;const m=i.reduce((_,h)=>{const b=" ".repeat(h.start-f),W="^".repeat(h.length);return f=h.start+h.length,_+b+W},"");throw new p(`Path parameters result in path with invalid segments:
13
- ${i.map(_=>_.error).join(`
14
- `)}
15
- ${a}
16
- ${m}`)}return a},E=qs(Mn);class Tn extends B{list(e={},n){const{betas:s,...r}=e??{};return this._client.getAPIList("/v1/files",ge,{query:r,...n,headers:g([{"anthropic-beta":[...s??[],"files-api-2025-04-14"].toString()},n?.headers])})}delete(e,n={},s){const{betas:r}=n??{};return this._client.delete(E`/v1/files/${e}`,{...s,headers:g([{"anthropic-beta":[...r??[],"files-api-2025-04-14"].toString()},s?.headers])})}download(e,n={},s){const{betas:r}=n??{};return this._client.get(E`/v1/files/${e}/content`,{...s,headers:g([{"anthropic-beta":[...r??[],"files-api-2025-04-14"].toString(),Accept:"application/binary"},s?.headers]),__binaryResponse:!0})}retrieveMetadata(e,n={},s){const{betas:r}=n??{};return this._client.get(E`/v1/files/${e}`,{...s,headers:g([{"anthropic-beta":[...r??[],"files-api-2025-04-14"].toString()},s?.headers])})}upload(e,n){const{betas:s,...r}=e;return this._client.post("/v1/files",Os({body:r,...n,headers:g([{"anthropic-beta":[...s??[],"files-api-2025-04-14"].toString()},n?.headers])},this._client))}}let Rn=class extends B{retrieve(e,n={},s){const{betas:r}=n??{};return this._client.get(E`/v1/models/${e}?beta=true`,{...s,headers:g([{...r?.toString()!=null?{"anthropic-beta":r?.toString()}:void 0},s?.headers])})}list(e={},n){const{betas:s,...r}=e??{};return this._client.getAPIList("/v1/models?beta=true",ge,{query:r,...n,headers:g([{...s?.toString()!=null?{"anthropic-beta":s?.toString()}:void 0},n?.headers])})}};class Je{constructor(e,n){this.iterator=e,this.controller=n}async*decoder(){const e=new me;for await(const n of this.iterator)for(const s of e.decode(n))yield JSON.parse(s);for(const n of e.flush())yield JSON.parse(n)}[Symbol.asyncIterator](){return this.decoder()}static fromResponse(e,n){if(!e.body)throw n.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new p("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new p("Attempted to iterate over a response with no body");return new Je(pt(e.body),n)}}let An=class extends B{create(e,n){const{betas:s,...r}=e;return this._client.post("/v1/messages/batches?beta=true",{body:r,...n,headers:g([{"anthropic-beta":[...s??[],"message-batches-2024-09-24"].toString()},n?.headers])})}retrieve(e,n={},s){const{betas:r}=n??{};return this._client.get(E`/v1/messages/batches/${e}?beta=true`,{...s,headers:g([{"anthropic-beta":[...r??[],"message-batches-2024-09-24"].toString()},s?.headers])})}list(e={},n){const{betas:s,...r}=e??{};return this._client.getAPIList("/v1/messages/batches?beta=true",ge,{query:r,...n,headers:g([{"anthropic-beta":[...s??[],"message-batches-2024-09-24"].toString()},n?.headers])})}delete(e,n={},s){const{betas:r}=n??{};return this._client.delete(E`/v1/messages/batches/${e}?beta=true`,{...s,headers:g([{"anthropic-beta":[...r??[],"message-batches-2024-09-24"].toString()},s?.headers])})}cancel(e,n={},s){const{betas:r}=n??{};return this._client.post(E`/v1/messages/batches/${e}/cancel?beta=true`,{...s,headers:g([{"anthropic-beta":[...r??[],"message-batches-2024-09-24"].toString()},s?.headers])})}async results(e,n={},s){const r=await this.retrieve(e);if(!r.results_url)throw new p(`No batch \`results_url\`; Has it finished processing? ${r.processing_status} - ${r.id}`);const{betas:i}=n??{};return this._client.get(r.results_url,{...s,headers:g([{"anthropic-beta":[...i??[],"message-batches-2024-09-24"].toString(),Accept:"application/binary"},s?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((a,c)=>Je.fromResponse(c.response,c.controller))}};const Ws=t=>{let e=0,n=[];for(;e<t.length;){let s=t[e];if(s==="\\"){e++;continue}if(s==="{"){n.push({type:"brace",value:"{"}),e++;continue}if(s==="}"){n.push({type:"brace",value:"}"}),e++;continue}if(s==="["){n.push({type:"paren",value:"["}),e++;continue}if(s==="]"){n.push({type:"paren",value:"]"}),e++;continue}if(s===":"){n.push({type:"separator",value:":"}),e++;continue}if(s===","){n.push({type:"delimiter",value:","}),e++;continue}if(s==='"'){let c="",l=!1;for(s=t[++e];s!=='"';){if(e===t.length){l=!0;break}if(s==="\\"){if(e++,e===t.length){l=!0;break}c+=s+t[e],s=t[++e]}else c+=s,s=t[++e]}s=t[++e],l||n.push({type:"string",value:c});continue}if(s&&/\s/.test(s)){e++;continue}let i=/[0-9]/;if(s&&i.test(s)||s==="-"||s==="."){let c="";for(s==="-"&&(c+=s,s=t[++e]);s&&i.test(s)||s===".";)c+=s,s=t[++e];n.push({type:"number",value:c});continue}let a=/[a-z]/i;if(s&&a.test(s)){let c="";for(;s&&a.test(s)&&e!==t.length;)c+=s,s=t[++e];if(c=="true"||c=="false"||c==="null")n.push({type:"name",value:c});else{e++;continue}continue}e++}return n},V=t=>{if(t.length===0)return t;let e=t[t.length-1];switch(e.type){case"separator":return t=t.slice(0,t.length-1),V(t);case"number":let n=e.value[e.value.length-1];if(n==="."||n==="-")return t=t.slice(0,t.length-1),V(t);case"string":let s=t[t.length-2];if(s?.type==="delimiter")return t=t.slice(0,t.length-1),V(t);if(s?.type==="brace"&&s.value==="{")return t=t.slice(0,t.length-1),V(t);break;case"delimiter":return t=t.slice(0,t.length-1),V(t)}return t},Fs=t=>{let e=[];return t.map(n=>{n.type==="brace"&&(n.value==="{"?e.push("}"):e.splice(e.lastIndexOf("}"),1)),n.type==="paren"&&(n.value==="["?e.push("]"):e.splice(e.lastIndexOf("]"),1))}),e.length>0&&e.reverse().map(n=>{n==="}"?t.push({type:"brace",value:"}"}):n==="]"&&t.push({type:"paren",value:"]"})}),t},Ds=t=>{let e="";return t.map(n=>{switch(n.type){case"string":e+='"'+n.value+'"';break;default:e+=n.value;break}}),e},vn=t=>JSON.parse(Ds(Fs(V(Ws(t)))));var T,L,Z,Me,ee,te,Te,ne,N,se,Re,Ae,K,ve,Ee,Ge,Ht,Pe,Ye,Ze,et,Kt;const Jt="__json_buf";function Xt(t){return t.type==="tool_use"||t.type==="server_tool_use"||t.type==="mcp_tool_use"}class Fe{constructor(){T.add(this),this.messages=[],this.receivedMessages=[],L.set(this,void 0),this.controller=new AbortController,Z.set(this,void 0),Me.set(this,()=>{}),ee.set(this,()=>{}),te.set(this,void 0),Te.set(this,()=>{}),ne.set(this,()=>{}),N.set(this,{}),se.set(this,!1),Re.set(this,!1),Ae.set(this,!1),K.set(this,!1),ve.set(this,void 0),Ee.set(this,void 0),Pe.set(this,e=>{if(u(this,Re,!0),fe(e)&&(e=new v),e instanceof v)return u(this,Ae,!0),this._emit("abort",e);if(e instanceof p)return this._emit("error",e);if(e instanceof Error){const n=new p(e.message);return n.cause=e,this._emit("error",n)}return this._emit("error",new p(String(e)))}),u(this,Z,new Promise((e,n)=>{u(this,Me,e,"f"),u(this,ee,n,"f")})),u(this,te,new Promise((e,n)=>{u(this,Te,e,"f"),u(this,ne,n,"f")})),o(this,Z,"f").catch(()=>{}),o(this,te,"f").catch(()=>{})}get response(){return o(this,ve,"f")}get request_id(){return o(this,Ee,"f")}async withResponse(){const e=await o(this,Z,"f");if(!e)throw new Error("Could not resolve a `Response` object");return{data:this,response:e,request_id:e.headers.get("request-id")}}static fromReadableStream(e){const n=new Fe;return n._run(()=>n._fromReadableStream(e)),n}static createMessage(e,n,s){const r=new Fe;for(const i of n.messages)r._addMessageParam(i);return r._run(()=>r._createMessage(e,{...n,stream:!0},{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),r}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},o(this,Pe,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,n=!0){this.receivedMessages.push(e),n&&this._emit("message",e)}async _createMessage(e,n,s){const r=s?.signal;let i;r&&(r.aborted&&this.controller.abort(),i=this.controller.abort.bind(this.controller),r.addEventListener("abort",i));try{o(this,T,"m",Ye).call(this);const{response:a,data:c}=await e.create({...n,stream:!0},{...s,signal:this.controller.signal}).withResponse();this._connected(a);for await(const l of c)o(this,T,"m",Ze).call(this,l);if(c.controller.signal?.aborted)throw new v;o(this,T,"m",et).call(this)}finally{r&&i&&r.removeEventListener("abort",i)}}_connected(e){this.ended||(u(this,ve,e),u(this,Ee,e?.headers.get("request-id")),o(this,Me,"f").call(this,e),this._emit("connect"))}get ended(){return o(this,se,"f")}get errored(){return o(this,Re,"f")}get aborted(){return o(this,Ae,"f")}abort(){this.controller.abort()}on(e,n){return(o(this,N,"f")[e]||(o(this,N,"f")[e]=[])).push({listener:n}),this}off(e,n){const s=o(this,N,"f")[e];if(!s)return this;const r=s.findIndex(i=>i.listener===n);return r>=0&&s.splice(r,1),this}once(e,n){return(o(this,N,"f")[e]||(o(this,N,"f")[e]=[])).push({listener:n,once:!0}),this}emitted(e){return new Promise((n,s)=>{u(this,K,!0),e!=="error"&&this.once("error",s),this.once(e,n)})}async done(){u(this,K,!0),await o(this,te,"f")}get currentMessage(){return o(this,L,"f")}async finalMessage(){return await this.done(),o(this,T,"m",Ge).call(this)}async finalText(){return await this.done(),o(this,T,"m",Ht).call(this)}_emit(e,...n){if(o(this,se,"f"))return;e==="end"&&(u(this,se,!0),o(this,Te,"f").call(this));const s=o(this,N,"f")[e];if(s&&(o(this,N,"f")[e]=s.filter(r=>!r.once),s.forEach(({listener:r})=>r(...n))),e==="abort"){const r=n[0];!o(this,K,"f")&&!s?.length&&Promise.reject(r),o(this,ee,"f").call(this,r),o(this,ne,"f").call(this,r),this._emit("end");return}if(e==="error"){const r=n[0];!o(this,K,"f")&&!s?.length&&Promise.reject(r),o(this,ee,"f").call(this,r),o(this,ne,"f").call(this,r),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",o(this,T,"m",Ge).call(this))}async _fromReadableStream(e,n){const s=n?.signal;let r;s&&(s.aborted&&this.controller.abort(),r=this.controller.abort.bind(this.controller),s.addEventListener("abort",r));try{o(this,T,"m",Ye).call(this),this._connected(null);const i=C.fromReadableStream(e,this.controller);for await(const a of i)o(this,T,"m",Ze).call(this,a);if(i.controller.signal?.aborted)throw new v;o(this,T,"m",et).call(this)}finally{s&&r&&s.removeEventListener("abort",r)}}[(L=new WeakMap,Z=new WeakMap,Me=new WeakMap,ee=new WeakMap,te=new WeakMap,Te=new WeakMap,ne=new WeakMap,N=new WeakMap,se=new WeakMap,Re=new WeakMap,Ae=new WeakMap,K=new WeakMap,ve=new WeakMap,Ee=new WeakMap,Pe=new WeakMap,T=new WeakSet,Ge=function(){if(this.receivedMessages.length===0)throw new p("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},Ht=function(){if(this.receivedMessages.length===0)throw new p("stream ended without producing a Message with role=assistant");const n=this.receivedMessages.at(-1).content.filter(s=>s.type==="text").map(s=>s.text);if(n.length===0)throw new p("stream ended without producing a content block with type=text");return n.join(" ")},Ye=function(){this.ended||u(this,L,void 0)},Ze=function(n){if(this.ended)return;const s=o(this,T,"m",Kt).call(this,n);switch(this._emit("streamEvent",n,s),n.type){case"content_block_delta":{const r=s.content.at(-1);switch(n.delta.type){case"text_delta":{r.type==="text"&&this._emit("text",n.delta.text,r.text||"");break}case"citations_delta":{r.type==="text"&&this._emit("citation",n.delta.citation,r.citations??[]);break}case"input_json_delta":{Xt(r)&&r.input&&this._emit("inputJson",n.delta.partial_json,r.input);break}case"thinking_delta":{r.type==="thinking"&&this._emit("thinking",n.delta.thinking,r.thinking);break}case"signature_delta":{r.type==="thinking"&&this._emit("signature",r.signature);break}default:n.delta}break}case"message_stop":{this._addMessageParam(s),this._addMessage(s,!0);break}case"content_block_stop":{this._emit("contentBlock",s.content.at(-1));break}case"message_start":{u(this,L,s);break}}},et=function(){if(this.ended)throw new p("stream has ended, this shouldn't happen");const n=o(this,L,"f");if(!n)throw new p("request ended without sending any chunks");return u(this,L,void 0),n},Kt=function(n){let s=o(this,L,"f");if(n.type==="message_start"){if(s)throw new p(`Unexpected event order, got ${n.type} before receiving "message_stop"`);return n.message}if(!s)throw new p(`Unexpected event order, got ${n.type} before "message_start"`);switch(n.type){case"message_stop":return s;case"message_delta":return s.container=n.delta.container,s.stop_reason=n.delta.stop_reason,s.stop_sequence=n.delta.stop_sequence,s.usage.output_tokens=n.usage.output_tokens,s.context_management=n.context_management,n.usage.input_tokens!=null&&(s.usage.input_tokens=n.usage.input_tokens),n.usage.cache_creation_input_tokens!=null&&(s.usage.cache_creation_input_tokens=n.usage.cache_creation_input_tokens),n.usage.cache_read_input_tokens!=null&&(s.usage.cache_read_input_tokens=n.usage.cache_read_input_tokens),n.usage.server_tool_use!=null&&(s.usage.server_tool_use=n.usage.server_tool_use),s;case"content_block_start":return s.content.push(n.content_block),s;case"content_block_delta":{const r=s.content.at(n.index);switch(n.delta.type){case"text_delta":{r?.type==="text"&&(s.content[n.index]={...r,text:(r.text||"")+n.delta.text});break}case"citations_delta":{r?.type==="text"&&(s.content[n.index]={...r,citations:[...r.citations??[],n.delta.citation]});break}case"input_json_delta":{if(r&&Xt(r)){let i=r[Jt]||"";i+=n.delta.partial_json;const a={...r};if(Object.defineProperty(a,Jt,{value:i,enumerable:!1,writable:!0}),i)try{a.input=vn(i)}catch(c){const l=new p(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${c}. JSON: ${i}`);o(this,Pe,"f").call(this,l)}s.content[n.index]=a}break}case"thinking_delta":{r?.type==="thinking"&&(s.content[n.index]={...r,thinking:r.thinking+n.delta.thinking});break}case"signature_delta":{r?.type==="thinking"&&(s.content[n.index]={...r,signature:n.delta.signature});break}default:n.delta}return s}case"content_block_stop":return s}},Symbol.asyncIterator)](){const e=[],n=[];let s=!1;return this.on("streamEvent",r=>{const i=n.shift();i?i.resolve(r):e.push(r)}),this.on("end",()=>{s=!0;for(const r of n)r.resolve(void 0);n.length=0}),this.on("abort",r=>{s=!0;for(const i of n)i.reject(r);n.length=0}),this.on("error",r=>{s=!0;for(const i of n)i.reject(r);n.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:s?{value:void 0,done:!0}:new Promise((i,a)=>n.push({resolve:i,reject:a})).then(i=>i?{value:i,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new C(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}const En={"claude-opus-4-20250514":8192,"claude-opus-4-0":8192,"claude-4-opus-20250514":8192,"anthropic.claude-opus-4-20250514-v1:0":8192,"claude-opus-4@20250514":8192,"claude-opus-4-1-20250805":8192,"anthropic.claude-opus-4-1-20250805-v1:0":8192,"claude-opus-4-1@20250805":8192};var Oe,J,F,S,re,O,j,U,ie,ht;function zt(){let t,e;return{promise:new Promise((s,r)=>{t=s,e=r}),resolve:t,reject:e}}class Pn{constructor(e,n,s){Oe.add(this),this.client=e,J.set(this,!1),F.set(this,!1),S.set(this,void 0),re.set(this,void 0),O.set(this,void 0),j.set(this,void 0),U.set(this,void 0),ie.set(this,0),u(this,S,{params:{...n,messages:structuredClone(n.messages)}}),u(this,re,{...s,headers:g([{"x-stainless-helper":"BetaToolRunner"},s?.headers])}),u(this,U,zt())}async*[(J=new WeakMap,F=new WeakMap,S=new WeakMap,re=new WeakMap,O=new WeakMap,j=new WeakMap,U=new WeakMap,ie=new WeakMap,Oe=new WeakSet,Symbol.asyncIterator)](){var e;if(o(this,J,"f"))throw new p("Cannot iterate over a consumed stream");u(this,J,!0),u(this,F,!0),u(this,j,void 0);try{for(;;){let n;try{if(o(this,S,"f").params.max_iterations&&o(this,ie,"f")>=o(this,S,"f").params.max_iterations)break;u(this,F,!1,"f"),u(this,O,void 0,"f"),u(this,j,void 0,"f"),u(this,ie,(e=o(this,ie,"f"),e++,e),"f");const{max_iterations:s,...r}=o(this,S,"f").params;if(r.stream?(n=this.client.beta.messages.stream({...r},o(this,re,"f")),u(this,O,n.finalMessage(),"f"),yield n):(u(this,O,this.client.beta.messages.create({...r,stream:!1},o(this,re,"f")),"f"),yield o(this,O,"f")),!o(this,F,"f")){const{role:a,content:c}=await o(this,O,"f");o(this,S,"f").params.messages.push({role:a,content:c})}const i=await o(this,Oe,"m",ht).call(this,o(this,S,"f").params.messages.at(-1));if(i&&o(this,S,"f").params.messages.push(i),!i&&!o(this,F,"f"))break}finally{n&&n.abort()}}if(!o(this,O,"f"))throw new p("ToolRunner concluded without a message from the server");o(this,U,"f").resolve(await o(this,O,"f"))}catch(n){throw u(this,J,!1),o(this,U,"f").promise.catch(()=>{}),o(this,U,"f").reject(n),u(this,U,zt()),n}}setMessagesParams(e){typeof e=="function"?o(this,S,"f").params=e(o(this,S,"f").params):o(this,S,"f").params=e,u(this,F,!0),u(this,j,void 0)}async generateToolResponse(){const e=await o(this,O,"f")??this.params.messages.at(-1);return e?o(this,Oe,"m",ht).call(this,e):null}done(){return o(this,U,"f").promise}async runUntilDone(){if(!o(this,J,"f"))for await(const e of this);return this.done()}get params(){return o(this,S,"f").params}pushMessages(...e){this.setMessagesParams(n=>({...n,messages:[...n.messages,...e]}))}then(e,n){return this.runUntilDone().then(e,n)}}ht=async function(e){return o(this,j,"f")!==void 0?o(this,j,"f"):(u(this,j,Hs(o(this,S,"f").params,e)),o(this,j,"f"))};async function Hs(t,e=t.messages.at(-1)){if(!e||e.role!=="assistant"||!e.content||typeof e.content=="string")return null;const n=e.content.filter(r=>r.type==="tool_use");return n.length===0?null:{role:"user",content:await Promise.all(n.map(async r=>{const i=t.tools.find(a=>a.name===r.name);if(!i||!("run"in i))return{type:"tool_result",tool_use_id:r.id,content:`Error: Tool '${r.name}' not found`,is_error:!0};try{let a=r.input;"parse"in i&&i.parse&&(a=i.parse(a));const c=await i.run(a);return{type:"tool_result",tool_use_id:r.id,content:c}}catch(a){return{type:"tool_result",tool_use_id:r.id,content:`Error: ${a instanceof Error?a.message:String(a)}`,is_error:!0}}}))}}const Vt={"claude-1.3":"November 6th, 2024","claude-1.3-100k":"November 6th, 2024","claude-instant-1.1":"November 6th, 2024","claude-instant-1.1-100k":"November 6th, 2024","claude-instant-1.2":"November 6th, 2024","claude-3-sonnet-20240229":"July 21st, 2025","claude-3-opus-20240229":"January 5th, 2026","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025","claude-3-5-sonnet-20241022":"October 22, 2025","claude-3-5-sonnet-20240620":"October 22, 2025"};let Xe=class extends B{constructor(){super(...arguments),this.batches=new An(this._client)}create(e,n){const{betas:s,...r}=e;r.model in Vt&&console.warn(`The model '${r.model}' is deprecated and will reach end-of-life on ${Vt[r.model]}
17
- Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);let i=this._client._options.timeout;if(!r.stream&&i==null){const a=En[r.model]??void 0;i=this._client.calculateNonstreamingTimeout(r.max_tokens,a)}return this._client.post("/v1/messages?beta=true",{body:r,timeout:i??6e5,...n,headers:g([{...s?.toString()!=null?{"anthropic-beta":s?.toString()}:void 0},n?.headers]),stream:e.stream??!1})}stream(e,n){return Fe.createMessage(this,e,n)}countTokens(e,n){const{betas:s,...r}=e;return this._client.post("/v1/messages/count_tokens?beta=true",{body:r,...n,headers:g([{"anthropic-beta":[...s??[],"token-counting-2024-11-01"].toString()},n?.headers])})}toolRunner(e,n){return new Pn(this._client,e,n)}};Xe.Batches=An;Xe.BetaToolRunner=Pn;class _e extends B{constructor(){super(...arguments),this.models=new Rn(this._client),this.messages=new Xe(this._client),this.files=new Tn(this._client)}}_e.Models=Rn;_e.Messages=Xe;_e.Files=Tn;class On extends B{create(e,n){const{betas:s,...r}=e;return this._client.post("/v1/complete",{body:r,timeout:this._client._options.timeout??6e5,...n,headers:g([{...s?.toString()!=null?{"anthropic-beta":s?.toString()}:void 0},n?.headers]),stream:e.stream??!1})}}var R,q,ae,Ce,oe,ce,Ie,le,$,ue,Ne,$e,X,je,Be,tt,Qt,nt,st,rt,it,Gt;const Yt="__json_buf";function Zt(t){return t.type==="tool_use"||t.type==="server_tool_use"}class De{constructor(){R.add(this),this.messages=[],this.receivedMessages=[],q.set(this,void 0),this.controller=new AbortController,ae.set(this,void 0),Ce.set(this,()=>{}),oe.set(this,()=>{}),ce.set(this,void 0),Ie.set(this,()=>{}),le.set(this,()=>{}),$.set(this,{}),ue.set(this,!1),Ne.set(this,!1),$e.set(this,!1),X.set(this,!1),je.set(this,void 0),Be.set(this,void 0),nt.set(this,e=>{if(u(this,Ne,!0),fe(e)&&(e=new v),e instanceof v)return u(this,$e,!0),this._emit("abort",e);if(e instanceof p)return this._emit("error",e);if(e instanceof Error){const n=new p(e.message);return n.cause=e,this._emit("error",n)}return this._emit("error",new p(String(e)))}),u(this,ae,new Promise((e,n)=>{u(this,Ce,e,"f"),u(this,oe,n,"f")})),u(this,ce,new Promise((e,n)=>{u(this,Ie,e,"f"),u(this,le,n,"f")})),o(this,ae,"f").catch(()=>{}),o(this,ce,"f").catch(()=>{})}get response(){return o(this,je,"f")}get request_id(){return o(this,Be,"f")}async withResponse(){const e=await o(this,ae,"f");if(!e)throw new Error("Could not resolve a `Response` object");return{data:this,response:e,request_id:e.headers.get("request-id")}}static fromReadableStream(e){const n=new De;return n._run(()=>n._fromReadableStream(e)),n}static createMessage(e,n,s){const r=new De;for(const i of n.messages)r._addMessageParam(i);return r._run(()=>r._createMessage(e,{...n,stream:!0},{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),r}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},o(this,nt,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,n=!0){this.receivedMessages.push(e),n&&this._emit("message",e)}async _createMessage(e,n,s){const r=s?.signal;let i;r&&(r.aborted&&this.controller.abort(),i=this.controller.abort.bind(this.controller),r.addEventListener("abort",i));try{o(this,R,"m",st).call(this);const{response:a,data:c}=await e.create({...n,stream:!0},{...s,signal:this.controller.signal}).withResponse();this._connected(a);for await(const l of c)o(this,R,"m",rt).call(this,l);if(c.controller.signal?.aborted)throw new v;o(this,R,"m",it).call(this)}finally{r&&i&&r.removeEventListener("abort",i)}}_connected(e){this.ended||(u(this,je,e),u(this,Be,e?.headers.get("request-id")),o(this,Ce,"f").call(this,e),this._emit("connect"))}get ended(){return o(this,ue,"f")}get errored(){return o(this,Ne,"f")}get aborted(){return o(this,$e,"f")}abort(){this.controller.abort()}on(e,n){return(o(this,$,"f")[e]||(o(this,$,"f")[e]=[])).push({listener:n}),this}off(e,n){const s=o(this,$,"f")[e];if(!s)return this;const r=s.findIndex(i=>i.listener===n);return r>=0&&s.splice(r,1),this}once(e,n){return(o(this,$,"f")[e]||(o(this,$,"f")[e]=[])).push({listener:n,once:!0}),this}emitted(e){return new Promise((n,s)=>{u(this,X,!0),e!=="error"&&this.once("error",s),this.once(e,n)})}async done(){u(this,X,!0),await o(this,ce,"f")}get currentMessage(){return o(this,q,"f")}async finalMessage(){return await this.done(),o(this,R,"m",tt).call(this)}async finalText(){return await this.done(),o(this,R,"m",Qt).call(this)}_emit(e,...n){if(o(this,ue,"f"))return;e==="end"&&(u(this,ue,!0),o(this,Ie,"f").call(this));const s=o(this,$,"f")[e];if(s&&(o(this,$,"f")[e]=s.filter(r=>!r.once),s.forEach(({listener:r})=>r(...n))),e==="abort"){const r=n[0];!o(this,X,"f")&&!s?.length&&Promise.reject(r),o(this,oe,"f").call(this,r),o(this,le,"f").call(this,r),this._emit("end");return}if(e==="error"){const r=n[0];!o(this,X,"f")&&!s?.length&&Promise.reject(r),o(this,oe,"f").call(this,r),o(this,le,"f").call(this,r),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",o(this,R,"m",tt).call(this))}async _fromReadableStream(e,n){const s=n?.signal;let r;s&&(s.aborted&&this.controller.abort(),r=this.controller.abort.bind(this.controller),s.addEventListener("abort",r));try{o(this,R,"m",st).call(this),this._connected(null);const i=C.fromReadableStream(e,this.controller);for await(const a of i)o(this,R,"m",rt).call(this,a);if(i.controller.signal?.aborted)throw new v;o(this,R,"m",it).call(this)}finally{s&&r&&s.removeEventListener("abort",r)}}[(q=new WeakMap,ae=new WeakMap,Ce=new WeakMap,oe=new WeakMap,ce=new WeakMap,Ie=new WeakMap,le=new WeakMap,$=new WeakMap,ue=new WeakMap,Ne=new WeakMap,$e=new WeakMap,X=new WeakMap,je=new WeakMap,Be=new WeakMap,nt=new WeakMap,R=new WeakSet,tt=function(){if(this.receivedMessages.length===0)throw new p("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},Qt=function(){if(this.receivedMessages.length===0)throw new p("stream ended without producing a Message with role=assistant");const n=this.receivedMessages.at(-1).content.filter(s=>s.type==="text").map(s=>s.text);if(n.length===0)throw new p("stream ended without producing a content block with type=text");return n.join(" ")},st=function(){this.ended||u(this,q,void 0)},rt=function(n){if(this.ended)return;const s=o(this,R,"m",Gt).call(this,n);switch(this._emit("streamEvent",n,s),n.type){case"content_block_delta":{const r=s.content.at(-1);switch(n.delta.type){case"text_delta":{r.type==="text"&&this._emit("text",n.delta.text,r.text||"");break}case"citations_delta":{r.type==="text"&&this._emit("citation",n.delta.citation,r.citations??[]);break}case"input_json_delta":{Zt(r)&&r.input&&this._emit("inputJson",n.delta.partial_json,r.input);break}case"thinking_delta":{r.type==="thinking"&&this._emit("thinking",n.delta.thinking,r.thinking);break}case"signature_delta":{r.type==="thinking"&&this._emit("signature",r.signature);break}default:n.delta}break}case"message_stop":{this._addMessageParam(s),this._addMessage(s,!0);break}case"content_block_stop":{this._emit("contentBlock",s.content.at(-1));break}case"message_start":{u(this,q,s);break}}},it=function(){if(this.ended)throw new p("stream has ended, this shouldn't happen");const n=o(this,q,"f");if(!n)throw new p("request ended without sending any chunks");return u(this,q,void 0),n},Gt=function(n){let s=o(this,q,"f");if(n.type==="message_start"){if(s)throw new p(`Unexpected event order, got ${n.type} before receiving "message_stop"`);return n.message}if(!s)throw new p(`Unexpected event order, got ${n.type} before "message_start"`);switch(n.type){case"message_stop":return s;case"message_delta":return s.stop_reason=n.delta.stop_reason,s.stop_sequence=n.delta.stop_sequence,s.usage.output_tokens=n.usage.output_tokens,n.usage.input_tokens!=null&&(s.usage.input_tokens=n.usage.input_tokens),n.usage.cache_creation_input_tokens!=null&&(s.usage.cache_creation_input_tokens=n.usage.cache_creation_input_tokens),n.usage.cache_read_input_tokens!=null&&(s.usage.cache_read_input_tokens=n.usage.cache_read_input_tokens),n.usage.server_tool_use!=null&&(s.usage.server_tool_use=n.usage.server_tool_use),s;case"content_block_start":return s.content.push({...n.content_block}),s;case"content_block_delta":{const r=s.content.at(n.index);switch(n.delta.type){case"text_delta":{r?.type==="text"&&(s.content[n.index]={...r,text:(r.text||"")+n.delta.text});break}case"citations_delta":{r?.type==="text"&&(s.content[n.index]={...r,citations:[...r.citations??[],n.delta.citation]});break}case"input_json_delta":{if(r&&Zt(r)){let i=r[Yt]||"";i+=n.delta.partial_json;const a={...r};Object.defineProperty(a,Yt,{value:i,enumerable:!1,writable:!0}),i&&(a.input=vn(i)),s.content[n.index]=a}break}case"thinking_delta":{r?.type==="thinking"&&(s.content[n.index]={...r,thinking:r.thinking+n.delta.thinking});break}case"signature_delta":{r?.type==="thinking"&&(s.content[n.index]={...r,signature:n.delta.signature});break}default:n.delta}return s}case"content_block_stop":return s}},Symbol.asyncIterator)](){const e=[],n=[];let s=!1;return this.on("streamEvent",r=>{const i=n.shift();i?i.resolve(r):e.push(r)}),this.on("end",()=>{s=!0;for(const r of n)r.resolve(void 0);n.length=0}),this.on("abort",r=>{s=!0;for(const i of n)i.reject(r);n.length=0}),this.on("error",r=>{s=!0;for(const i of n)i.reject(r);n.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:s?{value:void 0,done:!0}:new Promise((i,a)=>n.push({resolve:i,reject:a})).then(i=>i?{value:i,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new C(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}class Cn extends B{create(e,n){return this._client.post("/v1/messages/batches",{body:e,...n})}retrieve(e,n){return this._client.get(E`/v1/messages/batches/${e}`,n)}list(e={},n){return this._client.getAPIList("/v1/messages/batches",ge,{query:e,...n})}delete(e,n){return this._client.delete(E`/v1/messages/batches/${e}`,n)}cancel(e,n){return this._client.post(E`/v1/messages/batches/${e}/cancel`,n)}async results(e,n){const s=await this.retrieve(e);if(!s.results_url)throw new p(`No batch \`results_url\`; Has it finished processing? ${s.processing_status} - ${s.id}`);return this._client.get(s.results_url,{...n,headers:g([{Accept:"application/binary"},n?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((r,i)=>Je.fromResponse(i.response,i.controller))}}class mt extends B{constructor(){super(...arguments),this.batches=new Cn(this._client)}create(e,n){e.model in en&&console.warn(`The model '${e.model}' is deprecated and will reach end-of-life on ${en[e.model]}
18
- Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);let s=this._client._options.timeout;if(!e.stream&&s==null){const r=En[e.model]??void 0;s=this._client.calculateNonstreamingTimeout(e.max_tokens,r)}return this._client.post("/v1/messages",{body:e,timeout:s??6e5,...n,stream:e.stream??!1})}stream(e,n){return De.createMessage(this,e,n)}countTokens(e,n){return this._client.post("/v1/messages/count_tokens",{body:e,...n})}}const en={"claude-1.3":"November 6th, 2024","claude-1.3-100k":"November 6th, 2024","claude-instant-1.1":"November 6th, 2024","claude-instant-1.1-100k":"November 6th, 2024","claude-instant-1.2":"November 6th, 2024","claude-3-sonnet-20240229":"July 21st, 2025","claude-3-opus-20240229":"January 5th, 2026","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025","claude-3-5-sonnet-20241022":"October 22, 2025","claude-3-5-sonnet-20240620":"October 22, 2025"};mt.Batches=Cn;class In extends B{retrieve(e,n={},s){const{betas:r}=n??{};return this._client.get(E`/v1/models/${e}`,{...s,headers:g([{...r?.toString()!=null?{"anthropic-beta":r?.toString()}:void 0},s?.headers])})}list(e={},n){const{betas:s,...r}=e??{};return this._client.getAPIList("/v1/models",ge,{query:r,...n,headers:g([{...s?.toString()!=null?{"anthropic-beta":s?.toString()}:void 0},n?.headers])})}}var Ks={};const Le=t=>{if(typeof globalThis.process<"u")return Ks?.[t]?.trim()??void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(t)?.trim()};var dt,gt,qe,Nn;const Js="\\n\\nHuman:",Xs="\\n\\nAssistant:";class y{constructor({baseURL:e=Le("ANTHROPIC_BASE_URL"),apiKey:n=Le("ANTHROPIC_API_KEY")??null,authToken:s=Le("ANTHROPIC_AUTH_TOKEN")??null,...r}={}){dt.add(this),qe.set(this,void 0);const i={apiKey:n,authToken:s,...r,baseURL:e||"https://api.anthropic.com"};if(!i.dangerouslyAllowBrowser&&ps())throw new p(`It looks like you're running in a browser-like environment.
19
-
20
- This is disabled by default, as it risks exposing your secret API credentials to attackers.
21
- If you understand the risks and have appropriate mitigations in place,
22
- you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
23
-
24
- new Anthropic({ apiKey, dangerouslyAllowBrowser: true });
25
- `);this.baseURL=i.baseURL,this.timeout=i.timeout??gt.DEFAULT_TIMEOUT,this.logger=i.logger??console;const a="warn";this.logLevel=a,this.logLevel=qt(i.logLevel,"ClientOptions.logLevel",this)??qt(Le("ANTHROPIC_LOG"),"process.env['ANTHROPIC_LOG']",this)??a,this.fetchOptions=i.fetchOptions,this.maxRetries=i.maxRetries??2,this.fetch=i.fetch??ys(),u(this,qe,bs),this._options=i,this.apiKey=n,this.authToken=s}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,authToken:this.authToken,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:n}){if(!(this.apiKey&&e.get("x-api-key"))&&!n.has("x-api-key")&&!(this.authToken&&e.get("authorization"))&&!n.has("authorization"))throw new Error('Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted')}async authHeaders(e){return g([await this.apiKeyAuth(e),await this.bearerAuth(e)])}async apiKeyAuth(e){if(this.apiKey!=null)return g([{"X-Api-Key":this.apiKey}])}async bearerAuth(e){if(this.authToken!=null)return g([{Authorization:`Bearer ${this.authToken}`}])}stringifyQuery(e){return Object.entries(e).filter(([n,s])=>typeof s<"u").map(([n,s])=>{if(typeof s=="string"||typeof s=="number"||typeof s=="boolean")return`${encodeURIComponent(n)}=${encodeURIComponent(s)}`;if(s===null)return`${encodeURIComponent(n)}=`;throw new p(`Cannot stringify type ${typeof s}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}getUserAgent(){return`${this.constructor.name}/JS ${z}`}defaultIdempotencyKey(){return`stainless-node-retry-${rn()}`}makeStatusError(e,n,s,r){return w.generate(e,n,s,r)}buildURL(e,n,s){const r=!o(this,dt,"m",Nn).call(this)&&s||this.baseURL,i=cs(e)?new URL(e):new URL(r+(r.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),a=this.defaultQuery();return ls(a)||(n={...a,...n}),typeof n=="object"&&n&&!Array.isArray(n)&&(i.search=this.stringifyQuery(n)),i.toString()}_calculateNonstreamingTimeout(e){if(3600*e/128e3>600)throw new p("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details");return 600*1e3}async prepareOptions(e){}async prepareRequest(e,{url:n,options:s}){}get(e,n){return this.methodRequest("get",e,n)}post(e,n){return this.methodRequest("post",e,n)}patch(e,n){return this.methodRequest("patch",e,n)}put(e,n){return this.methodRequest("put",e,n)}delete(e,n){return this.methodRequest("delete",e,n)}methodRequest(e,n,s){return this.request(Promise.resolve(s).then(r=>({method:e,path:n,...r})))}request(e,n=null){return new Ke(this,this.makeRequest(e,n,void 0))}async makeRequest(e,n,s){const r=await e,i=r.maxRetries??this.maxRetries;n==null&&(n=i),await this.prepareOptions(r);const{req:a,url:c,timeout:l}=await this.buildRequest(r,{retryCount:i-n});await this.prepareRequest(a,{url:c,options:r});const d="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),f=s===void 0?"":`, retryOf: ${s}`,m=Date.now();if(x(this).debug(`[${d}] sending request`,D({retryOfRequestLogID:s,method:r.method,url:c,options:r,headers:a.headers})),r.signal?.aborted)throw new v;const _=new AbortController,h=await this.fetchWithTimeout(c,a,l,_).catch(ot),b=Date.now();if(h instanceof globalThis.Error){const I=`retrying, ${n} attempts remaining`;if(r.signal?.aborted)throw new v;const P=fe(h)||/timed? ?out/i.test(String(h)+("cause"in h?String(h.cause):""));if(n)return x(this).info(`[${d}] connection ${P?"timed out":"failed"} - ${I}`),x(this).debug(`[${d}] connection ${P?"timed out":"failed"} (${I})`,D({retryOfRequestLogID:s,url:c,durationMs:b-m,message:h.message})),this.retryRequest(r,n,s??d);throw x(this).info(`[${d}] connection ${P?"timed out":"failed"} - error; no more retries left`),x(this).debug(`[${d}] connection ${P?"timed out":"failed"} (error; no more retries left)`,D({retryOfRequestLogID:s,url:c,durationMs:b-m,message:h.message})),P?new an:new He({cause:h})}const W=[...h.headers.entries()].filter(([I])=>I==="request-id").map(([I,P])=>", "+I+": "+JSON.stringify(P)).join(""),ze=`[${d}${f}${W}] ${a.method} ${c} ${h.ok?"succeeded":"failed"} with status ${h.status} in ${b-m}ms`;if(!h.ok){const I=await this.shouldRetry(h);if(n&&I){const we=`retrying, ${n} attempts remaining`;return await ws(h.body),x(this).info(`${ze} - ${we}`),x(this).debug(`[${d}] response error (${we})`,D({retryOfRequestLogID:s,url:h.url,status:h.status,headers:h.headers,durationMs:b-m})),this.retryRequest(r,n,s??d,h.headers)}const P=I?"error; no more retries left":"error; not retryable";x(this).info(`${ze} - ${P}`);const _t=await h.text().catch(we=>ot(we).message),yt=mn(_t),wt=yt?void 0:_t;throw x(this).debug(`[${d}] response error (${P})`,D({retryOfRequestLogID:s,url:h.url,status:h.status,headers:h.headers,message:wt,durationMs:Date.now()-m})),this.makeStatusError(h.status,yt,wt,h.headers)}return x(this).info(ze),x(this).debug(`[${d}] response start`,D({retryOfRequestLogID:s,url:h.url,status:h.status,headers:h.headers,durationMs:b-m})),{response:h,options:r,controller:_,requestLogID:d,retryOfRequestLogID:s,startTime:m}}getAPIList(e,n,s){return this.requestAPIList(n,{method:"get",path:e,...s})}requestAPIList(e,n){const s=this.makeRequest(n,null,void 0);return new Ps(this,s,e)}async fetchWithTimeout(e,n,s,r){const{signal:i,method:a,...c}=n||{};i&&i.addEventListener("abort",()=>r.abort());const l=setTimeout(()=>r.abort(),s),d=globalThis.ReadableStream&&c.body instanceof globalThis.ReadableStream||typeof c.body=="object"&&c.body!==null&&Symbol.asyncIterator in c.body,f={signal:r.signal,...d?{duplex:"half"}:{},method:"GET",...c};a&&(f.method=a.toUpperCase());try{return await this.fetch.call(void 0,e,f)}finally{clearTimeout(l)}}async shouldRetry(e){const n=e.headers.get("x-should-retry");return n==="true"?!0:n==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,n,s,r){let i;const a=r?.get("retry-after-ms");if(a){const l=parseFloat(a);Number.isNaN(l)||(i=l)}const c=r?.get("retry-after");if(c&&!i){const l=parseFloat(c);Number.isNaN(l)?i=Date.parse(c)-Date.now():i=l*1e3}if(!(i&&0<=i&&i<60*1e3)){const l=e.maxRetries??this.maxRetries;i=this.calculateDefaultRetryTimeoutMillis(n,l)}return await ds(i),this.makeRequest(e,n-1,s)}calculateDefaultRetryTimeoutMillis(e,n){const i=n-e,a=Math.min(.5*Math.pow(2,i),8),c=1-Math.random()*.25;return a*c*1e3}calculateNonstreamingTimeout(e,n){if(36e5*e/128e3>6e5||n!=null&&e>n)throw new p("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#long-requests for more details");return 6e5}async buildRequest(e,{retryCount:n=0}={}){const s={...e},{method:r,path:i,query:a,defaultBaseURL:c}=s,l=this.buildURL(i,a,c);"timeout"in s&&hs("timeout",s.timeout),s.timeout=s.timeout??this.timeout;const{bodyHeaders:d,body:f}=this.buildBody({options:s}),m=await this.buildHeaders({options:e,method:r,bodyHeaders:d,retryCount:n});return{req:{method:r,headers:m,...s.signal&&{signal:s.signal},...globalThis.ReadableStream&&f instanceof globalThis.ReadableStream&&{duplex:"half"},...f&&{body:f},...this.fetchOptions??{},...s.fetchOptions??{}},url:l,timeout:s.timeout}}async buildHeaders({options:e,method:n,bodyHeaders:s,retryCount:r}){let i={};this.idempotencyHeader&&n!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),i[this.idempotencyHeader]=e.idempotencyKey);const a=g([i,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(r),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},..._s(),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":"true"}:void 0,"anthropic-version":"2023-06-01"},await this.authHeaders(e),this._options.defaultHeaders,s,e.headers]);return this.validateHeaders(a),a.values}buildBody({options:{body:e,headers:n}}){if(!e)return{bodyHeaders:void 0,body:void 0};const s=g([n]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&s.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:_n(e)}:o(this,qe,"f").call(this,{body:e,headers:s})}}gt=y,qe=new WeakMap,dt=new WeakSet,Nn=function(){return this.baseURL!=="https://api.anthropic.com"};y.Anthropic=gt;y.HUMAN_PROMPT=Js;y.AI_PROMPT=Xs;y.DEFAULT_TIMEOUT=6e5;y.AnthropicError=p;y.APIError=w;y.APIConnectionError=He;y.APIConnectionTimeoutError=an;y.APIUserAbortError=v;y.NotFoundError=un;y.ConflictError=hn;y.RateLimitError=pn;y.BadRequestError=on;y.AuthenticationError=cn;y.InternalServerError=fn;y.PermissionDeniedError=ln;y.UnprocessableEntityError=dn;y.toFile=Bs;class ye extends y{constructor(){super(...arguments),this.completions=new On(this),this.messages=new mt(this),this.models=new In(this),this.beta=new _e(this)}}ye.Completions=On;ye.Messages=mt;ye.Models=In;ye.Beta=_e;const zs={"claude-opus-4-1":8192,"claude-opus-4":8192,"claude-sonnet-4":8192,"claude-sonnet-3-7-sonnet":8192,"claude-3-5-sonnet":4096,"claude-3-5-haiku":4096,"claude-3-haiku":2048},tn=2048;function Vs(t){return t?Object.entries(zs).find(([n])=>t.startsWith(n))?.[1]??tn:tn}function Qs(t){return!!(t.tools&&t.tools.length>0)}function Gs(t){for(const e of t.messages??[])if(typeof e.content!="string"){for(const n of e.content??[])if(typeof n=="object"&&n!=null&&n.type==="document"&&typeof n.citations=="object"&&n.citations?.enabled)return!0}return!1}function Ys(t){return!!(t.thinking&&t.thinking.type==="enabled")}function Zs(t){return"input_schema"in t}function er(t){const e=["text_editor_","computer_","bash_","web_search_","web_fetch_","str_replace_editor_","str_replace_based_edit_tool_","code_execution_","memory_"];return typeof t=="object"&&t!==null&&"type"in t&&"name"in t&&typeof t.type=="string"&&e.some(n=>typeof t.type=="string"&&t.type.startsWith(n))}function tr(t){if(typeof t.content=="string")return t.content;if(Array.isArray(t.content)&&t.content.length>=1&&"input"in t.content[0])return typeof t.content[0].input=="string"?t.content[0].input:JSON.stringify(t.content[0].input);if(Array.isArray(t.content)&&t.content.length>=1&&"text"in t.content[0]&&typeof t.content[0].text=="string")return t.content[0].text}var nr=class extends Un{static lc_name(){return"ChatAnthropic"}get lc_secrets(){return{anthropicApiKey:"ANTHROPIC_API_KEY",apiKey:"ANTHROPIC_API_KEY"}}get lc_aliases(){return{modelName:"model"}}lc_serializable=!0;anthropicApiKey;apiKey;apiUrl;temperature;topK;topP;maxTokens;modelName="claude-3-5-sonnet-latest";model="claude-3-5-sonnet-latest";invocationKwargs;stopSequences;streaming=!1;clientOptions;thinking={type:"disabled"};contextManagement;batchClient;streamingClient;streamUsage=!0;createClient;constructor(t){if(super(t??{}),this.anthropicApiKey=t?.apiKey??t?.anthropicApiKey??qn("ANTHROPIC_API_KEY"),!this.anthropicApiKey&&!t?.createClient)throw new Error("Anthropic API key not found");this.clientOptions=t?.clientOptions??{},this.apiKey=this.anthropicApiKey,this.apiUrl=t?.anthropicApiUrl,this.modelName=t?.model??t?.modelName??this.model,this.model=this.modelName,this.invocationKwargs=t?.invocationKwargs??{},this.topP=t?.topP??this.topP,this.temperature=t?.temperature??this.temperature,this.topK=t?.topK??this.topK,this.maxTokens=t?.maxTokens??Vs(this.model),this.stopSequences=t?.stopSequences??this.stopSequences,this.streaming=t?.streaming??!1,this.streamUsage=t?.streamUsage??this.streamUsage,this.thinking=t?.thinking??this.thinking,this.contextManagement=t?.contextManagement??this.contextManagement,this.createClient=t?.createClient??(e=>new ye(e))}getLsParams(t){const e=this.invocationParams(t);return{ls_provider:"anthropic",ls_model_name:this.model,ls_model_type:"chat",ls_temperature:e.temperature??void 0,ls_max_tokens:e.max_tokens??void 0,ls_stop:t.stop}}formatStructuredToolToAnthropic(t){if(!(!t||!t.length))return t.map(e=>{if(er(e)||Zs(e))return e;if(Wn(e))return{name:e.function.name,description:e.function.description,input_schema:e.function.parameters};if(Fn(e))return{name:e.name,description:e.description,input_schema:Mt(e.schema)?be(e.schema):e.schema};throw new Error(`Unknown tool type passed to ChatAnthropic: ${JSON.stringify(e,null,2)}`)})}bindTools(t,e){return this.withConfig({tools:this.formatStructuredToolToAnthropic(t),...e})}invocationParams(t){const e=Kn(t?.tool_choice);if(this.thinking.type==="enabled"){if(this.topP!==void 0&&this.topK!==-1)throw new Error("topK is not supported when thinking is enabled");if(this.temperature!==void 0&&this.temperature!==1)throw new Error("temperature is not supported when thinking is enabled");return{model:this.model,stop_sequences:t?.stop??this.stopSequences,stream:this.streaming,max_tokens:this.maxTokens,tools:this.formatStructuredToolToAnthropic(t?.tools),tool_choice:e,thinking:this.thinking,context_management:this.contextManagement,...this.invocationKwargs,container:t?.container}}return{model:this.model,temperature:this.temperature,top_k:this.topK,top_p:this.topP,stop_sequences:t?.stop??this.stopSequences,stream:this.streaming,max_tokens:this.maxTokens,tools:this.formatStructuredToolToAnthropic(t?.tools),tool_choice:e,thinking:this.thinking,context_management:this.contextManagement,...this.invocationKwargs,container:t?.container}}_identifyingParams(){return{model_name:this.model,...this.invocationParams()}}identifyingParams(){return{model_name:this.model,...this.invocationParams()}}async*_streamResponseChunks(t,e,n){const s=this.invocationParams(e),r=Pt(t),i={...s,...r,stream:!0},a=!Qs(i)&&!Gs(i)&&!Ys(i),c=await this.createStreamWithRetry(i,{headers:e.headers});for await(const l of c){if(e.signal?.aborted)throw c.controller.abort(),new Error("AbortError: User aborted the request.");const d=this.streamUsage??e.streamUsage,f=is(l,{streamUsage:d,coerceContentToString:a});if(!f)continue;const{chunk:m}=f,_=tr(m),h=new Dn({message:new A({content:m.content,additional_kwargs:m.additional_kwargs,tool_call_chunks:m.tool_call_chunks,usage_metadata:d?m.usage_metadata:void 0,response_metadata:m.response_metadata,id:m.id}),text:_??""});yield h,await n?.handleLLMNewToken(_??"",void 0,void 0,void 0,void 0,{chunk:h})}}async _generateNonStreaming(t,e,n){const s=await this.completionWithRetry({...e,stream:!1,...Pt(t)},n),{content:r,...i}=s,a=as(r,i),{role:c,type:l,...d}=i;return{generations:a,llmOutput:d}}async _generate(t,e,n){if(this.stopSequences&&e.stop)throw new Error('"stopSequence" parameter found in input and default params');const s=this.invocationParams(e);if(s.stream){let r;const i=this._streamResponseChunks(t,e,n);for await(const a of i)r===void 0?r=a:r=r.concat(a);if(r===void 0)throw new Error("No chunks returned from Anthropic API.");return{generations:[{text:r.text,message:r.message}]}}else return this._generateNonStreaming(t,s,{signal:e.signal,headers:e.headers})}async createStreamWithRetry(t,e){if(!this.streamingClient){const s=this.apiUrl?{baseURL:this.apiUrl}:void 0;this.streamingClient=this.createClient({dangerouslyAllowBrowser:!0,...this.clientOptions,...s,apiKey:this.apiKey,maxRetries:0})}const n=async()=>{try{return await this.streamingClient.messages.create({...t,...this.invocationKwargs,stream:!0},e)}catch(s){throw Ot(s)}};return this.caller.call(n)}async completionWithRetry(t,e){if(!this.batchClient){const s=this.apiUrl?{baseURL:this.apiUrl}:void 0;this.batchClient=this.createClient({dangerouslyAllowBrowser:!0,...this.clientOptions,...s,apiKey:this.apiKey,maxRetries:0})}const n=async()=>{try{return await this.batchClient.messages.create({...t,...this.invocationKwargs},e)}catch(s){throw Ot(s)}};return this.caller.callWithOptions({signal:e.signal??void 0},n)}_llmType(){return"anthropic"}withStructuredOutput(t,e){const n=t,s=e?.name,r=e?.method,i=e?.includeRaw;if(r==="jsonMode")throw new Error('Anthropic only supports "functionCalling" as a method.');let a=s??"extract",c,l;if(Mt(n)){const h=be(n);l=[{name:a,description:h.description??"A function available to call.",input_schema:h}],c=new Rt({returnSingle:!0,keyName:a,zodSchema:n})}else{let h;typeof n.name=="string"&&typeof n.description=="string"&&typeof n.input_schema=="object"&&n.input_schema!=null?(h=n,a=n.name):h={name:a,description:n.description??"",input_schema:n},l=[h],c=new Rt({returnSingle:!0,keyName:a})}let d;if(this.thinking?.type==="enabled"){const h="Anthropic structured output relies on forced tool calling, which is not supported when `thinking` is enabled. This method will raise OutputParserException if tool calls are not generated. Consider disabling `thinking` or adjust your prompt to ensure the tool is called.";console.warn(h),d=this.withConfig({outputVersion:"v0",tools:l,ls_structured_output_format:{kwargs:{method:"functionCalling"},schema:be(n)}});const b=W=>{if(!W.tool_calls||W.tool_calls.length===0)throw new Error(h);return W};d=d.pipe(b)}else d=this.withConfig({outputVersion:"v0",tools:l,tool_choice:{type:"tool",name:a},ls_structured_output_format:{kwargs:{method:"functionCalling"},schema:be(n)}});if(!i)return d.pipe(c).withConfig({runName:"ChatAnthropicStructuredOutput"});const f=Tt.assign({parsed:(h,b)=>c.invoke(h.raw,b)}),m=Tt.assign({parsed:()=>null}),_=f.withFallbacks({fallbacks:[m]});return Hn.from([{raw:d},_]).withConfig({runName:"StructuredOutputRunnable"})}},hr=class extends nr{};export{hr as ChatAnthropic,nr as ChatAnthropicMessages};