@adaline/bedrock 0.7.0 → 0.7.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -6,13 +6,13 @@ var protocolHttp = require('@smithy/protocol-http');
6
6
  var signatureV4 = require('@smithy/signature-v4');
7
7
 
8
8
  var kn=Object.create;var Z=Object.defineProperty;var En=Object.getOwnPropertyDescriptor;var On=Object.getOwnPropertyNames,Se=Object.getOwnPropertySymbols,Ee=Object.getPrototypeOf,Oe=Object.prototype.hasOwnProperty,Pn=Object.prototype.propertyIsEnumerable,In=Reflect.get;var _n=(n,t)=>(t=Symbol[n])?t:Symbol.for("Symbol."+n);var ke=(n,t,a)=>t in n?Z(n,t,{enumerable:!0,configurable:!0,writable:!0,value:a}):n[t]=a,T=(n,t)=>{for(var a in t||(t={}))Oe.call(t,a)&&ke(n,a,t[a]);if(Se)for(var a of Se(t))Pn.call(t,a)&&ke(n,a,t[a]);return n};var Rn=(n=>typeof require!="undefined"?require:typeof Proxy!="undefined"?new Proxy(n,{get:(t,a)=>(typeof require!="undefined"?require:t)[a]}):n)(function(n){if(typeof require!="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});var Un=(n,t)=>()=>(t||n((t={exports:{}}).exports,t),t.exports);var $n=(n,t,a,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of On(t))!Oe.call(n,r)&&r!==a&&Z(n,r,{get:()=>t[r],enumerable:!(i=En(t,r))||i.enumerable});return n};var Pe=(n,t,a)=>(a=n!=null?kn(Ee(n)):{},$n(!n||!n.__esModule?Z(a,"default",{value:n,enumerable:!0}):a,n));var B=(n,t,a)=>In(Ee(n),a,t);var O=(n,t,a)=>new Promise((i,r)=>{var s=c=>{try{d(a.next(c));}catch(p){r(p);}},l=c=>{try{d(a.throw(c));}catch(p){r(p);}},d=c=>c.done?i(c.value):Promise.resolve(c.value).then(s,l);d((a=a.apply(n,t)).next());}),Y=function(n,t){this[0]=n,this[1]=t;},Ie=(n,t,a)=>{var i=(l,d,c,p)=>{try{var g=a[l](d),f=(d=g.value)instanceof Y,v=g.done;Promise.resolve(f?d[0]:d).then(h=>f?i(l==="return"?l:"next",d[1]?{done:h.done,value:h.value}:h,c,p):c({value:h,done:v})).catch(h=>i("throw",h,c,p));}catch(h){p(h);}},r=l=>s[l]=d=>new Promise((c,p)=>i(l,d,c,p)),s={};return a=a.apply(n,t),s[_n("asyncIterator")]=()=>s,r("next"),r("throw"),r("return"),s};var Te=Un(u=>{var e=Rn("zod"),_a=Object.defineProperty,Ra=Object.defineProperties,Ua=Object.getOwnPropertyDescriptors,ot=Object.getOwnPropertySymbols,$a=Object.prototype.hasOwnProperty,Aa=Object.prototype.propertyIsEnumerable,La=(n,t)=>(t=Symbol[n])?t:Symbol.for("Symbol."+n),it=(n,t,a)=>t in n?_a(n,t,{enumerable:!0,configurable:!0,writable:!0,value:a}):n[t]=a,y=(n,t)=>{for(var a in t||(t={}))$a.call(t,a)&&it(n,a,t[a]);if(ot)for(var a of ot(t))Aa.call(t,a)&&it(n,a,t[a]);return n},F=(n,t)=>Ra(n,Ua(t)),M=(n,t,a)=>new Promise((i,r)=>{var s=c=>{try{d(a.next(c));}catch(p){r(p);}},l=c=>{try{d(a.throw(c));}catch(p){r(p);}},d=c=>c.done?i(c.value):Promise.resolve(c.value).then(s,l);d((a=a.apply(n,t)).next());}),Ba=function(n,t){this[0]=n,this[1]=t;},qa=(n,t,a)=>{var i=(l,d,c,p)=>{try{var g=a[l](d),f=(d=g.value)instanceof Ba,v=g.done;Promise.resolve(f?d[0]:d).then(h=>f?i(l==="return"?l:"next",d[1]?{done:h.done,value:h.value}:h,c,p):c({value:h,done:v})).catch(h=>i("throw",h,c,p));}catch(h){p(h);}},r=l=>s[l]=d=>new Promise((c,p)=>i(l,d,c,p)),s={};return a=a.apply(n,t),s[La("asyncIterator")]=()=>s,r("next"),r("throw"),r("return"),s},Fa=n=>n==null?"unknown error":typeof n=="string"?n:n instanceof Error?n.message:JSON.stringify(n),ee="GatewayBaseError",k=class vt extends Error{constructor({info:t,cause:a},i){super(`[${i!=null?i:ee}]: ${t}
9
- Message: ${Fa(a)}`),this.name=ee,this.info=t,this.cause=a,this.name=i!=null?i:ee,Object.setPrototypeOf(this,new.target.prototype);}static isGatewayBaseError(t){return t instanceof vt}toJSON(){return {name:this.name,info:this.info,cause:this.cause,message:this.message,stack:this.stack}}},A="system",K="user",w="assistant",Ka="tool",Da=[A,K,w,Ka],wt=e.z.enum(Da),Ha=[w],Na=e.z.enum(Ha),I="image",Ct="base64",Ja=["png","jpeg","webp","gif"],Ga=e.z.object({type:e.z.literal(Ct),base64:e.z.string(),media_type:e.z.enum(Ja)}),Va="url",Za=e.z.object({type:e.z.literal(Va),url:e.z.string()}),Ya=e.z.discriminatedUnion("type",[Ga,Za]),Wa=["low","medium","high","auto"],Xa=e.z.enum(Wa),Qa=(n=e.z.undefined())=>e.z.object({modality:e.z.literal(I),detail:Xa,value:Ya,metadata:n}),b="text",xt=(n=e.z.undefined())=>e.z.object({modality:e.z.literal(b),value:e.z.string(),metadata:n}),ae="partial-text",Tt=(n=e.z.undefined())=>e.z.object({modality:e.z.literal(ae),value:e.z.string(),metadata:n}),x="tool-call",jt=(n=e.z.undefined())=>e.z.object({modality:e.z.literal(x),index:e.z.number().int().nonnegative(),id:e.z.string().min(1),name:e.z.string().min(1),arguments:e.z.string(),metadata:n}),oe="partial-tool-call",Mt=(n=e.z.undefined())=>e.z.object({modality:e.z.literal(oe),index:e.z.number().int().nonnegative(),id:e.z.string().optional(),name:e.z.string().optional(),arguments:e.z.string().optional(),metadata:n}),_="tool-response",eo=(n=e.z.undefined())=>e.z.object({modality:e.z.literal(_),index:e.z.number().int().nonnegative(),id:e.z.string().min(1),name:e.z.string().min(1),data:e.z.string(),metadata:n}),to=[b,I,x,_],no=e.z.enum(to),ao=(n=e.z.undefined(),t=e.z.undefined(),a=e.z.undefined(),i=e.z.undefined())=>e.z.discriminatedUnion("modality",[xt(n),Qa(t),jt(a),eo(i)]),oo=[ae,oe];e.z.enum(oo);var io=(n=e.z.undefined(),t=e.z.undefined())=>e.z.discriminatedUnion("modality",[Tt(n),Mt(t)]),St=(n=wt,t=e.z.undefined(),a=e.z.undefined(),i=e.z.undefined(),r=e.z.undefined(),s=e.z.undefined())=>e.z.object({role:n,content:e.z.array(ao(t,a,i,r)),metadata:s}),ie=(n=Na,t=e.z.undefined(),a=e.z.undefined(),i=e.z.undefined())=>e.z.object({role:n,partialContent:io(t,a),metadata:i}),ro=n=>xt().parse({modality:b,value:n}),so=(n,t,a,i)=>jt().parse({modality:x,index:n,id:t,name:a,arguments:i}),rt=(n,t)=>ie().parse({role:n,partialContent:Tt().parse({modality:ae,value:t})}),st=(n,t,a,i,r)=>ie().parse({role:n,partialContent:Mt().parse({modality:oe,index:t,id:a,name:i,arguments:r})}),kt=(n=e.z.record(e.z.string(),e.z.any()).optional())=>n,lo="function",mo=e.z.enum(["object","array","number","string","boolean","null"]),co=e.z.object({anyOf:e.z.array(e.z.any()).optional(),type:mo.optional(),default:e.z.any().optional(),title:e.z.string().optional(),description:e.z.string().max(4096).optional(),properties:e.z.record(e.z.any()).optional(),required:e.z.array(e.z.string()).optional(),minItems:e.z.number().int().min(0).optional(),maxItems:e.z.number().int().optional(),items:e.z.record(e.z.any()).optional(),enum:e.z.array(e.z.union([e.z.string(),e.z.number(),e.z.boolean(),e.z.null()])).optional(),minimum:e.z.number().optional(),maximum:e.z.number().optional(),minLength:e.z.number().int().min(0).optional(),maxLength:e.z.number().int().optional()});e.z.object({type:e.z.enum(["object"]),title:e.z.string().optional(),$defs:e.z.record(e.z.any()).optional(),properties:e.z.record(co).optional(),required:e.z.array(e.z.string()).optional()});var uo=e.z.object({name:e.z.string().regex(/^[a-zA-Z0-9_]{1,64}$/).max(64),description:e.z.string().max(4096),parameters:e.z.any(),strict:e.z.boolean().optional()}),po=e.z.enum(["function"]),ho=e.z.object({type:po,definition:e.z.object({schema:uo})}),go=[lo];e.z.enum(go);var fo=(n=e.z.undefined())=>e.z.discriminatedUnion("type",[ho.extend({metadata:n})]),R="text",Et="token",yo=[R,Et],bo=e.z.enum(yo),zo=e.z.array(e.z.string().min(1)),vo=e.z.array(e.z.array(e.z.number().int().nonnegative())),wo=(n=e.z.undefined())=>e.z.discriminatedUnion("modality",[e.z.object({modality:e.z.literal(R),metadata:n,requests:zo}),e.z.object({modality:e.z.literal(Et),metadata:n,requests:vo})]),Ot="float",Co=e.z.object({index:e.z.number().int().nonnegative(),embedding:e.z.array(e.z.number())}),Pt="base64",xo=e.z.object({index:e.z.number().int().nonnegative(),embedding:e.z.string().base64()}),lt=e.z.object({totalTokens:e.z.number().int().nonnegative()});e.z.discriminatedUnion("encodingFormat",[e.z.object({encodingFormat:e.z.literal(Ot),embeddings:e.z.array(Co),usage:lt.optional()}),e.z.object({encodingFormat:e.z.literal(Pt),embeddings:e.z.array(xo),usage:lt.optional()})]);var It=e.z.object({promptTokens:e.z.number().nonnegative(),completionTokens:e.z.number().nonnegative(),totalTokens:e.z.number().nonnegative()}),dt=e.z.object({token:e.z.string(),logProb:e.z.number(),bytes:e.z.array(e.z.number().int()).nullable()}),To=dt.extend({topLogProbs:e.z.array(dt)}),_t=e.z.array(To);e.z.object({messages:e.z.array(St()),usage:It.optional(),logProbs:_t.optional()});e.z.object({partialMessages:e.z.array(ie()),usage:It.optional(),logProbs:_t.optional()});var jo=Object.defineProperty,mt=Object.getOwnPropertySymbols,Mo=Object.prototype.hasOwnProperty,So=Object.prototype.propertyIsEnumerable,ct=(n,t,a)=>t in n?jo(n,t,{enumerable:!0,configurable:!0,writable:!0,value:a}):n[t]=a,re=(n,t)=>{for(var a in t||(t={}))Mo.call(t,a)&&ct(n,a,t[a]);if(mt)for(var a of mt(t))So.call(t,a)&&ct(n,a,t[a]);return n},ut="ProviderError",q=class Rt extends k{constructor({info:t,cause:a}){super({info:t,cause:a},ut),this.name=ut,this.info=t,this.cause=a;}static isProviderError(t){return t instanceof Rt}},pt="ModelResponseError",j=class Ut extends k{constructor({info:t,cause:a}){super({info:t,cause:a},pt),this.name=pt,this.cause=a,this.info=t;}static isModelResponseError(t){return t instanceof Ut}},ht="InvalidModelRequestError",$t=class At extends k{constructor({info:t,cause:a}){super({info:t,cause:a},ht),this.name=ht,this.cause=a,this.info=t,Object.setPrototypeOf(this,new.target.prototype);}static isInvalidModelRequestError(t){return t instanceof At}},gt="InvalidConfigError",P=class Lt extends k{constructor({info:t,cause:a}){super({info:t,cause:a},gt),this.name=gt,this.cause=a,this.info=t,Object.setPrototypeOf(this,new.target.prototype);}static isInvalidConfigError(t){return t instanceof Lt}},ft="InvalidMessagesError",C=class Bt extends k{constructor({info:t,cause:a}){super({info:t,cause:a},ft),this.name=ft,this.cause=a,this.info=t,Object.setPrototypeOf(this,new.target.prototype);}static isInvalidMessagesError(t){return t instanceof Bt}},yt="InvalidToolsError",bt=class qt extends k{constructor({info:t,cause:a}){super({info:t,cause:a},yt),this.name=yt,this.cause=a,this.info=t,Object.setPrototypeOf(this,new.target.prototype);}static isInvalidToolsError(t){return t instanceof qt}},zt="InvalidEmbeddingRequestsError",ko=class Ft extends k{constructor({info:t,cause:a}){super({info:t,cause:a},zt),this.name=zt,this.info=t,this.cause=a,Object.setPrototypeOf(this,new.target.prototype);}static isInvalidEmbeddingRequestsError(t){return t instanceof Ft}},se="multi-string",Kt=e.z.object({type:e.z.literal(se),param:e.z.string().min(1),title:e.z.string().min(1),description:e.z.string().min(1).max(500),max:e.z.number().int().positive()}),Eo=n=>e.z.array(e.z.string()).max(n).default([]).optional(),Oo=n=>({def:Kt.parse(re({type:se},n)),schema:Eo(n.max)}),le="range",Dt=e.z.object({type:e.z.literal(le),param:e.z.string().min(1),title:e.z.string().min(1),description:e.z.string().min(1).max(500),min:e.z.number().int(),max:e.z.number().int(),step:e.z.number().positive(),default:e.z.number().int()}),Po=(n,t,a,i)=>e.z.number().min(n).max(t).step(a).default(i).optional(),D=n=>({def:Dt.parse(re({type:le},n)),schema:Po(n.min,n.max,n.step,n.default)}),de="select-string",Ht=e.z.object({type:e.z.literal(de),param:e.z.string().min(1),title:e.z.string().min(1),description:e.z.string().min(1).max(500),default:e.z.string().min(1),choices:e.z.array(e.z.string().min(1))}),Io=(n,t)=>e.z.enum(t).default(n).optional(),H=n=>({def:Ht.parse(re({type:de},n)),schema:Io(n.default,n.choices)}),Nt="object-schema",_o=e.z.object({type:e.z.literal(Nt),param:e.z.string().min(1),title:e.z.string().min(1),description:e.z.string().min(1).max(500),objectSchema:e.z.any()}),Jt="select-boolean",Ro=e.z.object({type:e.z.literal(Jt),param:e.z.string().min(1),title:e.z.string().min(1),description:e.z.string().min(1).max(500),default:e.z.boolean().nullable()}),Uo=[le,se,de,Nt,Jt];e.z.enum(Uo);var Gt=e.z.discriminatedUnion("type",[Dt,Kt,Ht,Ro,_o]),$o=(n=wt,t=no)=>e.z.object({name:e.z.string().min(1),description:e.z.string().min(1),roles:e.z.record(n,e.z.string().min(1).optional()),modalities:e.z.array(t).nonempty(),maxInputTokens:e.z.number().int().positive().min(1),maxOutputTokens:e.z.number().int().positive().min(1),config:e.z.object({def:e.z.record(e.z.string().min(1),Gt),schema:e.z.instanceof(e.z.ZodObject)}).refine(a=>{var i,r;let s=Object.keys(a.def),l=Object.keys((r=(i=a.schema)==null?void 0:i.shape)!=null?r:{});return s.every(d=>l.includes(d))&&l.every(d=>s.includes(d))},{message:"Keys in 'config.def' must exactly match keys in 'config.schema'"})}),Ao=(n=bo)=>e.z.object({name:e.z.string().min(1),description:e.z.string().min(1),modalities:e.z.array(n).nonempty(),maxInputTokens:e.z.number().int().positive().min(1),maxOutputTokens:e.z.number().int().positive().min(1),config:e.z.object({def:e.z.record(e.z.string().min(1),Gt),schema:e.z.instanceof(e.z.ZodObject)}).refine(t=>{var a,i;let r=Object.keys(t.def),s=Object.keys((i=(a=t.schema)==null?void 0:a.shape)!=null?i:{});return r.every(l=>s.includes(l))&&s.every(l=>r.includes(l))},{message:"Keys in 'config.def' must exactly match keys in 'config.schema'"})});e.z.record(e.z.string());e.z.record(e.z.union([e.z.boolean(),e.z.string(),e.z.number(),e.z.object({}),e.z.array(e.z.any()),e.z.null(),e.z.undefined()]));e.z.string().url();var Lo={type:"range",title:"Temperature",description:"Adjusts the model's creativity level. With a setting of 0, the model strictly picks the most probable next word. For endeavors that benefit from a dash of inventiveness, consider dialing it up to 0.7 or higher, enabling the model to produce text that's unexpectedly fresh."},Bo={type:"range",title:"Max tokens",description:"Specify the total tokens for generation, where one token approximates four English characters. Setting this to 0 defaults to the model's maximum capacity."},qo=n=>({type:"multi",title:"Stop sequence",description:`Enter up to ${n} sequences that will halt additional text output. The generated text will exclude these sequences.`}),Fo={type:"range",title:"Top P",description:"Selects a subset of likely tokens for generation, restricting choices to the top-P fraction of possibilities, such as the top 10% when P=0.1. This approach can limit the variety of the output. By default, it's set to 1, indicating no restriction. It's advised to adjust this parameter or temperature to modulate output diversity, but not to modify both simultaneously."},Ko={type:"range",title:"Top K",description:"Select only from the highest K probabilities for each following word, effectively eliminating the less likely 'long tail' options."},Do={type:"range",title:"Frequency penalty",description:"Minimize redundancy. By assigning a penalty to frequently used tokens within the text, the likelihood of repeating identical phrases is reduced. The default setting for this penalty is zero."},Ho={type:"range",title:"Presence penalty",description:"Enhance the introduction of novel subjects by reducing the preference for tokens that have already appeared in the text, thus boosting the chances of exploring fresh topics. The standard setting for this is zero."},S={TEMPERATURE:Lo,MAX_TOKENS:Bo,STOP:qo,TOP_P:Fo,TOP_K:Ko,FREQUENCY_PENALTY:Do,PRESENCE_PENALTY:Ho},Vt=n=>Object.fromEntries(Object.entries(n).filter(([t,a])=>a!=null)),$=n=>n==null?void 0:n.replace(/\/$/,""),me=D({param:"temperature",title:S.TEMPERATURE.title,description:S.TEMPERATURE.description,min:0,max:1,step:.01,default:1}),ce=n=>D({param:"max_tokens",title:S.MAX_TOKENS.title,description:S.MAX_TOKENS.description,min:0,max:n,step:1,default:0}),ue=n=>Oo({param:"stop_sequences",title:S.STOP(n).title,description:S.STOP(n).description,max:n}),pe=D({param:"top_p",title:S.TOP_P.title,description:S.TOP_P.description,min:0,max:1,step:.01,default:1}),he=D({param:"top_k",title:"Top K",description:"Select only from the highest K probabilities for each following word, effectively eliminating the less likely 'long tail' options.",min:0,max:1,step:.01,default:1}),ge=H({param:"tool_choice",title:"Tool choice",description:"Controls which (if any) tool is called by the model. 'any' means the model will call any of the provided tools. 'auto' means the model can pick between generating a message or calling a tool.",default:"auto",choices:["auto","any"]}),Zt=(n,t)=>e.z.object({temperature:me.schema,maxTokens:ce(n).schema,stop:ue(t).schema,topP:pe.schema,topK:he.schema,toolChoice:ge.schema}),Yt=(n,t)=>({temperature:me.def,maxTokens:ce(n).def,stop:ue(t).def,topP:pe.def,topK:he.def,toolChoice:ge.def}),fe=H({param:"encoding_format",title:"Encoding format",description:"Select the encoding format for the word embedding.",default:"none",choices:["base64"]}),ye=H({param:"input_type",title:"Input type",description:"Select the input type for the word embedding.",default:"none",choices:["query","document"]}),be=H({param:"truncation",title:"Truncation",description:"Select the truncation for the word embedding.",default:"none",choices:["true","false"]}),Wt=()=>e.z.object({encodingFormat:fe.schema,inputType:ye.schema,truncation:be.schema}),Xt=()=>({encodingFormat:fe.def,inputType:ye.def,truncation:be.def}),te={base:(n,t)=>({def:Yt(n,t),schema:Zt(n,t)})},ne={base:()=>({def:Xt(),schema:Wt()})},Qt=e.z.enum([A,K,w]),en={system:A,user:K,assistant:w},tn=[b,I,x,_],nn=e.z.enum([b,I,x,_]),No=e.z.object({type:e.z.literal("text"),text:e.z.string()}),Jo=e.z.object({type:e.z.literal("tool_use"),id:e.z.string(),name:e.z.string(),input:e.z.record(e.z.any())}),an=e.z.object({content:e.z.array(e.z.discriminatedUnion("type",[No,Jo])),id:e.z.string(),model:e.z.string(),role:e.z.string(),stop_reason:e.z.string(),stop_sequence:e.z.null(),type:e.z.literal("message"),usage:e.z.object({input_tokens:e.z.number(),output_tokens:e.z.number(),cache_creation_input_tokens:e.z.number().nullish(),cache_read_input_tokens:e.z.number().nullish()})}),on=e.z.object({type:e.z.literal("message_start"),message:e.z.object({id:e.z.string(),type:e.z.literal("message"),role:e.z.string(),model:e.z.string(),stop_reason:e.z.string().nullable(),stop_sequence:e.z.string().nullable(),content:e.z.array(e.z.any()),usage:e.z.object({input_tokens:e.z.number(),output_tokens:e.z.number()})})}),rn=e.z.object({type:e.z.literal("message_delta"),delta:e.z.object({stop_reason:e.z.string().nullable(),stop_sequence:e.z.string().nullable()}),usage:e.z.object({output_tokens:e.z.number()})}),Go=e.z.object({type:e.z.literal("text"),text:e.z.string()}),Vo=e.z.object({type:e.z.literal("tool_use"),id:e.z.string(),name:e.z.string(),input:e.z.object({})}),sn=e.z.object({type:e.z.literal("content_block_start"),index:e.z.number(),content_block:e.z.discriminatedUnion("type",[Go,Vo])}),Zo=e.z.object({type:e.z.literal("text_delta"),text:e.z.string()}),Yo=e.z.object({type:e.z.literal("input_json_delta"),partial_json:e.z.string()}),ln=e.z.object({type:e.z.literal("content_block_delta"),index:e.z.number(),delta:e.z.discriminatedUnion("type",[Zo,Yo])}),Wo=e.z.object({name:e.z.string().min(1),description:e.z.string().min(1).optional(),input_schema:e.z.any()}),Xo=e.z.object({type:e.z.enum(["auto","any"])}),Qo=e.z.object({type:e.z.literal("tool"),name:e.z.string().min(1)}),ze=e.z.object({text:e.z.string().min(1),type:e.z.literal("text")}),dn=e.z.object({type:e.z.literal("image"),source:e.z.object({type:e.z.literal("base64"),media_type:e.z.enum(["image/jpeg","image/png","image/gif","image/webp"]),data:e.z.string().base64()})});e.z.object({id:e.z.string().min(1),type:e.z.literal("tool_use"),name:e.z.string().min(1),input:e.z.record(e.z.any())});var mn=e.z.object({type:e.z.literal("tool_result"),tool_use_id:e.z.string().min(1),content:e.z.string().min(1).or(e.z.array(e.z.union([ze,dn])).min(1))}),ei=e.z.object({role:e.z.literal("user"),content:e.z.string().min(1).or(e.z.array(e.z.union([ze,dn,mn])).min(1))}),ti=e.z.object({role:e.z.literal("assistant"),content:e.z.string().min(1).or(e.z.array(e.z.union([ze,mn])).min(1))}),ni=e.z.union([ei,ti]),ai=e.z.object({model:e.z.string().min(1).optional(),messages:e.z.array(ni).min(1).optional(),system:e.z.string().min(1).optional(),max_tokens:e.z.number().min(0).optional(),stop_sequences:e.z.array(e.z.string().min(1)).optional(),temperature:e.z.number().min(0).max(1).optional(),tool_choice:e.z.union([Xo,Qo]).optional(),tools:e.z.array(Wo).min(1).optional(),top_p:e.z.number().min(0).max(1).optional(),top_k:e.z.number().min(0).optional()}).refine(n=>!(n.tool_choice&&(!n.tools||n.tools.length===0)),{message:"'tools' must be provided if 'tool_choice' is provided",path:["tools"]}),ve=e.z.object({apiKey:e.z.string(),baseUrl:e.z.string().url(),completeChatUrl:e.z.string().url().optional(),streamChatUrl:e.z.string().url().optional()}),cn=class{constructor(n,t){this.version="v1";let a=ve.parse(t);this.modelSchema=n,this.apiKey=a.apiKey,this.baseUrl=$(a.baseUrl),this.completeChatUrl=$(a.completeChatUrl||`${this.baseUrl}/messages`),this.streamChatUrl=$(a.streamChatUrl||`${this.baseUrl}/messages`);}getDefaultBaseUrl(){return this.baseUrl}getDefaultHeaders(){return {"x-api-key":`${this.apiKey}`,"anthropic-version":"2023-06-01","content-type":"application/json"}}getDefaultParams(){return {model:this.modelSchema.name}}getRetryDelay(n){let t=0,a=!0;return n["x-should-retry"]&&(a=n["x-should-retry"].toLowerCase()!=="false"),n["retry-after"]&&(t=parseInt(n["retry-after"])*1e3),{shouldRetry:a,delayMs:t}}getTokenCount(n){return n.reduce((t,a)=>t+a.content.map(i=>i.modality==="text"?i.value:"").join(" ").length,0)}transformModelRequest(n){let t=ai.safeParse(n);if(!t.success)throw new $t({info:"Invalid model request",cause:t.error});let a=t.data,i=a.model,r={maxTokens:a.max_tokens,temperature:a.temperature,topP:a.top_p,topK:a.top_k,stop:a.stop_sequences,toolChoice:a.tool_choice},s=kt().parse(Vt(r)),l=[],d={};a.system&&l.push({role:A,content:[{modality:b,value:a.system}]}),a.messages&&a.messages.forEach(p=>{let g=p.role;switch(g){case"user":{let f=p.content;if(typeof f=="string")l.push({role:g,content:[{modality:b,value:f}]});else {let v=f.map(h=>{if(h.type==="text")return {modality:b,value:h.text};if(h.type==="image"){let V="auto",L=h.source.media_type.split("/")[1];return {modality:I,detail:V,value:{type:Ct,media_type:L,base64:h.source.data}}}else return {modality:_,id:h.tool_use_id,index:d[h.tool_use_id].index,name:d[h.tool_use_id].name,data:typeof h.content=="string"?h.content:JSON.stringify(h.content)}});l.push({role:g,content:v});}}break;case"assistant":{let f=p.content;if(typeof f=="string")l.push({role:g,content:[{modality:b,value:f}]});else {let v=f.map((h,V)=>{if(h.type==="text")return {modality:b,value:h.text};{let L={modality:x,id:h.id,index:V,name:h.name,arguments:JSON.stringify(h.input)};return d[h.id]=L,L}});l.push({role:g,content:v});}}break}});let c=[];return a.tools&&a.tools.forEach(p=>{c.push({type:"function",definition:{schema:{name:p.name,description:p.description||"",parameters:p.input_schema}}});}),{modelName:i,config:s,messages:l,tools:c}}transformConfig(n,t,a){let i=n.toolChoice;delete n.toolChoice;let r=this.modelSchema.config.schema.safeParse(n);if(!r.success)throw new P({info:`Invalid config for model : '${this.modelSchema.name}'`,cause:r.error});let s=r.data;i!==void 0&&(s.toolChoice=i),Object.keys(s).forEach(d=>{if(!(d in this.modelSchema.config.def))throw new P({info:`Invalid config for model : '${this.modelSchema.name}'`,cause:new Error(`Invalid config key : '${d}',
9
+ Message: ${Fa(a)}`),this.name=ee,this.info=t,this.cause=a,this.name=i!=null?i:ee,Object.setPrototypeOf(this,new.target.prototype);}static isGatewayBaseError(t){return t instanceof vt}toJSON(){return {name:this.name,info:this.info,cause:this.cause,message:this.message,stack:this.stack}}},A="system",K="user",w="assistant",Ka="tool",Da=[A,K,w,Ka],wt=e.z.enum(Da),Ha=[w],Na=e.z.enum(Ha),I="image",Ct="base64",Ja=["png","jpeg","webp","gif"],Ga=e.z.object({type:e.z.literal(Ct),base64:e.z.string(),media_type:e.z.enum(Ja)}),Va="url",Za=e.z.object({type:e.z.literal(Va),url:e.z.string()}),Ya=e.z.discriminatedUnion("type",[Ga,Za]),Wa=["low","medium","high","auto"],Xa=e.z.enum(Wa),Qa=(n=e.z.undefined())=>e.z.object({modality:e.z.literal(I),detail:Xa,value:Ya,metadata:n}),b="text",xt=(n=e.z.undefined())=>e.z.object({modality:e.z.literal(b),value:e.z.string(),metadata:n}),ae="partial-text",Tt=(n=e.z.undefined())=>e.z.object({modality:e.z.literal(ae),value:e.z.string(),metadata:n}),x="tool-call",jt=(n=e.z.undefined())=>e.z.object({modality:e.z.literal(x),index:e.z.number().int().nonnegative(),id:e.z.string().min(1),name:e.z.string().min(1),arguments:e.z.string(),metadata:n}),oe="partial-tool-call",Mt=(n=e.z.undefined())=>e.z.object({modality:e.z.literal(oe),index:e.z.number().int().nonnegative(),id:e.z.string().optional(),name:e.z.string().optional(),arguments:e.z.string().optional(),metadata:n}),_="tool-response",eo=(n=e.z.undefined())=>e.z.object({modality:e.z.literal(_),index:e.z.number().int().nonnegative(),id:e.z.string().min(1),name:e.z.string().min(1),data:e.z.string(),metadata:n}),to=[b,I,x,_],no=e.z.enum(to),ao=(n=e.z.undefined(),t=e.z.undefined(),a=e.z.undefined(),i=e.z.undefined())=>e.z.discriminatedUnion("modality",[xt(n),Qa(t),jt(a),eo(i)]),oo=[ae,oe];e.z.enum(oo);var io=(n=e.z.undefined(),t=e.z.undefined())=>e.z.discriminatedUnion("modality",[Tt(n),Mt(t)]),St=(n=wt,t=e.z.undefined(),a=e.z.undefined(),i=e.z.undefined(),r=e.z.undefined(),s=e.z.undefined())=>e.z.object({role:n,content:e.z.array(ao(t,a,i,r)),metadata:s}),ie=(n=Na,t=e.z.undefined(),a=e.z.undefined(),i=e.z.undefined())=>e.z.object({role:n,partialContent:io(t,a),metadata:i}),ro=n=>xt().parse({modality:b,value:n}),so=(n,t,a,i)=>jt().parse({modality:x,index:n,id:t,name:a,arguments:i}),rt=(n,t)=>ie().parse({role:n,partialContent:Tt().parse({modality:ae,value:t})}),st=(n,t,a,i,r)=>ie().parse({role:n,partialContent:Mt().parse({modality:oe,index:t,id:a,name:i,arguments:r})}),kt=(n=e.z.record(e.z.string(),e.z.any()).optional())=>n,lo="function",mo=e.z.enum(["object","array","number","string","boolean","null"]),co=e.z.object({anyOf:e.z.array(e.z.any()).optional(),type:mo.optional(),default:e.z.any().optional(),title:e.z.string().optional(),description:e.z.string().max(4096).optional(),properties:e.z.record(e.z.any()).optional(),required:e.z.array(e.z.string()).optional(),minItems:e.z.number().int().min(0).optional(),maxItems:e.z.number().int().optional(),items:e.z.record(e.z.any()).optional(),enum:e.z.array(e.z.union([e.z.string(),e.z.number(),e.z.boolean(),e.z.null()])).optional(),minimum:e.z.number().optional(),maximum:e.z.number().optional(),minLength:e.z.number().int().min(0).optional(),maxLength:e.z.number().int().optional()});e.z.object({type:e.z.enum(["object"]),title:e.z.string().optional(),$defs:e.z.record(e.z.any()).optional(),properties:e.z.record(co).optional(),required:e.z.array(e.z.string()).optional()});var uo=e.z.object({name:e.z.string().regex(/^[a-zA-Z0-9_]{1,64}$/).max(64),description:e.z.string().max(4096),parameters:e.z.any(),strict:e.z.boolean().optional()}),po=e.z.enum(["function"]),ho=e.z.object({type:po,definition:e.z.object({schema:uo})}),go=[lo];e.z.enum(go);var fo=(n=e.z.undefined())=>e.z.discriminatedUnion("type",[ho.extend({metadata:n})]),R="text",Et="token",yo=[R,Et],bo=e.z.enum(yo),zo=e.z.array(e.z.string().min(1)),vo=e.z.array(e.z.array(e.z.number().int().nonnegative())),wo=(n=e.z.undefined())=>e.z.discriminatedUnion("modality",[e.z.object({modality:e.z.literal(R),metadata:n,requests:zo}),e.z.object({modality:e.z.literal(Et),metadata:n,requests:vo})]),Ot="float",Co=e.z.object({index:e.z.number().int().nonnegative(),embedding:e.z.array(e.z.number())}),Pt="base64",xo=e.z.object({index:e.z.number().int().nonnegative(),embedding:e.z.string().base64()}),lt=e.z.object({totalTokens:e.z.number().int().nonnegative()});e.z.discriminatedUnion("encodingFormat",[e.z.object({encodingFormat:e.z.literal(Ot),embeddings:e.z.array(Co),usage:lt.optional()}),e.z.object({encodingFormat:e.z.literal(Pt),embeddings:e.z.array(xo),usage:lt.optional()})]);var It=e.z.object({promptTokens:e.z.number().nonnegative(),completionTokens:e.z.number().nonnegative(),totalTokens:e.z.number().nonnegative()}),dt=e.z.object({token:e.z.string(),logProb:e.z.number(),bytes:e.z.array(e.z.number().int()).nullable()}),To=dt.extend({topLogProbs:e.z.array(dt)}),_t=e.z.array(To);e.z.object({messages:e.z.array(St()),usage:It.optional(),logProbs:_t.optional()});e.z.object({partialMessages:e.z.array(ie()),usage:It.optional(),logProbs:_t.optional()});var jo=Object.defineProperty,mt=Object.getOwnPropertySymbols,Mo=Object.prototype.hasOwnProperty,So=Object.prototype.propertyIsEnumerable,ct=(n,t,a)=>t in n?jo(n,t,{enumerable:!0,configurable:!0,writable:!0,value:a}):n[t]=a,re=(n,t)=>{for(var a in t||(t={}))Mo.call(t,a)&&ct(n,a,t[a]);if(mt)for(var a of mt(t))So.call(t,a)&&ct(n,a,t[a]);return n},ut="ProviderError",q=class Rt extends k{constructor({info:t,cause:a}){super({info:t,cause:a},ut),this.name=ut,this.info=t,this.cause=a;}static isProviderError(t){return t instanceof Rt}},pt="ModelResponseError",j=class Ut extends k{constructor({info:t,cause:a}){super({info:t,cause:a},pt),this.name=pt,this.cause=a,this.info=t;}static isModelResponseError(t){return t instanceof Ut}},ht="InvalidModelRequestError",$t=class At extends k{constructor({info:t,cause:a}){super({info:t,cause:a},ht),this.name=ht,this.cause=a,this.info=t,Object.setPrototypeOf(this,new.target.prototype);}static isInvalidModelRequestError(t){return t instanceof At}},gt="InvalidConfigError",P=class Lt extends k{constructor({info:t,cause:a}){super({info:t,cause:a},gt),this.name=gt,this.cause=a,this.info=t,Object.setPrototypeOf(this,new.target.prototype);}static isInvalidConfigError(t){return t instanceof Lt}},ft="InvalidMessagesError",C=class Bt extends k{constructor({info:t,cause:a}){super({info:t,cause:a},ft),this.name=ft,this.cause=a,this.info=t,Object.setPrototypeOf(this,new.target.prototype);}static isInvalidMessagesError(t){return t instanceof Bt}},yt="InvalidToolsError",bt=class qt extends k{constructor({info:t,cause:a}){super({info:t,cause:a},yt),this.name=yt,this.cause=a,this.info=t,Object.setPrototypeOf(this,new.target.prototype);}static isInvalidToolsError(t){return t instanceof qt}},zt="InvalidEmbeddingRequestsError",ko=class Ft extends k{constructor({info:t,cause:a}){super({info:t,cause:a},zt),this.name=zt,this.info=t,this.cause=a,Object.setPrototypeOf(this,new.target.prototype);}static isInvalidEmbeddingRequestsError(t){return t instanceof Ft}},se="multi-string",Kt=e.z.object({type:e.z.literal(se),param:e.z.string().min(1),title:e.z.string().min(1),description:e.z.string().min(1).max(500),max:e.z.number().int().positive()}),Eo=n=>e.z.array(e.z.string()).max(n).default([]).optional(),Oo=n=>({def:Kt.parse(re({type:se},n)),schema:Eo(n.max)}),le="range",Dt=e.z.object({type:e.z.literal(le),param:e.z.string().min(1),title:e.z.string().min(1),description:e.z.string().min(1).max(500),min:e.z.number().int(),max:e.z.number().int(),step:e.z.number().positive(),default:e.z.number().int()}),Po=(n,t,a,i)=>e.z.number().min(n).max(t).step(a).default(i).optional(),D=n=>({def:Dt.parse(re({type:le},n)),schema:Po(n.min,n.max,n.step,n.default)}),de="select-string",Ht=e.z.object({type:e.z.literal(de),param:e.z.string().min(1),title:e.z.string().min(1),description:e.z.string().min(1).max(500),default:e.z.string().min(1),choices:e.z.array(e.z.string().min(1))}),Io=(n,t)=>e.z.enum(t).default(n).optional(),H=n=>({def:Ht.parse(re({type:de},n)),schema:Io(n.default,n.choices)}),Nt="object-schema",_o=e.z.object({type:e.z.literal(Nt),param:e.z.string().min(1),title:e.z.string().min(1),description:e.z.string().min(1).max(500),objectSchema:e.z.any()}),Jt="select-boolean",Ro=e.z.object({type:e.z.literal(Jt),param:e.z.string().min(1),title:e.z.string().min(1),description:e.z.string().min(1).max(500),default:e.z.boolean().nullable()}),Uo=[le,se,de,Nt,Jt];e.z.enum(Uo);var Gt=e.z.discriminatedUnion("type",[Dt,Kt,Ht,Ro,_o]),$o=(n=wt,t=no)=>e.z.object({name:e.z.string().min(1),description:e.z.string().min(1),roles:e.z.record(n,e.z.string().min(1).optional()),modalities:e.z.array(t).nonempty(),maxInputTokens:e.z.number().int().positive().min(1),maxOutputTokens:e.z.number().int().positive().min(1),config:e.z.object({def:e.z.record(e.z.string().min(1),Gt),schema:e.z.instanceof(e.z.ZodObject)}).refine(a=>{var i,r;let s=Object.keys(a.def),l=Object.keys((r=(i=a.schema)==null?void 0:i.shape)!=null?r:{});return s.every(d=>l.includes(d))&&l.every(d=>s.includes(d))},{message:"Keys in 'config.def' must exactly match keys in 'config.schema'"})}),Ao=(n=bo)=>e.z.object({name:e.z.string().min(1),description:e.z.string().min(1),modalities:e.z.array(n).nonempty(),maxInputTokens:e.z.number().int().positive().min(1),maxOutputTokens:e.z.number().int().positive().min(1),config:e.z.object({def:e.z.record(e.z.string().min(1),Gt),schema:e.z.instanceof(e.z.ZodObject)}).refine(t=>{var a,i;let r=Object.keys(t.def),s=Object.keys((i=(a=t.schema)==null?void 0:a.shape)!=null?i:{});return r.every(l=>s.includes(l))&&s.every(l=>r.includes(l))},{message:"Keys in 'config.def' must exactly match keys in 'config.schema'"})});e.z.record(e.z.string());e.z.record(e.z.union([e.z.boolean(),e.z.string(),e.z.number(),e.z.object({}),e.z.array(e.z.any()),e.z.null(),e.z.undefined()]));e.z.string().url();var Lo={type:"range",title:"Temperature",description:"Adjusts the model's creativity level. With a setting of 0, the model strictly picks the most probable next word. For endeavors that benefit from a dash of inventiveness, consider dialing it up to 0.7 or higher, enabling the model to produce text that's unexpectedly fresh."},Bo={type:"range",title:"Max tokens",description:"Specify the total tokens for generation, where one token approximates four English characters. Setting this to 0 defaults to the model's maximum capacity."},qo=n=>({type:"multi",title:"Stop sequence",description:`Enter up to ${n} sequences that will halt additional text output. The generated text will exclude these sequences.`}),Fo={type:"range",title:"Top P",description:"Selects a subset of likely tokens for generation, restricting choices to the top-P fraction of possibilities, such as the top 10% when P=0.1. This approach can limit the variety of the output. By default, it's set to 1, indicating no restriction. It's advised to adjust this parameter or temperature to modulate output diversity, but not to modify both simultaneously."},Ko={type:"range",title:"Top K",description:"Select only from the highest K probabilities for each following word, effectively eliminating the less likely 'long tail' options."},Do={type:"range",title:"Frequency penalty",description:"Minimize redundancy. By assigning a penalty to frequently used tokens within the text, the likelihood of repeating identical phrases is reduced. The default setting for this penalty is zero."},Ho={type:"range",title:"Presence penalty",description:"Enhance the introduction of novel subjects by reducing the preference for tokens that have already appeared in the text, thus boosting the chances of exploring fresh topics. The standard setting for this is zero."},S={TEMPERATURE:Lo,MAX_TOKENS:Bo,STOP:qo,TOP_P:Fo,TOP_K:Ko,FREQUENCY_PENALTY:Do,PRESENCE_PENALTY:Ho},Vt=n=>Object.fromEntries(Object.entries(n).filter(([t,a])=>a!=null)),$=n=>n==null?void 0:n.replace(/\/$/,""),me=D({param:"temperature",title:S.TEMPERATURE.title,description:S.TEMPERATURE.description,min:0,max:1,step:.01,default:1}),ce=n=>D({param:"max_tokens",title:S.MAX_TOKENS.title,description:S.MAX_TOKENS.description,min:0,max:n,step:1,default:0}),ue=n=>Oo({param:"stop_sequences",title:S.STOP(n).title,description:S.STOP(n).description,max:n}),pe=D({param:"top_p",title:S.TOP_P.title,description:S.TOP_P.description,min:0,max:1,step:.01,default:1}),he=D({param:"top_k",title:"Top K",description:"Select only from the highest K probabilities for each following word, effectively eliminating the less likely 'long tail' options.",min:0,max:1,step:.01,default:1}),ge=H({param:"tool_choice",title:"Tool choice",description:"Controls which (if any) tool is called by the model. 'any' means the model will call any of the provided tools. 'auto' means the model can pick between generating a message or calling a tool.",default:"auto",choices:["auto","any"]}),Zt=(n,t)=>e.z.object({temperature:me.schema,maxTokens:ce(n).schema,stop:ue(t).schema,topP:pe.schema,topK:he.schema,toolChoice:ge.schema}),Yt=(n,t)=>({temperature:me.def,maxTokens:ce(n).def,stop:ue(t).def,topP:pe.def,topK:he.def,toolChoice:ge.def}),fe=H({param:"encoding_format",title:"Encoding format",description:"Select the encoding format for the word embedding.",default:"none",choices:["base64"]}),ye=H({param:"input_type",title:"Input type",description:"Select the input type for the word embedding.",default:"none",choices:["query","document"]}),be=H({param:"truncation",title:"Truncation",description:"Select the truncation for the word embedding.",default:"none",choices:["true","false"]}),Wt=()=>e.z.object({encodingFormat:fe.schema,inputType:ye.schema,truncation:be.schema}),Xt=()=>({encodingFormat:fe.def,inputType:ye.def,truncation:be.def}),te={base:(n,t)=>({def:Yt(n,t),schema:Zt(n,t)})},ne={base:()=>({def:Xt(),schema:Wt()})},Qt=e.z.enum([A,K,w]),en={system:A,user:K,assistant:w},tn=[b,I,x,_],nn=e.z.enum([b,I,x,_]),No=e.z.object({type:e.z.literal("text"),text:e.z.string()}),Jo=e.z.object({type:e.z.literal("tool_use"),id:e.z.string(),name:e.z.string(),input:e.z.record(e.z.any())}),an=e.z.object({content:e.z.array(e.z.discriminatedUnion("type",[No,Jo])),id:e.z.string(),model:e.z.string(),role:e.z.string(),stop_reason:e.z.string(),stop_sequence:e.z.null(),type:e.z.literal("message"),usage:e.z.object({input_tokens:e.z.number(),output_tokens:e.z.number(),cache_creation_input_tokens:e.z.number().nullish(),cache_read_input_tokens:e.z.number().nullish()})}),on=e.z.object({type:e.z.literal("message_start"),message:e.z.object({id:e.z.string(),type:e.z.literal("message"),role:e.z.string(),model:e.z.string(),stop_reason:e.z.string().nullable(),stop_sequence:e.z.string().nullable(),content:e.z.array(e.z.any()),usage:e.z.object({input_tokens:e.z.number(),output_tokens:e.z.number()})})}),rn=e.z.object({type:e.z.literal("message_delta"),delta:e.z.object({stop_reason:e.z.string().nullable(),stop_sequence:e.z.string().nullable()}),usage:e.z.object({output_tokens:e.z.number()})}),Go=e.z.object({type:e.z.literal("text"),text:e.z.string()}),Vo=e.z.object({type:e.z.literal("tool_use"),id:e.z.string(),name:e.z.string(),input:e.z.object({})}),sn=e.z.object({type:e.z.literal("content_block_start"),index:e.z.number(),content_block:e.z.discriminatedUnion("type",[Go,Vo])}),Zo=e.z.object({type:e.z.literal("text_delta"),text:e.z.string()}),Yo=e.z.object({type:e.z.literal("input_json_delta"),partial_json:e.z.string()}),ln=e.z.object({type:e.z.literal("content_block_delta"),index:e.z.number(),delta:e.z.discriminatedUnion("type",[Zo,Yo])}),Wo=e.z.object({name:e.z.string().min(1),description:e.z.string().min(1).optional(),input_schema:e.z.any()}),Xo=e.z.object({type:e.z.enum(["auto","any"])}),Qo=e.z.object({type:e.z.literal("tool"),name:e.z.string().min(1)}),ze=e.z.object({text:e.z.string().min(1),type:e.z.literal("text")}),dn=e.z.object({type:e.z.literal("image"),source:e.z.object({type:e.z.literal("base64"),media_type:e.z.enum(["image/jpeg","image/png","image/gif","image/webp"]),data:e.z.string().base64()})});e.z.object({id:e.z.string().min(1),type:e.z.literal("tool_use"),name:e.z.string().min(1),input:e.z.record(e.z.any())});var mn=e.z.object({type:e.z.literal("tool_result"),tool_use_id:e.z.string().min(1),content:e.z.string().min(1).or(e.z.array(e.z.union([ze,dn])).min(1))}),ei=e.z.object({role:e.z.literal("user"),content:e.z.string().min(1).or(e.z.array(e.z.union([ze,dn,mn])).min(1))}),ti=e.z.object({role:e.z.literal("assistant"),content:e.z.string().min(1).or(e.z.array(e.z.union([ze,mn])).min(1))}),ni=e.z.union([ei,ti]),ai=e.z.object({model:e.z.string().min(1).optional(),messages:e.z.array(ni).min(1),system:e.z.string().min(1).optional(),max_tokens:e.z.number().min(0).optional(),stop_sequences:e.z.array(e.z.string().min(1)).optional(),temperature:e.z.number().min(0).max(1).optional(),tool_choice:e.z.union([Xo,Qo]).optional(),tools:e.z.array(Wo).min(1).optional(),top_p:e.z.number().min(0).max(1).optional(),top_k:e.z.number().min(0).optional()}).refine(n=>!(n.tool_choice&&(!n.tools||n.tools.length===0)),{message:"'tools' must be provided if 'tool_choice' is provided",path:["tools"]}),ve=e.z.object({apiKey:e.z.string(),baseUrl:e.z.string().url(),completeChatUrl:e.z.string().url().optional(),streamChatUrl:e.z.string().url().optional()}),cn=class{constructor(n,t){this.version="v1";let a=ve.parse(t);this.modelSchema=n,this.apiKey=a.apiKey,this.baseUrl=$(a.baseUrl),this.completeChatUrl=$(a.completeChatUrl||`${this.baseUrl}/messages`),this.streamChatUrl=$(a.streamChatUrl||`${this.baseUrl}/messages`);}getDefaultBaseUrl(){return this.baseUrl}getDefaultHeaders(){return {"x-api-key":`${this.apiKey}`,"anthropic-version":"2023-06-01","content-type":"application/json"}}getDefaultParams(){return {model:this.modelSchema.name}}getRetryDelay(n){let t=0,a=!0;return n["x-should-retry"]&&(a=n["x-should-retry"].toLowerCase()!=="false"),n["retry-after"]&&(t=parseInt(n["retry-after"])*1e3),{shouldRetry:a,delayMs:t}}getTokenCount(n){return n.reduce((t,a)=>t+a.content.map(i=>i.modality==="text"?i.value:"").join(" ").length,0)}transformModelRequest(n){let t=ai.safeParse(n);if(!t.success)throw new $t({info:"Invalid model request",cause:t.error});let a=t.data,i=a.model,r={};a.tool_choice&&(a.tool_choice.type==="tool"?r.toolChoice=a.tool_choice.name:r.toolChoice=a.tool_choice.type),r.maxTokens=a.max_tokens,r.temperature=a.temperature,r.topP=a.top_p,r.topK=a.top_k,r.stop=a.stop_sequences;let s=kt().parse(Vt(r)),l=[],d={};a.system&&l.push({role:A,content:[{modality:b,value:a.system}]}),a.messages.forEach(p=>{let g=p.role;switch(g){case"user":{let f=p.content;if(typeof f=="string")l.push({role:g,content:[{modality:b,value:f}]});else {let v=f.map(h=>{if(h.type==="text")return {modality:b,value:h.text};if(h.type==="image"){let V="auto",L=h.source.media_type.split("/")[1];return {modality:I,detail:V,value:{type:Ct,media_type:L,base64:h.source.data}}}else return {modality:_,id:h.tool_use_id,index:d[h.tool_use_id].index,name:d[h.tool_use_id].name,data:typeof h.content=="string"?h.content:JSON.stringify(h.content)}});l.push({role:g,content:v});}}break;case"assistant":{let f=p.content;if(typeof f=="string")l.push({role:g,content:[{modality:b,value:f}]});else {let v=f.map((h,V)=>{if(h.type==="text")return {modality:b,value:h.text};{let L={modality:x,id:h.id,index:V,name:h.name,arguments:JSON.stringify(h.input)};return d[h.id]=L,L}});l.push({role:g,content:v});}}break}});let c=[];return a.tools&&a.tools.forEach(p=>{c.push({type:"function",definition:{schema:{name:p.name,description:p.description||"",parameters:p.input_schema}}});}),{modelName:i,config:s,messages:l,tools:c.length>0?c:void 0}}transformConfig(n,t,a){let i=n.toolChoice;delete n.toolChoice;let r=this.modelSchema.config.schema.safeParse(n);if(!r.success)throw new P({info:`Invalid config for model : '${this.modelSchema.name}'`,cause:r.error});let s=r.data;i!==void 0&&(s.toolChoice=i),Object.keys(s).forEach(d=>{if(!(d in this.modelSchema.config.def))throw new P({info:`Invalid config for model : '${this.modelSchema.name}'`,cause:new Error(`Invalid config key : '${d}',
10
10
  available keys : [${Object.keys(this.modelSchema.config.def).join(", ")}]`)})});let l=Object.keys(s).reduce((d,c)=>{let p=this.modelSchema.config.def[c],g=p.param,f=s[c];return g==="max_tokens"&&p.type==="range"&&f===0?d[g]=p.max:d[g]=f,d},{});if("tool_choice"in l&&l.tool_choice!==void 0){let d=l.tool_choice;if(!a||a&&a.length===0)throw new P({info:`Invalid config for model : '${this.modelSchema.name}'`,cause:new Error("'tools' are required when 'toolChoice' is specified")});if(a&&a.length>0){let c=this.modelSchema.config.def.toolChoice;if(!c.choices.includes(d))if(a.map(p=>p.definition.schema.name).includes(d))l.tool_choice={type:"tool",name:d};else throw new P({info:`Invalid config for model : '${this.modelSchema.name}'`,cause:new Error(`toolChoice : '${d}' is not part of provided 'tools' names or
11
11
  one of [${c.choices.join(", ")}]`)})}}return l}transformMessages(n){if(!n||n&&n.length===0)return {messages:[]};let t=n.map(r=>{let s=St().safeParse(r);if(!s.success)throw new C({info:"Invalid messages",cause:s.error});return s.data});t.forEach(r=>{r.content.forEach(s=>{if(!this.modelSchema.modalities.includes(s.modality))throw new C({info:`Invalid message content for model : '${this.modelSchema.name}'`,cause:new Error(`model : '${this.modelSchema.name}' does not support modality : '${s.modality}',
12
12
  available modalities : [${this.modelSchema.modalities.join(", ")}]`)})});});let a="",i=[];return t.forEach(r=>{switch(r.role){case A:r.content.forEach(s=>{if(s.modality===b)a+=s.value;else throw new C({info:`Invalid message 'role' and 'modality' combination for model : ${this.modelSchema.name}`,cause:new Error(`role : '${r.role}' cannot have content with modality : '${s.modality}'`)})});break;case w:{let s=[];r.content.forEach(l=>{if(l.modality===b)s.push({type:"text",text:l.value});else if(l.modality===x)s.push({type:"tool_use",id:l.id,name:l.name,input:JSON.parse(l.arguments)});else throw new C({info:`Invalid message 'role' and 'modality' combination for model : ${this.modelSchema.name}`,cause:new Error(`role : '${r.role}' cannot have content with modality : '${l.modality}'`)})}),i.push({role:this.modelSchema.roles[r.role],content:s});}break;case K:{let s=[];r.content.forEach(l=>{if(l.modality===b)s.push({type:"text",text:l.value});else if(l.modality===I){if(l.value.type==="base64")s.push({type:"image",source:{type:"base64",media_type:`image/${l.value.media_type}`,data:l.value.base64}});else if(l.value.type==="url")throw new C({info:`Invalid message 'modality' for model : ${this.modelSchema.name}`,cause:new Error(`model: '${this.modelSchema.name}' does not support image content type: '${l.value.type}'`)})}else if(l.modality===_)s.push({type:"tool_result",tool_use_id:l.id,content:l.data});else throw new C({info:`Invalid message 'role' and 'modality' combination for model : ${this.modelSchema.name}`,cause:new Error(`role : '${r.role}' cannot have content with modality : '${l.modality}'`)})}),i.push({role:this.modelSchema.roles[r.role],content:s});}break;default:throw new C({info:`Invalid message 'role' for model : ${this.modelSchema.name}`,cause:new Error(`role : '${r.role}' is not supported,
13
13
  available roles : [${Object.keys(this.modelSchema.roles).join(", ")}]`)})}}),{system:a,messages:i}}transformTools(n){if(!this.modelSchema.modalities.includes(x))throw new bt({info:`Invalid tool 'modality' for model : ${this.modelSchema.name}`,cause:new Error(`model : '${this.modelSchema.name}' does not support tool modality : '${x}'`)});return !n||n&&n.length===0?{tools:[]}:{tools:n.map(t=>{let a=fo().safeParse(t);if(!a.success)throw new bt({info:"Invalid tools",cause:a.error});return a.data}).map(t=>({name:t.definition.schema.name,description:t.definition.schema.description,function:t.definition.schema}))}}getCompleteChatUrl(n,t,a){return M(this,null,function*(){return new Promise(i=>{i(this.completeChatUrl);})})}getCompleteChatHeaders(n,t,a){return M(this,null,function*(){let i=this.getDefaultHeaders();return a&&a.length>0&&(i=F(y({},i),{"anthropic-beta":"tools-2024-05-16"})),new Promise(r=>{r(i);})})}getCompleteChatData(n,t,a){return M(this,null,function*(){let i=this.transformConfig(n,t,a),r=this.transformMessages(t);if(r.messages&&r.messages.length===0)throw new C({info:"Messages are required",cause:new Error("Messages are required")});let s=a?this.transformTools(a):{};return new Promise(l=>{l(y(y(y(y({},this.getDefaultParams()),i),r),s));})})}transformCompleteChatResponse(n){let t=an.safeParse(n);if(t.success){let a=t.data,i=a.content.map((l,d)=>{if(l.type==="text")return ro(l.text);if(l.type==="tool_use")return so(d,l.id,l.name,JSON.stringify(l.input))}),r=[{role:w,content:i}],s={promptTokens:a.usage.input_tokens,completionTokens:a.usage.output_tokens,totalTokens:a.usage.input_tokens+a.usage.output_tokens};return {messages:r,usage:s,logProbs:[]}}throw new j({info:"Invalid response from model",cause:t.error})}getStreamChatUrl(n,t,a){return M(this,null,function*(){return new Promise(i=>{i(this.streamChatUrl);})})}getStreamChatHeaders(n,t,a){let i=this.getDefaultHeaders();return a&&a.length>0&&(i=F(y({},i),{"anthropic-beta":"tools-2024-05-16"})),new Promise(r=>{r(i);})}getStreamChatData(n,t,a){return M(this,null,function*(){let i=this.transformConfig(n,t,a),r=this.transformMessages(t);if(r.messages&&r.messages.length===0)throw new C({info:"Messages are required",cause:new Error("Messages are required")});let s=a?this.transformTools(a):{};return new Promise(l=>{l(y(y(y(y({stream:!0},this.getDefaultParams()),i),r),s));})})}transformStreamChatResponseChunk(n,t){return qa(this,null,function*(){let a=(t+n).split(`
14
14
  `).filter(i=>i.trim()!=="");for(let i of a)if(i.startsWith("data: {")&&i.endsWith("}")){let r;try{r=JSON.parse(i.substring(6));}catch(s){throw new j({info:"Malformed JSON received in stream",cause:new Error(`Malformed JSON received in stream : ${r}`)})}if("type"in r){if(r.type==="message_stop")return;if(r.type==="message_start"){let s=on.safeParse(r);if(s.success){let l=s.data;yield {partialResponse:{partialMessages:[],usage:{promptTokens:l.message.usage.input_tokens,completionTokens:l.message.usage.output_tokens,totalTokens:l.message.usage.input_tokens+l.message.usage.output_tokens}},buffer:t};}else throw new j({info:"Invalid response from model",cause:s.error})}else if(r.type==="message_delta"){let s=rn.safeParse(r);if(s.success){let l=s.data;yield {partialResponse:{partialMessages:[],usage:{promptTokens:0,completionTokens:l.usage.output_tokens,totalTokens:l.usage.output_tokens}},buffer:t};}else throw new j({info:"Invalid response from model",cause:s.error})}else if(r.type==="content_block_start"){let s=sn.safeParse(r);if(s.success){let l=s.data,d=[];l.content_block.type==="text"?d.push(rt(w,l.content_block.text)):l.content_block.type==="tool_use"&&d.push(st(w,l.index,l.content_block.id,l.content_block.name,"")),yield {partialResponse:{partialMessages:d},buffer:t};}else throw new j({info:"Invalid response from model",cause:s.error})}else if(r.type==="content_block_delta"){let s=ln.safeParse(r);if(s.success){let l=s.data,d=[];l.delta.type==="text_delta"?d.push(rt(w,l.delta.text)):l.delta.type==="input_json_delta"&&d.push(st(w,l.index,"","",l.delta.partial_json)),yield {partialResponse:{partialMessages:d},buffer:t};}else throw new j({info:"Invalid response from model",cause:s.error})}}else throw new j({info:"Invalid JSON received in stream",cause:new Error(`Invalid JSON received in stream, expected 'type' property,
15
- received : ${JSON.stringify(r)}`)})}})}},oi="claude-3-haiku-20240307",ii="Claude 3 Haiku is a large-scale multimodal model trained by Anthropic. It is the successor to Claude 3 and is designed to be more powerful and capable than its predecessor.",we=$o(Qt,nn).parse({name:oi,description:ii,maxInputTokens:128e3,maxOutputTokens:128e3,roles:en,modalities:tn,config:{def:te.base(128e3,4).def,schema:te.base(128e3,4).schema}}),un=ve,pn=class extends cn{constructor(n){super(we,n);}},hn=[R],gn=e.z.enum([R]),fn=e.z.object({object:e.z.literal("list"),model:e.z.string(),data:e.z.array(e.z.object({index:e.z.number(),object:e.z.literal("embedding"),embedding:e.z.array(e.z.number()).or(e.z.string().base64())})),usage:e.z.object({total_tokens:e.z.number()})}),yn=e.z.string().min(1).or(e.z.array(e.z.string().min(1)).min(1)),bn=e.z.object({model:e.z.string().min(1).optional(),input:yn.optional(),encoding_format:e.z.enum(["base64"]).nullable().optional(),input_type:e.z.enum(["query","document"]).nullable().optional(),truncation:e.z.boolean().optional()}),Ce=e.z.object({apiKey:e.z.string(),baseUrl:e.z.string().url(),getEmbeddingsUrl:e.z.string().url().optional()}),zn=class{constructor(n,t){this.version="v1";let a=Ce.parse(t);this.modelSchema=n,this.apiKey=a.apiKey,this.baseUrl=$(a.baseUrl),this.getEmbeddingsUrl=$(a.getEmbeddingsUrl||`${this.baseUrl}/embeddings`);}getDefaultBaseUrl(){return this.baseUrl}getDefaultHeaders(){return {Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"}}getDefaultParams(){return {model:this.modelSchema.name}}getTokenCount(n){return n.requests.reduce((t,a)=>t+a.length,0)}getRetryDelay(n){return {shouldRetry:!0,delayMs:0}}transformModelRequest(n){let t=bn.safeParse(n);if(!t.success)throw new $t({info:"Invalid model request",cause:t.error});let a=t.data,i=a.model,r={encodingFormat:a.encoding_format,inputType:a.input_type,truncation:a.truncation},s=kt().parse(Vt(r)),l;return a.input&&(typeof a.input=="string"?l={modality:R,requests:[a.input]}:l={modality:R,requests:a.input}),{modelName:i,config:s,embeddingRequests:l}}transformConfig(n,t){let a=this.modelSchema.config.schema.safeParse(n);if(!a.success)throw new P({info:`Invalid config for model : '${this.modelSchema.name}'`,cause:a.error});let i=a.data;return Object.keys(i).forEach(r=>{if(!this.modelSchema.config.def[r])throw new P({info:`Invalid config for model : '${this.modelSchema.name}'`,cause:new Error(`Invalid config key : '${r}',
15
+ received : ${JSON.stringify(r)}`)})}})}},oi="claude-3-haiku-20240307",ii="Claude 3 Haiku is a large-scale multimodal model trained by Anthropic. It is the successor to Claude 3 and is designed to be more powerful and capable than its predecessor.",we=$o(Qt,nn).parse({name:oi,description:ii,maxInputTokens:128e3,maxOutputTokens:128e3,roles:en,modalities:tn,config:{def:te.base(128e3,4).def,schema:te.base(128e3,4).schema}}),un=ve,pn=class extends cn{constructor(n){super(we,n);}},hn=[R],gn=e.z.enum([R]),fn=e.z.object({object:e.z.literal("list"),model:e.z.string(),data:e.z.array(e.z.object({index:e.z.number(),object:e.z.literal("embedding"),embedding:e.z.array(e.z.number()).or(e.z.string().base64())})),usage:e.z.object({total_tokens:e.z.number()})}),yn=e.z.string().min(1).or(e.z.array(e.z.string().min(1)).min(1)),bn=e.z.object({model:e.z.string().min(1).optional(),input:yn,encoding_format:e.z.enum(["base64"]).nullable().optional(),input_type:e.z.enum(["query","document"]).nullable().optional(),truncation:e.z.boolean().optional()}),Ce=e.z.object({apiKey:e.z.string(),baseUrl:e.z.string().url(),getEmbeddingsUrl:e.z.string().url().optional()}),zn=class{constructor(n,t){this.version="v1";let a=Ce.parse(t);this.modelSchema=n,this.apiKey=a.apiKey,this.baseUrl=$(a.baseUrl),this.getEmbeddingsUrl=$(a.getEmbeddingsUrl||`${this.baseUrl}/embeddings`);}getDefaultBaseUrl(){return this.baseUrl}getDefaultHeaders(){return {Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"}}getDefaultParams(){return {model:this.modelSchema.name}}getTokenCount(n){return n.requests.reduce((t,a)=>t+a.length,0)}getRetryDelay(n){return {shouldRetry:!0,delayMs:0}}transformModelRequest(n){let t=bn.safeParse(n);if(!t.success)throw new $t({info:"Invalid model request",cause:t.error});let a=t.data,i=a.model,r={encodingFormat:a.encoding_format,inputType:a.input_type,truncation:a.truncation},s=kt().parse(Vt(r)),l;return typeof a.input=="string"?l={modality:R,requests:[a.input]}:l={modality:R,requests:a.input},{modelName:i,config:s,embeddingRequests:l}}transformConfig(n,t){let a=this.modelSchema.config.schema.safeParse(n);if(!a.success)throw new P({info:`Invalid config for model : '${this.modelSchema.name}'`,cause:a.error});let i=a.data;return Object.keys(i).forEach(r=>{if(!this.modelSchema.config.def[r])throw new P({info:`Invalid config for model : '${this.modelSchema.name}'`,cause:new Error(`Invalid config key : '${r}',
16
16
  available keys : [${Object.keys(this.modelSchema.config.def).join(", ")}]`)})}),Object.keys(i).reduce((r,s)=>{let l=this.modelSchema.config.def[s].param,d=i[s];return r[l]=d,r},{})}transformEmbeddingRequests(n){let t=wo().safeParse(n);if(!t.success)throw new ko({info:"Invalid embedding requests",cause:t.error});return {input:t.data.requests}}getGetEmbeddingsUrl(n,t){return M(this,null,function*(){return new Promise(a=>{a(this.getEmbeddingsUrl);})})}getGetEmbeddingsHeaders(n,t){return M(this,null,function*(){return new Promise(a=>{a(this.getDefaultHeaders());})})}getGetEmbeddingsData(n,t){return M(this,null,function*(){return new Promise(a=>{a(y(y(y({},this.getDefaultParams()),this.transformConfig(n,t)),this.transformEmbeddingRequests(t)));})})}transformGetEmbeddingsResponse(n){let t,a=fn.safeParse(n);if(a.success){let i=a.data;t=typeof i.data[0].embedding=="string"?Pt:Ot;let r=i.data.map(s=>typeof s.embedding=="string"?{index:s.index,embedding:s.embedding}:{index:s.index,embedding:s.embedding});return {encodingFormat:t,embeddings:r,usage:{totalTokens:i.usage.total_tokens}}}throw new j({info:"Invalid response from model",cause:a.error})}},ri="voyage-2",si="some description",xe=Ao(gn).parse({name:ri,description:si,modalities:hn,maxInputTokens:8192,maxOutputTokens:8192,config:{def:ne.base().def,schema:ne.base().schema}}),vn=Ce,wn=class extends zn{constructor(n){super(xe,n);}},Cn="anthropic",li=class{constructor(){this.version="v1",this.name=Cn,this.chatBaseUrl="https://api.anthropic.com/v1",this.embeddingBaseUrl="https://api.anthropic.com/v1",this.chatModelFactories={"claude-3-haiku-20240307":{model:pn,modelOptions:un,modelSchema:we}},this.embeddingModelFactories={"voyage-2":{model:wn,modelOptions:vn,modelSchema:xe}};}chatModelLiterals(){return Object.keys(this.chatModelFactories)}chatModel(n,t){var a;if(!(n in this.chatModelFactories))throw new q({info:`Anthropic chat model: ${n} not found`,cause:new Error(`Anthropic chat model: ${n} not found, available chat models:
17
17
  ${this.chatModelLiterals().join(", ")}`)});let i=this.chatModelFactories[n].model,r=F(y({},t),{baseUrl:(a=t.baseUrl)!=null?a:this.chatBaseUrl}),s=this.chatModelFactories[n].modelOptions.parse(r);return new i(s)}chatModelSchema(n){if(!(n in this.chatModelFactories))throw new q({info:`Anthropic chat model: ${n} not found`,cause:new Error(`Anthropic chat model: ${n} not found, available chat models:
18
18
  ${this.chatModelLiterals().join(", ")}`)});return this.chatModelFactories[n].modelSchema}chatModelSchemas(){return Object.keys(this.chatModelFactories).reduce((n,t)=>(n[t]=this.chatModelFactories[t].modelSchema,n),{})}embeddingModelLiterals(){return Object.keys(this.embeddingModelFactories)}embeddingModel(n,t){var a;if(!(n in this.embeddingModelFactories))throw new q({info:`Anthropic embedding model: ${n} not found`,cause:new Error(`Anthropic embedding model: ${n} not found, available embedding models: