@adaline/bedrock 0.22.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -5,16 +5,16 @@ 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 Ko=Object.defineProperty,Vo=Object.defineProperties;var Jo=Object.getOwnPropertyDescriptors;var xt=Object.getOwnPropertySymbols,Go=Object.getPrototypeOf,Zo=Object.prototype.hasOwnProperty,Wo=Object.prototype.propertyIsEnumerable,Xo=Reflect.get;var me=(t,n)=>(n=Symbol[t])?n:Symbol.for("Symbol."+t),Yo=t=>{throw TypeError(t)};var Mt=(t,n,o)=>n in t?Ko(t,n,{enumerable:!0,configurable:!0,writable:!0,value:o}):t[n]=o,B=(t,n)=>{for(var o in n||(n={}))Zo.call(n,o)&&Mt(t,o,n[o]);if(xt)for(var o of xt(n))Wo.call(n,o)&&Mt(t,o,n[o]);return t},X=(t,n)=>Vo(t,Jo(n));var ue=(t,n,o)=>Xo(Go(t),o,n);var N=(t,n,o)=>new Promise((s,i)=>{var l=m=>{try{d(o.next(m));}catch(u){i(u);}},r=m=>{try{d(o.throw(m));}catch(u){i(u);}},d=m=>m.done?s(m.value):Promise.resolve(m.value).then(l,r);d((o=o.apply(t,n)).next());}),pe=function(t,n){this[0]=t,this[1]=n;},Ne=(t,n,o)=>{var s=(r,d,m,u)=>{try{var g=o[r](d),f=(d=g.value)instanceof pe,h=g.done;Promise.resolve(f?d[0]:d).then(p=>f?s(r==="return"?r:"next",d[1]?{done:p.done,value:p.value}:p,m,u):m({value:p,done:h})).catch(p=>s("throw",p,m,u));}catch(p){u(p);}},i=r=>l[r]=d=>new Promise((m,u)=>s(r,d,m,u)),l={};return o=o.apply(t,n),l[me("asyncIterator")]=()=>l,i("next"),i("throw"),i("return"),l},he=t=>{var n=t[me("asyncIterator")],o=!1,s,i={};return n==null?(n=t[me("iterator")](),s=l=>i[l]=r=>n[l](r)):(n=n.call(t),s=l=>i[l]=r=>{if(o){if(o=!1,l==="throw")throw r;return r}return o=!0,{done:!1,value:new pe(new Promise(d=>{var m=n[l](r);m instanceof Object||Yo("Object expected"),d(m);}),1)}}),i[me("iterator")]=()=>i,s("next"),"throw"in n?s("throw"):i.throw=l=>{throw l},"return"in n&&s("return"),i};var Qo=Object.defineProperty,ea=Object.defineProperties,ta=Object.getOwnPropertyDescriptors,wt=Object.getOwnPropertySymbols,na=Object.prototype.hasOwnProperty,oa=Object.prototype.propertyIsEnumerable,ge=(t,n)=>(n=Symbol[t])?n:Symbol.for("Symbol."+t),aa=t=>{throw TypeError(t)},St=(t,n,o)=>n in t?Qo(t,n,{enumerable:!0,configurable:!0,writable:!0,value:o}):t[n]=o,x=(t,n)=>{for(var o in n||(n={}))na.call(n,o)&&St(t,o,n[o]);if(wt)for(var o of wt(n))oa.call(n,o)&&St(t,o,n[o]);return t},Kt=(t,n)=>ea(t,ta(n)),E=(t,n,o)=>new Promise((s,i)=>{var l=m=>{try{d(o.next(m));}catch(u){i(u);}},r=m=>{try{d(o.throw(m));}catch(u){i(u);}},d=m=>m.done?s(m.value):Promise.resolve(m.value).then(l,r);d((o=o.apply(t,n)).next());}),Vt=function(t,n){this[0]=t,this[1]=n;},Pt=(t,n,o)=>{var s=(r,d,m,u)=>{try{var g=o[r](d),f=(d=g.value)instanceof Vt,h=g.done;Promise.resolve(f?d[0]:d).then(p=>f?s(r==="return"?r:"next",d[1]?{done:p.done,value:p.value}:p,m,u):m({value:p,done:h})).catch(p=>s("throw",p,m,u));}catch(p){u(p);}},i=r=>l[r]=d=>new Promise((m,u)=>s(r,d,m,u)),l={};return o=o.apply(t,n),l[ge("asyncIterator")]=()=>l,i("next"),i("throw"),i("return"),l},ia=t=>{var n=t[ge("asyncIterator")],o=!1,s,i={};return n==null?(n=t[ge("iterator")](),s=l=>i[l]=r=>n[l](r)):(n=n.call(t),s=l=>i[l]=r=>{if(o){if(o=!1,l==="throw")throw r;return r}return o=!0,{done:!1,value:new Vt(new Promise(d=>{var m=n[l](r);m instanceof Object||aa("Object expected"),d(m);}),1)}}),i[ge("iterator")]=()=>i,s("next"),"throw"in n?s("throw"):i.throw=l=>{throw l},"return"in n&&s("return"),i},re="system",Y="user",S="assistant",Je="tool",sa=[re,Y,S,Je],Jt=zod.z.enum(sa),ra=[S],la=zod.z.enum(ra),K="image",Gt="base64",da=["png","jpeg","webp","gif"],ca=zod.z.object({type:zod.z.literal(Gt),base64:zod.z.string(),media_type:zod.z.enum(da)}),ma="url",ua=zod.z.object({type:zod.z.literal(ma),url:zod.z.string()}),pa=zod.z.discriminatedUnion("type",[ca,ua]),ha=["low","medium","high","auto"],ga=zod.z.enum(ha),fa=(t=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(K),detail:ga,value:pa,metadata:t}),V="reasoning",ye="partial-reasoning",be="thinking",Ge="redacted",$e=zod.z.object({type:zod.z.literal(be),thinking:zod.z.string(),signature:zod.z.string()}),Zt=zod.z.object({type:zod.z.literal(Ge),data:zod.z.string()}),ya=zod.z.discriminatedUnion("type",[$e,Zt]),Ze=(t=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(V),value:ya,metadata:t}),ba=zod.z.object({type:zod.z.literal(be),thinking:$e.shape.thinking.optional(),signature:$e.shape.signature.optional()}),ka=zod.z.discriminatedUnion("type",[ba,Zt]),We=(t=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(ye),value:ka,metadata:t}),M="text",Wt=(t=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(M),value:zod.z.string(),metadata:t}),Xe="partial-text",Xt=(t=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(Xe),value:zod.z.string(),metadata:t}),U="tool-call",Yt=(t=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(U),index:zod.z.number().int().nonnegative(),id:zod.z.string().min(1),name:zod.z.string().min(1),arguments:zod.z.string(),metadata:t}),Ye="partial-tool-call",Qt=(t=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(Ye),index:zod.z.number().int().nonnegative(),id:zod.z.string().optional(),name:zod.z.string().optional(),arguments:zod.z.string().optional(),metadata:t}),J="tool-response",va=(t=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(J),index:zod.z.number().int().nonnegative(),id:zod.z.string().min(1),name:zod.z.string().min(1),data:zod.z.string(),metadata:t}),Ta=[M,K,U,J,V],Ca=zod.z.enum(Ta),xa=(t=zod.z.undefined(),n=zod.z.undefined(),o=zod.z.undefined(),s=zod.z.undefined(),i=zod.z.undefined())=>zod.z.discriminatedUnion("modality",[Wt(t),fa(n),Yt(o),va(s),Ze(i)]),Ma=[Xe,Ye,ye];zod.z.enum(Ma);var wa=(t=zod.z.undefined(),n=zod.z.undefined(),o=zod.z.undefined())=>zod.z.discriminatedUnion("modality",[Xt(t),Qt(n),We(o)]),en=(t=Jt,n=zod.z.undefined(),o=zod.z.undefined(),s=zod.z.undefined(),i=zod.z.undefined(),l=zod.z.undefined(),r=zod.z.undefined())=>zod.z.object({role:t,content:zod.z.array(xa(n,o,s,i,r)),metadata:l}),le=(t=la,n=zod.z.undefined(),o=zod.z.undefined(),s=zod.z.undefined(),i=zod.z.undefined())=>zod.z.object({role:t,partialContent:wa(n,o,s),metadata:i}),Sa=zod.z.object({promptTokens:zod.z.number().nonnegative(),completionTokens:zod.z.number().nonnegative(),totalTokens:zod.z.number().nonnegative()}),Ot=zod.z.object({token:zod.z.string(),logProb:zod.z.number(),bytes:zod.z.array(zod.z.number().int()).nullable()}),Pa=Ot.extend({topLogProbs:zod.z.array(Ot)}),tn=zod.z.array(Pa);zod.z.object({messages:zod.z.array(en()),usage:Sa.optional(),logProbs:tn.optional()});var Oa=zod.z.object({promptTokens:zod.z.number().nonnegative().optional(),completionTokens:zod.z.number().nonnegative().optional(),totalTokens:zod.z.number().nonnegative().optional()});zod.z.object({partialMessages:zod.z.array(le()),usage:Oa.optional(),logProbs:tn.optional()});var nn=(t=zod.z.record(zod.z.string(),zod.z.any()).optional())=>t,Ra=["object","array","number","string","boolean","enum"],Rt=zod.z.enum(Ra),ja=zod.z.object({anyOf:zod.z.array(zod.z.any()).optional(),type:zod.z.union([Rt,zod.z.array(zod.z.union([Rt,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()}),Ea=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(ja),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:Ea}).optional();var Q="text",on="token",_a=[Q,on],Ia=zod.z.enum(_a),Aa=zod.z.array(zod.z.string().min(1)),Ba=zod.z.array(zod.z.array(zod.z.number().int().nonnegative())),Na=(t=zod.z.undefined())=>zod.z.discriminatedUnion("modality",[zod.z.object({modality:zod.z.literal(Q),metadata:t,requests:Aa}),zod.z.object({modality:zod.z.literal(on),metadata:t,requests:Ba})]),an="float",Ua=zod.z.object({index:zod.z.number().int().nonnegative(),embedding:zod.z.array(zod.z.number())}),sn="base64",La=zod.z.object({index:zod.z.number().int().nonnegative(),embedding:zod.z.string().base64()}),jt=zod.z.object({totalTokens:zod.z.number().int().nonnegative()});zod.z.discriminatedUnion("encodingFormat",[zod.z.object({encodingFormat:zod.z.literal(an),embeddings:zod.z.array(Ua),usage:jt.optional()}),zod.z.object({encodingFormat:zod.z.literal(sn),embeddings:zod.z.array(La),usage:jt.optional()})]);var $a=t=>{let n=new WeakSet;return JSON.stringify(t,(o,s)=>{if(typeof s=="object"&&s!==null){if(n.has(s))return;n.add(s);}return s})},qa=t=>t==null?"unknown error":typeof t=="string"?t:t instanceof Error?t.message:$a(t),Ue="GatewayBaseError",Z=class rn extends Error{constructor({info:n,cause:o},s){super(`[${s!=null?s:Ue}]: ${n}
8
+ var Ko=Object.defineProperty,Vo=Object.defineProperties;var Jo=Object.getOwnPropertyDescriptors;var xt=Object.getOwnPropertySymbols,Go=Object.getPrototypeOf,Zo=Object.prototype.hasOwnProperty,Wo=Object.prototype.propertyIsEnumerable,Xo=Reflect.get;var me=(t,n)=>(n=Symbol[t])?n:Symbol.for("Symbol."+t),Yo=t=>{throw TypeError(t)};var Mt=(t,n,o)=>n in t?Ko(t,n,{enumerable:!0,configurable:!0,writable:!0,value:o}):t[n]=o,B=(t,n)=>{for(var o in n||(n={}))Zo.call(n,o)&&Mt(t,o,n[o]);if(xt)for(var o of xt(n))Wo.call(n,o)&&Mt(t,o,n[o]);return t},X=(t,n)=>Vo(t,Jo(n));var ue=(t,n,o)=>Xo(Go(t),o,n);var N=(t,n,o)=>new Promise((s,i)=>{var l=m=>{try{d(o.next(m));}catch(u){i(u);}},r=m=>{try{d(o.throw(m));}catch(u){i(u);}},d=m=>m.done?s(m.value):Promise.resolve(m.value).then(l,r);d((o=o.apply(t,n)).next());}),pe=function(t,n){this[0]=t,this[1]=n;},Ne=(t,n,o)=>{var s=(r,d,m,u)=>{try{var g=o[r](d),f=(d=g.value)instanceof pe,h=g.done;Promise.resolve(f?d[0]:d).then(p=>f?s(r==="return"?r:"next",d[1]?{done:p.done,value:p.value}:p,m,u):m({value:p,done:h})).catch(p=>s("throw",p,m,u));}catch(p){u(p);}},i=r=>l[r]=d=>new Promise((m,u)=>s(r,d,m,u)),l={};return o=o.apply(t,n),l[me("asyncIterator")]=()=>l,i("next"),i("throw"),i("return"),l},he=t=>{var n=t[me("asyncIterator")],o=!1,s,i={};return n==null?(n=t[me("iterator")](),s=l=>i[l]=r=>n[l](r)):(n=n.call(t),s=l=>i[l]=r=>{if(o){if(o=!1,l==="throw")throw r;return r}return o=!0,{done:!1,value:new pe(new Promise(d=>{var m=n[l](r);m instanceof Object||Yo("Object expected"),d(m);}),1)}}),i[me("iterator")]=()=>i,s("next"),"throw"in n?s("throw"):i.throw=l=>{throw l},"return"in n&&s("return"),i};var Qo=Object.defineProperty,ea=Object.defineProperties,ta=Object.getOwnPropertyDescriptors,wt=Object.getOwnPropertySymbols,na=Object.prototype.hasOwnProperty,oa=Object.prototype.propertyIsEnumerable,ge=(t,n)=>(n=Symbol[t])?n:Symbol.for("Symbol."+t),aa=t=>{throw TypeError(t)},St=(t,n,o)=>n in t?Qo(t,n,{enumerable:!0,configurable:!0,writable:!0,value:o}):t[n]=o,x=(t,n)=>{for(var o in n||(n={}))na.call(n,o)&&St(t,o,n[o]);if(wt)for(var o of wt(n))oa.call(n,o)&&St(t,o,n[o]);return t},Kt=(t,n)=>ea(t,ta(n)),E=(t,n,o)=>new Promise((s,i)=>{var l=m=>{try{d(o.next(m));}catch(u){i(u);}},r=m=>{try{d(o.throw(m));}catch(u){i(u);}},d=m=>m.done?s(m.value):Promise.resolve(m.value).then(l,r);d((o=o.apply(t,n)).next());}),Vt=function(t,n){this[0]=t,this[1]=n;},Pt=(t,n,o)=>{var s=(r,d,m,u)=>{try{var g=o[r](d),f=(d=g.value)instanceof Vt,h=g.done;Promise.resolve(f?d[0]:d).then(p=>f?s(r==="return"?r:"next",d[1]?{done:p.done,value:p.value}:p,m,u):m({value:p,done:h})).catch(p=>s("throw",p,m,u));}catch(p){u(p);}},i=r=>l[r]=d=>new Promise((m,u)=>s(r,d,m,u)),l={};return o=o.apply(t,n),l[ge("asyncIterator")]=()=>l,i("next"),i("throw"),i("return"),l},ia=t=>{var n=t[ge("asyncIterator")],o=!1,s,i={};return n==null?(n=t[ge("iterator")](),s=l=>i[l]=r=>n[l](r)):(n=n.call(t),s=l=>i[l]=r=>{if(o){if(o=!1,l==="throw")throw r;return r}return o=!0,{done:!1,value:new Vt(new Promise(d=>{var m=n[l](r);m instanceof Object||aa("Object expected"),d(m);}),1)}}),i[ge("iterator")]=()=>i,s("next"),"throw"in n?s("throw"):i.throw=l=>{throw l},"return"in n&&s("return"),i},re="system",Y="user",S="assistant",Je="tool",sa=[re,Y,S,Je],Jt=zod.z.enum(sa),ra=[S],la=zod.z.enum(ra),K="image",Gt="base64",da=["png","jpeg","webp","gif"],ca=zod.z.object({type:zod.z.literal(Gt),base64:zod.z.string(),mediaType:zod.z.enum(da)}),ma="url",ua=zod.z.object({type:zod.z.literal(ma),url:zod.z.string()}),pa=zod.z.discriminatedUnion("type",[ca,ua]),ha=["low","medium","high","auto"],ga=zod.z.enum(ha),fa=(t=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(K),detail:ga,value:pa,metadata:t}),V="reasoning",ye="partial-reasoning",be="thinking",Ge="redacted",$e=zod.z.object({type:zod.z.literal(be),thinking:zod.z.string(),signature:zod.z.string()}),Zt=zod.z.object({type:zod.z.literal(Ge),data:zod.z.string()}),ya=zod.z.discriminatedUnion("type",[$e,Zt]),Ze=(t=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(V),value:ya,metadata:t}),ba=zod.z.object({type:zod.z.literal(be),thinking:$e.shape.thinking.optional(),signature:$e.shape.signature.optional()}),ka=zod.z.discriminatedUnion("type",[ba,Zt]),We=(t=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(ye),value:ka,metadata:t}),M="text",Wt=(t=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(M),value:zod.z.string(),metadata:t}),Xe="partial-text",Xt=(t=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(Xe),value:zod.z.string(),metadata:t}),U="tool-call",Yt=(t=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(U),index:zod.z.number().int().nonnegative(),id:zod.z.string().min(1),name:zod.z.string().min(1),arguments:zod.z.string(),metadata:t}),Ye="partial-tool-call",Qt=(t=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(Ye),index:zod.z.number().int().nonnegative(),id:zod.z.string().optional(),name:zod.z.string().optional(),arguments:zod.z.string().optional(),metadata:t}),J="tool-response",va=(t=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(J),index:zod.z.number().int().nonnegative(),id:zod.z.string().min(1),name:zod.z.string().min(1),data:zod.z.string(),metadata:t}),Ta=[M,K,U,J,V],Ca=zod.z.enum(Ta),xa=(t=zod.z.undefined(),n=zod.z.undefined(),o=zod.z.undefined(),s=zod.z.undefined(),i=zod.z.undefined())=>zod.z.discriminatedUnion("modality",[Wt(t),fa(n),Yt(o),va(s),Ze(i)]),Ma=[Xe,Ye,ye];zod.z.enum(Ma);var wa=(t=zod.z.undefined(),n=zod.z.undefined(),o=zod.z.undefined())=>zod.z.discriminatedUnion("modality",[Xt(t),Qt(n),We(o)]),en=(t=Jt,n=zod.z.undefined(),o=zod.z.undefined(),s=zod.z.undefined(),i=zod.z.undefined(),l=zod.z.undefined(),r=zod.z.undefined())=>zod.z.object({role:t,content:zod.z.array(xa(n,o,s,i,r)),metadata:l}),le=(t=la,n=zod.z.undefined(),o=zod.z.undefined(),s=zod.z.undefined(),i=zod.z.undefined())=>zod.z.object({role:t,partialContent:wa(n,o,s),metadata:i}),Sa=zod.z.object({promptTokens:zod.z.number().nonnegative(),completionTokens:zod.z.number().nonnegative(),totalTokens:zod.z.number().nonnegative()}),Ot=zod.z.object({token:zod.z.string(),logProb:zod.z.number(),bytes:zod.z.array(zod.z.number().int()).nullable()}),Pa=Ot.extend({topLogProbs:zod.z.array(Ot)}),tn=zod.z.array(Pa);zod.z.object({messages:zod.z.array(en()),usage:Sa.optional(),logProbs:tn.optional()});var Oa=zod.z.object({promptTokens:zod.z.number().nonnegative().optional(),completionTokens:zod.z.number().nonnegative().optional(),totalTokens:zod.z.number().nonnegative().optional()});zod.z.object({partialMessages:zod.z.array(le()),usage:Oa.optional(),logProbs:tn.optional()});var nn=(t=zod.z.record(zod.z.string(),zod.z.any()).optional())=>t,Ra=["object","array","number","string","boolean","enum"],Rt=zod.z.enum(Ra),ja=zod.z.object({anyOf:zod.z.array(zod.z.any()).optional(),type:zod.z.union([Rt,zod.z.array(zod.z.union([Rt,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()}),Ea=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(ja),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:Ea}).optional();var Q="text",on="token",_a=[Q,on],Ia=zod.z.enum(_a),Aa=zod.z.array(zod.z.string().min(1)),Ba=zod.z.array(zod.z.array(zod.z.number().int().nonnegative())),Na=(t=zod.z.undefined())=>zod.z.discriminatedUnion("modality",[zod.z.object({modality:zod.z.literal(Q),metadata:t,requests:Aa}),zod.z.object({modality:zod.z.literal(on),metadata:t,requests:Ba})]),an="float",Ua=zod.z.object({index:zod.z.number().int().nonnegative(),embedding:zod.z.array(zod.z.number())}),sn="base64",La=zod.z.object({index:zod.z.number().int().nonnegative(),embedding:zod.z.string().base64()}),jt=zod.z.object({totalTokens:zod.z.number().int().nonnegative()});zod.z.discriminatedUnion("encodingFormat",[zod.z.object({encodingFormat:zod.z.literal(an),embeddings:zod.z.array(Ua),usage:jt.optional()}),zod.z.object({encodingFormat:zod.z.literal(sn),embeddings:zod.z.array(La),usage:jt.optional()})]);var $a=t=>{let n=new WeakSet;return JSON.stringify(t,(o,s)=>{if(typeof s=="object"&&s!==null){if(n.has(s))return;n.add(s);}return s})},qa=t=>t==null?"unknown error":typeof t=="string"?t:t instanceof Error?t.message:$a(t),Ue="GatewayBaseError",Z=class rn extends Error{constructor({info:n,cause:o},s){super(`[${s!=null?s:Ue}]: ${n}
9
9
  Message: ${qa(o)}`),this.name=Ue,this.info=n,this.cause=o,this.name=s!=null?s:Ue,Object.setPrototypeOf(this,new.target.prototype);}static isGatewayBaseError(n){return n instanceof rn}toJSON(){return {name:this.name,info:this.info,cause:this.cause,message:this.message,stack:this.stack}}},Da=zod.z.object({inputPricePerMillion:zod.z.number().nonnegative().describe("Price per 1M input tokens"),outputPricePerMillion:zod.z.number().nonnegative().describe("Price per 1M output tokens")}).describe("Input/output price pair (per 1M tokens) for a specific category within a ChatModel pricing tier."),Ha=zod.z.object({base:Da.describe("Base (uncached, non\u2011reasoning) rates")}).describe("Holds the `ChatModelTokenPairPrice` for different categories (e.g., base) within a single pricing tier."),Fa=zod.z.object({minTokens:zod.z.number().int().nonnegative().describe("Inclusive lower token bound for this tier."),maxTokens:zod.z.number().int().nullable().optional().describe("Exclusive upper token bound; `null` means \u221E."),prices:Ha.describe("Price categories and rates for this specific token range.")}).refine(t=>t.maxTokens===null||typeof t.maxTokens=="number"&&t.maxTokens>t.minTokens,{message:"maxTokens must be > minTokens (or null for infinite).",path:["maxTokens"]}).describe("A single pricing tier defined by a token range and associated prices.");zod.z.object({modelName:zod.z.string().describe("Model name this schedule applies to."),currency:zod.z.string().default("USD").describe("Currency code (e.g., USD)."),tokenRanges:zod.z.array(Fa).min(1).describe("Pricing tiers (`ChatModelTokenRangePrice`) schedule, sorted by minTokens.")}).superRefine((t,n)=>{let{tokenRanges:o}=t;o[0].minTokens!==0&&n.addIssue({code:zod.z.ZodIssueCode.custom,path:["tokenRanges",0,"minTokens"],message:"The first tier must have minTokens = 0."});for(let i=1;i<o.length;i++){let l=o[i-1],r=o[i];if(l.maxTokens===null){n.addIssue({code:zod.z.ZodIssueCode.custom,path:["tokenRanges",i-1,"maxTokens"],message:"Cannot define any tokenRanges after an infinite tier (maxTokens = null)."});break}r.minTokens!==l.maxTokens&&n.addIssue({code:zod.z.ZodIssueCode.custom,path:["tokenRanges",i,"minTokens"],message:`Tier ${i} minTokens (${r.minTokens}) must equal previous tier's maxTokens (${l.maxTokens}) for contiguity.`}),r.minTokens<l.minTokens&&n.addIssue({code:zod.z.ZodIssueCode.custom,path:["tokenRanges",i,"minTokens"],message:`tokenRanges must be sorted by ascending minTokens. Tier ${i} (${r.minTokens}) starts before Tier ${i-1} (${l.minTokens}).`});}let s=o[o.length-1];o.every(i=>i.maxTokens!==null||i===s)&&s.maxTokens!==null&&n.addIssue({code:zod.z.ZodIssueCode.custom,path:["tokenRanges",o.length-1,"maxTokens"],message:"The final tier must have maxTokens = null (representing infinity)."});}).describe("Complete pricing schedule for a single chat model, including all its token-based tiers.");var za="function",Ka=zod.z.enum(["object","array","number","string","boolean","null"]),Va=zod.z.object({anyOf:zod.z.array(zod.z.any()).optional(),type:Ka.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(Va).optional(),required:zod.z.array(zod.z.string()).optional()});var Ja=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()}),Ga=zod.z.enum(["function"]),Za=zod.z.object({type:Ga,definition:zod.z.object({schema:Ja})}),Wa=[za];zod.z.enum(Wa);var Xa=(t=zod.z.undefined())=>zod.z.discriminatedUnion("type",[Za.extend({metadata:t})]),Ya=t=>Wt().parse({modality:M,value:t}),Qa=(t,n,o,s)=>Yt().parse({modality:U,index:t,id:n,name:o,arguments:s}),Et=(t,n)=>le().parse({role:t,partialContent:Xt().parse({modality:Xe,value:n})}),_t=(t,n,o,s,i)=>le().parse({role:t,partialContent:Qt().parse({modality:Ye,index:n,id:o,name:s,arguments:i})}),ei=(t,n)=>Ze().parse({modality:V,value:{type:be,thinking:t,signature:n}}),ti=t=>Ze().parse({modality:V,value:{type:Ge,data:t}}),Le=(t,n,o)=>le().parse({role:t,partialContent:We().parse({modality:ye,value:{type:be,thinking:n,signature:o}})}),ni=(t,n)=>le().parse({role:t,partialContent:We().parse({modality:ye,value:{type:Ge,data:n}})}),oi=Object.defineProperty,It=Object.getOwnPropertySymbols,ai=Object.prototype.hasOwnProperty,ii=Object.prototype.propertyIsEnumerable,At=(t,n,o)=>n in t?oi(t,n,{enumerable:!0,configurable:!0,writable:!0,value:o}):t[n]=o,ke=(t,n)=>{for(var o in n||(n={}))ai.call(n,o)&&At(t,o,n[o]);if(It)for(var o of It(n))ii.call(n,o)&&At(t,o,n[o]);return t},Bt="ProviderError",Nt=class ln extends Z{constructor({info:n,cause:o}){super({info:n,cause:o},Bt),this.name=Bt,this.info=n,this.cause=o;}static isProviderError(n){return n instanceof ln}},Ut="ModelResponseError",H=class dn extends Z{constructor({info:n,cause:o}){super({info:n,cause:o},Ut),this.name=Ut,this.cause=o,this.info=n;}static isModelResponseError(n){return n instanceof dn}},Lt="InvalidModelRequestError",qe=class cn extends Z{constructor({info:n,cause:o}){super({info:n,cause:o},Lt),this.name=Lt,this.cause=o,this.info=n,Object.setPrototypeOf(this,new.target.prototype);}static isInvalidModelRequestError(n){return n instanceof cn}},$t="InvalidConfigError",z=class mn extends Z{constructor({info:n,cause:o}){super({info:n,cause:o},$t),this.name=$t,this.cause=o,this.info=n,Object.setPrototypeOf(this,new.target.prototype);}static isInvalidConfigError(n){return n instanceof mn}},qt="InvalidMessagesError",j=class un extends Z{constructor({info:n,cause:o}){super({info:n,cause:o},qt),this.name=qt,this.cause=o,this.info=n,Object.setPrototypeOf(this,new.target.prototype);}static isInvalidMessagesError(n){return n instanceof un}},Dt="InvalidToolsError",Ht=class pn extends Z{constructor({info:n,cause:o}){super({info:n,cause:o},Dt),this.name=Dt,this.cause=o,this.info=n,Object.setPrototypeOf(this,new.target.prototype);}static isInvalidToolsError(n){return n instanceof pn}},Ft="InvalidEmbeddingRequestsError",zt=class hn extends Z{constructor({info:n,cause:o}){super({info:n,cause:o},Ft),this.name=Ft,this.info=n,this.cause=o,Object.setPrototypeOf(this,new.target.prototype);}static isInvalidEmbeddingRequestsError(n){return n instanceof hn}},Qe="multi-string",gn=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),max:zod.z.number().int().positive()}),si=t=>zod.z.array(zod.z.string()).max(t).default([]).optional(),ri=t=>({def:gn.parse(ke({type:Qe},t)),schema:si(t.max)}),fn="object-schema",li=zod.z.object({type:zod.z.literal(fn),param:zod.z.string().min(1),title:zod.z.string().min(1),description:zod.z.string().min(1).max(500),objectSchema:zod.z.any()}),et="range",yn=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),min:zod.z.number().int(),max:zod.z.number().int(),step:zod.z.number().positive(),default:zod.z.number()}),di=(t,n,o,s)=>zod.z.number().min(t).max(n).step(o).default(s).optional(),de=t=>({def:yn.parse(ke({type:et},t)),schema:di(t.min,t.max,t.step,t.default)}),tt="select-boolean",bn=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()}),ci=t=>zod.z.boolean().nullable().default(t).optional(),kn=t=>({def:bn.parse(ke({type:tt},t)),schema:ci(t.default)}),nt="select-string",vn=zod.z.object({type:zod.z.literal(nt),param:zod.z.string().min(1),title:zod.z.string().min(1),description:zod.z.string().min(1).max(500),default:zod.z.string(),choices:zod.z.array(zod.z.string())}),mi=(t,n)=>zod.z.enum(n).nullable().default(t).optional(),ot=t=>({def:vn.parse(ke({type:nt},t)),schema:mi(t.default,t.choices)}),ui=[et,Qe,nt,fn,tt];zod.z.enum(ui);var Tn=zod.z.discriminatedUnion("type",[yn,gn,vn,bn,li]),F=(t=Jt,n=Ca)=>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(n).nonempty(),maxInputTokens:zod.z.number().int().positive().min(1),maxOutputTokens:zod.z.number().int().positive().min(1),maxReasoningTokens:zod.z.number().int().positive().min(1).optional(),config:zod.z.object({def:zod.z.record(zod.z.string().min(1),Tn),schema:zod.z.instanceof(zod.z.ZodObject)}).refine(o=>{var s,i;let l=Object.keys(o.def),r=Object.keys((i=(s=o.schema)==null?void 0:s.shape)!=null?i:{});return l.every(d=>r.includes(d))&&r.every(d=>l.includes(d))},{message:"Keys in 'config.def' must exactly match keys in 'config.schema'"}),price:zod.z.custom()}),ee=(t=Ia)=>zod.z.object({name:zod.z.string().min(1),description:zod.z.string().min(1),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),Tn),schema:zod.z.instanceof(zod.z.ZodObject)}).refine(n=>{var o,s;let i=Object.keys(n.def),l=Object.keys((s=(o=n.schema)==null?void 0:o.shape)!=null?s:{});return i.every(r=>l.includes(r))&&l.every(r=>i.includes(r))},{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 pi={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."},hi={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."},gi={type:"range",title:"Max reasoning tokens",description:"Specify the total tokens for reasoning, where one token approximates four English characters."},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.`}),yi={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."},bi={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."},ki={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."},vi={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."},Ti={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."},Ci={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."},xi={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."},Mi={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."},Si={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."},Pi={type:"boolean",title:"Echo",description:"If true, the response will contain the prompt."},Oi={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."},Ri={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."},ji={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."},_={TEMPERATURE:pi,MAX_TOKENS:hi,STOP:fi,TOP_A:yi,TOP_P:bi,TOP_K:ki,MIN_P:vi,FREQUENCY_PENALTY:Ti,PRESENCE_PENALTY:Ci,REPETITION_PENALTY:Mi,SEED:xi,LOG_PROBS:wi,TOP_LOG_PROBS:Si,ECHO:Pi,RESPONSE_FORMAT:Oi,RESPONSE_FORMAT_WITH_SCHEMA:Ri,RESPONSE_SCHEMA:ji,MAX_REASONING_TOKENS:gi},Cn=t=>Object.fromEntries(Object.entries(t).filter(([n,o])=>o!=null)),se=t=>t==null?void 0:t.replace(/\/$/,""),xn=de({param:"temperature",title:_.TEMPERATURE.title,description:_.TEMPERATURE.description,min:0,max:1,step:.01,default:1}),Mn=t=>de({param:"max_tokens",title:_.MAX_TOKENS.title,description:_.MAX_TOKENS.description,min:0,max:t,step:1,default:0}),wn=t=>ri({param:"stop_sequences",title:_.STOP(t).title,description:_.STOP(t).description,max:t}),Sn=de({param:"top_p",title:_.TOP_P.title,description:_.TOP_P.description,min:0,max:1,step:.01,default:1}),Pn=de({param:"top_k",title:_.TOP_K.title,description:_.TOP_K.description,min:0,max:1,step:.01,default:1}),On=ot({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"]}),ve=(t,n)=>zod.z.object({temperature:xn.schema,maxTokens:Mn(t).schema,stop:wn(n).schema,topP:Sn.schema,topK:Pn.schema,toolChoice:On.schema}),Te=(t,n)=>({temperature:xn.def,maxTokens:Mn(t).def,stop:wn(n).def,topP:Sn.def,topK:Pn.def,toolChoice:On.def}),Rn=(t,n)=>de({param:"max_reasoning_tokens",title:_.MAX_REASONING_TOKENS.title,description:_.MAX_REASONING_TOKENS.description,min:t,max:n,step:1,default:0}),jn=kn({param:"reasoning_enabled",title:"Reasoning Enabled",description:`Controls whether the model is allowed to think for a longer period of time before generating a response.
10
10
  This can be useful for complex tasks that require more time to think.`,default:!1}),Ei=(t,n,o,s)=>Kt(x({},Te(t,n)),{reasoningEnabled:jn.def,maxReasoningTokens:Rn(o,s).def}),_i=(t,n,o,s)=>ve(t,n).extend({reasoningEnabled:jn.schema,maxReasoningTokens:Rn(o,s).schema}),En=ot({param:"encoding_format",title:"Encoding format",description:"Select the encoding format for the word embedding.",default:"",choices:["base64",""]}),_n=ot({param:"input_type",title:"Input type",description:"Select the input type for the word embedding.",default:"",choices:["query","document",""]}),In=kn({param:"truncation",title:"Truncation",description:"Select the truncation for the word embedding.",default:!0}),Ii=()=>zod.z.object({encodingFormat:En.schema,inputType:_n.schema,truncation:In.schema}),Ai=()=>({encodingFormat:En.def,inputType:_n.def,truncation:In.def}),T={base:(t,n)=>({def:Te(t,n),schema:ve(t,n)}),extendedThinking:(t,n,o,s)=>({def:Ei(t,n,o,s),schema:_i(t,n,o,s)})},I={base:()=>({def:Ai(),schema:Ii()})},Bi="anthropic",fe=class{constructor(){this.version="v1",this.name=Bi,this.chatModelFactories={[qn]:{model:Ms,modelOptions:xs,modelSchema:Dn},[Vn]:{model:Ns,modelOptions:Bs,modelSchema:Jn},[zn]:{model:Is,modelOptions:_s,modelSchema:Kn},[De]:{model:us,modelOptions:ms,modelSchema:Nn},[He]:{model:gs,modelOptions:hs,modelSchema:Un},[Ke]:{model:Ps,modelOptions:Ss,modelSchema:Hn},[Fe]:{model:bs,modelOptions:ys,modelSchema:Ln},[Ve]:{model:js,modelOptions:Rs,modelSchema:Fn},[ze]:{model:Ts,modelOptions:vs,modelSchema:$n}},this.embeddingModelFactories={[ao]:{model:or,modelOptions:nr,modelSchema:io},[no]:{model:er,modelOptions:Qs,modelSchema:oo},[Gn]:{model:Hs,modelOptions:Ds,modelSchema:Zn},[Wn]:{model:Ks,modelOptions:zs,modelSchema:Xn},[Yn]:{model:Gs,modelOptions:Js,modelSchema:Qn},[eo]:{model:Xs,modelOptions:Ws,modelSchema:to}};}chatModelLiterals(){return Object.keys(this.chatModelFactories)}chatModelSchemas(){return Object.keys(this.chatModelFactories).reduce((t,n)=>(t[n]=this.chatModelFactories[n].modelSchema,t),{})}chatModel(t){let n=t.modelName;if(!(n in this.chatModelFactories))throw new Nt({info:`Anthropic chat model: ${n} not found`,cause:new Error(`Anthropic chat model: ${n} not found, available chat models:
11
11
  ${this.chatModelLiterals().join(", ")}`)});let o=this.chatModelFactories[n].model,s=this.chatModelFactories[n].modelOptions.parse(t);return new o(s)}embeddingModelLiterals(){return Object.keys(this.embeddingModelFactories)}embeddingModelSchemas(){return Object.keys(this.embeddingModelFactories).reduce((t,n)=>(t[n]=this.embeddingModelFactories[n].modelSchema,t),{})}embeddingModel(t){let n=t.modelName;if(!(n in this.embeddingModelFactories))throw new Nt({info:`Anthropic embedding model: ${n} not found`,cause:new Error(`Anthropic embedding model: ${n} not found, available embedding models:
12
- ${this.embeddingModelLiterals().join(", ")}`)});let o=this.embeddingModelFactories[n].model,s=this.embeddingModelFactories[n].modelOptions.parse(t);return new o(s)}};fe.chatBaseUrl="https://api.anthropic.com/v1",fe.embeddingBaseUrl="https://api.voyageai.com/v1";var G={"claude-3-opus-20240229":{modelName:"claude-3-opus-20240229",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:15,outputPricePerMillion:75}}}]},"claude-3-sonnet-20240229":{modelName:"claude-3-sonnet-20240229",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:3,outputPricePerMillion:15}}}]},"claude-3-5-sonnet-20240620":{modelName:"claude-3-5-sonnet-20240620",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:3,outputPricePerMillion:15}}}]},"claude-3-5-sonnet-20241022":{modelName:"claude-3-5-sonnet-20241022",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:3,outputPricePerMillion:15}}}]},"claude-3-5-sonnet-latest":{modelName:"claude-3-5-sonnet-latest",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:3,outputPricePerMillion:15}}}]},"claude-3-7-sonnet-20250219":{modelName:"claude-3-7-sonnet-20250219",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:3,outputPricePerMillion:15}}}]},"claude-3-haiku-20240307":{modelName:"claude-3-haiku-20240307",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:.25,outputPricePerMillion:1.25}}}]},"claude-3-haiku-20241022":{modelName:"claude-3-haiku-20241022",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:.25,outputPricePerMillion:1.25}}}]},"claude-3-haiku-latest":{modelName:"claude-3-haiku-latest",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:.25,outputPricePerMillion:1.25}}}]},"claude-3-5-haiku-20241022":{modelName:"claude-3-5-haiku-20241022",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:.8,outputPricePerMillion:4}}}]},"claude-3-5-haiku-latest":{modelName:"claude-3-5-haiku-20241022",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:.8,outputPricePerMillion:4}}}]}},y=zod.z.enum([re,Y,S,Je]),b={system:re,user:Y,assistant:S,tool:Y},k=[M,K,U,J],v=zod.z.enum([M,K,U,J]),Ni=[M,K,U,J,V],Ui=zod.z.enum([M,K,U,J,V]),Li=zod.z.object({type:zod.z.literal("text"),text:zod.z.string()}),$i=zod.z.object({type:zod.z.literal("tool_use"),id:zod.z.string(),name:zod.z.string(),input:zod.z.record(zod.z.any())}),qi=zod.z.object({type:zod.z.literal("thinking"),thinking:zod.z.string(),signature:zod.z.string()}),Di=zod.z.object({type:zod.z.literal("redacted_thinking"),data:zod.z.string()}),Hi=zod.z.object({content:zod.z.array(zod.z.discriminatedUnion("type",[Li,$i,qi,Di])),id:zod.z.string(),model:zod.z.string(),role:zod.z.string(),stop_reason:zod.z.string(),stop_sequence:zod.z.null(),type:zod.z.literal("message"),usage:zod.z.object({input_tokens:zod.z.number(),output_tokens:zod.z.number(),cache_creation_input_tokens:zod.z.number().nullish(),cache_read_input_tokens:zod.z.number().nullish()})}),Fi=zod.z.object({type:zod.z.literal("message_start"),message:zod.z.object({id:zod.z.string(),type:zod.z.literal("message"),role:zod.z.string(),model:zod.z.string(),stop_reason:zod.z.string().nullable(),stop_sequence:zod.z.string().nullable(),content:zod.z.array(zod.z.any()),usage:zod.z.object({input_tokens:zod.z.number(),output_tokens:zod.z.number()})})}),zi=zod.z.object({type:zod.z.literal("message_delta"),delta:zod.z.object({stop_reason:zod.z.string().nullable(),stop_sequence:zod.z.string().nullable()}),usage:zod.z.object({output_tokens:zod.z.number()})}),Ki=zod.z.object({type:zod.z.literal("text"),text:zod.z.string()}),Vi=zod.z.object({type:zod.z.literal("tool_use"),id:zod.z.string(),name:zod.z.string(),input:zod.z.object({})}),Ji=zod.z.object({type:zod.z.literal("thinking"),thinking:zod.z.string()}),Gi=zod.z.object({type:zod.z.literal("redacted_thinking"),data:zod.z.string()}),Zi=zod.z.object({type:zod.z.literal("content_block_start"),index:zod.z.number(),content_block:zod.z.discriminatedUnion("type",[Ki,Vi,Ji,Gi])}),Wi=zod.z.object({type:zod.z.literal("text_delta"),text:zod.z.string()}),Xi=zod.z.object({type:zod.z.literal("input_json_delta"),partial_json:zod.z.string()}),Yi=zod.z.object({type:zod.z.literal("thinking_delta"),thinking:zod.z.string()}),Qi=zod.z.object({type:zod.z.literal("signature_delta"),signature:zod.z.string()}),es=zod.z.object({type:zod.z.literal("content_block_delta"),index:zod.z.number(),delta:zod.z.discriminatedUnion("type",[Wi,Xi,Yi,Qi])}),ts=zod.z.object({type:zod.z.literal("thinking"),thinking:zod.z.string().optional(),signature:zod.z.string().optional()}),ns=zod.z.object({type:zod.z.literal("redacted_thinking"),data:zod.z.string()}),os=zod.z.object({name:zod.z.string().min(1),description:zod.z.string().min(1).optional(),input_schema:zod.z.any()}),as=zod.z.object({type:zod.z.enum(["auto","any"])}),is=zod.z.object({type:zod.z.literal("tool"),name:zod.z.string().min(1)}),at=zod.z.object({text:zod.z.string().min(1),type:zod.z.literal("text")}),An=zod.z.object({type:zod.z.literal("image"),source:zod.z.object({type:zod.z.literal("base64"),media_type:zod.z.enum(["image/jpeg","image/png","image/gif","image/webp"]),data:zod.z.string().base64()})});zod.z.object({id:zod.z.string().min(1),type:zod.z.literal("tool_use"),name:zod.z.string().min(1),input:zod.z.record(zod.z.any())});var Bn=zod.z.object({type:zod.z.literal("tool_result"),tool_use_id:zod.z.string().min(1),content:zod.z.string().min(1).or(zod.z.array(zod.z.union([at,An])).min(1))}),ss=zod.z.object({role:zod.z.literal("user"),content:zod.z.string().min(1).or(zod.z.array(zod.z.union([at,An,Bn])).min(1))}),rs=zod.z.object({role:zod.z.literal("assistant"),content:zod.z.string().min(1).or(zod.z.array(zod.z.union([at,Bn,ts,ns])).min(1))}),ls=zod.z.union([ss,rs]),ds=zod.z.object({model:zod.z.string().min(1).optional(),messages:zod.z.array(ls).min(1),system:zod.z.string().min(1).optional(),max_tokens:zod.z.number().min(0).optional(),stop_sequences:zod.z.array(zod.z.string().min(1)).optional(),temperature:zod.z.number().min(0).max(1).optional(),tool_choice:zod.z.union([as,is]).optional(),tools:zod.z.array(os).min(1).optional(),top_p:zod.z.number().min(0).max(1).optional(),top_k:zod.z.number().min(0).optional()}),D=zod.z.object({modelName:zod.z.string(),apiKey:zod.z.string(),completeChatUrl:zod.z.string().url().optional(),streamChatUrl:zod.z.string().url().optional()}),L=class{constructor(t,n){this.version="v1";let o=D.parse(n);this.modelSchema=t,this.modelName=o.modelName,this.apiKey=o.apiKey,this.baseUrl=se(fe.chatBaseUrl),this.completeChatUrl=se(o.completeChatUrl||`${this.baseUrl}/messages`),this.streamChatUrl=se(o.streamChatUrl||`${this.baseUrl}/messages`);}getDefaultBaseUrl(){return this.baseUrl}getDefaultHeaders(){return {"x-api-key":`${this.apiKey}`,"anthropic-version":"2023-06-01","content-type":"application/json","anthropic-dangerous-direct-browser-access":"true"}}getDefaultParams(){return {model:this.modelName}}getRetryDelay(t){let n=0,o=!0;return t["x-should-retry"]&&(o=t["x-should-retry"].toLowerCase()!=="false"),t["retry-after"]&&(n=parseInt(t["retry-after"])*1e3),{shouldRetry:o,delayMs:n}}getTokenCount(t){return t.reduce((n,o)=>n+o.content.map(s=>s.modality==="text"?s.value:"").join(" ").length,0)}transformModelRequest(t){let n=ds.safeParse(t);if(!n.success)throw new qe({info:"Invalid model request",cause:n.error});let o=n.data,s=o.model;if(o.tool_choice&&(!o.tools||o.tools.length===0))throw new qe({info:`Invalid model request for model : '${this.modelName}'`,cause:new Error("'tools' are required when 'tool_choice' is specified")});let i={};o.tool_choice&&(o.tool_choice.type==="tool"?i.toolChoice=o.tool_choice.name:i.toolChoice=o.tool_choice.type),i.maxTokens=o.max_tokens,i.temperature=o.temperature,i.topP=o.top_p,i.topK=o.top_k,i.stop=o.stop_sequences;let l=nn().parse(Cn(i)),r=[],d={};o.system&&r.push({role:re,content:[{modality:M,value:o.system}]}),o.messages.forEach(u=>{let g=u.role;switch(g){case"user":{let f=u.content;if(typeof f=="string")r.push({role:g,content:[{modality:M,value:f}]});else {let h=f.map(p=>{if(p.type==="text")return {modality:M,value:p.text};if(p.type==="image"){let q="auto",R=p.source.media_type.split("/")[1];return {modality:K,detail:q,value:{type:Gt,media_type:R,base64:p.source.data}}}else return {modality:J,id:p.tool_use_id,index:d[p.tool_use_id].index,name:d[p.tool_use_id].name,data:typeof p.content=="string"?p.content:JSON.stringify(p.content)}});r.push({role:g,content:h});}}break;case"assistant":{let f=u.content;if(typeof f=="string")r.push({role:g,content:[{modality:M,value:f}]});else {let h=f.map((p,q)=>{if(p.type==="text")return {modality:M,value:p.text};{let R={modality:U,id:p.id,index:q,name:p.name,arguments:JSON.stringify(p.input)};return d[p.id]=R,R}});r.push({role:g,content:h});}}break}});let m=[];return o.tools&&o.tools.forEach(u=>{m.push({type:"function",definition:{schema:{name:u.name,description:u.description||"",parameters:u.input_schema}}});}),{modelName:s,config:l,messages:r,tools:m.length>0?m:void 0}}transformConfig(t,n,o){let s=t.toolChoice,i=t.reasoningEnabled,l=t.maxReasoningTokens,r=x({},t);delete r.toolChoice,delete r.reasoningEnabled,delete r.maxReasoningTokens;let d=this.modelSchema.config.schema.safeParse(r);if(!d.success)throw new z({info:`Invalid config for model : '${this.modelName}'`,cause:d.error});let m=d.data;s!==void 0&&(m.toolChoice=s),Object.keys(m).forEach(h=>{if(!(h in this.modelSchema.config.def))throw new z({info:`Invalid config for model : '${this.modelName}'`,cause:new Error(`Invalid config key : '${h}',
12
+ ${this.embeddingModelLiterals().join(", ")}`)});let o=this.embeddingModelFactories[n].model,s=this.embeddingModelFactories[n].modelOptions.parse(t);return new o(s)}};fe.chatBaseUrl="https://api.anthropic.com/v1",fe.embeddingBaseUrl="https://api.voyageai.com/v1";var G={"claude-3-opus-20240229":{modelName:"claude-3-opus-20240229",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:15,outputPricePerMillion:75}}}]},"claude-3-sonnet-20240229":{modelName:"claude-3-sonnet-20240229",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:3,outputPricePerMillion:15}}}]},"claude-3-5-sonnet-20240620":{modelName:"claude-3-5-sonnet-20240620",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:3,outputPricePerMillion:15}}}]},"claude-3-5-sonnet-20241022":{modelName:"claude-3-5-sonnet-20241022",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:3,outputPricePerMillion:15}}}]},"claude-3-5-sonnet-latest":{modelName:"claude-3-5-sonnet-latest",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:3,outputPricePerMillion:15}}}]},"claude-3-7-sonnet-20250219":{modelName:"claude-3-7-sonnet-20250219",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:3,outputPricePerMillion:15}}}]},"claude-3-haiku-20240307":{modelName:"claude-3-haiku-20240307",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:.25,outputPricePerMillion:1.25}}}]},"claude-3-haiku-20241022":{modelName:"claude-3-haiku-20241022",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:.25,outputPricePerMillion:1.25}}}]},"claude-3-haiku-latest":{modelName:"claude-3-haiku-latest",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:.25,outputPricePerMillion:1.25}}}]},"claude-3-5-haiku-20241022":{modelName:"claude-3-5-haiku-20241022",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:.8,outputPricePerMillion:4}}}]},"claude-3-5-haiku-latest":{modelName:"claude-3-5-haiku-20241022",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:.8,outputPricePerMillion:4}}}]}},y=zod.z.enum([re,Y,S,Je]),b={system:re,user:Y,assistant:S,tool:Y},k=[M,K,U,J],v=zod.z.enum([M,K,U,J]),Ni=[M,K,U,J,V],Ui=zod.z.enum([M,K,U,J,V]),Li=zod.z.object({type:zod.z.literal("text"),text:zod.z.string()}),$i=zod.z.object({type:zod.z.literal("tool_use"),id:zod.z.string(),name:zod.z.string(),input:zod.z.record(zod.z.any())}),qi=zod.z.object({type:zod.z.literal("thinking"),thinking:zod.z.string(),signature:zod.z.string()}),Di=zod.z.object({type:zod.z.literal("redacted_thinking"),data:zod.z.string()}),Hi=zod.z.object({content:zod.z.array(zod.z.discriminatedUnion("type",[Li,$i,qi,Di])),id:zod.z.string(),model:zod.z.string(),role:zod.z.string(),stop_reason:zod.z.string(),stop_sequence:zod.z.null(),type:zod.z.literal("message"),usage:zod.z.object({input_tokens:zod.z.number(),output_tokens:zod.z.number(),cache_creation_input_tokens:zod.z.number().nullish(),cache_read_input_tokens:zod.z.number().nullish()})}),Fi=zod.z.object({type:zod.z.literal("message_start"),message:zod.z.object({id:zod.z.string(),type:zod.z.literal("message"),role:zod.z.string(),model:zod.z.string(),stop_reason:zod.z.string().nullable(),stop_sequence:zod.z.string().nullable(),content:zod.z.array(zod.z.any()),usage:zod.z.object({input_tokens:zod.z.number(),output_tokens:zod.z.number()})})}),zi=zod.z.object({type:zod.z.literal("message_delta"),delta:zod.z.object({stop_reason:zod.z.string().nullable(),stop_sequence:zod.z.string().nullable()}),usage:zod.z.object({output_tokens:zod.z.number()})}),Ki=zod.z.object({type:zod.z.literal("text"),text:zod.z.string()}),Vi=zod.z.object({type:zod.z.literal("tool_use"),id:zod.z.string(),name:zod.z.string(),input:zod.z.object({})}),Ji=zod.z.object({type:zod.z.literal("thinking"),thinking:zod.z.string()}),Gi=zod.z.object({type:zod.z.literal("redacted_thinking"),data:zod.z.string()}),Zi=zod.z.object({type:zod.z.literal("content_block_start"),index:zod.z.number(),content_block:zod.z.discriminatedUnion("type",[Ki,Vi,Ji,Gi])}),Wi=zod.z.object({type:zod.z.literal("text_delta"),text:zod.z.string()}),Xi=zod.z.object({type:zod.z.literal("input_json_delta"),partial_json:zod.z.string()}),Yi=zod.z.object({type:zod.z.literal("thinking_delta"),thinking:zod.z.string()}),Qi=zod.z.object({type:zod.z.literal("signature_delta"),signature:zod.z.string()}),es=zod.z.object({type:zod.z.literal("content_block_delta"),index:zod.z.number(),delta:zod.z.discriminatedUnion("type",[Wi,Xi,Yi,Qi])}),ts=zod.z.object({type:zod.z.literal("thinking"),thinking:zod.z.string().optional(),signature:zod.z.string().optional()}),ns=zod.z.object({type:zod.z.literal("redacted_thinking"),data:zod.z.string()}),os=zod.z.object({name:zod.z.string().min(1),description:zod.z.string().min(1).optional(),input_schema:zod.z.any()}),as=zod.z.object({type:zod.z.enum(["auto","any"])}),is=zod.z.object({type:zod.z.literal("tool"),name:zod.z.string().min(1)}),at=zod.z.object({text:zod.z.string().min(1),type:zod.z.literal("text")}),An=zod.z.object({type:zod.z.literal("image"),source:zod.z.object({type:zod.z.literal("base64"),mediaType:zod.z.enum(["image/jpeg","image/png","image/gif","image/webp"]),data:zod.z.string().base64()})});zod.z.object({id:zod.z.string().min(1),type:zod.z.literal("tool_use"),name:zod.z.string().min(1),input:zod.z.record(zod.z.any())});var Bn=zod.z.object({type:zod.z.literal("tool_result"),tool_use_id:zod.z.string().min(1),content:zod.z.string().min(1).or(zod.z.array(zod.z.union([at,An])).min(1))}),ss=zod.z.object({role:zod.z.literal("user"),content:zod.z.string().min(1).or(zod.z.array(zod.z.union([at,An,Bn])).min(1))}),rs=zod.z.object({role:zod.z.literal("assistant"),content:zod.z.string().min(1).or(zod.z.array(zod.z.union([at,Bn,ts,ns])).min(1))}),ls=zod.z.union([ss,rs]),ds=zod.z.object({model:zod.z.string().min(1).optional(),messages:zod.z.array(ls).min(1),system:zod.z.string().min(1).optional(),max_tokens:zod.z.number().min(0).optional(),stop_sequences:zod.z.array(zod.z.string().min(1)).optional(),temperature:zod.z.number().min(0).max(1).optional(),tool_choice:zod.z.union([as,is]).optional(),tools:zod.z.array(os).min(1).optional(),top_p:zod.z.number().min(0).max(1).optional(),top_k:zod.z.number().min(0).optional()}),D=zod.z.object({modelName:zod.z.string(),apiKey:zod.z.string(),completeChatUrl:zod.z.string().url().optional(),streamChatUrl:zod.z.string().url().optional()}),L=class{constructor(t,n){this.version="v1";let o=D.parse(n);this.modelSchema=t,this.modelName=o.modelName,this.apiKey=o.apiKey,this.baseUrl=se(fe.chatBaseUrl),this.completeChatUrl=se(o.completeChatUrl||`${this.baseUrl}/messages`),this.streamChatUrl=se(o.streamChatUrl||`${this.baseUrl}/messages`);}getDefaultBaseUrl(){return this.baseUrl}getDefaultHeaders(){return {"x-api-key":`${this.apiKey}`,"anthropic-version":"2023-06-01","content-type":"application/json","anthropic-dangerous-direct-browser-access":"true"}}getDefaultParams(){return {model:this.modelName}}getRetryDelay(t){let n=0,o=!0;return t["x-should-retry"]&&(o=t["x-should-retry"].toLowerCase()!=="false"),t["retry-after"]&&(n=parseInt(t["retry-after"])*1e3),{shouldRetry:o,delayMs:n}}getTokenCount(t){return t.reduce((n,o)=>n+o.content.map(s=>s.modality==="text"?s.value:"").join(" ").length,0)}transformModelRequest(t){let n=ds.safeParse(t);if(!n.success)throw new qe({info:"Invalid model request",cause:n.error});let o=n.data,s=o.model;if(o.tool_choice&&(!o.tools||o.tools.length===0))throw new qe({info:`Invalid model request for model : '${this.modelName}'`,cause:new Error("'tools' are required when 'tool_choice' is specified")});let i={};o.tool_choice&&(o.tool_choice.type==="tool"?i.toolChoice=o.tool_choice.name:i.toolChoice=o.tool_choice.type),i.maxTokens=o.max_tokens,i.temperature=o.temperature,i.topP=o.top_p,i.topK=o.top_k,i.stop=o.stop_sequences;let l=nn().parse(Cn(i)),r=[],d={};o.system&&r.push({role:re,content:[{modality:M,value:o.system}]}),o.messages.forEach(u=>{let g=u.role;switch(g){case"user":{let f=u.content;if(typeof f=="string")r.push({role:g,content:[{modality:M,value:f}]});else {let h=f.map(p=>{if(p.type==="text")return {modality:M,value:p.text};if(p.type==="image"){let q="auto",R=p.source.mediaType.split("/")[1];return {modality:K,detail:q,value:{type:Gt,mediaType:R,base64:p.source.data}}}else return {modality:J,id:p.tool_use_id,index:d[p.tool_use_id].index,name:d[p.tool_use_id].name,data:typeof p.content=="string"?p.content:JSON.stringify(p.content)}});r.push({role:g,content:h});}}break;case"assistant":{let f=u.content;if(typeof f=="string")r.push({role:g,content:[{modality:M,value:f}]});else {let h=f.map((p,q)=>{if(p.type==="text")return {modality:M,value:p.text};{let R={modality:U,id:p.id,index:q,name:p.name,arguments:JSON.stringify(p.input)};return d[p.id]=R,R}});r.push({role:g,content:h});}}break}});let m=[];return o.tools&&o.tools.forEach(u=>{m.push({type:"function",definition:{schema:{name:u.name,description:u.description||"",parameters:u.input_schema}}});}),{modelName:s,config:l,messages:r,tools:m.length>0?m:void 0}}transformConfig(t,n,o){let s=t.toolChoice,i=t.reasoningEnabled,l=t.maxReasoningTokens,r=x({},t);delete r.toolChoice,delete r.reasoningEnabled,delete r.maxReasoningTokens;let d=this.modelSchema.config.schema.safeParse(r);if(!d.success)throw new z({info:`Invalid config for model : '${this.modelName}'`,cause:d.error});let m=d.data;s!==void 0&&(m.toolChoice=s),Object.keys(m).forEach(h=>{if(!(h in this.modelSchema.config.def))throw new z({info:`Invalid config for model : '${this.modelName}'`,cause:new Error(`Invalid config key : '${h}',
13
13
  available keys : [${Object.keys(this.modelSchema.config.def).join(", ")}]`)})});let u=Object.keys(m).reduce((h,p)=>{let q=this.modelSchema.config.def[p],R=q.param,ie=m[p];return R==="max_tokens"&&q.type==="range"&&ie===0?h[R]=q.max:h[R]=ie,h},{});if(!u.max_tokens){let h=this.modelSchema.config.def.maxTokens;u.max_tokens=h.max;}if("tool_choice"in u&&u.tool_choice!==void 0){let h=u.tool_choice;if(!o||o&&o.length===0)throw new z({info:`Invalid config for model : '${this.modelName}'`,cause:new Error("'tools' are required when 'toolChoice' is specified")});if(o&&o.length>0){let p=this.modelSchema.config.def.toolChoice;if(p.choices.includes(h))u.tool_choice={type:h};else if(o.map(q=>q.definition.schema.name).includes(h))u.tool_choice={type:"tool",name:h};else throw new z({info:`Invalid config for model : '${this.modelName}'`,cause:new Error(`toolChoice : '${h}' is not part of provided 'tools' names or
14
- one of [${p.choices.join(", ")}]`)})}}let g=i!==void 0,f=l!==void 0;if(g!==f)throw new z({info:`Invalid extended thinking config for model: '${this.modelName}'`,cause:new Error("Both 'reasoningEnabled' and 'maxReasoningTokens' must be defined together.")});if(g&&f){let h=u.max_tokens;if(i)if(l<h)u.thinking={type:"enabled",budget_tokens:l};else throw new z({info:`Invalid extended thinking token budget for model: '${this.modelName}'`,cause:new Error(`maxReasoningTokens (${l}) must be less than max_tokens (${h})`)})}return u}transformMessages(t){if(!t||t&&t.length===0)return {messages:[]};let n=l=>{let r=l.match(/^data:image\/[a-zA-Z]+;base64,/);return r?l.substring(r[0].length):l},o=t.map(l=>{let r=en().safeParse(l);if(!r.success)throw new j({info:"Invalid messages",cause:r.error});return r.data});o.forEach(l=>{l.content.forEach(r=>{if(!this.modelSchema.modalities.includes(r.modality))throw new j({info:`Invalid message content for model : '${this.modelName}'`,cause:new Error(`model : '${this.modelName}' does not support modality : '${r.modality}', available modalities : [${this.modelSchema.modalities.join(", ")}]`)})});}),o.forEach(l=>{if(!Object.keys(this.modelSchema.roles).includes(l.role))throw new j({info:`Invalid message content for model : '${this.modelName}'`,cause:new Error(`model : '${this.modelName}' does not support role : '${l.role}', available roles : [${Object.keys(this.modelSchema.roles).join(", ")}]`)})});let s="",i=[];if(o.forEach(l=>{switch(l.role){case re:{l.content.forEach(r=>{if(r.modality===M)s+=r.value;else throw new j({info:`Invalid message 'role' and 'modality' combination for model : ${this.modelName}`,cause:new Error(`role : '${l.role}' cannot have content with modality : '${r.modality}'`)})});break}case S:{let r=[];l.content.forEach(d=>{if(d.modality===M)r.push({type:"text",text:d.value});else if(d.modality===U)r.push({type:"tool_use",id:d.id,name:d.name,input:JSON.parse(d.arguments)});else if(d.modality===V&&d.value.type==="thinking")r.push({type:"thinking",thinking:d.value.thinking,signature:d.value.signature});else if(d.modality===V&&d.value.type==="redacted")r.push({type:"redacted_thinking",data:d.value.data});else throw new j({info:`Invalid message 'role' and 'modality' combination for model : ${this.modelName}`,cause:new Error(`role : '${l.role}' cannot have content with modality : '${d.modality}'`)})}),i.push({role:this.modelSchema.roles[l.role],content:r});break}case Y:{let r=[];l.content.forEach(d=>{if(d.modality===M)r.push({type:"text",text:d.value});else if(d.modality===K){if(d.value.type==="base64"){let m=d.value.base64;m=n(m),r.push({type:"image",source:{type:"base64",media_type:`image/${d.value.media_type}`,data:m}});}else if(d.value.type==="url")throw new j({info:`Invalid message 'modality' for model : ${this.modelName}`,cause:new Error(`model: '${this.modelName}' does not support image content type: '${d.value.type}'`)})}else throw new j({info:`Invalid message 'role' and 'modality' combination for model : ${this.modelName}`,cause:new Error(`role : '${l.role}' cannot have content with modality : '${d.modality}'`)})}),i.push({role:this.modelSchema.roles[l.role],content:r});break}case Je:{let r=[];l.content.forEach(d=>{if(d.modality===J)r.push({type:"tool_result",tool_use_id:d.id,content:d.data});else throw new j({info:`Invalid message 'role' and 'modality' combination for model : ${this.modelName}`,cause:new Error(`role : '${l.role}' cannot have content with modality : '${d.modality}'`)})}),i.push({role:this.modelSchema.roles[l.role],content:r});break}default:throw new j({info:`Invalid message 'role' for model : ${this.modelName}`,cause:new Error(`role : '${l.role}' is not supported,
14
+ one of [${p.choices.join(", ")}]`)})}}let g=i!==void 0,f=l!==void 0;if(g!==f)throw new z({info:`Invalid extended thinking config for model: '${this.modelName}'`,cause:new Error("Both 'reasoningEnabled' and 'maxReasoningTokens' must be defined together.")});if(g&&f){let h=u.max_tokens;if(i)if(l<h)u.thinking={type:"enabled",budget_tokens:l};else throw new z({info:`Invalid extended thinking token budget for model: '${this.modelName}'`,cause:new Error(`maxReasoningTokens (${l}) must be less than max_tokens (${h})`)})}return u}transformMessages(t){if(!t||t&&t.length===0)return {messages:[]};let n=l=>{let r=l.match(/^data:image\/[a-zA-Z]+;base64,/);return r?l.substring(r[0].length):l},o=t.map(l=>{let r=en().safeParse(l);if(!r.success)throw new j({info:"Invalid messages",cause:r.error});return r.data});o.forEach(l=>{l.content.forEach(r=>{if(!this.modelSchema.modalities.includes(r.modality))throw new j({info:`Invalid message content for model : '${this.modelName}'`,cause:new Error(`model : '${this.modelName}' does not support modality : '${r.modality}', available modalities : [${this.modelSchema.modalities.join(", ")}]`)})});}),o.forEach(l=>{if(!Object.keys(this.modelSchema.roles).includes(l.role))throw new j({info:`Invalid message content for model : '${this.modelName}'`,cause:new Error(`model : '${this.modelName}' does not support role : '${l.role}', available roles : [${Object.keys(this.modelSchema.roles).join(", ")}]`)})});let s="",i=[];if(o.forEach(l=>{switch(l.role){case re:{l.content.forEach(r=>{if(r.modality===M)s+=r.value;else throw new j({info:`Invalid message 'role' and 'modality' combination for model : ${this.modelName}`,cause:new Error(`role : '${l.role}' cannot have content with modality : '${r.modality}'`)})});break}case S:{let r=[];l.content.forEach(d=>{if(d.modality===M)r.push({type:"text",text:d.value});else if(d.modality===U)r.push({type:"tool_use",id:d.id,name:d.name,input:JSON.parse(d.arguments)});else if(d.modality===V&&d.value.type==="thinking")r.push({type:"thinking",thinking:d.value.thinking,signature:d.value.signature});else if(d.modality===V&&d.value.type==="redacted")r.push({type:"redacted_thinking",data:d.value.data});else throw new j({info:`Invalid message 'role' and 'modality' combination for model : ${this.modelName}`,cause:new Error(`role : '${l.role}' cannot have content with modality : '${d.modality}'`)})}),i.push({role:this.modelSchema.roles[l.role],content:r});break}case Y:{let r=[];l.content.forEach(d=>{if(d.modality===M)r.push({type:"text",text:d.value});else if(d.modality===K){if(d.value.type==="base64"){let m=d.value.base64;m=n(m),r.push({type:"image",source:{type:"base64",mediaType:`image/${d.value.mediaType}`,data:m}});}else if(d.value.type==="url")throw new j({info:`Invalid message 'modality' for model : ${this.modelName}`,cause:new Error(`model: '${this.modelName}' does not support image content type: '${d.value.type}'`)})}else throw new j({info:`Invalid message 'role' and 'modality' combination for model : ${this.modelName}`,cause:new Error(`role : '${l.role}' cannot have content with modality : '${d.modality}'`)})}),i.push({role:this.modelSchema.roles[l.role],content:r});break}case Je:{let r=[];l.content.forEach(d=>{if(d.modality===J)r.push({type:"tool_result",tool_use_id:d.id,content:d.data});else throw new j({info:`Invalid message 'role' and 'modality' combination for model : ${this.modelName}`,cause:new Error(`role : '${l.role}' cannot have content with modality : '${d.modality}'`)})}),i.push({role:this.modelSchema.roles[l.role],content:r});break}default:throw new j({info:`Invalid message 'role' for model : ${this.modelName}`,cause:new Error(`role : '${l.role}' is not supported,
15
15
  available roles : [${Object.keys(this.modelSchema.roles).join(", ")}]`)})}}),i[0].role!==this.modelSchema.roles[Y])throw new j({info:`Invalid message 'role' for model : ${this.modelName}`,cause:new Error(`model : '${this.modelName}' requires first message to be from user`)});return {system:s,messages:i}}transformTools(t){if(!this.modelSchema.modalities.includes(U))throw new Ht({info:`Invalid tool 'modality' for model : ${this.modelName}`,cause:new Error(`model : '${this.modelName}' does not support tool modality : '${U}'`)});return !t||t&&t.length===0?{tools:[]}:{tools:t.map(n=>{let o=Xa().safeParse(n);if(!o.success)throw new Ht({info:"Invalid tools",cause:o.error});return o.data}).map(n=>({name:n.definition.schema.name,description:n.definition.schema.description,input_schema:n.definition.schema.parameters}))}}getCompleteChatUrl(t,n,o){return E(this,null,function*(){return new Promise(s=>{s(this.completeChatUrl);})})}getCompleteChatHeaders(t,n,o){return E(this,null,function*(){let s=this.getDefaultHeaders();return new Promise(i=>{i(s);})})}getCompleteChatData(t,n,o){return E(this,null,function*(){let s=this.transformConfig(t,n,o),i=this.transformMessages(n);if(i.messages&&i.messages.length===0)throw new j({info:"Messages are required",cause:new Error("Messages are required")});let l=o?this.transformTools(o):{};return new Promise(r=>{r(x(x(x(x({},this.getDefaultParams()),s),i),l));})})}transformCompleteChatResponse(t){let n=Hi.safeParse(t);if(n.success){let o=n.data,s=o.content.map((r,d)=>{if(r.type==="text")return Ya(r.text);if(r.type==="tool_use")return Qa(d,r.id,r.name,JSON.stringify(r.input));if(r.type==="thinking")return ei(r.thinking,r.signature);if(r.type==="redacted_thinking")return ti(r.data)}),i=[{role:S,content:s}],l={promptTokens:o.usage.input_tokens,completionTokens:o.usage.output_tokens,totalTokens:o.usage.input_tokens+o.usage.output_tokens};return {messages:i,usage:l,logProbs:[]}}throw new H({info:"Invalid response from model",cause:n.error})}getStreamChatUrl(t,n,o){return E(this,null,function*(){return new Promise(s=>{s(this.streamChatUrl);})})}getStreamChatHeaders(t,n,o){let s=this.getDefaultHeaders();return new Promise(i=>{i(s);})}getStreamChatData(t,n,o){return E(this,null,function*(){let s=this.transformConfig(t,n,o),i=this.transformMessages(n);if(i.messages&&i.messages.length===0)throw new j({info:"Messages are required",cause:new Error("Messages are required")});let l=o?this.transformTools(o):{};return new Promise(r=>{r(x(x(x(x({stream:!0},this.getDefaultParams()),s),i),l));})})}transformStreamChatResponseChunk(t,n){return Pt(this,null,function*(){let o=(n+t).split(`
16
16
  `).filter(s=>s.trim()!=="");for(let s of o)if(s.startsWith("data: {")&&s.endsWith("}")){let i;try{i=JSON.parse(s.substring(6));}catch(l){throw new H({info:`Malformed JSON received in stream : ${i}`,cause:l})}if("type"in i){if(i.type==="message_stop")return;if(i.type==="message_start"){let l=Fi.safeParse(i);if(l.success){let r=l.data;yield {partialResponse:{partialMessages:[],usage:{promptTokens:r.message.usage.input_tokens,completionTokens:r.message.usage.output_tokens,totalTokens:r.message.usage.input_tokens+r.message.usage.output_tokens}},buffer:n};}else throw new H({info:"Invalid response from model",cause:l.error})}else if(i.type==="message_delta"){let l=zi.safeParse(i);if(l.success){let r=l.data;yield {partialResponse:{partialMessages:[],usage:{promptTokens:void 0,completionTokens:r.usage.output_tokens,totalTokens:r.usage.output_tokens}},buffer:n};}else throw new H({info:"Invalid response from model",cause:l.error})}else if(i.type==="content_block_start"){let l=Zi.safeParse(i);if(l.success){let r=l.data,d=[];r.content_block.type==="text"?d.push(Et(S,r.content_block.text)):r.content_block.type==="tool_use"?d.push(_t(S,r.index,r.content_block.id,r.content_block.name,"")):r.content_block.type==="thinking"?d.push(Le(S,r.content_block.thinking)):r.content_block.type==="redacted_thinking"&&d.push(ni(S,r.content_block.data)),yield {partialResponse:{partialMessages:d},buffer:n};}else throw new H({info:"Invalid response from model",cause:l.error})}else if(i.type==="content_block_delta"){let l=es.safeParse(i);if(l.success){let r=l.data,d=[];r.delta.type==="text_delta"?d.push(Et(S,r.delta.text)):r.delta.type==="input_json_delta"?d.push(_t(S,r.index,"","",r.delta.partial_json)):r.delta.type==="thinking_delta"?d.push(Le(S,r.delta.thinking)):r.delta.type==="signature_delta"&&d.push(Le(S,void 0,r.delta.signature)),yield {partialResponse:{partialMessages:d},buffer:n};}else throw new H({info:"Invalid response from model",cause:l.error})}}else throw new H({info:"Invalid JSON received in stream",cause:new Error(`Invalid JSON received in stream, expected 'type' property, received: ${JSON.stringify(i)}`)})}})}transformProxyStreamChatResponseChunk(t,n,o,s,i){return Pt(this,null,function*(){yield*he(ia(this.transformStreamChatResponseChunk(t,n)));})}getProxyStreamChatUrl(t,n,o){return E(this,null,function*(){return new Promise(s=>{s(this.streamChatUrl);})})}getProxyCompleteChatUrl(t,n,o){return E(this,null,function*(){return new Promise(s=>{s(this.completeChatUrl);})})}getProxyCompleteChatHeaders(t,n,o){return E(this,null,function*(){if(!n)return {};let s=x({},n);return delete s.host,delete s["content-length"],s})}getProxyStreamChatHeaders(t,n,o){return E(this,null,function*(){return yield this.getProxyCompleteChatHeaders(t,n,o)})}getModelPricing(){if(!(this.modelName in G))throw new H({info:`Invalid model pricing for model : '${this.modelName}'`,cause:new Error(`No pricing configuration found for model "${this.modelName}"`)});return G[this.modelName]}},De="claude-3-5-sonnet-20240620",cs="Most intelligent model. Highest level of intelligence and capability.",Nn=F(y,v).parse({name:De,description:cs,maxInputTokens:2e5,maxOutputTokens:8192,roles:b,modalities:k,config:{def:T.base(8192,4).def,schema:T.base(8192,4).schema},price:G[De]}),ms=D,us=class extends L{constructor(t){super(Nn,t);}},He="claude-3-5-sonnet-20241022",ps="Most intelligent model. Highest level of intelligence and capability.",Un=F(y,v).parse({name:He,description:ps,maxInputTokens:2e5,maxOutputTokens:8192,roles:b,modalities:k,config:{def:T.base(8192,4).def,schema:T.base(8192,4).schema},price:G[He]}),hs=D,gs=class extends L{constructor(t){super(Un,t);}},Fe="claude-3-5-sonnet-latest",fs="Most intelligent model. Highest level of intelligence and capability.",Ln=F(y,v).parse({name:Fe,description:fs,maxInputTokens:2e5,maxOutputTokens:8192,roles:b,modalities:k,config:{def:T.base(8192,4).def,schema:T.base(8192,4).schema},price:G[Fe]}),ys=D,bs=class extends L{constructor(t){super(Ln,t);}},ze="claude-3-7-sonnet-20250219",ks="Most intelligent model. Highest level of intelligence and capability.",$n=F(y,Ui).parse({name:ze,description:ks,maxInputTokens:2e5,maxOutputTokens:128e3,maxReasoningTokens:64e3,roles:b,modalities:Ni,config:{def:T.extendedThinking(128e3,4,1024,64e3).def,schema:T.extendedThinking(128e3,4,1024,64e3).schema},price:G[ze]}),vs=D,Ts=class extends L{constructor(t){super($n,t);}getDefaultHeaders(){let t=super.getDefaultHeaders();return t=Kt(x({},t),{"anthropic-beta":"output-128k-2025-02-19"}),t}},qn="claude-3-haiku-20240307",Cs="Fastest and most compact model for near-instant responsiveness. Quick and accurate targeted performance.",Dn=F(y,v).parse({name:qn,description:Cs,maxInputTokens:2e5,maxOutputTokens:4096,roles:b,modalities:k,config:{def:T.base(4096,4).def,schema:T.base(4096,4).schema}}),xs=D,Ms=class extends L{constructor(t){super(Dn,t);}},Ke="claude-3-5-haiku-20241022",ws="Our fastest model with intelligence at blazing speeds.",Hn=F(y,v).parse({name:Ke,description:ws,maxInputTokens:2e5,maxOutputTokens:8192,roles:b,modalities:k,config:{def:T.base(8192,4).def,schema:T.base(8192,4).schema},price:G[Ke]}),Ss=D,Ps=class extends L{constructor(t){super(Hn,t);}},Ve="claude-3-5-haiku-latest",Os="Our fastest model with intelligence at blazing speeds.",Fn=F(y,v).parse({name:Ve,description:Os,maxInputTokens:2e5,maxOutputTokens:8192,roles:b,modalities:k,config:{def:T.base(8192,4).def,schema:T.base(8192,4).schema},price:G[Ve]}),Rs=D,js=class extends L{constructor(t){super(Fn,t);}},zn="claude-3-opus-20240229",Es="Powerful model for highly complex tasks. Top-level performance, intelligence, fluency, and understanding.",Kn=F(y,v).parse({name:zn,description:Es,maxInputTokens:2e5,maxOutputTokens:4096,roles:b,modalities:k,config:{def:T.base(4096,4).def,schema:T.base(4096,4).schema}}),_s=D,Is=class extends L{constructor(t){super(Kn,t);}},Vn="claude-3-sonnet-20240229",As="Balance of intelligence and speed. Strong utility, balanced for scaled deployments.",Jn=F(y,v).parse({name:Vn,description:As,maxInputTokens:2e5,maxOutputTokens:4096,roles:b,modalities:k,config:{def:T.base(4096,4).def,schema:T.base(4096,4).schema}}),Bs=D,Ns=class extends L{constructor(t){super(Jn,t);}},te=[Q],ne=zod.z.enum([Q]),Us=zod.z.object({object:zod.z.literal("list"),model:zod.z.string(),data:zod.z.array(zod.z.object({index:zod.z.number(),object:zod.z.literal("embedding"),embedding:zod.z.array(zod.z.number()).or(zod.z.string().base64())})),usage:zod.z.object({total_tokens:zod.z.number()})}),Ls=zod.z.string().min(1).or(zod.z.array(zod.z.string().min(1)).min(1)),$s=zod.z.object({model:zod.z.string().min(1).optional(),input:Ls,encoding_format:zod.z.enum(["base64"]).nullable().optional(),input_type:zod.z.enum(["query","document"]).nullable().optional(),truncation:zod.z.boolean().optional()}),W=zod.z.object({modelName:zod.z.string(),apiKey:zod.z.string(),getEmbeddingsUrl:zod.z.string().url().optional()}),oe=class{constructor(t,n){this.version="v1";let o=W.parse(n);this.modelSchema=t,this.modelName=o.modelName,this.apiKey=o.apiKey,this.baseUrl=se(fe.embeddingBaseUrl),this.getEmbeddingsUrl=se(o.getEmbeddingsUrl||`${this.baseUrl}/embeddings`);}getDefaultBaseUrl(){return this.baseUrl}getDefaultHeaders(){return {Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"}}getDefaultParams(){return {model:this.modelName}}getTokenCount(t){return t.requests.reduce((n,o)=>n+o.length,0)}getRetryDelay(t){return {shouldRetry:!0,delayMs:0}}transformModelRequest(t){let n=$s.safeParse(t);if(!n.success)throw new qe({info:"Invalid model request",cause:n.error});let o=n.data,s=o.model,i={encodingFormat:o.encoding_format,inputType:o.input_type,truncation:o.truncation},l=nn().parse(Cn(i)),r;return typeof o.input=="string"?r={modality:Q,requests:[o.input]}:r={modality:Q,requests:o.input},{modelName:s,config:l,embeddingRequests:r}}transformConfig(t,n){"inputType"in t&&t.inputType===""&&delete t.inputType,"encodingFormat"in t&&t.encodingFormat===""&&delete t.encodingFormat;let o=this.modelSchema.config.schema.safeParse(t);if(!o.success)throw new z({info:`Invalid config for model : '${this.modelName}'`,cause:o.error});let s=o.data;return Object.keys(s).forEach(i=>{if(!this.modelSchema.config.def[i])throw new z({info:`Invalid config for model : '${this.modelName}'`,cause:new Error(`Invalid config key : '${i}',
17
- available keys : [${Object.keys(this.modelSchema.config.def).join(", ")}]`)})}),Object.keys(s).reduce((i,l)=>{let r=this.modelSchema.config.def[l].param,d=s[l];return i[r]=d,i},{})}transformEmbeddingRequests(t){let n=Na().safeParse(t);if(!n.success)throw new zt({info:"Invalid embedding requests",cause:n.error});if(n.data.requests.length>128)throw new zt({info:`Invalid embedding requests for model : '${this.modelName}'`,cause:new Error(`Max requests for model : '${this.modelName}' is 128`)});return {input:n.data.requests}}getGetEmbeddingsUrl(t,n){return E(this,null,function*(){return new Promise(o=>{o(this.getEmbeddingsUrl);})})}getGetEmbeddingsHeaders(t,n){return E(this,null,function*(){return new Promise(o=>{o(this.getDefaultHeaders());})})}getGetEmbeddingsData(t,n){return E(this,null,function*(){return new Promise(o=>{o(x(x(x({},this.getDefaultParams()),this.transformConfig(t,n)),this.transformEmbeddingRequests(n)));})})}transformGetEmbeddingsResponse(t){let n,o=Us.safeParse(t);if(o.success){let s=o.data;n=typeof s.data[0].embedding=="string"?sn:an;let i=s.data.map(l=>typeof l.embedding=="string"?{index:l.index,embedding:l.embedding}:{index:l.index,embedding:l.embedding});return {encodingFormat:n,embeddings:i,usage:{totalTokens:s.usage.total_tokens}}}throw new H({info:"Invalid response from model",cause:o.error})}},Gn="voyage-code-2",qs="Optimized for code retrieval.",Zn=ee(ne).parse({name:Gn,description:qs,modalities:te,maxInputTokens:16e3,maxOutputTokens:16e3,config:{def:I.base().def,schema:I.base().schema}}),Ds=W,Hs=class extends oe{constructor(t){super(Zn,t);}},Wn="voyage-law-2",Fs="Optimized for legal and long-context retrieval and RAG. Also improved performance across all domains.",Xn=ee(ne).parse({name:Wn,description:Fs,modalities:te,maxInputTokens:16e3,maxOutputTokens:16e3,config:{def:I.base().def,schema:I.base().schema}}),zs=W,Ks=class extends oe{constructor(t){super(Xn,t);}},Yn="voyage-multilingual-2",Vs="Optimized for multilingual retrieval and RAG.",Qn=ee(ne).parse({name:Yn,description:Vs,modalities:te,maxInputTokens:32e3,maxOutputTokens:32e3,config:{def:I.base().def,schema:I.base().schema}}),Js=W,Gs=class extends oe{constructor(t){super(Qn,t);}},eo="voyage-finance-2",Zs="Optimized for finance retrieval and RAG.",to=ee(ne).parse({name:eo,description:Zs,modalities:te,maxInputTokens:32e3,maxOutputTokens:32e3,config:{def:I.base().def,schema:I.base().schema}}),Ws=W,Xs=class extends oe{constructor(t){super(to,t);}},no="voyage-3-lite",Ys="Optimized for latency and cost.",oo=ee(ne).parse({name:no,description:Ys,modalities:te,maxInputTokens:32e3,maxOutputTokens:32e3,config:{def:I.base().def,schema:I.base().schema}}),Qs=W,er=class extends oe{constructor(t){super(oo,t);}},ao="voyage-3",tr="Optimized for quality.",io=ee(ne).parse({name:ao,description:tr,modalities:te,maxInputTokens:32e3,maxOutputTokens:32e3,config:{def:I.base().def,schema:I.base().schema}}),nr=W,or=class extends oe{constructor(t){super(io,t);}};var ar="system",ir="user",co="assistant",sr="tool",rr=[ar,ir,co,sr],rt=zod.z.enum(rr),lr=[co],dr=zod.z.enum(lr),mo="image",cr="base64",mr=["png","jpeg","webp","gif"],ur=zod.z.object({type:zod.z.literal(cr),base64:zod.z.string(),media_type:zod.z.enum(mr)}),pr="url",hr=zod.z.object({type:zod.z.literal(pr),url:zod.z.string()}),gr=zod.z.discriminatedUnion("type",[ur,hr]),fr=["low","medium","high","auto"],yr=zod.z.enum(fr),br=(t=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(mo),detail:yr,value:gr,metadata:t}),uo="reasoning",po="partial-reasoning",ho="thinking",kr="redacted",st=zod.z.object({type:zod.z.literal(ho),thinking:zod.z.string(),signature:zod.z.string()}),go=zod.z.object({type:zod.z.literal(kr),data:zod.z.string()}),vr=zod.z.discriminatedUnion("type",[st,go]),Tr=(t=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(uo),value:vr,metadata:t}),Cr=zod.z.object({type:zod.z.literal(ho),thinking:st.shape.thinking.optional(),signature:st.shape.signature.optional()}),xr=zod.z.discriminatedUnion("type",[Cr,go]),Mr=(t=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(po),value:xr,metadata:t}),fo="text",wr=(t=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(fo),value:zod.z.string(),metadata:t}),yo="partial-text",Sr=(t=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(yo),value:zod.z.string(),metadata:t}),bo="tool-call",Pr=(t=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(bo),index:zod.z.number().int().nonnegative(),id:zod.z.string().min(1),name:zod.z.string().min(1),arguments:zod.z.string(),metadata:t}),ko="partial-tool-call",Or=(t=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(ko),index:zod.z.number().int().nonnegative(),id:zod.z.string().optional(),name:zod.z.string().optional(),arguments:zod.z.string().optional(),metadata:t}),vo="tool-response",Rr=(t=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(vo),index:zod.z.number().int().nonnegative(),id:zod.z.string().min(1),name:zod.z.string().min(1),data:zod.z.string(),metadata:t}),jr=[fo,mo,bo,vo,uo],To=zod.z.enum(jr),Er=(t=zod.z.undefined(),n=zod.z.undefined(),o=zod.z.undefined(),s=zod.z.undefined(),i=zod.z.undefined())=>zod.z.discriminatedUnion("modality",[wr(t),br(n),Pr(o),Rr(s),Tr(i)]),_r=[yo,ko,po];zod.z.enum(_r);var Ir=(t=zod.z.undefined(),n=zod.z.undefined(),o=zod.z.undefined())=>zod.z.discriminatedUnion("modality",[Sr(t),Or(n),Mr(o)]);var Ar=(t=rt,n=zod.z.undefined(),o=zod.z.undefined(),s=zod.z.undefined(),i=zod.z.undefined(),l=zod.z.undefined(),r=zod.z.undefined())=>zod.z.object({role:t,content:zod.z.array(Er(n,o,s,i,r)),metadata:l}),Br=(t=dr,n=zod.z.undefined(),o=zod.z.undefined(),s=zod.z.undefined(),i=zod.z.undefined())=>zod.z.object({role:t,partialContent:Ir(n,o,s),metadata:i}),Nr=zod.z.object({promptTokens:zod.z.number().nonnegative(),completionTokens:zod.z.number().nonnegative(),totalTokens:zod.z.number().nonnegative()}),so=zod.z.object({token:zod.z.string(),logProb:zod.z.number(),bytes:zod.z.array(zod.z.number().int()).nullable()}),Ur=so.extend({topLogProbs:zod.z.array(so)}),Co=zod.z.array(Ur);zod.z.object({messages:zod.z.array(Ar()),usage:Nr.optional(),logProbs:Co.optional()});var Lr=zod.z.object({promptTokens:zod.z.number().nonnegative().optional(),completionTokens:zod.z.number().nonnegative().optional(),totalTokens:zod.z.number().nonnegative().optional()});zod.z.object({partialMessages:zod.z.array(Br()),usage:Lr.optional(),logProbs:Co.optional()});var $r=["object","array","number","string","boolean","enum"],ro=zod.z.enum($r),qr=zod.z.object({anyOf:zod.z.array(zod.z.any()).optional(),type:zod.z.union([ro,zod.z.array(zod.z.union([ro,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()}),Dr=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(qr),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:Dr}).optional();var Hr="text",Fr="token",zr=[Hr,Fr];zod.z.enum(zr);zod.z.array(zod.z.string().min(1));zod.z.array(zod.z.array(zod.z.number().int().nonnegative()));var Vr="float",Jr=zod.z.object({index:zod.z.number().int().nonnegative(),embedding:zod.z.array(zod.z.number())}),Gr="base64",Zr=zod.z.object({index:zod.z.number().int().nonnegative(),embedding:zod.z.string().base64()}),lo=zod.z.object({totalTokens:zod.z.number().int().nonnegative()});zod.z.discriminatedUnion("encodingFormat",[zod.z.object({encodingFormat:zod.z.literal(Vr),embeddings:zod.z.array(Jr),usage:lo.optional()}),zod.z.object({encodingFormat:zod.z.literal(Gr),embeddings:zod.z.array(Zr),usage:lo.optional()})]);var Wr=t=>{let n=new WeakSet;return JSON.stringify(t,(o,s)=>{if(typeof s=="object"&&s!==null){if(n.has(s))return;n.add(s);}return s})},Xr=t=>t==null?"unknown error":typeof t=="string"?t:t instanceof Error?t.message:Wr(t),it="GatewayBaseError",lt=class xo extends Error{constructor({info:n,cause:o},s){super(`[${s!=null?s:it}]: ${n}
17
+ available keys : [${Object.keys(this.modelSchema.config.def).join(", ")}]`)})}),Object.keys(s).reduce((i,l)=>{let r=this.modelSchema.config.def[l].param,d=s[l];return i[r]=d,i},{})}transformEmbeddingRequests(t){let n=Na().safeParse(t);if(!n.success)throw new zt({info:"Invalid embedding requests",cause:n.error});if(n.data.requests.length>128)throw new zt({info:`Invalid embedding requests for model : '${this.modelName}'`,cause:new Error(`Max requests for model : '${this.modelName}' is 128`)});return {input:n.data.requests}}getGetEmbeddingsUrl(t,n){return E(this,null,function*(){return new Promise(o=>{o(this.getEmbeddingsUrl);})})}getGetEmbeddingsHeaders(t,n){return E(this,null,function*(){return new Promise(o=>{o(this.getDefaultHeaders());})})}getGetEmbeddingsData(t,n){return E(this,null,function*(){return new Promise(o=>{o(x(x(x({},this.getDefaultParams()),this.transformConfig(t,n)),this.transformEmbeddingRequests(n)));})})}transformGetEmbeddingsResponse(t){let n,o=Us.safeParse(t);if(o.success){let s=o.data;n=typeof s.data[0].embedding=="string"?sn:an;let i=s.data.map(l=>typeof l.embedding=="string"?{index:l.index,embedding:l.embedding}:{index:l.index,embedding:l.embedding});return {encodingFormat:n,embeddings:i,usage:{totalTokens:s.usage.total_tokens}}}throw new H({info:"Invalid response from model",cause:o.error})}},Gn="voyage-code-2",qs="Optimized for code retrieval.",Zn=ee(ne).parse({name:Gn,description:qs,modalities:te,maxInputTokens:16e3,maxOutputTokens:16e3,config:{def:I.base().def,schema:I.base().schema}}),Ds=W,Hs=class extends oe{constructor(t){super(Zn,t);}},Wn="voyage-law-2",Fs="Optimized for legal and long-context retrieval and RAG. Also improved performance across all domains.",Xn=ee(ne).parse({name:Wn,description:Fs,modalities:te,maxInputTokens:16e3,maxOutputTokens:16e3,config:{def:I.base().def,schema:I.base().schema}}),zs=W,Ks=class extends oe{constructor(t){super(Xn,t);}},Yn="voyage-multilingual-2",Vs="Optimized for multilingual retrieval and RAG.",Qn=ee(ne).parse({name:Yn,description:Vs,modalities:te,maxInputTokens:32e3,maxOutputTokens:32e3,config:{def:I.base().def,schema:I.base().schema}}),Js=W,Gs=class extends oe{constructor(t){super(Qn,t);}},eo="voyage-finance-2",Zs="Optimized for finance retrieval and RAG.",to=ee(ne).parse({name:eo,description:Zs,modalities:te,maxInputTokens:32e3,maxOutputTokens:32e3,config:{def:I.base().def,schema:I.base().schema}}),Ws=W,Xs=class extends oe{constructor(t){super(to,t);}},no="voyage-3-lite",Ys="Optimized for latency and cost.",oo=ee(ne).parse({name:no,description:Ys,modalities:te,maxInputTokens:32e3,maxOutputTokens:32e3,config:{def:I.base().def,schema:I.base().schema}}),Qs=W,er=class extends oe{constructor(t){super(oo,t);}},ao="voyage-3",tr="Optimized for quality.",io=ee(ne).parse({name:ao,description:tr,modalities:te,maxInputTokens:32e3,maxOutputTokens:32e3,config:{def:I.base().def,schema:I.base().schema}}),nr=W,or=class extends oe{constructor(t){super(io,t);}};var ar="system",ir="user",co="assistant",sr="tool",rr=[ar,ir,co,sr],rt=zod.z.enum(rr),lr=[co],dr=zod.z.enum(lr),mo="image",cr="base64",mr=["png","jpeg","webp","gif"],ur=zod.z.object({type:zod.z.literal(cr),base64:zod.z.string(),mediaType:zod.z.enum(mr)}),pr="url",hr=zod.z.object({type:zod.z.literal(pr),url:zod.z.string()}),gr=zod.z.discriminatedUnion("type",[ur,hr]),fr=["low","medium","high","auto"],yr=zod.z.enum(fr),br=(t=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(mo),detail:yr,value:gr,metadata:t}),uo="reasoning",po="partial-reasoning",ho="thinking",kr="redacted",st=zod.z.object({type:zod.z.literal(ho),thinking:zod.z.string(),signature:zod.z.string()}),go=zod.z.object({type:zod.z.literal(kr),data:zod.z.string()}),vr=zod.z.discriminatedUnion("type",[st,go]),Tr=(t=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(uo),value:vr,metadata:t}),Cr=zod.z.object({type:zod.z.literal(ho),thinking:st.shape.thinking.optional(),signature:st.shape.signature.optional()}),xr=zod.z.discriminatedUnion("type",[Cr,go]),Mr=(t=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(po),value:xr,metadata:t}),fo="text",wr=(t=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(fo),value:zod.z.string(),metadata:t}),yo="partial-text",Sr=(t=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(yo),value:zod.z.string(),metadata:t}),bo="tool-call",Pr=(t=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(bo),index:zod.z.number().int().nonnegative(),id:zod.z.string().min(1),name:zod.z.string().min(1),arguments:zod.z.string(),metadata:t}),ko="partial-tool-call",Or=(t=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(ko),index:zod.z.number().int().nonnegative(),id:zod.z.string().optional(),name:zod.z.string().optional(),arguments:zod.z.string().optional(),metadata:t}),vo="tool-response",Rr=(t=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(vo),index:zod.z.number().int().nonnegative(),id:zod.z.string().min(1),name:zod.z.string().min(1),data:zod.z.string(),metadata:t}),jr=[fo,mo,bo,vo,uo],To=zod.z.enum(jr),Er=(t=zod.z.undefined(),n=zod.z.undefined(),o=zod.z.undefined(),s=zod.z.undefined(),i=zod.z.undefined())=>zod.z.discriminatedUnion("modality",[wr(t),br(n),Pr(o),Rr(s),Tr(i)]),_r=[yo,ko,po];zod.z.enum(_r);var Ir=(t=zod.z.undefined(),n=zod.z.undefined(),o=zod.z.undefined())=>zod.z.discriminatedUnion("modality",[Sr(t),Or(n),Mr(o)]);var Ar=(t=rt,n=zod.z.undefined(),o=zod.z.undefined(),s=zod.z.undefined(),i=zod.z.undefined(),l=zod.z.undefined(),r=zod.z.undefined())=>zod.z.object({role:t,content:zod.z.array(Er(n,o,s,i,r)),metadata:l}),Br=(t=dr,n=zod.z.undefined(),o=zod.z.undefined(),s=zod.z.undefined(),i=zod.z.undefined())=>zod.z.object({role:t,partialContent:Ir(n,o,s),metadata:i}),Nr=zod.z.object({promptTokens:zod.z.number().nonnegative(),completionTokens:zod.z.number().nonnegative(),totalTokens:zod.z.number().nonnegative()}),so=zod.z.object({token:zod.z.string(),logProb:zod.z.number(),bytes:zod.z.array(zod.z.number().int()).nullable()}),Ur=so.extend({topLogProbs:zod.z.array(so)}),Co=zod.z.array(Ur);zod.z.object({messages:zod.z.array(Ar()),usage:Nr.optional(),logProbs:Co.optional()});var Lr=zod.z.object({promptTokens:zod.z.number().nonnegative().optional(),completionTokens:zod.z.number().nonnegative().optional(),totalTokens:zod.z.number().nonnegative().optional()});zod.z.object({partialMessages:zod.z.array(Br()),usage:Lr.optional(),logProbs:Co.optional()});var $r=["object","array","number","string","boolean","enum"],ro=zod.z.enum($r),qr=zod.z.object({anyOf:zod.z.array(zod.z.any()).optional(),type:zod.z.union([ro,zod.z.array(zod.z.union([ro,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()}),Dr=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(qr),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:Dr}).optional();var Hr="text",Fr="token",zr=[Hr,Fr];zod.z.enum(zr);zod.z.array(zod.z.string().min(1));zod.z.array(zod.z.array(zod.z.number().int().nonnegative()));var Vr="float",Jr=zod.z.object({index:zod.z.number().int().nonnegative(),embedding:zod.z.array(zod.z.number())}),Gr="base64",Zr=zod.z.object({index:zod.z.number().int().nonnegative(),embedding:zod.z.string().base64()}),lo=zod.z.object({totalTokens:zod.z.number().int().nonnegative()});zod.z.discriminatedUnion("encodingFormat",[zod.z.object({encodingFormat:zod.z.literal(Vr),embeddings:zod.z.array(Jr),usage:lo.optional()}),zod.z.object({encodingFormat:zod.z.literal(Gr),embeddings:zod.z.array(Zr),usage:lo.optional()})]);var Wr=t=>{let n=new WeakSet;return JSON.stringify(t,(o,s)=>{if(typeof s=="object"&&s!==null){if(n.has(s))return;n.add(s);}return s})},Xr=t=>t==null?"unknown error":typeof t=="string"?t:t instanceof Error?t.message:Wr(t),it="GatewayBaseError",lt=class xo extends Error{constructor({info:n,cause:o},s){super(`[${s!=null?s:it}]: ${n}
18
18
  Message: ${Xr(o)}`),this.name=it,this.info=n,this.cause=o,this.name=s!=null?s:it,Object.setPrototypeOf(this,new.target.prototype);}static isGatewayBaseError(n){return n instanceof xo}toJSON(){return {name:this.name,info:this.info,cause:this.cause,message:this.message,stack:this.stack}}},Yr=zod.z.object({inputPricePerMillion:zod.z.number().nonnegative().describe("Price per 1M input tokens"),outputPricePerMillion:zod.z.number().nonnegative().describe("Price per 1M output tokens")}).describe("Input/output price pair (per 1M tokens) for a specific category within a ChatModel pricing tier."),Qr=zod.z.object({base:Yr.describe("Base (uncached, non\u2011reasoning) rates")}).describe("Holds the `ChatModelTokenPairPrice` for different categories (e.g., base) within a single pricing tier."),el=zod.z.object({minTokens:zod.z.number().int().nonnegative().describe("Inclusive lower token bound for this tier."),maxTokens:zod.z.number().int().nullable().optional().describe("Exclusive upper token bound; `null` means \u221E."),prices:Qr.describe("Price categories and rates for this specific token range.")}).refine(t=>t.maxTokens===null||typeof t.maxTokens=="number"&&t.maxTokens>t.minTokens,{message:"maxTokens must be > minTokens (or null for infinite).",path:["maxTokens"]}).describe("A single pricing tier defined by a token range and associated prices.");zod.z.object({modelName:zod.z.string().describe("Model name this schedule applies to."),currency:zod.z.string().default("USD").describe("Currency code (e.g., USD)."),tokenRanges:zod.z.array(el).min(1).describe("Pricing tiers (`ChatModelTokenRangePrice`) schedule, sorted by minTokens.")}).superRefine((t,n)=>{let{tokenRanges:o}=t;o[0].minTokens!==0&&n.addIssue({code:zod.z.ZodIssueCode.custom,path:["tokenRanges",0,"minTokens"],message:"The first tier must have minTokens = 0."});for(let i=1;i<o.length;i++){let l=o[i-1],r=o[i];if(l.maxTokens===null){n.addIssue({code:zod.z.ZodIssueCode.custom,path:["tokenRanges",i-1,"maxTokens"],message:"Cannot define any tokenRanges after an infinite tier (maxTokens = null)."});break}r.minTokens!==l.maxTokens&&n.addIssue({code:zod.z.ZodIssueCode.custom,path:["tokenRanges",i,"minTokens"],message:`Tier ${i} minTokens (${r.minTokens}) must equal previous tier's maxTokens (${l.maxTokens}) for contiguity.`}),r.minTokens<l.minTokens&&n.addIssue({code:zod.z.ZodIssueCode.custom,path:["tokenRanges",i,"minTokens"],message:`tokenRanges must be sorted by ascending minTokens. Tier ${i} (${r.minTokens}) starts before Tier ${i-1} (${l.minTokens}).`});}let s=o[o.length-1];o.every(i=>i.maxTokens!==null||i===s)&&s.maxTokens!==null&&n.addIssue({code:zod.z.ZodIssueCode.custom,path:["tokenRanges",o.length-1,"maxTokens"],message:"The final tier must have maxTokens = null (representing infinity)."});}).describe("Complete pricing schedule for a single chat model, including all its token-based tiers.");var tl="function";var nl=zod.z.enum(["object","array","number","string","boolean","null"]),ol=zod.z.object({anyOf:zod.z.array(zod.z.any()).optional(),type:nl.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(ol).optional(),required:zod.z.array(zod.z.string()).optional()});var al=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 il=zod.z.enum(["function"]);zod.z.object({type:il,definition:zod.z.object({schema:al})});var sl=[tl];zod.z.enum(sl);var rl=Object.defineProperty,Mo=Object.getOwnPropertySymbols,ll=Object.prototype.hasOwnProperty,dl=Object.prototype.propertyIsEnumerable,wo=(t,n,o)=>n in t?rl(t,n,{enumerable:!0,configurable:!0,writable:!0,value:o}):t[n]=o,cl=(t,n)=>{for(var o in n||(n={}))ll.call(n,o)&&wo(t,o,n[o]);if(Mo)for(var o of Mo(n))dl.call(n,o)&&wo(t,o,n[o]);return t},So="ProviderError",dt=class Oo extends lt{constructor({info:n,cause:o}){super({info:n,cause:o},So),this.name=So,this.info=n,this.cause=o;}static isProviderError(n){return n instanceof Oo}};var Po="ModelResponseError",ct=class Ro extends lt{constructor({info:n,cause:o}){super({info:n,cause:o},Po),this.name=Po,this.cause=o,this.info=n;}static isModelResponseError(n){return n instanceof Ro}};var jo="multi-string",ml=zod.z.object({type:zod.z.literal(jo),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 Eo="object-schema",ul=zod.z.object({type:zod.z.literal(Eo),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 _o="range",pl=zod.z.object({type:zod.z.literal(_o),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 Io="select-boolean",hl=zod.z.object({type:zod.z.literal(Io),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 mt="select-string",Ao=zod.z.object({type:zod.z.literal(mt),param:zod.z.string().min(1),title:zod.z.string().min(1),description:zod.z.string().min(1).max(500),default:zod.z.string(),choices:zod.z.array(zod.z.string())}),gl=(t,n)=>zod.z.enum(n).nullable().default(t).optional(),Bo=t=>({def:Ao.parse(cl({type:mt},t)),schema:gl(t.default,t.choices)}),fl=[_o,jo,mt,Eo,Io];zod.z.enum(fl);var yl=zod.z.discriminatedUnion("type",[pl,ml,Ao,hl,ul]),A=(t=rt,n=To)=>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(n).nonempty(),maxInputTokens:zod.z.number().int().positive().min(1),maxOutputTokens:zod.z.number().int().positive().min(1),maxReasoningTokens:zod.z.number().int().positive().min(1).optional(),config:zod.z.object({def:zod.z.record(zod.z.string().min(1),yl),schema:zod.z.instanceof(zod.z.ZodObject)}).refine(o=>{var s,i;let l=Object.keys(o.def),r=Object.keys((i=(s=o.schema)==null?void 0:s.shape)!=null?i:{});return l.every(d=>r.includes(d))&&r.every(d=>l.includes(d))},{message:"Keys in 'config.def' must exactly match keys in 'config.schema'"}),price:zod.z.custom()});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 bl=()=>typeof window!="undefined"&&typeof window.document!="undefined"&&typeof navigator!="undefined";var No=t=>{if(bl()){let n=atob(t),o=new Uint8Array(n.length);for(let s=0;s<n.length;s++)o[s]=n.charCodeAt(s);return new TextDecoder("utf-8").decode(o)}else return Buffer.from(t,"base64").toString("utf-8")};var ut=Bo({param:"awsRegion",title:"AWS Region",description:"Controls which region the model will use to call AWS services.",default:"us-east-1",choices:["us-east-1","us-west-2","eu-west-1","eu-west-3","eu-central-1","ap-south-3","ap-southeast-1","ap-southeast-2","ap-northeast-1"]});var Uo=(t,n)=>ve(t,n).extend({awsRegion:ut.schema}),Lo=(t,n)=>X(B({},Te(t,n)),{awsRegion:ut.def});var C={base:(t,n)=>({def:Lo(t,n),schema:Uo(t,n)})};var kl="bedrock",ae=class ae{constructor(){this.version="v1";this.name=kl;this.chatModelFactories={[Oe]:{model:Re,modelOptions:Ho,modelSchema:ft},[_e]:{model:Ie,modelOptions:zo,modelSchema:bt},[je]:{model:Ee,modelOptions:Fo,modelSchema:yt},[Me]:{model:we,modelOptions:qo,modelSchema:ht},[Se]:{model:Pe,modelOptions:Do,modelSchema:gt},[Ce]:{model:xe,modelOptions:$o,modelSchema:pt}};this.embeddingModelFactories={};}chatModelLiterals(){return Object.keys(this.chatModelFactories)}chatModelSchemas(){return Object.keys(this.chatModelFactories).reduce((n,o)=>(n[o]=this.chatModelFactories[o].modelSchema,n),{})}chatModel(n){let o=n.modelName;if(!(o in this.chatModelFactories))throw new dt({info:`Bedrock chat model: ${o} not found`,cause:new Error(`Bedrock chat model: ${o} not found, available chat models:
19
19
  ${this.chatModelLiterals().join(", ")}`)});let s=this.chatModelFactories[o].model,i=this.chatModelFactories[o].modelOptions.parse(n);return new s(i)}embeddingModelLiterals(){return Object.keys(this.embeddingModelFactories)}embeddingModelSchemas(){return Object.keys(this.embeddingModelFactories).reduce((n,o)=>(n[o]=this.embeddingModelFactories[o].modelSchema,n),{})}embeddingModel(n){throw new dt({info:"Adaline Bedrock provider does not support embedding models yet",cause:new Error("Adaline Bedrock provider does not support embedding models yet")})}};ae.awsService="bedrock",ae.awsDefaultRegion="us-east-1",ae.awsUrl=n=>`https://bedrock-runtime.${n!=null?n:ae.awsDefaultRegion}.amazonaws.com`;var $=ae;var P=zod.z.object({modelName:zod.z.string(),awsAccessKeyId:zod.z.string(),awsSecretAccessKey:zod.z.string()});var w={"anthropic.claude-3-5-haiku-20241022-v1:0":{modelName:"anthropic.claude-3-5-haiku-20241022-v1:0",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:1,outputPricePerMillion:5}}}]},"anthropic.claude-3-5-sonnet-20240620-v1:0":{modelName:"anthropic.claude-3-5-sonnet-20240620-v1:0",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:3,outputPricePerMillion:15}}}]},"anthropic.claude-3-5-sonnet-20241022-v2:0":{modelName:"anthropic.claude-3-5-sonnet-20241022-v2:0",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:3,outputPricePerMillion:15}}}]},"anthropic.claude-3-haiku-20240307-v1:0":{modelName:"anthropic.claude-3-haiku-20240307-v1:0",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:.25,outputPricePerMillion:1.25}}}]},"anthropic.claude-3-opus-20240229-v1:0":{modelName:"anthropic.claude-3-opus-20240229-v1:0",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:15,outputPricePerMillion:75}}}]},"anthropic.claude-3-sonnet-20240229-v1:0":{modelName:"anthropic.claude-3-sonnet-20240229-v1:0",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:3,outputPricePerMillion:15}}}]}};var O=class t extends L{constructor(o,s){let i=P.parse(s);super(o,{apiKey:"random-api-key",modelName:i.modelName});this.version="v1";this.modelSchema=o,this.modelName=i.modelName,this.awsService=$.awsService,this.awsAccessKeyId=i.awsAccessKeyId,this.awsSecretAccessKey=i.awsSecretAccessKey;}getDefaultBaseUrl(){return $.awsUrl()}getDefaultHeaders(){return {Accept:"application/json","Content-Type":"application/json"}}getDefaultParams(){return {anthropic_version:"bedrock-2023-05-31"}}getCompleteChatUrl(o,s,i){let l=$.awsUrl(o==null?void 0:o.awsRegion);return new Promise(r=>{r(`${l}/model/${this.modelName}/invoke`);})}transformConfig(o,s,i){let l=B({},o);return delete l.awsRegion,super.transformConfig(l,s,i)}getCompleteChatHeaders(o,s,i){return N(this,null,function*(){let l=new URL(yield this.getCompleteChatUrl(o,s,i)),r={accessKeyId:this.awsAccessKeyId,secretAccessKey:this.awsSecretAccessKey},d=o==null?void 0:o.awsRegion,m=this.getDefaultHeaders();m=X(B({},m),{host:$.awsUrl(d).split("://")[1]});let u=yield this.getCompleteChatData(o||{},s||[],i),g=new protocolHttp.HttpRequest({hostname:l.hostname,path:l.pathname,protocol:l.protocol,method:"POST",body:JSON.stringify(u),headers:m});return (yield new signatureV4.SignatureV4({credentials:r,service:this.awsService,region:d,sha256:sha256Js.Sha256}).sign(g)).headers})}getCompleteChatData(o,s,i){return N(this,null,function*(){let l=B(B({},this.getDefaultParams()),yield ue(t.prototype,this,"getCompleteChatData").call(this,o,s,i));return new Promise(r=>{r(l);})})}getStreamChatUrl(o,s,i){return N(this,null,function*(){let l=$.awsUrl(o==null?void 0:o.awsRegion);return new Promise(r=>{r(`${l}/model/${this.modelName}/invoke-with-response-stream`);})})}getStreamChatHeaders(o,s,i){return N(this,null,function*(){let l=new URL(yield this.getStreamChatUrl(o,s,i)),r={accessKeyId:this.awsAccessKeyId,secretAccessKey:this.awsSecretAccessKey},d=o==null?void 0:o.awsRegion,m=this.getDefaultHeaders();m=X(B({},m),{host:$.awsUrl(d).split("://")[1]});let u=yield this.getCompleteChatData(o||{},s||[],i),g=new protocolHttp.HttpRequest({hostname:l.hostname,path:l.pathname,protocol:l.protocol,method:"POST",body:JSON.stringify(u),headers:m});return (yield new signatureV4.SignatureV4({credentials:r,service:this.awsService,region:d,sha256:sha256Js.Sha256}).sign(g)).headers})}getStreamChatData(o,s,i){return N(this,null,function*(){let l=B(B({},this.getDefaultParams()),yield ue(t.prototype,this,"getStreamChatData").call(this,o,s,i));return "stream"in l&&delete l.stream,l})}transformStreamChatResponseChunk(o,s){return Ne(this,null,function*(){let i=o.toString(),l=/{\s*"bytes"\s*:\s*"[\w=+/]+".*?}/g,r=i.match(l)||[];for(let d of r){let m=d.indexOf("{"),u=d.indexOf("}");if(m!==-1&&u!==-1&&m<u){let g;try{g=JSON.parse(d.slice(m,u+1));}catch(p){throw new ct({info:`Malformed JSON received in stream : ${g}`,cause:p})}let f=No(g.bytes),h=(yield new pe(ue(t.prototype,this,"transformStreamChatResponseChunk").call(this,`data: ${f}`,s).next())).value;h&&(yield h);}}})}transformProxyStreamChatResponseChunk(o,s,i,l,r){return Ne(this,null,function*(){yield*he(this.transformStreamChatResponseChunk(o,s));})}getRegionHelper(o){var i;let s=o["aws-region"];if(!s){let l=(i=o.authorization)==null?void 0:i.match(/Credential=[^/]+\/\d+\/([^/]+)\/bedrock/);l&&(s=l[1]);}return s}getProxyStreamChatUrl(o,s,i){return N(this,null,function*(){let l=this.getRegionHelper(s||{}),r=$.awsUrl(l);return new Promise(d=>{d(`${r}/model/${this.modelName}/invoke-with-response-stream`);})})}getProxyChatHeaders(o,s,i,l){return N(this,null,function*(){let r=new URL(yield o());if(!i)return {};let d=i["aws-access-key-id"],m=i["aws-secret-access-key"],u=this.getRegionHelper(i);if(!d||!m)return {};let g={accessKeyId:d,secretAccessKey:m};i=X(B({},i),{host:r.host,"content-type":"application/json",accept:"application/json"}),delete i["content-length"];let f=i.authorization||i.Authorization;if(f){let R=f.match(/SignedHeaders=([^,]+)/);if(R&&R[1]){let ie=R[1].split(";").map(ce=>ce.trim().toLowerCase());ie.push("authorization"),i=Object.keys(i).reduce((ce,Be)=>{var Ct;return ie.includes(Be.toLowerCase())&&(ce[Be]=(Ct=i==null?void 0:i[Be])!=null?Ct:""),ce},{});}}let h=new protocolHttp.HttpRequest({hostname:r.hostname,path:r.pathname,protocol:r.protocol,method:"POST",body:JSON.stringify(s),headers:i});return (yield new signatureV4.SignatureV4({credentials:g,service:this.awsService,region:u,sha256:sha256Js.Sha256}).sign(h)).headers})}getProxyCompleteChatUrl(o,s,i){return N(this,null,function*(){let l=this.getRegionHelper(s||{}),r=$.awsUrl(l);return new Promise(d=>{d(`${r}/model/${this.modelName}/invoke`);})})}getProxyCompleteChatHeaders(o,s,i){return N(this,null,function*(){return this.getProxyChatHeaders(()=>this.getProxyCompleteChatUrl(o,s,i),o,s,i)})}getProxyStreamChatHeaders(o,s,i){return N(this,null,function*(){return this.getProxyChatHeaders(()=>this.getProxyStreamChatUrl(o,s,i),o,s,i)})}getModelPricing(){if(!(this.modelName in w))throw new ct({info:`Invalid model pricing for model : '${this.modelName}'`,cause:new Error(`No pricing configuration found for model "${this.modelName}"`)});return w[this.modelName]}};var Ce="anthropic.claude-3-5-haiku-20241022-v1:0",Tl="Our fastest model with intelligence at blazing speeds.",pt=A(y,v).parse({name:Ce,description:Tl,maxInputTokens:2e5,maxOutputTokens:8192,roles:b,modalities:k,config:{def:C.base(8192,4).def,schema:C.base(8192,4).schema},price:w[Ce]}),$o=P,xe=class extends O{constructor(n){super(pt,n);}};var Me="anthropic.claude-3-5-sonnet-20240620-v1:0",Cl="Most intelligent model. Highest level of intelligence and capability.",ht=A(y,v).parse({name:Me,description:Cl,maxInputTokens:2e5,maxOutputTokens:8192,roles:b,modalities:k,config:{def:C.base(8192,4).def,schema:C.base(8192,4).schema},price:w[Me]}),qo=P,we=class extends O{constructor(n){super(ht,n);}};var Se="anthropic.claude-3-5-sonnet-20241022-v2:0",xl="Most intelligent model. Highest level of intelligence and capability.",gt=A(y,v).parse({name:Se,description:xl,maxInputTokens:2e5,maxOutputTokens:8192,roles:b,modalities:k,config:{def:C.base(8192,4).def,schema:C.base(8192,4).schema},price:w[Se]}),Do=P,Pe=class extends O{constructor(n){super(gt,n);}};var Oe="anthropic.claude-3-haiku-20240307-v1:0",Ml="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.",ft=A(y,v).parse({name:Oe,description:Ml,maxInputTokens:2e5,maxOutputTokens:4096,roles:b,modalities:k,config:{def:C.base(4096,4).def,schema:C.base(4096,4).schema},price:w[Oe]}),Ho=P,Re=class extends O{constructor(n){super(ft,n);}};var je="anthropic.claude-3-opus-20240229-v1:0",wl="Powerful model for highly complex tasks. Top-level performance, intelligence, fluency, and understanding.",yt=A(y,v).parse({name:je,description:wl,maxInputTokens:2e5,maxOutputTokens:4096,roles:b,modalities:k,config:{def:C.base(4096,4).def,schema:C.base(4096,4).schema},price:w[je]}),Fo=P,Ee=class extends O{constructor(n){super(yt,n);}};var _e="anthropic.claude-3-sonnet-20240229-v1:0",Sl="Balance of intelligence and speed. Strong utility, balanced for scaled deployments.",bt=A(y,v).parse({name:_e,description:Sl,maxInputTokens:2e5,maxOutputTokens:4096,roles:b,modalities:k,config:{def:C.base(4096,4).def,schema:C.base(4096,4).schema},price:w[_e]}),zo=P,Ie=class extends O{constructor(n){super(bt,n);}};
20
20