@adaline/anthropic 0.7.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/LICENSE +19 -0
- package/README.md +7 -0
- package/dist/index.d.mts +994 -0
- package/dist/index.d.ts +994 -0
- package/dist/index.js +61 -0
- package/dist/index.js.map +1 -0
- package/dist/index.mjs +19 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +64 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var zod = require('zod');
|
|
4
|
+
|
|
5
|
+
var Kt=Object.defineProperty,Nt=Object.defineProperties;var Vt=Object.getOwnPropertyDescriptors;var ke=Object.getOwnPropertySymbols;var Gt=Object.prototype.hasOwnProperty,Jt=Object.prototype.propertyIsEnumerable;var Zt=(a,e)=>(e=Symbol[a])?e:Symbol.for("Symbol."+a);var Pe=(a,e,o)=>e in a?Kt(a,e,{enumerable:!0,configurable:!0,writable:!0,value:o}):a[e]=o,y=(a,e)=>{for(var o in e||(e={}))Gt.call(e,o)&&Pe(a,o,e[o]);if(ke)for(var o of ke(e))Jt.call(e,o)&&Pe(a,o,e[o]);return a},U=(a,e)=>Nt(a,Vt(e));var E=(a,e,o)=>new Promise((n,d)=>{var l=c=>{try{i(o.next(c));}catch(u){d(u);}},s=c=>{try{i(o.throw(c));}catch(u){d(u);}},i=c=>c.done?n(c.value):Promise.resolve(c.value).then(l,s);i((o=o.apply(a,e)).next());}),Wt=function(a,e){this[0]=a,this[1]=e;},_e=(a,e,o)=>{var n=(s,i,c,u)=>{try{var g=o[s](i),b=(i=g.value)instanceof Wt,T=g.done;Promise.resolve(b?i[0]:i).then(C=>b?n(s==="return"?s:"next",i[1]?{done:C.done,value:C.value}:C,c,u):c({value:C,done:T})).catch(C=>n("throw",C,c,u));}catch(C){u(C);}},d=s=>l[s]=i=>new Promise((c,u)=>n(s,i,c,u)),l={};return o=o.apply(a,e),l[Zt("asyncIterator")]=()=>l,d("next"),d("throw"),d("return"),l};var Xt=a=>a==null?"unknown error":typeof a=="string"?a:a instanceof Error?a.message:JSON.stringify(a),Y="GatewayBaseError",w=class Oe extends Error{constructor({info:e,cause:o},n){super(`[${n!=null?n:Y}]: ${e}
|
|
6
|
+
Message: ${Xt(o)}`),this.name=Y,this.info=e,this.cause=o,this.name=n!=null?n:Y,Object.setPrototypeOf(this,new.target.prototype);}static isGatewayBaseError(e){return e instanceof Oe}toJSON(){return {name:this.name,info:this.info,cause:this.cause,message:this.message,stack:this.stack}}},I="system",L="user",M="assistant",Yt="tool",Qt=[I,L,M,Yt],Q=zod.z.enum(Qt),eo=[M],to=zod.z.enum(eo),j="image",ee="base64",oo=["png","jpeg","webp","gif"],no=zod.z.object({type:zod.z.literal(ee),base64:zod.z.string(),media_type:zod.z.enum(oo)}),ao="url",so=zod.z.object({type:zod.z.literal(ao),url:zod.z.string()}),io=zod.z.discriminatedUnion("type",[no,so]),ro=["low","medium","high","auto"],lo=zod.z.enum(ro),mo=(a=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(j),detail:lo,value:io,metadata:a}),f="text",Ue=(a=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(f),value:zod.z.string(),metadata:a}),te="partial-text",Le=(a=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(te),value:zod.z.string(),metadata:a}),R="tool-call",Be=(a=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(R),index:zod.z.number().int().nonnegative(),id:zod.z.string().min(1),name:zod.z.string().min(1),arguments:zod.z.string(),metadata:a}),oe="partial-tool-call",$e=(a=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(oe),index:zod.z.number().int().nonnegative(),id:zod.z.string().optional(),name:zod.z.string().optional(),arguments:zod.z.string().optional(),metadata:a}),k="tool-response",po=(a=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(k),index:zod.z.number().int().nonnegative(),id:zod.z.string().min(1),name:zod.z.string().min(1),data:zod.z.string(),metadata:a}),co=[f,j,R,k],Fe=zod.z.enum(co),uo=(a=zod.z.undefined(),e=zod.z.undefined(),o=zod.z.undefined(),n=zod.z.undefined())=>zod.z.discriminatedUnion("modality",[Ue(a),mo(e),Be(o),po(n)]),go=[te,oe];zod.z.enum(go);var ho=(a=zod.z.undefined(),e=zod.z.undefined())=>zod.z.discriminatedUnion("modality",[Le(a),$e(e)]);var ne=(a=Q,e=zod.z.undefined(),o=zod.z.undefined(),n=zod.z.undefined(),d=zod.z.undefined(),l=zod.z.undefined())=>zod.z.object({role:a,content:zod.z.array(uo(e,o,n,d)),metadata:l}),ae=(a=to,e=zod.z.undefined(),o=zod.z.undefined(),n=zod.z.undefined())=>zod.z.object({role:a,partialContent:ho(e,o),metadata:n}),ze=a=>Ue().parse({modality:f,value:a}),De=(a,e,o,n)=>Be().parse({modality:R,index:a,id:e,name:o,arguments:n});var se=(a,e)=>ae().parse({role:a,partialContent:Le().parse({modality:te,value:e})}),ie=(a,e,o,n,d)=>ae().parse({role:a,partialContent:$e().parse({modality:oe,index:e,id:o,name:n,arguments:d})});var H=(a=zod.z.record(zod.z.string(),zod.z.any()).optional())=>a,yo="function";var fo=zod.z.enum(["object","array","number","string","boolean","null"]),bo=zod.z.object({anyOf:zod.z.array(zod.z.any()).optional(),type:fo.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(bo).optional(),required:zod.z.array(zod.z.string()).optional()});var To=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 Co=zod.z.enum(["function"]),Mo=zod.z.object({type:Co,definition:zod.z.object({schema:To})}),vo=[yo];zod.z.enum(vo);var He=(a=zod.z.undefined())=>zod.z.discriminatedUnion("type",[Mo.extend({metadata:a})]),P="text",Ke="token",Ro=[P,Ke],Ne=zod.z.enum(Ro),Eo=zod.z.array(zod.z.string().min(1)),xo=zod.z.array(zod.z.array(zod.z.number().int().nonnegative())),Ve=(a=zod.z.undefined())=>zod.z.discriminatedUnion("modality",[zod.z.object({modality:zod.z.literal(P),metadata:a,requests:Eo}),zod.z.object({modality:zod.z.literal(Ke),metadata:a,requests:xo})]),re="float",So=zod.z.object({index:zod.z.number().int().nonnegative(),embedding:zod.z.array(zod.z.number())}),le="base64",Ao=zod.z.object({index:zod.z.number().int().nonnegative(),embedding:zod.z.string().base64()}),qe=zod.z.object({totalTokens:zod.z.number().int().nonnegative()});zod.z.discriminatedUnion("encodingFormat",[zod.z.object({encodingFormat:zod.z.literal(re),embeddings:zod.z.array(So),usage:qe.optional()}),zod.z.object({encodingFormat:zod.z.literal(le),embeddings:zod.z.array(Ao),usage:qe.optional()})]);var Ge=zod.z.object({promptTokens:zod.z.number().nonnegative(),completionTokens:zod.z.number().nonnegative(),totalTokens:zod.z.number().nonnegative()}),Ie=zod.z.object({token:zod.z.string(),logProb:zod.z.number(),bytes:zod.z.array(zod.z.number().int()).nullable()}),wo=Ie.extend({topLogProbs:zod.z.array(Ie)}),Je=zod.z.array(wo);zod.z.object({messages:zod.z.array(ne()),usage:Ge.optional(),logProbs:Je.optional()});zod.z.object({partialMessages:zod.z.array(ae()),usage:Ge.optional(),logProbs:Je.optional()});var jo=Object.defineProperty,Ze=Object.getOwnPropertySymbols,ko=Object.prototype.hasOwnProperty,Po=Object.prototype.propertyIsEnumerable,We=(a,e,o)=>e in a?jo(a,e,{enumerable:!0,configurable:!0,writable:!0,value:o}):a[e]=o,de=(a,e)=>{for(var o in e||(e={}))ko.call(e,o)&&We(a,o,e[o]);if(Ze)for(var o of Ze(e))Po.call(e,o)&&We(a,o,e[o]);return a},Xe="ProviderError",$=class at extends w{constructor({info:e,cause:o}){super({info:e,cause:o},Xe),this.name=Xe,this.info=e,this.cause=o;}static isProviderError(e){return e instanceof at}};var Ye="ModelResponseError",x=class st extends w{constructor({info:e,cause:o}){super({info:e,cause:o},Ye),this.name=Ye,this.cause=o,this.info=e;}static isModelResponseError(e){return e instanceof st}},Qe="InvalidModelRequestError",K=class it extends w{constructor({info:e,cause:o}){super({info:e,cause:o},Qe),this.name=Qe,this.cause=o,this.info=e,Object.setPrototypeOf(this,new.target.prototype);}static isInvalidModelRequestError(e){return e instanceof it}},et="InvalidConfigError",_=class rt extends w{constructor({info:e,cause:o}){super({info:e,cause:o},et),this.name=et,this.cause=o,this.info=e,Object.setPrototypeOf(this,new.target.prototype);}static isInvalidConfigError(e){return e instanceof rt}},tt="InvalidMessagesError",S=class lt extends w{constructor({info:e,cause:o}){super({info:e,cause:o},tt),this.name=tt,this.cause=o,this.info=e,Object.setPrototypeOf(this,new.target.prototype);}static isInvalidMessagesError(e){return e instanceof lt}},ot="InvalidToolsError",me=class dt extends w{constructor({info:e,cause:o}){super({info:e,cause:o},ot),this.name=ot,this.cause=o,this.info=e,Object.setPrototypeOf(this,new.target.prototype);}static isInvalidToolsError(e){return e instanceof dt}},nt="InvalidEmbeddingRequestsError",mt=class pt extends w{constructor({info:e,cause:o}){super({info:e,cause:o},nt),this.name=nt,this.info=e,this.cause=o,Object.setPrototypeOf(this,new.target.prototype);}static isInvalidEmbeddingRequestsError(e){return e instanceof pt}},pe="multi-string",ct=zod.z.object({type:zod.z.literal(pe),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()}),_o=a=>zod.z.array(zod.z.string()).max(a).default([]).optional(),ut=a=>({def:ct.parse(de({type:pe},a)),schema:_o(a.max)}),ce="range",gt=zod.z.object({type:zod.z.literal(ce),param:zod.z.string().min(1),title:zod.z.string().min(1),description:zod.z.string().min(1).max(500),min:zod.z.number().int(),max:zod.z.number().int(),step:zod.z.number().positive(),default:zod.z.number().int()}),qo=(a,e,o,n)=>zod.z.number().min(a).max(e).step(o).default(n).optional(),F=a=>({def:gt.parse(de({type:ce},a)),schema:qo(a.min,a.max,a.step,a.default)}),ue="select-string",ht=zod.z.object({type:zod.z.literal(ue),param:zod.z.string().min(1),title:zod.z.string().min(1),description:zod.z.string().min(1).max(500),default:zod.z.string().min(1),choices:zod.z.array(zod.z.string().min(1))}),Io=(a,e)=>zod.z.enum(e).default(a).optional(),B=a=>({def:ht.parse(de({type:ue},a)),schema:Io(a.default,a.choices)}),yt="object-schema",Oo=zod.z.object({type:zod.z.literal(yt),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 ft="select-boolean",Uo=zod.z.object({type:zod.z.literal(ft),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 Lo=[ce,pe,ue,yt,ft];zod.z.enum(Lo);var bt=zod.z.discriminatedUnion("type",[gt,ct,ht,Uo,Oo]),Tt=(a=Q,e=Fe)=>zod.z.object({name:zod.z.string().min(1),description:zod.z.string().min(1),roles:zod.z.record(a,zod.z.string().min(1).optional()),modalities:zod.z.array(e).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),bt),schema:zod.z.instanceof(zod.z.ZodObject)}).refine(o=>{var n,d;let l=Object.keys(o.def),s=Object.keys((d=(n=o.schema)==null?void 0:n.shape)!=null?d:{});return l.every(i=>s.includes(i))&&s.every(i=>l.includes(i))},{message:"Keys in 'config.def' must exactly match keys in 'config.schema'"})}),Ct=(a=Ne)=>zod.z.object({name:zod.z.string().min(1),description:zod.z.string().min(1),modalities:zod.z.array(a).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),bt),schema:zod.z.instanceof(zod.z.ZodObject)}).refine(e=>{var o,n;let d=Object.keys(e.def),l=Object.keys((n=(o=e.schema)==null?void 0:o.shape)!=null?n:{});return d.every(s=>l.includes(s))&&l.every(s=>d.includes(s))},{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 Bo={type:"range",title:"Temperature",description:"Adjusts the model's creativity level. With a setting of 0, the model strictly picks the most probable next word. For endeavors that benefit from a dash of inventiveness, consider dialing it up to 0.7 or higher, enabling the model to produce text that's unexpectedly fresh."},$o={type:"range",title:"Max tokens",description:"Specify the total tokens for generation, where one token approximates four English characters. Setting this to 0 defaults to the model's maximum capacity."},Fo=a=>({type:"multi",title:"Stop sequence",description:`Enter up to ${a} sequences that will halt additional text output. The generated text will exclude these sequences.`}),zo={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."},Do={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."},Ho={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."},Ko={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."},A={TEMPERATURE:Bo,MAX_TOKENS:$o,STOP:Fo,TOP_P:zo,TOP_K:Do,FREQUENCY_PENALTY:Ho,PRESENCE_PENALTY:Ko};var N=a=>Object.fromEntries(Object.entries(a).filter(([e,o])=>o!=null));var O=a=>a==null?void 0:a.replace(/\/$/,"");var ge=F({param:"temperature",title:A.TEMPERATURE.title,description:A.TEMPERATURE.description,min:0,max:1,step:.01,default:1}),he=a=>F({param:"max_tokens",title:A.MAX_TOKENS.title,description:A.MAX_TOKENS.description,min:0,max:a,step:1,default:0}),ye=a=>ut({param:"stop_sequences",title:A.STOP(a).title,description:A.STOP(a).description,max:a}),fe=F({param:"top_p",title:A.TOP_P.title,description:A.TOP_P.description,min:0,max:1,step:.01,default:1}),be=F({param:"top_k",title:"Top K",description:"Select only from the highest K probabilities for each following word, effectively eliminating the less likely 'long tail' options.",min:0,max:1,step:.01,default:1}),Te=B({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"]});var Mt=(a,e)=>zod.z.object({temperature:ge.schema,maxTokens:he(a).schema,stop:ye(e).schema,topP:fe.schema,topK:be.schema,toolChoice:Te.schema}),vt=(a,e)=>({temperature:ge.def,maxTokens:he(a).def,stop:ye(e).def,topP:fe.def,topK:be.def,toolChoice:Te.def});var Ce=B({param:"encoding_format",title:"Encoding format",description:"Select the encoding format for the word embedding.",default:"none",choices:["base64"]}),Me=B({param:"input_type",title:"Input type",description:"Select the input type for the word embedding.",default:"none",choices:["query","document"]}),ve=B({param:"truncation",title:"Truncation",description:"Select the truncation for the word embedding.",default:"none",choices:["true","false"]});var Rt=()=>zod.z.object({encodingFormat:Ce.schema,inputType:Me.schema,truncation:ve.schema}),Et=()=>({encodingFormat:Ce.def,inputType:Me.def,truncation:ve.def});var Re={base:(a,e)=>({def:vt(a,e),schema:Mt(a,e)})},Ee={base:()=>({def:Et(),schema:Rt()})};var xt=zod.z.enum([I,L,M]),St={system:I,user:L,assistant:M};var At=[f,j,R,k],wt=zod.z.enum([f,j,R,k]);var Zo=zod.z.object({type:zod.z.literal("text"),text:zod.z.string()}),Wo=zod.z.object({type:zod.z.literal("tool_use"),id:zod.z.string(),name:zod.z.string(),input:zod.z.record(zod.z.any())}),jt=zod.z.object({content:zod.z.array(zod.z.discriminatedUnion("type",[Zo,Wo])),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()})}),kt=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()})})}),Pt=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()})}),Xo=zod.z.object({type:zod.z.literal("text"),text:zod.z.string()}),Yo=zod.z.object({type:zod.z.literal("tool_use"),id:zod.z.string(),name:zod.z.string(),input:zod.z.object({})}),_t=zod.z.object({type:zod.z.literal("content_block_start"),index:zod.z.number(),content_block:zod.z.discriminatedUnion("type",[Xo,Yo])}),Qo=zod.z.object({type:zod.z.literal("text_delta"),text:zod.z.string()}),en=zod.z.object({type:zod.z.literal("input_json_delta"),partial_json:zod.z.string()}),qt=zod.z.object({type:zod.z.literal("content_block_delta"),index:zod.z.number(),delta:zod.z.discriminatedUnion("type",[Qo,en])});var tn=zod.z.object({name:zod.z.string().min(1),description:zod.z.string().min(1).optional(),input_schema:zod.z.any()}),on=zod.z.object({type:zod.z.enum(["auto","any"])}),nn=zod.z.object({type:zod.z.literal("tool"),name:zod.z.string().min(1)}),xe=zod.z.object({text:zod.z.string().min(1),type:zod.z.literal("text")}),It=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 Ot=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([xe,It])).min(1))}),an=zod.z.object({role:zod.z.literal("user"),content:zod.z.string().min(1).or(zod.z.array(zod.z.union([xe,It,Ot])).min(1))}),sn=zod.z.object({role:zod.z.literal("assistant"),content:zod.z.string().min(1).or(zod.z.array(zod.z.union([xe,Ot])).min(1))}),rn=zod.z.union([an,sn]),Ut=zod.z.object({model:zod.z.string().min(1).optional(),messages:zod.z.array(rn).min(1).optional(),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([on,nn]).optional(),tools:zod.z.array(tn).min(1).optional(),top_p:zod.z.number().min(0).max(1).optional(),top_k:zod.z.number().min(0).optional()}).refine(a=>!(a.tool_choice&&(!a.tools||a.tools.length===0)),{message:"'tools' must be provided if 'tool_choice' is provided",path:["tools"]});var Se=zod.z.object({apiKey:zod.z.string(),baseUrl:zod.z.string().url(),completeChatUrl:zod.z.string().url().optional(),streamChatUrl:zod.z.string().url().optional()}),V=class{constructor(e,o){this.version="v1";let n=Se.parse(o);this.modelSchema=e,this.apiKey=n.apiKey,this.baseUrl=O(n.baseUrl),this.completeChatUrl=O(n.completeChatUrl||`${this.baseUrl}/messages`),this.streamChatUrl=O(n.streamChatUrl||`${this.baseUrl}/messages`);}getDefaultBaseUrl(){return this.baseUrl}getDefaultHeaders(){return {"x-api-key":`${this.apiKey}`,"anthropic-version":"2023-06-01","content-type":"application/json"}}getDefaultParams(){return {model:this.modelSchema.name}}getRetryDelay(e){let o=0,n=!0;return e["x-should-retry"]&&(n=e["x-should-retry"].toLowerCase()!=="false"),e["retry-after"]&&(o=parseInt(e["retry-after"])*1e3),{shouldRetry:n,delayMs:o}}getTokenCount(e){return e.reduce((o,n)=>o+n.content.map(d=>d.modality==="text"?d.value:"").join(" ").length,0)}transformModelRequest(e){let o=Ut.safeParse(e);if(!o.success)throw new K({info:"Invalid model request",cause:o.error});let n=o.data,d=n.model,l={maxTokens:n.max_tokens,temperature:n.temperature,topP:n.top_p,topK:n.top_k,stop:n.stop_sequences,toolChoice:n.tool_choice},s=H().parse(N(l)),i=[],c={};n.system&&i.push({role:I,content:[{modality:f,value:n.system}]}),n.messages&&n.messages.forEach(g=>{let b=g.role;switch(b){case"user":{let T=g.content;if(typeof T=="string")i.push({role:b,content:[{modality:f,value:T}]});else {let C=T.map(h=>{if(h.type==="text")return {modality:f,value:h.text};if(h.type==="image"){let X="auto",D=h.source.media_type.split("/")[1];return {modality:j,detail:X,value:{type:ee,media_type:D,base64:h.source.data}}}else return {modality:k,id:h.tool_use_id,index:c[h.tool_use_id].index,name:c[h.tool_use_id].name,data:typeof h.content=="string"?h.content:JSON.stringify(h.content)}});i.push({role:b,content:C});}}break;case"assistant":{let T=g.content;if(typeof T=="string")i.push({role:b,content:[{modality:f,value:T}]});else {let C=T.map((h,X)=>{if(h.type==="text")return {modality:f,value:h.text};{let D={modality:R,id:h.id,index:X,name:h.name,arguments:JSON.stringify(h.input)};return c[h.id]=D,D}});i.push({role:b,content:C});}}break}});let u=[];return n.tools&&n.tools.forEach(g=>{u.push({type:"function",definition:{schema:{name:g.name,description:g.description||"",parameters:g.input_schema}}});}),{modelName:d,config:s,messages:i,tools:u}}transformConfig(e,o,n){let d=e.toolChoice;delete e.toolChoice;let l=this.modelSchema.config.schema.safeParse(e);if(!l.success)throw new _({info:`Invalid config for model : '${this.modelSchema.name}'`,cause:l.error});let s=l.data;d!==void 0&&(s.toolChoice=d),Object.keys(s).forEach(c=>{if(!(c in this.modelSchema.config.def))throw new _({info:`Invalid config for model : '${this.modelSchema.name}'`,cause:new Error(`Invalid config key : '${c}',
|
|
7
|
+
available keys : [${Object.keys(this.modelSchema.config.def).join(", ")}]`)})});let i=Object.keys(s).reduce((c,u)=>{let g=this.modelSchema.config.def[u],b=g.param,T=s[u];return b==="max_tokens"&&g.type==="range"&&T===0?c[b]=g.max:c[b]=T,c},{});if("tool_choice"in i&&i.tool_choice!==void 0){let c=i.tool_choice;if(!n||n&&n.length===0)throw new _({info:`Invalid config for model : '${this.modelSchema.name}'`,cause:new Error("'tools' are required when 'toolChoice' is specified")});if(n&&n.length>0){let u=this.modelSchema.config.def.toolChoice;if(!u.choices.includes(c))if(n.map(g=>g.definition.schema.name).includes(c))i.tool_choice={type:"tool",name:c};else throw new _({info:`Invalid config for model : '${this.modelSchema.name}'`,cause:new Error(`toolChoice : '${c}' is not part of provided 'tools' names or
|
|
8
|
+
one of [${u.choices.join(", ")}]`)})}}return i}transformMessages(e){if(!e||e&&e.length===0)return {messages:[]};let o=e.map(l=>{let s=ne().safeParse(l);if(!s.success)throw new S({info:"Invalid messages",cause:s.error});return s.data});o.forEach(l=>{l.content.forEach(s=>{if(!this.modelSchema.modalities.includes(s.modality))throw new S({info:`Invalid message content for model : '${this.modelSchema.name}'`,cause:new Error(`model : '${this.modelSchema.name}' does not support modality : '${s.modality}',
|
|
9
|
+
available modalities : [${this.modelSchema.modalities.join(", ")}]`)})});});let n="",d=[];return o.forEach(l=>{switch(l.role){case I:l.content.forEach(s=>{if(s.modality===f)n+=s.value;else throw new S({info:`Invalid message 'role' and 'modality' combination for model : ${this.modelSchema.name}`,cause:new Error(`role : '${l.role}' cannot have content with modality : '${s.modality}'`)})});break;case M:{let s=[];l.content.forEach(i=>{if(i.modality===f)s.push({type:"text",text:i.value});else if(i.modality===R)s.push({type:"tool_use",id:i.id,name:i.name,input:JSON.parse(i.arguments)});else throw new S({info:`Invalid message 'role' and 'modality' combination for model : ${this.modelSchema.name}`,cause:new Error(`role : '${l.role}' cannot have content with modality : '${i.modality}'`)})}),d.push({role:this.modelSchema.roles[l.role],content:s});}break;case L:{let s=[];l.content.forEach(i=>{if(i.modality===f)s.push({type:"text",text:i.value});else if(i.modality===j){if(i.value.type==="base64")s.push({type:"image",source:{type:"base64",media_type:`image/${i.value.media_type}`,data:i.value.base64}});else if(i.value.type==="url")throw new S({info:`Invalid message 'modality' for model : ${this.modelSchema.name}`,cause:new Error(`model: '${this.modelSchema.name}' does not support image content type: '${i.value.type}'`)})}else if(i.modality===k)s.push({type:"tool_result",tool_use_id:i.id,content:i.data});else throw new S({info:`Invalid message 'role' and 'modality' combination for model : ${this.modelSchema.name}`,cause:new Error(`role : '${l.role}' cannot have content with modality : '${i.modality}'`)})}),d.push({role:this.modelSchema.roles[l.role],content:s});}break;default:throw new S({info:`Invalid message 'role' for model : ${this.modelSchema.name}`,cause:new Error(`role : '${l.role}' is not supported,
|
|
10
|
+
available roles : [${Object.keys(this.modelSchema.roles).join(", ")}]`)})}}),{system:n,messages:d}}transformTools(e){if(!this.modelSchema.modalities.includes(R))throw new me({info:`Invalid tool 'modality' for model : ${this.modelSchema.name}`,cause:new Error(`model : '${this.modelSchema.name}' does not support tool modality : '${R}'`)});return !e||e&&e.length===0?{tools:[]}:{tools:e.map(d=>{let l=He().safeParse(d);if(!l.success)throw new me({info:"Invalid tools",cause:l.error});return l.data}).map(d=>({name:d.definition.schema.name,description:d.definition.schema.description,function:d.definition.schema}))}}getCompleteChatUrl(e,o,n){return E(this,null,function*(){return new Promise(d=>{d(this.completeChatUrl);})})}getCompleteChatHeaders(e,o,n){return E(this,null,function*(){let d=this.getDefaultHeaders();return n&&n.length>0&&(d=U(y({},d),{"anthropic-beta":"tools-2024-05-16"})),new Promise(l=>{l(d);})})}getCompleteChatData(e,o,n){return E(this,null,function*(){let d=this.transformConfig(e,o,n),l=this.transformMessages(o);if(l.messages&&l.messages.length===0)throw new S({info:"Messages are required",cause:new Error("Messages are required")});let s=n?this.transformTools(n):{};return new Promise(i=>{i(y(y(y(y({},this.getDefaultParams()),d),l),s));})})}transformCompleteChatResponse(e){let o=jt.safeParse(e);if(o.success){let n=o.data,l=n.content.map((c,u)=>{if(c.type==="text")return ze(c.text);if(c.type==="tool_use")return De(u,c.id,c.name,JSON.stringify(c.input))}),s=[{role:M,content:l}],i={promptTokens:n.usage.input_tokens,completionTokens:n.usage.output_tokens,totalTokens:n.usage.input_tokens+n.usage.output_tokens};return {messages:s,usage:i,logProbs:[]}}throw new x({info:"Invalid response from model",cause:o.error})}getStreamChatUrl(e,o,n){return E(this,null,function*(){return new Promise(d=>{d(this.streamChatUrl);})})}getStreamChatHeaders(e,o,n){let d=this.getDefaultHeaders();return n&&n.length>0&&(d=U(y({},d),{"anthropic-beta":"tools-2024-05-16"})),new Promise(l=>{l(d);})}getStreamChatData(e,o,n){return E(this,null,function*(){let d=this.transformConfig(e,o,n),l=this.transformMessages(o);if(l.messages&&l.messages.length===0)throw new S({info:"Messages are required",cause:new Error("Messages are required")});let s=n?this.transformTools(n):{};return new Promise(i=>{i(y(y(y(y({stream:!0},this.getDefaultParams()),d),l),s));})})}transformStreamChatResponseChunk(e,o){return _e(this,null,function*(){let n=(o+e).split(`
|
|
11
|
+
`).filter(d=>d.trim()!=="");for(let d of n)if(d.startsWith("data: {")&&d.endsWith("}")){let l;try{l=JSON.parse(d.substring(6));}catch(s){throw new x({info:"Malformed JSON received in stream",cause:new Error(`Malformed JSON received in stream : ${l}`)})}if("type"in l){if(l.type==="message_stop")return;if(l.type==="message_start"){let s=kt.safeParse(l);if(s.success){let i=s.data;yield {partialResponse:{partialMessages:[],usage:{promptTokens:i.message.usage.input_tokens,completionTokens:i.message.usage.output_tokens,totalTokens:i.message.usage.input_tokens+i.message.usage.output_tokens}},buffer:o};}else throw new x({info:"Invalid response from model",cause:s.error})}else if(l.type==="message_delta"){let s=Pt.safeParse(l);if(s.success){let i=s.data;yield {partialResponse:{partialMessages:[],usage:{promptTokens:0,completionTokens:i.usage.output_tokens,totalTokens:i.usage.output_tokens}},buffer:o};}else throw new x({info:"Invalid response from model",cause:s.error})}else if(l.type==="content_block_start"){let s=_t.safeParse(l);if(s.success){let i=s.data,c=[];i.content_block.type==="text"?c.push(se(M,i.content_block.text)):i.content_block.type==="tool_use"&&c.push(ie(M,i.index,i.content_block.id,i.content_block.name,"")),yield {partialResponse:{partialMessages:c},buffer:o};}else throw new x({info:"Invalid response from model",cause:s.error})}else if(l.type==="content_block_delta"){let s=qt.safeParse(l);if(s.success){let i=s.data,c=[];i.delta.type==="text_delta"?c.push(se(M,i.delta.text)):i.delta.type==="input_json_delta"&&c.push(ie(M,i.index,"","",i.delta.partial_json)),yield {partialResponse:{partialMessages:c},buffer:o};}else throw new x({info:"Invalid response from model",cause:s.error})}}else throw new x({info:"Invalid JSON received in stream",cause:new Error(`Invalid JSON received in stream, expected 'type' property,
|
|
12
|
+
received : ${JSON.stringify(l)}`)})}})}};var ln="claude-3-haiku-20240307",dn="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.",Ae=Tt(xt,wt).parse({name:ln,description:dn,maxInputTokens:128e3,maxOutputTokens:128e3,roles:St,modalities:At,config:{def:Re.base(128e3,4).def,schema:Re.base(128e3,4).schema}}),Lt=Se,G=class extends V{constructor(e){super(Ae,e);}};var Bt=[P],$t=zod.z.enum([P]);var Ft=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()})});var pn=zod.z.string().min(1).or(zod.z.array(zod.z.string().min(1)).min(1)),zt=zod.z.object({model:zod.z.string().min(1).optional(),input:pn.optional(),encoding_format:zod.z.enum(["base64"]).nullable().optional(),input_type:zod.z.enum(["query","document"]).nullable().optional(),truncation:zod.z.boolean().optional()});var we=zod.z.object({apiKey:zod.z.string(),baseUrl:zod.z.string().url(),getEmbeddingsUrl:zod.z.string().url().optional()}),Z=class{constructor(e,o){this.version="v1";let n=we.parse(o);this.modelSchema=e,this.apiKey=n.apiKey,this.baseUrl=O(n.baseUrl),this.getEmbeddingsUrl=O(n.getEmbeddingsUrl||`${this.baseUrl}/embeddings`);}getDefaultBaseUrl(){return this.baseUrl}getDefaultHeaders(){return {Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"}}getDefaultParams(){return {model:this.modelSchema.name}}getTokenCount(e){return e.requests.reduce((o,n)=>o+n.length,0)}getRetryDelay(e){return {shouldRetry:!0,delayMs:0}}transformModelRequest(e){let o=zt.safeParse(e);if(!o.success)throw new K({info:"Invalid model request",cause:o.error});let n=o.data,d=n.model,l={encodingFormat:n.encoding_format,inputType:n.input_type,truncation:n.truncation},s=H().parse(N(l)),i;return n.input&&(typeof n.input=="string"?i={modality:P,requests:[n.input]}:i={modality:P,requests:n.input}),{modelName:d,config:s,embeddingRequests:i}}transformConfig(e,o){let n=this.modelSchema.config.schema.safeParse(e);if(!n.success)throw new _({info:`Invalid config for model : '${this.modelSchema.name}'`,cause:n.error});let d=n.data;return Object.keys(d).forEach(s=>{if(!this.modelSchema.config.def[s])throw new _({info:`Invalid config for model : '${this.modelSchema.name}'`,cause:new Error(`Invalid config key : '${s}',
|
|
13
|
+
available keys : [${Object.keys(this.modelSchema.config.def).join(", ")}]`)})}),Object.keys(d).reduce((s,i)=>{let u=this.modelSchema.config.def[i].param,g=d[i];return s[u]=g,s},{})}transformEmbeddingRequests(e){let o=Ve().safeParse(e);if(!o.success)throw new mt({info:"Invalid embedding requests",cause:o.error});return {input:o.data.requests}}getGetEmbeddingsUrl(e,o){return E(this,null,function*(){return new Promise(n=>{n(this.getEmbeddingsUrl);})})}getGetEmbeddingsHeaders(e,o){return E(this,null,function*(){return new Promise(n=>{n(this.getDefaultHeaders());})})}getGetEmbeddingsData(e,o){return E(this,null,function*(){return new Promise(n=>{n(y(y(y({},this.getDefaultParams()),this.transformConfig(e,o)),this.transformEmbeddingRequests(o)));})})}transformGetEmbeddingsResponse(e){let o,n=Ft.safeParse(e);if(n.success){let d=n.data;o=typeof d.data[0].embedding=="string"?le:re;let l=d.data.map(s=>typeof s.embedding=="string"?{index:s.index,embedding:s.embedding}:{index:s.index,embedding:s.embedding});return {encodingFormat:o,embeddings:l,usage:{totalTokens:d.usage.total_tokens}}}throw new x({info:"Invalid response from model",cause:n.error})}};var cn="voyage-2",un="some description",je=Ct($t).parse({name:cn,description:un,modalities:Bt,maxInputTokens:8192,maxOutputTokens:8192,config:{def:Ee.base().def,schema:Ee.base().schema}}),Dt=we,W=class extends Z{constructor(e){super(je,e);}};var gn="anthropic",Ht=class{constructor(){this.version="v1";this.name=gn;this.chatBaseUrl="https://api.anthropic.com/v1";this.embeddingBaseUrl="https://api.anthropic.com/v1";this.chatModelFactories={"claude-3-haiku-20240307":{model:G,modelOptions:Lt,modelSchema:Ae}};this.embeddingModelFactories={"voyage-2":{model:W,modelOptions:Dt,modelSchema:je}};}chatModelLiterals(){return Object.keys(this.chatModelFactories)}chatModel(e,o){var s;if(!(e in this.chatModelFactories))throw new $({info:`Anthropic chat model: ${e} not found`,cause:new Error(`Anthropic chat model: ${e} not found, available chat models:
|
|
14
|
+
${this.chatModelLiterals().join(", ")}`)});let n=this.chatModelFactories[e].model,d=U(y({},o),{baseUrl:(s=o.baseUrl)!=null?s:this.chatBaseUrl}),l=this.chatModelFactories[e].modelOptions.parse(d);return new n(l)}chatModelSchema(e){if(!(e in this.chatModelFactories))throw new $({info:`Anthropic chat model: ${e} not found`,cause:new Error(`Anthropic chat model: ${e} not found, available chat models:
|
|
15
|
+
${this.chatModelLiterals().join(", ")}`)});return this.chatModelFactories[e].modelSchema}chatModelSchemas(){return Object.keys(this.chatModelFactories).reduce((e,o)=>(e[o]=this.chatModelFactories[o].modelSchema,e),{})}embeddingModelLiterals(){return Object.keys(this.embeddingModelFactories)}embeddingModel(e,o){var s;if(!(e in this.embeddingModelFactories))throw new $({info:`Anthropic embedding model: ${e} not found`,cause:new Error(`Anthropic embedding model: ${e} not found, available embedding models:
|
|
16
|
+
${this.embeddingModelLiterals().join(", ")}`)});let n=this.embeddingModelFactories[e].model,d=U(y({},o),{baseUrl:(s=o.baseUrl)!=null?s:this.embeddingBaseUrl}),l=this.embeddingModelFactories[e].modelOptions.parse(d);return new n(l)}embeddingModelSchema(e){if(!(e in this.embeddingModelFactories))throw new $({info:`Anthropic embedding model: ${e} not found`,cause:new Error(`Anthropic embedding model: ${e} not found, available embedding models:
|
|
17
|
+
${this.embeddingModelLiterals().join(", ")}`)});return this.embeddingModelFactories[e].modelSchema}embeddingModelSchemas(){return Object.keys(this.embeddingModelFactories).reduce((e,o)=>(e[o]=this.embeddingModelFactories[o].modelSchema,e),{})}};
|
|
18
|
+
|
|
19
|
+
exports.Anthropic = Ht;
|
|
20
|
+
exports.AnthropicChatModelModalities = At;
|
|
21
|
+
exports.AnthropicChatModelModalitiesEnum = wt;
|
|
22
|
+
exports.AnthropicChatModelRoles = xt;
|
|
23
|
+
exports.AnthropicChatModelRolesMap = St;
|
|
24
|
+
exports.AnthropicCompleteChatResponse = jt;
|
|
25
|
+
exports.AnthropicEmbeddingModelModalities = Bt;
|
|
26
|
+
exports.AnthropicEmbeddingModelModalitiesEnum = $t;
|
|
27
|
+
exports.AnthropicEmbeddingRequest = zt;
|
|
28
|
+
exports.AnthropicEmbeddingRequestInput = pn;
|
|
29
|
+
exports.AnthropicGetEmbeddingsResponse = Ft;
|
|
30
|
+
exports.AnthropicStreamChatContentBlockDeltaResponse = qt;
|
|
31
|
+
exports.AnthropicStreamChatContentBlockStartResponse = _t;
|
|
32
|
+
exports.AnthropicStreamChatMessageDeltaResponse = Pt;
|
|
33
|
+
exports.AnthropicStreamChatMessageStartResponse = kt;
|
|
34
|
+
exports.BaseChatModel = V;
|
|
35
|
+
exports.BaseChatModelOptions = Se;
|
|
36
|
+
exports.BaseEmbeddingModel = Z;
|
|
37
|
+
exports.BaseEmbeddingModelOptions = we;
|
|
38
|
+
exports.ChatModelAnthropicConfigs = Re;
|
|
39
|
+
exports.ChatModelBaseConfigDef = vt;
|
|
40
|
+
exports.ChatModelBaseConfigSchema = Mt;
|
|
41
|
+
exports.Claude3Haiku20240307 = G;
|
|
42
|
+
exports.Claude3Haiku20240307Options = Lt;
|
|
43
|
+
exports.Claude3Haiku20240307Schema = Ae;
|
|
44
|
+
exports.EmbeddingModelAnthropicConfigs = Ee;
|
|
45
|
+
exports.EmbeddingModelBaseConfigDef = Et;
|
|
46
|
+
exports.EmbeddingModelBaseConfigSchema = Rt;
|
|
47
|
+
exports.ProviderLiteral = gn;
|
|
48
|
+
exports.Voyage2 = W;
|
|
49
|
+
exports.Voyage2Options = Dt;
|
|
50
|
+
exports.Voyage2Schema = je;
|
|
51
|
+
exports.encodingFormat = Ce;
|
|
52
|
+
exports.inputType = Me;
|
|
53
|
+
exports.maxTokens = he;
|
|
54
|
+
exports.stop = ye;
|
|
55
|
+
exports.temperature = ge;
|
|
56
|
+
exports.toolChoice = Te;
|
|
57
|
+
exports.topK = be;
|
|
58
|
+
exports.topP = fe;
|
|
59
|
+
exports.truncation = ve;
|
|
60
|
+
//# sourceMappingURL=index.js.map
|
|
61
|
+
//# sourceMappingURL=index.js.map
|