@imgly/plugin-ai-text-generation-web 0.1.8 → 0.1.10
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/CHANGELOG.md
CHANGED
|
@@ -1 +1,19 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Changelog - AI Plugins
|
|
2
|
+
|
|
3
|
+
## [Unreleased]
|
|
4
|
+
|
|
5
|
+
## [0.1.10] - 2025-06-20
|
|
6
|
+
|
|
7
|
+
- [all] Fix issue with GPT provider when using text provider
|
|
8
|
+
|
|
9
|
+
## [0.1.9] - 2025-06-05
|
|
10
|
+
|
|
11
|
+
- [all] Add support for custom headers
|
|
12
|
+
|
|
13
|
+
## [0.1.8] - 2025-05-26
|
|
14
|
+
|
|
15
|
+
- [ai-apps] Handle `sceneMode` change in upcoming CE.SDK version 1.52.0
|
|
16
|
+
|
|
17
|
+
## [0.1.0] - 2025-04-17
|
|
18
|
+
|
|
19
|
+
- [all] Initial release
|
|
@@ -1,10 +1,5 @@
|
|
|
1
1
|
import CreativeEditorSDK from '@cesdk/cesdk-js';
|
|
2
|
-
import {
|
|
3
|
-
type ProviderConfiguration = {
|
|
4
|
-
proxyUrl: string;
|
|
5
|
-
debug?: boolean;
|
|
6
|
-
middleware?: Middleware<AnthropicInput, AnthropicOutput>[];
|
|
7
|
-
};
|
|
2
|
+
import { Provider, type CommonProviderConfiguration } from '@imgly/plugin-ai-generation-web';
|
|
8
3
|
type AnthropicInput = {
|
|
9
4
|
prompt: string;
|
|
10
5
|
temperature?: number;
|
|
@@ -16,7 +11,7 @@ type AnthropicOutput = {
|
|
|
16
11
|
kind: 'text';
|
|
17
12
|
text: string;
|
|
18
13
|
};
|
|
19
|
-
export declare function AnthropicProvider(config:
|
|
14
|
+
export declare function AnthropicProvider(config: CommonProviderConfiguration<AnthropicInput, AnthropicOutput>): (context: {
|
|
20
15
|
cesdk: CreativeEditorSDK;
|
|
21
16
|
}) => Promise<Provider<'text', AnthropicInput, AnthropicOutput>>;
|
|
22
17
|
export {};
|
package/dist/anthropic/index.mjs
CHANGED
|
@@ -1,27 +1,27 @@
|
|
|
1
|
-
var L="0.39.0";var xt=!1,D,et,
|
|
1
|
+
var L="0.39.0";var xt=!1,D,et,nr,sr,ir,_t,or,Re,tt,At,rt,ve,St;function kt(r,e={auto:!1}){if(xt)throw new Error(`you must \`import '@anthropic-ai/sdk/shims/${r.kind}'\` before importing anything else from @anthropic-ai/sdk`);if(D)throw new Error(`can't \`import '@anthropic-ai/sdk/shims/${r.kind}'\` after \`import '@anthropic-ai/sdk/shims/${D}'\``);xt=e.auto,D=r.kind,et=r.fetch,nr=r.Request,sr=r.Response,ir=r.Headers,_t=r.FormData,or=r.Blob,Re=r.File,tt=r.ReadableStream,At=r.getMultipartRequestOptions,rt=r.getDefaultAgent,ve=r.fileFromPath,St=r.isFsReadStream}var Te=class{constructor(e){this.body=e}get[Symbol.toStringTag](){return"MultipartBody"}};function Pt({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,s,i;try{t=fetch,n=Request,s=Response,i=Headers}catch(o){throw new Error(`this environment is missing the following Web Fetch API type: ${o.message}. ${e}`)}return{kind:"web",fetch:t,Request:n,Response:s,Headers:i,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(o,a)=>({...a,body:new Te(o)}),getDefaultAgent:o=>{},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:o=>!1}}D||kt(Pt(),{auto:!0});var c=class extends Error{},m=class r extends c{constructor(e,t,n,s){super(`${r.makeMessage(e,t,n)}`),this.status=e,this.headers=s,this.request_id=s?.["request-id"],this.error=t}static makeMessage(e,t,n){let s=t?.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):n;return e&&s?`${e} ${s}`:e?`${e} status code (no body)`:s||"(no status code or body)"}static generate(e,t,n,s){if(!e||!s)return new F({message:n,cause:Ie(t)});let i=t;return e===400?new ie(e,i,n,s):e===401?new oe(e,i,n,s):e===403?new ae(e,i,n,s):e===404?new ce(e,i,n,s):e===409?new le(e,i,n,s):e===422?new ue(e,i,n,s):e===429?new he(e,i,n,s):e>=500?new de(e,i,n,s):new r(e,i,n,s)}},w=class extends m{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},F=class extends m{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},V=class extends F{constructor({message:e}={}){super({message:e??"Request timed out."})}},ie=class extends m{},oe=class extends m{},ae=class extends m{},ce=class extends m{},le=class extends m{},ue=class extends m{},he=class extends m{},de=class extends m{};var Oe=function(r,e,t,n,s){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!s:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?s.call(r,t):s?s.value=t:e.set(r,t),t},H=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)},_,R=class{constructor(){_.set(this,void 0),this.buffer=new Uint8Array,Oe(this,_,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 s=[],i;for(;(i=lr(this.buffer,H(this,_,"f")))!=null;){if(i.carriage&&H(this,_,"f")==null){Oe(this,_,i.index,"f");continue}if(H(this,_,"f")!=null&&(i.index!==H(this,_,"f")+1||i.carriage)){s.push(this.decodeText(this.buffer.slice(0,H(this,_,"f")-1))),this.buffer=this.buffer.slice(H(this,_,"f")),Oe(this,_,null,"f");continue}let o=H(this,_,"f")!==null?i.preceding-1:i.preceding,a=this.decodeText(this.buffer.slice(0,o));s.push(a),this.buffer=this.buffer.slice(i.index),Oe(this,_,null,"f")}return s}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 c(`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 c(`Unexpected: received non-Uint8Array/ArrayBuffer (${e.constructor.name}) in a web platform. Please report this error.`)}throw new c("Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.")}flush(){return this.buffer.length?this.decode(`
|
|
2
2
|
`):[]}};_=new WeakMap;R.NEWLINE_CHARS=new Set([`
|
|
3
|
-
`,"\r"]);R.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function
|
|
4
|
-
`);s.enqueue(a)}catch(i){s.error(i)}},async cancel(){await t.return?.()}})}};async function*
|
|
5
|
-
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],i}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,r,s]=hr(e,":");return s.startsWith(" ")&&(s=s.substring(1)),t==="event"?this.event=s:t==="data"&&this.data.push(s),null}};function hr(n,e){let t=n.indexOf(e);return t!==-1?[n.substring(0,t),e,n.substring(t+e.length)]:[n,"",""]}var dr=n=>n!=null&&typeof n=="object"&&typeof n.url=="string"&&typeof n.blob=="function",fr=n=>n!=null&&typeof n=="object"&&typeof n.name=="string"&&typeof n.lastModified=="number"&&pe(n),pe=n=>n!=null&&typeof n=="object"&&typeof n.size=="number"&&typeof n.type=="string"&&typeof n.text=="function"&&typeof n.slice=="function"&&typeof n.arrayBuffer=="function";async function Mt(n,e,t){if(n=await n,fr(n))return n;if(dr(n)){let s=await n.blob();e||(e=new URL(n.url).pathname.split(/[\\/]/).pop()??"unknown_file");let i=pe(s)?[await s.arrayBuffer()]:[s];return new Re(i,e,t)}let r=await pr(n);if(e||(e=gr(n)??"unknown_file"),!t?.type){let s=r[0]?.type;typeof s=="string"&&(t={...t,type:s})}return new Re(r,e,t)}async function pr(n){let e=[];if(typeof n=="string"||ArrayBuffer.isView(n)||n instanceof ArrayBuffer)e.push(n);else if(pe(n))e.push(await n.arrayBuffer());else if(yr(n))for await(let t of n)e.push(t);else throw new Error(`Unexpected data type: ${typeof n}; constructor: ${n?.constructor?.name}; props: ${mr(n)}`);return e}function mr(n){return`[${Object.getOwnPropertyNames(n).map(t=>`"${t}"`).join(", ")}]`}function gr(n){return it(n.name)||it(n.filename)||it(n.path)?.split(/[\\/]/).pop()}var it=n=>{if(typeof n=="string")return n;if(typeof Buffer<"u"&&n instanceof Buffer)return String(n)},yr=n=>n!=null&&typeof n=="object"&&typeof n[Symbol.asyncIterator]=="function",ot=n=>n&&typeof n=="object"&&n.body&&n[Symbol.toStringTag]==="MultipartBody";var br=function(n,e,t,r,s){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?n!==e||!s:!e.has(n))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?s.call(n,t):s?s.value=t:e.set(n,t),t},xr=function(n,e,t,r){if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?n!==e||!r:!e.has(n))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?r:t==="a"?r.call(n):r?r.value:e.get(n)},Be;async function Ot(n){let{response:e}=n;if(n.options.stream)return Y("response",e.status,e.url,e.headers,e.body),n.options.__streamClass?n.options.__streamClass.fromSSEResponse(e,n.controller):P.fromSSEResponse(e,n.controller);if(e.status===204)return null;if(n.options.__binaryResponse)return e;let t=e.headers.get("content-type");if(t?.includes("application/json")||t?.includes("application/vnd.api+json")){let i=await e.json();return Y("response",e.status,e.url,e.headers,i),Bt(i,e)}let s=await e.text();return Y("response",e.status,e.url,e.headers,s),s}function Bt(n,e){return!n||typeof n!="object"||Array.isArray(n)?n:Object.defineProperty(n,"_request_id",{value:e.headers.get("request-id"),enumerable:!1})}var Fe=class n extends Promise{constructor(e,t=Ot){super(r=>{r(null)}),this.responsePromise=e,this.parseResponse=t}_thenUnwrap(e){return new n(this.responsePromise,async t=>Bt(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)}},qe=class{constructor({baseURL:e,maxRetries:t=2,timeout:r=6e5,httpAgent:s,fetch:i}){this.baseURL=e,this.maxRetries=at("maxRetries",t),this.timeout=at("timeout",r),this.httpAgent=s,this.fetch=i??et}authHeaders(e){return{}}defaultHeaders(e){return{Accept:"application/json","Content-Type":"application/json","User-Agent":this.getUserAgent(),...kr(),...this.authHeaders(e)}}validateHeaders(e,t){}defaultIdempotencyKey(){return`stainless-node-retry-${vr()}`}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,r){return this.request(Promise.resolve(r).then(async s=>{let i=s&&pe(s?.body)?new DataView(await s.body.arrayBuffer()):s?.body instanceof DataView?s.body:s?.body instanceof ArrayBuffer?new DataView(s.body):s&&ArrayBuffer.isView(s?.body)?new DataView(s.body.buffer):s?.body;return{method:e,path:t,...s,body:i}}))}getAPIList(e,t,r){return this.requestAPIList(t,{method:"get",path:e,...r})}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:r,path:s,query:i,headers:o={}}=e,a=ArrayBuffer.isView(e.body)||e.__binaryRequest&&typeof e.body=="string"?e.body:ot(e.body)?e.body.body:e.body?JSON.stringify(e.body,null,2):null,d=this.calculateContentLength(a),h=this.buildURL(s,i);"timeout"in e&&at("timeout",e.timeout),e.timeout=e.timeout??this.timeout;let p=e.httpAgent??this.httpAgent??rt(h),y=e.timeout+1e3;typeof p?.options?.timeout=="number"&&y>(p.options.timeout??0)&&(p.options.timeout=y),this.idempotencyHeader&&r!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),o[this.idempotencyHeader]=e.idempotencyKey);let O=this.buildHeaders({options:e,headers:o,contentLength:d,retryCount:t});return{req:{method:r,...a&&{body:a},headers:O,...p&&{agent:p},signal:e.signal??null},url:h,timeout:e.timeout}}buildHeaders({options:e,headers:t,contentLength:r,retryCount:s}){let i={};r&&(i["content-length"]=r);let o=this.defaultHeaders(e);return It(i,o),It(i,t),ot(e.body)&&D!=="node"&&delete i["content-type"],Ce(o,"x-stainless-retry-count")===void 0&&Ce(t,"x-stainless-retry-count")===void 0&&(i["x-stainless-retry-count"]=String(s)),Ce(o,"x-stainless-timeout")===void 0&&Ce(t,"x-stainless-timeout")===void 0&&e.timeout&&(i["x-stainless-timeout"]=String(e.timeout)),this.validateHeaders(i,t),i}_calculateNonstreamingTimeout(e){if(3600*e/128e3>600)throw new c("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:r}){}parseHeaders(e){return e?Symbol.iterator in e?Object.fromEntries(Array.from(e).map(t=>[...t])):{...e}:{}}makeStatusError(e,t,r,s){return m.generate(e,t,r,s)}request(e,t=null){return new Fe(this.makeRequest(e,t))}async makeRequest(e,t){let r=await e,s=r.maxRetries??this.maxRetries;t==null&&(t=s),await this.prepareOptions(r);let{req:i,url:o,timeout:a}=this.buildRequest(r,{retryCount:s-t});if(await this.prepareRequest(i,{url:o,options:r}),Y("request",o,r,i.headers),r.signal?.aborted)throw new w;let d=new AbortController,h=await this.fetchWithTimeout(o,i,a,d).catch(Ie);if(h instanceof Error){if(r.signal?.aborted)throw new w;if(t)return this.retryRequest(r,t);throw h.name==="AbortError"?new V:new F({cause:h})}let p=st(h.headers);if(!h.ok){if(t&&this.shouldRetry(h)){let G=`retrying, ${t} attempts remaining`;return Y(`response (error; ${G})`,h.status,o,p),this.retryRequest(r,t,p)}let y=await h.text().catch(G=>Ie(G).message),O=Pr(y),B=O?void 0:y;throw Y(`response (error; ${t?"(error; no more retries left)":"(error; not retryable)"})`,h.status,o,p,B),this.makeStatusError(h.status,O,B,p)}return{response:h,options:r,controller:d}}requestAPIList(e,t){let r=this.makeRequest(t,null);return new ct(this,r,e)}buildURL(e,t){let r=Mr(e)?new URL(e):new URL(this.baseURL+(this.baseURL.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),s=this.defaultQuery();return me(s)||(t={...s,...t}),typeof t=="object"&&t&&!Array.isArray(t)&&(r.search=this.stringifyQuery(t)),r.toString()}stringifyQuery(e){return Object.entries(e).filter(([t,r])=>typeof r<"u").map(([t,r])=>{if(typeof r=="string"||typeof r=="number"||typeof r=="boolean")return`${encodeURIComponent(t)}=${encodeURIComponent(r)}`;if(r===null)return`${encodeURIComponent(t)}=`;throw new c(`Cannot stringify type ${typeof r}; 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,r,s){let{signal:i,...o}=t||{};i&&i.addEventListener("abort",()=>s.abort());let a=setTimeout(()=>s.abort(),r),d={signal:s.signal,...o};d.method&&(d.method=d.method.toUpperCase());let h=60*1e3,p=setTimeout(()=>{if(d&&d?.agent?.sockets)for(let y of Object.values(d?.agent?.sockets).flat())y?.setKeepAlive&&y.setKeepAlive(!0,h)},h);return this.fetch.call(void 0,e,d).finally(()=>{clearTimeout(a),clearTimeout(p)})}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,r){let s,i=r?.["retry-after-ms"];if(i){let a=parseFloat(i);Number.isNaN(a)||(s=a)}let o=r?.["retry-after"];if(o&&!s){let a=parseFloat(o);Number.isNaN(a)?s=Date.parse(o)-Date.now():s=a*1e3}if(!(s&&0<=s&&s<60*1e3)){let a=e.maxRetries??this.maxRetries;s=this.calculateDefaultRetryTimeoutMillis(t,a)}return await Rr(s),this.makeRequest(e,t-1)}calculateDefaultRetryTimeoutMillis(e,t){let i=t-e,o=Math.min(.5*Math.pow(2,i),8),a=1-Math.random()*.25;return o*a*1e3}getUserAgent(){return`${this.constructor.name}/JS ${L}`}},$e=class{constructor(e,t,r,s){Be.set(this,void 0),br(this,Be,e,"f"),this.options=s,this.response=t,this.body=r}hasNextPage(){return this.getPaginatedItems().length?this.nextPageInfo()!=null:!1}async getNextPage(){let e=this.nextPageInfo();if(!e)throw new c("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 r=[...Object.entries(t.query||{}),...e.url.searchParams.entries()];for(let[s,i]of r)e.url.searchParams.set(s,i);t.query=void 0,t.path=e.url.toString()}return await xr(this,Be,"f").requestAPIList(this.constructor,t)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(Be=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}},ct=class extends Fe{constructor(e,t,r){super(t,async s=>new r(e,s.response,await Ot(s),s.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}},st=n=>new Proxy(Object.fromEntries(n.entries()),{get(e,t){let r=t.toString();return e[r.toLowerCase()]||e[r]}}),_r={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},A=n=>typeof n=="object"&&n!==null&&!me(n)&&Object.keys(n).every(e=>Ct(_r,e)),Ar=()=>{if(typeof Deno<"u"&&Deno.build!=null)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":L,"X-Stainless-OS":vt(Deno.build.os),"X-Stainless-Arch":Rt(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":L,"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":L,"X-Stainless-OS":vt(process.platform),"X-Stainless-Arch":Rt(process.arch),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":process.version};let n=Sr();return n?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":L,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${n.browser}`,"X-Stainless-Runtime-Version":n.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":L,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function Sr(){if(typeof navigator>"u"||!navigator)return null;let n=[{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 n){let r=t.exec(navigator.userAgent);if(r){let s=r[1]||0,i=r[2]||0,o=r[3]||0;return{browser:e,version:`${s}.${i}.${o}`}}}return null}var Rt=n=>n==="x32"?"x32":n==="x86_64"||n==="x64"?"x64":n==="arm"?"arm":n==="aarch64"||n==="arm64"?"arm64":n?`other:${n}`:"unknown",vt=n=>(n=n.toLowerCase(),n.includes("ios")?"iOS":n==="android"?"Android":n==="darwin"?"MacOS":n==="win32"?"Windows":n==="freebsd"?"FreeBSD":n==="openbsd"?"OpenBSD":n==="linux"?"Linux":n?`Other:${n}`:"Unknown"),Tt,kr=()=>Tt??(Tt=Ar()),Pr=n=>{try{return JSON.parse(n)}catch{return}},Er=/^[a-z][a-z0-9+.-]*:/i,Mr=n=>Er.test(n),Rr=n=>new Promise(e=>setTimeout(e,n)),at=(n,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new c(`${n} must be an integer`);if(e<0)throw new c(`${n} must be a positive integer`);return e},Ie=n=>{if(n instanceof Error)return n;if(typeof n=="object"&&n!==null)try{return new Error(JSON.stringify(n))}catch{}return new Error(String(n))};var je=n=>{if(typeof process<"u")return process.env?.[n]?.trim()??void 0;if(typeof Deno<"u")return Deno.env?.get?.(n)?.trim()};function me(n){if(!n)return!0;for(let e in n)return!1;return!0}function Ct(n,e){return Object.prototype.hasOwnProperty.call(n,e)}function It(n,e){for(let t in e){if(!Ct(e,t))continue;let r=t.toLowerCase();if(!r)continue;let s=e[t];s===null?delete n[r]:s!==void 0&&(n[r]=s)}}function Y(n,...e){typeof process<"u"&&process?.env?.DEBUG==="true"&&console.log(`Anthropic:DEBUG:${n}`,...e)}var vr=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,n=>{let e=Math.random()*16|0;return(n==="x"?e:e&3|8).toString(16)}),Ft=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u",Tr=n=>typeof n?.get=="function";var Ce=(n,e)=>{let t=e.toLowerCase();if(Tr(n)){let r=e[0]?.toUpperCase()+e.substring(1).replace(/([^\w])(\w)/g,(s,i,o)=>i+o.toUpperCase());for(let s of[e,t,e.toUpperCase(),r]){let i=n.get(s);if(i)return i}}for(let[r,s]of Object.entries(n))if(r.toLowerCase()===t)return Array.isArray(s)?(s.length<=1||console.warn(`Received ${s.length} entries for the ${e} header, using the first entry.`),s[0]):s};var E=class extends $e{constructor(e,t,r,s){super(e,t,r,s),this.data=r.data||[],this.has_more=r.has_more||!1,this.first_id=r.first_id||null,this.last_id=r.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 g=class{constructor(e){this._client=e}};var W=class extends g{retrieve(e,t){return this._client.get(`/v1/models/${e}?beta=true`,t)}list(e={},t){return A(e)?this.list({},e):this._client.getAPIList("/v1/models?beta=true",z,{query:e,...t})}},z=class extends E{};W.BetaModelInfosPage=z;var Z=class n{constructor(e,t){this.iterator=e,this.controller=t}async*decoder(){let e=new R;for await(let t of this.iterator)for(let r of e.decode(t))yield JSON.parse(r);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 c("Attempted to iterate over a response with no body");return new n(fe(e.body),t)}};var Q=class extends g{create(e,t){let{betas:r,...s}=e;return this._client.post("/v1/messages/batches?beta=true",{body:s,...t,headers:{"anthropic-beta":[...r??[],"message-batches-2024-09-24"].toString(),...t?.headers}})}retrieve(e,t={},r){if(A(t))return this.retrieve(e,{},t);let{betas:s}=t;return this._client.get(`/v1/messages/batches/${e}?beta=true`,{...r,headers:{"anthropic-beta":[...s??[],"message-batches-2024-09-24"].toString(),...r?.headers}})}list(e={},t){if(A(e))return this.list({},e);let{betas:r,...s}=e;return this._client.getAPIList("/v1/messages/batches?beta=true",ee,{query:s,...t,headers:{"anthropic-beta":[...r??[],"message-batches-2024-09-24"].toString(),...t?.headers}})}delete(e,t={},r){if(A(t))return this.delete(e,{},t);let{betas:s}=t;return this._client.delete(`/v1/messages/batches/${e}?beta=true`,{...r,headers:{"anthropic-beta":[...s??[],"message-batches-2024-09-24"].toString(),...r?.headers}})}cancel(e,t={},r){if(A(t))return this.cancel(e,{},t);let{betas:s}=t;return this._client.post(`/v1/messages/batches/${e}/cancel?beta=true`,{...r,headers:{"anthropic-beta":[...s??[],"message-batches-2024-09-24"].toString(),...r?.headers}})}async results(e,t={},r){if(A(t))return this.results(e,{},t);let s=await this.retrieve(e);if(!s.results_url)throw new c(`No batch \`results_url\`; Has it finished processing? ${s.processing_status} - ${s.id}`);let{betas:i}=t;return this._client.get(s.results_url,{...r,headers:{"anthropic-beta":[...i??[],"message-batches-2024-09-24"].toString(),Accept:"application/binary",...r?.headers},__binaryResponse:!0})._thenUnwrap((o,a)=>Z.fromResponse(a.response,a.controller))}},ee=class extends E{};Q.BetaMessageBatchesPage=ee;var Cr=n=>{let e=0,t=[];for(;e<n.length;){let r=n[e];if(r==="\\"){e++;continue}if(r==="{"){t.push({type:"brace",value:"{"}),e++;continue}if(r==="}"){t.push({type:"brace",value:"}"}),e++;continue}if(r==="["){t.push({type:"paren",value:"["}),e++;continue}if(r==="]"){t.push({type:"paren",value:"]"}),e++;continue}if(r===":"){t.push({type:"separator",value:":"}),e++;continue}if(r===","){t.push({type:"delimiter",value:","}),e++;continue}if(r==='"'){let a="",d=!1;for(r=n[++e];r!=='"';){if(e===n.length){d=!0;break}if(r==="\\"){if(e++,e===n.length){d=!0;break}a+=r+n[e],r=n[++e]}else a+=r,r=n[++e]}r=n[++e],d||t.push({type:"string",value:a});continue}if(r&&/\s/.test(r)){e++;continue}let i=/[0-9]/;if(r&&i.test(r)||r==="-"||r==="."){let a="";for(r==="-"&&(a+=r,r=n[++e]);r&&i.test(r)||r===".";)a+=r,r=n[++e];t.push({type:"number",value:a});continue}let o=/[a-z]/i;if(r&&o.test(r)){let a="";for(;r&&o.test(r)&&e!==n.length;)a+=r,r=n[++e];if(a=="true"||a=="false"||a==="null")t.push({type:"name",value:a});else{e++;continue}continue}e++}return t},te=n=>{if(n.length===0)return n;let e=n[n.length-1];switch(e.type){case"separator":return n=n.slice(0,n.length-1),te(n);break;case"number":let t=e.value[e.value.length-1];if(t==="."||t==="-")return n=n.slice(0,n.length-1),te(n);case"string":let r=n[n.length-2];if(r?.type==="delimiter")return n=n.slice(0,n.length-1),te(n);if(r?.type==="brace"&&r.value==="{")return n=n.slice(0,n.length-1),te(n);break;case"delimiter":return n=n.slice(0,n.length-1),te(n);break}return n},Fr=n=>{let e=[];return n.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==="}"?n.push({type:"brace",value:"}"}):t==="]"&&n.push({type:"paren",value:"]"})}),n},qr=n=>{let e="";return n.map(t=>{switch(t.type){case"string":e+='"'+t.value+'"';break;default:e+=t.value;break}}),e},Ue=n=>JSON.parse(qr(Fr(te(Cr(n)))));var b=function(n,e,t,r,s){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?n!==e||!s:!e.has(n))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?s.call(n,t):s?s.value=t:e.set(n,t),t},l=function(n,e,t,r){if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?n!==e||!r:!e.has(n))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?r:t==="a"?r.call(n):r?r.value:e.get(n)},S,q,ge,Ne,ye,we,Le,be,v,xe,De,He,re,We,Qe,lt,qt,ut,ht,dt,ft,$t,jt="__json_buf",Xe=class n{constructor(){S.add(this),this.messages=[],this.receivedMessages=[],q.set(this,void 0),this.controller=new AbortController,ge.set(this,void 0),Ne.set(this,()=>{}),ye.set(this,()=>{}),we.set(this,void 0),Le.set(this,()=>{}),be.set(this,()=>{}),v.set(this,{}),xe.set(this,!1),De.set(this,!1),He.set(this,!1),re.set(this,!1),We.set(this,void 0),Qe.set(this,void 0),ut.set(this,e=>{if(b(this,De,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new w),e instanceof w)return b(this,He,!0,"f"),this._emit("abort",e);if(e instanceof c)return this._emit("error",e);if(e instanceof Error){let t=new c(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new c(String(e)))}),b(this,ge,new Promise((e,t)=>{b(this,Ne,e,"f"),b(this,ye,t,"f")}),"f"),b(this,we,new Promise((e,t)=>{b(this,Le,e,"f"),b(this,be,t,"f")}),"f"),l(this,ge,"f").catch(()=>{}),l(this,we,"f").catch(()=>{})}get response(){return l(this,We,"f")}get request_id(){return l(this,Qe,"f")}async withResponse(){let e=await l(this,ge,"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 n;return t._run(()=>t._fromReadableStream(e)),t}static createMessage(e,t,r){let s=new n;for(let i of t.messages)s._addMessageParam(i);return s._run(()=>s._createMessage(e,{...t,stream:!0},{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),s}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},l(this,ut,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,t=!0){this.receivedMessages.push(e),t&&this._emit("message",e)}async _createMessage(e,t,r){let s=r?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),l(this,S,"m",ht).call(this);let{response:i,data:o}=await e.create({...t,stream:!0},{...r,signal:this.controller.signal}).withResponse();this._connected(i);for await(let a of o)l(this,S,"m",dt).call(this,a);if(o.controller.signal?.aborted)throw new w;l(this,S,"m",ft).call(this)}_connected(e){this.ended||(b(this,We,e,"f"),b(this,Qe,e?.headers.get("request-id"),"f"),l(this,Ne,"f").call(this,e),this._emit("connect"))}get ended(){return l(this,xe,"f")}get errored(){return l(this,De,"f")}get aborted(){return l(this,He,"f")}abort(){this.controller.abort()}on(e,t){return(l(this,v,"f")[e]||(l(this,v,"f")[e]=[])).push({listener:t}),this}off(e,t){let r=l(this,v,"f")[e];if(!r)return this;let s=r.findIndex(i=>i.listener===t);return s>=0&&r.splice(s,1),this}once(e,t){return(l(this,v,"f")[e]||(l(this,v,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,r)=>{b(this,re,!0,"f"),e!=="error"&&this.once("error",r),this.once(e,t)})}async done(){b(this,re,!0,"f"),await l(this,we,"f")}get currentMessage(){return l(this,q,"f")}async finalMessage(){return await this.done(),l(this,S,"m",lt).call(this)}async finalText(){return await this.done(),l(this,S,"m",qt).call(this)}_emit(e,...t){if(l(this,xe,"f"))return;e==="end"&&(b(this,xe,!0,"f"),l(this,Le,"f").call(this));let r=l(this,v,"f")[e];if(r&&(l(this,v,"f")[e]=r.filter(s=>!s.once),r.forEach(({listener:s})=>s(...t))),e==="abort"){let s=t[0];!l(this,re,"f")&&!r?.length&&Promise.reject(s),l(this,ye,"f").call(this,s),l(this,be,"f").call(this,s),this._emit("end");return}if(e==="error"){let s=t[0];!l(this,re,"f")&&!r?.length&&Promise.reject(s),l(this,ye,"f").call(this,s),l(this,be,"f").call(this,s),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",l(this,S,"m",lt).call(this))}async _fromReadableStream(e,t){let r=t?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),l(this,S,"m",ht).call(this),this._connected(null);let s=P.fromReadableStream(e,this.controller);for await(let i of s)l(this,S,"m",dt).call(this,i);if(s.controller.signal?.aborted)throw new w;l(this,S,"m",ft).call(this)}[(q=new WeakMap,ge=new WeakMap,Ne=new WeakMap,ye=new WeakMap,we=new WeakMap,Le=new WeakMap,be=new WeakMap,v=new WeakMap,xe=new WeakMap,De=new WeakMap,He=new WeakMap,re=new WeakMap,We=new WeakMap,Qe=new WeakMap,ut=new WeakMap,S=new WeakSet,lt=function(){if(this.receivedMessages.length===0)throw new c("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},qt=function(){if(this.receivedMessages.length===0)throw new c("stream ended without producing a Message with role=assistant");let t=this.receivedMessages.at(-1).content.filter(r=>r.type==="text").map(r=>r.text);if(t.length===0)throw new c("stream ended without producing a content block with type=text");return t.join(" ")},ht=function(){this.ended||b(this,q,void 0,"f")},dt=function(t){if(this.ended)return;let r=l(this,S,"m",$t).call(this,t);switch(this._emit("streamEvent",t,r),t.type){case"content_block_delta":{let s=r.content.at(-1);switch(t.delta.type){case"text_delta":{s.type==="text"&&this._emit("text",t.delta.text,s.text||"");break}case"citations_delta":{s.type==="text"&&this._emit("citation",t.delta.citation,s.citations??[]);break}case"input_json_delta":{s.type==="tool_use"&&s.input&&this._emit("inputJson",t.delta.partial_json,s.input);break}case"thinking_delta":{s.type==="thinking"&&this._emit("thinking",t.delta.thinking,s.thinking);break}case"signature_delta":{s.type==="thinking"&&this._emit("signature",s.signature);break}default:t.delta}break}case"message_stop":{this._addMessageParam(r),this._addMessage(r,!0);break}case"content_block_stop":{this._emit("contentBlock",r.content.at(-1));break}case"message_start":{b(this,q,r,"f");break}case"content_block_start":case"message_delta":break}},ft=function(){if(this.ended)throw new c("stream has ended, this shouldn't happen");let t=l(this,q,"f");if(!t)throw new c("request ended without sending any chunks");return b(this,q,void 0,"f"),t},$t=function(t){let r=l(this,q,"f");if(t.type==="message_start"){if(r)throw new c(`Unexpected event order, got ${t.type} before receiving "message_stop"`);return t.message}if(!r)throw new c(`Unexpected event order, got ${t.type} before "message_start"`);switch(t.type){case"message_stop":return r;case"message_delta":return r.stop_reason=t.delta.stop_reason,r.stop_sequence=t.delta.stop_sequence,r.usage.output_tokens=t.usage.output_tokens,r;case"content_block_start":return r.content.push(t.content_block),r;case"content_block_delta":{let s=r.content.at(t.index);switch(t.delta.type){case"text_delta":{s?.type==="text"&&(s.text+=t.delta.text);break}case"citations_delta":{s?.type==="text"&&(s.citations??(s.citations=[]),s.citations.push(t.delta.citation));break}case"input_json_delta":{if(s?.type==="tool_use"){let i=s[jt]||"";i+=t.delta.partial_json,Object.defineProperty(s,jt,{value:i,enumerable:!1,writable:!0}),i&&(s.input=Ue(i))}break}case"thinking_delta":{s?.type==="thinking"&&(s.thinking+=t.delta.thinking);break}case"signature_delta":{s?.type==="thinking"&&(s.signature=t.delta.signature);break}default:t.delta}return r}case"content_block_stop":return r}},Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("streamEvent",s=>{let i=t.shift();i?i.resolve(s):e.push(s)}),this.on("end",()=>{r=!0;for(let s of t)s.resolve(void 0);t.length=0}),this.on("abort",s=>{r=!0;for(let i of t)i.reject(s);t.length=0}),this.on("error",s=>{r=!0;for(let i of t)i.reject(s);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((i,o)=>t.push({resolve:i,reject:o})).then(i=>i?{value:i,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new P(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};var Ut={"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"},$=class extends g{constructor(){super(...arguments),this.batches=new Q(this._client)}create(e,t){let{betas:r,...s}=e;return s.model in Ut&&console.warn(`The model '${s.model}' is deprecated and will reach end-of-life on ${Ut[s.model]}
|
|
6
|
-
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:s,timeout:this._client._options.timeout??(s.stream?6e5:this._client._calculateNonstreamingTimeout(s.max_tokens)),...t,headers:{...r?.toString()!=null?{"anthropic-beta":r?.toString()}:void 0,...t?.headers},stream:e.stream??!1})}stream(e,t){return Xe.createMessage(this,e,t)}countTokens(e,t){let{betas:r,...s}=e;return this._client.post("/v1/messages/count_tokens?beta=true",{body:s,...t,headers:{"anthropic-beta":[...r??[],"token-counting-2024-11-01"].toString(),...t?.headers}})}};$.Batches=Q;$.BetaMessageBatchesPage=ee;var M=class extends g{constructor(){super(...arguments),this.models=new W(this._client),this.messages=new $(this._client)}};M.Models=W;M.BetaModelInfosPage=z;M.Messages=$;var X=class extends g{create(e,t){return this._client.post("/v1/complete",{body:e,timeout:this._client._options.timeout??6e5,...t,stream:e.stream??!1})}};var K=class extends g{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 A(e)?this.list({},e):this._client.getAPIList("/v1/messages/batches",ne,{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 r=await this.retrieve(e);if(!r.results_url)throw new c(`No batch \`results_url\`; Has it finished processing? ${r.processing_status} - ${r.id}`);return this._client.get(r.results_url,{...t,headers:{Accept:"application/binary",...t?.headers},__binaryResponse:!0})._thenUnwrap((s,i)=>Z.fromResponse(i.response,i.controller))}},ne=class extends E{};K.MessageBatchesPage=ne;var x=function(n,e,t,r,s){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?n!==e||!s:!e.has(n))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?s.call(n,t):s?s.value=t:e.set(n,t),t},u=function(n,e,t,r){if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?n!==e||!r:!e.has(n))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?r:t==="a"?r.call(n):r?r.value:e.get(n)},k,j,_e,Ke,Ae,Se,Je,ke,T,Pe,Ge,Ve,se,Ye,ze,pt,Nt,mt,gt,yt,wt,Lt,Dt="__json_buf",Ze=class n{constructor(){k.add(this),this.messages=[],this.receivedMessages=[],j.set(this,void 0),this.controller=new AbortController,_e.set(this,void 0),Ke.set(this,()=>{}),Ae.set(this,()=>{}),Se.set(this,void 0),Je.set(this,()=>{}),ke.set(this,()=>{}),T.set(this,{}),Pe.set(this,!1),Ge.set(this,!1),Ve.set(this,!1),se.set(this,!1),Ye.set(this,void 0),ze.set(this,void 0),mt.set(this,e=>{if(x(this,Ge,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new w),e instanceof w)return x(this,Ve,!0,"f"),this._emit("abort",e);if(e instanceof c)return this._emit("error",e);if(e instanceof Error){let t=new c(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new c(String(e)))}),x(this,_e,new Promise((e,t)=>{x(this,Ke,e,"f"),x(this,Ae,t,"f")}),"f"),x(this,Se,new Promise((e,t)=>{x(this,Je,e,"f"),x(this,ke,t,"f")}),"f"),u(this,_e,"f").catch(()=>{}),u(this,Se,"f").catch(()=>{})}get response(){return u(this,Ye,"f")}get request_id(){return u(this,ze,"f")}async withResponse(){let e=await u(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 n;return t._run(()=>t._fromReadableStream(e)),t}static createMessage(e,t,r){let s=new n;for(let i of t.messages)s._addMessageParam(i);return s._run(()=>s._createMessage(e,{...t,stream:!0},{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),s}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},u(this,mt,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,t=!0){this.receivedMessages.push(e),t&&this._emit("message",e)}async _createMessage(e,t,r){let s=r?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),u(this,k,"m",gt).call(this);let{response:i,data:o}=await e.create({...t,stream:!0},{...r,signal:this.controller.signal}).withResponse();this._connected(i);for await(let a of o)u(this,k,"m",yt).call(this,a);if(o.controller.signal?.aborted)throw new w;u(this,k,"m",wt).call(this)}_connected(e){this.ended||(x(this,Ye,e,"f"),x(this,ze,e?.headers.get("request-id"),"f"),u(this,Ke,"f").call(this,e),this._emit("connect"))}get ended(){return u(this,Pe,"f")}get errored(){return u(this,Ge,"f")}get aborted(){return u(this,Ve,"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 r=u(this,T,"f")[e];if(!r)return this;let s=r.findIndex(i=>i.listener===t);return s>=0&&r.splice(s,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,r)=>{x(this,se,!0,"f"),e!=="error"&&this.once("error",r),this.once(e,t)})}async done(){x(this,se,!0,"f"),await u(this,Se,"f")}get currentMessage(){return u(this,j,"f")}async finalMessage(){return await this.done(),u(this,k,"m",pt).call(this)}async finalText(){return await this.done(),u(this,k,"m",Nt).call(this)}_emit(e,...t){if(u(this,Pe,"f"))return;e==="end"&&(x(this,Pe,!0,"f"),u(this,Je,"f").call(this));let r=u(this,T,"f")[e];if(r&&(u(this,T,"f")[e]=r.filter(s=>!s.once),r.forEach(({listener:s})=>s(...t))),e==="abort"){let s=t[0];!u(this,se,"f")&&!r?.length&&Promise.reject(s),u(this,Ae,"f").call(this,s),u(this,ke,"f").call(this,s),this._emit("end");return}if(e==="error"){let s=t[0];!u(this,se,"f")&&!r?.length&&Promise.reject(s),u(this,Ae,"f").call(this,s),u(this,ke,"f").call(this,s),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",u(this,k,"m",pt).call(this))}async _fromReadableStream(e,t){let r=t?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),u(this,k,"m",gt).call(this),this._connected(null);let s=P.fromReadableStream(e,this.controller);for await(let i of s)u(this,k,"m",yt).call(this,i);if(s.controller.signal?.aborted)throw new w;u(this,k,"m",wt).call(this)}[(j=new WeakMap,_e=new WeakMap,Ke=new WeakMap,Ae=new WeakMap,Se=new WeakMap,Je=new WeakMap,ke=new WeakMap,T=new WeakMap,Pe=new WeakMap,Ge=new WeakMap,Ve=new WeakMap,se=new WeakMap,Ye=new WeakMap,ze=new WeakMap,mt=new WeakMap,k=new WeakSet,pt=function(){if(this.receivedMessages.length===0)throw new c("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},Nt=function(){if(this.receivedMessages.length===0)throw new c("stream ended without producing a Message with role=assistant");let t=this.receivedMessages.at(-1).content.filter(r=>r.type==="text").map(r=>r.text);if(t.length===0)throw new c("stream ended without producing a content block with type=text");return t.join(" ")},gt=function(){this.ended||x(this,j,void 0,"f")},yt=function(t){if(this.ended)return;let r=u(this,k,"m",Lt).call(this,t);switch(this._emit("streamEvent",t,r),t.type){case"content_block_delta":{let s=r.content.at(-1);switch(t.delta.type){case"text_delta":{s.type==="text"&&this._emit("text",t.delta.text,s.text||"");break}case"citations_delta":{s.type==="text"&&this._emit("citation",t.delta.citation,s.citations??[]);break}case"input_json_delta":{s.type==="tool_use"&&s.input&&this._emit("inputJson",t.delta.partial_json,s.input);break}case"thinking_delta":{s.type==="thinking"&&this._emit("thinking",t.delta.thinking,s.thinking);break}case"signature_delta":{s.type==="thinking"&&this._emit("signature",s.signature);break}default:t.delta}break}case"message_stop":{this._addMessageParam(r),this._addMessage(r,!0);break}case"content_block_stop":{this._emit("contentBlock",r.content.at(-1));break}case"message_start":{x(this,j,r,"f");break}case"content_block_start":case"message_delta":break}},wt=function(){if(this.ended)throw new c("stream has ended, this shouldn't happen");let t=u(this,j,"f");if(!t)throw new c("request ended without sending any chunks");return x(this,j,void 0,"f"),t},Lt=function(t){let r=u(this,j,"f");if(t.type==="message_start"){if(r)throw new c(`Unexpected event order, got ${t.type} before receiving "message_stop"`);return t.message}if(!r)throw new c(`Unexpected event order, got ${t.type} before "message_start"`);switch(t.type){case"message_stop":return r;case"message_delta":return r.stop_reason=t.delta.stop_reason,r.stop_sequence=t.delta.stop_sequence,r.usage.output_tokens=t.usage.output_tokens,r;case"content_block_start":return r.content.push(t.content_block),r;case"content_block_delta":{let s=r.content.at(t.index);switch(t.delta.type){case"text_delta":{s?.type==="text"&&(s.text+=t.delta.text);break}case"citations_delta":{s?.type==="text"&&(s.citations??(s.citations=[]),s.citations.push(t.delta.citation));break}case"input_json_delta":{if(s?.type==="tool_use"){let i=s[Dt]||"";i+=t.delta.partial_json,Object.defineProperty(s,Dt,{value:i,enumerable:!1,writable:!0}),i&&(s.input=Ue(i))}break}case"thinking_delta":{s?.type==="thinking"&&(s.thinking+=t.delta.thinking);break}case"signature_delta":{s?.type==="thinking"&&(s.signature=t.delta.signature);break}default:t.delta}return r}case"content_block_stop":return r}},Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("streamEvent",s=>{let i=t.shift();i?i.resolve(s):e.push(s)}),this.on("end",()=>{r=!0;for(let s of t)s.resolve(void 0);t.length=0}),this.on("abort",s=>{r=!0;for(let i of t)i.reject(s);t.length=0}),this.on("error",s=>{r=!0;for(let i of t)i.reject(s);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((i,o)=>t.push({resolve:i,reject:o})).then(i=>i?{value:i,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new P(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};var I=class extends g{constructor(){super(...arguments),this.batches=new K(this._client)}create(e,t){return e.model in Ht&&console.warn(`The model '${e.model}' is deprecated and will reach end-of-life on ${Ht[e.model]}
|
|
7
|
-
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 Ze.createMessage(this,e,t)}countTokens(e,t){return this._client.post("/v1/messages/count_tokens",{body:e,...t})}},Ht={"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"};I.Batches=K;I.MessageBatchesPage=ne;var
|
|
3
|
+
`,"\r"]);R.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function lr(r,e){for(let s=e??0;s<r.length;s++){if(r[s]===10)return{preceding:s,index:s+1,carriage:!1};if(r[s]===13)return{preceding:s,index:s+1,carriage:!0}}return null}function Et(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 fe(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 P=class r{constructor(e,t){this.iterator=e,this.controller=t}static fromSSEResponse(e,t){let n=!1;async function*s(){if(n)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let i=!1;try{for await(let o of ur(e,t)){if(o.event==="completion")try{yield JSON.parse(o.data)}catch(a){throw console.error("Could not parse message into JSON:",o.data),console.error("From chunk:",o.raw),a}if(o.event==="message_start"||o.event==="message_delta"||o.event==="message_stop"||o.event==="content_block_start"||o.event==="content_block_delta"||o.event==="content_block_stop")try{yield JSON.parse(o.data)}catch(a){throw console.error("Could not parse message into JSON:",o.data),console.error("From chunk:",o.raw),a}if(o.event!=="ping"&&o.event==="error")throw m.generate(void 0,`SSE Error: ${o.data}`,o.data,st(e.headers))}i=!0}catch(o){if(o instanceof Error&&o.name==="AbortError")return;throw o}finally{i||t.abort()}}return new r(s,t)}static fromReadableStream(e,t){let n=!1;async function*s(){let o=new R,a=fe(e);for await(let d of a)for(let h of o.decode(d))yield h;for(let d of o.flush())yield d}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 s())o||a&&(yield JSON.parse(a));o=!0}catch(a){if(a instanceof Error&&a.name==="AbortError")return;throw a}finally{o||t.abort()}}return new r(i,t)}[Symbol.asyncIterator](){return this.iterator()}tee(){let e=[],t=[],n=this.iterator(),s=i=>({next:()=>{if(i.length===0){let o=n.next();e.push(o),t.push(o)}return i.shift()}});return[new r(()=>s(e),this.controller),new r(()=>s(t),this.controller)]}toReadableStream(){let e=this,t,n=new TextEncoder;return new tt({async start(){t=e[Symbol.asyncIterator]()},async pull(s){try{let{value:i,done:o}=await t.next();if(o)return s.close();let a=n.encode(JSON.stringify(i)+`
|
|
4
|
+
`);s.enqueue(a)}catch(i){s.error(i)}},async cancel(){await t.return?.()}})}};async function*ur(r,e){if(!r.body)throw e.abort(),new c("Attempted to iterate over a response with no body");let t=new nt,n=new R,s=fe(r.body);for await(let i of hr(s))for(let o of n.decode(i)){let a=t.decode(o);a&&(yield a)}for(let i of n.flush()){let o=t.decode(i);o&&(yield o)}}async function*hr(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,s=new Uint8Array(e.length+n.length);s.set(e),s.set(n,e.length),e=s;let i;for(;(i=Et(e))!==-1;)yield e.slice(0,i),e=e.slice(i)}e.length>0&&(yield e)}var nt=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 i={event:this.event,data:this.data.join(`
|
|
5
|
+
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],i}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,n,s]=dr(e,":");return s.startsWith(" ")&&(s=s.substring(1)),t==="event"?this.event=s:t==="data"&&this.data.push(s),null}};function dr(r,e){let t=r.indexOf(e);return t!==-1?[r.substring(0,t),e,r.substring(t+e.length)]:[r,"",""]}var fr=r=>r!=null&&typeof r=="object"&&typeof r.url=="string"&&typeof r.blob=="function",pr=r=>r!=null&&typeof r=="object"&&typeof r.name=="string"&&typeof r.lastModified=="number"&&pe(r),pe=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 Mt(r,e,t){if(r=await r,pr(r))return r;if(fr(r)){let s=await r.blob();e||(e=new URL(r.url).pathname.split(/[\\/]/).pop()??"unknown_file");let i=pe(s)?[await s.arrayBuffer()]:[s];return new Re(i,e,t)}let n=await mr(r);if(e||(e=yr(r)??"unknown_file"),!t?.type){let s=n[0]?.type;typeof s=="string"&&(t={...t,type:s})}return new Re(n,e,t)}async function mr(r){let e=[];if(typeof r=="string"||ArrayBuffer.isView(r)||r instanceof ArrayBuffer)e.push(r);else if(pe(r))e.push(await r.arrayBuffer());else if(wr(r))for await(let t of r)e.push(t);else throw new Error(`Unexpected data type: ${typeof r}; constructor: ${r?.constructor?.name}; props: ${gr(r)}`);return e}function gr(r){return`[${Object.getOwnPropertyNames(r).map(t=>`"${t}"`).join(", ")}]`}function yr(r){return it(r.name)||it(r.filename)||it(r.path)?.split(/[\\/]/).pop()}var it=r=>{if(typeof r=="string")return r;if(typeof Buffer<"u"&&r instanceof Buffer)return String(r)},wr=r=>r!=null&&typeof r=="object"&&typeof r[Symbol.asyncIterator]=="function",ot=r=>r&&typeof r=="object"&&r.body&&r[Symbol.toStringTag]==="MultipartBody";var xr=function(r,e,t,n,s){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!s:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?s.call(r,t):s?s.value=t:e.set(r,t),t},_r=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)},Be;async function Ot(r){let{response:e}=r;if(r.options.stream)return Y("response",e.status,e.url,e.headers,e.body),r.options.__streamClass?r.options.__streamClass.fromSSEResponse(e,r.controller):P.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 i=await e.json();return Y("response",e.status,e.url,e.headers,i),Bt(i,e)}let s=await e.text();return Y("response",e.status,e.url,e.headers,s),s}function Bt(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 Fe=class r extends Promise{constructor(e,t=Ot){super(n=>{n(null)}),this.responsePromise=e,this.parseResponse=t}_thenUnwrap(e){return new r(this.responsePromise,async t=>Bt(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)}},qe=class{constructor({baseURL:e,maxRetries:t=2,timeout:n=6e5,httpAgent:s,fetch:i}){this.baseURL=e,this.maxRetries=at("maxRetries",t),this.timeout=at("timeout",n),this.httpAgent=s,this.fetch=i??et}authHeaders(e){return{}}defaultHeaders(e){return{Accept:"application/json","Content-Type":"application/json","User-Agent":this.getUserAgent(),...Pr(),...this.authHeaders(e)}}validateHeaders(e,t){}defaultIdempotencyKey(){return`stainless-node-retry-${Tr()}`}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 s=>{let i=s&&pe(s?.body)?new DataView(await s.body.arrayBuffer()):s?.body instanceof DataView?s.body:s?.body instanceof ArrayBuffer?new DataView(s.body):s&&ArrayBuffer.isView(s?.body)?new DataView(s.body.buffer):s?.body;return{method:e,path:t,...s,body:i}}))}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:s,query:i,headers:o={}}=e,a=ArrayBuffer.isView(e.body)||e.__binaryRequest&&typeof e.body=="string"?e.body:ot(e.body)?e.body.body:e.body?JSON.stringify(e.body,null,2):null,d=this.calculateContentLength(a),h=this.buildURL(s,i);"timeout"in e&&at("timeout",e.timeout),e.timeout=e.timeout??this.timeout;let p=e.httpAgent??this.httpAgent??rt(h),y=e.timeout+1e3;typeof p?.options?.timeout=="number"&&y>(p.options.timeout??0)&&(p.options.timeout=y),this.idempotencyHeader&&n!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),o[this.idempotencyHeader]=e.idempotencyKey);let O=this.buildHeaders({options:e,headers:o,contentLength:d,retryCount:t});return{req:{method:n,...a&&{body:a},headers:O,...p&&{agent:p},signal:e.signal??null},url:h,timeout:e.timeout}}buildHeaders({options:e,headers:t,contentLength:n,retryCount:s}){let i={};n&&(i["content-length"]=n);let o=this.defaultHeaders(e);return It(i,o),It(i,t),ot(e.body)&&D!=="node"&&delete i["content-type"],Ce(o,"x-stainless-retry-count")===void 0&&Ce(t,"x-stainless-retry-count")===void 0&&(i["x-stainless-retry-count"]=String(s)),Ce(o,"x-stainless-timeout")===void 0&&Ce(t,"x-stainless-timeout")===void 0&&e.timeout&&(i["x-stainless-timeout"]=String(e.timeout)),this.validateHeaders(i,t),i}_calculateNonstreamingTimeout(e){if(3600*e/128e3>600)throw new c("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,s){return m.generate(e,t,n,s)}request(e,t=null){return new Fe(this.makeRequest(e,t))}async makeRequest(e,t){let n=await e,s=n.maxRetries??this.maxRetries;t==null&&(t=s),await this.prepareOptions(n);let{req:i,url:o,timeout:a}=this.buildRequest(n,{retryCount:s-t});if(await this.prepareRequest(i,{url:o,options:n}),Y("request",o,n,i.headers),n.signal?.aborted)throw new w;let d=new AbortController,h=await this.fetchWithTimeout(o,i,a,d).catch(Ie);if(h instanceof Error){if(n.signal?.aborted)throw new w;if(t)return this.retryRequest(n,t);throw h.name==="AbortError"?new V:new F({cause:h})}let p=st(h.headers);if(!h.ok){if(t&&this.shouldRetry(h)){let G=`retrying, ${t} attempts remaining`;return Y(`response (error; ${G})`,h.status,o,p),this.retryRequest(n,t,p)}let y=await h.text().catch(G=>Ie(G).message),O=Er(y),B=O?void 0:y;throw Y(`response (error; ${t?"(error; no more retries left)":"(error; not retryable)"})`,h.status,o,p,B),this.makeStatusError(h.status,O,B,p)}return{response:h,options:n,controller:d}}requestAPIList(e,t){let n=this.makeRequest(t,null);return new ct(this,n,e)}buildURL(e,t){let n=Rr(e)?new URL(e):new URL(this.baseURL+(this.baseURL.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),s=this.defaultQuery();return me(s)||(t={...s,...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 c(`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,s){let{signal:i,...o}=t||{};i&&i.addEventListener("abort",()=>s.abort());let a=setTimeout(()=>s.abort(),n),d={signal:s.signal,...o};d.method&&(d.method=d.method.toUpperCase());let h=60*1e3,p=setTimeout(()=>{if(d&&d?.agent?.sockets)for(let y of Object.values(d?.agent?.sockets).flat())y?.setKeepAlive&&y.setKeepAlive(!0,h)},h);return this.fetch.call(void 0,e,d).finally(()=>{clearTimeout(a),clearTimeout(p)})}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 s,i=n?.["retry-after-ms"];if(i){let a=parseFloat(i);Number.isNaN(a)||(s=a)}let o=n?.["retry-after"];if(o&&!s){let a=parseFloat(o);Number.isNaN(a)?s=Date.parse(o)-Date.now():s=a*1e3}if(!(s&&0<=s&&s<60*1e3)){let a=e.maxRetries??this.maxRetries;s=this.calculateDefaultRetryTimeoutMillis(t,a)}return await vr(s),this.makeRequest(e,t-1)}calculateDefaultRetryTimeoutMillis(e,t){let i=t-e,o=Math.min(.5*Math.pow(2,i),8),a=1-Math.random()*.25;return o*a*1e3}getUserAgent(){return`${this.constructor.name}/JS ${L}`}},$e=class{constructor(e,t,n,s){Be.set(this,void 0),xr(this,Be,e,"f"),this.options=s,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 c("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[s,i]of n)e.url.searchParams.set(s,i);t.query=void 0,t.path=e.url.toString()}return await _r(this,Be,"f").requestAPIList(this.constructor,t)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(Be=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}},ct=class extends Fe{constructor(e,t,n){super(t,async s=>new n(e,s.response,await Ot(s),s.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}},st=r=>new Proxy(Object.fromEntries(r.entries()),{get(e,t){let n=t.toString();return e[n.toLowerCase()]||e[n]}}),Ar={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},A=r=>typeof r=="object"&&r!==null&&!me(r)&&Object.keys(r).every(e=>Ct(Ar,e)),Sr=()=>{if(typeof Deno<"u"&&Deno.build!=null)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":L,"X-Stainless-OS":vt(Deno.build.os),"X-Stainless-Arch":Rt(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":L,"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":L,"X-Stainless-OS":vt(process.platform),"X-Stainless-Arch":Rt(process.arch),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":process.version};let r=kr();return r?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":L,"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":L,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function kr(){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 s=n[1]||0,i=n[2]||0,o=n[3]||0;return{browser:e,version:`${s}.${i}.${o}`}}}return null}var Rt=r=>r==="x32"?"x32":r==="x86_64"||r==="x64"?"x64":r==="arm"?"arm":r==="aarch64"||r==="arm64"?"arm64":r?`other:${r}`:"unknown",vt=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"),Tt,Pr=()=>Tt??(Tt=Sr()),Er=r=>{try{return JSON.parse(r)}catch{return}},Mr=/^[a-z][a-z0-9+.-]*:/i,Rr=r=>Mr.test(r),vr=r=>new Promise(e=>setTimeout(e,r)),at=(r,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new c(`${r} must be an integer`);if(e<0)throw new c(`${r} must be a positive integer`);return e},Ie=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 je=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 Ct(r,e){return Object.prototype.hasOwnProperty.call(r,e)}function It(r,e){for(let t in e){if(!Ct(e,t))continue;let n=t.toLowerCase();if(!n)continue;let s=e[t];s===null?delete r[n]:s!==void 0&&(r[n]=s)}}function Y(r,...e){typeof process<"u"&&process?.env?.DEBUG==="true"&&console.log(`Anthropic:DEBUG:${r}`,...e)}var Tr=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,r=>{let e=Math.random()*16|0;return(r==="x"?e:e&3|8).toString(16)}),Ft=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u",Ir=r=>typeof r?.get=="function";var Ce=(r,e)=>{let t=e.toLowerCase();if(Ir(r)){let n=e[0]?.toUpperCase()+e.substring(1).replace(/([^\w])(\w)/g,(s,i,o)=>i+o.toUpperCase());for(let s of[e,t,e.toUpperCase(),n]){let i=r.get(s);if(i)return i}}for(let[n,s]of Object.entries(r))if(n.toLowerCase()===t)return Array.isArray(s)?(s.length<=1||console.warn(`Received ${s.length} entries for the ${e} header, using the first entry.`),s[0]):s};var E=class extends $e{constructor(e,t,n,s){super(e,t,n,s),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 g=class{constructor(e){this._client=e}};var W=class extends g{retrieve(e,t){return this._client.get(`/v1/models/${e}?beta=true`,t)}list(e={},t){return A(e)?this.list({},e):this._client.getAPIList("/v1/models?beta=true",z,{query:e,...t})}},z=class extends E{};W.BetaModelInfosPage=z;var Z=class r{constructor(e,t){this.iterator=e,this.controller=t}async*decoder(){let e=new R;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 c("Attempted to iterate over a response with no body");return new r(fe(e.body),t)}};var Q=class extends g{create(e,t){let{betas:n,...s}=e;return this._client.post("/v1/messages/batches?beta=true",{body:s,...t,headers:{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString(),...t?.headers}})}retrieve(e,t={},n){if(A(t))return this.retrieve(e,{},t);let{betas:s}=t;return this._client.get(`/v1/messages/batches/${e}?beta=true`,{...n,headers:{"anthropic-beta":[...s??[],"message-batches-2024-09-24"].toString(),...n?.headers}})}list(e={},t){if(A(e))return this.list({},e);let{betas:n,...s}=e;return this._client.getAPIList("/v1/messages/batches?beta=true",ee,{query:s,...t,headers:{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString(),...t?.headers}})}delete(e,t={},n){if(A(t))return this.delete(e,{},t);let{betas:s}=t;return this._client.delete(`/v1/messages/batches/${e}?beta=true`,{...n,headers:{"anthropic-beta":[...s??[],"message-batches-2024-09-24"].toString(),...n?.headers}})}cancel(e,t={},n){if(A(t))return this.cancel(e,{},t);let{betas:s}=t;return this._client.post(`/v1/messages/batches/${e}/cancel?beta=true`,{...n,headers:{"anthropic-beta":[...s??[],"message-batches-2024-09-24"].toString(),...n?.headers}})}async results(e,t={},n){if(A(t))return this.results(e,{},t);let s=await this.retrieve(e);if(!s.results_url)throw new c(`No batch \`results_url\`; Has it finished processing? ${s.processing_status} - ${s.id}`);let{betas:i}=t;return this._client.get(s.results_url,{...n,headers:{"anthropic-beta":[...i??[],"message-batches-2024-09-24"].toString(),Accept:"application/binary",...n?.headers},__binaryResponse:!0})._thenUnwrap((o,a)=>Z.fromResponse(a.response,a.controller))}},ee=class extends E{};Q.BetaMessageBatchesPage=ee;var Fr=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 a="",d=!1;for(n=r[++e];n!=='"';){if(e===r.length){d=!0;break}if(n==="\\"){if(e++,e===r.length){d=!0;break}a+=n+r[e],n=r[++e]}else a+=n,n=r[++e]}n=r[++e],d||t.push({type:"string",value:a});continue}if(n&&/\s/.test(n)){e++;continue}let i=/[0-9]/;if(n&&i.test(n)||n==="-"||n==="."){let a="";for(n==="-"&&(a+=n,n=r[++e]);n&&i.test(n)||n===".";)a+=n,n=r[++e];t.push({type:"number",value:a});continue}let o=/[a-z]/i;if(n&&o.test(n)){let a="";for(;n&&o.test(n)&&e!==r.length;)a+=n,n=r[++e];if(a=="true"||a=="false"||a==="null")t.push({type:"name",value:a});else{e++;continue}continue}e++}return t},te=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),te(r);break;case"number":let t=e.value[e.value.length-1];if(t==="."||t==="-")return r=r.slice(0,r.length-1),te(r);case"string":let n=r[r.length-2];if(n?.type==="delimiter")return r=r.slice(0,r.length-1),te(r);if(n?.type==="brace"&&n.value==="{")return r=r.slice(0,r.length-1),te(r);break;case"delimiter":return r=r.slice(0,r.length-1),te(r);break}return r},qr=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},$r=r=>{let e="";return r.map(t=>{switch(t.type){case"string":e+='"'+t.value+'"';break;default:e+=t.value;break}}),e},Ne=r=>JSON.parse($r(qr(te(Fr(r)))));var b=function(r,e,t,n,s){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!s:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?s.call(r,t):s?s.value=t:e.set(r,t),t},l=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,q,ge,Ue,ye,we,Le,be,v,xe,De,He,re,We,Qe,lt,qt,ut,ht,dt,ft,$t,jt="__json_buf",Xe=class r{constructor(){S.add(this),this.messages=[],this.receivedMessages=[],q.set(this,void 0),this.controller=new AbortController,ge.set(this,void 0),Ue.set(this,()=>{}),ye.set(this,()=>{}),we.set(this,void 0),Le.set(this,()=>{}),be.set(this,()=>{}),v.set(this,{}),xe.set(this,!1),De.set(this,!1),He.set(this,!1),re.set(this,!1),We.set(this,void 0),Qe.set(this,void 0),ut.set(this,e=>{if(b(this,De,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new w),e instanceof w)return b(this,He,!0,"f"),this._emit("abort",e);if(e instanceof c)return this._emit("error",e);if(e instanceof Error){let t=new c(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new c(String(e)))}),b(this,ge,new Promise((e,t)=>{b(this,Ue,e,"f"),b(this,ye,t,"f")}),"f"),b(this,we,new Promise((e,t)=>{b(this,Le,e,"f"),b(this,be,t,"f")}),"f"),l(this,ge,"f").catch(()=>{}),l(this,we,"f").catch(()=>{})}get response(){return l(this,We,"f")}get request_id(){return l(this,Qe,"f")}async withResponse(){let e=await l(this,ge,"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 s=new r;for(let i of t.messages)s._addMessageParam(i);return s._run(()=>s._createMessage(e,{...t,stream:!0},{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),s}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},l(this,ut,"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 s=n?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),l(this,S,"m",ht).call(this);let{response:i,data:o}=await e.create({...t,stream:!0},{...n,signal:this.controller.signal}).withResponse();this._connected(i);for await(let a of o)l(this,S,"m",dt).call(this,a);if(o.controller.signal?.aborted)throw new w;l(this,S,"m",ft).call(this)}_connected(e){this.ended||(b(this,We,e,"f"),b(this,Qe,e?.headers.get("request-id"),"f"),l(this,Ue,"f").call(this,e),this._emit("connect"))}get ended(){return l(this,xe,"f")}get errored(){return l(this,De,"f")}get aborted(){return l(this,He,"f")}abort(){this.controller.abort()}on(e,t){return(l(this,v,"f")[e]||(l(this,v,"f")[e]=[])).push({listener:t}),this}off(e,t){let n=l(this,v,"f")[e];if(!n)return this;let s=n.findIndex(i=>i.listener===t);return s>=0&&n.splice(s,1),this}once(e,t){return(l(this,v,"f")[e]||(l(this,v,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,n)=>{b(this,re,!0,"f"),e!=="error"&&this.once("error",n),this.once(e,t)})}async done(){b(this,re,!0,"f"),await l(this,we,"f")}get currentMessage(){return l(this,q,"f")}async finalMessage(){return await this.done(),l(this,S,"m",lt).call(this)}async finalText(){return await this.done(),l(this,S,"m",qt).call(this)}_emit(e,...t){if(l(this,xe,"f"))return;e==="end"&&(b(this,xe,!0,"f"),l(this,Le,"f").call(this));let n=l(this,v,"f")[e];if(n&&(l(this,v,"f")[e]=n.filter(s=>!s.once),n.forEach(({listener:s})=>s(...t))),e==="abort"){let s=t[0];!l(this,re,"f")&&!n?.length&&Promise.reject(s),l(this,ye,"f").call(this,s),l(this,be,"f").call(this,s),this._emit("end");return}if(e==="error"){let s=t[0];!l(this,re,"f")&&!n?.length&&Promise.reject(s),l(this,ye,"f").call(this,s),l(this,be,"f").call(this,s),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",l(this,S,"m",lt).call(this))}async _fromReadableStream(e,t){let n=t?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),l(this,S,"m",ht).call(this),this._connected(null);let s=P.fromReadableStream(e,this.controller);for await(let i of s)l(this,S,"m",dt).call(this,i);if(s.controller.signal?.aborted)throw new w;l(this,S,"m",ft).call(this)}[(q=new WeakMap,ge=new WeakMap,Ue=new WeakMap,ye=new WeakMap,we=new WeakMap,Le=new WeakMap,be=new WeakMap,v=new WeakMap,xe=new WeakMap,De=new WeakMap,He=new WeakMap,re=new WeakMap,We=new WeakMap,Qe=new WeakMap,ut=new WeakMap,S=new WeakSet,lt=function(){if(this.receivedMessages.length===0)throw new c("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},qt=function(){if(this.receivedMessages.length===0)throw new c("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 c("stream ended without producing a content block with type=text");return t.join(" ")},ht=function(){this.ended||b(this,q,void 0,"f")},dt=function(t){if(this.ended)return;let n=l(this,S,"m",$t).call(this,t);switch(this._emit("streamEvent",t,n),t.type){case"content_block_delta":{let s=n.content.at(-1);switch(t.delta.type){case"text_delta":{s.type==="text"&&this._emit("text",t.delta.text,s.text||"");break}case"citations_delta":{s.type==="text"&&this._emit("citation",t.delta.citation,s.citations??[]);break}case"input_json_delta":{s.type==="tool_use"&&s.input&&this._emit("inputJson",t.delta.partial_json,s.input);break}case"thinking_delta":{s.type==="thinking"&&this._emit("thinking",t.delta.thinking,s.thinking);break}case"signature_delta":{s.type==="thinking"&&this._emit("signature",s.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,q,n,"f");break}case"content_block_start":case"message_delta":break}},ft=function(){if(this.ended)throw new c("stream has ended, this shouldn't happen");let t=l(this,q,"f");if(!t)throw new c("request ended without sending any chunks");return b(this,q,void 0,"f"),t},$t=function(t){let n=l(this,q,"f");if(t.type==="message_start"){if(n)throw new c(`Unexpected event order, got ${t.type} before receiving "message_stop"`);return t.message}if(!n)throw new c(`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 s=n.content.at(t.index);switch(t.delta.type){case"text_delta":{s?.type==="text"&&(s.text+=t.delta.text);break}case"citations_delta":{s?.type==="text"&&(s.citations??(s.citations=[]),s.citations.push(t.delta.citation));break}case"input_json_delta":{if(s?.type==="tool_use"){let i=s[jt]||"";i+=t.delta.partial_json,Object.defineProperty(s,jt,{value:i,enumerable:!1,writable:!0}),i&&(s.input=Ne(i))}break}case"thinking_delta":{s?.type==="thinking"&&(s.thinking+=t.delta.thinking);break}case"signature_delta":{s?.type==="thinking"&&(s.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",s=>{let i=t.shift();i?i.resolve(s):e.push(s)}),this.on("end",()=>{n=!0;for(let s of t)s.resolve(void 0);t.length=0}),this.on("abort",s=>{n=!0;for(let i of t)i.reject(s);t.length=0}),this.on("error",s=>{n=!0;for(let i of t)i.reject(s);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((i,o)=>t.push({resolve:i,reject:o})).then(i=>i?{value:i,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new P(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};var Nt={"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"},$=class extends g{constructor(){super(...arguments),this.batches=new Q(this._client)}create(e,t){let{betas:n,...s}=e;return s.model in Nt&&console.warn(`The model '${s.model}' is deprecated and will reach end-of-life on ${Nt[s.model]}
|
|
6
|
+
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:s,timeout:this._client._options.timeout??(s.stream?6e5:this._client._calculateNonstreamingTimeout(s.max_tokens)),...t,headers:{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0,...t?.headers},stream:e.stream??!1})}stream(e,t){return Xe.createMessage(this,e,t)}countTokens(e,t){let{betas:n,...s}=e;return this._client.post("/v1/messages/count_tokens?beta=true",{body:s,...t,headers:{"anthropic-beta":[...n??[],"token-counting-2024-11-01"].toString(),...t?.headers}})}};$.Batches=Q;$.BetaMessageBatchesPage=ee;var M=class extends g{constructor(){super(...arguments),this.models=new W(this._client),this.messages=new $(this._client)}};M.Models=W;M.BetaModelInfosPage=z;M.Messages=$;var X=class extends g{create(e,t){return this._client.post("/v1/complete",{body:e,timeout:this._client._options.timeout??6e5,...t,stream:e.stream??!1})}};var K=class extends g{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 A(e)?this.list({},e):this._client.getAPIList("/v1/messages/batches",ne,{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 c(`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((s,i)=>Z.fromResponse(i.response,i.controller))}},ne=class extends E{};K.MessageBatchesPage=ne;var x=function(r,e,t,n,s){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!s:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?s.call(r,t):s?s.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)},k,j,_e,Ke,Ae,Se,Je,ke,T,Pe,Ge,Ve,se,Ye,ze,pt,Ut,mt,gt,yt,wt,Lt,Dt="__json_buf",Ze=class r{constructor(){k.add(this),this.messages=[],this.receivedMessages=[],j.set(this,void 0),this.controller=new AbortController,_e.set(this,void 0),Ke.set(this,()=>{}),Ae.set(this,()=>{}),Se.set(this,void 0),Je.set(this,()=>{}),ke.set(this,()=>{}),T.set(this,{}),Pe.set(this,!1),Ge.set(this,!1),Ve.set(this,!1),se.set(this,!1),Ye.set(this,void 0),ze.set(this,void 0),mt.set(this,e=>{if(x(this,Ge,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new w),e instanceof w)return x(this,Ve,!0,"f"),this._emit("abort",e);if(e instanceof c)return this._emit("error",e);if(e instanceof Error){let t=new c(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new c(String(e)))}),x(this,_e,new Promise((e,t)=>{x(this,Ke,e,"f"),x(this,Ae,t,"f")}),"f"),x(this,Se,new Promise((e,t)=>{x(this,Je,e,"f"),x(this,ke,t,"f")}),"f"),u(this,_e,"f").catch(()=>{}),u(this,Se,"f").catch(()=>{})}get response(){return u(this,Ye,"f")}get request_id(){return u(this,ze,"f")}async withResponse(){let e=await u(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 s=new r;for(let i of t.messages)s._addMessageParam(i);return s._run(()=>s._createMessage(e,{...t,stream:!0},{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),s}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},u(this,mt,"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 s=n?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),u(this,k,"m",gt).call(this);let{response:i,data:o}=await e.create({...t,stream:!0},{...n,signal:this.controller.signal}).withResponse();this._connected(i);for await(let a of o)u(this,k,"m",yt).call(this,a);if(o.controller.signal?.aborted)throw new w;u(this,k,"m",wt).call(this)}_connected(e){this.ended||(x(this,Ye,e,"f"),x(this,ze,e?.headers.get("request-id"),"f"),u(this,Ke,"f").call(this,e),this._emit("connect"))}get ended(){return u(this,Pe,"f")}get errored(){return u(this,Ge,"f")}get aborted(){return u(this,Ve,"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 n=u(this,T,"f")[e];if(!n)return this;let s=n.findIndex(i=>i.listener===t);return s>=0&&n.splice(s,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,n)=>{x(this,se,!0,"f"),e!=="error"&&this.once("error",n),this.once(e,t)})}async done(){x(this,se,!0,"f"),await u(this,Se,"f")}get currentMessage(){return u(this,j,"f")}async finalMessage(){return await this.done(),u(this,k,"m",pt).call(this)}async finalText(){return await this.done(),u(this,k,"m",Ut).call(this)}_emit(e,...t){if(u(this,Pe,"f"))return;e==="end"&&(x(this,Pe,!0,"f"),u(this,Je,"f").call(this));let n=u(this,T,"f")[e];if(n&&(u(this,T,"f")[e]=n.filter(s=>!s.once),n.forEach(({listener:s})=>s(...t))),e==="abort"){let s=t[0];!u(this,se,"f")&&!n?.length&&Promise.reject(s),u(this,Ae,"f").call(this,s),u(this,ke,"f").call(this,s),this._emit("end");return}if(e==="error"){let s=t[0];!u(this,se,"f")&&!n?.length&&Promise.reject(s),u(this,Ae,"f").call(this,s),u(this,ke,"f").call(this,s),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",u(this,k,"m",pt).call(this))}async _fromReadableStream(e,t){let n=t?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),u(this,k,"m",gt).call(this),this._connected(null);let s=P.fromReadableStream(e,this.controller);for await(let i of s)u(this,k,"m",yt).call(this,i);if(s.controller.signal?.aborted)throw new w;u(this,k,"m",wt).call(this)}[(j=new WeakMap,_e=new WeakMap,Ke=new WeakMap,Ae=new WeakMap,Se=new WeakMap,Je=new WeakMap,ke=new WeakMap,T=new WeakMap,Pe=new WeakMap,Ge=new WeakMap,Ve=new WeakMap,se=new WeakMap,Ye=new WeakMap,ze=new WeakMap,mt=new WeakMap,k=new WeakSet,pt=function(){if(this.receivedMessages.length===0)throw new c("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},Ut=function(){if(this.receivedMessages.length===0)throw new c("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 c("stream ended without producing a content block with type=text");return t.join(" ")},gt=function(){this.ended||x(this,j,void 0,"f")},yt=function(t){if(this.ended)return;let n=u(this,k,"m",Lt).call(this,t);switch(this._emit("streamEvent",t,n),t.type){case"content_block_delta":{let s=n.content.at(-1);switch(t.delta.type){case"text_delta":{s.type==="text"&&this._emit("text",t.delta.text,s.text||"");break}case"citations_delta":{s.type==="text"&&this._emit("citation",t.delta.citation,s.citations??[]);break}case"input_json_delta":{s.type==="tool_use"&&s.input&&this._emit("inputJson",t.delta.partial_json,s.input);break}case"thinking_delta":{s.type==="thinking"&&this._emit("thinking",t.delta.thinking,s.thinking);break}case"signature_delta":{s.type==="thinking"&&this._emit("signature",s.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":{x(this,j,n,"f");break}case"content_block_start":case"message_delta":break}},wt=function(){if(this.ended)throw new c("stream has ended, this shouldn't happen");let t=u(this,j,"f");if(!t)throw new c("request ended without sending any chunks");return x(this,j,void 0,"f"),t},Lt=function(t){let n=u(this,j,"f");if(t.type==="message_start"){if(n)throw new c(`Unexpected event order, got ${t.type} before receiving "message_stop"`);return t.message}if(!n)throw new c(`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 s=n.content.at(t.index);switch(t.delta.type){case"text_delta":{s?.type==="text"&&(s.text+=t.delta.text);break}case"citations_delta":{s?.type==="text"&&(s.citations??(s.citations=[]),s.citations.push(t.delta.citation));break}case"input_json_delta":{if(s?.type==="tool_use"){let i=s[Dt]||"";i+=t.delta.partial_json,Object.defineProperty(s,Dt,{value:i,enumerable:!1,writable:!0}),i&&(s.input=Ne(i))}break}case"thinking_delta":{s?.type==="thinking"&&(s.thinking+=t.delta.thinking);break}case"signature_delta":{s?.type==="thinking"&&(s.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",s=>{let i=t.shift();i?i.resolve(s):e.push(s)}),this.on("end",()=>{n=!0;for(let s of t)s.resolve(void 0);t.length=0}),this.on("abort",s=>{n=!0;for(let i of t)i.reject(s);t.length=0}),this.on("error",s=>{n=!0;for(let i of t)i.reject(s);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((i,o)=>t.push({resolve:i,reject:o})).then(i=>i?{value:i,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new P(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};var I=class extends g{constructor(){super(...arguments),this.batches=new K(this._client)}create(e,t){return e.model in Ht&&console.warn(`The model '${e.model}' is deprecated and will reach end-of-life on ${Ht[e.model]}
|
|
7
|
+
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 Ze.createMessage(this,e,t)}countTokens(e,t){return this._client.post("/v1/messages/count_tokens",{body:e,...t})}},Ht={"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"};I.Batches=K;I.MessageBatchesPage=ne;var N=class extends g{retrieve(e,t){return this._client.get(`/v1/models/${e}`,t)}list(e={},t){return A(e)?this.list({},e):this._client.getAPIList("/v1/models",J,{query:e,...t})}},J=class extends E{};N.ModelInfosPage=J;var Wt,f=class extends qe{constructor({baseURL:e=je("ANTHROPIC_BASE_URL"),apiKey:t=je("ANTHROPIC_API_KEY")??null,authToken:n=je("ANTHROPIC_AUTH_TOKEN")??null,...s}={}){let i={apiKey:t,authToken:n,...s,baseURL:e||"https://api.anthropic.com"};if(!i.dangerouslyAllowBrowser&&Ft())throw new c(`It looks like you're running in a browser-like environment.
|
|
8
8
|
|
|
9
9
|
This is disabled by default, as it risks exposing your secret API credentials to attackers.
|
|
10
10
|
If you understand the risks and have appropriate mitigations in place,
|
|
11
11
|
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
|
|
12
12
|
|
|
13
13
|
new Anthropic({ apiKey, dangerouslyAllowBrowser: true });
|
|
14
|
-
`);super({baseURL:i.baseURL,timeout:i.timeout??6e5,httpAgent:i.httpAgent,maxRetries:i.maxRetries,fetch:i.fetch}),this.completions=new X(this),this.messages=new I(this),this.models=new
|
|
14
|
+
`);super({baseURL:i.baseURL,timeout:i.timeout??6e5,httpAgent:i.httpAgent,maxRetries:i.maxRetries,fetch:i.fetch}),this.completions=new X(this),this.messages=new I(this),this.models=new N(this),this.beta=new M(this),this._options=i,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}`}}};Wt=f;f.Anthropic=Wt;f.HUMAN_PROMPT=`
|
|
15
15
|
|
|
16
16
|
Human:`;f.AI_PROMPT=`
|
|
17
17
|
|
|
18
|
-
Assistant:`;f.DEFAULT_TIMEOUT=6e5;f.AnthropicError=c;f.APIError=m;f.APIConnectionError=F;f.APIConnectionTimeoutError=V;f.APIUserAbortError=w;f.NotFoundError=ce;f.ConflictError=le;f.RateLimitError=he;f.BadRequestError=ie;f.AuthenticationError=oe;f.InternalServerError=de;f.PermissionDeniedError=ae;f.UnprocessableEntityError=ue;f.toFile=Mt;f.fileFromPath=ve;f.Completions=X;f.Messages=I;f.Models=
|
|
18
|
+
Assistant:`;f.DEFAULT_TIMEOUT=6e5;f.AnthropicError=c;f.APIError=m;f.APIConnectionError=F;f.APIConnectionTimeoutError=V;f.APIUserAbortError=w;f.NotFoundError=ce;f.ConflictError=le;f.RateLimitError=he;f.BadRequestError=ie;f.AuthenticationError=oe;f.InternalServerError=de;f.PermissionDeniedError=ae;f.UnprocessableEntityError=ue;f.toFile=Mt;f.fileFromPath=ve;f.Completions=X;f.Messages=I;f.Models=N;f.ModelInfosPage=J;f.Beta=M;var{HUMAN_PROMPT:Ns,AI_PROMPT:Us}=f,Qt=f;var Lr={model:"claude-3-7-sonnet-20250219",max_tokens:8192,temperature:.1},Xt={headers:{"x-api-key":null,authorization:null}};async function Dr(r,e,t,n){let s={};e.model&&(s.model=e.model),e.maxTokens&&(s.max_tokens=e.maxTokens),e.temperature&&(s.temperature=e.temperature);let i=await r.messages.create({...Lr,...s,stream:!0,messages:[{role:"user",content:[{type:"text",text:t}]}]},{signal:n,...Xt,headers:{...Xt.headers??{},...e.headers}});async function*o(){try{for await(let a of i)a.type==="content_block_delta"&&a.delta.type==="text_delta"&&(yield a.delta.text)}catch(a){throw console.error("Stream error:",a),a}}return o()}var Kt=Dr;function Hr(r){return`
|
|
19
19
|
You are an AI writing assistant tasked with improving a given text based on a specific type of improvement requested. Your goal is to enhance the text while maintaining its original meaning and intent.
|
|
20
20
|
|
|
21
21
|
Here is the original text you will be working with:
|
|
22
22
|
|
|
23
23
|
<original_text>
|
|
24
|
-
${
|
|
24
|
+
${r}
|
|
25
25
|
</original_text>
|
|
26
26
|
|
|
27
27
|
Please follow these steps to improve the text:
|
|
@@ -39,13 +39,13 @@ Please follow these steps to improve the text:
|
|
|
39
39
|
7. If you cannot make any meaningful improvements, return the original text as is.
|
|
40
40
|
|
|
41
41
|
Once you have made the improvements, only return the improved text and nothing else.
|
|
42
|
-
`}var
|
|
42
|
+
`}var Jt=Hr;function Wr(r){return`
|
|
43
43
|
You will be given a text to shorten. Your task is to reduce the length of the text by 30% to 50% while maintaining its original voice, perspective, and key information. This is not a summary - you should preserve the style and tone of the original text.
|
|
44
44
|
|
|
45
45
|
Here is the original text:
|
|
46
46
|
|
|
47
47
|
<original_text>
|
|
48
|
-
${
|
|
48
|
+
${r}
|
|
49
49
|
</original_text>
|
|
50
50
|
|
|
51
51
|
To complete this task, follow these steps:
|
|
@@ -70,13 +70,13 @@ To complete this task, follow these steps:
|
|
|
70
70
|
6. Once you've finished shortening, review the text to ensure it still reads smoothly and retains the essence of the original.
|
|
71
71
|
|
|
72
72
|
Provide only the shortened version of the text in your response, without any additional comments, tags or explanations.
|
|
73
|
-
`}var
|
|
73
|
+
`}var Gt=Wr;function Qr(r){return`
|
|
74
74
|
You are tasked with expanding a given text to make it longer. Here's how to proceed:
|
|
75
75
|
|
|
76
76
|
First, you will be provided with the original text:
|
|
77
77
|
|
|
78
78
|
<original_text>
|
|
79
|
-
${
|
|
79
|
+
${r}
|
|
80
80
|
</original_text>
|
|
81
81
|
|
|
82
82
|
To expand the text:
|
|
@@ -104,11 +104,11 @@ Only return the longer text and nothing else.
|
|
|
104
104
|
Make sure to only return the expanded text and nothing else. Do not include any additional information or comments in your response about what you have done.
|
|
105
105
|
|
|
106
106
|
Do not add the original text or the original_text tags to the response.
|
|
107
|
-
`}var
|
|
107
|
+
`}var Vt=Qr;function Xr(r){return`
|
|
108
108
|
You are tasked with fixing spelling and grammar errors in a given text. Your goal is to improve the text while maintaining its original meaning and style. Here is the text you need to correct:
|
|
109
109
|
|
|
110
110
|
<original_text>
|
|
111
|
-
${
|
|
111
|
+
${r}
|
|
112
112
|
</original_text>
|
|
113
113
|
|
|
114
114
|
Please follow these steps to complete the task:
|
|
@@ -134,7 +134,7 @@ Please follow these steps to complete the task:
|
|
|
134
134
|
After making the necessary corrections, please provide only the improved output and nothing else.
|
|
135
135
|
|
|
136
136
|
Remember to preserve the original structure and formatting of the text as much as possible while making your corrections.
|
|
137
|
-
`}var
|
|
137
|
+
`}var Yt=Xr;function Kr(r){return`
|
|
138
138
|
Your task is to create a new text based on a given prompt. The text should be short enough that it can be read aloud in no more than 5 seconds.
|
|
139
139
|
|
|
140
140
|
Follow these guidelines when generating the text:
|
|
@@ -146,16 +146,16 @@ Follow these guidelines when generating the text:
|
|
|
146
146
|
|
|
147
147
|
Here is the prompt to base your text on:
|
|
148
148
|
<prompt>
|
|
149
|
-
${
|
|
149
|
+
${r}
|
|
150
150
|
</prompt>
|
|
151
151
|
|
|
152
152
|
Generate a short text based on this prompt. Output only the generated text, without any additional explanation or commentary. Do not include any XML tags in your response.
|
|
153
|
-
`}var
|
|
153
|
+
`}var zt=Kr;var Ee={en_US:"English (US)",en_UK:"English (UK)",es:"Spanish",fr:"French",de:"German",pt:"Portuguese",it:"Italian",ru:"Russian",zh:"Mandarin Chinese",ja:"Japanese"},Zt=Object.keys(Ee);function Jr(r,e){let t=Ee[e]||e;return`
|
|
154
154
|
You are a translation AI. Your task is to translate the given text into the specified target language. Follow these steps:
|
|
155
155
|
|
|
156
156
|
1. Here is the source text to be translated:
|
|
157
157
|
<source_text>
|
|
158
|
-
${
|
|
158
|
+
${r}
|
|
159
159
|
</source_text>
|
|
160
160
|
|
|
161
161
|
2. The target language for translation is:
|
|
@@ -166,12 +166,12 @@ ${t}
|
|
|
166
166
|
3. Translate the source text into the target language. Ensure that you maintain the original meaning, tone, and style as closely as possible while adapting to the linguistic and cultural norms of the target language.
|
|
167
167
|
|
|
168
168
|
4. Return only the translated text, without any additional comments, explanations, or metadata. Do not include the original text or any other information in your response.
|
|
169
|
-
`}var
|
|
169
|
+
`}var er=Jr;function Gr(r,e){return`
|
|
170
170
|
You will be given a piece of text and a desired tone. Your task is to rewrite the text to match the desired tone while preserving the original meaning and key information. Here's how to proceed:
|
|
171
171
|
|
|
172
172
|
First, you will be provided with the original text:
|
|
173
173
|
<original_text>
|
|
174
|
-
${
|
|
174
|
+
${r}
|
|
175
175
|
</original_text>
|
|
176
176
|
|
|
177
177
|
The desired tone for the rewritten text is:
|
|
@@ -188,12 +188,12 @@ To change the tone of the text:
|
|
|
188
188
|
6. Only return the rewritten text without any additional commentary, tags or explanation.
|
|
189
189
|
|
|
190
190
|
Now, rewrite the text to match the desired tone. Your response should contain only the rewritten text, without any additional explanations or comments. Do not use any tags in your response.
|
|
191
|
-
`}var
|
|
191
|
+
`}var tr=Gr;function Vr(r,e){return`
|
|
192
192
|
You will be given an original text and a custom prompt addition that specifies how to change the text. Your task is to modify the original text according to the prompt and return only the new, modified text.
|
|
193
193
|
|
|
194
194
|
Here is the original text:
|
|
195
195
|
<original_text>
|
|
196
|
-
${
|
|
196
|
+
${r}
|
|
197
197
|
</original_text>
|
|
198
198
|
|
|
199
199
|
The custom prompt addition is:
|
|
@@ -202,5 +202,5 @@ ${e}
|
|
|
202
202
|
</change_text_to>
|
|
203
203
|
|
|
204
204
|
Please modify the original text according to the "Change Text to..." prompt. Only return the new, modified text without any additional commentary or explanation. Your entire response should be the modified text itself, with no other content.
|
|
205
|
-
`}var bt=Vr;function
|
|
205
|
+
`}var bt=Vr;function rr(r){return e=>{e.cesdk.i18n.setTranslations({en:{...Object.entries(Ee).reduce((s,[i,o])=>(s[`ly.img.ai.inference.translate.type.${i}`]=o,s),{})}});let t=null,n={kind:"text",id:"anthropic",initialize:async()=>{t=new Qt({dangerouslyAllowBrowser:!0,baseURL:r.proxyUrl,apiKey:null,authToken:null})},input:{quickActions:{actions:[Yr(),en(),zr(),Zr(),tn(),nn(),sn(),on()]}},output:{middleware:r.middleware,generate:async({prompt:s,blockId:i},{engine:o,abortSignal:a})=>{if(t==null)throw new Error("Anthropic SDK is not initialized");if(i!=null&&o.block.getType(i)!=="//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(s,void 0,2));let d=await Kt(t,{proxyUrl:r.proxyUrl,headers:r.headers},s,a);async function*h(){let p="";for await(let y of d){if(a.aborted)break;p+=y,yield{kind:"text",text:p}}return{kind:"text",text:p}}return h()}}};return Promise.resolve(n)}}function U(r){let{id:e,label:t,icon:n,promptFn:s,parameters:i,renderExpanded:o}=r,d={id:e,version:"1",confirmation:!0,enable:({engine:h})=>{let p=h.block.findAllSelected();if(p==null||p.length!==1)return!1;let[y]=p;return h.block.getType(y)==="//ly.img.ubq/text"}};return o?{...d,render:({builder:h},{toggleExpand:p})=>{h.Button(`${e}.button`,{label:t,icon:n,labelAlignment:"left",variant:"plain",onClick:p})},renderExpanded:o}:!i||i.length===0?{...d,render:({builder:h,engine:p},{generate:y,closeMenu:O})=>{h.Button(e,{label:t,icon:n,labelAlignment:"left",variant:"plain",onClick:()=>{O();let[B]=p.block.findAllSelected(),C=p.block.getString(B,"text/text");y({prompt:s(C),blockId:B,initialText:C})}})}}:{...d,render:({builder:h,engine:p,experimental:y},{generate:O,closeMenu:B})=>{y.builder.Popover(`${e}.popover`,{label:t,icon:n,labelAlignment:"left",variant:"plain",trailingIcon:"@imgly/ChevronRight",placement:"right",children:()=>{h.Section(`${e}.popover.section`,{children:()=>{y.builder.Menu(`${e}.popover.menu`,{children:()=>{i.forEach(C=>{h.Button(`${e}.popover.menu.${C.id}`,{label:C.label,icon:C.icon,labelAlignment:"left",variant:"plain",onClick:()=>{B();let[Me]=p.block.findAllSelected(),G=p.block.getString(Me,"text/text");O({prompt:s(G,C.id),blockId:Me,initialText:G})}})})}})}})}})}}}function Yr(){return U({id:"improve",label:"Improve",icon:"@imgly/MagicWand",promptFn:Jt})}function zr(){return U({id:"shorter",label:"Make Shorter",icon:"@imgly/TextShorter",promptFn:Gt})}function Zr(){return U({id:"longer",label:"Make Longer",icon:"@imgly/TextLonger",promptFn:Vt})}function en(){return U({id:"fix",label:"Fix Spelling & Grammar",icon:"@imgly/CheckmarkAll",promptFn:Yt})}function tn(){return U({id:"speech",label:"Generate Speech Text",icon:"@imgly/Microphone",promptFn:zt})}var rn=["professional","casual","friendly","serious","humorous","optimistic"];function nn(){return U({id:"changeTone",label:"Change Tone",icon:"@imgly/Microphone",promptFn:tr,parameters:rn.map(r=>({id:r,label:r.charAt(0).toUpperCase()+r.slice(1)}))})}function sn(){return U({id:"translate",label:"Translate",icon:"@imgly/Language",promptFn:er,parameters:Zt.map(r=>({id:r,label:Ee[r]}))})}function on(){return U({id:"changeTextTo",label:"Change Text to...",icon:"@imgly/Rename",promptFn:bt,renderExpanded:({builder:r,engine:e,experimental:t,state:n},{generate:s,toggleExpand:i})=>{let o=n("changeTextTo.prompt","");r.TextArea("changeTextTo.textarea",{inputLabel:"Change text to...",...o}),r.Separator("changeTextTo.separator"),t.builder.ButtonRow("changeTextTo.footer",{justifyContent:"space-between",children:()=>{r.Button("changeTextTo.footer.cancel",{label:"Back",icon:"@imgly/ChevronLeft",onClick:i}),r.Button("changeTextTo.footer.apply",{label:"Rewrite",icon:"@imgly/MagicWand",color:"accent",onClick:()=>{let a=o.value;if(!a)return;let[d]=e.block.findAllSelected(),h=e.block.getString(d,"text/text");s({prompt:bt(h,a),blockId:d,initialText:h}),i()}})}})}})}var an={AnthropicProvider:rr},li=an;export{li as default};
|
|
206
206
|
//# sourceMappingURL=index.mjs.map
|