@imgly/plugin-ai-text-generation-web 1.72.0-rc.1 → 1.72.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.
- package/dist/.tsbuildinfo +1 -1
- package/dist/anthropic/index.mjs +10 -10
- package/dist/anthropic/index.mjs.map +4 -4
- package/dist/gateway/GatewayProvider.d.ts +17 -0
- package/dist/gateway/index.d.ts +7 -0
- package/dist/gateway/index.mjs +78 -0
- package/dist/gateway/index.mjs.map +7 -0
- package/dist/index.mjs +15 -15
- package/dist/index.mjs.map +4 -4
- package/dist/open-ai/index.mjs +11 -11
- package/dist/open-ai/index.mjs.map +4 -4
- package/package.json +7 -3
package/dist/anthropic/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var
|
|
1
|
+
var Br=typeof global=="object"&&global&&global.Object===Object&&global,rr=Br,Ur=typeof self=="object"&&self&&self.Object===Object&&self,Fr=rr||Ur||Function("return this")(),C=Fr,zr=C.Symbol,Y=zr,nr=Object.prototype,qr=nr.hasOwnProperty,Vr=nr.toString,ce=Y?Y.toStringTag:void 0;function Gr(r){var e=qr.call(r,ce),t=r[ce];try{r[ce]=void 0;var n=!0}catch{}var i=Vr.call(r);return n&&(e?r[ce]=t:delete r[ce]),i}var Wr=Gr,Hr=Object.prototype,Kr=Hr.toString;function Qr(r){return Kr.call(r)}var Yr=Qr,Jr="[object Null]",Xr="[object Undefined]",zt=Y?Y.toStringTag:void 0;function Zr(r){return r==null?r===void 0?Xr:Jr:zt&&zt in Object(r)?Wr(r):Yr(r)}var ge=Zr;function en(r){return r!=null&&typeof r=="object"}var xt=en,Ma=Array.isArray;function tn(r){var e=typeof r;return r!=null&&(e=="object"||e=="function")}var ir=tn,rn="[object AsyncFunction]",nn="[object Function]",on="[object GeneratorFunction]",an="[object Proxy]";function sn(r){if(!ir(r))return!1;var e=ge(r);return e==nn||e==on||e==rn||e==an}var ln=sn,un=C["__core-js_shared__"],gt=un,qt=function(){var r=/[^.]+$/.exec(gt&>.keys&>.keys.IE_PROTO||"");return r?"Symbol(src)_1."+r:""}();function cn(r){return!!qt&&qt in r}var dn=cn,pn=Function.prototype,fn=pn.toString;function gn(r){if(r!=null){try{return fn.call(r)}catch{}try{return r+""}catch{}}return""}var B=gn,hn=/[\\^$.*+?()[\]{}|]/g,mn=/^\[object .+?Constructor\]$/,yn=Function.prototype,bn=Object.prototype,wn=yn.toString,kn=bn.hasOwnProperty,vn=RegExp("^"+wn.call(kn).replace(hn,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function xn(r){if(!ir(r)||dn(r))return!1;var e=ln(r)?vn:mn;return e.test(B(r))}var _n=xn;function An(r,e){return r?.[e]}var Sn=An;function Mn(r,e){var t=Sn(r,e);return _n(t)?t:void 0}var J=Mn,In=J(C,"WeakMap"),yt=In;function En(r,e){return r===e||r!==r&&e!==e}var Cn=En,Tn=9007199254740991;function Pn(r){return typeof r=="number"&&r>-1&&r%1==0&&r<=Tn}var $n=Pn,Ia=Object.prototype,jn="[object Arguments]";function Rn(r){return xt(r)&&ge(r)==jn}var Vt=Rn,or=Object.prototype,Ln=or.hasOwnProperty,On=or.propertyIsEnumerable,Ea=Vt(function(){return arguments}())?Vt:function(r){return xt(r)&&Ln.call(r,"callee")&&!On.call(r,"callee")},ar=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Gt=ar&&typeof module=="object"&&module&&!module.nodeType&&module,Nn=Gt&&Gt.exports===ar,Wt=Nn?C.Buffer:void 0,Ca=Wt?Wt.isBuffer:void 0,Dn="[object Arguments]",Bn="[object Array]",Un="[object Boolean]",Fn="[object Date]",zn="[object Error]",qn="[object Function]",Vn="[object Map]",Gn="[object Number]",Wn="[object Object]",Hn="[object RegExp]",Kn="[object Set]",Qn="[object String]",Yn="[object WeakMap]",Jn="[object ArrayBuffer]",Xn="[object DataView]",Zn="[object Float32Array]",ei="[object Float64Array]",ti="[object Int8Array]",ri="[object Int16Array]",ni="[object Int32Array]",ii="[object Uint8Array]",oi="[object Uint8ClampedArray]",ai="[object Uint16Array]",si="[object Uint32Array]",p={};p[Zn]=p[ei]=p[ti]=p[ri]=p[ni]=p[ii]=p[oi]=p[ai]=p[si]=!0;p[Dn]=p[Bn]=p[Jn]=p[Un]=p[Xn]=p[Fn]=p[zn]=p[qn]=p[Vn]=p[Gn]=p[Wn]=p[Hn]=p[Kn]=p[Qn]=p[Yn]=!1;function li(r){return xt(r)&&$n(r.length)&&!!p[ge(r)]}var ui=li;function ci(r){return function(e){return r(e)}}var di=ci,sr=typeof exports=="object"&&exports&&!exports.nodeType&&exports,de=sr&&typeof module=="object"&&module&&!module.nodeType&&module,pi=de&&de.exports===sr,ht=pi&&rr.process,fi=function(){try{var r=de&&de.require&&de.require("util").types;return r||ht&&ht.binding&&ht.binding("util")}catch{}}(),Ht=fi,Kt=Ht&&Ht.isTypedArray,Ta=Kt?di(Kt):ui,gi=Object.prototype,Pa=gi.hasOwnProperty;function hi(r,e){return function(t){return r(e(t))}}var mi=hi,$a=mi(Object.keys,Object),yi=Object.prototype,ja=yi.hasOwnProperty,bi=J(Object,"create"),pe=bi;function wi(){this.__data__=pe?pe(null):{},this.size=0}var ki=wi;function vi(r){var e=this.has(r)&&delete this.__data__[r];return this.size-=e?1:0,e}var xi=vi,_i="__lodash_hash_undefined__",Ai=Object.prototype,Si=Ai.hasOwnProperty;function Mi(r){var e=this.__data__;if(pe){var t=e[r];return t===_i?void 0:t}return Si.call(e,r)?e[r]:void 0}var Ii=Mi,Ei=Object.prototype,Ci=Ei.hasOwnProperty;function Ti(r){var e=this.__data__;return pe?e[r]!==void 0:Ci.call(e,r)}var Pi=Ti,$i="__lodash_hash_undefined__";function ji(r,e){var t=this.__data__;return this.size+=this.has(r)?0:1,t[r]=pe&&e===void 0?$i:e,this}var Ri=ji;function X(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var n=r[e];this.set(n[0],n[1])}}X.prototype.clear=ki;X.prototype.delete=xi;X.prototype.get=Ii;X.prototype.has=Pi;X.prototype.set=Ri;var Qt=X;function Li(){this.__data__=[],this.size=0}var Oi=Li;function Ni(r,e){for(var t=r.length;t--;)if(Cn(r[t][0],e))return t;return-1}var Ne=Ni,Di=Array.prototype,Bi=Di.splice;function Ui(r){var e=this.__data__,t=Ne(e,r);if(t<0)return!1;var n=e.length-1;return t==n?e.pop():Bi.call(e,t,1),--this.size,!0}var Fi=Ui;function zi(r){var e=this.__data__,t=Ne(e,r);return t<0?void 0:e[t][1]}var qi=zi;function Vi(r){return Ne(this.__data__,r)>-1}var Gi=Vi;function Wi(r,e){var t=this.__data__,n=Ne(t,r);return n<0?(++this.size,t.push([r,e])):t[n][1]=e,this}var Hi=Wi;function Z(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var n=r[e];this.set(n[0],n[1])}}Z.prototype.clear=Oi;Z.prototype.delete=Fi;Z.prototype.get=qi;Z.prototype.has=Gi;Z.prototype.set=Hi;var De=Z,Ki=J(C,"Map"),fe=Ki;function Qi(){this.size=0,this.__data__={hash:new Qt,map:new(fe||De),string:new Qt}}var Yi=Qi;function Ji(r){var e=typeof r;return e=="string"||e=="number"||e=="symbol"||e=="boolean"?r!=="__proto__":r===null}var Xi=Ji;function Zi(r,e){var t=r.__data__;return Xi(e)?t[typeof e=="string"?"string":"hash"]:t.map}var Be=Zi;function eo(r){var e=Be(this,r).delete(r);return this.size-=e?1:0,e}var to=eo;function ro(r){return Be(this,r).get(r)}var no=ro;function io(r){return Be(this,r).has(r)}var oo=io;function ao(r,e){var t=Be(this,r),n=t.size;return t.set(r,e),this.size+=t.size==n?0:1,this}var so=ao;function ee(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var n=r[e];this.set(n[0],n[1])}}ee.prototype.clear=Yi;ee.prototype.delete=to;ee.prototype.get=no;ee.prototype.has=oo;ee.prototype.set=so;var lr=ee;function lo(){this.__data__=new De,this.size=0}var uo=lo;function co(r){var e=this.__data__,t=e.delete(r);return this.size=e.size,t}var po=co;function fo(r){return this.__data__.get(r)}var go=fo;function ho(r){return this.__data__.has(r)}var mo=ho,yo=200;function bo(r,e){var t=this.__data__;if(t instanceof De){var n=t.__data__;if(!fe||n.length<yo-1)return n.push([r,e]),this.size=++t.size,this;t=this.__data__=new lr(n)}return t.set(r,e),this.size=t.size,this}var wo=bo;function he(r){var e=this.__data__=new De(r);this.size=e.size}he.prototype.clear=uo;he.prototype.delete=po;he.prototype.get=go;he.prototype.has=mo;he.prototype.set=wo;var ko=Object.prototype,Ra=ko.propertyIsEnumerable,vo=J(C,"DataView"),bt=vo,xo=J(C,"Promise"),wt=xo,_o=J(C,"Set"),kt=_o,Yt="[object Map]",Ao="[object Object]",Jt="[object Promise]",Xt="[object Set]",Zt="[object WeakMap]",er="[object DataView]",So=B(bt),Mo=B(fe),Io=B(wt),Eo=B(kt),Co=B(yt),Q=ge;(bt&&Q(new bt(new ArrayBuffer(1)))!=er||fe&&Q(new fe)!=Yt||wt&&Q(wt.resolve())!=Jt||kt&&Q(new kt)!=Xt||yt&&Q(new yt)!=Zt)&&(Q=function(r){var e=ge(r),t=e==Ao?r.constructor:void 0,n=t?B(t):"";if(n)switch(n){case So:return er;case Mo:return Yt;case Io:return Jt;case Eo:return Xt;case Co:return Zt}return e});var La=C.Uint8Array,To="__lodash_hash_undefined__";function Po(r){return this.__data__.set(r,To),this}var $o=Po;function jo(r){return this.__data__.has(r)}var Ro=jo;function vt(r){var e=-1,t=r==null?0:r.length;for(this.__data__=new lr;++e<t;)this.add(r[e])}vt.prototype.add=vt.prototype.push=$o;vt.prototype.has=Ro;var tr=Y?Y.prototype:void 0,Oa=tr?tr.valueOf:void 0,Lo=Object.prototype,Na=Lo.hasOwnProperty,Oo=Object.prototype,Da=Oo.hasOwnProperty,Ba=new RegExp(/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/,"i"),Ua=new RegExp(/[A-Fa-f0-9]{1}/,"g"),Fa=new RegExp(/[A-Fa-f0-9]{2}/,"g");function ur(r,e){let t={...r};if(!e)return t;for(let[n,i]of Object.entries(e))i===!1||i===null||i===void 0?delete t[n]:i===!0?n in r||(t[n]=!0):t[n]=i;return t}var mt="@imgly/plugin-ai-generation",za=`
|
|
2
2
|
<svg>
|
|
3
3
|
<symbol
|
|
4
4
|
fill="none"
|
|
@@ -59,24 +59,24 @@ var Ur=typeof global=="object"&&global&&global.Object===Object&&global,rr=Ur,Br=
|
|
|
59
59
|
|
|
60
60
|
</symbol>
|
|
61
61
|
</svg>
|
|
62
|
-
`;var
|
|
63
|
-
`):[]}};v=new WeakMap;
|
|
64
|
-
`,"\r"]);
|
|
65
|
-
`);
|
|
66
|
-
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],o}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,i,n]=Wo(e,":");return n.startsWith(" ")&&(n=n.substring(1)),t==="event"?this.event=n:t==="data"&&this.data.push(n),null}};function Wo(r,e){let t=r.indexOf(e);return t!==-1?[r.substring(0,t),e,r.substring(t+e.length)]:[r,"",""]}var Go=r=>r!=null&&typeof r=="object"&&typeof r.url=="string"&&typeof r.blob=="function",Ko=r=>r!=null&&typeof r=="object"&&typeof r.name=="string"&&typeof r.lastModified=="number"&&Se(r),Se=r=>r!=null&&typeof r=="object"&&typeof r.size=="number"&&typeof r.type=="string"&&typeof r.text=="function"&&typeof r.slice=="function"&&typeof r.arrayBuffer=="function";async function yr(r,e,t){if(r=await r,Ko(r))return r;if(Go(r)){let n=await r.blob();e||(e=new URL(r.url).pathname.split(/[\\/]/).pop()??"unknown_file");let o=Se(n)?[await n.arrayBuffer()]:[n];return new Be(o,e,t)}let i=await Qo(r);if(e||(e=Jo(r)??"unknown_file"),!t?.type){let n=i[0]?.type;typeof n=="string"&&(t={...t,type:n})}return new Be(i,e,t)}async function Qo(r){let e=[];if(typeof r=="string"||ArrayBuffer.isView(r)||r instanceof ArrayBuffer)e.push(r);else if(Se(r))e.push(await r.arrayBuffer());else if(Xo(r))for await(let t of r)e.push(t);else throw new Error(`Unexpected data type: ${typeof r}; constructor: ${r?.constructor?.name}; props: ${Yo(r)}`);return e}function Yo(r){return`[${Object.getOwnPropertyNames(r).map(t=>`"${t}"`).join(", ")}]`}function Jo(r){return Et(r.name)||Et(r.filename)||Et(r.path)?.split(/[\\/]/).pop()}var Et=r=>{if(typeof r=="string")return r;if(typeof Buffer<"u"&&r instanceof Buffer)return String(r)},Xo=r=>r!=null&&typeof r=="object"&&typeof r[Symbol.asyncIterator]=="function",Ct=r=>r&&typeof r=="object"&&r.body&&r[Symbol.toStringTag]==="MultipartBody";var es=function(r,e,t,i,n){if(i==="m")throw new TypeError("Private method is not writable");if(i==="a"&&!n)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return i==="a"?n.call(r,t):n?n.value=t:e.set(r,t),t},ts=function(r,e,t,i){if(t==="a"&&!i)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!i:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?i:t==="a"?i.call(r):i?i.value:e.get(r)},He;async function xr(r){let{response:e}=r;if(r.options.stream)return re("response",e.status,e.url,e.headers,e.body),r.options.__streamClass?r.options.__streamClass.fromSSEResponse(e,r.controller):I.fromSSEResponse(e,r.controller);if(e.status===204)return null;if(r.options.__binaryResponse)return e;let t=e.headers.get("content-type");if(t?.includes("application/json")||t?.includes("application/vnd.api+json")){let o=await e.json();return re("response",e.status,e.url,e.headers,o),_r(o,e)}let n=await e.text();return re("response",e.status,e.url,e.headers,n),n}function _r(r,e){return!r||typeof r!="object"||Array.isArray(r)?r:Object.defineProperty(r,"_request_id",{value:e.headers.get("request-id"),enumerable:!1})}var Ge=class r extends Promise{constructor(e,t=xr){super(i=>{i(null)}),this.responsePromise=e,this.parseResponse=t}_thenUnwrap(e){return new r(this.responsePromise,async t=>_r(e(await this.parseResponse(t),t),t.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get("request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(this.parseResponse)),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}},Ke=class{constructor({baseURL:e,maxRetries:t=2,timeout:i=6e5,httpAgent:n,fetch:o}){this.baseURL=e,this.maxRetries=Pt("maxRetries",t),this.timeout=Pt("timeout",i),this.httpAgent=n,this.fetch=o??_t}authHeaders(e){return{}}defaultHeaders(e){return{Accept:"application/json","Content-Type":"application/json","User-Agent":this.getUserAgent(),...os(),...this.authHeaders(e)}}validateHeaders(e,t){}defaultIdempotencyKey(){return`stainless-node-retry-${cs()}`}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,i){return this.request(Promise.resolve(i).then(async n=>{let o=n&&Se(n?.body)?new DataView(await n.body.arrayBuffer()):n?.body instanceof DataView?n.body:n?.body instanceof ArrayBuffer?new DataView(n.body):n&&ArrayBuffer.isView(n?.body)?new DataView(n.body.buffer):n?.body;return{method:e,path:t,...n,body:o}}))}getAPIList(e,t,i){return this.requestAPIList(t,{method:"get",path:e,...i})}calculateContentLength(e){if(typeof e=="string"){if(typeof Buffer<"u")return Buffer.byteLength(e,"utf8").toString();if(typeof TextEncoder<"u")return new TextEncoder().encode(e).length.toString()}else if(ArrayBuffer.isView(e))return e.byteLength.toString();return null}buildRequest(e,{retryCount:t=0}={}){e={...e};let{method:i,path:n,query:o,headers:s={}}=e,a=ArrayBuffer.isView(e.body)||e.__binaryRequest&&typeof e.body=="string"?e.body:Ct(e.body)?e.body.body:e.body?JSON.stringify(e.body,null,2):null,f=this.calculateContentLength(a),g=this.buildURL(n,o);"timeout"in e&&Pt("timeout",e.timeout),e.timeout=e.timeout??this.timeout;let k=e.httpAgent??this.httpAgent??St(g),x=e.timeout+1e3;typeof k?.options?.timeout=="number"&&x>(k.options.timeout??0)&&(k.options.timeout=x),this.idempotencyHeader&&i!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),s[this.idempotencyHeader]=e.idempotencyKey);let K=this.buildHeaders({options:e,headers:s,contentLength:f,retryCount:t});return{req:{method:i,...a&&{body:a},headers:K,...k&&{agent:k},signal:e.signal??null},url:g,timeout:e.timeout}}buildHeaders({options:e,headers:t,contentLength:i,retryCount:n}){let o={};i&&(o["content-length"]=i);let s=this.defaultHeaders(e);return vr(o,s),vr(o,t),Ct(e.body)&&F!=="node"&&delete o["content-type"],We(s,"x-stainless-retry-count")===void 0&&We(t,"x-stainless-retry-count")===void 0&&(o["x-stainless-retry-count"]=String(n)),We(s,"x-stainless-timeout")===void 0&&We(t,"x-stainless-timeout")===void 0&&e.timeout&&(o["x-stainless-timeout"]=String(e.timeout)),this.validateHeaders(o,t),o}_calculateNonstreamingTimeout(e){if(3600*e/128e3>600)throw new l("Streaming is strongly recommended for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-python#streaming-responses for more details");return 600*1e3}async prepareOptions(e){}async prepareRequest(e,{url:t,options:i}){}parseHeaders(e){return e?Symbol.iterator in e?Object.fromEntries(Array.from(e).map(t=>[...t])):{...e}:{}}makeStatusError(e,t,i,n){return h.generate(e,t,i,n)}request(e,t=null){return new Ge(this.makeRequest(e,t))}async makeRequest(e,t){let i=await e,n=i.maxRetries??this.maxRetries;t==null&&(t=n),await this.prepareOptions(i);let{req:o,url:s,timeout:a}=this.buildRequest(i,{retryCount:n-t});if(await this.prepareRequest(o,{url:s,options:i}),re("request",s,i,o.headers),i.signal?.aborted)throw new y;let f=new AbortController,g=await this.fetchWithTimeout(s,o,a,f).catch(qe);if(g instanceof Error){if(i.signal?.aborted)throw new y;if(t)return this.retryRequest(i,t);throw g.name==="AbortError"?new te:new R({cause:g})}let k=Mt(g.headers);if(!g.ok){if(t&&this.shouldRetry(g)){let ft=`retrying, ${t} attempts remaining`;return re(`response (error; ${ft})`,g.status,s,k),this.retryRequest(i,t,k)}let x=await g.text().catch(ft=>qe(ft).message),K=ss(x),pt=K?void 0:x;throw re(`response (error; ${t?"(error; no more retries left)":"(error; not retryable)"})`,g.status,s,k,pt),this.makeStatusError(g.status,K,pt,k)}return{response:g,options:i,controller:f}}requestAPIList(e,t){let i=this.makeRequest(t,null);return new Tt(this,i,e)}buildURL(e,t){let i=ls(e)?new URL(e):new URL(this.baseURL+(this.baseURL.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),n=this.defaultQuery();return Ie(n)||(t={...n,...t}),typeof t=="object"&&t&&!Array.isArray(t)&&(i.search=this.stringifyQuery(t)),i.toString()}stringifyQuery(e){return Object.entries(e).filter(([t,i])=>typeof i<"u").map(([t,i])=>{if(typeof i=="string"||typeof i=="number"||typeof i=="boolean")return`${encodeURIComponent(t)}=${encodeURIComponent(i)}`;if(i===null)return`${encodeURIComponent(t)}=`;throw new l(`Cannot stringify type ${typeof i}; 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("&")}async fetchWithTimeout(e,t,i,n){let{signal:o,...s}=t||{};o&&o.addEventListener("abort",()=>n.abort());let a=setTimeout(()=>n.abort(),i),f={signal:n.signal,...s};f.method&&(f.method=f.method.toUpperCase());let g=60*1e3,k=setTimeout(()=>{if(f&&f?.agent?.sockets)for(let x of Object.values(f?.agent?.sockets).flat())x?.setKeepAlive&&x.setKeepAlive(!0,g)},g);return this.fetch.call(void 0,e,f).finally(()=>{clearTimeout(a),clearTimeout(k)})}shouldRetry(e){let t=e.headers.get("x-should-retry");return t==="true"?!0:t==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,i){let n,o=i?.["retry-after-ms"];if(o){let a=parseFloat(o);Number.isNaN(a)||(n=a)}let s=i?.["retry-after"];if(s&&!n){let a=parseFloat(s);Number.isNaN(a)?n=Date.parse(s)-Date.now():n=a*1e3}if(!(n&&0<=n&&n<60*1e3)){let a=e.maxRetries??this.maxRetries;n=this.calculateDefaultRetryTimeoutMillis(t,a)}return await us(n),this.makeRequest(e,t-1)}calculateDefaultRetryTimeoutMillis(e,t){let o=t-e,s=Math.min(.5*Math.pow(2,o),8),a=1-Math.random()*.25;return s*a*1e3}getUserAgent(){return`${this.constructor.name}/JS ${B}`}},Qe=class{constructor(e,t,i,n){He.set(this,void 0),es(this,He,e,"f"),this.options=n,this.response=t,this.body=i}hasNextPage(){return this.getPaginatedItems().length?this.nextPageInfo()!=null:!1}async getNextPage(){let e=this.nextPageInfo();if(!e)throw new l("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");let t={...this.options};if("params"in e&&typeof t.query=="object")t.query={...t.query,...e.params};else if("url"in e){let i=[...Object.entries(t.query||{}),...e.url.searchParams.entries()];for(let[n,o]of i)e.url.searchParams.set(n,o);t.query=void 0,t.path=e.url.toString()}return await ts(this,He,"f").requestAPIList(this.constructor,t)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(He=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}},Tt=class extends Ge{constructor(e,t,i){super(t,async n=>new i(e,n.response,await xr(n),n.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}},Mt=r=>new Proxy(Object.fromEntries(r.entries()),{get(e,t){let i=t.toString();return e[i.toLowerCase()]||e[i]}}),rs={method:!0,path:!0,query:!0,body:!0,headers:!0,maxRetries:!0,stream:!0,timeout:!0,httpAgent:!0,signal:!0,idempotencyKey:!0,__binaryRequest:!0,__binaryResponse:!0,__streamClass:!0},_=r=>typeof r=="object"&&r!==null&&!Ie(r)&&Object.keys(r).every(e=>Ar(rs,e)),is=()=>{if(typeof Deno<"u"&&Deno.build!=null)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":B,"X-Stainless-OS":wr(Deno.build.os),"X-Stainless-Arch":br(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":B,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":process.version};if(Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":B,"X-Stainless-OS":wr(process.platform),"X-Stainless-Arch":br(process.arch),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":process.version};let r=ns();return r?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":B,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${r.browser}`,"X-Stainless-Runtime-Version":r.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":B,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function ns(){if(typeof navigator>"u"||!navigator)return null;let r=[{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(let{key:e,pattern:t}of r){let i=t.exec(navigator.userAgent);if(i){let n=i[1]||0,o=i[2]||0,s=i[3]||0;return{browser:e,version:`${n}.${o}.${s}`}}}return null}var br=r=>r==="x32"?"x32":r==="x86_64"||r==="x64"?"x64":r==="arm"?"arm":r==="aarch64"||r==="arm64"?"arm64":r?`other:${r}`:"unknown",wr=r=>(r=r.toLowerCase(),r.includes("ios")?"iOS":r==="android"?"Android":r==="darwin"?"MacOS":r==="win32"?"Windows":r==="freebsd"?"FreeBSD":r==="openbsd"?"OpenBSD":r==="linux"?"Linux":r?`Other:${r}`:"Unknown"),kr,os=()=>kr??(kr=is()),ss=r=>{try{return JSON.parse(r)}catch{return}},as=/^[a-z][a-z0-9+.-]*:/i,ls=r=>as.test(r),us=r=>new Promise(e=>setTimeout(e,r)),Pt=(r,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new l(`${r} must be an integer`);if(e<0)throw new l(`${r} must be a positive integer`);return e},qe=r=>{if(r instanceof Error)return r;if(typeof r=="object"&&r!==null)try{return new Error(JSON.stringify(r))}catch{}return new Error(String(r))};var Ye=r=>{if(typeof process<"u")return process.env?.[r]?.trim()??void 0;if(typeof Deno<"u")return Deno.env?.get?.(r)?.trim()};function Ie(r){if(!r)return!0;for(let e in r)return!1;return!0}function Ar(r,e){return Object.prototype.hasOwnProperty.call(r,e)}function vr(r,e){for(let t in e){if(!Ar(e,t))continue;let i=t.toLowerCase();if(!i)continue;let n=e[t];n===null?delete r[i]:n!==void 0&&(r[i]=n)}}function re(r,...e){typeof process<"u"&&process?.env?.DEBUG==="true"&&console.log(`Anthropic:DEBUG:${r}`,...e)}var cs=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,r=>{let e=Math.random()*16|0;return(r==="x"?e:e&3|8).toString(16)}),Sr=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u",ds=r=>typeof r?.get=="function";var We=(r,e)=>{let t=e.toLowerCase();if(ds(r)){let i=e[0]?.toUpperCase()+e.substring(1).replace(/([^\w])(\w)/g,(n,o,s)=>o+s.toUpperCase());for(let n of[e,t,e.toUpperCase(),i]){let o=r.get(n);if(o)return o}}for(let[i,n]of Object.entries(r))if(i.toLowerCase()===t)return Array.isArray(n)?(n.length<=1||console.warn(`Received ${n.length} entries for the ${e} header, using the first entry.`),n[0]):n};var M=class extends Qe{constructor(e,t,i,n){super(e,t,i,n),this.data=i.data||[],this.has_more=i.has_more||!1,this.first_id=i.first_id||null,this.last_id=i.last_id||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageParams(){let e=this.nextPageInfo();if(!e)return null;if("params"in e)return e.params;let t=Object.fromEntries(e.url.searchParams);return Object.keys(t).length?t:null}nextPageInfo(){if(this.options.query?.before_id){let t=this.first_id;return t?{params:{before_id:t}}:null}let e=this.last_id;return e?{params:{after_id:e}}:null}};var m=class{constructor(e){this._client=e}};var q=class extends m{retrieve(e,t){return this._client.get(`/v1/models/${e}?beta=true`,t)}list(e={},t){return _(e)?this.list({},e):this._client.getAPIList("/v1/models?beta=true",ie,{query:e,...t})}},ie=class extends M{};q.BetaModelInfosPage=ie;var ne=class r{constructor(e,t){this.iterator=e,this.controller=t}async*decoder(){let e=new P;for await(let t of this.iterator)for(let i of e.decode(t))yield JSON.parse(i);for(let t of e.flush())yield JSON.parse(t)}[Symbol.asyncIterator](){return this.decoder()}static fromResponse(e,t){if(!e.body)throw t.abort(),new l("Attempted to iterate over a response with no body");return new r(Ae(e.body),t)}};var V=class extends m{create(e,t){let{betas:i,...n}=e;return this._client.post("/v1/messages/batches?beta=true",{body:n,...t,headers:{"anthropic-beta":[...i??[],"message-batches-2024-09-24"].toString(),...t?.headers}})}retrieve(e,t={},i){if(_(t))return this.retrieve(e,{},t);let{betas:n}=t;return this._client.get(`/v1/messages/batches/${e}?beta=true`,{...i,headers:{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString(),...i?.headers}})}list(e={},t){if(_(e))return this.list({},e);let{betas:i,...n}=e;return this._client.getAPIList("/v1/messages/batches?beta=true",oe,{query:n,...t,headers:{"anthropic-beta":[...i??[],"message-batches-2024-09-24"].toString(),...t?.headers}})}delete(e,t={},i){if(_(t))return this.delete(e,{},t);let{betas:n}=t;return this._client.delete(`/v1/messages/batches/${e}?beta=true`,{...i,headers:{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString(),...i?.headers}})}cancel(e,t={},i){if(_(t))return this.cancel(e,{},t);let{betas:n}=t;return this._client.post(`/v1/messages/batches/${e}/cancel?beta=true`,{...i,headers:{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString(),...i?.headers}})}async results(e,t={},i){if(_(t))return this.results(e,{},t);let n=await this.retrieve(e);if(!n.results_url)throw new l(`No batch \`results_url\`; Has it finished processing? ${n.processing_status} - ${n.id}`);let{betas:o}=t;return this._client.get(n.results_url,{...i,headers:{"anthropic-beta":[...o??[],"message-batches-2024-09-24"].toString(),Accept:"application/binary",...i?.headers},__binaryResponse:!0})._thenUnwrap((s,a)=>ne.fromResponse(a.response,a.controller))}},oe=class extends M{};V.BetaMessageBatchesPage=oe;var hs=r=>{let e=0,t=[];for(;e<r.length;){let i=r[e];if(i==="\\"){e++;continue}if(i==="{"){t.push({type:"brace",value:"{"}),e++;continue}if(i==="}"){t.push({type:"brace",value:"}"}),e++;continue}if(i==="["){t.push({type:"paren",value:"["}),e++;continue}if(i==="]"){t.push({type:"paren",value:"]"}),e++;continue}if(i===":"){t.push({type:"separator",value:":"}),e++;continue}if(i===","){t.push({type:"delimiter",value:","}),e++;continue}if(i==='"'){let a="",f=!1;for(i=r[++e];i!=='"';){if(e===r.length){f=!0;break}if(i==="\\"){if(e++,e===r.length){f=!0;break}a+=i+r[e],i=r[++e]}else a+=i,i=r[++e]}i=r[++e],f||t.push({type:"string",value:a});continue}if(i&&/\s/.test(i)){e++;continue}let o=/[0-9]/;if(i&&o.test(i)||i==="-"||i==="."){let a="";for(i==="-"&&(a+=i,i=r[++e]);i&&o.test(i)||i===".";)a+=i,i=r[++e];t.push({type:"number",value:a});continue}let s=/[a-z]/i;if(i&&s.test(i)){let a="";for(;i&&s.test(i)&&e!==r.length;)a+=i,i=r[++e];if(a=="true"||a=="false"||a==="null")t.push({type:"name",value:a});else{e++;continue}continue}e++}return t},se=r=>{if(r.length===0)return r;let e=r[r.length-1];switch(e.type){case"separator":return r=r.slice(0,r.length-1),se(r);break;case"number":let t=e.value[e.value.length-1];if(t==="."||t==="-")return r=r.slice(0,r.length-1),se(r);case"string":let i=r[r.length-2];if(i?.type==="delimiter")return r=r.slice(0,r.length-1),se(r);if(i?.type==="brace"&&i.value==="{")return r=r.slice(0,r.length-1),se(r);break;case"delimiter":return r=r.slice(0,r.length-1),se(r);break}return r},ms=r=>{let e=[];return r.map(t=>{t.type==="brace"&&(t.value==="{"?e.push("}"):e.splice(e.lastIndexOf("}"),1)),t.type==="paren"&&(t.value==="["?e.push("]"):e.splice(e.lastIndexOf("]"),1))}),e.length>0&&e.reverse().map(t=>{t==="}"?r.push({type:"brace",value:"}"}):t==="]"&&r.push({type:"paren",value:"]"})}),r},ys=r=>{let e="";return r.map(t=>{switch(t.type){case"string":e+='"'+t.value+'"';break;default:e+=t.value;break}}),e},Je=r=>JSON.parse(ys(ms(se(hs(r)))));var b=function(r,e,t,i,n){if(i==="m")throw new TypeError("Private method is not writable");if(i==="a"&&!n)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return i==="a"?n.call(r,t):n?n.value=t:e.set(r,t),t},u=function(r,e,t,i){if(t==="a"&&!i)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!i:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?i:t==="a"?i.call(r):i?i.value:e.get(r)},A,L,Me,Xe,Ee,Ce,Ze,Pe,T,Te,et,tt,ae,rt,it,jt,Ir,$t,Rt,Lt,Ot,Mr,Er="__json_buf",nt=class r{constructor(){A.add(this),this.messages=[],this.receivedMessages=[],L.set(this,void 0),this.controller=new AbortController,Me.set(this,void 0),Xe.set(this,()=>{}),Ee.set(this,()=>{}),Ce.set(this,void 0),Ze.set(this,()=>{}),Pe.set(this,()=>{}),T.set(this,{}),Te.set(this,!1),et.set(this,!1),tt.set(this,!1),ae.set(this,!1),rt.set(this,void 0),it.set(this,void 0),$t.set(this,e=>{if(b(this,et,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new y),e instanceof y)return b(this,tt,!0,"f"),this._emit("abort",e);if(e instanceof l)return this._emit("error",e);if(e instanceof Error){let t=new l(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new l(String(e)))}),b(this,Me,new Promise((e,t)=>{b(this,Xe,e,"f"),b(this,Ee,t,"f")}),"f"),b(this,Ce,new Promise((e,t)=>{b(this,Ze,e,"f"),b(this,Pe,t,"f")}),"f"),u(this,Me,"f").catch(()=>{}),u(this,Ce,"f").catch(()=>{})}get response(){return u(this,rt,"f")}get request_id(){return u(this,it,"f")}async withResponse(){let e=await u(this,Me,"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){let t=new r;return t._run(()=>t._fromReadableStream(e)),t}static createMessage(e,t,i){let n=new r;for(let o of t.messages)n._addMessageParam(o);return n._run(()=>n._createMessage(e,{...t,stream:!0},{...i,headers:{...i?.headers,"X-Stainless-Helper-Method":"stream"}})),n}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},u(this,$t,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,t=!0){this.receivedMessages.push(e),t&&this._emit("message",e)}async _createMessage(e,t,i){let n=i?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),u(this,A,"m",Rt).call(this);let{response:o,data:s}=await e.create({...t,stream:!0},{...i,signal:this.controller.signal}).withResponse();this._connected(o);for await(let a of s)u(this,A,"m",Lt).call(this,a);if(s.controller.signal?.aborted)throw new y;u(this,A,"m",Ot).call(this)}_connected(e){this.ended||(b(this,rt,e,"f"),b(this,it,e?.headers.get("request-id"),"f"),u(this,Xe,"f").call(this,e),this._emit("connect"))}get ended(){return u(this,Te,"f")}get errored(){return u(this,et,"f")}get aborted(){return u(this,tt,"f")}abort(){this.controller.abort()}on(e,t){return(u(this,T,"f")[e]||(u(this,T,"f")[e]=[])).push({listener:t}),this}off(e,t){let i=u(this,T,"f")[e];if(!i)return this;let n=i.findIndex(o=>o.listener===t);return n>=0&&i.splice(n,1),this}once(e,t){return(u(this,T,"f")[e]||(u(this,T,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,i)=>{b(this,ae,!0,"f"),e!=="error"&&this.once("error",i),this.once(e,t)})}async done(){b(this,ae,!0,"f"),await u(this,Ce,"f")}get currentMessage(){return u(this,L,"f")}async finalMessage(){return await this.done(),u(this,A,"m",jt).call(this)}async finalText(){return await this.done(),u(this,A,"m",Ir).call(this)}_emit(e,...t){if(u(this,Te,"f"))return;e==="end"&&(b(this,Te,!0,"f"),u(this,Ze,"f").call(this));let i=u(this,T,"f")[e];if(i&&(u(this,T,"f")[e]=i.filter(n=>!n.once),i.forEach(({listener:n})=>n(...t))),e==="abort"){let n=t[0];!u(this,ae,"f")&&!i?.length&&Promise.reject(n),u(this,Ee,"f").call(this,n),u(this,Pe,"f").call(this,n),this._emit("end");return}if(e==="error"){let n=t[0];!u(this,ae,"f")&&!i?.length&&Promise.reject(n),u(this,Ee,"f").call(this,n),u(this,Pe,"f").call(this,n),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",u(this,A,"m",jt).call(this))}async _fromReadableStream(e,t){let i=t?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener("abort",()=>this.controller.abort())),u(this,A,"m",Rt).call(this),this._connected(null);let n=I.fromReadableStream(e,this.controller);for await(let o of n)u(this,A,"m",Lt).call(this,o);if(n.controller.signal?.aborted)throw new y;u(this,A,"m",Ot).call(this)}[(L=new WeakMap,Me=new WeakMap,Xe=new WeakMap,Ee=new WeakMap,Ce=new WeakMap,Ze=new WeakMap,Pe=new WeakMap,T=new WeakMap,Te=new WeakMap,et=new WeakMap,tt=new WeakMap,ae=new WeakMap,rt=new WeakMap,it=new WeakMap,$t=new WeakMap,A=new WeakSet,jt=function(){if(this.receivedMessages.length===0)throw new l("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},Ir=function(){if(this.receivedMessages.length===0)throw new l("stream ended without producing a Message with role=assistant");let t=this.receivedMessages.at(-1).content.filter(i=>i.type==="text").map(i=>i.text);if(t.length===0)throw new l("stream ended without producing a content block with type=text");return t.join(" ")},Rt=function(){this.ended||b(this,L,void 0,"f")},Lt=function(t){if(this.ended)return;let i=u(this,A,"m",Mr).call(this,t);switch(this._emit("streamEvent",t,i),t.type){case"content_block_delta":{let n=i.content.at(-1);switch(t.delta.type){case"text_delta":{n.type==="text"&&this._emit("text",t.delta.text,n.text||"");break}case"citations_delta":{n.type==="text"&&this._emit("citation",t.delta.citation,n.citations??[]);break}case"input_json_delta":{n.type==="tool_use"&&n.input&&this._emit("inputJson",t.delta.partial_json,n.input);break}case"thinking_delta":{n.type==="thinking"&&this._emit("thinking",t.delta.thinking,n.thinking);break}case"signature_delta":{n.type==="thinking"&&this._emit("signature",n.signature);break}default:t.delta}break}case"message_stop":{this._addMessageParam(i),this._addMessage(i,!0);break}case"content_block_stop":{this._emit("contentBlock",i.content.at(-1));break}case"message_start":{b(this,L,i,"f");break}case"content_block_start":case"message_delta":break}},Ot=function(){if(this.ended)throw new l("stream has ended, this shouldn't happen");let t=u(this,L,"f");if(!t)throw new l("request ended without sending any chunks");return b(this,L,void 0,"f"),t},Mr=function(t){let i=u(this,L,"f");if(t.type==="message_start"){if(i)throw new l(`Unexpected event order, got ${t.type} before receiving "message_stop"`);return t.message}if(!i)throw new l(`Unexpected event order, got ${t.type} before "message_start"`);switch(t.type){case"message_stop":return i;case"message_delta":return i.stop_reason=t.delta.stop_reason,i.stop_sequence=t.delta.stop_sequence,i.usage.output_tokens=t.usage.output_tokens,i;case"content_block_start":return i.content.push(t.content_block),i;case"content_block_delta":{let n=i.content.at(t.index);switch(t.delta.type){case"text_delta":{n?.type==="text"&&(n.text+=t.delta.text);break}case"citations_delta":{n?.type==="text"&&(n.citations??(n.citations=[]),n.citations.push(t.delta.citation));break}case"input_json_delta":{if(n?.type==="tool_use"){let o=n[Er]||"";o+=t.delta.partial_json,Object.defineProperty(n,Er,{value:o,enumerable:!1,writable:!0}),o&&(n.input=Je(o))}break}case"thinking_delta":{n?.type==="thinking"&&(n.thinking+=t.delta.thinking);break}case"signature_delta":{n?.type==="thinking"&&(n.signature=t.delta.signature);break}default:t.delta}return i}case"content_block_stop":return i}},Symbol.asyncIterator)](){let e=[],t=[],i=!1;return this.on("streamEvent",n=>{let o=t.shift();o?o.resolve(n):e.push(n)}),this.on("end",()=>{i=!0;for(let n of t)n.resolve(void 0);t.length=0}),this.on("abort",n=>{i=!0;for(let o of t)o.reject(n);t.length=0}),this.on("error",n=>{i=!0;for(let o of t)o.reject(n);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:i?{value:void 0,done:!0}:new Promise((o,s)=>t.push({resolve:o,reject:s})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new I(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};var Cr={"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-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025"},O=class extends m{constructor(){super(...arguments),this.batches=new V(this._client)}create(e,t){let{betas:i,...n}=e;return n.model in Cr&&console.warn(`The model '${n.model}' is deprecated and will reach end-of-life on ${Cr[n.model]}
|
|
67
|
-
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),this._client.post("/v1/messages?beta=true",{body:n,timeout:this._client._options.timeout??(n.stream?6e5:this._client._calculateNonstreamingTimeout(n.max_tokens)),...t,headers:{...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0,...t?.headers},stream:e.stream??!1})}stream(e,t){return nt.createMessage(this,e,t)}countTokens(e,t){let{betas:i,...n}=e;return this._client.post("/v1/messages/count_tokens?beta=true",{body:n,...t,headers:{"anthropic-beta":[...i??[],"token-counting-2024-11-01"].toString(),...t?.headers}})}};O.Batches=V;O.BetaMessageBatchesPage=oe;var E=class extends m{constructor(){super(...arguments),this.models=new q(this._client),this.messages=new O(this._client)}};E.Models=q;E.BetaModelInfosPage=ie;E.Messages=O;var H=class extends m{create(e,t){return this._client.post("/v1/complete",{body:e,timeout:this._client._options.timeout??6e5,...t,stream:e.stream??!1})}};var W=class extends m{create(e,t){return this._client.post("/v1/messages/batches",{body:e,...t})}retrieve(e,t){return this._client.get(`/v1/messages/batches/${e}`,t)}list(e={},t){return _(e)?this.list({},e):this._client.getAPIList("/v1/messages/batches",le,{query:e,...t})}delete(e,t){return this._client.delete(`/v1/messages/batches/${e}`,t)}cancel(e,t){return this._client.post(`/v1/messages/batches/${e}/cancel`,t)}async results(e,t){let i=await this.retrieve(e);if(!i.results_url)throw new l(`No batch \`results_url\`; Has it finished processing? ${i.processing_status} - ${i.id}`);return this._client.get(i.results_url,{...t,headers:{Accept:"application/binary",...t?.headers},__binaryResponse:!0})._thenUnwrap((n,o)=>ne.fromResponse(o.response,o.controller))}},le=class extends M{};W.MessageBatchesPage=le;var w=function(r,e,t,i,n){if(i==="m")throw new TypeError("Private method is not writable");if(i==="a"&&!n)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return i==="a"?n.call(r,t):n?n.value=t:e.set(r,t),t},c=function(r,e,t,i){if(t==="a"&&!i)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!i:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?i:t==="a"?i.call(r):i?i.value:e.get(r)},S,N,je,ot,$e,Re,st,Le,j,Oe,at,lt,ue,ut,ct,Nt,Pr,Dt,Ut,Bt,Ft,Tr,jr="__json_buf",dt=class r{constructor(){S.add(this),this.messages=[],this.receivedMessages=[],N.set(this,void 0),this.controller=new AbortController,je.set(this,void 0),ot.set(this,()=>{}),$e.set(this,()=>{}),Re.set(this,void 0),st.set(this,()=>{}),Le.set(this,()=>{}),j.set(this,{}),Oe.set(this,!1),at.set(this,!1),lt.set(this,!1),ue.set(this,!1),ut.set(this,void 0),ct.set(this,void 0),Dt.set(this,e=>{if(w(this,at,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new y),e instanceof y)return w(this,lt,!0,"f"),this._emit("abort",e);if(e instanceof l)return this._emit("error",e);if(e instanceof Error){let t=new l(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new l(String(e)))}),w(this,je,new Promise((e,t)=>{w(this,ot,e,"f"),w(this,$e,t,"f")}),"f"),w(this,Re,new Promise((e,t)=>{w(this,st,e,"f"),w(this,Le,t,"f")}),"f"),c(this,je,"f").catch(()=>{}),c(this,Re,"f").catch(()=>{})}get response(){return c(this,ut,"f")}get request_id(){return c(this,ct,"f")}async withResponse(){let e=await c(this,je,"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){let t=new r;return t._run(()=>t._fromReadableStream(e)),t}static createMessage(e,t,i){let n=new r;for(let o of t.messages)n._addMessageParam(o);return n._run(()=>n._createMessage(e,{...t,stream:!0},{...i,headers:{...i?.headers,"X-Stainless-Helper-Method":"stream"}})),n}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},c(this,Dt,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,t=!0){this.receivedMessages.push(e),t&&this._emit("message",e)}async _createMessage(e,t,i){let n=i?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),c(this,S,"m",Ut).call(this);let{response:o,data:s}=await e.create({...t,stream:!0},{...i,signal:this.controller.signal}).withResponse();this._connected(o);for await(let a of s)c(this,S,"m",Bt).call(this,a);if(s.controller.signal?.aborted)throw new y;c(this,S,"m",Ft).call(this)}_connected(e){this.ended||(w(this,ut,e,"f"),w(this,ct,e?.headers.get("request-id"),"f"),c(this,ot,"f").call(this,e),this._emit("connect"))}get ended(){return c(this,Oe,"f")}get errored(){return c(this,at,"f")}get aborted(){return c(this,lt,"f")}abort(){this.controller.abort()}on(e,t){return(c(this,j,"f")[e]||(c(this,j,"f")[e]=[])).push({listener:t}),this}off(e,t){let i=c(this,j,"f")[e];if(!i)return this;let n=i.findIndex(o=>o.listener===t);return n>=0&&i.splice(n,1),this}once(e,t){return(c(this,j,"f")[e]||(c(this,j,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,i)=>{w(this,ue,!0,"f"),e!=="error"&&this.once("error",i),this.once(e,t)})}async done(){w(this,ue,!0,"f"),await c(this,Re,"f")}get currentMessage(){return c(this,N,"f")}async finalMessage(){return await this.done(),c(this,S,"m",Nt).call(this)}async finalText(){return await this.done(),c(this,S,"m",Pr).call(this)}_emit(e,...t){if(c(this,Oe,"f"))return;e==="end"&&(w(this,Oe,!0,"f"),c(this,st,"f").call(this));let i=c(this,j,"f")[e];if(i&&(c(this,j,"f")[e]=i.filter(n=>!n.once),i.forEach(({listener:n})=>n(...t))),e==="abort"){let n=t[0];!c(this,ue,"f")&&!i?.length&&Promise.reject(n),c(this,$e,"f").call(this,n),c(this,Le,"f").call(this,n),this._emit("end");return}if(e==="error"){let n=t[0];!c(this,ue,"f")&&!i?.length&&Promise.reject(n),c(this,$e,"f").call(this,n),c(this,Le,"f").call(this,n),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",c(this,S,"m",Nt).call(this))}async _fromReadableStream(e,t){let i=t?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener("abort",()=>this.controller.abort())),c(this,S,"m",Ut).call(this),this._connected(null);let n=I.fromReadableStream(e,this.controller);for await(let o of n)c(this,S,"m",Bt).call(this,o);if(n.controller.signal?.aborted)throw new y;c(this,S,"m",Ft).call(this)}[(N=new WeakMap,je=new WeakMap,ot=new WeakMap,$e=new WeakMap,Re=new WeakMap,st=new WeakMap,Le=new WeakMap,j=new WeakMap,Oe=new WeakMap,at=new WeakMap,lt=new WeakMap,ue=new WeakMap,ut=new WeakMap,ct=new WeakMap,Dt=new WeakMap,S=new WeakSet,Nt=function(){if(this.receivedMessages.length===0)throw new l("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},Pr=function(){if(this.receivedMessages.length===0)throw new l("stream ended without producing a Message with role=assistant");let t=this.receivedMessages.at(-1).content.filter(i=>i.type==="text").map(i=>i.text);if(t.length===0)throw new l("stream ended without producing a content block with type=text");return t.join(" ")},Ut=function(){this.ended||w(this,N,void 0,"f")},Bt=function(t){if(this.ended)return;let i=c(this,S,"m",Tr).call(this,t);switch(this._emit("streamEvent",t,i),t.type){case"content_block_delta":{let n=i.content.at(-1);switch(t.delta.type){case"text_delta":{n.type==="text"&&this._emit("text",t.delta.text,n.text||"");break}case"citations_delta":{n.type==="text"&&this._emit("citation",t.delta.citation,n.citations??[]);break}case"input_json_delta":{n.type==="tool_use"&&n.input&&this._emit("inputJson",t.delta.partial_json,n.input);break}case"thinking_delta":{n.type==="thinking"&&this._emit("thinking",t.delta.thinking,n.thinking);break}case"signature_delta":{n.type==="thinking"&&this._emit("signature",n.signature);break}default:t.delta}break}case"message_stop":{this._addMessageParam(i),this._addMessage(i,!0);break}case"content_block_stop":{this._emit("contentBlock",i.content.at(-1));break}case"message_start":{w(this,N,i,"f");break}case"content_block_start":case"message_delta":break}},Ft=function(){if(this.ended)throw new l("stream has ended, this shouldn't happen");let t=c(this,N,"f");if(!t)throw new l("request ended without sending any chunks");return w(this,N,void 0,"f"),t},Tr=function(t){let i=c(this,N,"f");if(t.type==="message_start"){if(i)throw new l(`Unexpected event order, got ${t.type} before receiving "message_stop"`);return t.message}if(!i)throw new l(`Unexpected event order, got ${t.type} before "message_start"`);switch(t.type){case"message_stop":return i;case"message_delta":return i.stop_reason=t.delta.stop_reason,i.stop_sequence=t.delta.stop_sequence,i.usage.output_tokens=t.usage.output_tokens,i;case"content_block_start":return i.content.push(t.content_block),i;case"content_block_delta":{let n=i.content.at(t.index);switch(t.delta.type){case"text_delta":{n?.type==="text"&&(n.text+=t.delta.text);break}case"citations_delta":{n?.type==="text"&&(n.citations??(n.citations=[]),n.citations.push(t.delta.citation));break}case"input_json_delta":{if(n?.type==="tool_use"){let o=n[jr]||"";o+=t.delta.partial_json,Object.defineProperty(n,jr,{value:o,enumerable:!1,writable:!0}),o&&(n.input=Je(o))}break}case"thinking_delta":{n?.type==="thinking"&&(n.thinking+=t.delta.thinking);break}case"signature_delta":{n?.type==="thinking"&&(n.signature=t.delta.signature);break}default:t.delta}return i}case"content_block_stop":return i}},Symbol.asyncIterator)](){let e=[],t=[],i=!1;return this.on("streamEvent",n=>{let o=t.shift();o?o.resolve(n):e.push(n)}),this.on("end",()=>{i=!0;for(let n of t)n.resolve(void 0);t.length=0}),this.on("abort",n=>{i=!0;for(let o of t)o.reject(n);t.length=0}),this.on("error",n=>{i=!0;for(let o of t)o.reject(n);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:i?{value:void 0,done:!0}:new Promise((o,s)=>t.push({resolve:o,reject:s})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new I(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};var $=class extends m{constructor(){super(...arguments),this.batches=new W(this._client)}create(e,t){return e.model in $r&&console.warn(`The model '${e.model}' is deprecated and will reach end-of-life on ${$r[e.model]}
|
|
68
|
-
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),this._client.post("/v1/messages",{body:e,timeout:this._client._options.timeout??(e.stream?6e5:this._client._calculateNonstreamingTimeout(e.max_tokens)),...t,stream:e.stream??!1})}stream(e,t){return dt.createMessage(this,e,t)}countTokens(e,t){return this._client.post("/v1/messages/count_tokens",{body:e,...t})}}
|
|
62
|
+
`;var U="0.39.0";var cr=!1,F,_t,No,Do,Bo,dr,Uo,Ue,At,pr,St,Fe,fr;function gr(r,e={auto:!1}){if(cr)throw new Error(`you must \`import '@anthropic-ai/sdk/shims/${r.kind}'\` before importing anything else from @anthropic-ai/sdk`);if(F)throw new Error(`can't \`import '@anthropic-ai/sdk/shims/${r.kind}'\` after \`import '@anthropic-ai/sdk/shims/${F}'\``);cr=e.auto,F=r.kind,_t=r.fetch,No=r.Request,Do=r.Response,Bo=r.Headers,dr=r.FormData,Uo=r.Blob,Ue=r.File,At=r.ReadableStream,pr=r.getMultipartRequestOptions,St=r.getDefaultAgent,Fe=r.fileFromPath,fr=r.isFsReadStream}var ze=class{constructor(e){this.body=e}get[Symbol.toStringTag](){return"MultipartBody"}};function hr({manuallyImported:r}={}){let e=r?"You may need to use polyfills":"Add one of these imports before your first `import \u2026 from '@anthropic-ai/sdk'`:\n- `import '@anthropic-ai/sdk/shims/node'` (if you're running on Node)\n- `import '@anthropic-ai/sdk/shims/web'` (otherwise)\n",t,n,i,o;try{t=fetch,n=Request,i=Response,o=Headers}catch(a){throw new Error(`this environment is missing the following Web Fetch API type: ${a.message}. ${e}`)}return{kind:"web",fetch:t,Request:n,Response:i,Headers:o,FormData:typeof FormData<"u"?FormData:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'FormData' is undefined. ${e}`)}},Blob:typeof Blob<"u"?Blob:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'Blob' is undefined. ${e}`)}},File:typeof File<"u"?File:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'File' is undefined. ${e}`)}},ReadableStream:typeof ReadableStream<"u"?ReadableStream:class{constructor(){throw new Error(`streaming isn't supported in this environment yet as 'ReadableStream' is undefined. ${e}`)}},getMultipartRequestOptions:async(a,s)=>({...s,body:new ze(a)}),getDefaultAgent:a=>{},fileFromPath:()=>{throw new Error("The `fileFromPath` function is only supported in Node. See the README for more details: https://www.github.com/anthropics/anthropic-sdk-typescript#file-uploads")},isFsReadStream:a=>!1}}F||gr(hr(),{auto:!0});var l=class extends Error{},h=class r extends l{constructor(e,t,n,i){super(`${r.makeMessage(e,t,n)}`),this.status=e,this.headers=i,this.request_id=i?.["request-id"],this.error=t}static makeMessage(e,t,n){let i=t?.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):n;return e&&i?`${e} ${i}`:e?`${e} status code (no body)`:i||"(no status code or body)"}static generate(e,t,n,i){if(!e||!i)return new R({message:n,cause:qe(t)});let o=t;return e===400?new me(e,o,n,i):e===401?new ye(e,o,n,i):e===403?new be(e,o,n,i):e===404?new we(e,o,n,i):e===409?new ke(e,o,n,i):e===422?new ve(e,o,n,i):e===429?new xe(e,o,n,i):e>=500?new _e(e,o,n,i):new r(e,o,n,i)}},y=class extends h{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},R=class extends h{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},te=class extends R{constructor({message:e}={}){super({message:e??"Request timed out."})}},me=class extends h{},ye=class extends h{},be=class extends h{},we=class extends h{},ke=class extends h{},ve=class extends h{},xe=class extends h{},_e=class extends h{};var Ve=function(r,e,t,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!i:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(r,t):i?i.value=t:e.set(r,t),t},z=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},v,T=class{constructor(){v.set(this,void 0),this.buffer=new Uint8Array,Ve(this,v,null,"f")}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?new TextEncoder().encode(e):e,n=new Uint8Array(this.buffer.length+t.length);n.set(this.buffer),n.set(t,this.buffer.length),this.buffer=n;let i=[],o;for(;(o=qo(this.buffer,z(this,v,"f")))!=null;){if(o.carriage&&z(this,v,"f")==null){Ve(this,v,o.index,"f");continue}if(z(this,v,"f")!=null&&(o.index!==z(this,v,"f")+1||o.carriage)){i.push(this.decodeText(this.buffer.slice(0,z(this,v,"f")-1))),this.buffer=this.buffer.slice(z(this,v,"f")),Ve(this,v,null,"f");continue}let a=z(this,v,"f")!==null?o.preceding-1:o.preceding,s=this.decodeText(this.buffer.slice(0,a));i.push(s),this.buffer=this.buffer.slice(o.index),Ve(this,v,null,"f")}return i}decodeText(e){if(e==null)return"";if(typeof e=="string")return e;if(typeof Buffer<"u"){if(e instanceof Buffer)return e.toString();if(e instanceof Uint8Array)return Buffer.from(e).toString();throw new l(`Unexpected: received non-Uint8Array (${e.constructor.name}) stream chunk in an environment with a global "Buffer" defined, which this library assumes to be Node. Please report this error.`)}if(typeof TextDecoder<"u"){if(e instanceof Uint8Array||e instanceof ArrayBuffer)return this.textDecoder??(this.textDecoder=new TextDecoder("utf8")),this.textDecoder.decode(e);throw new l(`Unexpected: received non-Uint8Array/ArrayBuffer (${e.constructor.name}) in a web platform. Please report this error.`)}throw new l("Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.")}flush(){return this.buffer.length?this.decode(`
|
|
63
|
+
`):[]}};v=new WeakMap;T.NEWLINE_CHARS=new Set([`
|
|
64
|
+
`,"\r"]);T.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function qo(r,e){for(let i=e??0;i<r.length;i++){if(r[i]===10)return{preceding:i,index:i+1,carriage:!1};if(r[i]===13)return{preceding:i,index:i+1,carriage:!0}}return null}function mr(r){for(let n=0;n<r.length-1;n++){if(r[n]===10&&r[n+1]===10||r[n]===13&&r[n+1]===13)return n+2;if(r[n]===13&&r[n+1]===10&&n+3<r.length&&r[n+2]===13&&r[n+3]===10)return n+4}return-1}function Ae(r){if(r[Symbol.asyncIterator])return r;let e=r.getReader();return{async next(){try{let t=await e.read();return t?.done&&e.releaseLock(),t}catch(t){throw e.releaseLock(),t}},async return(){let t=e.cancel();return e.releaseLock(),await t,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}var M=class r{constructor(e,t){this.iterator=e,this.controller=t}static fromSSEResponse(e,t){let n=!1;async function*i(){if(n)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let o=!1;try{for await(let a of Vo(e,t)){if(a.event==="completion")try{yield JSON.parse(a.data)}catch(s){throw console.error("Could not parse message into JSON:",a.data),console.error("From chunk:",a.raw),s}if(a.event==="message_start"||a.event==="message_delta"||a.event==="message_stop"||a.event==="content_block_start"||a.event==="content_block_delta"||a.event==="content_block_stop")try{yield JSON.parse(a.data)}catch(s){throw console.error("Could not parse message into JSON:",a.data),console.error("From chunk:",a.raw),s}if(a.event!=="ping"&&a.event==="error")throw h.generate(void 0,`SSE Error: ${a.data}`,a.data,It(e.headers))}o=!0}catch(a){if(a instanceof Error&&a.name==="AbortError")return;throw a}finally{o||t.abort()}}return new r(i,t)}static fromReadableStream(e,t){let n=!1;async function*i(){let a=new T,s=Ae(e);for await(let f of s)for(let g of a.decode(f))yield g;for(let f of a.flush())yield f}async function*o(){if(n)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let a=!1;try{for await(let s of i())a||s&&(yield JSON.parse(s));a=!0}catch(s){if(s instanceof Error&&s.name==="AbortError")return;throw s}finally{a||t.abort()}}return new r(o,t)}[Symbol.asyncIterator](){return this.iterator()}tee(){let e=[],t=[],n=this.iterator(),i=o=>({next:()=>{if(o.length===0){let a=n.next();e.push(a),t.push(a)}return o.shift()}});return[new r(()=>i(e),this.controller),new r(()=>i(t),this.controller)]}toReadableStream(){let e=this,t,n=new TextEncoder;return new At({async start(){t=e[Symbol.asyncIterator]()},async pull(i){try{let{value:o,done:a}=await t.next();if(a)return i.close();let s=n.encode(JSON.stringify(o)+`
|
|
65
|
+
`);i.enqueue(s)}catch(o){i.error(o)}},async cancel(){await t.return?.()}})}};async function*Vo(r,e){if(!r.body)throw e.abort(),new l("Attempted to iterate over a response with no body");let t=new Mt,n=new T,i=Ae(r.body);for await(let o of Go(i))for(let a of n.decode(o)){let s=t.decode(a);s&&(yield s)}for(let o of n.flush()){let a=t.decode(o);a&&(yield a)}}async function*Go(r){let e=new Uint8Array;for await(let t of r){if(t==null)continue;let n=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?new TextEncoder().encode(t):t,i=new Uint8Array(e.length+n.length);i.set(e),i.set(n,e.length),e=i;let o;for(;(o=mr(e))!==-1;)yield e.slice(0,o),e=e.slice(o)}e.length>0&&(yield e)}var Mt=class{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;let o={event:this.event,data:this.data.join(`
|
|
66
|
+
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],o}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,n,i]=Wo(e,":");return i.startsWith(" ")&&(i=i.substring(1)),t==="event"?this.event=i:t==="data"&&this.data.push(i),null}};function Wo(r,e){let t=r.indexOf(e);return t!==-1?[r.substring(0,t),e,r.substring(t+e.length)]:[r,"",""]}var Ho=r=>r!=null&&typeof r=="object"&&typeof r.url=="string"&&typeof r.blob=="function",Ko=r=>r!=null&&typeof r=="object"&&typeof r.name=="string"&&typeof r.lastModified=="number"&&Se(r),Se=r=>r!=null&&typeof r=="object"&&typeof r.size=="number"&&typeof r.type=="string"&&typeof r.text=="function"&&typeof r.slice=="function"&&typeof r.arrayBuffer=="function";async function yr(r,e,t){if(r=await r,Ko(r))return r;if(Ho(r)){let i=await r.blob();e||(e=new URL(r.url).pathname.split(/[\\/]/).pop()??"unknown_file");let o=Se(i)?[await i.arrayBuffer()]:[i];return new Ue(o,e,t)}let n=await Qo(r);if(e||(e=Jo(r)??"unknown_file"),!t?.type){let i=n[0]?.type;typeof i=="string"&&(t={...t,type:i})}return new Ue(n,e,t)}async function Qo(r){let e=[];if(typeof r=="string"||ArrayBuffer.isView(r)||r instanceof ArrayBuffer)e.push(r);else if(Se(r))e.push(await r.arrayBuffer());else if(Xo(r))for await(let t of r)e.push(t);else throw new Error(`Unexpected data type: ${typeof r}; constructor: ${r?.constructor?.name}; props: ${Yo(r)}`);return e}function Yo(r){return`[${Object.getOwnPropertyNames(r).map(t=>`"${t}"`).join(", ")}]`}function Jo(r){return Et(r.name)||Et(r.filename)||Et(r.path)?.split(/[\\/]/).pop()}var Et=r=>{if(typeof r=="string")return r;if(typeof Buffer<"u"&&r instanceof Buffer)return String(r)},Xo=r=>r!=null&&typeof r=="object"&&typeof r[Symbol.asyncIterator]=="function",Ct=r=>r&&typeof r=="object"&&r.body&&r[Symbol.toStringTag]==="MultipartBody";var ea=function(r,e,t,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!i:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(r,t):i?i.value=t:e.set(r,t),t},ta=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},Ge;async function xr(r){let{response:e}=r;if(r.options.stream)return re("response",e.status,e.url,e.headers,e.body),r.options.__streamClass?r.options.__streamClass.fromSSEResponse(e,r.controller):M.fromSSEResponse(e,r.controller);if(e.status===204)return null;if(r.options.__binaryResponse)return e;let t=e.headers.get("content-type");if(t?.includes("application/json")||t?.includes("application/vnd.api+json")){let o=await e.json();return re("response",e.status,e.url,e.headers,o),_r(o,e)}let i=await e.text();return re("response",e.status,e.url,e.headers,i),i}function _r(r,e){return!r||typeof r!="object"||Array.isArray(r)?r:Object.defineProperty(r,"_request_id",{value:e.headers.get("request-id"),enumerable:!1})}var He=class r extends Promise{constructor(e,t=xr){super(n=>{n(null)}),this.responsePromise=e,this.parseResponse=t}_thenUnwrap(e){return new r(this.responsePromise,async t=>_r(e(await this.parseResponse(t),t),t.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get("request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(this.parseResponse)),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}},Ke=class{constructor({baseURL:e,maxRetries:t=2,timeout:n=6e5,httpAgent:i,fetch:o}){this.baseURL=e,this.maxRetries=Tt("maxRetries",t),this.timeout=Tt("timeout",n),this.httpAgent=i,this.fetch=o??_t}authHeaders(e){return{}}defaultHeaders(e){return{Accept:"application/json","Content-Type":"application/json","User-Agent":this.getUserAgent(),...oa(),...this.authHeaders(e)}}validateHeaders(e,t){}defaultIdempotencyKey(){return`stainless-node-retry-${ca()}`}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,n){return this.request(Promise.resolve(n).then(async i=>{let o=i&&Se(i?.body)?new DataView(await i.body.arrayBuffer()):i?.body instanceof DataView?i.body:i?.body instanceof ArrayBuffer?new DataView(i.body):i&&ArrayBuffer.isView(i?.body)?new DataView(i.body.buffer):i?.body;return{method:e,path:t,...i,body:o}}))}getAPIList(e,t,n){return this.requestAPIList(t,{method:"get",path:e,...n})}calculateContentLength(e){if(typeof e=="string"){if(typeof Buffer<"u")return Buffer.byteLength(e,"utf8").toString();if(typeof TextEncoder<"u")return new TextEncoder().encode(e).length.toString()}else if(ArrayBuffer.isView(e))return e.byteLength.toString();return null}buildRequest(e,{retryCount:t=0}={}){e={...e};let{method:n,path:i,query:o,headers:a={}}=e,s=ArrayBuffer.isView(e.body)||e.__binaryRequest&&typeof e.body=="string"?e.body:Ct(e.body)?e.body.body:e.body?JSON.stringify(e.body,null,2):null,f=this.calculateContentLength(s),g=this.buildURL(i,o);"timeout"in e&&Tt("timeout",e.timeout),e.timeout=e.timeout??this.timeout;let k=e.httpAgent??this.httpAgent??St(g),x=e.timeout+1e3;typeof k?.options?.timeout=="number"&&x>(k.options.timeout??0)&&(k.options.timeout=x),this.idempotencyHeader&&n!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),a[this.idempotencyHeader]=e.idempotencyKey);let K=this.buildHeaders({options:e,headers:a,contentLength:f,retryCount:t});return{req:{method:n,...s&&{body:s},headers:K,...k&&{agent:k},signal:e.signal??null},url:g,timeout:e.timeout}}buildHeaders({options:e,headers:t,contentLength:n,retryCount:i}){let o={};n&&(o["content-length"]=n);let a=this.defaultHeaders(e);return vr(o,a),vr(o,t),Ct(e.body)&&F!=="node"&&delete o["content-type"],We(a,"x-stainless-retry-count")===void 0&&We(t,"x-stainless-retry-count")===void 0&&(o["x-stainless-retry-count"]=String(i)),We(a,"x-stainless-timeout")===void 0&&We(t,"x-stainless-timeout")===void 0&&e.timeout&&(o["x-stainless-timeout"]=String(e.timeout)),this.validateHeaders(o,t),o}_calculateNonstreamingTimeout(e){if(3600*e/128e3>600)throw new l("Streaming is strongly recommended for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-python#streaming-responses for more details");return 600*1e3}async prepareOptions(e){}async prepareRequest(e,{url:t,options:n}){}parseHeaders(e){return e?Symbol.iterator in e?Object.fromEntries(Array.from(e).map(t=>[...t])):{...e}:{}}makeStatusError(e,t,n,i){return h.generate(e,t,n,i)}request(e,t=null){return new He(this.makeRequest(e,t))}async makeRequest(e,t){let n=await e,i=n.maxRetries??this.maxRetries;t==null&&(t=i),await this.prepareOptions(n);let{req:o,url:a,timeout:s}=this.buildRequest(n,{retryCount:i-t});if(await this.prepareRequest(o,{url:a,options:n}),re("request",a,n,o.headers),n.signal?.aborted)throw new y;let f=new AbortController,g=await this.fetchWithTimeout(a,o,s,f).catch(qe);if(g instanceof Error){if(n.signal?.aborted)throw new y;if(t)return this.retryRequest(n,t);throw g.name==="AbortError"?new te:new R({cause:g})}let k=It(g.headers);if(!g.ok){if(t&&this.shouldRetry(g)){let ft=`retrying, ${t} attempts remaining`;return re(`response (error; ${ft})`,g.status,a,k),this.retryRequest(n,t,k)}let x=await g.text().catch(ft=>qe(ft).message),K=aa(x),pt=K?void 0:x;throw re(`response (error; ${t?"(error; no more retries left)":"(error; not retryable)"})`,g.status,a,k,pt),this.makeStatusError(g.status,K,pt,k)}return{response:g,options:n,controller:f}}requestAPIList(e,t){let n=this.makeRequest(t,null);return new Pt(this,n,e)}buildURL(e,t){let n=la(e)?new URL(e):new URL(this.baseURL+(this.baseURL.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),i=this.defaultQuery();return Me(i)||(t={...i,...t}),typeof t=="object"&&t&&!Array.isArray(t)&&(n.search=this.stringifyQuery(t)),n.toString()}stringifyQuery(e){return Object.entries(e).filter(([t,n])=>typeof n<"u").map(([t,n])=>{if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")return`${encodeURIComponent(t)}=${encodeURIComponent(n)}`;if(n===null)return`${encodeURIComponent(t)}=`;throw new l(`Cannot stringify type ${typeof n}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}async fetchWithTimeout(e,t,n,i){let{signal:o,...a}=t||{};o&&o.addEventListener("abort",()=>i.abort());let s=setTimeout(()=>i.abort(),n),f={signal:i.signal,...a};f.method&&(f.method=f.method.toUpperCase());let g=60*1e3,k=setTimeout(()=>{if(f&&f?.agent?.sockets)for(let x of Object.values(f?.agent?.sockets).flat())x?.setKeepAlive&&x.setKeepAlive(!0,g)},g);return this.fetch.call(void 0,e,f).finally(()=>{clearTimeout(s),clearTimeout(k)})}shouldRetry(e){let t=e.headers.get("x-should-retry");return t==="true"?!0:t==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,n){let i,o=n?.["retry-after-ms"];if(o){let s=parseFloat(o);Number.isNaN(s)||(i=s)}let a=n?.["retry-after"];if(a&&!i){let s=parseFloat(a);Number.isNaN(s)?i=Date.parse(a)-Date.now():i=s*1e3}if(!(i&&0<=i&&i<60*1e3)){let s=e.maxRetries??this.maxRetries;i=this.calculateDefaultRetryTimeoutMillis(t,s)}return await ua(i),this.makeRequest(e,t-1)}calculateDefaultRetryTimeoutMillis(e,t){let o=t-e,a=Math.min(.5*Math.pow(2,o),8),s=1-Math.random()*.25;return a*s*1e3}getUserAgent(){return`${this.constructor.name}/JS ${U}`}},Qe=class{constructor(e,t,n,i){Ge.set(this,void 0),ea(this,Ge,e,"f"),this.options=i,this.response=t,this.body=n}hasNextPage(){return this.getPaginatedItems().length?this.nextPageInfo()!=null:!1}async getNextPage(){let e=this.nextPageInfo();if(!e)throw new l("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");let t={...this.options};if("params"in e&&typeof t.query=="object")t.query={...t.query,...e.params};else if("url"in e){let n=[...Object.entries(t.query||{}),...e.url.searchParams.entries()];for(let[i,o]of n)e.url.searchParams.set(i,o);t.query=void 0,t.path=e.url.toString()}return await ta(this,Ge,"f").requestAPIList(this.constructor,t)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(Ge=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}},Pt=class extends He{constructor(e,t,n){super(t,async i=>new n(e,i.response,await xr(i),i.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}},It=r=>new Proxy(Object.fromEntries(r.entries()),{get(e,t){let n=t.toString();return e[n.toLowerCase()]||e[n]}}),ra={method:!0,path:!0,query:!0,body:!0,headers:!0,maxRetries:!0,stream:!0,timeout:!0,httpAgent:!0,signal:!0,idempotencyKey:!0,__binaryRequest:!0,__binaryResponse:!0,__streamClass:!0},_=r=>typeof r=="object"&&r!==null&&!Me(r)&&Object.keys(r).every(e=>Ar(ra,e)),na=()=>{if(typeof Deno<"u"&&Deno.build!=null)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":U,"X-Stainless-OS":wr(Deno.build.os),"X-Stainless-Arch":br(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":U,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":process.version};if(Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":U,"X-Stainless-OS":wr(process.platform),"X-Stainless-Arch":br(process.arch),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":process.version};let r=ia();return r?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":U,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${r.browser}`,"X-Stainless-Runtime-Version":r.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":U,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function ia(){if(typeof navigator>"u"||!navigator)return null;let r=[{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(let{key:e,pattern:t}of r){let n=t.exec(navigator.userAgent);if(n){let i=n[1]||0,o=n[2]||0,a=n[3]||0;return{browser:e,version:`${i}.${o}.${a}`}}}return null}var br=r=>r==="x32"?"x32":r==="x86_64"||r==="x64"?"x64":r==="arm"?"arm":r==="aarch64"||r==="arm64"?"arm64":r?`other:${r}`:"unknown",wr=r=>(r=r.toLowerCase(),r.includes("ios")?"iOS":r==="android"?"Android":r==="darwin"?"MacOS":r==="win32"?"Windows":r==="freebsd"?"FreeBSD":r==="openbsd"?"OpenBSD":r==="linux"?"Linux":r?`Other:${r}`:"Unknown"),kr,oa=()=>kr??(kr=na()),aa=r=>{try{return JSON.parse(r)}catch{return}},sa=/^[a-z][a-z0-9+.-]*:/i,la=r=>sa.test(r),ua=r=>new Promise(e=>setTimeout(e,r)),Tt=(r,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new l(`${r} must be an integer`);if(e<0)throw new l(`${r} must be a positive integer`);return e},qe=r=>{if(r instanceof Error)return r;if(typeof r=="object"&&r!==null)try{return new Error(JSON.stringify(r))}catch{}return new Error(String(r))};var Ye=r=>{if(typeof process<"u")return process.env?.[r]?.trim()??void 0;if(typeof Deno<"u")return Deno.env?.get?.(r)?.trim()};function Me(r){if(!r)return!0;for(let e in r)return!1;return!0}function Ar(r,e){return Object.prototype.hasOwnProperty.call(r,e)}function vr(r,e){for(let t in e){if(!Ar(e,t))continue;let n=t.toLowerCase();if(!n)continue;let i=e[t];i===null?delete r[n]:i!==void 0&&(r[n]=i)}}function re(r,...e){typeof process<"u"&&process?.env?.DEBUG==="true"&&console.log(`Anthropic:DEBUG:${r}`,...e)}var ca=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,r=>{let e=Math.random()*16|0;return(r==="x"?e:e&3|8).toString(16)}),Sr=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u",da=r=>typeof r?.get=="function";var We=(r,e)=>{let t=e.toLowerCase();if(da(r)){let n=e[0]?.toUpperCase()+e.substring(1).replace(/([^\w])(\w)/g,(i,o,a)=>o+a.toUpperCase());for(let i of[e,t,e.toUpperCase(),n]){let o=r.get(i);if(o)return o}}for(let[n,i]of Object.entries(r))if(n.toLowerCase()===t)return Array.isArray(i)?(i.length<=1||console.warn(`Received ${i.length} entries for the ${e} header, using the first entry.`),i[0]):i};var I=class extends Qe{constructor(e,t,n,i){super(e,t,n,i),this.data=n.data||[],this.has_more=n.has_more||!1,this.first_id=n.first_id||null,this.last_id=n.last_id||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageParams(){let e=this.nextPageInfo();if(!e)return null;if("params"in e)return e.params;let t=Object.fromEntries(e.url.searchParams);return Object.keys(t).length?t:null}nextPageInfo(){if(this.options.query?.before_id){let t=this.first_id;return t?{params:{before_id:t}}:null}let e=this.last_id;return e?{params:{after_id:e}}:null}};var m=class{constructor(e){this._client=e}};var q=class extends m{retrieve(e,t){return this._client.get(`/v1/models/${e}?beta=true`,t)}list(e={},t){return _(e)?this.list({},e):this._client.getAPIList("/v1/models?beta=true",ne,{query:e,...t})}},ne=class extends I{};q.BetaModelInfosPage=ne;var ie=class r{constructor(e,t){this.iterator=e,this.controller=t}async*decoder(){let e=new T;for await(let t of this.iterator)for(let n of e.decode(t))yield JSON.parse(n);for(let t of e.flush())yield JSON.parse(t)}[Symbol.asyncIterator](){return this.decoder()}static fromResponse(e,t){if(!e.body)throw t.abort(),new l("Attempted to iterate over a response with no body");return new r(Ae(e.body),t)}};var V=class extends m{create(e,t){let{betas:n,...i}=e;return this._client.post("/v1/messages/batches?beta=true",{body:i,...t,headers:{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString(),...t?.headers}})}retrieve(e,t={},n){if(_(t))return this.retrieve(e,{},t);let{betas:i}=t;return this._client.get(`/v1/messages/batches/${e}?beta=true`,{...n,headers:{"anthropic-beta":[...i??[],"message-batches-2024-09-24"].toString(),...n?.headers}})}list(e={},t){if(_(e))return this.list({},e);let{betas:n,...i}=e;return this._client.getAPIList("/v1/messages/batches?beta=true",oe,{query:i,...t,headers:{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString(),...t?.headers}})}delete(e,t={},n){if(_(t))return this.delete(e,{},t);let{betas:i}=t;return this._client.delete(`/v1/messages/batches/${e}?beta=true`,{...n,headers:{"anthropic-beta":[...i??[],"message-batches-2024-09-24"].toString(),...n?.headers}})}cancel(e,t={},n){if(_(t))return this.cancel(e,{},t);let{betas:i}=t;return this._client.post(`/v1/messages/batches/${e}/cancel?beta=true`,{...n,headers:{"anthropic-beta":[...i??[],"message-batches-2024-09-24"].toString(),...n?.headers}})}async results(e,t={},n){if(_(t))return this.results(e,{},t);let i=await this.retrieve(e);if(!i.results_url)throw new l(`No batch \`results_url\`; Has it finished processing? ${i.processing_status} - ${i.id}`);let{betas:o}=t;return this._client.get(i.results_url,{...n,headers:{"anthropic-beta":[...o??[],"message-batches-2024-09-24"].toString(),Accept:"application/binary",...n?.headers},__binaryResponse:!0})._thenUnwrap((a,s)=>ie.fromResponse(s.response,s.controller))}},oe=class extends I{};V.BetaMessageBatchesPage=oe;var ha=r=>{let e=0,t=[];for(;e<r.length;){let n=r[e];if(n==="\\"){e++;continue}if(n==="{"){t.push({type:"brace",value:"{"}),e++;continue}if(n==="}"){t.push({type:"brace",value:"}"}),e++;continue}if(n==="["){t.push({type:"paren",value:"["}),e++;continue}if(n==="]"){t.push({type:"paren",value:"]"}),e++;continue}if(n===":"){t.push({type:"separator",value:":"}),e++;continue}if(n===","){t.push({type:"delimiter",value:","}),e++;continue}if(n==='"'){let s="",f=!1;for(n=r[++e];n!=='"';){if(e===r.length){f=!0;break}if(n==="\\"){if(e++,e===r.length){f=!0;break}s+=n+r[e],n=r[++e]}else s+=n,n=r[++e]}n=r[++e],f||t.push({type:"string",value:s});continue}if(n&&/\s/.test(n)){e++;continue}let o=/[0-9]/;if(n&&o.test(n)||n==="-"||n==="."){let s="";for(n==="-"&&(s+=n,n=r[++e]);n&&o.test(n)||n===".";)s+=n,n=r[++e];t.push({type:"number",value:s});continue}let a=/[a-z]/i;if(n&&a.test(n)){let s="";for(;n&&a.test(n)&&e!==r.length;)s+=n,n=r[++e];if(s=="true"||s=="false"||s==="null")t.push({type:"name",value:s});else{e++;continue}continue}e++}return t},ae=r=>{if(r.length===0)return r;let e=r[r.length-1];switch(e.type){case"separator":return r=r.slice(0,r.length-1),ae(r);break;case"number":let t=e.value[e.value.length-1];if(t==="."||t==="-")return r=r.slice(0,r.length-1),ae(r);case"string":let n=r[r.length-2];if(n?.type==="delimiter")return r=r.slice(0,r.length-1),ae(r);if(n?.type==="brace"&&n.value==="{")return r=r.slice(0,r.length-1),ae(r);break;case"delimiter":return r=r.slice(0,r.length-1),ae(r);break}return r},ma=r=>{let e=[];return r.map(t=>{t.type==="brace"&&(t.value==="{"?e.push("}"):e.splice(e.lastIndexOf("}"),1)),t.type==="paren"&&(t.value==="["?e.push("]"):e.splice(e.lastIndexOf("]"),1))}),e.length>0&&e.reverse().map(t=>{t==="}"?r.push({type:"brace",value:"}"}):t==="]"&&r.push({type:"paren",value:"]"})}),r},ya=r=>{let e="";return r.map(t=>{switch(t.type){case"string":e+='"'+t.value+'"';break;default:e+=t.value;break}}),e},Je=r=>JSON.parse(ya(ma(ae(ha(r)))));var b=function(r,e,t,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!i:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(r,t):i?i.value=t:e.set(r,t),t},u=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},A,L,Ie,Xe,Ee,Ce,Ze,Te,P,Pe,et,tt,se,rt,nt,$t,Mr,jt,Rt,Lt,Ot,Ir,Er="__json_buf",it=class r{constructor(){A.add(this),this.messages=[],this.receivedMessages=[],L.set(this,void 0),this.controller=new AbortController,Ie.set(this,void 0),Xe.set(this,()=>{}),Ee.set(this,()=>{}),Ce.set(this,void 0),Ze.set(this,()=>{}),Te.set(this,()=>{}),P.set(this,{}),Pe.set(this,!1),et.set(this,!1),tt.set(this,!1),se.set(this,!1),rt.set(this,void 0),nt.set(this,void 0),jt.set(this,e=>{if(b(this,et,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new y),e instanceof y)return b(this,tt,!0,"f"),this._emit("abort",e);if(e instanceof l)return this._emit("error",e);if(e instanceof Error){let t=new l(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new l(String(e)))}),b(this,Ie,new Promise((e,t)=>{b(this,Xe,e,"f"),b(this,Ee,t,"f")}),"f"),b(this,Ce,new Promise((e,t)=>{b(this,Ze,e,"f"),b(this,Te,t,"f")}),"f"),u(this,Ie,"f").catch(()=>{}),u(this,Ce,"f").catch(()=>{})}get response(){return u(this,rt,"f")}get request_id(){return u(this,nt,"f")}async withResponse(){let e=await u(this,Ie,"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){let t=new r;return t._run(()=>t._fromReadableStream(e)),t}static createMessage(e,t,n){let i=new r;for(let o of t.messages)i._addMessageParam(o);return i._run(()=>i._createMessage(e,{...t,stream:!0},{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),i}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},u(this,jt,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,t=!0){this.receivedMessages.push(e),t&&this._emit("message",e)}async _createMessage(e,t,n){let i=n?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener("abort",()=>this.controller.abort())),u(this,A,"m",Rt).call(this);let{response:o,data:a}=await e.create({...t,stream:!0},{...n,signal:this.controller.signal}).withResponse();this._connected(o);for await(let s of a)u(this,A,"m",Lt).call(this,s);if(a.controller.signal?.aborted)throw new y;u(this,A,"m",Ot).call(this)}_connected(e){this.ended||(b(this,rt,e,"f"),b(this,nt,e?.headers.get("request-id"),"f"),u(this,Xe,"f").call(this,e),this._emit("connect"))}get ended(){return u(this,Pe,"f")}get errored(){return u(this,et,"f")}get aborted(){return u(this,tt,"f")}abort(){this.controller.abort()}on(e,t){return(u(this,P,"f")[e]||(u(this,P,"f")[e]=[])).push({listener:t}),this}off(e,t){let n=u(this,P,"f")[e];if(!n)return this;let i=n.findIndex(o=>o.listener===t);return i>=0&&n.splice(i,1),this}once(e,t){return(u(this,P,"f")[e]||(u(this,P,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,n)=>{b(this,se,!0,"f"),e!=="error"&&this.once("error",n),this.once(e,t)})}async done(){b(this,se,!0,"f"),await u(this,Ce,"f")}get currentMessage(){return u(this,L,"f")}async finalMessage(){return await this.done(),u(this,A,"m",$t).call(this)}async finalText(){return await this.done(),u(this,A,"m",Mr).call(this)}_emit(e,...t){if(u(this,Pe,"f"))return;e==="end"&&(b(this,Pe,!0,"f"),u(this,Ze,"f").call(this));let n=u(this,P,"f")[e];if(n&&(u(this,P,"f")[e]=n.filter(i=>!i.once),n.forEach(({listener:i})=>i(...t))),e==="abort"){let i=t[0];!u(this,se,"f")&&!n?.length&&Promise.reject(i),u(this,Ee,"f").call(this,i),u(this,Te,"f").call(this,i),this._emit("end");return}if(e==="error"){let i=t[0];!u(this,se,"f")&&!n?.length&&Promise.reject(i),u(this,Ee,"f").call(this,i),u(this,Te,"f").call(this,i),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",u(this,A,"m",$t).call(this))}async _fromReadableStream(e,t){let n=t?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),u(this,A,"m",Rt).call(this),this._connected(null);let i=M.fromReadableStream(e,this.controller);for await(let o of i)u(this,A,"m",Lt).call(this,o);if(i.controller.signal?.aborted)throw new y;u(this,A,"m",Ot).call(this)}[(L=new WeakMap,Ie=new WeakMap,Xe=new WeakMap,Ee=new WeakMap,Ce=new WeakMap,Ze=new WeakMap,Te=new WeakMap,P=new WeakMap,Pe=new WeakMap,et=new WeakMap,tt=new WeakMap,se=new WeakMap,rt=new WeakMap,nt=new WeakMap,jt=new WeakMap,A=new WeakSet,$t=function(){if(this.receivedMessages.length===0)throw new l("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},Mr=function(){if(this.receivedMessages.length===0)throw new l("stream ended without producing a Message with role=assistant");let t=this.receivedMessages.at(-1).content.filter(n=>n.type==="text").map(n=>n.text);if(t.length===0)throw new l("stream ended without producing a content block with type=text");return t.join(" ")},Rt=function(){this.ended||b(this,L,void 0,"f")},Lt=function(t){if(this.ended)return;let n=u(this,A,"m",Ir).call(this,t);switch(this._emit("streamEvent",t,n),t.type){case"content_block_delta":{let i=n.content.at(-1);switch(t.delta.type){case"text_delta":{i.type==="text"&&this._emit("text",t.delta.text,i.text||"");break}case"citations_delta":{i.type==="text"&&this._emit("citation",t.delta.citation,i.citations??[]);break}case"input_json_delta":{i.type==="tool_use"&&i.input&&this._emit("inputJson",t.delta.partial_json,i.input);break}case"thinking_delta":{i.type==="thinking"&&this._emit("thinking",t.delta.thinking,i.thinking);break}case"signature_delta":{i.type==="thinking"&&this._emit("signature",i.signature);break}default:t.delta}break}case"message_stop":{this._addMessageParam(n),this._addMessage(n,!0);break}case"content_block_stop":{this._emit("contentBlock",n.content.at(-1));break}case"message_start":{b(this,L,n,"f");break}case"content_block_start":case"message_delta":break}},Ot=function(){if(this.ended)throw new l("stream has ended, this shouldn't happen");let t=u(this,L,"f");if(!t)throw new l("request ended without sending any chunks");return b(this,L,void 0,"f"),t},Ir=function(t){let n=u(this,L,"f");if(t.type==="message_start"){if(n)throw new l(`Unexpected event order, got ${t.type} before receiving "message_stop"`);return t.message}if(!n)throw new l(`Unexpected event order, got ${t.type} before "message_start"`);switch(t.type){case"message_stop":return n;case"message_delta":return n.stop_reason=t.delta.stop_reason,n.stop_sequence=t.delta.stop_sequence,n.usage.output_tokens=t.usage.output_tokens,n;case"content_block_start":return n.content.push(t.content_block),n;case"content_block_delta":{let i=n.content.at(t.index);switch(t.delta.type){case"text_delta":{i?.type==="text"&&(i.text+=t.delta.text);break}case"citations_delta":{i?.type==="text"&&(i.citations??(i.citations=[]),i.citations.push(t.delta.citation));break}case"input_json_delta":{if(i?.type==="tool_use"){let o=i[Er]||"";o+=t.delta.partial_json,Object.defineProperty(i,Er,{value:o,enumerable:!1,writable:!0}),o&&(i.input=Je(o))}break}case"thinking_delta":{i?.type==="thinking"&&(i.thinking+=t.delta.thinking);break}case"signature_delta":{i?.type==="thinking"&&(i.signature=t.delta.signature);break}default:t.delta}return n}case"content_block_stop":return n}},Symbol.asyncIterator)](){let e=[],t=[],n=!1;return this.on("streamEvent",i=>{let o=t.shift();o?o.resolve(i):e.push(i)}),this.on("end",()=>{n=!0;for(let i of t)i.resolve(void 0);t.length=0}),this.on("abort",i=>{n=!0;for(let o of t)o.reject(i);t.length=0}),this.on("error",i=>{n=!0;for(let o of t)o.reject(i);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((o,a)=>t.push({resolve:o,reject:a})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new M(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};var Cr={"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-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025"},O=class extends m{constructor(){super(...arguments),this.batches=new V(this._client)}create(e,t){let{betas:n,...i}=e;return i.model in Cr&&console.warn(`The model '${i.model}' is deprecated and will reach end-of-life on ${Cr[i.model]}
|
|
67
|
+
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),this._client.post("/v1/messages?beta=true",{body:i,timeout:this._client._options.timeout??(i.stream?6e5:this._client._calculateNonstreamingTimeout(i.max_tokens)),...t,headers:{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0,...t?.headers},stream:e.stream??!1})}stream(e,t){return it.createMessage(this,e,t)}countTokens(e,t){let{betas:n,...i}=e;return this._client.post("/v1/messages/count_tokens?beta=true",{body:i,...t,headers:{"anthropic-beta":[...n??[],"token-counting-2024-11-01"].toString(),...t?.headers}})}};O.Batches=V;O.BetaMessageBatchesPage=oe;var E=class extends m{constructor(){super(...arguments),this.models=new q(this._client),this.messages=new O(this._client)}};E.Models=q;E.BetaModelInfosPage=ne;E.Messages=O;var G=class extends m{create(e,t){return this._client.post("/v1/complete",{body:e,timeout:this._client._options.timeout??6e5,...t,stream:e.stream??!1})}};var W=class extends m{create(e,t){return this._client.post("/v1/messages/batches",{body:e,...t})}retrieve(e,t){return this._client.get(`/v1/messages/batches/${e}`,t)}list(e={},t){return _(e)?this.list({},e):this._client.getAPIList("/v1/messages/batches",le,{query:e,...t})}delete(e,t){return this._client.delete(`/v1/messages/batches/${e}`,t)}cancel(e,t){return this._client.post(`/v1/messages/batches/${e}/cancel`,t)}async results(e,t){let n=await this.retrieve(e);if(!n.results_url)throw new l(`No batch \`results_url\`; Has it finished processing? ${n.processing_status} - ${n.id}`);return this._client.get(n.results_url,{...t,headers:{Accept:"application/binary",...t?.headers},__binaryResponse:!0})._thenUnwrap((i,o)=>ie.fromResponse(o.response,o.controller))}},le=class extends I{};W.MessageBatchesPage=le;var w=function(r,e,t,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!i:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(r,t):i?i.value=t:e.set(r,t),t},c=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},S,N,$e,ot,je,Re,at,Le,$,Oe,st,lt,ue,ut,ct,Nt,Tr,Dt,Bt,Ut,Ft,Pr,$r="__json_buf",dt=class r{constructor(){S.add(this),this.messages=[],this.receivedMessages=[],N.set(this,void 0),this.controller=new AbortController,$e.set(this,void 0),ot.set(this,()=>{}),je.set(this,()=>{}),Re.set(this,void 0),at.set(this,()=>{}),Le.set(this,()=>{}),$.set(this,{}),Oe.set(this,!1),st.set(this,!1),lt.set(this,!1),ue.set(this,!1),ut.set(this,void 0),ct.set(this,void 0),Dt.set(this,e=>{if(w(this,st,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new y),e instanceof y)return w(this,lt,!0,"f"),this._emit("abort",e);if(e instanceof l)return this._emit("error",e);if(e instanceof Error){let t=new l(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new l(String(e)))}),w(this,$e,new Promise((e,t)=>{w(this,ot,e,"f"),w(this,je,t,"f")}),"f"),w(this,Re,new Promise((e,t)=>{w(this,at,e,"f"),w(this,Le,t,"f")}),"f"),c(this,$e,"f").catch(()=>{}),c(this,Re,"f").catch(()=>{})}get response(){return c(this,ut,"f")}get request_id(){return c(this,ct,"f")}async withResponse(){let e=await c(this,$e,"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){let t=new r;return t._run(()=>t._fromReadableStream(e)),t}static createMessage(e,t,n){let i=new r;for(let o of t.messages)i._addMessageParam(o);return i._run(()=>i._createMessage(e,{...t,stream:!0},{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),i}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},c(this,Dt,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,t=!0){this.receivedMessages.push(e),t&&this._emit("message",e)}async _createMessage(e,t,n){let i=n?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener("abort",()=>this.controller.abort())),c(this,S,"m",Bt).call(this);let{response:o,data:a}=await e.create({...t,stream:!0},{...n,signal:this.controller.signal}).withResponse();this._connected(o);for await(let s of a)c(this,S,"m",Ut).call(this,s);if(a.controller.signal?.aborted)throw new y;c(this,S,"m",Ft).call(this)}_connected(e){this.ended||(w(this,ut,e,"f"),w(this,ct,e?.headers.get("request-id"),"f"),c(this,ot,"f").call(this,e),this._emit("connect"))}get ended(){return c(this,Oe,"f")}get errored(){return c(this,st,"f")}get aborted(){return c(this,lt,"f")}abort(){this.controller.abort()}on(e,t){return(c(this,$,"f")[e]||(c(this,$,"f")[e]=[])).push({listener:t}),this}off(e,t){let n=c(this,$,"f")[e];if(!n)return this;let i=n.findIndex(o=>o.listener===t);return i>=0&&n.splice(i,1),this}once(e,t){return(c(this,$,"f")[e]||(c(this,$,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,n)=>{w(this,ue,!0,"f"),e!=="error"&&this.once("error",n),this.once(e,t)})}async done(){w(this,ue,!0,"f"),await c(this,Re,"f")}get currentMessage(){return c(this,N,"f")}async finalMessage(){return await this.done(),c(this,S,"m",Nt).call(this)}async finalText(){return await this.done(),c(this,S,"m",Tr).call(this)}_emit(e,...t){if(c(this,Oe,"f"))return;e==="end"&&(w(this,Oe,!0,"f"),c(this,at,"f").call(this));let n=c(this,$,"f")[e];if(n&&(c(this,$,"f")[e]=n.filter(i=>!i.once),n.forEach(({listener:i})=>i(...t))),e==="abort"){let i=t[0];!c(this,ue,"f")&&!n?.length&&Promise.reject(i),c(this,je,"f").call(this,i),c(this,Le,"f").call(this,i),this._emit("end");return}if(e==="error"){let i=t[0];!c(this,ue,"f")&&!n?.length&&Promise.reject(i),c(this,je,"f").call(this,i),c(this,Le,"f").call(this,i),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",c(this,S,"m",Nt).call(this))}async _fromReadableStream(e,t){let n=t?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),c(this,S,"m",Bt).call(this),this._connected(null);let i=M.fromReadableStream(e,this.controller);for await(let o of i)c(this,S,"m",Ut).call(this,o);if(i.controller.signal?.aborted)throw new y;c(this,S,"m",Ft).call(this)}[(N=new WeakMap,$e=new WeakMap,ot=new WeakMap,je=new WeakMap,Re=new WeakMap,at=new WeakMap,Le=new WeakMap,$=new WeakMap,Oe=new WeakMap,st=new WeakMap,lt=new WeakMap,ue=new WeakMap,ut=new WeakMap,ct=new WeakMap,Dt=new WeakMap,S=new WeakSet,Nt=function(){if(this.receivedMessages.length===0)throw new l("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},Tr=function(){if(this.receivedMessages.length===0)throw new l("stream ended without producing a Message with role=assistant");let t=this.receivedMessages.at(-1).content.filter(n=>n.type==="text").map(n=>n.text);if(t.length===0)throw new l("stream ended without producing a content block with type=text");return t.join(" ")},Bt=function(){this.ended||w(this,N,void 0,"f")},Ut=function(t){if(this.ended)return;let n=c(this,S,"m",Pr).call(this,t);switch(this._emit("streamEvent",t,n),t.type){case"content_block_delta":{let i=n.content.at(-1);switch(t.delta.type){case"text_delta":{i.type==="text"&&this._emit("text",t.delta.text,i.text||"");break}case"citations_delta":{i.type==="text"&&this._emit("citation",t.delta.citation,i.citations??[]);break}case"input_json_delta":{i.type==="tool_use"&&i.input&&this._emit("inputJson",t.delta.partial_json,i.input);break}case"thinking_delta":{i.type==="thinking"&&this._emit("thinking",t.delta.thinking,i.thinking);break}case"signature_delta":{i.type==="thinking"&&this._emit("signature",i.signature);break}default:t.delta}break}case"message_stop":{this._addMessageParam(n),this._addMessage(n,!0);break}case"content_block_stop":{this._emit("contentBlock",n.content.at(-1));break}case"message_start":{w(this,N,n,"f");break}case"content_block_start":case"message_delta":break}},Ft=function(){if(this.ended)throw new l("stream has ended, this shouldn't happen");let t=c(this,N,"f");if(!t)throw new l("request ended without sending any chunks");return w(this,N,void 0,"f"),t},Pr=function(t){let n=c(this,N,"f");if(t.type==="message_start"){if(n)throw new l(`Unexpected event order, got ${t.type} before receiving "message_stop"`);return t.message}if(!n)throw new l(`Unexpected event order, got ${t.type} before "message_start"`);switch(t.type){case"message_stop":return n;case"message_delta":return n.stop_reason=t.delta.stop_reason,n.stop_sequence=t.delta.stop_sequence,n.usage.output_tokens=t.usage.output_tokens,n;case"content_block_start":return n.content.push(t.content_block),n;case"content_block_delta":{let i=n.content.at(t.index);switch(t.delta.type){case"text_delta":{i?.type==="text"&&(i.text+=t.delta.text);break}case"citations_delta":{i?.type==="text"&&(i.citations??(i.citations=[]),i.citations.push(t.delta.citation));break}case"input_json_delta":{if(i?.type==="tool_use"){let o=i[$r]||"";o+=t.delta.partial_json,Object.defineProperty(i,$r,{value:o,enumerable:!1,writable:!0}),o&&(i.input=Je(o))}break}case"thinking_delta":{i?.type==="thinking"&&(i.thinking+=t.delta.thinking);break}case"signature_delta":{i?.type==="thinking"&&(i.signature=t.delta.signature);break}default:t.delta}return n}case"content_block_stop":return n}},Symbol.asyncIterator)](){let e=[],t=[],n=!1;return this.on("streamEvent",i=>{let o=t.shift();o?o.resolve(i):e.push(i)}),this.on("end",()=>{n=!0;for(let i of t)i.resolve(void 0);t.length=0}),this.on("abort",i=>{n=!0;for(let o of t)o.reject(i);t.length=0}),this.on("error",i=>{n=!0;for(let o of t)o.reject(i);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((o,a)=>t.push({resolve:o,reject:a})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new M(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};var j=class extends m{constructor(){super(...arguments),this.batches=new W(this._client)}create(e,t){return e.model in jr&&console.warn(`The model '${e.model}' is deprecated and will reach end-of-life on ${jr[e.model]}
|
|
68
|
+
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),this._client.post("/v1/messages",{body:e,timeout:this._client._options.timeout??(e.stream?6e5:this._client._calculateNonstreamingTimeout(e.max_tokens)),...t,stream:e.stream??!1})}stream(e,t){return dt.createMessage(this,e,t)}countTokens(e,t){return this._client.post("/v1/messages/count_tokens",{body:e,...t})}},jr={"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-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025"};j.Batches=W;j.MessageBatchesPage=le;var D=class extends m{retrieve(e,t){return this._client.get(`/v1/models/${e}`,t)}list(e={},t){return _(e)?this.list({},e):this._client.getAPIList("/v1/models",H,{query:e,...t})}},H=class extends I{};D.ModelInfosPage=H;var Rr,d=class extends Ke{constructor({baseURL:e=Ye("ANTHROPIC_BASE_URL"),apiKey:t=Ye("ANTHROPIC_API_KEY")??null,authToken:n=Ye("ANTHROPIC_AUTH_TOKEN")??null,...i}={}){let o={apiKey:t,authToken:n,...i,baseURL:e||"https://api.anthropic.com"};if(!o.dangerouslyAllowBrowser&&Sr())throw new l(`It looks like you're running in a browser-like environment.
|
|
69
69
|
|
|
70
70
|
This is disabled by default, as it risks exposing your secret API credentials to attackers.
|
|
71
71
|
If you understand the risks and have appropriate mitigations in place,
|
|
72
72
|
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
|
|
73
73
|
|
|
74
74
|
new Anthropic({ apiKey, dangerouslyAllowBrowser: true });
|
|
75
|
-
`);super({baseURL:o.baseURL,timeout:o.timeout??6e5,httpAgent:o.httpAgent,maxRetries:o.maxRetries,fetch:o.fetch}),this.completions=new
|
|
75
|
+
`);super({baseURL:o.baseURL,timeout:o.timeout??6e5,httpAgent:o.httpAgent,maxRetries:o.maxRetries,fetch:o.fetch}),this.completions=new G(this),this.messages=new j(this),this.models=new D(this),this.beta=new E(this),this._options=o,this.apiKey=t,this.authToken=n}defaultQuery(){return this._options.defaultQuery}defaultHeaders(e){return{...super.defaultHeaders(e),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":"true"}:void 0,"anthropic-version":"2023-06-01",...this._options.defaultHeaders}}validateHeaders(e,t){if(!(this.apiKey&&e["x-api-key"])&&t["x-api-key"]!==null&&!(this.authToken&&e.authorization)&&t.authorization!==null)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')}authHeaders(e){let t=this.apiKeyAuth(e),n=this.bearerAuth(e);return t!=null&&!Me(t)?t:n!=null&&!Me(n)?n:{}}apiKeyAuth(e){return this.apiKey==null?{}:{"X-Api-Key":this.apiKey}}bearerAuth(e){return this.authToken==null?{}:{Authorization:`Bearer ${this.authToken}`}}};Rr=d;d.Anthropic=Rr;d.HUMAN_PROMPT=`
|
|
76
76
|
|
|
77
77
|
Human:`;d.AI_PROMPT=`
|
|
78
78
|
|
|
79
|
-
Assistant:`;d.DEFAULT_TIMEOUT=6e5;d.AnthropicError=l;d.APIError=h;d.APIConnectionError=R;d.APIConnectionTimeoutError=te;d.APIUserAbortError=y;d.NotFoundError=we;d.ConflictError=ke;d.RateLimitError=xe;d.BadRequestError=me;d.AuthenticationError=ye;d.InternalServerError=_e;d.PermissionDeniedError=be;d.UnprocessableEntityError=ve;d.toFile=yr;d.fileFromPath=Fe;d.Completions=
|
|
79
|
+
Assistant:`;d.DEFAULT_TIMEOUT=6e5;d.AnthropicError=l;d.APIError=h;d.APIConnectionError=R;d.APIConnectionTimeoutError=te;d.APIUserAbortError=y;d.NotFoundError=we;d.ConflictError=ke;d.RateLimitError=xe;d.BadRequestError=me;d.AuthenticationError=ye;d.InternalServerError=_e;d.PermissionDeniedError=be;d.UnprocessableEntityError=ve;d.toFile=yr;d.fileFromPath=Fe;d.Completions=G;d.Messages=j;d.Models=D;d.ModelInfosPage=H;d.Beta=E;var{HUMAN_PROMPT:kl,AI_PROMPT:vl}=d,Lr=d;var va={model:"claude-3-7-sonnet-20250219",max_tokens:8192,temperature:.1},Or={headers:{"x-api-key":null,authorization:null}};async function xa(r,e,t,n){let i={};e.model&&(i.model=e.model),e.maxTokens&&(i.max_tokens=e.maxTokens),e.temperature&&(i.temperature=e.temperature);let o=await r.messages.create({...va,...i,stream:!0,messages:[{role:"user",content:[{type:"text",text:t}]}]},{signal:n,...Or,headers:{...Or.headers??{},...e.headers}});async function*a(){try{for await(let s of o)s.type==="content_block_delta"&&s.delta.type==="text_delta"&&(yield s.delta.text)}catch(s){throw console.error("Stream error:",s),s}}return a()}var Nr=xa;function Dr(r){return()=>{let e=null,n=ur({"ly.img.improve":!0,"ly.img.fix":{},"ly.img.shorter":!0,"ly.img.longer":{},"ly.img.changeTone":!0,"ly.img.translate":!0,"ly.img.changeTextTo":{}},r.supportedQuickActions),i={kind:"text",id:"anthropic",name:"Anthropic",initialize:async()=>{e=new Lr({dangerouslyAllowBrowser:!0,baseURL:r.proxyUrl,apiKey:null,authToken:null})},input:{quickActions:{supported:n}},output:{middleware:r.middlewares??r.middleware??[],generate:async({prompt:o,blockId:a},{engine:s,abortSignal:f})=>{if(e==null)throw new Error("Anthropic SDK is not initialized");if(a!=null&&s.block.getType(a)!=="//ly.img.ubq/text")throw new Error("If a block is provided to this generation, it most be a text block");r.debug&&console.log("Sending prompt to Anthropic:",JSON.stringify(o,void 0,2));let g=await Nr(e,{proxyUrl:r.proxyUrl,headers:r.headers,model:r.model??"claude-3-7-sonnet-20250219"},o,f);async function*k(){let x="";for await(let K of g){if(f?.aborted)break;x+=K,yield{kind:"text",text:x}}return{kind:"text",text:x}}return k()}}};return Promise.resolve(i)}}var _a={AnthropicProvider:Dr},Cl=_a;export{Cl as default};
|
|
80
80
|
/*! Bundled license information:
|
|
81
81
|
|
|
82
82
|
lodash-es/lodash.js:
|