@imgly/plugin-ai-text-generation-web 0.1.0-rc.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,126 @@
1
+ # IMG.LY Creative Editor SDK AI Text2Text Plugin
2
+
3
+ A plugin for [IMG.LY Creative Editor SDK](https://img.ly/) that provides AI-powered text transformation capabilities using the Claude AI model from Anthropic. Other providers will be added in the future.
4
+
5
+ ## Features
6
+
7
+ This plugin adds a "Magic Menu" with the following text transformation options:
8
+
9
+ - **Improve Writing**: Enhance the quality and clarity of text
10
+ - **Fix Spelling & Grammar**: Correct language errors in text
11
+ - **Make Shorter**: Create a more concise version of the text
12
+ - **Make Longer**: Expand text with additional details
13
+ - **Change Tone**: Modify the tone of text to professional, casual, friendly, serious, humorous, or optimistic
14
+ - **Translate**: Translate text to various languages
15
+ - **Change Text to...**: Completely rewrite text based on a custom prompt
16
+
17
+ ## Installation
18
+
19
+ ```bash
20
+ npm install @imgly/plugin-ai-text2text-web
21
+ ```
22
+
23
+ ## Usage
24
+
25
+ Add the plugin to your Creative Engine instance:
26
+
27
+ ```typescript
28
+ import CreativeEditorSDK from '@cesdk/cesdk-js';
29
+ import AIText2TextPlugin from '@imgly/plugin-ai-text2text-web';
30
+
31
+ const cesdk = CreativeEditorSDK.create(domElement, {
32
+ // other configuration options...
33
+ });
34
+
35
+ // Add the plugin
36
+ cesdk.addPlugin(
37
+ AIText2TextPlugin({
38
+ provider: {
39
+ id: 'anthropic',
40
+ proxyUrl: 'https://your-proxy-server.com/anthropic',
41
+ // Optional configuration
42
+ model: 'claude-3-haiku-20240307',
43
+ maxTokens: 1000,
44
+ temperature: 0.7
45
+ },
46
+ // Optional debug mode
47
+ debug: false
48
+ })
49
+ );
50
+
51
+ // The plugin registers new canvas "magic menu" for text. It can
52
+ // be placed in the desired position in the menu order with the
53
+ // following code:
54
+ cesdk.ui.setCanvasMenuOrder([
55
+ 'ly.img.ai.text.canvasMenu',
56
+ ...instance.ui.getCanvasMenuOrder()
57
+ ]);
58
+ ```
59
+
60
+ ## Security Note
61
+
62
+ This plugin requires a proxy server to handle API key injection. The proxy server should:
63
+
64
+ 1. Receive requests from the client
65
+ 2. Add the Anthropic API key to the request
66
+ 3. Forward the request to Anthropic
67
+ 4. Return the response to the client
68
+
69
+ Never expose your Anthropic API key in client-side code.
70
+
71
+ ## Configuration
72
+
73
+ ### PluginConfiguration
74
+
75
+ | Option | Type | Required | Description |
76
+ | ---------- | ------------------- | -------- | --------------------------------- |
77
+ | `provider` | `Text2TextProvider` | Yes | The AI provider configuration |
78
+ | `debug` | `boolean` | No | Enable console logs for debugging |
79
+
80
+ ### AnthropicProvider (only supported provider for now)
81
+
82
+ | Option | Type | Required | Description |
83
+ | ------------- | ------------- | -------- | ------------------------------------------------------------------------------------------------------------------------- |
84
+ | `id` | `'anthropic'` | Yes | Provider identifier (must be 'anthropic') |
85
+ | `proxyUrl` | `string` | Yes | URL to AI service that handles API key injection |
86
+ | `model` | `string` | No | Anthropic model to use (see [Anthropic documentation](https://docs.anthropic.com/en/docs/about-claude/models/all-models)) |
87
+ | `maxTokens` | `number` | No | Maximum token generation limit |
88
+ | `temperature` | `number` | No | Randomness level (0.0-1.0) |
89
+
90
+ ### Extending the "magic menu"
91
+
92
+ The "magic menu" can be extended with additional entries from other plugins. This allows you to combine multiple AI-powered text transformation plugins, each providing their own specialized capabilities.
93
+
94
+ #### Adding entries from other plugins
95
+
96
+ When other plugins export their own `MagicEntry` objects, you can add them to the existing magic menu:
97
+
98
+ ```typescript
99
+ import CreativeEditorSDK from '@cesdk/cesdk-js';
100
+ import AIText2TextPlugin from '@imgly/plugin-ai-text2text-web';
101
+ import OtherPlugin from '@imgly/other-plugin';
102
+
103
+ // Initialize Creative Engine
104
+ const cesdk = CreativeEditorSDK.create(domElement, {
105
+ // config options...
106
+ });
107
+
108
+ // Add the plugins
109
+ cesdk.addPlugin(
110
+ AIText2TextPlugin({
111
+ provider: {
112
+ id: 'anthropic',
113
+ proxyUrl: 'https://your-proxy-server.com/anthropic'
114
+ }
115
+ })
116
+ );
117
+ cesdk.addPlugin(OtherPlugin());
118
+
119
+ // Set canvas menu order to render the magic button
120
+ instance.ui.setCanvasMenuOrder([
121
+ 'ly.img.ai.text.canvasMenu',
122
+ ...instance.ui.getCanvasMenuOrder()
123
+ ]);
124
+ ```
125
+
126
+ For plugin developers wanting to create and export compatible magic entries, refer to the `MagicEntry` interface in the plugin source code.
@@ -0,0 +1,21 @@
1
+ import CreativeEditorSDK from '@cesdk/cesdk-js';
2
+ import { Provider } from '@imgly/plugin-ai-generation-web';
3
+ type ProviderConfiguration = {
4
+ proxyUrl: string;
5
+ debug?: boolean;
6
+ };
7
+ type AnthropicInput = {
8
+ prompt: string;
9
+ temperature?: number;
10
+ maxTokens?: number;
11
+ blockId?: number;
12
+ initialText?: string;
13
+ };
14
+ type AnthropicOutput = {
15
+ kind: 'text';
16
+ text: string;
17
+ };
18
+ export declare function AnthropicProvider(config: ProviderConfiguration): (context: {
19
+ cesdk: CreativeEditorSDK;
20
+ }) => Promise<Provider<'text', AnthropicInput, AnthropicOutput>>;
21
+ export {};
@@ -0,0 +1,5 @@
1
+ import { AnthropicProvider } from './AnthropicProvider';
2
+ declare const Anthropic: {
3
+ AnthropicProvider: typeof AnthropicProvider;
4
+ };
5
+ export default Anthropic;
@@ -0,0 +1,206 @@
1
+ var L="0.39.0";var xt=!1,D,et,rr,nr,sr,_t,ir,Re,tt,At,rt,ve,St;function kt(n,e={auto:!1}){if(xt)throw new Error(`you must \`import '@anthropic-ai/sdk/shims/${n.kind}'\` before importing anything else from @anthropic-ai/sdk`);if(D)throw new Error(`can't \`import '@anthropic-ai/sdk/shims/${n.kind}'\` after \`import '@anthropic-ai/sdk/shims/${D}'\``);xt=e.auto,D=n.kind,et=n.fetch,rr=n.Request,nr=n.Response,sr=n.Headers,_t=n.FormData,ir=n.Blob,Re=n.File,tt=n.ReadableStream,At=n.getMultipartRequestOptions,rt=n.getDefaultAgent,ve=n.fileFromPath,St=n.isFsReadStream}var Te=class{constructor(e){this.body=e}get[Symbol.toStringTag](){return"MultipartBody"}};function Pt({manuallyImported:n}={}){let e=n?"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,r,s,i;try{t=fetch,r=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:r,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 n extends c{constructor(e,t,r,s){super(`${n.makeMessage(e,t,r)}`),this.status=e,this.headers=s,this.request_id=s?.["request-id"],this.error=t}static makeMessage(e,t,r){let s=t?.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):r;return e&&s?`${e} ${s}`:e?`${e} status code (no body)`:s||"(no status code or body)"}static generate(e,t,r,s){if(!e||!s)return new F({message:r,cause:Ie(t)});let i=t;return e===400?new ie(e,i,r,s):e===401?new oe(e,i,r,s):e===403?new ae(e,i,r,s):e===404?new ce(e,i,r,s):e===409?new le(e,i,r,s):e===422?new ue(e,i,r,s):e===429?new he(e,i,r,s):e>=500?new de(e,i,r,s):new n(e,i,r,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(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},H=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)},_,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,r=new Uint8Array(this.buffer.length+t.length);r.set(this.buffer),r.set(t,this.buffer.length),this.buffer=r;let s=[],i;for(;(i=cr(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
+ `):[]}};_=new WeakMap;R.NEWLINE_CHARS=new Set([`
3
+ `,"\r"]);R.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function cr(n,e){for(let s=e??0;s<n.length;s++){if(n[s]===10)return{preceding:s,index:s+1,carriage:!1};if(n[s]===13)return{preceding:s,index:s+1,carriage:!0}}return null}function Et(n){for(let r=0;r<n.length-1;r++){if(n[r]===10&&n[r+1]===10||n[r]===13&&n[r+1]===13)return r+2;if(n[r]===13&&n[r+1]===10&&r+3<n.length&&n[r+2]===13&&n[r+3]===10)return r+4}return-1}function fe(n){if(n[Symbol.asyncIterator])return n;let e=n.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 n{constructor(e,t){this.iterator=e,this.controller=t}static fromSSEResponse(e,t){let r=!1;async function*s(){if(r)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");r=!0;let i=!1;try{for await(let o of lr(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 n(s,t)}static fromReadableStream(e,t){let r=!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(r)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");r=!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 n(i,t)}[Symbol.asyncIterator](){return this.iterator()}tee(){let e=[],t=[],r=this.iterator(),s=i=>({next:()=>{if(i.length===0){let o=r.next();e.push(o),t.push(o)}return i.shift()}});return[new n(()=>s(e),this.controller),new n(()=>s(t),this.controller)]}toReadableStream(){let e=this,t,r=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=r.encode(JSON.stringify(i)+`
4
+ `);s.enqueue(a)}catch(i){s.error(i)}},async cancel(){await t.return?.()}})}};async function*lr(n,e){if(!n.body)throw e.abort(),new c("Attempted to iterate over a response with no body");let t=new nt,r=new R,s=fe(n.body);for await(let i of ur(s))for(let o of r.decode(i)){let a=t.decode(o);a&&(yield a)}for(let i of r.flush()){let o=t.decode(i);o&&(yield o)}}async function*ur(n){let e=new Uint8Array;for await(let t of n){if(t==null)continue;let r=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?new TextEncoder().encode(t):t,s=new Uint8Array(e.length+r.length);s.set(e),s.set(r,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,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 U=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{};U.ModelInfosPage=J;var Wt,f=class extends qe{constructor({baseURL:e=je("ANTHROPIC_BASE_URL"),apiKey:t=je("ANTHROPIC_API_KEY")??null,authToken:r=je("ANTHROPIC_AUTH_TOKEN")??null,...s}={}){let i={apiKey:t,authToken:r,...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
+
9
+ This is disabled by default, as it risks exposing your secret API credentials to attackers.
10
+ If you understand the risks and have appropriate mitigations in place,
11
+ you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
12
+
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 U(this),this.beta=new M(this),this._options=i,this.apiKey=t,this.authToken=r}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),r=this.bearerAuth(e);return t!=null&&!me(t)?t:r!=null&&!me(r)?r:{}}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
+
16
+ Human:`;f.AI_PROMPT=`
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=U;f.ModelInfosPage=J;f.Beta=M;var{HUMAN_PROMPT:Us,AI_PROMPT:Ns}=f,Qt=f;var Nr={model:"claude-3-7-sonnet-20250219",max_tokens:8192,temperature:.1},Lr={headers:{"x-api-key":null,authorization:null}};async function Dr(n,e,t,r){let s={};e.model&&(s.model=e.model),e.maxTokens&&(s.max_tokens=e.maxTokens),e.temperature&&(s.temperature=e.temperature);let i=await n.messages.create({...Nr,...s,stream:!0,messages:[{role:"user",content:[{type:"text",text:t}]}]},{signal:r,...Lr});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 Xt=Dr;function Hr(n){return`
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
+
21
+ Here is the original text you will be working with:
22
+
23
+ <original_text>
24
+ ${n}
25
+ </original_text>
26
+
27
+ Please follow these steps to improve the text:
28
+
29
+ 1. Carefully read and analyze the original text.
30
+ 2. Consider the specific improvement type requested and how it applies to the given text.
31
+ 3. Make the necessary changes to improve the text according to the requested improvement type. This may include:
32
+ - Rephrasing sentences
33
+ - Adjusting vocabulary
34
+ - Restructuring paragraphs
35
+ - Adding or removing content as appropriate
36
+ 4. Ensure that the improved version maintains the original meaning and intent of the text.
37
+ 5. Return the improved text without any additional commentary or explanation.
38
+ 6. If there is nothing to improve, simply return the original text without any changes.
39
+ 7. If you cannot make any meaningful improvements, return the original text as is.
40
+
41
+ Once you have made the improvements, only return the improved text and nothing else.
42
+ `}var Kt=Hr;function Wr(n){return`
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
+
45
+ Here is the original text:
46
+
47
+ <original_text>
48
+ ${n}
49
+ </original_text>
50
+
51
+ To complete this task, follow these steps:
52
+
53
+ 1. Carefully read and analyze the text, paying attention to its style, tone, and main points.
54
+
55
+ 2. Identify areas where the text can be condensed without losing essential information or altering the author's voice.
56
+
57
+ 3. Begin shortening the text by:
58
+ - Removing redundant or repetitive information
59
+ - Simplifying complex sentences
60
+ - Eliminating unnecessary examples or elaborations
61
+ - Combining related ideas into more concise statements
62
+
63
+ 4. As you shorten, continuously check that you are:
64
+ - Maintaining the original voice and perspective
65
+ - Keeping all crucial information
66
+ - Preserving the flow and coherence of the text
67
+
68
+ 5. Aim to reduce the length by 30% to 50% of the original. If you find yourself shortening less than 30%, look for additional opportunities to condense. If you're reducing more than 50%, ensure you haven't cut too much important content.
69
+
70
+ 6. Once you've finished shortening, review the text to ensure it still reads smoothly and retains the essence of the original.
71
+
72
+ Provide only the shortened version of the text in your response, without any additional comments, tags or explanations.
73
+ `}var Jt=Wr;function Qr(n){return`
74
+ You are tasked with expanding a given text to make it longer. Here's how to proceed:
75
+
76
+ First, you will be provided with the original text:
77
+
78
+ <original_text>
79
+ ${n}
80
+ </original_text>
81
+
82
+ To expand the text:
83
+
84
+ 1. Analyze the original text to understand its main ideas, tone, and style.
85
+ 2. Identify areas where you can add more detail, examples, or explanations.
86
+ 3. Expand on these areas by:
87
+ - Providing more context or background information
88
+ - Adding relevant examples or anecdotes
89
+ - Elaborating on key points
90
+ - Introducing related concepts or ideas
91
+ - Explaining implications or consequences of the main ideas
92
+ 4. Ensure that the expanded text length is not exceeding the original text by more than 50%.
93
+ 5. Always expand the text, even if it is a single word. Explain the word with a few short sentences in that case. If the text is empty, make up a short sentence.
94
+
95
+ Guidelines:
96
+
97
+ - Maintain the original tone and style of the text.
98
+ - Ensure all additions are relevant to the main topic.
99
+ - Keep the flow of the text natural and coherent.
100
+ - Do not contradict any information in the original text.
101
+
102
+ Only return the longer text and nothing else.
103
+
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
+
106
+ Do not add the original text or the original_text tags to the response.
107
+ `}var Gt=Qr;function Xr(n){return`
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
+
110
+ <original_text>
111
+ ${n}
112
+ </original_text>
113
+
114
+ Please follow these steps to complete the task:
115
+
116
+ 1. Carefully read through the text and identify any spelling or grammatical errors.
117
+
118
+ 2. Correct all spelling mistakes, including typos and incorrectly spelled words.
119
+
120
+ 3. Fix grammatical errors, including:
121
+ - Incorrect verb tenses
122
+ - Subject-verb agreement issues
123
+ - Improper use of articles (a, an, the)
124
+ - Incorrect word usage
125
+ - Run-on sentences or sentence fragments
126
+ - Punctuation errors
127
+
128
+ 4. Ensure proper capitalization, especially at the beginning of sentences and for proper nouns.
129
+
130
+ 5. Maintain the original meaning and tone of the text. Do not add or remove information, or change the author's intended message.
131
+
132
+ 6. Make sure the corrected text flows naturally and is easy to read.
133
+
134
+ After making the necessary corrections, please provide only the improved output and nothing else.
135
+
136
+ Remember to preserve the original structure and formatting of the text as much as possible while making your corrections.
137
+ `}var Vt=Xr;function Kr(n){return`
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
+
140
+ Follow these guidelines when generating the text:
141
+ 1. Keep the text concise and to the point.
142
+ 2. Use simple words and sentence structures.
143
+ 3. Aim for approximately 20-25 words.
144
+ 4. Ensure the text is coherent and meaningful.
145
+ 5. Stay relevant to the given prompt.
146
+
147
+ Here is the prompt to base your text on:
148
+ <prompt>
149
+ ${n}
150
+ </prompt>
151
+
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 Yt=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(n,e){let t=Ee[e]||e;return`
154
+ You are a translation AI. Your task is to translate the given text into the specified target language. Follow these steps:
155
+
156
+ 1. Here is the source text to be translated:
157
+ <source_text>
158
+ ${n}
159
+ </source_text>
160
+
161
+ 2. The target language for translation is:
162
+ <target_language>
163
+ ${t}
164
+ </target_language>
165
+
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
+
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 Zt=Jr;function Gr(n,e){return`
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
+
172
+ First, you will be provided with the original text:
173
+ <original_text>
174
+ ${n}
175
+ </original_text>
176
+
177
+ The desired tone for the rewritten text is:
178
+ <desired_tone>
179
+ ${e}
180
+ </desired_tone>
181
+
182
+ To change the tone of the text:
183
+ 1. Analyze the current tone and style of the original text.
184
+ 2. Identify the key information and main ideas in the original text.
185
+ 3. Consider the characteristics of the desired tone (e.g., formal, casual, humorous, professional, etc.).
186
+ 4. Rewrite the text, adapting the language, vocabulary, and sentence structure to match the desired tone while maintaining the original meaning and key information.
187
+ 5. Ensure that the rewritten text flows naturally and coherently.
188
+ 6. Only return the rewritten text without any additional commentary, tags or explanation.
189
+
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 er=Gr;function Vr(n,e){return`
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
+
194
+ Here is the original text:
195
+ <original_text>
196
+ ${n}
197
+ </original_text>
198
+
199
+ The custom prompt addition is:
200
+ <change_text_to>
201
+ ${e}
202
+ </change_text_to>
203
+
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 tr(n){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,r={kind:"text",id:"anthropic",initialize:async()=>{t=new Qt({dangerouslyAllowBrowser:!0,baseURL:n.proxyUrl,apiKey:null,authToken:null})},input:{quickActions:{actions:[Yr(),en(),zr(),Zr(),tn(),nn(),sn(),on()]}},output:{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");n.debug&&console.log("Sending prompt to Anthropic:",JSON.stringify(s,void 0,2));let d=await Xt(t,{proxyUrl:n.proxyUrl},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(r)}}function N(n){let{id:e,label:t,icon:r,promptFn:s,parameters:i,renderExpanded:o}=n,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:r,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:r,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:r,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 N({id:"improve",label:"Improve",icon:"@imgly/MagicWand",promptFn:Kt})}function zr(){return N({id:"shorter",label:"Make Shorter",icon:"@imgly/TextShorter",promptFn:Jt})}function Zr(){return N({id:"longer",label:"Make Longer",icon:"@imgly/TextLonger",promptFn:Gt})}function en(){return N({id:"fix",label:"Fix Spelling & Grammar",icon:"@imgly/CheckmarkAll",promptFn:Vt})}function tn(){return N({id:"speech",label:"Generate Speech Text",icon:"@imgly/Microphone",promptFn:Yt})}var rn=["professional","casual","friendly","serious","humorous","optimistic"];function nn(){return N({id:"changeTone",label:"Change Tone",icon:"@imgly/Microphone",promptFn:er,parameters:rn.map(n=>({id:n,label:n.charAt(0).toUpperCase()+n.slice(1)}))})}function sn(){return N({id:"translate",label:"Translate",icon:"@imgly/Language",promptFn:Zt,parameters:zt.map(n=>({id:n,label:Ee[n]}))})}function on(){return N({id:"changeTextTo",label:"Change Text to...",icon:"@imgly/Rename",promptFn:bt,renderExpanded:({builder:n,engine:e,experimental:t,state:r},{generate:s,toggleExpand:i})=>{let o=r("changeTextTo.prompt","");n.TextArea("changeTextTo.textarea",{inputLabel:"Change text to...",...o}),n.Separator("changeTextTo.separator"),t.builder.ButtonRow("changeTextTo.footer",{justifyContent:"space-between",children:()=>{n.Button("changeTextTo.footer.cancel",{label:"Back",icon:"@imgly/ChevronLeft",onClick:i}),n.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:tr},li=an;export{li as default};
206
+ //# sourceMappingURL=index.mjs.map