@adaline/bedrock 0.7.3 → 0.8.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 CHANGED
@@ -5,3 +5,5 @@
5
5
  ![ESLint](https://img.shields.io/badge/ESLint-passing-brightgreen.svg)
6
6
  ![NPM](https://img.shields.io/npm/l/@adaline/bedrock)
7
7
  [![NPM version](https://img.shields.io/npm/v/@adaline/bedrock.svg)](https://npmjs.org/package/@adaline/bedrock)
8
+
9
+ ##
package/dist/index.d.mts CHANGED
@@ -86,7 +86,7 @@ declare const BedrockClaude3Haiku20240307Schema: {
86
86
  param: string;
87
87
  title: string;
88
88
  description: string;
89
- default: string;
89
+ default: string | null;
90
90
  choices: string[];
91
91
  } | {
92
92
  type: "object-schema";
package/dist/index.d.ts CHANGED
@@ -86,7 +86,7 @@ declare const BedrockClaude3Haiku20240307Schema: {
86
86
  param: string;
87
87
  title: string;
88
88
  description: string;
89
- default: string;
89
+ default: string | null;
90
90
  choices: string[];
91
91
  } | {
92
92
  type: "object-schema";
package/dist/index.js CHANGED
@@ -5,31 +5,31 @@ var sha256Js = require('@aws-crypto/sha256-js');
5
5
  var protocolHttp = require('@smithy/protocol-http');
6
6
  var signatureV4 = require('@smithy/signature-v4');
7
7
 
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,j=(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,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of On(t))!Oe.call(n,i)&&i!==a&&Z(n,i,{get:()=>t[i],enumerable:!(r=En(t,i))||r.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 L=(n,t,a)=>In(Ee(n),a,t);var O=(n,t,a)=>new Promise((r,i)=>{var s=c=>{try{d(a.next(c));}catch(p){i(p);}},l=c=>{try{d(a.throw(c));}catch(p){i(p);}},d=c=>c.done?r(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 r=(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?r(l==="return"?l:"next",d[1]?{done:h.done,value:h.value}:h,c,p):c({value:h,done:v})).catch(h=>r("throw",h,c,p));}catch(h){p(h);}},i=l=>s[l]=d=>new Promise((c,p)=>r(l,d,c,p)),s={};return a=a.apply(n,t),s[_n("asyncIterator")]=()=>s,i("next"),i("throw"),i("return"),s};var je=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,Ba=(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},q=(n,t)=>Ra(n,Ua(t)),M=(n,t,a)=>new Promise((r,i)=>{var s=c=>{try{d(a.next(c));}catch(p){i(p);}},l=c=>{try{d(a.throw(c));}catch(p){i(p);}},d=c=>c.done?r(c.value):Promise.resolve(c.value).then(s,l);d((a=a.apply(n,t)).next());}),La=function(n,t){this[0]=n,this[1]=t;},Fa=(n,t,a)=>{var r=(l,d,c,p)=>{try{var g=a[l](d),f=(d=g.value)instanceof La,v=g.done;Promise.resolve(f?d[0]:d).then(h=>f?r(l==="return"?l:"next",d[1]?{done:h.done,value:h.value}:h,c,p):c({value:h,done:v})).catch(h=>r("throw",h,c,p));}catch(h){p(h);}},i=l=>s[l]=d=>new Promise((c,p)=>r(l,d,c,p)),s={};return a=a.apply(n,t),s[Ba("asyncIterator")]=()=>s,i("next"),i("throw"),i("return"),s},qa=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},r){super(`[${r!=null?r:ee}]: ${t}
9
- Message: ${qa(a)}`),this.name=ee,this.info=t,this.cause=a,this.name=r!=null?r: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",C="assistant",Ka="tool",Da=[A,K,C,Ka],wt=e.z.enum(Da),Na=[C],Ha=e.z.enum(Na),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",jt=(n=e.z.undefined())=>e.z.object({modality:e.z.literal(ae),value:e.z.string(),metadata:n}),x="tool-call",Tt=(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(),r=e.z.undefined())=>e.z.discriminatedUnion("modality",[xt(n),Qa(t),Tt(a),eo(r)]),oo=[ae,oe];e.z.enum(oo);var io=(n=e.z.undefined(),t=e.z.undefined())=>e.z.discriminatedUnion("modality",[jt(n),Mt(t)]),St=(n=wt,t=e.z.undefined(),a=e.z.undefined(),r=e.z.undefined(),i=e.z.undefined(),s=e.z.undefined())=>e.z.object({role:n,content:e.z.array(ao(t,a,r,i)),metadata:s}),ie=(n=Ha,t=e.z.undefined(),a=e.z.undefined(),r=e.z.undefined())=>e.z.object({role:n,partialContent:io(t,a),metadata:r}),ro=n=>xt().parse({modality:b,value:n}),so=(n,t,a,r)=>Tt().parse({modality:x,index:n,id:t,name:a,arguments:r}),rt=(n,t)=>ie().parse({role:n,partialContent:jt().parse({modality:ae,value:t})}),st=(n,t,a,r,i)=>ie().parse({role:n,partialContent:Mt().parse({modality:oe,index:t,id:a,name:r,arguments:i})}),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()}),jo=dt.extend({topLogProbs:e.z.array(dt)}),_t=e.z.array(jo);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 To=Object.defineProperty,mt=Object.getOwnPropertySymbols,Mo=Object.prototype.hasOwnProperty,So=Object.prototype.propertyIsEnumerable,ct=(n,t,a)=>t in n?To(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",F=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",T=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 Bt 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 Bt}},ft="InvalidMessagesError",w=class Lt 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 Lt}},yt="InvalidToolsError",bt=class Ft 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 Ft}},zt="InvalidEmbeddingRequestsError",ko=class qt 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 qt}},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,r)=>e.z.number().min(n).max(t).step(a).default(r).optional(),D=n=>({def:Dt.parse(re({type:le},n)),schema:Po(n.min,n.max,n.step,n.default)}),de="select-string",Nt=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(),N=n=>({def:Nt.parse(re({type:de},n)),schema:Io(n.default,n.choices)}),Ht="object-schema",_o=e.z.object({type:e.z.literal(Ht),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,Ht,Jt];e.z.enum(Uo);var Gt=e.z.discriminatedUnion("type",[Dt,Kt,Nt,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 r,i;let s=Object.keys(a.def),l=Object.keys((i=(r=a.schema)==null?void 0:r.shape)!=null?i:{});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,r;let i=Object.keys(t.def),s=Object.keys((r=(a=t.schema)==null?void 0:a.shape)!=null?r:{});return i.every(l=>s.includes(l))&&s.every(l=>i.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 Bo={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."},Lo={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."},Fo=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.`}),qo={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."},No={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:Bo,MAX_TOKENS:Lo,STOP:Fo,TOP_P:qo,TOP_K:Ko,FREQUENCY_PENALTY:Do,PRESENCE_PENALTY:No},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=N({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=N({param:"encoding_format",title:"Encoding format",description:"Select the encoding format for the word embedding.",default:"none",choices:["base64"]}),ye=N({param:"input_type",title:"Input type",description:"Select the input type for the word embedding.",default:"none",choices:["query","document"]}),be=N({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,C]),en={system:A,user:K,assistant:C},tn=[b,I,x,_],nn=e.z.enum([b,I,x,_]),Ho=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",[Ho,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",source:"adaline.ai"}}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(r=>r.modality==="text"?r.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,r=a.model,i={};a.tool_choice&&(a.tool_choice.type==="tool"?i.toolChoice=a.tool_choice.name:i.toolChoice=a.tool_choice.type),i.maxTokens=a.max_tokens,i.temperature=a.temperature,i.topP=a.top_p,i.topK=a.top_k,i.stop=a.stop_sequences;let s=kt().parse(Vt(i)),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",B=h.source.media_type.split("/")[1];return {modality:I,detail:V,value:{type:Ct,media_type:B,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 B={modality:x,id:h.id,index:V,name:h.name,arguments:JSON.stringify(h.input)};return d[h.id]=B,B}});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:r,config:s,messages:l,tools:c.length>0?c:void 0}}transformConfig(n,t,a){let r=n.toolChoice;delete n.toolChoice;let i=this.modelSchema.config.schema.safeParse(n);if(!i.success)throw new P({info:`Invalid config for model : '${this.modelSchema.name}'`,cause:i.error});let s=i.data;r!==void 0&&(s.toolChoice=r),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
- 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
- one of [${c.choices.join(", ")}]`)})}}return l}transformMessages(n){if(!n||n&&n.length===0)return {messages:[]};let t=n.map(i=>{let s=St().safeParse(i);if(!s.success)throw new w({info:"Invalid messages",cause:s.error});return s.data});t.forEach(i=>{i.content.forEach(s=>{if(!this.modelSchema.modalities.includes(s.modality))throw new w({info:`Invalid message content for model : '${this.modelSchema.name}'`,cause:new Error(`model : '${this.modelSchema.name}' does not support modality : '${s.modality}',
12
- available modalities : [${this.modelSchema.modalities.join(", ")}]`)})});}),t.forEach(i=>{if(!Object.keys(this.modelSchema.roles).includes(i.role))throw new w({info:`Invalid message content for model : '${this.modelSchema.name}'`,cause:new Error(`model : '${this.modelSchema.name}' does not support role : '${i.role}',
13
- available roles : [${Object.keys(this.modelSchema.roles).join(", ")}]`)})});let a="",r=[];return t.forEach(i=>{switch(i.role){case A:i.content.forEach(s=>{if(s.modality===b)a+=s.value;else throw new w({info:`Invalid message 'role' and 'modality' combination for model : ${this.modelSchema.name}`,cause:new Error(`role : '${i.role}' cannot have content with modality : '${s.modality}'`)})});break;case C:{let s=[];i.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 w({info:`Invalid message 'role' and 'modality' combination for model : ${this.modelSchema.name}`,cause:new Error(`role : '${i.role}' cannot have content with modality : '${l.modality}'`)})}),r.push({role:this.modelSchema.roles[i.role],content:s});}break;case K:{let s=[];i.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 w({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 w({info:`Invalid message 'role' and 'modality' combination for model : ${this.modelSchema.name}`,cause:new Error(`role : '${i.role}' cannot have content with modality : '${l.modality}'`)})}),r.push({role:this.modelSchema.roles[i.role],content:s});}break;default:throw new w({info:`Invalid message 'role' for model : ${this.modelSchema.name}`,cause:new Error(`role : '${i.role}' is not supported,
14
- available roles : [${Object.keys(this.modelSchema.roles).join(", ")}]`)})}}),{system:a,messages:r}}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(r=>{r(this.completeChatUrl);})})}getCompleteChatHeaders(n,t,a){return M(this,null,function*(){let r=this.getDefaultHeaders();return a&&a.length>0&&(r=q(y({},r),{"anthropic-beta":"tools-2024-05-16"})),new Promise(i=>{i(r);})})}getCompleteChatData(n,t,a){return M(this,null,function*(){let r=this.transformConfig(n,t,a),i=this.transformMessages(t);if(i.messages&&i.messages.length===0)throw new w({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()),r),i),s));})})}transformCompleteChatResponse(n){let t=an.safeParse(n);if(t.success){let a=t.data,r=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))}),i=[{role:C,content:r}],s={promptTokens:a.usage.input_tokens,completionTokens:a.usage.output_tokens,totalTokens:a.usage.input_tokens+a.usage.output_tokens};return {messages:i,usage:s,logProbs:[]}}throw new T({info:"Invalid response from model",cause:t.error})}getStreamChatUrl(n,t,a){return M(this,null,function*(){return new Promise(r=>{r(this.streamChatUrl);})})}getStreamChatHeaders(n,t,a){let r=this.getDefaultHeaders();return a&&a.length>0&&(r=q(y({},r),{"anthropic-beta":"tools-2024-05-16"})),new Promise(i=>{i(r);})}getStreamChatData(n,t,a){return M(this,null,function*(){let r=this.transformConfig(n,t,a),i=this.transformMessages(t);if(i.messages&&i.messages.length===0)throw new w({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()),r),i),s));})})}transformStreamChatResponseChunk(n,t){return Fa(this,null,function*(){let a=(t+n).split(`
15
- `).filter(r=>r.trim()!=="");for(let r of a)if(r.startsWith("data: {")&&r.endsWith("}")){let i;try{i=JSON.parse(r.substring(6));}catch(s){throw new T({info:"Malformed JSON received in stream",cause:new Error(`Malformed JSON received in stream : ${i}`)})}if("type"in i){if(i.type==="message_stop")return;if(i.type==="message_start"){let s=on.safeParse(i);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 T({info:"Invalid response from model",cause:s.error})}else if(i.type==="message_delta"){let s=rn.safeParse(i);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 T({info:"Invalid response from model",cause:s.error})}else if(i.type==="content_block_start"){let s=sn.safeParse(i);if(s.success){let l=s.data,d=[];l.content_block.type==="text"?d.push(rt(C,l.content_block.text)):l.content_block.type==="tool_use"&&d.push(st(C,l.index,l.content_block.id,l.content_block.name,"")),yield {partialResponse:{partialMessages:d},buffer:t};}else throw new T({info:"Invalid response from model",cause:s.error})}else if(i.type==="content_block_delta"){let s=ln.safeParse(i);if(s.success){let l=s.data,d=[];l.delta.type==="text_delta"?d.push(rt(C,l.delta.text)):l.delta.type==="input_json_delta"&&d.push(st(C,l.index,"","",l.delta.partial_json)),yield {partialResponse:{partialMessages:d},buffer:t};}else throw new T({info:"Invalid response from model",cause:s.error})}}else throw new T({info:"Invalid JSON received in stream",cause:new Error(`Invalid JSON received in stream, expected 'type' property,
16
- received : ${JSON.stringify(i)}`)})}})}},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",source:"adaline.ai"}}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,r=a.model,i={encodingFormat:a.encoding_format,inputType:a.input_type,truncation:a.truncation},s=kt().parse(Vt(i)),l;return typeof a.input=="string"?l={modality:R,requests:[a.input]}:l={modality:R,requests:a.input},{modelName:r,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 r=a.data;return Object.keys(r).forEach(i=>{if(!this.modelSchema.config.def[i])throw new P({info:`Invalid config for model : '${this.modelSchema.name}'`,cause:new Error(`Invalid config key : '${i}',
17
- available keys : [${Object.keys(this.modelSchema.config.def).join(", ")}]`)})}),Object.keys(r).reduce((i,s)=>{let l=this.modelSchema.config.def[s].param,d=r[s];return i[l]=d,i},{})}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 r=a.data;t=typeof r.data[0].embedding=="string"?Pt:Ot;let i=r.data.map(s=>typeof s.embedding=="string"?{index:s.index,embedding:s.embedding}:{index:s.index,embedding:s.embedding});return {encodingFormat:t,embeddings:i,usage:{totalTokens:r.usage.total_tokens}}}throw new T({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 F({info:`Anthropic chat model: ${n} not found`,cause:new Error(`Anthropic chat model: ${n} not found, available chat models:
18
- ${this.chatModelLiterals().join(", ")}`)});let r=this.chatModelFactories[n].model,i=q(y({},t),{baseUrl:(a=t.baseUrl)!=null?a:this.chatBaseUrl}),s=this.chatModelFactories[n].modelOptions.parse(i);return new r(s)}chatModelSchema(n){if(!(n in this.chatModelFactories))throw new F({info:`Anthropic chat model: ${n} not found`,cause:new Error(`Anthropic chat model: ${n} not found, available chat models:
19
- ${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 F({info:`Anthropic embedding model: ${n} not found`,cause:new Error(`Anthropic embedding model: ${n} not found, available embedding models:
20
- ${this.embeddingModelLiterals().join(", ")}`)});let r=this.embeddingModelFactories[n].model,i=q(y({},t),{baseUrl:(a=t.baseUrl)!=null?a:this.embeddingBaseUrl}),s=this.embeddingModelFactories[n].modelOptions.parse(i);return new r(s)}embeddingModelSchema(n){if(!(n in this.embeddingModelFactories))throw new F({info:`Anthropic embedding model: ${n} not found`,cause:new Error(`Anthropic embedding model: ${n} not found, available embedding models:
21
- ${this.embeddingModelLiterals().join(", ")}`)});return this.embeddingModelFactories[n].modelSchema}embeddingModelSchemas(){return Object.keys(this.embeddingModelFactories).reduce((n,t)=>(n[t]=this.embeddingModelFactories[t].modelSchema,n),{})}};u.Anthropic=li;u.AnthropicChatModelModalities=tn;u.AnthropicChatModelModalitiesEnum=nn;u.AnthropicChatModelRoles=Qt;u.AnthropicChatModelRolesMap=en;u.AnthropicCompleteChatResponse=an;u.AnthropicEmbeddingModelModalities=hn;u.AnthropicEmbeddingModelModalitiesEnum=gn;u.AnthropicEmbeddingRequest=bn;u.AnthropicEmbeddingRequestInput=yn;u.AnthropicGetEmbeddingsResponse=fn;u.AnthropicStreamChatContentBlockDeltaResponse=ln;u.AnthropicStreamChatContentBlockStartResponse=sn;u.AnthropicStreamChatMessageDeltaResponse=rn;u.AnthropicStreamChatMessageStartResponse=on;u.BaseChatModel=cn;u.BaseChatModelOptions=ve;u.BaseEmbeddingModel=zn;u.BaseEmbeddingModelOptions=Ce;u.ChatModelAnthropicConfigs=te;u.ChatModelBaseConfigDef=Yt;u.ChatModelBaseConfigSchema=Zt;u.Claude3Haiku20240307=pn;u.Claude3Haiku20240307Options=un;u.Claude3Haiku20240307Schema=we;u.EmbeddingModelAnthropicConfigs=ne;u.EmbeddingModelBaseConfigDef=Xt;u.EmbeddingModelBaseConfigSchema=Wt;u.ProviderLiteral=Cn;u.Voyage2=wn;u.Voyage2Options=vn;u.Voyage2Schema=xe;u.encodingFormat=fe;u.inputType=ye;u.maxTokens=ce;u.stop=ue;u.temperature=me;u.toolChoice=ge;u.topK=he;u.topP=pe;u.truncation=be;});var An=n=>n==null?"unknown error":typeof n=="string"?n:n instanceof Error?n.message:JSON.stringify(n),W="GatewayBaseError",X=class Ue extends Error{constructor({info:t,cause:a},r){super(`[${r!=null?r:W}]: ${t}
22
- Message: ${An(a)}`),this.name=W,this.info=t,this.cause=a,this.name=r!=null?r:W,Object.setPrototypeOf(this,new.target.prototype);}static isGatewayBaseError(t){return t instanceof Ue}toJSON(){return {name:this.name,info:this.info,cause:this.cause,message:this.message,stack:this.stack}}},Bn="system",Ln="user",$e="assistant",Fn="tool",qn=[Bn,Ln,$e,Fn],Q=zod.z.enum(qn),Kn=[$e],Dn=zod.z.enum(Kn),Ae="image",Nn="base64",Hn=["png","jpeg","webp","gif"],Jn=zod.z.object({type:zod.z.literal(Nn),base64:zod.z.string(),media_type:zod.z.enum(Hn)}),Gn="url",Vn=zod.z.object({type:zod.z.literal(Gn),url:zod.z.string()}),Zn=zod.z.discriminatedUnion("type",[Jn,Vn]),Yn=["low","medium","high","auto"],Wn=zod.z.enum(Yn),Xn=(n=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(Ae),detail:Wn,value:Zn,metadata:n}),Be="text",Qn=(n=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(Be),value:zod.z.string(),metadata:n}),Le="partial-text",ea=(n=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(Le),value:zod.z.string(),metadata:n}),Fe="tool-call",ta=(n=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(Fe),index:zod.z.number().int().nonnegative(),id:zod.z.string().min(1),name:zod.z.string().min(1),arguments:zod.z.string(),metadata:n}),qe="partial-tool-call",na=(n=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(qe),index:zod.z.number().int().nonnegative(),id:zod.z.string().optional(),name:zod.z.string().optional(),arguments:zod.z.string().optional(),metadata:n}),Ke="tool-response",aa=(n=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(Ke),index:zod.z.number().int().nonnegative(),id:zod.z.string().min(1),name:zod.z.string().min(1),data:zod.z.string(),metadata:n}),oa=[Be,Ae,Fe,Ke],De=zod.z.enum(oa),ia=(n=zod.z.undefined(),t=zod.z.undefined(),a=zod.z.undefined(),r=zod.z.undefined())=>zod.z.discriminatedUnion("modality",[Qn(n),Xn(t),ta(a),aa(r)]),ra=[Le,qe];zod.z.enum(ra);var sa=(n=zod.z.undefined(),t=zod.z.undefined())=>zod.z.discriminatedUnion("modality",[ea(n),na(t)]);var la=(n=Q,t=zod.z.undefined(),a=zod.z.undefined(),r=zod.z.undefined(),i=zod.z.undefined(),s=zod.z.undefined())=>zod.z.object({role:n,content:zod.z.array(ia(t,a,r,i)),metadata:s}),da=(n=Dn,t=zod.z.undefined(),a=zod.z.undefined(),r=zod.z.undefined())=>zod.z.object({role:n,partialContent:sa(t,a),metadata:r});var ma="function";var ca=zod.z.enum(["object","array","number","string","boolean","null"]),ua=zod.z.object({anyOf:zod.z.array(zod.z.any()).optional(),type:ca.optional(),default:zod.z.any().optional(),title:zod.z.string().optional(),description:zod.z.string().max(4096).optional(),properties:zod.z.record(zod.z.any()).optional(),required:zod.z.array(zod.z.string()).optional(),minItems:zod.z.number().int().min(0).optional(),maxItems:zod.z.number().int().optional(),items:zod.z.record(zod.z.any()).optional(),enum:zod.z.array(zod.z.union([zod.z.string(),zod.z.number(),zod.z.boolean(),zod.z.null()])).optional(),minimum:zod.z.number().optional(),maximum:zod.z.number().optional(),minLength:zod.z.number().int().min(0).optional(),maxLength:zod.z.number().int().optional()});zod.z.object({type:zod.z.enum(["object"]),title:zod.z.string().optional(),$defs:zod.z.record(zod.z.any()).optional(),properties:zod.z.record(ua).optional(),required:zod.z.array(zod.z.string()).optional()});var pa=zod.z.object({name:zod.z.string().regex(/^[a-zA-Z0-9_]{1,64}$/).max(64),description:zod.z.string().max(4096),parameters:zod.z.any(),strict:zod.z.boolean().optional()});var ha=zod.z.enum(["function"]);zod.z.object({type:ha,definition:zod.z.object({schema:pa})});var ga=[ma];zod.z.enum(ga);var fa="text",ya="token",ba=[fa,ya];zod.z.enum(ba);zod.z.array(zod.z.string().min(1));zod.z.array(zod.z.array(zod.z.number().int().nonnegative()));var va="float",wa=zod.z.object({index:zod.z.number().int().nonnegative(),embedding:zod.z.array(zod.z.number())}),Ca="base64",xa=zod.z.object({index:zod.z.number().int().nonnegative(),embedding:zod.z.string().base64()}),_e=zod.z.object({totalTokens:zod.z.number().int().nonnegative()});zod.z.discriminatedUnion("encodingFormat",[zod.z.object({encodingFormat:zod.z.literal(va),embeddings:zod.z.array(wa),usage:_e.optional()}),zod.z.object({encodingFormat:zod.z.literal(Ca),embeddings:zod.z.array(xa),usage:_e.optional()})]);var Ne=zod.z.object({promptTokens:zod.z.number().nonnegative(),completionTokens:zod.z.number().nonnegative(),totalTokens:zod.z.number().nonnegative()}),Re=zod.z.object({token:zod.z.string(),logProb:zod.z.number(),bytes:zod.z.array(zod.z.number().int()).nullable()}),ja=Re.extend({topLogProbs:zod.z.array(Re)}),He=zod.z.array(ja);zod.z.object({messages:zod.z.array(la()),usage:Ne.optional(),logProbs:He.optional()});zod.z.object({partialMessages:zod.z.array(da()),usage:Ne.optional(),logProbs:He.optional()});var Je="ProviderError",U=class Ve extends X{constructor({info:t,cause:a}){super({info:t,cause:a},Je),this.name=Je,this.info=t,this.cause=a;}static isProviderError(t){return t instanceof Ve}};var Ge="ModelResponseError",Ze=class Ye extends X{constructor({info:t,cause:a}){super({info:t,cause:a},Ge),this.name=Ge,this.cause=a,this.info=t;}static isModelResponseError(t){return t instanceof Ye}};var We="multi-string",Ta=zod.z.object({type:zod.z.literal(We),param:zod.z.string().min(1),title:zod.z.string().min(1),description:zod.z.string().min(1).max(500),max:zod.z.number().int().positive()});var Xe="range",Ma=zod.z.object({type:zod.z.literal(Xe),param:zod.z.string().min(1),title:zod.z.string().min(1),description:zod.z.string().min(1).max(500),min:zod.z.number().int(),max:zod.z.number().int(),step:zod.z.number().positive(),default:zod.z.number().int()});var Qe="select-string",Sa=zod.z.object({type:zod.z.literal(Qe),param:zod.z.string().min(1),title:zod.z.string().min(1),description:zod.z.string().min(1).max(500),default:zod.z.string().min(1),choices:zod.z.array(zod.z.string().min(1))});var et="object-schema",ka=zod.z.object({type:zod.z.literal(et),param:zod.z.string().min(1),title:zod.z.string().min(1),description:zod.z.string().min(1).max(500),objectSchema:zod.z.any()});var tt="select-boolean",Ea=zod.z.object({type:zod.z.literal(tt),param:zod.z.string().min(1),title:zod.z.string().min(1),description:zod.z.string().min(1).max(500),default:zod.z.boolean().nullable()});var Oa=[Xe,We,Qe,et,tt];zod.z.enum(Oa);var Pa=zod.z.discriminatedUnion("type",[Ma,Ta,Sa,Ea,ka]),nt=(n=Q,t=De)=>zod.z.object({name:zod.z.string().min(1),description:zod.z.string().min(1),roles:zod.z.record(n,zod.z.string().min(1).optional()),modalities:zod.z.array(t).nonempty(),maxInputTokens:zod.z.number().int().positive().min(1),maxOutputTokens:zod.z.number().int().positive().min(1),config:zod.z.object({def:zod.z.record(zod.z.string().min(1),Pa),schema:zod.z.instanceof(zod.z.ZodObject)}).refine(a=>{var r,i;let s=Object.keys(a.def),l=Object.keys((i=(r=a.schema)==null?void 0:r.shape)!=null?i:{});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'"})});zod.z.record(zod.z.string());zod.z.record(zod.z.union([zod.z.boolean(),zod.z.string(),zod.z.number(),zod.z.object({}),zod.z.array(zod.z.any()),zod.z.null(),zod.z.undefined()]));zod.z.string().url();var Ia=()=>typeof window!="undefined"&&typeof window.document!="undefined"&&typeof navigator!="undefined";var at=n=>{if(Ia()){let t=atob(n),a=new Uint8Array(t.length);for(let r=0;r<t.length;r++)a[r]=t.charCodeAt(r);return new TextDecoder("utf-8").decode(a)}else return Buffer.from(n,"base64").toString("utf-8")};var Mn=Pe(je());var Te=zod.z.object({awsRegion:zod.z.string(),awsAccessKeyId:zod.z.string(),awsSecretAccessKey:zod.z.string()}),J=class n extends Mn.BaseChatModel{constructor(a,r){let i=Te.parse(r);super(a,{apiKey:"random-api-key",baseUrl:"https://random.url"});this.version="v1";this.modelSchema=a,this.awsRegion=i.awsRegion,this.awsUrl=E.awsUrl(this.awsRegion),this.awsService=E.awsService,this.awsAccessKeyId=i.awsAccessKeyId,this.awsSecretAccessKey=i.awsSecretAccessKey;}getDefaultBaseUrl(){return this.awsUrl}getDefaultHeaders(){return {Accept:"application/json","Content-Type":"application/json",host:this.awsUrl.split("://")[1]}}getDefaultParams(){return {anthropic_version:"bedrock-2023-05-31"}}getCompleteChatUrl(a,r,i){return new Promise(s=>{s(`${this.awsUrl}/model/${this.modelSchema.name}/invoke`);})}getCompleteChatHeaders(a,r,i){return O(this,null,function*(){let s=new URL(yield this.getCompleteChatUrl(a,r,i)),l={accessKeyId:this.awsAccessKeyId,secretAccessKey:this.awsSecretAccessKey},d=this.getDefaultHeaders(),c=this.getCompleteChatData(a||{},r||[],i),p=new protocolHttp.HttpRequest({hostname:s.hostname,path:s.pathname,protocol:s.protocol,method:"POST",body:JSON.stringify(c),headers:d});return (yield new signatureV4.SignatureV4({credentials:l,service:this.awsService,region:this.awsRegion,sha256:sha256Js.Sha256}).sign(p)).headers})}getCompleteChatData(a,r,i){return O(this,null,function*(){let s=j(j({},this.getDefaultParams()),L(n.prototype,this,"getCompleteChatData").call(this,a,r,i));return new Promise(l=>{l(s);})})}getStreamChatUrl(a,r,i){return O(this,null,function*(){return new Promise(s=>{s(`${this.awsUrl}/model/${this.modelSchema.name}/invoke-with-response-stream`);})})}getStreamChatHeaders(a,r,i){return O(this,null,function*(){let s=new URL(yield this.getStreamChatUrl(a,r,i)),l={accessKeyId:this.awsAccessKeyId,secretAccessKey:this.awsSecretAccessKey},d=this.getDefaultHeaders(),c=this.getCompleteChatData(a||{},r||[],i),p=new protocolHttp.HttpRequest({hostname:s.hostname,path:s.pathname,protocol:s.protocol,method:"POST",body:JSON.stringify(c),headers:d});return (yield new signatureV4.SignatureV4({credentials:l,service:this.awsService,region:this.awsRegion,sha256:sha256Js.Sha256}).sign(p)).headers})}getStreamChatData(a,r,i){return O(this,null,function*(){let s=j(j({},this.getDefaultParams()),L(n.prototype,this,"getStreamChatData").call(this,a,r,i));return "stream"in s&&delete s.stream,s})}transformStreamChatResponseChunk(a,r){return Ie(this,null,function*(){let i=a.toString(),s=/{\s*"bytes"\s*:\s*"[\w=+/]+".*?}/g,l=i.match(s)||[];for(let d of l){let c=d.indexOf("{"),p=d.indexOf("}");if(c!==-1&&p!==-1&&c<p){let g;try{g=JSON.parse(d.slice(c,p+1));}catch(h){throw new Ze({info:"Malformed JSON received in stream",cause:new Error(`Malformed JSON received in stream : ${g}`)})}let f=at(g.bytes),v=(yield new Y(L(n.prototype,this,"transformStreamChatResponseChunk").call(this,`data: ${f}`,r).next())).value;v&&(yield v);}}})}};var z=Pe(je());var di="anthropic.claude-3-haiku-20240307-v1:0",mi="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.",Me=nt(z.AnthropicChatModelRoles,z.AnthropicChatModelModalitiesEnum).parse({name:di,description:mi,maxInputTokens:128e3,maxOutputTokens:128e3,roles:z.AnthropicChatModelRolesMap,modalities:z.AnthropicChatModelModalities,config:{def:z.ChatModelAnthropicConfigs.base(128e3,4).def,schema:z.ChatModelAnthropicConfigs.base(128e3,4).schema}}),Sn=Te,G=class extends J{constructor(t){super(Me,t);}};var ci="bedrock",E=class{constructor(){this.version="v1";this.name=ci;this.chatModelFactories={"claude-3-haiku-20240307":{model:G,modelOptions:Sn,modelSchema:Me}};this.embeddingModelFactories={};}chatModelLiterals(){return Object.keys(this.chatModelFactories)}chatModel(t,a){if(!(t in this.chatModelFactories))throw new U({info:`Bedrock chat model: ${t} not found`,cause:new Error(`Bedrock chat model: ${t} not found, available chat models:
23
- ${this.chatModelLiterals().join(", ")}`)});let r=this.chatModelFactories[t].model,i=j({},a),s=this.chatModelFactories[t].modelOptions.parse(i);return new r(s)}chatModelSchema(t){if(!(t in this.chatModelFactories))throw new U({info:`Bedrock chat model: ${t} not found`,cause:new Error(`Bedrock chat model: ${t} not found, available chat models:
24
- ${this.chatModelLiterals().join(", ")}`)});return this.chatModelFactories[t].modelSchema}chatModelSchemas(){return Object.keys(this.chatModelFactories).reduce((t,a)=>(t[a]=this.chatModelFactories[a].modelSchema,t),{})}embeddingModelLiterals(){return Object.keys(this.embeddingModelFactories)}embeddingModel(t,a){if(!(t in this.embeddingModelFactories))throw new U({info:`Bedrock embedding model: ${t} not found`,cause:new Error(`Bedrock embedding model: ${t} not found, available embedding models:
25
- ${this.embeddingModelLiterals().join(", ")}`)});let r=this.embeddingModelFactories[t].model,i=j({},a),s=this.embeddingModelFactories[t].modelOptions.parse(i);return new r(s)}embeddingModelSchema(t){if(!(t in this.embeddingModelFactories))throw new U({info:`Bedrock embedding model: ${t} not found`,cause:new Error(`Bedrock embedding model: ${t} not found, available embedding models:
26
- ${this.embeddingModelLiterals().join(", ")}`)});return this.embeddingModelFactories[t].modelSchema}embeddingModelSchemas(){return Object.keys(this.embeddingModelFactories).reduce((t,a)=>(t[a]=this.embeddingModelFactories[a].modelSchema,t),{})}};E.awsService="bedrock",E.awsUrl=t=>`https://bedrock.${t}.amazonaws.com`;
8
+ var Cn=Object.create;var me=Object.defineProperty;var Tn=Object.getOwnPropertyDescriptor;var kn=Object.getOwnPropertyNames,it=Object.getOwnPropertySymbols,rt=Object.getPrototypeOf,lt=Object.prototype.hasOwnProperty,xn=Object.prototype.propertyIsEnumerable,jn=Reflect.get;var On=(t,o)=>(o=Symbol[t])?o:Symbol.for("Symbol."+t);var st=(t,o,n)=>o in t?me(t,o,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[o]=n,j=(t,o)=>{for(var n in o||(o={}))lt.call(o,n)&&st(t,n,o[n]);if(it)for(var n of it(o))xn.call(o,n)&&st(t,n,o[n]);return t};var Mn=(t=>typeof require!="undefined"?require:typeof Proxy!="undefined"?new Proxy(t,{get:(o,n)=>(typeof require!="undefined"?require:o)[n]}):t)(function(t){if(typeof require!="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var En=(t,o)=>()=>(o||t((o={exports:{}}).exports,o),o.exports);var Pn=(t,o,n,i)=>{if(o&&typeof o=="object"||typeof o=="function")for(let r of kn(o))!lt.call(t,r)&&r!==n&&me(t,r,{get:()=>o[r],enumerable:!(i=Tn(o,r))||i.enumerable});return t};var dt=(t,o,n)=>(n=t!=null?Cn(rt(t)):{},Pn(!t||!t.__esModule?me(n,"default",{value:t,enumerable:!0}):n,t));var ee=(t,o,n)=>jn(rt(t),n,o);var q=(t,o,n)=>new Promise((i,r)=>{var s=u=>{try{d(n.next(u));}catch(p){r(p);}},l=u=>{try{d(n.throw(u));}catch(p){r(p);}},d=u=>u.done?i(u.value):Promise.resolve(u.value).then(s,l);d((n=n.apply(t,o)).next());}),ce=function(t,o){this[0]=t,this[1]=o;},mt=(t,o,n)=>{var i=(l,d,u,p)=>{try{var g=n[l](d),f=(d=g.value)instanceof ce,C=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,u,p):u({value:h,done:C})).catch(h=>i("throw",h,u,p));}catch(h){p(h);}},r=l=>s[l]=d=>new Promise((u,p)=>i(l,d,u,p)),s={};return n=n.apply(t,o),s[On("asyncIterator")]=()=>s,r("next"),r("throw"),r("return"),s};var ot=En(m=>{var e=Mn("zod"),Ia=Object.defineProperty,Ra=Object.defineProperties,_a=Object.getOwnPropertyDescriptors,Lt=Object.getOwnPropertySymbols,Aa=Object.prototype.hasOwnProperty,$a=Object.prototype.propertyIsEnumerable,La=(t,o)=>(o=Symbol[t])?o:Symbol.for("Symbol."+t),qt=(t,o,n)=>o in t?Ia(t,o,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[o]=n,y=(t,o)=>{for(var n in o||(o={}))Aa.call(o,n)&&qt(t,n,o[n]);if(Lt)for(var n of Lt(o))$a.call(o,n)&&qt(t,n,o[n]);return t},Ut=(t,o)=>Ra(t,_a(o)),M=(t,o,n)=>new Promise((i,r)=>{var s=u=>{try{d(n.next(u));}catch(p){r(p);}},l=u=>{try{d(n.throw(u));}catch(p){r(p);}},d=u=>u.done?i(u.value):Promise.resolve(u.value).then(s,l);d((n=n.apply(t,o)).next());}),qa=function(t,o){this[0]=t,this[1]=o;},Ua=(t,o,n)=>{var i=(l,d,u,p)=>{try{var g=n[l](d),f=(d=g.value)instanceof qa,C=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,u,p):u({value:h,done:C})).catch(h=>i("throw",h,u,p));}catch(h){p(h);}},r=l=>s[l]=d=>new Promise((u,p)=>i(l,d,u,p)),s={};return n=n.apply(t,o),s[La("asyncIterator")]=()=>s,r("next"),r("throw"),r("return"),s},Fa=t=>{let o=new WeakSet;return JSON.stringify(t,(n,i)=>{if(typeof i=="object"&&i!==null){if(o.has(i))return;o.add(i);}return i})},Ba=t=>t==null?"unknown error":typeof t=="string"?t:t instanceof Error?t.message:Fa(t),ge="GatewayBaseError",R=class oo extends Error{constructor({info:o,cause:n},i){super(`[${i!=null?i:ge}]: ${o}
9
+ Message: ${Ba(n)}`),this.name=ge,this.info=o,this.cause=n,this.name=i!=null?i:ge,Object.setPrototypeOf(this,new.target.prototype);}static isGatewayBaseError(o){return o instanceof oo}toJSON(){return {name:this.name,info:this.info,cause:this.cause,message:this.message,stack:this.stack}}},V="system",I="user",w="assistant",Na="tool",Da=[V,I,w,Na],no=e.z.enum(Da),Ka=[w],Ha=e.z.enum(Ka),U="image",ao="base64",Va=["png","jpeg","webp","gif"],Ja=e.z.object({type:e.z.literal(ao),base64:e.z.string(),media_type:e.z.enum(Va)}),Ga="url",Wa=e.z.object({type:e.z.literal(Ga),url:e.z.string()}),Za=e.z.discriminatedUnion("type",[Ja,Wa]),Ya=["low","medium","high","auto"],Qa=e.z.enum(Ya),Xa=(t=e.z.undefined())=>e.z.object({modality:e.z.literal(U),detail:Qa,value:Za,metadata:t}),b="text",io=(t=e.z.undefined())=>e.z.object({modality:e.z.literal(b),value:e.z.string(),metadata:t}),ye="partial-text",so=(t=e.z.undefined())=>e.z.object({modality:e.z.literal(ye),value:e.z.string(),metadata:t}),k="tool-call",ro=(t=e.z.undefined())=>e.z.object({modality:e.z.literal(k),index:e.z.number().int().nonnegative(),id:e.z.string().min(1),name:e.z.string().min(1),arguments:e.z.string(),metadata:t}),be="partial-tool-call",lo=(t=e.z.undefined())=>e.z.object({modality:e.z.literal(be),index:e.z.number().int().nonnegative(),id:e.z.string().optional(),name:e.z.string().optional(),arguments:e.z.string().optional(),metadata:t}),F="tool-response",ei=(t=e.z.undefined())=>e.z.object({modality:e.z.literal(F),index:e.z.number().int().nonnegative(),id:e.z.string().min(1),name:e.z.string().min(1),data:e.z.string(),metadata:t}),ti=[b,U,k,F],oi=e.z.enum(ti),ni=(t=e.z.undefined(),o=e.z.undefined(),n=e.z.undefined(),i=e.z.undefined())=>e.z.discriminatedUnion("modality",[io(t),Xa(o),ro(n),ei(i)]),ai=[ye,be];e.z.enum(ai);var ii=(t=e.z.undefined(),o=e.z.undefined())=>e.z.discriminatedUnion("modality",[so(t),lo(o)]),mo=(t=no,o=e.z.undefined(),n=e.z.undefined(),i=e.z.undefined(),r=e.z.undefined(),s=e.z.undefined())=>e.z.object({role:t,content:e.z.array(ni(o,n,i,r)),metadata:s}),ze=(t=Ha,o=e.z.undefined(),n=e.z.undefined(),i=e.z.undefined())=>e.z.object({role:t,partialContent:ii(o,n),metadata:i}),si=t=>io().parse({modality:b,value:t}),ri=(t,o,n,i)=>ro().parse({modality:k,index:t,id:o,name:n,arguments:i}),Ft=(t,o)=>ze().parse({role:t,partialContent:so().parse({modality:ye,value:o})}),Bt=(t,o,n,i,r)=>ze().parse({role:t,partialContent:lo().parse({modality:be,index:o,id:n,name:i,arguments:r})}),co=(t=e.z.record(e.z.string(),e.z.any()).optional())=>t,li=["object","array","number","string","boolean","enum"],Nt=e.z.enum(li),di=e.z.object({anyOf:e.z.array(e.z.any()).optional(),type:e.z.union([Nt,e.z.array(e.z.union([Nt,e.z.literal("null")]))]).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(),$ref:e.z.string().optional()}),mi=e.z.object({type:e.z.enum(["object"]),required:e.z.array(e.z.string()),$defs:e.z.record(e.z.any()).optional(),properties:e.z.record(di),additionalProperties:e.z.literal(!1)});e.z.object({name:e.z.string().regex(/^[a-zA-Z0-9_]{1,64}$/).max(64),description:e.z.string().max(4096),strict:e.z.boolean().optional(),schema:mi}).optional();var ci="function",ui=e.z.enum(["object","array","number","string","boolean","null"]),pi=e.z.object({anyOf:e.z.array(e.z.any()).optional(),type:ui.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(pi).optional(),required:e.z.array(e.z.string()).optional()});var hi=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()}),gi=e.z.enum(["function"]),fi=e.z.object({type:gi,definition:e.z.object({schema:hi})}),yi=[ci];e.z.enum(yi);var bi=(t=e.z.undefined())=>e.z.discriminatedUnion("type",[fi.extend({metadata:t})]),B="text",uo="token",zi=[B,uo],vi=e.z.enum(zi),wi=e.z.array(e.z.string().min(1)),Si=e.z.array(e.z.array(e.z.number().int().nonnegative())),Ci=(t=e.z.undefined())=>e.z.discriminatedUnion("modality",[e.z.object({modality:e.z.literal(B),metadata:t,requests:wi}),e.z.object({modality:e.z.literal(uo),metadata:t,requests:Si})]),po="float",Ti=e.z.object({index:e.z.number().int().nonnegative(),embedding:e.z.array(e.z.number())}),ho="base64",ki=e.z.object({index:e.z.number().int().nonnegative(),embedding:e.z.string().base64()}),Dt=e.z.object({totalTokens:e.z.number().int().nonnegative()});e.z.discriminatedUnion("encodingFormat",[e.z.object({encodingFormat:e.z.literal(po),embeddings:e.z.array(Ti),usage:Dt.optional()}),e.z.object({encodingFormat:e.z.literal(ho),embeddings:e.z.array(ki),usage:Dt.optional()})]);var go=e.z.object({promptTokens:e.z.number().nonnegative(),completionTokens:e.z.number().nonnegative(),totalTokens:e.z.number().nonnegative()}),Kt=e.z.object({token:e.z.string(),logProb:e.z.number(),bytes:e.z.array(e.z.number().int()).nullable()}),xi=Kt.extend({topLogProbs:e.z.array(Kt)}),fo=e.z.array(xi);e.z.object({messages:e.z.array(mo()),usage:go.optional(),logProbs:fo.optional()});e.z.object({partialMessages:e.z.array(ze()),usage:go.optional(),logProbs:fo.optional()});var ji=Object.defineProperty,Ht=Object.getOwnPropertySymbols,Oi=Object.prototype.hasOwnProperty,Mi=Object.prototype.propertyIsEnumerable,Vt=(t,o,n)=>o in t?ji(t,o,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[o]=n,oe=(t,o)=>{for(var n in o||(o={}))Oi.call(o,n)&&Vt(t,n,o[n]);if(Ht)for(var n of Ht(o))Mi.call(o,n)&&Vt(t,n,o[n]);return t},Jt="ProviderError",te=class yo extends R{constructor({info:o,cause:n}){super({info:o,cause:n},Jt),this.name=Jt,this.info=o,this.cause=n;}static isProviderError(o){return o instanceof yo}},Gt="ModelResponseError",O=class bo extends R{constructor({info:o,cause:n}){super({info:o,cause:n},Gt),this.name=Gt,this.cause=n,this.info=o;}static isModelResponseError(o){return o instanceof bo}},Wt="InvalidModelRequestError",fe=class zo extends R{constructor({info:o,cause:n}){super({info:o,cause:n},Wt),this.name=Wt,this.cause=n,this.info=o,Object.setPrototypeOf(this,new.target.prototype);}static isInvalidModelRequestError(o){return o instanceof zo}},Zt="InvalidConfigError",P=class vo extends R{constructor({info:o,cause:n}){super({info:o,cause:n},Zt),this.name=Zt,this.cause=n,this.info=o,Object.setPrototypeOf(this,new.target.prototype);}static isInvalidConfigError(o){return o instanceof vo}},Yt="InvalidMessagesError",v=class wo extends R{constructor({info:o,cause:n}){super({info:o,cause:n},Yt),this.name=Yt,this.cause=n,this.info=o,Object.setPrototypeOf(this,new.target.prototype);}static isInvalidMessagesError(o){return o instanceof wo}},Qt="InvalidToolsError",Xt=class So extends R{constructor({info:o,cause:n}){super({info:o,cause:n},Qt),this.name=Qt,this.cause=n,this.info=o,Object.setPrototypeOf(this,new.target.prototype);}static isInvalidToolsError(o){return o instanceof So}},eo="InvalidEmbeddingRequestsError",to=class Co extends R{constructor({info:o,cause:n}){super({info:o,cause:n},eo),this.name=eo,this.info=o,this.cause=n,Object.setPrototypeOf(this,new.target.prototype);}static isInvalidEmbeddingRequestsError(o){return o instanceof Co}},ve="multi-string",To=e.z.object({type:e.z.literal(ve),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()}),Ei=t=>e.z.array(e.z.string()).max(t).default([]).optional(),Pi=t=>({def:To.parse(oe({type:ve},t)),schema:Ei(t.max)}),we="range",ko=e.z.object({type:e.z.literal(we),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()}),Ii=(t,o,n,i)=>e.z.number().min(t).max(o).step(n).default(i).optional(),ne=t=>({def:ko.parse(oe({type:we},t)),schema:Ii(t.min,t.max,t.step,t.default)}),Se="select-string",xo=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),default:e.z.string().min(1).nullable(),choices:e.z.array(e.z.string().min(1))}),Ri=(t,o)=>e.z.enum(o).nullable().default(t).optional(),Ce=t=>({def:xo.parse(oe({type:Se},t)),schema:Ri(t.default,t.choices)}),jo="object-schema",_i=e.z.object({type:e.z.literal(jo),param:e.z.string().min(1),title:e.z.string().min(1),description:e.z.string().min(1).max(500),objectSchema:e.z.any()}),Te="select-boolean",Oo=e.z.object({type:e.z.literal(Te),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()}),Ai=t=>e.z.boolean().nullable().default(t).optional(),$i=t=>({def:Oo.parse(oe({type:Te},t)),schema:Ai(t.default)}),Li=[we,ve,Se,jo,Te];e.z.enum(Li);var Mo=e.z.discriminatedUnion("type",[ko,To,xo,Oo,_i]),ae=(t=no,o=oi)=>e.z.object({name:e.z.string().min(1),description:e.z.string().min(1),roles:e.z.record(t,e.z.string().min(1).optional()),modalities:e.z.array(o).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),Mo),schema:e.z.instanceof(e.z.ZodObject)}).refine(n=>{var i,r;let s=Object.keys(n.def),l=Object.keys((r=(i=n.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'"})}),N=(t=vi)=>e.z.object({name:e.z.string().min(1),description:e.z.string().min(1),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),Mo),schema:e.z.instanceof(e.z.ZodObject)}).refine(o=>{var n,i;let r=Object.keys(o.def),s=Object.keys((i=(n=o.schema)==null?void 0:n.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 qi={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."},Ui={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."},Fi=t=>({type:"multi",title:"Stop sequence",description:`Enter up to ${t} sequences that will halt additional text output. The generated text will exclude these sequences.`}),Bi={type:"range",title:"Top A",description:"Considers only the top tokens that have 'sufficiently high' probabilities relative to the most likely token, functioning like a dynamic Top-P. A lower Top-A value narrows down the token choices based on the highest probability token, while a higher Top-A value refines the filtering without necessarily impacting the creativity of the output."},Ni={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."},Di={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."},Ki={type:"range",title:"Min P",description:"Specifies the minimum probability a token must have to be considered, in relation to the probability of the most likely token. (This value varies based on the confidence level of the top token.) For example, if Min-P is set to 0.1, only tokens with at least 1/10th the probability of the highest-ranked token will be considered."},Hi={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."},Vi={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."},Ji={type:"range",title:"Seed",description:"When seed is fixed to a specific value, the model makes a best effort to provide the same response for repeated requests. Deterministic output isn't guaranteed. Also, changing the model or parameter settings, such as the temperature, can cause variations in the response even when you use the same seed value. By default, a random seed value is used."},Gi={type:"range",title:"Repetition penalty",description:"Reduces the likelihood of repeating tokens from the input. Increasing this value makes the model less prone to repetition, but setting it too high may lead to less coherent output, often resulting in run-on sentences missing smaller words. The token penalty is scaled according to the original token's probability."},Wi={type:"boolean",title:"Log probs",description:"Whether to return log probabilities of the output tokens or not. If true, returns the log probabilities of each output token returned."},Zi={type:"range",title:"Top log probs",description:"The number of most likely tokens to return at each token position, each with an associated log probability. 'logprobs' must be set to true if this parameter is used."},Yi={type:"boolean",title:"Echo",description:"If true, the response will contain the prompt."},Qi={type:"select",title:"Response format",description:"Choose the response format of your model. For JSON, you must include the string 'JSON' in some form within your system / user prompt."},Xi={type:"select",title:"Response format",description:"Choose the response format of your model. 'json_object' colloquially known as JSON mode, instructs the model to respond with a valid JSON (must include the term 'json' in prompt). 'json_schema' colloquially known as structured outputs, allows you to specify a strict response schema that the model will adhere to."},es={type:"object",title:"Response schema",description:"When response format is set to 'json_schema', the model will return a JSON object of the specified schema."},T={TEMPERATURE:qi,MAX_TOKENS:Ui,STOP:Fi,TOP_A:Bi,TOP_P:Ni,TOP_K:Di,MIN_P:Ki,FREQUENCY_PENALTY:Hi,PRESENCE_PENALTY:Vi,REPETITION_PENALTY:Gi,SEED:Ji,LOG_PROBS:Wi,TOP_LOG_PROBS:Zi,ECHO:Yi,RESPONSE_FORMAT:Qi,RESPONSE_FORMAT_WITH_SCHEMA:Xi,RESPONSE_SCHEMA:es},Eo=t=>Object.fromEntries(Object.entries(t).filter(([o,n])=>n!=null)),H=t=>t==null?void 0:t.replace(/\/$/,""),ke=ne({param:"temperature",title:T.TEMPERATURE.title,description:T.TEMPERATURE.description,min:0,max:1,step:.01,default:1}),xe=t=>ne({param:"max_tokens",title:T.MAX_TOKENS.title,description:T.MAX_TOKENS.description,min:0,max:t,step:1,default:0}),je=t=>Pi({param:"stop_sequences",title:T.STOP(t).title,description:T.STOP(t).description,max:t}),Oe=ne({param:"top_p",title:T.TOP_P.title,description:T.TOP_P.description,min:0,max:1,step:.01,default:1}),Me=ne({param:"top_k",title:T.TOP_K.title,description:T.TOP_K.description,min:0,max:1,step:.01,default:1}),Ee=Ce({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"]}),Po=(t,o)=>e.z.object({temperature:ke.schema,maxTokens:xe(t).schema,stop:je(o).schema,topP:Oe.schema,topK:Me.schema,toolChoice:Ee.schema}),Io=(t,o)=>({temperature:ke.def,maxTokens:xe(t).def,stop:je(o).def,topP:Oe.def,topK:Me.def,toolChoice:Ee.def}),Pe=Ce({param:"encoding_format",title:"Encoding format",description:"Select the encoding format for the word embedding.",default:null,choices:["base64"]}),Ie=Ce({param:"input_type",title:"Input type",description:"Select the input type for the word embedding.",default:null,choices:["query","document"]}),Re=$i({param:"truncation",title:"Truncation",description:"Select the truncation for the word embedding.",default:!0}),Ro=()=>e.z.object({encodingFormat:Pe.schema,inputType:Ie.schema,truncation:Re.schema}),_o=()=>({encodingFormat:Pe.def,inputType:Ie.def,truncation:Re.def}),x={base:(t,o)=>({def:Io(t,o),schema:Po(t,o)})},z={base:()=>({def:_o(),schema:Ro()})},G=e.z.enum([V,I,w]),W={system:V,user:I,assistant:w},Z=[b,U,k,F],Y=e.z.enum([b,U,k,F]),ts=e.z.object({type:e.z.literal("text"),text:e.z.string()}),os=e.z.object({type:e.z.literal("tool_use"),id:e.z.string(),name:e.z.string(),input:e.z.record(e.z.any())}),Ao=e.z.object({content:e.z.array(e.z.discriminatedUnion("type",[ts,os])),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()})}),$o=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()})})}),Lo=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()})}),ns=e.z.object({type:e.z.literal("text"),text:e.z.string()}),as=e.z.object({type:e.z.literal("tool_use"),id:e.z.string(),name:e.z.string(),input:e.z.object({})}),qo=e.z.object({type:e.z.literal("content_block_start"),index:e.z.number(),content_block:e.z.discriminatedUnion("type",[ns,as])}),is=e.z.object({type:e.z.literal("text_delta"),text:e.z.string()}),ss=e.z.object({type:e.z.literal("input_json_delta"),partial_json:e.z.string()}),Uo=e.z.object({type:e.z.literal("content_block_delta"),index:e.z.number(),delta:e.z.discriminatedUnion("type",[is,ss])}),Fo=e.z.object({name:e.z.string().min(1),description:e.z.string().min(1).optional(),input_schema:e.z.any()}),Bo=e.z.object({type:e.z.enum(["auto","any"])}),No=e.z.object({type:e.z.literal("tool"),name:e.z.string().min(1)}),ie=e.z.object({text:e.z.string().min(1),type:e.z.literal("text")}),_e=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()})}),rs=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())}),Ae=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([ie,_e])).min(1))}),Do=e.z.object({role:e.z.literal("user"),content:e.z.string().min(1).or(e.z.array(e.z.union([ie,_e,Ae])).min(1))}),Ko=e.z.object({role:e.z.literal("assistant"),content:e.z.string().min(1).or(e.z.array(e.z.union([ie,Ae])).min(1))}),Ho=e.z.union([Do,Ko]),Vo=e.z.object({model:e.z.string().min(1).optional(),messages:e.z.array(Ho).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([Bo,No]).optional(),tools:e.z.array(Fo).min(1).optional(),top_p:e.z.number().min(0).max(1).optional(),top_k:e.z.number().min(0).optional()}),Jo="anthropic",J=class{constructor(){this.version="v1",this.name=Jo,this.chatModelFactories={[$e]:{model:Wo,modelOptions:Go,modelSchema:Le},[qe]:{model:Yo,modelOptions:Zo,modelSchema:Ue},[Fe]:{model:Xo,modelOptions:Qo,modelSchema:Be},[Ne]:{model:tn,modelOptions:en,modelSchema:De}},this.embeddingModelFactories={[et]:{model:yn,modelOptions:fn,modelSchema:tt},[Qe]:{model:gn,modelOptions:hn,modelSchema:Xe},[Ke]:{model:rn,modelOptions:sn,modelSchema:He},[Ve]:{model:dn,modelOptions:ln,modelSchema:Je},[Ge]:{model:cn,modelOptions:mn,modelSchema:We},[Ze]:{model:pn,modelOptions:un,modelSchema:Ye}};}chatModelLiterals(){return Object.keys(this.chatModelFactories)}chatModel(t,o){if(!(t in this.chatModelFactories))throw new te({info:`Anthropic chat model: ${t} not found`,cause:new Error(`Anthropic chat model: ${t} not found, available chat models:
10
+ ${this.chatModelLiterals().join(", ")}`)});let n=this.chatModelFactories[t].model,i=y({},o),r=this.chatModelFactories[t].modelOptions.parse(i);return new n(r)}chatModelSchema(t){if(!(t in this.chatModelFactories))throw new te({info:`Anthropic chat model: ${t} not found`,cause:new Error(`Anthropic chat model: ${t} not found, available chat models:
11
+ ${this.chatModelLiterals().join(", ")}`)});return this.chatModelFactories[t].modelSchema}chatModelSchemas(){return Object.keys(this.chatModelFactories).reduce((t,o)=>(t[o]=this.chatModelFactories[o].modelSchema,t),{})}embeddingModelLiterals(){return Object.keys(this.embeddingModelFactories)}embeddingModel(t,o){if(!(t in this.embeddingModelFactories))throw new te({info:`Anthropic embedding model: ${t} not found`,cause:new Error(`Anthropic embedding model: ${t} not found, available embedding models:
12
+ ${this.embeddingModelLiterals().join(", ")}`)});let n=this.embeddingModelFactories[t].model,i=y({},o),r=this.embeddingModelFactories[t].modelOptions.parse(i);return new n(r)}embeddingModelSchema(t){if(!(t in this.embeddingModelFactories))throw new te({info:`Anthropic embedding model: ${t} not found`,cause:new Error(`Anthropic embedding model: ${t} not found, available embedding models:
13
+ ${this.embeddingModelLiterals().join(", ")}`)});return this.embeddingModelFactories[t].modelSchema}embeddingModelSchemas(){return Object.keys(this.embeddingModelFactories).reduce((t,o)=>(t[o]=this.embeddingModelFactories[o].modelSchema,t),{})}};J.chatBaseUrl="https://api.anthropic.com/v1",J.embeddingBaseUrl="https://api.anthropic.com/v1";var D=e.z.object({apiKey:e.z.string(),completeChatUrl:e.z.string().url().optional(),streamChatUrl:e.z.string().url().optional()}),Q=class{constructor(t,o){this.version="v1";let n=D.parse(o);this.modelSchema=t,this.apiKey=n.apiKey,this.baseUrl=H(J.chatBaseUrl),this.completeChatUrl=H(n.completeChatUrl||`${this.baseUrl}/messages`),this.streamChatUrl=H(n.streamChatUrl||`${this.baseUrl}/messages`);}getDefaultBaseUrl(){return this.baseUrl}getDefaultHeaders(){return {"x-api-key":`${this.apiKey}`,"anthropic-version":"2023-06-01","content-type":"application/json",source:"adaline.ai"}}getDefaultParams(){return {model:this.modelSchema.name}}getRetryDelay(t){let o=0,n=!0;return t["x-should-retry"]&&(n=t["x-should-retry"].toLowerCase()!=="false"),t["retry-after"]&&(o=parseInt(t["retry-after"])*1e3),{shouldRetry:n,delayMs:o}}getTokenCount(t){return t.reduce((o,n)=>o+n.content.map(i=>i.modality==="text"?i.value:"").join(" ").length,0)}transformModelRequest(t){let o=Vo.safeParse(t);if(!o.success)throw new fe({info:"Invalid model request",cause:o.error});let n=o.data,i=n.model;if(n.tool_choice&&(!n.tools||n.tools.length===0))throw new fe({info:`Invalid model request for model : '${this.modelSchema.name}'`,cause:new Error("'tools' are required when 'tool_choice' is specified")});let r={};n.tool_choice&&(n.tool_choice.type==="tool"?r.toolChoice=n.tool_choice.name:r.toolChoice=n.tool_choice.type),r.maxTokens=n.max_tokens,r.temperature=n.temperature,r.topP=n.top_p,r.topK=n.top_k,r.stop=n.stop_sequences;let s=co().parse(Eo(r)),l=[],d={};n.system&&l.push({role:V,content:[{modality:b,value:n.system}]}),n.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 C=f.map(h=>{if(h.type==="text")return {modality:b,value:h.text};if(h.type==="image"){let de="auto",X=h.source.media_type.split("/")[1];return {modality:U,detail:de,value:{type:ao,media_type:X,base64:h.source.data}}}else return {modality:F,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:C});}}break;case"assistant":{let f=p.content;if(typeof f=="string")l.push({role:g,content:[{modality:b,value:f}]});else {let C=f.map((h,de)=>{if(h.type==="text")return {modality:b,value:h.text};{let X={modality:k,id:h.id,index:de,name:h.name,arguments:JSON.stringify(h.input)};return d[h.id]=X,X}});l.push({role:g,content:C});}}break}});let u=[];return n.tools&&n.tools.forEach(p=>{u.push({type:"function",definition:{schema:{name:p.name,description:p.description||"",parameters:p.input_schema}}});}),{modelName:i,config:s,messages:l,tools:u.length>0?u:void 0}}transformConfig(t,o,n){let i=t.toolChoice;delete t.toolChoice;let r=this.modelSchema.config.schema.safeParse(t);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}',
14
+ available keys : [${Object.keys(this.modelSchema.config.def).join(", ")}]`)})});let l=Object.keys(s).reduce((d,u)=>{let p=this.modelSchema.config.def[u],g=p.param,f=s[u];return g==="max_tokens"&&p.type==="range"&&f===0?d[g]=p.max:d[g]=f,d},{});if(!l.max_tokens)throw new P({info:`Invalid config for model : '${this.modelSchema.name}'`,cause:new Error(`'max_tokens' is required for model : '${this.modelSchema.name}'`)});if("tool_choice"in l&&l.tool_choice!==void 0){let d=l.tool_choice;if(!n||n&&n.length===0)throw new P({info:`Invalid config for model : '${this.modelSchema.name}'`,cause:new Error("'tools' are required when 'toolChoice' is specified")});if(n&&n.length>0){let u=this.modelSchema.config.def.toolChoice;if(!u.choices.includes(d))if(n.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
15
+ one of [${u.choices.join(", ")}]`)})}}return l}transformMessages(t){if(!t||t&&t.length===0)return {messages:[]};let o=t.map(s=>{let l=mo().safeParse(s);if(!l.success)throw new v({info:"Invalid messages",cause:l.error});return l.data});o.forEach(s=>{s.content.forEach(l=>{if(!this.modelSchema.modalities.includes(l.modality))throw new v({info:`Invalid message content for model : '${this.modelSchema.name}'`,cause:new Error(`model : '${this.modelSchema.name}' does not support modality : '${l.modality}',
16
+ available modalities : [${this.modelSchema.modalities.join(", ")}]`)})});}),o.forEach(s=>{if(!Object.keys(this.modelSchema.roles).includes(s.role))throw new v({info:`Invalid message content for model : '${this.modelSchema.name}'`,cause:new Error(`model : '${this.modelSchema.name}' does not support role : '${s.role}',
17
+ available roles : [${Object.keys(this.modelSchema.roles).join(", ")}]`)})});let n="",i=[];if(o.forEach(s=>{switch(s.role){case V:s.content.forEach(l=>{if(l.modality===b)n+=l.value;else throw new v({info:`Invalid message 'role' and 'modality' combination for model : ${this.modelSchema.name}`,cause:new Error(`role : '${s.role}' cannot have content with modality : '${l.modality}'`)})});break;case w:{let l=[];s.content.forEach(d=>{if(d.modality===b)l.push({type:"text",text:d.value});else if(d.modality===k)l.push({type:"tool_use",id:d.id,name:d.name,input:JSON.parse(d.arguments)});else throw new v({info:`Invalid message 'role' and 'modality' combination for model : ${this.modelSchema.name}`,cause:new Error(`role : '${s.role}' cannot have content with modality : '${d.modality}'`)})}),i.push({role:this.modelSchema.roles[s.role],content:l});}break;case I:{let l=[];s.content.forEach(d=>{if(d.modality===b)l.push({type:"text",text:d.value});else if(d.modality===U){if(d.value.type==="base64")l.push({type:"image",source:{type:"base64",media_type:`image/${d.value.media_type}`,data:d.value.base64}});else if(d.value.type==="url")throw new v({info:`Invalid message 'modality' for model : ${this.modelSchema.name}`,cause:new Error(`model: '${this.modelSchema.name}' does not support image content type: '${d.value.type}'`)})}else if(d.modality===F)l.push({type:"tool_result",tool_use_id:d.id,content:d.data});else throw new v({info:`Invalid message 'role' and 'modality' combination for model : ${this.modelSchema.name}`,cause:new Error(`role : '${s.role}' cannot have content with modality : '${d.modality}'`)})}),i.push({role:this.modelSchema.roles[s.role],content:l});}break;default:throw new v({info:`Invalid message 'role' for model : ${this.modelSchema.name}`,cause:new Error(`role : '${s.role}' is not supported,
18
+ available roles : [${Object.keys(this.modelSchema.roles).join(", ")}]`)})}}),i[0].role!==this.modelSchema.roles[I])throw new v({info:`Invalid message 'role' for model : ${this.modelSchema.name}`,cause:new Error(`model : '${this.modelSchema.name}' requires first message to be from user`)});let r=s=>s===this.modelSchema.roles[I]?this.modelSchema.roles[w]:this.modelSchema.roles[I];for(let s=1;s<i.length;s++)if(i[s].role!==r(i[s-1].role))throw new v({info:`Invalid message format for model : ${this.modelSchema.name}`,cause:new Error(`model : '${this.modelSchema.name}' requires messages to alternate between user and assistant`)});return {system:n,messages:i}}transformTools(t){if(!this.modelSchema.modalities.includes(k))throw new Xt({info:`Invalid tool 'modality' for model : ${this.modelSchema.name}`,cause:new Error(`model : '${this.modelSchema.name}' does not support tool modality : '${k}'`)});return !t||t&&t.length===0?{tools:[]}:{tools:t.map(o=>{let n=bi().safeParse(o);if(!n.success)throw new Xt({info:"Invalid tools",cause:n.error});return n.data}).map(o=>({name:o.definition.schema.name,description:o.definition.schema.description,function:o.definition.schema}))}}getCompleteChatUrl(t,o,n){return M(this,null,function*(){return new Promise(i=>{i(this.completeChatUrl);})})}getCompleteChatHeaders(t,o,n){return M(this,null,function*(){let i=this.getDefaultHeaders();return n&&n.length>0&&(i=Ut(y({},i),{"anthropic-beta":"tools-2024-05-16"})),new Promise(r=>{r(i);})})}getCompleteChatData(t,o,n){return M(this,null,function*(){let i=this.transformConfig(t,o,n),r=this.transformMessages(o);if(r.messages&&r.messages.length===0)throw new v({info:"Messages are required",cause:new Error("Messages are required")});let s=n?this.transformTools(n):{};return new Promise(l=>{l(y(y(y(y({},this.getDefaultParams()),i),r),s));})})}transformCompleteChatResponse(t){let o=Ao.safeParse(t);if(o.success){let n=o.data,i=n.content.map((l,d)=>{if(l.type==="text")return si(l.text);if(l.type==="tool_use")return ri(d,l.id,l.name,JSON.stringify(l.input))}),r=[{role:w,content:i}],s={promptTokens:n.usage.input_tokens,completionTokens:n.usage.output_tokens,totalTokens:n.usage.input_tokens+n.usage.output_tokens};return {messages:r,usage:s,logProbs:[]}}throw new O({info:"Invalid response from model",cause:o.error})}getStreamChatUrl(t,o,n){return M(this,null,function*(){return new Promise(i=>{i(this.streamChatUrl);})})}getStreamChatHeaders(t,o,n){let i=this.getDefaultHeaders();return n&&n.length>0&&(i=Ut(y({},i),{"anthropic-beta":"tools-2024-05-16"})),new Promise(r=>{r(i);})}getStreamChatData(t,o,n){return M(this,null,function*(){let i=this.transformConfig(t,o,n),r=this.transformMessages(o);if(r.messages&&r.messages.length===0)throw new v({info:"Messages are required",cause:new Error("Messages are required")});let s=n?this.transformTools(n):{};return new Promise(l=>{l(y(y(y(y({stream:!0},this.getDefaultParams()),i),r),s));})})}transformStreamChatResponseChunk(t,o){return Ua(this,null,function*(){let n=(o+t).split(`
19
+ `).filter(i=>i.trim()!=="");for(let i of n)if(i.startsWith("data: {")&&i.endsWith("}")){let r;try{r=JSON.parse(i.substring(6));}catch(s){throw new O({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=$o.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:o};}else throw new O({info:"Invalid response from model",cause:s.error})}else if(r.type==="message_delta"){let s=Lo.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:o};}else throw new O({info:"Invalid response from model",cause:s.error})}else if(r.type==="content_block_start"){let s=qo.safeParse(r);if(s.success){let l=s.data,d=[];l.content_block.type==="text"?d.push(Ft(w,l.content_block.text)):l.content_block.type==="tool_use"&&d.push(Bt(w,l.index,l.content_block.id,l.content_block.name,"")),yield {partialResponse:{partialMessages:d},buffer:o};}else throw new O({info:"Invalid response from model",cause:s.error})}else if(r.type==="content_block_delta"){let s=Uo.safeParse(r);if(s.success){let l=s.data,d=[];l.delta.type==="text_delta"?d.push(Ft(w,l.delta.text)):l.delta.type==="input_json_delta"&&d.push(Bt(w,l.index,"","",l.delta.partial_json)),yield {partialResponse:{partialMessages:d},buffer:o};}else throw new O({info:"Invalid response from model",cause:s.error})}}else throw new O({info:"Invalid JSON received in stream",cause:new Error(`Invalid JSON received in stream, expected 'type' property,
20
+ received : ${JSON.stringify(r)}`)})}})}},$e="claude-3-haiku-20240307",ls="Fastest and most compact model for near-instant responsiveness. Quick and accurate targeted performance.",Le=ae(G,Y).parse({name:$e,description:ls,maxInputTokens:2e5,maxOutputTokens:4096,roles:W,modalities:Z,config:{def:x.base(4096,4).def,schema:x.base(4096,4).schema}}),Go=D,Wo=class extends Q{constructor(t){super(Le,t);}},qe="claude-3-sonnet-20240229",ds="Balance of intelligence and speed. Strong utility, balanced for scaled deployments.",Ue=ae(G,Y).parse({name:qe,description:ds,maxInputTokens:2e5,maxOutputTokens:4096,roles:W,modalities:Z,config:{def:x.base(4096,4).def,schema:x.base(4096,4).schema}}),Zo=D,Yo=class extends Q{constructor(t){super(Ue,t);}},Fe="claude-3-opus-20240229",ms="Powerful model for highly complex tasks. Top-level performance, intelligence, fluency, and understanding.",Be=ae(G,Y).parse({name:Fe,description:ms,maxInputTokens:2e5,maxOutputTokens:4096,roles:W,modalities:Z,config:{def:x.base(4096,4).def,schema:x.base(4096,4).schema}}),Qo=D,Xo=class extends Q{constructor(t){super(Be,t);}},Ne="claude-3-5-sonnet-20240620",cs="Most intelligent model. Highest level of intelligence and capability.",De=ae(G,Y).parse({name:Ne,description:cs,maxInputTokens:2e5,maxOutputTokens:8192,roles:W,modalities:Z,config:{def:x.base(8192,4).def,schema:x.base(8192,4).schema}}),en=D,tn=class extends Q{constructor(t){super(De,t);}},_=[B],A=e.z.enum([B]),on=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()})}),nn=e.z.string().min(1).or(e.z.array(e.z.string().min(1)).min(1)),an=e.z.object({model:e.z.string().min(1).optional(),input:nn,encoding_format:e.z.enum(["base64"]).nullable().optional(),input_type:e.z.enum(["query","document"]).nullable().optional(),truncation:e.z.boolean().optional()}),E=e.z.object({apiKey:e.z.string(),getEmbeddingsUrl:e.z.string().url().optional()}),$=class{constructor(t,o){this.version="v1";let n=E.parse(o);this.modelSchema=t,this.apiKey=n.apiKey,this.baseUrl=H(J.embeddingBaseUrl),this.getEmbeddingsUrl=H(n.getEmbeddingsUrl||`${this.baseUrl}/embeddings`);}getDefaultBaseUrl(){return this.baseUrl}getDefaultHeaders(){return {Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json",source:"adaline.ai"}}getDefaultParams(){return {model:this.modelSchema.name}}getTokenCount(t){return t.requests.reduce((o,n)=>o+n.length,0)}getRetryDelay(t){return {shouldRetry:!0,delayMs:0}}transformModelRequest(t){let o=an.safeParse(t);if(!o.success)throw new fe({info:"Invalid model request",cause:o.error});let n=o.data,i=n.model,r={encodingFormat:n.encoding_format,inputType:n.input_type,truncation:n.truncation},s=co().parse(Eo(r)),l;return typeof n.input=="string"?l={modality:B,requests:[n.input]}:l={modality:B,requests:n.input},{modelName:i,config:s,embeddingRequests:l}}transformConfig(t,o){let n=this.modelSchema.config.schema.safeParse(t);if(!n.success)throw new P({info:`Invalid config for model : '${this.modelSchema.name}'`,cause:n.error});let i=n.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}',
21
+ 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(t){let o=Ci().safeParse(t);if(!o.success)throw new to({info:"Invalid embedding requests",cause:o.error});if(o.data.requests.length>128)throw new to({info:`Invalid embedding requests for model : '${this.modelSchema.name}'`,cause:new Error(`Max requests for model : '${this.modelSchema.name}' is 128`)});return {input:o.data.requests}}getGetEmbeddingsUrl(t,o){return M(this,null,function*(){return new Promise(n=>{n(this.getEmbeddingsUrl);})})}getGetEmbeddingsHeaders(t,o){return M(this,null,function*(){return new Promise(n=>{n(this.getDefaultHeaders());})})}getGetEmbeddingsData(t,o){return M(this,null,function*(){return new Promise(n=>{n(y(y(y({},this.getDefaultParams()),this.transformConfig(t,o)),this.transformEmbeddingRequests(o)));})})}transformGetEmbeddingsResponse(t){let o,n=on.safeParse(t);if(n.success){let i=n.data;o=typeof i.data[0].embedding=="string"?ho:po;let r=i.data.map(s=>typeof s.embedding=="string"?{index:s.index,embedding:s.embedding}:{index:s.index,embedding:s.embedding});return {encodingFormat:o,embeddings:r,usage:{totalTokens:i.usage.total_tokens}}}throw new O({info:"Invalid response from model",cause:n.error})}},Ke="voyage-code-2",us="Optimized for code retrieval.",He=N(A).parse({name:Ke,description:us,modalities:_,maxInputTokens:16e3,maxOutputTokens:16e3,config:{def:z.base().def,schema:z.base().schema}}),sn=E,rn=class extends ${constructor(t){super(He,t);}},Ve="voyage-law-2",ps="Optimized for legal and long-context retrieval and RAG. Also improved performance across all domains.",Je=N(A).parse({name:Ve,description:ps,modalities:_,maxInputTokens:16e3,maxOutputTokens:16e3,config:{def:z.base().def,schema:z.base().schema}}),ln=E,dn=class extends ${constructor(t){super(Je,t);}},Ge="voyage-multilingual-2",hs="Optimized for multilingual retrieval and RAG.",We=N(A).parse({name:Ge,description:hs,modalities:_,maxInputTokens:32e3,maxOutputTokens:32e3,config:{def:z.base().def,schema:z.base().schema}}),mn=E,cn=class extends ${constructor(t){super(We,t);}},Ze="voyage-finance-2",gs="Optimized for finance retrieval and RAG.",Ye=N(A).parse({name:Ze,description:gs,modalities:_,maxInputTokens:32e3,maxOutputTokens:32e3,config:{def:z.base().def,schema:z.base().schema}}),un=E,pn=class extends ${constructor(t){super(Ye,t);}},Qe="voyage-3-lite",fs="Optimized for latency and cost.",Xe=N(A).parse({name:Qe,description:fs,modalities:_,maxInputTokens:32e3,maxOutputTokens:32e3,config:{def:z.base().def,schema:z.base().schema}}),hn=E,gn=class extends ${constructor(t){super(Xe,t);}},et="voyage-3",ys="Optimized for quality.",tt=N(A).parse({name:et,description:ys,modalities:_,maxInputTokens:32e3,maxOutputTokens:32e3,config:{def:z.base().def,schema:z.base().schema}}),fn=E,yn=class extends ${constructor(t){super(tt,t);}};m.Anthropic=J;m.AnthropicChatModelConfigs=x;m.AnthropicChatModelModalities=Z;m.AnthropicChatModelModalitiesEnum=Y;m.AnthropicChatModelRoles=G;m.AnthropicChatModelRolesMap=W;m.AnthropicCompleteChatResponse=Ao;m.AnthropicEmbeddingModelConfigs=z;m.AnthropicEmbeddingModelModalities=_;m.AnthropicEmbeddingModelModalitiesEnum=A;m.AnthropicEmbeddingRequest=an;m.AnthropicEmbeddingRequestInput=nn;m.AnthropicGetEmbeddingsResponse=on;m.AnthropicRequest=Vo;m.AnthropicRequestAssistantMessage=Ko;m.AnthropicRequestImageContent=_e;m.AnthropicRequestMessage=Ho;m.AnthropicRequestTextContent=ie;m.AnthropicRequestTool=Fo;m.AnthropicRequestToolCallContent=rs;m.AnthropicRequestToolChoiceEnum=Bo;m.AnthropicRequestToolChoiceTool=No;m.AnthropicRequestToolResponseContent=Ae;m.AnthropicRequestUserMessage=Do;m.AnthropicStreamChatContentBlockDeltaResponse=Uo;m.AnthropicStreamChatContentBlockStartResponse=qo;m.AnthropicStreamChatMessageDeltaResponse=Lo;m.AnthropicStreamChatMessageStartResponse=$o;m.BaseChatModel=Q;m.BaseChatModelOptions=D;m.BaseEmbeddingModel=$;m.BaseEmbeddingModelOptions=E;m.ChatModelBaseConfigDef=Io;m.ChatModelBaseConfigSchema=Po;m.Claude3Haiku20240307=Wo;m.Claude3Haiku20240307Literal=$e;m.Claude3Haiku20240307Options=Go;m.Claude3Haiku20240307Schema=Le;m.Claude3Opus20240229=Xo;m.Claude3Opus20240229Literal=Fe;m.Claude3Opus20240229Options=Qo;m.Claude3Opus20240229Schema=Be;m.Claude3Sonnet20240229=Yo;m.Claude3Sonnet20240229Literal=qe;m.Claude3Sonnet20240229Options=Zo;m.Claude3Sonnet20240229Schema=Ue;m.Claude3_5Sonnet20240620=tn;m.Claude3_5Sonnet20240620Literal=Ne;m.Claude3_5Sonnet20240620Options=en;m.Claude3_5Sonnet20240620Schema=De;m.EmbeddingModelBaseConfigDef=_o;m.EmbeddingModelBaseConfigSchema=Ro;m.ProviderLiteral=Jo;m.Voyage3=yn;m.Voyage3Lite=gn;m.Voyage3LiteLiteral=Qe;m.Voyage3LiteOptions=hn;m.Voyage3LiteSchema=Xe;m.Voyage3Literal=et;m.Voyage3Options=fn;m.Voyage3Schema=tt;m.VoyageCode2=rn;m.VoyageCode2Literal=Ke;m.VoyageCode2Options=sn;m.VoyageCode2Schema=He;m.VoyageFinance2=pn;m.VoyageFinance2Literal=Ze;m.VoyageFinance2Options=un;m.VoyageFinance2Schema=Ye;m.VoyageLaw2=dn;m.VoyageLaw2Literal=Ve;m.VoyageLaw2Options=ln;m.VoyageLaw2Schema=Je;m.VoyageMultilingual2=cn;m.VoyageMultilingual2Literal=Ge;m.VoyageMultilingual2Options=mn;m.VoyageMultilingual2Schema=We;m.encodingFormat=Pe;m.inputType=Ie;m.maxTokens=xe;m.stop=je;m.temperature=ke;m.toolChoice=Ee;m.topK=Me;m.topP=Oe;m.truncation=Re;});var In=t=>{let o=new WeakSet;return JSON.stringify(t,(n,i)=>{if(typeof i=="object"&&i!==null){if(o.has(i))return;o.add(i);}return i})},Rn=t=>t==null?"unknown error":typeof t=="string"?t:t instanceof Error?t.message:In(t),ue="GatewayBaseError",pe=class ht extends Error{constructor({info:o,cause:n},i){super(`[${i!=null?i:ue}]: ${o}
22
+ Message: ${Rn(n)}`),this.name=ue,this.info=o,this.cause=n,this.name=i!=null?i:ue,Object.setPrototypeOf(this,new.target.prototype);}static isGatewayBaseError(o){return o instanceof ht}toJSON(){return {name:this.name,info:this.info,cause:this.cause,message:this.message,stack:this.stack}}},_n="system",An="user",gt="assistant",$n="tool",Ln=[_n,An,gt,$n],he=zod.z.enum(Ln),qn=[gt],Un=zod.z.enum(qn),ft="image",Fn="base64",Bn=["png","jpeg","webp","gif"],Nn=zod.z.object({type:zod.z.literal(Fn),base64:zod.z.string(),media_type:zod.z.enum(Bn)}),Dn="url",Kn=zod.z.object({type:zod.z.literal(Dn),url:zod.z.string()}),Hn=zod.z.discriminatedUnion("type",[Nn,Kn]),Vn=["low","medium","high","auto"],Jn=zod.z.enum(Vn),Gn=(t=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(ft),detail:Jn,value:Hn,metadata:t}),yt="text",Wn=(t=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(yt),value:zod.z.string(),metadata:t}),bt="partial-text",Zn=(t=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(bt),value:zod.z.string(),metadata:t}),zt="tool-call",Yn=(t=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(zt),index:zod.z.number().int().nonnegative(),id:zod.z.string().min(1),name:zod.z.string().min(1),arguments:zod.z.string(),metadata:t}),vt="partial-tool-call",Qn=(t=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(vt),index:zod.z.number().int().nonnegative(),id:zod.z.string().optional(),name:zod.z.string().optional(),arguments:zod.z.string().optional(),metadata:t}),wt="tool-response",Xn=(t=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(wt),index:zod.z.number().int().nonnegative(),id:zod.z.string().min(1),name:zod.z.string().min(1),data:zod.z.string(),metadata:t}),ea=[yt,ft,zt,wt],St=zod.z.enum(ea),ta=(t=zod.z.undefined(),o=zod.z.undefined(),n=zod.z.undefined(),i=zod.z.undefined())=>zod.z.discriminatedUnion("modality",[Wn(t),Gn(o),Yn(n),Xn(i)]),oa=[bt,vt];zod.z.enum(oa);var na=(t=zod.z.undefined(),o=zod.z.undefined())=>zod.z.discriminatedUnion("modality",[Zn(t),Qn(o)]);var aa=(t=he,o=zod.z.undefined(),n=zod.z.undefined(),i=zod.z.undefined(),r=zod.z.undefined(),s=zod.z.undefined())=>zod.z.object({role:t,content:zod.z.array(ta(o,n,i,r)),metadata:s}),ia=(t=Un,o=zod.z.undefined(),n=zod.z.undefined(),i=zod.z.undefined())=>zod.z.object({role:t,partialContent:na(o,n),metadata:i});var sa=["object","array","number","string","boolean","enum"],ct=zod.z.enum(sa),ra=zod.z.object({anyOf:zod.z.array(zod.z.any()).optional(),type:zod.z.union([ct,zod.z.array(zod.z.union([ct,zod.z.literal("null")]))]).optional(),default:zod.z.any().optional(),title:zod.z.string().optional(),description:zod.z.string().max(4096).optional(),properties:zod.z.record(zod.z.any()).optional(),required:zod.z.array(zod.z.string()).optional(),minItems:zod.z.number().int().min(0).optional(),maxItems:zod.z.number().int().optional(),items:zod.z.record(zod.z.any()).optional(),enum:zod.z.array(zod.z.union([zod.z.string(),zod.z.number(),zod.z.boolean(),zod.z.null()])).optional(),minimum:zod.z.number().optional(),maximum:zod.z.number().optional(),minLength:zod.z.number().int().min(0).optional(),maxLength:zod.z.number().int().optional(),$ref:zod.z.string().optional()}),la=zod.z.object({type:zod.z.enum(["object"]),required:zod.z.array(zod.z.string()),$defs:zod.z.record(zod.z.any()).optional(),properties:zod.z.record(ra),additionalProperties:zod.z.literal(!1)});zod.z.object({name:zod.z.string().regex(/^[a-zA-Z0-9_]{1,64}$/).max(64),description:zod.z.string().max(4096),strict:zod.z.boolean().optional(),schema:la}).optional();var da="function";var ma=zod.z.enum(["object","array","number","string","boolean","null"]),ca=zod.z.object({anyOf:zod.z.array(zod.z.any()).optional(),type:ma.optional(),default:zod.z.any().optional(),title:zod.z.string().optional(),description:zod.z.string().max(4096).optional(),properties:zod.z.record(zod.z.any()).optional(),required:zod.z.array(zod.z.string()).optional(),minItems:zod.z.number().int().min(0).optional(),maxItems:zod.z.number().int().optional(),items:zod.z.record(zod.z.any()).optional(),enum:zod.z.array(zod.z.union([zod.z.string(),zod.z.number(),zod.z.boolean(),zod.z.null()])).optional(),minimum:zod.z.number().optional(),maximum:zod.z.number().optional(),minLength:zod.z.number().int().min(0).optional(),maxLength:zod.z.number().int().optional()});zod.z.object({type:zod.z.enum(["object"]),title:zod.z.string().optional(),$defs:zod.z.record(zod.z.any()).optional(),properties:zod.z.record(ca).optional(),required:zod.z.array(zod.z.string()).optional()});var ua=zod.z.object({name:zod.z.string().regex(/^[a-zA-Z0-9_]{1,64}$/).max(64),description:zod.z.string().max(4096),parameters:zod.z.any(),strict:zod.z.boolean().optional()});var pa=zod.z.enum(["function"]);zod.z.object({type:pa,definition:zod.z.object({schema:ua})});var ha=[da];zod.z.enum(ha);var ga="text",fa="token",ya=[ga,fa];zod.z.enum(ya);zod.z.array(zod.z.string().min(1));zod.z.array(zod.z.array(zod.z.number().int().nonnegative()));var za="float",va=zod.z.object({index:zod.z.number().int().nonnegative(),embedding:zod.z.array(zod.z.number())}),wa="base64",Sa=zod.z.object({index:zod.z.number().int().nonnegative(),embedding:zod.z.string().base64()}),ut=zod.z.object({totalTokens:zod.z.number().int().nonnegative()});zod.z.discriminatedUnion("encodingFormat",[zod.z.object({encodingFormat:zod.z.literal(za),embeddings:zod.z.array(va),usage:ut.optional()}),zod.z.object({encodingFormat:zod.z.literal(wa),embeddings:zod.z.array(Sa),usage:ut.optional()})]);var Ct=zod.z.object({promptTokens:zod.z.number().nonnegative(),completionTokens:zod.z.number().nonnegative(),totalTokens:zod.z.number().nonnegative()}),pt=zod.z.object({token:zod.z.string(),logProb:zod.z.number(),bytes:zod.z.array(zod.z.number().int()).nullable()}),Ca=pt.extend({topLogProbs:zod.z.array(pt)}),Tt=zod.z.array(Ca);zod.z.object({messages:zod.z.array(aa()),usage:Ct.optional(),logProbs:Tt.optional()});zod.z.object({partialMessages:zod.z.array(ia()),usage:Ct.optional(),logProbs:Tt.optional()});var kt="ProviderError",K=class jt extends pe{constructor({info:o,cause:n}){super({info:o,cause:n},kt),this.name=kt,this.info=o,this.cause=n;}static isProviderError(o){return o instanceof jt}};var xt="ModelResponseError",Ot=class Mt extends pe{constructor({info:o,cause:n}){super({info:o,cause:n},xt),this.name=xt,this.cause=n,this.info=o;}static isModelResponseError(o){return o instanceof Mt}};var Et="multi-string",Ta=zod.z.object({type:zod.z.literal(Et),param:zod.z.string().min(1),title:zod.z.string().min(1),description:zod.z.string().min(1).max(500),max:zod.z.number().int().positive()});var Pt="range",ka=zod.z.object({type:zod.z.literal(Pt),param:zod.z.string().min(1),title:zod.z.string().min(1),description:zod.z.string().min(1).max(500),min:zod.z.number().int(),max:zod.z.number().int(),step:zod.z.number().positive(),default:zod.z.number()});var It="select-string",xa=zod.z.object({type:zod.z.literal(It),param:zod.z.string().min(1),title:zod.z.string().min(1),description:zod.z.string().min(1).max(500),default:zod.z.string().min(1).nullable(),choices:zod.z.array(zod.z.string().min(1))});var Rt="object-schema",ja=zod.z.object({type:zod.z.literal(Rt),param:zod.z.string().min(1),title:zod.z.string().min(1),description:zod.z.string().min(1).max(500),objectSchema:zod.z.any()});var _t="select-boolean",Oa=zod.z.object({type:zod.z.literal(_t),param:zod.z.string().min(1),title:zod.z.string().min(1),description:zod.z.string().min(1).max(500),default:zod.z.boolean().nullable()});var Ma=[Pt,Et,It,Rt,_t];zod.z.enum(Ma);var Ea=zod.z.discriminatedUnion("type",[ka,Ta,xa,Oa,ja]),At=(t=he,o=St)=>zod.z.object({name:zod.z.string().min(1),description:zod.z.string().min(1),roles:zod.z.record(t,zod.z.string().min(1).optional()),modalities:zod.z.array(o).nonempty(),maxInputTokens:zod.z.number().int().positive().min(1),maxOutputTokens:zod.z.number().int().positive().min(1),config:zod.z.object({def:zod.z.record(zod.z.string().min(1),Ea),schema:zod.z.instanceof(zod.z.ZodObject)}).refine(n=>{var i,r;let s=Object.keys(n.def),l=Object.keys((r=(i=n.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'"})});zod.z.record(zod.z.string());zod.z.record(zod.z.union([zod.z.boolean(),zod.z.string(),zod.z.number(),zod.z.object({}),zod.z.array(zod.z.any()),zod.z.null(),zod.z.undefined()]));zod.z.string().url();var Pa=()=>typeof window!="undefined"&&typeof window.document!="undefined"&&typeof navigator!="undefined";var $t=t=>{if(Pa()){let o=atob(t),n=new Uint8Array(o.length);for(let i=0;i<o.length;i++)n[i]=o.charCodeAt(i);return new TextDecoder("utf-8").decode(n)}else return Buffer.from(t,"base64").toString("utf-8")};var wn=dt(ot());var nt=zod.z.object({awsRegion:zod.z.string(),awsAccessKeyId:zod.z.string(),awsSecretAccessKey:zod.z.string()}),re=class t extends wn.BaseChatModel{constructor(n,i){let r=nt.parse(i);super(n,{apiKey:"random-api-key"});this.version="v1";this.modelSchema=n,this.awsRegion=r.awsRegion,this.awsUrl=L.awsUrl(this.awsRegion),this.awsService=L.awsService,this.awsAccessKeyId=r.awsAccessKeyId,this.awsSecretAccessKey=r.awsSecretAccessKey;}getDefaultBaseUrl(){return this.awsUrl}getDefaultHeaders(){return {Accept:"application/json","Content-Type":"application/json",host:this.awsUrl.split("://")[1]}}getDefaultParams(){return {anthropic_version:"bedrock-2023-05-31"}}getCompleteChatUrl(n,i,r){return new Promise(s=>{s(`${this.awsUrl}/model/${this.modelSchema.name}/invoke`);})}getCompleteChatHeaders(n,i,r){return q(this,null,function*(){let s=new URL(yield this.getCompleteChatUrl(n,i,r)),l={accessKeyId:this.awsAccessKeyId,secretAccessKey:this.awsSecretAccessKey},d=this.getDefaultHeaders(),u=this.getCompleteChatData(n||{},i||[],r),p=new protocolHttp.HttpRequest({hostname:s.hostname,path:s.pathname,protocol:s.protocol,method:"POST",body:JSON.stringify(u),headers:d});return (yield new signatureV4.SignatureV4({credentials:l,service:this.awsService,region:this.awsRegion,sha256:sha256Js.Sha256}).sign(p)).headers})}getCompleteChatData(n,i,r){return q(this,null,function*(){let s=j(j({},this.getDefaultParams()),ee(t.prototype,this,"getCompleteChatData").call(this,n,i,r));return new Promise(l=>{l(s);})})}getStreamChatUrl(n,i,r){return q(this,null,function*(){return new Promise(s=>{s(`${this.awsUrl}/model/${this.modelSchema.name}/invoke-with-response-stream`);})})}getStreamChatHeaders(n,i,r){return q(this,null,function*(){let s=new URL(yield this.getStreamChatUrl(n,i,r)),l={accessKeyId:this.awsAccessKeyId,secretAccessKey:this.awsSecretAccessKey},d=this.getDefaultHeaders(),u=this.getCompleteChatData(n||{},i||[],r),p=new protocolHttp.HttpRequest({hostname:s.hostname,path:s.pathname,protocol:s.protocol,method:"POST",body:JSON.stringify(u),headers:d});return (yield new signatureV4.SignatureV4({credentials:l,service:this.awsService,region:this.awsRegion,sha256:sha256Js.Sha256}).sign(p)).headers})}getStreamChatData(n,i,r){return q(this,null,function*(){let s=j(j({},this.getDefaultParams()),ee(t.prototype,this,"getStreamChatData").call(this,n,i,r));return "stream"in s&&delete s.stream,s})}transformStreamChatResponseChunk(n,i){return mt(this,null,function*(){let r=n.toString(),s=/{\s*"bytes"\s*:\s*"[\w=+/]+".*?}/g,l=r.match(s)||[];for(let d of l){let u=d.indexOf("{"),p=d.indexOf("}");if(u!==-1&&p!==-1&&u<p){let g;try{g=JSON.parse(d.slice(u,p+1));}catch(h){throw new Ot({info:"Malformed JSON received in stream",cause:new Error(`Malformed JSON received in stream : ${g}`)})}let f=$t(g.bytes),C=(yield new ce(ee(t.prototype,this,"transformStreamChatResponseChunk").call(this,`data: ${f}`,i).next())).value;C&&(yield C);}}})}};var S=dt(ot());var bs="anthropic.claude-3-haiku-20240307-v1:0",zs="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.",at=At(S.AnthropicChatModelRoles,S.AnthropicChatModelModalitiesEnum).parse({name:bs,description:zs,maxInputTokens:128e3,maxOutputTokens:128e3,roles:S.AnthropicChatModelRolesMap,modalities:S.AnthropicChatModelModalities,config:{def:S.AnthropicChatModelConfigs.base(128e3,4).def,schema:S.AnthropicChatModelConfigs.base(128e3,4).schema}}),Sn=nt,le=class extends re{constructor(o){super(at,o);}};var vs="bedrock",L=class{constructor(){this.version="v1";this.name=vs;this.chatModelFactories={"claude-3-haiku-20240307":{model:le,modelOptions:Sn,modelSchema:at}};this.embeddingModelFactories={};}chatModelLiterals(){return Object.keys(this.chatModelFactories)}chatModel(o,n){if(!(o in this.chatModelFactories))throw new K({info:`Bedrock chat model: ${o} not found`,cause:new Error(`Bedrock chat model: ${o} not found, available chat models:
23
+ ${this.chatModelLiterals().join(", ")}`)});let i=this.chatModelFactories[o].model,r=j({},n),s=this.chatModelFactories[o].modelOptions.parse(r);return new i(s)}chatModelSchema(o){if(!(o in this.chatModelFactories))throw new K({info:`Bedrock chat model: ${o} not found`,cause:new Error(`Bedrock chat model: ${o} not found, available chat models:
24
+ ${this.chatModelLiterals().join(", ")}`)});return this.chatModelFactories[o].modelSchema}chatModelSchemas(){return Object.keys(this.chatModelFactories).reduce((o,n)=>(o[n]=this.chatModelFactories[n].modelSchema,o),{})}embeddingModelLiterals(){return Object.keys(this.embeddingModelFactories)}embeddingModel(o,n){if(!(o in this.embeddingModelFactories))throw new K({info:`Bedrock embedding model: ${o} not found`,cause:new Error(`Bedrock embedding model: ${o} not found, available embedding models:
25
+ ${this.embeddingModelLiterals().join(", ")}`)});let i=this.embeddingModelFactories[o].model,r=j({},n),s=this.embeddingModelFactories[o].modelOptions.parse(r);return new i(s)}embeddingModelSchema(o){if(!(o in this.embeddingModelFactories))throw new K({info:`Bedrock embedding model: ${o} not found`,cause:new Error(`Bedrock embedding model: ${o} not found, available embedding models:
26
+ ${this.embeddingModelLiterals().join(", ")}`)});return this.embeddingModelFactories[o].modelSchema}embeddingModelSchemas(){return Object.keys(this.embeddingModelFactories).reduce((o,n)=>(o[n]=this.embeddingModelFactories[n].modelSchema,o),{})}};L.awsService="bedrock",L.awsUrl=o=>`https://bedrock.${o}.amazonaws.com`;
27
27
 
28
- exports.BaseChatModelAnthropic = J;
29
- exports.BaseChatModelAnthropicOptions = Te;
30
- exports.Bedrock = E;
31
- exports.BedrockClaude3Haiku20240307 = G;
28
+ exports.BaseChatModelAnthropic = re;
29
+ exports.BaseChatModelAnthropicOptions = nt;
30
+ exports.Bedrock = L;
31
+ exports.BedrockClaude3Haiku20240307 = le;
32
32
  exports.BedrockClaude3Haiku20240307Options = Sn;
33
- exports.BedrockClaude3Haiku20240307Schema = Me;
33
+ exports.BedrockClaude3Haiku20240307Schema = at;
34
34
  //# sourceMappingURL=index.js.map
35
35
  //# sourceMappingURL=index.js.map