@adaline/openai 0.2.0 → 0.3.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 +47 -60
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +7 -20
- package/dist/index.mjs.map +1 -1
- package/package.json +5 -5
package/dist/index.js
CHANGED
|
@@ -1,67 +1,54 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
+
var provider = require('@adaline/provider');
|
|
3
4
|
var zod = require('zod');
|
|
5
|
+
var types = require('@adaline/types');
|
|
4
6
|
|
|
5
|
-
var pa=Object.create;var Se=Object.defineProperty,ua=Object.defineProperties,ga=Object.getOwnPropertyDescriptor,fa=Object.getOwnPropertyDescriptors,ha=Object.getOwnPropertyNames,wt=Object.getOwnPropertySymbols,ya=Object.getPrototypeOf,Pt=Object.prototype.hasOwnProperty,ba=Object.prototype.propertyIsEnumerable;var za=(t,e)=>(e=Symbol[t])?e:Symbol.for("Symbol."+t);var It=(t,e,n)=>e in t?Se(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,I=(t,e)=>{for(var n in e||(e={}))Pt.call(e,n)&&It(t,n,e[n]);if(wt)for(var n of wt(e))ba.call(e,n)&&It(t,n,e[n]);return t},Rt=(t,e)=>ua(t,fa(e));var $=(t=>typeof require!="undefined"?require:typeof Proxy!="undefined"?new Proxy(t,{get:(e,n)=>(typeof require!="undefined"?require:e)[n]}):t)(function(t){if(typeof require!="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var Ot=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var Ta=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of ha(e))!Pt.call(t,o)&&o!==n&&Se(t,o,{get:()=>e[o],enumerable:!(i=ga(e,o))||i.enumerable});return t};var _=(t,e,n)=>(n=t!=null?pa(ya(t)):{},Ta(!t||!t.__esModule?Se(n,"default",{value:t,enumerable:!0}):n,t));var Ea=function(t,e){this[0]=t,this[1]=e;},_t=(t,e,n)=>{var i=(s,c,h,v)=>{try{var y=n[s](c),j=(c=y.value)instanceof Ea,N=y.done;Promise.resolve(j?c[0]:c).then(R=>j?i(s==="return"?s:"next",c[1]?{done:R.done,value:R.value}:R,h,v):h({value:R,done:N})).catch(R=>i("throw",R,h,v));}catch(R){v(R);}},o=s=>r[s]=c=>new Promise((h,v)=>i(s,c,h,v)),r={};return n=n.apply(t,e),r[za("asyncIterator")]=()=>r,o("next"),o("throw"),o("return"),r};var G=Ot(p=>{var l=$("zod"),Ca=Object.create,je=Object.defineProperty,Ma=Object.getOwnPropertyDescriptor,va=Object.getOwnPropertyNames,Lt=Object.getOwnPropertySymbols,xa=Object.getPrototypeOf,qt=Object.prototype.hasOwnProperty,Sa=Object.prototype.propertyIsEnumerable,kt=(t,e,n)=>e in t?je(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,ae=(t,e)=>{for(var n in e||(e={}))qt.call(e,n)&&kt(t,n,e[n]);if(Lt)for(var n of Lt(e))Sa.call(e,n)&&kt(t,n,e[n]);return t},ja=(t=>typeof $!="undefined"?$:typeof Proxy!="undefined"?new Proxy(t,{get:(e,n)=>(typeof $!="undefined"?$:e)[n]}):t)(function(t){if(typeof $!="undefined")return $.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')}),wa=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Ia=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of va(e))!qt.call(t,o)&&o!==n&&je(t,o,{get:()=>e[o],enumerable:!(i=Ma(e,o))||i.enumerable});return t},Ft=(t,e,n)=>(n=t!=null?Ca(xa(t)):{},Ia(!t||!t.__esModule?je(n,"default",{value:t,enumerable:!0}):n,t)),$t=wa(t=>{var e=ja("zod"),n="system",i="user",o="assistant",r="tool",s=[n,i,o,r],c=e.z.enum(s),h=[o],v=e.z.enum(h),y="image",j="base64",N=e.z.object({type:e.z.literal(j),base64:e.z.string()}),R="url",rt=e.z.object({type:e.z.literal(R),url:e.z.string()}),Jn=e.z.discriminatedUnion("type",[N,rt]),st=["low","medium","high","auto"],lt=e.z.enum(st),te=(u=e.z.undefined())=>e.z.object({modality:e.z.literal(y),detail:lt,value:Jn,metadata:u}),K="text",be=(u=e.z.undefined())=>e.z.object({modality:e.z.literal(K),value:e.z.string(),metadata:u}),q="partial-text",ze=(u=e.z.undefined())=>e.z.object({modality:e.z.literal(q),value:e.z.string(),metadata:u}),D="tool-call",Te=(u=e.z.undefined())=>e.z.object({modality:e.z.literal(D),index:e.z.number().int().nonnegative(),id:e.z.string().min(1),name:e.z.string().min(1),arguments:e.z.string(),metadata:u}),O="partial-tool-call",Ee=(u=e.z.undefined())=>e.z.object({modality:e.z.literal(O),index:e.z.number().int().nonnegative(),id:e.z.string().optional(),name:e.z.string().optional(),arguments:e.z.string().optional(),metadata:u}),ne="tool-response",Ce=(u=e.z.undefined())=>e.z.object({modality:e.z.literal(ne),index:e.z.number().int().nonnegative(),id:e.z.string().min(1),name:e.z.string().min(1),data:e.z.string(),metadata:u}),mt=[K,y,D,ne],Kn=e.z.enum(mt),dt=(u=e.z.undefined(),b=e.z.undefined(),C=e.z.undefined(),x=e.z.undefined())=>e.z.discriminatedUnion("modality",[be(u),te(b),Te(C),Ce(x)]),ct=[q,O],Vn=e.z.enum(ct),pt=(u=e.z.undefined(),b=e.z.undefined())=>e.z.discriminatedUnion("modality",[ze(u),Ee(b)]),ut="token",Hn=(u=e.z.undefined())=>e.z.object({modality:e.z.literal(ut),value:e.z.array(e.z.number().int().nonnegative()),metadata:u}),V=(u=c,b=e.z.undefined(),C=e.z.undefined(),x=e.z.undefined(),w=e.z.undefined(),M=e.z.undefined())=>e.z.object({role:u,content:e.z.array(dt(b,C,x,w)),metadata:M}),Me=(u=v,b=e.z.undefined(),C=e.z.undefined(),x=e.z.undefined())=>e.z.object({role:u,partialContent:pt(b,C),metadata:x}),Wn=(u,b)=>V().parse({role:u,content:[be().parse({modality:K,value:b})]}),Yn=(u,b,C)=>V().parse({role:u,content:[te().parse({modality:y,detail:C,value:{type:R,url:b}})]}),Zn=(u,b,C)=>V().parse({role:u,content:[te().parse({modality:y,detail:C,value:{type:j,base64:b}})]}),Qn=(u,b,C,x,w)=>V().parse({role:u,content:[Te().parse({modality:D,index:b,id:C,name:x,arguments:w})]}),Xn=(u,b,C,x,w)=>V().parse({role:u,content:[Ce().parse({modality:ne,index:b,id:C,name:x,data:w})]}),ea=(u,b)=>Me().parse({role:u,partialContent:ze().parse({modality:q,value:b})}),ta=(u,b,C,x,w)=>Me().parse({role:u,partialContent:Ee().parse({modality:O,index:b,id:C,name:x,arguments:w})}),na=(u,b)=>{if(b.length===0)return u;let C=u,x=b[0].partialContent.modality,w={modality:q,value:""},M={modality:O,index:0,id:"",name:"",arguments:""};if(b.forEach(E=>{if(E.partialContent.modality===x){if(E.partialContent.modality===q)w.value+=E.partialContent.value;else if(E.partialContent.modality===O)if(M.index==E.partialContent.index)M.id+=E.partialContent.id||"",M.name+=E.partialContent.name||"",M.arguments+=E.partialContent.arguments||"";else {let X={modality:D,index:M.index,id:M.id,name:M.name,arguments:M.arguments};C.push({role:o,content:[X]}),M={modality:O,index:E.partialContent.index,id:E.partialContent.id||"",name:E.partialContent.name||"",arguments:E.partialContent.arguments||""};}}else {if(x===q){let X={modality:K,value:w.value};C.push({role:o,content:[X]}),w={modality:q,value:""};}else if(x===O){let X={modality:D,index:M.index,id:M.id,name:M.name,arguments:M.arguments};C.push({role:o,content:[X]}),M={modality:O,index:0,id:"",name:"",arguments:""};}x=E.partialContent.modality,E.partialContent.modality===q?w.value+=E.partialContent.value:E.partialContent.modality===O&&(M={modality:O,index:E.partialContent.index,id:E.partialContent.id||"",name:E.partialContent.name||"",arguments:E.partialContent.arguments||""});}}),x===q){let E={modality:K,value:w.value};C.push({role:o,content:[E]});}else if(x===O){let E={modality:D,index:M.index,id:M.id,name:M.name,arguments:M.arguments};C.push({role:o,content:[E]});}return C},aa=(u=e.z.record(e.z.string(),e.z.any()).optional())=>u,gt="function",oa=["object","array","number","string","boolean","null"],ft=e.z.enum(["object","array","number","string","boolean","null"]),ht=e.z.object({anyOf:e.z.array(e.z.any()).optional(),type:ft.optional(),default:e.z.any().optional(),title:e.z.string().optional(),description:e.z.string().max(4096).optional(),properties:e.z.record(e.z.any()).optional(),required:e.z.array(e.z.string()).optional(),minItems:e.z.number().int().min(0).optional(),maxItems:e.z.number().int().optional(),items:e.z.record(e.z.any()).optional(),enum:e.z.array(e.z.union([e.z.string(),e.z.number(),e.z.boolean(),e.z.null()])).optional(),minimum:e.z.number().optional(),maximum:e.z.number().optional(),minLength:e.z.number().int().min(0).optional(),maxLength:e.z.number().int().optional()}),ia=e.z.object({type:e.z.enum(["object"]),title:e.z.string().optional(),$defs:e.z.record(e.z.any()).optional(),properties:e.z.record(ht).optional(),required:e.z.array(e.z.string()).optional()}),yt=e.z.object({name:e.z.string().regex(/^[a-zA-Z0-9_]{1,64}$/).max(64),description:e.z.string().max(4096),parameters:e.z.any(),strict:e.z.boolean().optional()}),ra=["function"],bt=e.z.enum(["function"]),zt=e.z.object({type:bt,definition:e.z.object({schema:yt})}),Tt=[gt],sa=e.z.enum(Tt),la=(u=e.z.undefined())=>e.z.discriminatedUnion("type",[zt.extend({metadata:u})]),Et="float",Ct=e.z.object({index:e.z.number().int().nonnegative(),embedding:e.z.array(e.z.number())}),Mt="base64",vt=e.z.object({index:e.z.number().int().nonnegative(),embedding:e.z.string().base64()}),ma=e.z.discriminatedUnion("encodingFormat",[e.z.object({encodingFormat:e.z.literal(Et),embeddings:e.z.array(Ct)}),e.z.object({encodingFormat:e.z.literal(Mt),embeddings:e.z.array(vt)})]),ve="text",xe="token",xt=[ve,xe],da=e.z.enum(xt),St=e.z.array(e.z.string().min(1)),jt=e.z.array(e.z.array(e.z.number().int().nonnegative())),ca=(u=e.z.undefined())=>e.z.discriminatedUnion("modality",[e.z.object({modality:e.z.literal(ve),metadata:u,requests:St}),e.z.object({modality:e.z.literal(xe),metadata:u,requests:jt})]);t.AssistantRoleLiteral=o,t.Base64Embedding=vt,t.Base64EmbeddingLiteral=Mt,t.Base64ImageContentTypeLiteral=j,t.Base64ImageContentValue=N,t.Config=aa,t.Content=dt,t.EmbeddingModalityEnum=da,t.EmbeddingModalityLiterals=xt,t.EmbeddingRequests=ca,t.EmbeddingTextModalityLiteral=ve,t.EmbeddingTokenModalityLiteral=xe,t.Embeddings=ma,t.FloatEmbedding=Ct,t.FloatEmbeddingLiteral=Et,t.Function=yt,t.FunctionParameter=ht,t.FunctionParameterTypes=oa,t.FunctionParameterTypesLiteral=ft,t.FunctionParameters=ia,t.FunctionTool=zt,t.FunctionToolLiteral=gt,t.ImageContent=te,t.ImageContentDetails=st,t.ImageContentDetailsLiteral=lt,t.ImageModalityLiteral=y,t.Message=V,t.ModalityEnum=Kn,t.ModalityLiterals=mt,t.PartialContent=pt,t.PartialMessage=Me,t.PartialModalityEnum=Vn,t.PartialModalityLiterals=ct,t.PartialRoleEnum=v,t.PartialRoleLiterals=h,t.PartialTextContent=ze,t.PartialTextModalityLiteral=q,t.PartialToolCallContent=Ee,t.PartialToolCallModalityLiteral=O,t.RoleEnum=c,t.RoleLiterals=s,t.SystemRoleLiteral=n,t.TextContent=be,t.TextEmbeddingRequests=St,t.TextModalityLiteral=K,t.TokenContent=Hn,t.TokenEmbeddingRequests=jt,t.TokenModalityLiteral=ut,t.Tool=la,t.ToolCallContent=Te,t.ToolCallModalityLiteral=D,t.ToolEnum=sa,t.ToolLiterals=Tt,t.ToolResponseContent=Ce,t.ToolResponseModalityLiteral=ne,t.ToolRoleLiteral=r,t.ToolTypes=ra,t.ToolTypesLiteral=bt,t.UrlImageContentTypeLiteral=R,t.UrlImageContentValue=rt,t.UserRoleLiteral=i,t.createBase64ImageMessage=Zn,t.createPartialTextMessage=ea,t.createPartialToolCallMessage=ta,t.createTextMessage=Wn,t.createToolCallMessage=Qn,t.createToolResponseMessage=Xn,t.createUrlImageMessage=Yn,t.mergePartialMessages=na;}),Pa={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."},Ra={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."},Oa=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.`}),_a={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."},La={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."},ka={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."},Aa={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."},qa={TEMPERATURE:Pa,MAX_TOKENS:Ra,STOP:Oa,TOP_P:_a,TOP_K:La,FREQUENCY_PENALTY:ka,PRESENCE_PENALTY:Aa},S=t=>t==null?"unknown error":typeof t=="string"?t:t instanceof Error?t.message:JSON.stringify(t),Fa=t=>Object.fromEntries(Object.entries(t).filter(([e,n])=>n!=null)),$a=t=>{let e=t.replace(/-/g,"+").replace(/_/g,"/"),n=globalThis.atob(e);return Uint8Array.from(n,i=>i.codePointAt(0))},Ua=t=>{let e="";for(let n=0;n<t.length;n++)e+=String.fromCodePoint(t[n]);return globalThis.btoa(e)},Ga=t=>t==null?void 0:t.replace(/\/$/,""),Ba=class extends Error{constructor({info:t,error:e}){super(`[Gateway_ApiRequestError]: ${t}.
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
Message: ${S(e)}`),this.name="Gateway_DownloadError",this.cause=e,this.info=t;}static isDownloadError(t){return t instanceof Error&&t.name===this.name&&typeof t.info=="string"}toJSON(){return {name:this.name,message:this.message,cause:this.cause,stack:this.stack,info:this.info}}},Ja=class extends Error{constructor({info:t,error:e}){super(`[Gateway_InvalidAuthError]: ${t}.
|
|
9
|
-
Message: ${S(e)}`),this.name="Gateway_InvalidAuthError",this.cause=e,this.info=t;}static isInvalidAuthError(t){return t instanceof Error&&t.name===this.name&&typeof t.info=="string"}toJSON(){return {name:this.name,message:this.message,cause:this.cause,stack:this.stack,info:this.info}}},Ka=class extends Error{constructor({info:t,error:e}){super(`[Gateway_InvalidConfigError]: ${t}.
|
|
10
|
-
Message: ${S(e)}`),this.name="Gateway_InvalidConfigError",this.cause=e,this.info=t;}static isInvalidConfigError(t){return t instanceof Error&&t.name===this.name&&typeof t.info=="string"}toJSON(){return {name:this.name,message:this.message,cause:this.cause,stack:this.stack,info:this.info}}},Va=class extends Error{constructor({info:t,error:e}){super(`[Gateway_InvalidEndpointError]: ${t}.
|
|
11
|
-
Message: ${S(e)}`),this.name="Gateway_InvalidEndpointError",this.cause=e,this.info=t;}static isInvalidEndpointError(t){return t instanceof Error&&t.name===this.name&&typeof t.info=="string"}toJSON(){return {name:this.name,message:this.message,cause:this.cause,stack:this.stack,info:this.info}}},Ha=class extends Error{constructor({info:t,error:e}){super(`[Gateway_InvalidMessagesError]: ${t}.
|
|
12
|
-
Message: ${S(e)}`),this.name="Gateway_InvalidMessagesError",this.cause=e,this.info=t;}static isInvalidMessagesError(t){return t instanceof Error&&t.name===this.name&&typeof t.info=="string"}toJSON(){return {name:this.name,message:this.message,cause:this.cause,stack:this.stack,info:this.info}}},Wa=class extends Error{constructor({info:t,error:e}){super(`[Gateway_InvalidModalityError]: ${t}.
|
|
13
|
-
Message: ${S(e)}`),this.name="Gateway_InvalidModalityError",this.cause=e,this.info=t;}static isInvalidModalityError(t){return t instanceof Error&&t.name===this.name&&typeof t.info=="string"}toJSON(){return {name:this.name,message:this.message,cause:this.cause,stack:this.stack,info:this.info}}},Ya=class extends Error{constructor({info:t,error:e}){super(`[Gateway_InvalidModelError]: ${t}.
|
|
14
|
-
Message: ${S(e)}`),this.name="Gateway_InvalidModelError",this.cause=e,this.info=t;}static isInvalidModelError(t){return t instanceof Error&&t.name===this.name&&typeof t.info=="string"}toJSON(){return {name:this.name,message:this.message,cause:this.cause,stack:this.stack,info:this.info}}},Za=class extends Error{constructor({info:t,error:e}){super(`[Gateway_InvalidPromptError]: ${t}.
|
|
15
|
-
Message: ${S(e)}`),this.name="Gateway_InvalidPromptError",this.cause=e,this.info=t;}static isInvalidPromptError(t){return t instanceof Error&&t.name===this.name&&typeof t.info=="string"}toJSON(){return {name:this.name,message:this.message,cause:this.cause,stack:this.stack,info:this.info}}},Qa=class extends Error{constructor({info:t,error:e}){super(`[Gateway_InvalidRoleError]: ${t}.
|
|
16
|
-
Message: ${S(e)}`),this.name="Gateway_InvalidRoleError",this.cause=e,this.info=t;}static isInvalidRoleError(t){return t instanceof Error&&t.name===this.name&&typeof t.info=="string"}toJSON(){return {name:this.name,message:this.message,cause:this.cause,stack:this.stack,info:this.info}}},Xa=class extends Error{constructor({info:t,error:e}){super(`[Gateway_InvalidToolsError]: ${t}.
|
|
17
|
-
Message: ${S(e)}`),this.name="Gateway_InvalidToolsError",this.cause=e,this.info=t;}static isInvalidToolsError(t){return t instanceof Error&&t.name===this.name&&typeof t.info=="string"}toJSON(){return {name:this.name,message:this.message,cause:this.cause,stack:this.stack,info:this.info}}},eo=class extends Error{constructor({info:t,error:e}){super(`[Gateway_InvalidEmbeddingRequestsError]: ${t}.
|
|
18
|
-
Message: ${S(e)}`),this.name="Gateway_InvalidEmbeddingRequestsError",this.info=t,this.cause=e;}static isInvalidEmbeddingRequestsError(t){return t instanceof Error&&t.name===this.name&&typeof t.info=="string"}toJSON(){return {name:this.name,message:this.message,cause:this.cause,info:this.info,stack:this.stack}}},to=class extends Error{constructor({info:t,error:e}){super(`[Gateway_JsonParseError]: ${t}.
|
|
19
|
-
Message: ${S(e)}`),this.name="Gateway_JsonParseError",this.cause=e,this.info=t;}static isJsonParseError(t){return t instanceof Error&&t.name===this.name&&typeof t.info=="string"}toJSON(){return {name:this.name,message:this.message,cause:this.cause,stack:this.stack,info:this.info}}},no=class extends Error{constructor({info:t,error:e}){super(`[Gateway_ValidationError]: ${t}.
|
|
20
|
-
Message: ${S(e)}`),this.name="Gateway_ValidationError",this.cause=e,this.info=t;}static isValidationError(t){return t instanceof Error&&t.name===this.name&&typeof t.info=="string"}toJSON(){return {name:this.name,message:this.message,cause:this.cause,stack:this.stack,info:this.info}}},At=Ft($t()),oe="multi-string",we=l.z.object({type:l.z.literal(oe),param:l.z.string().min(1),title:l.z.string().min(1),description:l.z.string().min(1).max(500),max:l.z.number().int().positive()}),Ut=t=>l.z.array(l.z.string()).max(t).default([]).optional(),ao=t=>({def:we.parse(ae({type:oe},t)),schema:Ut(t.max)}),ie="range",Ie=l.z.object({type:l.z.literal(ie),param:l.z.string().min(1),title:l.z.string().min(1),description:l.z.string().min(1).max(500),min:l.z.number().int(),max:l.z.number().int(),step:l.z.number().positive(),default:l.z.number().int()}),Gt=(t,e,n,i)=>l.z.number().min(t).max(e).step(n).default(i).optional(),oo=t=>({def:Ie.parse(ae({type:ie},t)),schema:Gt(t.min,t.max,t.step,t.default)}),re="select-string",Pe=l.z.object({type:l.z.literal(re),param:l.z.string().min(1),title:l.z.string().min(1),description:l.z.string().min(1).max(500),default:l.z.string().min(1),choices:l.z.array(l.z.string().min(1))}),Bt=(t,e)=>l.z.enum(e).default(t).optional(),io=t=>({def:Pe.parse(ae({type:re},t)),schema:Bt(t.default,t.choices)}),se="object-schema",Re=l.z.object({type:l.z.literal(se),param:l.z.string().min(1),title:l.z.string().min(1),description:l.z.string().min(1).max(500),objectSchema:l.z.any()}),Nt=t=>t,ro=t=>({def:Re.parse(ae({type:se},t)),schema:Nt(t.objectSchema)}),Dt=[ie,oe,re,se],so=l.z.enum(Dt),Oe=l.z.discriminatedUnion("type",[Ie,we,Pe,Re]),lo=(t=At.RoleEnum,e=At.ModalityEnum)=>l.z.object({name:l.z.string().min(1),description:l.z.string().min(1),roles:l.z.record(t,l.z.string().min(1).optional()),modalities:l.z.array(e).nonempty(),maxInputTokens:l.z.number().int().positive().min(1),maxOutputTokens:l.z.number().int().positive().min(1),config:l.z.object({def:l.z.record(l.z.string().min(1),Oe),schema:l.z.instanceof(l.z.ZodObject)}).refine(n=>{var i,o;let r=Object.keys(n.def),s=Object.keys((o=(i=n.schema)==null?void 0:i.shape)!=null?o:{});return r.every(c=>s.includes(c))&&s.every(c=>r.includes(c))},{message:"Keys in 'config.def' must exactly match keys in 'config.schema'"})}),mo=Ft($t()),co=(t=mo.EmbeddingModalityEnum)=>l.z.object({name:l.z.string().min(1),description:l.z.string().min(1),modalities:l.z.array(t).nonempty(),maxInputTokens:l.z.number().int().positive().min(1),maxOutputTokens:l.z.number().int().positive().min(1),config:l.z.object({def:l.z.record(l.z.string().min(1),Oe),schema:l.z.instanceof(l.z.ZodObject)}).refine(e=>{var n,i;let o=Object.keys(e.def),r=Object.keys((i=(n=e.schema)==null?void 0:n.shape)!=null?i:{});return o.every(s=>r.includes(s))&&r.every(s=>o.includes(s))},{message:"Keys in 'config.def' must exactly match keys in 'config.schema'"})}),po=l.z.record(l.z.string().optional()),uo=l.z.record(l.z.union([l.z.boolean(),l.z.string(),l.z.number(),l.z.object({}),l.z.array(l.z.any()),l.z.null(),l.z.undefined()])),go=l.z.string().url();p.ApiRequestError=Ba;p.ApiResponseError=Na;p.CONFIG=qa;p.ChatModelSchema=lo;p.ConfigItemDef=Oe;p.ConfigItemEnum=so;p.ConfigItemLiterals=Dt;p.DownloadError=Da;p.EmbeddingModelSchema=co;p.Headers=po;p.InvalidAuthError=Ja;p.InvalidConfigError=Ka;p.InvalidEmbeddingRequestsError=eo;p.InvalidEndpointError=Va;p.InvalidMessagesError=Ha;p.InvalidModalityError=Wa;p.InvalidModelError=Ya;p.InvalidPromptError=Za;p.InvalidRoleError=Qa;p.InvalidToolsError=Xa;p.JsonParseError=to;p.MultiStringConfigItem=ao;p.MultiStringConfigItemDef=we;p.MultiStringConfigItemSchema=Ut;p.MultiStringConfigItemTypeLiteral=oe;p.ObjectSchemaConfigItem=ro;p.ObjectSchemaConfigItemDef=Re;p.ObjectSchemaConfigItemSchema=Nt;p.ObjectSchemaConfigItemTypeLiteral=se;p.Params=uo;p.RangeConfigItem=oo;p.RangeConfigItemDef=Ie;p.RangeConfigItemSchema=Gt;p.RangeConfigItemTypeLiteral=ie;p.SelectStringConfigItem=io;p.SelectStringConfigItemDef=Pe;p.SelectStringConfigItemSchema=Bt;p.SelectStringConfigItemTypeLiteral=re;p.Url=go;p.ValidationError=no;p.convertBase64ToUint8Array=$a;p.convertUint8ArrayToBase64=Ua;p.getErrorMessage=S;p.removeUndefinedEntries=Fa;p.urlWithoutTrailingSlash=Ga;});var Y=Ot(m=>{var a=$("zod"),Qt="system",Xt="user",B="assistant",en="tool",tn=[Qt,Xt,B,en],nn=a.z.enum(tn),an=[B],on=a.z.enum(an),ee="image",Ke="base64",rn=a.z.object({type:a.z.literal(Ke),base64:a.z.string()}),Ve="url",sn=a.z.object({type:a.z.literal(Ve),url:a.z.string()}),Eo=a.z.discriminatedUnion("type",[rn,sn]),ln=["low","medium","high","auto"],mn=a.z.enum(ln),pe=(t=a.z.undefined())=>a.z.object({modality:a.z.literal(ee),detail:mn,value:Eo,metadata:t}),H="text",He=(t=a.z.undefined())=>a.z.object({modality:a.z.literal(H),value:a.z.string(),metadata:t}),F="partial-text",We=(t=a.z.undefined())=>a.z.object({modality:a.z.literal(F),value:a.z.string(),metadata:t}),J="tool-call",Ye=(t=a.z.undefined())=>a.z.object({modality:a.z.literal(J),index:a.z.number().int().nonnegative(),id:a.z.string().min(1),name:a.z.string().min(1),arguments:a.z.string(),metadata:t}),L="partial-tool-call",Ze=(t=a.z.undefined())=>a.z.object({modality:a.z.literal(L),index:a.z.number().int().nonnegative(),id:a.z.string().optional(),name:a.z.string().optional(),arguments:a.z.string().optional(),metadata:t}),ue="tool-response",Qe=(t=a.z.undefined())=>a.z.object({modality:a.z.literal(ue),index:a.z.number().int().nonnegative(),id:a.z.string().min(1),name:a.z.string().min(1),data:a.z.string(),metadata:t}),dn=[H,ee,J,ue],Co=a.z.enum(dn),cn=(t=a.z.undefined(),e=a.z.undefined(),n=a.z.undefined(),i=a.z.undefined())=>a.z.discriminatedUnion("modality",[He(t),pe(e),Ye(n),Qe(i)]),pn=[F,L],Mo=a.z.enum(pn),un=(t=a.z.undefined(),e=a.z.undefined())=>a.z.discriminatedUnion("modality",[We(t),Ze(e)]),gn="token",vo=(t=a.z.undefined())=>a.z.object({modality:a.z.literal(gn),value:a.z.array(a.z.number().int().nonnegative()),metadata:t}),W=(t=nn,e=a.z.undefined(),n=a.z.undefined(),i=a.z.undefined(),o=a.z.undefined(),r=a.z.undefined())=>a.z.object({role:t,content:a.z.array(cn(e,n,i,o)),metadata:r}),Xe=(t=on,e=a.z.undefined(),n=a.z.undefined(),i=a.z.undefined())=>a.z.object({role:t,partialContent:un(e,n),metadata:i}),xo=(t,e)=>W().parse({role:t,content:[He().parse({modality:H,value:e})]}),So=(t,e,n)=>W().parse({role:t,content:[pe().parse({modality:ee,detail:n,value:{type:Ve,url:e}})]}),jo=(t,e,n)=>W().parse({role:t,content:[pe().parse({modality:ee,detail:n,value:{type:Ke,base64:e}})]}),wo=(t,e,n,i,o)=>W().parse({role:t,content:[Ye().parse({modality:J,index:e,id:n,name:i,arguments:o})]}),Io=(t,e,n,i,o)=>W().parse({role:t,content:[Qe().parse({modality:ue,index:e,id:n,name:i,data:o})]}),Po=(t,e)=>Xe().parse({role:t,partialContent:We().parse({modality:F,value:e})}),Ro=(t,e,n,i,o)=>Xe().parse({role:t,partialContent:Ze().parse({modality:L,index:e,id:n,name:i,arguments:o})}),Oo=(t,e)=>{if(e.length===0)return t;let n=t,i=e[0].partialContent.modality,o={modality:F,value:""},r={modality:L,index:0,id:"",name:"",arguments:""};if(e.forEach(s=>{if(s.partialContent.modality===i){if(s.partialContent.modality===F)o.value+=s.partialContent.value;else if(s.partialContent.modality===L)if(r.index==s.partialContent.index)r.id+=s.partialContent.id||"",r.name+=s.partialContent.name||"",r.arguments+=s.partialContent.arguments||"";else {let c={modality:J,index:r.index,id:r.id,name:r.name,arguments:r.arguments};n.push({role:B,content:[c]}),r={modality:L,index:s.partialContent.index,id:s.partialContent.id||"",name:s.partialContent.name||"",arguments:s.partialContent.arguments||""};}}else {if(i===F){let c={modality:H,value:o.value};n.push({role:B,content:[c]}),o={modality:F,value:""};}else if(i===L){let c={modality:J,index:r.index,id:r.id,name:r.name,arguments:r.arguments};n.push({role:B,content:[c]}),r={modality:L,index:0,id:"",name:"",arguments:""};}i=s.partialContent.modality,s.partialContent.modality===F?o.value+=s.partialContent.value:s.partialContent.modality===L&&(r={modality:L,index:s.partialContent.index,id:s.partialContent.id||"",name:s.partialContent.name||"",arguments:s.partialContent.arguments||""});}}),i===F){let s={modality:H,value:o.value};n.push({role:B,content:[s]});}else if(i===L){let s={modality:J,index:r.index,id:r.id,name:r.name,arguments:r.arguments};n.push({role:B,content:[s]});}return n},_o=(t=a.z.record(a.z.string(),a.z.any()).optional())=>t,fn="function",Lo=["object","array","number","string","boolean","null"],hn=a.z.enum(["object","array","number","string","boolean","null"]),yn=a.z.object({anyOf:a.z.array(a.z.any()).optional(),type:hn.optional(),default:a.z.any().optional(),title:a.z.string().optional(),description:a.z.string().max(4096).optional(),properties:a.z.record(a.z.any()).optional(),required:a.z.array(a.z.string()).optional(),minItems:a.z.number().int().min(0).optional(),maxItems:a.z.number().int().optional(),items:a.z.record(a.z.any()).optional(),enum:a.z.array(a.z.union([a.z.string(),a.z.number(),a.z.boolean(),a.z.null()])).optional(),minimum:a.z.number().optional(),maximum:a.z.number().optional(),minLength:a.z.number().int().min(0).optional(),maxLength:a.z.number().int().optional()}),ko=a.z.object({type:a.z.enum(["object"]),title:a.z.string().optional(),$defs:a.z.record(a.z.any()).optional(),properties:a.z.record(yn).optional(),required:a.z.array(a.z.string()).optional()}),bn=a.z.object({name:a.z.string().regex(/^[a-zA-Z0-9_]{1,64}$/).max(64),description:a.z.string().max(4096),parameters:a.z.any(),strict:a.z.boolean().optional()}),Ao=["function"],zn=a.z.enum(["function"]),Tn=a.z.object({type:zn,definition:a.z.object({schema:bn})}),En=[fn],qo=a.z.enum(En),Fo=(t=a.z.undefined())=>a.z.discriminatedUnion("type",[Tn.extend({metadata:t})]),Cn="float",Mn=a.z.object({index:a.z.number().int().nonnegative(),embedding:a.z.array(a.z.number())}),vn="base64",xn=a.z.object({index:a.z.number().int().nonnegative(),embedding:a.z.string().base64()}),$o=a.z.discriminatedUnion("encodingFormat",[a.z.object({encodingFormat:a.z.literal(Cn),embeddings:a.z.array(Mn)}),a.z.object({encodingFormat:a.z.literal(vn),embeddings:a.z.array(xn)})]),et="text",tt="token",Sn=[et,tt],Uo=a.z.enum(Sn),jn=a.z.array(a.z.string().min(1)),wn=a.z.array(a.z.array(a.z.number().int().nonnegative())),Go=(t=a.z.undefined())=>a.z.discriminatedUnion("modality",[a.z.object({modality:a.z.literal(et),metadata:t,requests:jn}),a.z.object({modality:a.z.literal(tt),metadata:t,requests:wn})]);m.AssistantRoleLiteral=B;m.Base64Embedding=xn;m.Base64EmbeddingLiteral=vn;m.Base64ImageContentTypeLiteral=Ke;m.Base64ImageContentValue=rn;m.Config=_o;m.Content=cn;m.EmbeddingModalityEnum=Uo;m.EmbeddingModalityLiterals=Sn;m.EmbeddingRequests=Go;m.EmbeddingTextModalityLiteral=et;m.EmbeddingTokenModalityLiteral=tt;m.Embeddings=$o;m.FloatEmbedding=Mn;m.FloatEmbeddingLiteral=Cn;m.Function=bn;m.FunctionParameter=yn;m.FunctionParameterTypes=Lo;m.FunctionParameterTypesLiteral=hn;m.FunctionParameters=ko;m.FunctionTool=Tn;m.FunctionToolLiteral=fn;m.ImageContent=pe;m.ImageContentDetails=ln;m.ImageContentDetailsLiteral=mn;m.ImageModalityLiteral=ee;m.Message=W;m.ModalityEnum=Co;m.ModalityLiterals=dn;m.PartialContent=un;m.PartialMessage=Xe;m.PartialModalityEnum=Mo;m.PartialModalityLiterals=pn;m.PartialRoleEnum=on;m.PartialRoleLiterals=an;m.PartialTextContent=We;m.PartialTextModalityLiteral=F;m.PartialToolCallContent=Ze;m.PartialToolCallModalityLiteral=L;m.RoleEnum=nn;m.RoleLiterals=tn;m.SystemRoleLiteral=Qt;m.TextContent=He;m.TextEmbeddingRequests=jn;m.TextModalityLiteral=H;m.TokenContent=vo;m.TokenEmbeddingRequests=wn;m.TokenModalityLiteral=gn;m.Tool=Fo;m.ToolCallContent=Ye;m.ToolCallModalityLiteral=J;m.ToolEnum=qo;m.ToolLiterals=En;m.ToolResponseContent=Qe;m.ToolResponseModalityLiteral=ue;m.ToolRoleLiteral=en;m.ToolTypes=Ao;m.ToolTypesLiteral=zn;m.UrlImageContentTypeLiteral=Ve;m.UrlImageContentValue=sn;m.UserRoleLiteral=Xt;m.createBase64ImageMessage=jo;m.createPartialTextMessage=Po;m.createPartialToolCallMessage=Ro;m.createTextMessage=xo;m.createToolCallMessage=wo;m.createToolResponseMessage=Io;m.createUrlImageMessage=So;m.mergePartialMessages=Oo;});var z=_(G()),_e=(0, z.RangeConfigItem)({param:"temperature",title:z.CONFIG.TEMPERATURE.title,description:z.CONFIG.TEMPERATURE.description,min:0,max:2,step:.01,default:1}),Le=t=>(0, z.RangeConfigItem)({param:"max_tokens",title:z.CONFIG.MAX_TOKENS.title,description:z.CONFIG.MAX_TOKENS.description,min:0,max:t,step:1,default:0}),ke=t=>(0, z.MultiStringConfigItem)({param:"stop",title:z.CONFIG.STOP(t).title,description:z.CONFIG.STOP(t).description,max:t}),Ae=(0, z.RangeConfigItem)({param:"top_p",title:z.CONFIG.TOP_P.title,description:z.CONFIG.TOP_P.description,min:0,max:1,step:.01,default:1}),qe=(0, z.RangeConfigItem)({param:"frequency_penalty",title:z.CONFIG.FREQUENCY_PENALTY.title,description:z.CONFIG.FREQUENCY_PENALTY.description,min:-2,max:2,step:.01,default:0}),Fe=(0, z.RangeConfigItem)({param:"presence_penalty",title:z.CONFIG.PRESENCE_PENALTY.title,description:z.CONFIG.PRESENCE_PENALTY.description,min:-2,max:2,step:.01,default:0}),$e=(0, z.RangeConfigItem)({param:"seed",title:"Seed",description:"This is in BETA. Set a seed to get reproducible results. Determinism is not guaranteed. Set to 0 to disable.",min:0,max:1e6,step:1,default:0}),Ue=(0, z.SelectStringConfigItem)({param:"response_format",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.",default:"text",choices:["text","json_object"]}),Ge=(0, z.SelectStringConfigItem)({param:"tool_choice",title:"Tool choice",description:"Controls which (if any) tool is called by the model. 'none' means the model will not call a function. 'auto' means the model can pick between generating a message or calling a tool.",default:"auto",choices:["auto","required","none"]});var le=(t,e)=>zod.z.object({temperature:_e.schema,maxTokens:Le(t).schema,stop:ke(e).schema,topP:Ae.schema,frequencyPenalty:qe.schema,presencePenalty:Fe.schema,seed:$e.schema.transform(n=>n===0?void 0:n),responseFormat:Ue.schema,toolChoice:Ge.schema}),me=(t,e)=>({temperature:_e.def,maxTokens:Le(t).def,stop:ke(e).def,topP:Ae.def,frequencyPenalty:qe.def,presencePenalty:Fe.def,seed:$e.def,responseFormat:Ue.def,toolChoice:Ge.def});var de=_(G());var ho=["object","array","number","string","boolean","enum"],Jt=zod.z.enum(ho),yo=zod.z.object({anyOf:zod.z.array(zod.z.any()).optional(),type:zod.z.union([Jt,zod.z.array(zod.z.union([Jt,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()}),bo=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(yo),additionalProperties:zod.z.literal(!1)}),zo=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:bo}).optional(),Kt=(0, de.ObjectSchemaConfigItem)({param:"response_schema",title:"Response schema",description:"When response format is set to 'json_schema', the model will return a JSON object of the specified schema.",objectSchema:zo}),Vt=(0, de.SelectStringConfigItem)({param:"response_format",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.",default:"text",choices:["text","json_object","json_schema"]}),Ht=(t,e)=>Rt(I({},me(t,e)),{responseFormat:Vt.def,responseSchema:Kt.def}),Wt=(t,e)=>le(t,e).extend({responseFormat:Vt.schema,responseSchema:Kt.schema});var ce=_(G()),Be=(0, ce.SelectStringConfigItem)({param:"encoding_format",title:"Encoding format",description:"Select the encoding format for the word embedding.",default:"float",choices:["float","base64"]}),Ne=(0, ce.RangeConfigItem)({param:"dimensions",title:"Dimensions",description:"Select the number of dimensions for the word embedding.",min:1,max:1024,step:1,default:1024});var Yt=()=>zod.z.object({encodingFormat:Be.schema,dimensions:Ne.schema}),Zt=()=>({encodingFormat:Be.def,dimensions:Ne.def});var De={base:(t,e)=>({def:me(t,e),schema:le(t,e)}),responseSchema:(t,e)=>({def:Ht(t,e),schema:Wt(t,e)})},Je={base:()=>({def:Zt(),schema:Yt()})};var k=_(Y());var In=zod.z.enum([k.SystemRoleLiteral,k.UserRoleLiteral,k.AssistantRoleLiteral,k.ToolRoleLiteral]),Pn={system:k.SystemRoleLiteral,user:k.UserRoleLiteral,assistant:k.AssistantRoleLiteral,tool:k.ToolRoleLiteral};var A=_(Y());var Rn=[A.TextModalityLiteral,A.ImageModalityLiteral,A.ToolCallModalityLiteral,A.ToolResponseModalityLiteral],On=zod.z.enum([A.TextModalityLiteral,A.ImageModalityLiteral,A.ToolCallModalityLiteral,A.ToolResponseModalityLiteral]);var Do=zod.z.array(zod.z.object({id:zod.z.string().min(1),type:zod.z.enum(["function"]),function:zod.z.object({name:zod.z.string(),arguments:zod.z.string()})})),_n=zod.z.object({id:zod.z.string(),object:zod.z.literal("chat.completion"),created:zod.z.number(),model:zod.z.string(),system_fingerprint:zod.z.any(),choices:zod.z.array(zod.z.object({index:zod.z.number(),message:zod.z.object({role:zod.z.string(),content:zod.z.string().nullable().optional(),tool_calls:Do.optional(),refusal:zod.z.string().nullable().optional()}),logprobs:zod.z.any(),finish_reason:zod.z.any()})),usage:zod.z.object({prompt_tokens:zod.z.number(),completion_tokens:zod.z.number(),total_tokens:zod.z.number()})}),Jo=zod.z.array(zod.z.object({index:zod.z.number().int(),id:zod.z.string().min(1).optional(),type:zod.z.enum(["function"]).optional(),function:zod.z.object({name:zod.z.string().min(1).optional(),arguments:zod.z.string().optional()}).optional()})),Ln=zod.z.object({id:zod.z.string(),object:zod.z.string(),created:zod.z.number(),model:zod.z.string(),system_fingerprint:zod.z.any().nullable(),choices:zod.z.array(zod.z.object({index:zod.z.number(),delta:zod.z.object({content:zod.z.string().nullable().optional(),tool_calls:Jo.optional(),refusal:zod.z.string().nullable().optional()}).or(zod.z.object({})),finish_reason:zod.z.any().nullable(),logprobs:zod.z.any().nullable()}))});var T=_(G()),g=_(Y());var kn=zod.z.object({apiKey:zod.z.string(),proxyUrl:zod.z.string().optional()}),ge=class{constructor(e,n){this.version="v1";this.baseUrl="https://api.openai.com/v1";this.getTokenCount=e=>e.reduce((n,i)=>n+i.content.map(o=>o.modality==="text"?o.value:"").join(" ").length,0);this.getDefaultBaseUrl=()=>this.baseUrl;this.getDefaultHeaders=()=>({Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"});this.getDefaultParams=()=>({model:this.modelSchema.name});this.transformConfig=(e,n,i)=>{let o=e.toolChoice;delete e.toolChoice;let r=this.modelSchema.config.schema.safeParse(e);if(!r.success)throw new T.InvalidConfigError({info:this.modelSchema.name,error:r.error});let s=r.data;o!==void 0&&(s.toolChoice=o),Object.keys(s).forEach(h=>{if(!(h in this.modelSchema.config.def))throw new T.InvalidConfigError({info:this.modelSchema.name,error:new Error(`Invalid config key: '${h}'`)})});let c=Object.keys(s).reduce((h,v)=>{let y=this.modelSchema.config.def[v],j=y.param,N=s[v];return j==="max_tokens"&&y.type==="range"&&N===0?h[j]=y.max:h[j]=N,h},{});if("tool_choice"in c&&c.tool_choice!==void 0){let h=c.tool_choice;if(!i||i&&i.length===0)throw new T.InvalidConfigError({info:this.modelSchema.name,error:new Error("'tools' are required when 'toolChoice' is specified")});if(i&&i.length>0){let v=this.modelSchema.config.def.toolChoice;if(!v.choices.includes(h))if(i.map(y=>y.definition.schema.name).includes(h))c.tool_choice={type:"function",function:{name:h}};else throw new T.InvalidConfigError({info:this.modelSchema.name,error:new Error(`Invalid 'toolChoice': '${h}' is not part of provided tools or
|
|
21
|
-
one of '${v.choices.join(", ")}'`)})}}if("response_format"in c&&c.response_format!==void 0){let h=c.response_format;if(h==="json_schema")if("response_schema"in c)c.response_format={type:"json_schema",json_schema:c.response_schema},delete c.response_schema;else throw new T.InvalidConfigError({info:this.modelSchema.name,error:new Error("'responseSchema' is required in config when 'responseFormat' is 'json_schema'")});else c.response_format={type:h};}return c};this.transformMessages=e=>{if(!e||e&&e.length===0)return {messages:[]};let n=e.map(o=>{let r=(0, g.Message)().safeParse(o);if(!r.success)throw new T.InvalidMessagesError({info:this.modelSchema.name,error:r.error});return r.data});return n.forEach(o=>{o.content.forEach(r=>{if(!this.modelSchema.modalities.includes(r.modality))throw new T.InvalidMessagesError({info:this.modelSchema.name,error:new Error(`model: '${this.modelSchema.name}' does not support modality: '${r.modality}'`)})});}),{messages:n.map(o=>{switch(o.role){case g.SystemRoleLiteral:{let r=[];return o.content.forEach(s=>{if(s.modality===g.TextModalityLiteral)r.push(s.value);else throw new T.InvalidMessagesError({info:this.modelSchema.name,error:new Error(`role: '${g.SystemRoleLiteral}' cannot have content with modality '${s.modality}'`)})}),{role:this.modelSchema.roles[o.role],content:r}}case g.AssistantRoleLiteral:{let r=[],s=[];return o.content.forEach(c=>{if(c.modality===g.TextModalityLiteral)r.push(c.value);else if(c.modality===g.ToolCallModalityLiteral)s.push({id:c.id,type:"function",function:{name:c.name,arguments:c.arguments}});else throw new T.InvalidMessagesError({info:this.modelSchema.name,error:new Error(`role: '${g.AssistantRoleLiteral}' cannot have content with modality '${c.modality}'`)})}),I({role:this.modelSchema.roles[o.role],content:r},s.length>0?{tool_calls:s}:{})}case g.UserRoleLiteral:{let r=[],s=[];o.content.forEach(h=>{if(h.modality===g.TextModalityLiteral)r.push({type:"text",text:h.value});else if(h.modality===g.ImageModalityLiteral)s.push({type:"image_url",image_url:{url:h.value.type==="url"?h.value.url:h.value.base64,detail:h.detail}});else throw new T.InvalidMessagesError({info:this.modelSchema.name,error:new Error(`role: '${g.UserRoleLiteral}' cannot have content with modality '${h.modality}'`)})});let c=[...r,...s];return {role:this.modelSchema.roles[o.role],content:c}}case g.ToolRoleLiteral:{if(o.content.length!==1)throw new T.InvalidMessagesError({info:this.modelSchema.name,error:new Error(`role: '${g.ToolRoleLiteral}' must have exactly one content item`)});if(o.content[0].modality!==g.ToolResponseModalityLiteral)throw new T.InvalidMessagesError({info:this.modelSchema.name,error:new Error(`role: '${g.ToolRoleLiteral}' must have content with modality '${g.ToolResponseModalityLiteral}'`)});let r=o.content[0];return {role:this.modelSchema.roles[o.role],tool_call_id:r.id,content:r.data}}default:throw new T.InvalidMessagesError({info:this.modelSchema.name,error:new Error(`Invalid role: '${o.role}'`)})}})}};this.transformTools=e=>!e||e&&e.length===0?{tools:[]}:{tools:e.map(o=>{let r=(0, g.Tool)().safeParse(o);if(!r.success)throw new T.InvalidToolsError({info:this.modelSchema.name,error:r.error});return r.data}).map(o=>({type:"function",function:o.definition.schema}))};this.getCompleteChatUrl=(e,n,i)=>`${this.baseUrl}/chat/completions`;this.getCompleteChatHeaders=(e,n,i)=>this.getDefaultHeaders();this.getCompleteChatData=(e,n,i)=>{let o=this.transformConfig(e,n,i),r=this.transformMessages(n);if(r.messages&&r.messages.length===0)throw new T.InvalidMessagesError({info:this.modelSchema.name,error:new Error("Messages are required")});let s=i?this.transformTools(i):{};return I(I(I({model:this.modelSchema.name},o),r),s)};this.transformCompleteChatResponse=e=>{let n=_n.safeParse(e);if(n.success){if(n.data.choices.length===0)throw new T.ApiResponseError({info:this.modelSchema.name,error:new Error("No choices in response")});let i=[],o=n.data.choices[0].message;return o.content&&i.push((0, g.createTextMessage)(g.AssistantRoleLiteral,o.content)),o.refusal&&i.push((0, g.createTextMessage)(g.AssistantRoleLiteral,o.refusal)),o.tool_calls&&o.tool_calls.forEach((r,s)=>{i.push((0, g.createToolCallMessage)(g.AssistantRoleLiteral,s,r.id,r.function.name,r.function.arguments));}),i}throw new T.ApiRequestError({info:this.modelSchema.name,error:n.error})};this.getStreamChatUrl=(e,n,i)=>`${this.baseUrl}/chat/completions`;this.getStreamChatHeaders=(e,n,i)=>this.getDefaultHeaders();this.getStreamChatData=(e,n,i)=>{let o=this.transformConfig(e,n,i),r=this.transformMessages(n);if(r.messages&&r.messages.length===0)throw new T.InvalidMessagesError({info:this.modelSchema.name,error:new Error("Messages are required")});let s=i?this.transformTools(i):{};return I(I(I({stream:!0,model:this.modelSchema.name},o),r),s)};this.transformStreamChatResponseChunk=function(e,n){return _t(this,null,function*(){var o,r;let i=(n+e).split(`
|
|
22
|
-
`).filter(s=>s.trim()!=="");for(let s of i){let c;if(s==="data: [DONE]")return;if(s.startsWith("data: {")){try{c=JSON.parse(s.substring(6));}catch(y){if(y instanceof SyntaxError){n+=s;continue}else throw y}n="";let h=[],v=Ln.safeParse(c);if(v.success){let y=v.data.choices[0].delta;if(y!==void 0&&Object.keys(y).length!==0){if("content"in y&&y.content!==null)h.push((0, g.createPartialTextMessage)(g.AssistantRoleLiteral,y.content));else if("refusal"in y&&y.refusal!==null)h.push((0, g.createPartialTextMessage)(g.AssistantRoleLiteral,y.refusal));else if("tool_calls"in y&&y.tool_calls!==void 0){let j=y.tool_calls.at(0);h.push((0, g.createPartialToolCallMessage)(g.AssistantRoleLiteral,j.index,j.id,(o=j.function)==null?void 0:o.name,(r=j.function)==null?void 0:r.arguments));}}}yield {partialMessages:h,buffer:n};}}yield {partialMessages:[],buffer:n};})};this.modelSchema=e,this.apiKey=n.apiKey,n.proxyUrl&&(this.baseUrl=(0, T.urlWithoutTrailingSlash)(n.proxyUrl));}};var An=_(G());var Ko="gpt-4o",Vo="GPT-4o is a large-scale multimodal model trained by OpenAI. It is the successor to GPT-4 and is designed to be more powerful and capable than its predecessor.",at=(0, An.ChatModelSchema)(In,On).parse({name:Ko,description:Vo,maxInputTokens:128e3,maxOutputTokens:128e3,roles:Pn,modalities:Rn,config:{def:De.base(128e3,4).def,schema:De.base(128e3,4).schema}}),qn=kn,fe=class extends ge{constructor(e){super(at,e);}};var Z=_(Y());var Fn=[Z.EmbeddingTextModalityLiteral,Z.EmbeddingTokenModalityLiteral],$n=zod.z.enum([Z.EmbeddingTextModalityLiteral,Z.EmbeddingTokenModalityLiteral]);var Un=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({prompt_tokens:zod.z.number(),total_tokens:zod.z.number()})});var Q=_(Y()),U=_(G());var Gn=zod.z.object({apiKey:zod.z.string(),proxyUrl:zod.z.string().optional()}),he=class{constructor(e,n){this.version="v1";this.baseUrl="https://api.openai.com/v1";this.validateConfig=e=>{let n=this.modelSchema.config.schema.safeParse(e);if(!n.success)throw new U.InvalidConfigError({info:this.modelSchema.name,error:n.error});return Object.keys(n.data).forEach(i=>{if(!this.modelSchema.config.def[i])throw new U.InvalidConfigError({info:this.modelSchema.name,error:new Error(`Invalid config key: '${i}'`)})}),n.data};this.validateEmbeddingRequests=e=>{let n=(0, Q.EmbeddingRequests)().safeParse(e);if(!n.success)throw new U.InvalidEmbeddingRequestsError({info:this.modelSchema.name,error:n.error});return n.data};this.getDefaultBaseUrl=()=>this.baseUrl;this.getDefaultHeaders=()=>({Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"});this.getDefaultParams=()=>({model:this.modelSchema.name});this.getTokenCount=e=>this.validateEmbeddingRequests(e).requests.reduce((i,o)=>i+o.length,0);this.transformConfig=(e,n)=>{let i=this.validateConfig(e);return Object.keys(i).reduce((r,s)=>{let h=this.modelSchema.config.def[s].param,v=i[s];return r[h]=v,r},{})};this.transformEmbeddingRequests=e=>({input:e.requests});this.getGetEmbeddingsUrl=(e,n)=>`${this.baseUrl}/embeddings`;this.getGetEmbeddingsHeaders=(e,n)=>this.getDefaultHeaders();this.getGetEmbeddingsData=(e,n)=>I(I({model:this.modelSchema.name},this.transformConfig(e,n)),this.transformEmbeddingRequests(n));this.transformGetEmbeddingsResponse=e=>{let n,i=Un.safeParse(e);if(i.success){n=typeof i.data.data[0].embedding=="string"?Q.Base64EmbeddingLiteral:Q.FloatEmbeddingLiteral;let o=i.data.data.map(r=>typeof r.embedding=="string"?{index:r.index,embedding:r.embedding}:{index:r.index,embedding:r.embedding});return {encodingFormat:n,embeddings:o}}throw new U.ApiRequestError({info:this.modelSchema.name,error:i.error})};this.modelSchema=e,this.apiKey=n.apiKey,n.proxyUrl&&(this.baseUrl=(0, U.urlWithoutTrailingSlash)(n.proxyUrl));}};var Bn=_(G());var Wo="text-embedding-ada-002",Yo="some description",it=(0, Bn.EmbeddingModelSchema)($n).parse({name:Wo,description:Yo,modalities:Fn,maxInputTokens:8192,maxOutputTokens:8192,config:{def:Je.base().def,schema:Je.base().schema}}),Nn=Gn,ye=class extends he{constructor(e){super(it,e);}};var Zo="openai",Dn=class{constructor(){this.version="v1";this.name=Zo;this.chatModelFactories={"gpt-4o":{model:fe,modelOptions:qn,modelSchema:at}};this.embeddingModelFactories={"text-embedding-ada-002":{model:ye,modelOptions:Nn,modelSchema:it}};}chatModelLiterals(){return Object.keys(this.chatModelFactories)}chatModel(e,n){if(!(e in this.chatModelFactories))throw new Error(`Model ${e} not found`);let i=this.chatModelFactories[e].model,o=this.chatModelFactories[e].modelOptions.parse(n);return new i(o)}chatModelSchema(e){if(!(e in this.chatModelFactories))throw new Error(`Model ${e} not found`);return this.chatModelFactories[e].modelSchema}chatModelSchemas(){return Object.keys(this.chatModelFactories).reduce((e,n)=>(e[n]=this.chatModelFactories[n].modelSchema,e),{})}embeddingModelLiterals(){return Object.keys(this.embeddingModelFactories)}embeddingModel(e,n){if(!(e in this.embeddingModelFactories))throw new Error(`Model ${e} not found`);let i=this.embeddingModelFactories[e].model,o=this.embeddingModelFactories[e].modelOptions.parse(n);return new i(o)}embeddingModelSchema(e){if(!(e in this.embeddingModelFactories))throw new Error(`Model ${e} not found`);return this.embeddingModelFactories[e].modelSchema}embeddingModelSchemas(){return Object.keys(this.embeddingModelFactories).reduce((e,n)=>(e[n]=this.embeddingModelFactories[n].modelSchema,e),{})}};
|
|
7
|
+
var qe=Object.defineProperty,Ue=Object.defineProperties;var Be=Object.getOwnPropertyDescriptors;var W=Object.getOwnPropertySymbols;var $e=Object.prototype.hasOwnProperty,ke=Object.prototype.propertyIsEnumerable;var De=(i,e)=>(e=Symbol[i])?e:Symbol.for("Symbol."+i);var J=(i,e,o)=>e in i?qe(i,e,{enumerable:!0,configurable:!0,writable:!0,value:o}):i[e]=o,h=(i,e)=>{for(var o in e||(e={}))$e.call(e,o)&&J(i,o,e[o]);if(W)for(var o of W(e))ke.call(e,o)&&J(i,o,e[o]);return i},Y=(i,e)=>Ue(i,Be(e));var ze=function(i,e){this[0]=i,this[1]=e;},Z=(i,e,o)=>{var s=(m,l,d,p)=>{try{var c=o[m](l),u=(l=c.value)instanceof ze,E=c.done;Promise.resolve(u?l[0]:l).then(T=>u?s(m==="return"?m:"next",l[1]?{done:T.done,value:T.value}:T,d,p):d({value:T,done:E})).catch(T=>s("throw",T,d,p));}catch(T){p(T);}},n=m=>t[m]=l=>new Promise((d,p)=>s(m,l,d,p)),t={};return o=o.apply(i,e),t[De("asyncIterator")]=()=>t,n("next"),n("throw"),n("return"),t};var _=provider.RangeConfigItem({param:"temperature",title:provider.CONFIG.TEMPERATURE.title,description:provider.CONFIG.TEMPERATURE.description,min:0,max:2,step:.01,default:1}),j=i=>provider.RangeConfigItem({param:"max_tokens",title:provider.CONFIG.MAX_TOKENS.title,description:provider.CONFIG.MAX_TOKENS.description,min:0,max:i,step:1,default:0}),A=i=>provider.MultiStringConfigItem({param:"stop",title:provider.CONFIG.STOP(i).title,description:provider.CONFIG.STOP(i).description,max:i}),I=provider.RangeConfigItem({param:"top_p",title:provider.CONFIG.TOP_P.title,description:provider.CONFIG.TOP_P.description,min:0,max:1,step:.01,default:1}),v=provider.RangeConfigItem({param:"frequency_penalty",title:provider.CONFIG.FREQUENCY_PENALTY.title,description:provider.CONFIG.FREQUENCY_PENALTY.description,min:-2,max:2,step:.01,default:0}),F=provider.RangeConfigItem({param:"presence_penalty",title:provider.CONFIG.PRESENCE_PENALTY.title,description:provider.CONFIG.PRESENCE_PENALTY.description,min:-2,max:2,step:.01,default:0}),L=provider.RangeConfigItem({param:"seed",title:"Seed",description:"This is in BETA. Set a seed to get reproducible results. Determinism is not guaranteed. Set to 0 to disable.",min:0,max:1e6,step:1,default:0}),q=provider.SelectStringConfigItem({param:"response_format",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.",default:"text",choices:["text","json_object"]}),U=provider.SelectStringConfigItem({param:"tool_choice",title:"Tool choice",description:"Controls which (if any) tool is called by the model. 'none' means the model will not call a function. 'auto' means the model can pick between generating a message or calling a tool.",default:"auto",choices:["auto","required","none"]});var S=(i,e)=>zod.z.object({temperature:_.schema,maxTokens:j(i).schema,stop:A(e).schema,topP:I.schema,frequencyPenalty:v.schema,presencePenalty:F.schema,seed:L.schema.transform(o=>o===0?void 0:o),responseFormat:q.schema,toolChoice:U.schema}),w=(i,e)=>({temperature:_.def,maxTokens:j(i).def,stop:A(e).def,topP:I.def,frequencyPenalty:v.def,presencePenalty:F.def,seed:L.def,responseFormat:q.def,toolChoice:U.def});var Ve=["object","array","number","string","boolean","enum"],X=zod.z.enum(Ve),We=zod.z.object({anyOf:zod.z.array(zod.z.any()).optional(),type:zod.z.union([X,zod.z.array(zod.z.union([X,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()}),Je=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(We),additionalProperties:zod.z.literal(!1)}),Ye=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:Je}).optional(),ee=provider.ObjectSchemaConfigItem({param:"response_schema",title:"Response schema",description:"When response format is set to 'json_schema', the model will return a JSON object of the specified schema.",objectSchema:Ye}),oe=provider.SelectStringConfigItem({param:"response_format",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.",default:"text",choices:["text","json_object","json_schema"]}),te=(i,e)=>Y(h({},w(i,e)),{responseFormat:oe.def,responseSchema:ee.def}),ne=(i,e)=>S(i,e).extend({responseFormat:oe.schema,responseSchema:ee.schema});var B=provider.SelectStringConfigItem({param:"encoding_format",title:"Encoding format",description:"Select the encoding format for the word embedding.",default:"float",choices:["float","base64"]}),$=provider.RangeConfigItem({param:"dimensions",title:"Dimensions",description:"Select the number of dimensions for the word embedding.",min:1,max:1024,step:1,default:1024});var se=()=>zod.z.object({encodingFormat:B.schema,dimensions:$.schema}),re=()=>({encodingFormat:B.def,dimensions:$.def});var k={base:(i,e)=>({def:w(i,e),schema:S(i,e)}),responseSchema:(i,e)=>({def:te(i,e),schema:ne(i,e)})},D={base:()=>({def:re(),schema:se()})};var le=zod.z.enum([types.SystemRoleLiteral,types.UserRoleLiteral,types.AssistantRoleLiteral,types.ToolRoleLiteral]),ce={system:types.SystemRoleLiteral,user:types.UserRoleLiteral,assistant:types.AssistantRoleLiteral,tool:types.ToolRoleLiteral};var ue=[types.TextModalityLiteral,types.ImageModalityLiteral,types.ToolCallModalityLiteral,types.ToolResponseModalityLiteral],ye=zod.z.enum([types.TextModalityLiteral,types.ImageModalityLiteral,types.ToolCallModalityLiteral,types.ToolResponseModalityLiteral]);var to=zod.z.array(zod.z.object({id:zod.z.string().min(1),type:zod.z.enum(["function"]),function:zod.z.object({name:zod.z.string(),arguments:zod.z.string()})})),Te=zod.z.object({id:zod.z.string(),object:zod.z.literal("chat.completion"),created:zod.z.number(),model:zod.z.string(),system_fingerprint:zod.z.any(),choices:zod.z.array(zod.z.object({index:zod.z.number(),message:zod.z.object({role:zod.z.string(),content:zod.z.string().nullable().optional(),tool_calls:to.optional(),refusal:zod.z.string().nullable().optional()}),logprobs:zod.z.any(),finish_reason:zod.z.any()})),usage:zod.z.object({prompt_tokens:zod.z.number(),completion_tokens:zod.z.number(),total_tokens:zod.z.number()})}),no=zod.z.array(zod.z.object({index:zod.z.number().int(),id:zod.z.string().min(1).optional(),type:zod.z.enum(["function"]).optional(),function:zod.z.object({name:zod.z.string().min(1).optional(),arguments:zod.z.string().optional()}).optional()})),be=zod.z.object({id:zod.z.string(),object:zod.z.string(),created:zod.z.number(),model:zod.z.string(),system_fingerprint:zod.z.any().nullable(),choices:zod.z.array(zod.z.object({index:zod.z.number(),delta:zod.z.object({content:zod.z.string().nullable().optional(),tool_calls:no.optional(),refusal:zod.z.string().nullable().optional()}).or(zod.z.object({})),finish_reason:zod.z.any().nullable(),logprobs:zod.z.any().nullable()}))});var xe=zod.z.object({apiKey:zod.z.string(),proxyUrl:zod.z.string().optional()}),x=class{constructor(e,o){this.version="v1";this.baseUrl="https://api.openai.com/v1";this.getTokenCount=e=>e.reduce((o,s)=>o+s.content.map(n=>n.modality==="text"?n.value:"").join(" ").length,0);this.getDefaultBaseUrl=()=>this.baseUrl;this.getDefaultHeaders=()=>({Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"});this.getDefaultParams=()=>({model:this.modelSchema.name});this.transformConfig=(e,o,s)=>{let n=e.toolChoice;delete e.toolChoice;let t=this.modelSchema.config.schema.safeParse(e);if(!t.success)throw new provider.InvalidConfigError({info:this.modelSchema.name,error:t.error});let m=t.data;n!==void 0&&(m.toolChoice=n),Object.keys(m).forEach(d=>{if(!(d in this.modelSchema.config.def))throw new provider.InvalidConfigError({info:this.modelSchema.name,error:new Error(`Invalid config key: '${d}'`)})});let l=Object.keys(m).reduce((d,p)=>{let c=this.modelSchema.config.def[p],u=c.param,E=m[p];return u==="max_tokens"&&c.type==="range"&&E===0?d[u]=c.max:d[u]=E,d},{});if("tool_choice"in l&&l.tool_choice!==void 0){let d=l.tool_choice;if(!s||s&&s.length===0)throw new provider.InvalidConfigError({info:this.modelSchema.name,error:new Error("'tools' are required when 'toolChoice' is specified")});if(s&&s.length>0){let p=this.modelSchema.config.def.toolChoice;if(!p.choices.includes(d))if(s.map(c=>c.definition.schema.name).includes(d))l.tool_choice={type:"function",function:{name:d}};else throw new provider.InvalidConfigError({info:this.modelSchema.name,error:new Error(`Invalid 'toolChoice': '${d}' is not part of provided tools or
|
|
8
|
+
one of '${p.choices.join(", ")}'`)})}}if("response_format"in l&&l.response_format!==void 0){let d=l.response_format;if(d==="json_schema")if("response_schema"in l)l.response_format={type:"json_schema",json_schema:l.response_schema},delete l.response_schema;else throw new provider.InvalidConfigError({info:this.modelSchema.name,error:new Error("'responseSchema' is required in config when 'responseFormat' is 'json_schema'")});else l.response_format={type:d};}return l};this.transformMessages=e=>{if(!e||e&&e.length===0)return {messages:[]};let o=e.map(n=>{let t=types.Message().safeParse(n);if(!t.success)throw new provider.InvalidMessagesError({info:this.modelSchema.name,error:t.error});return t.data});return o.forEach(n=>{n.content.forEach(t=>{if(!this.modelSchema.modalities.includes(t.modality))throw new provider.InvalidMessagesError({info:this.modelSchema.name,error:new Error(`model: '${this.modelSchema.name}' does not support modality: '${t.modality}'`)})});}),{messages:o.map(n=>{switch(n.role){case types.SystemRoleLiteral:{let t=[];return n.content.forEach(m=>{if(m.modality===types.TextModalityLiteral)t.push(m.value);else throw new provider.InvalidMessagesError({info:this.modelSchema.name,error:new Error(`role: '${types.SystemRoleLiteral}' cannot have content with modality '${m.modality}'`)})}),{role:this.modelSchema.roles[n.role],content:t}}case types.AssistantRoleLiteral:{let t=[],m=[];return n.content.forEach(l=>{if(l.modality===types.TextModalityLiteral)t.push(l.value);else if(l.modality===types.ToolCallModalityLiteral)m.push({id:l.id,type:"function",function:{name:l.name,arguments:l.arguments}});else throw new provider.InvalidMessagesError({info:this.modelSchema.name,error:new Error(`role: '${types.AssistantRoleLiteral}' cannot have content with modality '${l.modality}'`)})}),h({role:this.modelSchema.roles[n.role],content:t},m.length>0?{tool_calls:m}:{})}case types.UserRoleLiteral:{let t=[],m=[];n.content.forEach(d=>{if(d.modality===types.TextModalityLiteral)t.push({type:"text",text:d.value});else if(d.modality===types.ImageModalityLiteral)m.push({type:"image_url",image_url:{url:d.value.type==="url"?d.value.url:d.value.base64,detail:d.detail}});else throw new provider.InvalidMessagesError({info:this.modelSchema.name,error:new Error(`role: '${types.UserRoleLiteral}' cannot have content with modality '${d.modality}'`)})});let l=[...t,...m];return {role:this.modelSchema.roles[n.role],content:l}}case types.ToolRoleLiteral:{if(n.content.length!==1)throw new provider.InvalidMessagesError({info:this.modelSchema.name,error:new Error(`role: '${types.ToolRoleLiteral}' must have exactly one content item`)});if(n.content[0].modality!==types.ToolResponseModalityLiteral)throw new provider.InvalidMessagesError({info:this.modelSchema.name,error:new Error(`role: '${types.ToolRoleLiteral}' must have content with modality '${types.ToolResponseModalityLiteral}'`)});let t=n.content[0];return {role:this.modelSchema.roles[n.role],tool_call_id:t.id,content:t.data}}default:throw new provider.InvalidMessagesError({info:this.modelSchema.name,error:new Error(`Invalid role: '${n.role}'`)})}})}};this.transformTools=e=>!e||e&&e.length===0?{tools:[]}:{tools:e.map(n=>{let t=types.Tool().safeParse(n);if(!t.success)throw new provider.InvalidToolsError({info:this.modelSchema.name,error:t.error});return t.data}).map(n=>({type:"function",function:n.definition.schema}))};this.getCompleteChatUrl=(e,o,s)=>`${this.baseUrl}/chat/completions`;this.getCompleteChatHeaders=(e,o,s)=>this.getDefaultHeaders();this.getCompleteChatData=(e,o,s)=>{let n=this.transformConfig(e,o,s),t=this.transformMessages(o);if(t.messages&&t.messages.length===0)throw new provider.InvalidMessagesError({info:this.modelSchema.name,error:new Error("Messages are required")});let m=s?this.transformTools(s):{};return h(h(h({model:this.modelSchema.name},n),t),m)};this.transformCompleteChatResponse=e=>{let o=Te.safeParse(e);if(o.success){if(o.data.choices.length===0)throw new provider.ApiResponseError({info:this.modelSchema.name,error:new Error("No choices in response")});let s=[],n=o.data.choices[0].message;return n.content&&s.push(types.createTextMessage(types.AssistantRoleLiteral,n.content)),n.refusal&&s.push(types.createTextMessage(types.AssistantRoleLiteral,n.refusal)),n.tool_calls&&n.tool_calls.forEach((t,m)=>{s.push(types.createToolCallMessage(types.AssistantRoleLiteral,m,t.id,t.function.name,t.function.arguments));}),s}throw new provider.ApiRequestError({info:this.modelSchema.name,error:o.error})};this.getStreamChatUrl=(e,o,s)=>`${this.baseUrl}/chat/completions`;this.getStreamChatHeaders=(e,o,s)=>this.getDefaultHeaders();this.getStreamChatData=(e,o,s)=>{let n=this.transformConfig(e,o,s),t=this.transformMessages(o);if(t.messages&&t.messages.length===0)throw new provider.InvalidMessagesError({info:this.modelSchema.name,error:new Error("Messages are required")});let m=s?this.transformTools(s):{};return h(h(h({stream:!0,model:this.modelSchema.name},n),t),m)};this.transformStreamChatResponseChunk=function(e,o){return Z(this,null,function*(){var n,t;let s=(o+e).split(`
|
|
9
|
+
`).filter(m=>m.trim()!=="");for(let m of s){let l;if(m==="data: [DONE]")return;if(m.startsWith("data: {")){try{l=JSON.parse(m.substring(6));}catch(c){if(c instanceof SyntaxError){o+=m;continue}else throw c}o="";let d=[],p=be.safeParse(l);if(p.success){let c=p.data.choices[0].delta;if(c!==void 0&&Object.keys(c).length!==0){if("content"in c&&c.content!==null)d.push(types.createPartialTextMessage(types.AssistantRoleLiteral,c.content));else if("refusal"in c&&c.refusal!==null)d.push(types.createPartialTextMessage(types.AssistantRoleLiteral,c.refusal));else if("tool_calls"in c&&c.tool_calls!==void 0){let u=c.tool_calls.at(0);d.push(types.createPartialToolCallMessage(types.AssistantRoleLiteral,u.index,u.id,(n=u.function)==null?void 0:n.name,(t=u.function)==null?void 0:t.arguments));}}}yield {partialMessages:d,buffer:o};}}yield {partialMessages:[],buffer:o};})};this.modelSchema=e,this.apiKey=o.apiKey,o.proxyUrl&&(this.baseUrl=provider.urlWithoutTrailingSlash(o.proxyUrl));}};var uo="gpt-4o",yo="GPT-4o is a large-scale multimodal model trained by OpenAI. It is the successor to GPT-4 and is designed to be more powerful and capable than its predecessor.",H=provider.ChatModelSchema(le,ye).parse({name:uo,description:yo,maxInputTokens:128e3,maxOutputTokens:128e3,roles:ce,modalities:ue,config:{def:k.base(128e3,4).def,schema:k.base(128e3,4).schema}}),Oe=xe,O=class extends x{constructor(e){super(H,e);}};var _e=[types.EmbeddingTextModalityLiteral,types.EmbeddingTokenModalityLiteral],je=zod.z.enum([types.EmbeddingTextModalityLiteral,types.EmbeddingTokenModalityLiteral]);var Ae=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({prompt_tokens:zod.z.number(),total_tokens:zod.z.number()})});var ve=zod.z.object({apiKey:zod.z.string(),proxyUrl:zod.z.string().optional()}),R=class{constructor(e,o){this.version="v1";this.baseUrl="https://api.openai.com/v1";this.validateConfig=e=>{let o=this.modelSchema.config.schema.safeParse(e);if(!o.success)throw new provider.InvalidConfigError({info:this.modelSchema.name,error:o.error});return Object.keys(o.data).forEach(s=>{if(!this.modelSchema.config.def[s])throw new provider.InvalidConfigError({info:this.modelSchema.name,error:new Error(`Invalid config key: '${s}'`)})}),o.data};this.validateEmbeddingRequests=e=>{let o=types.EmbeddingRequests().safeParse(e);if(!o.success)throw new provider.InvalidEmbeddingRequestsError({info:this.modelSchema.name,error:o.error});return o.data};this.getDefaultBaseUrl=()=>this.baseUrl;this.getDefaultHeaders=()=>({Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"});this.getDefaultParams=()=>({model:this.modelSchema.name});this.getTokenCount=e=>this.validateEmbeddingRequests(e).requests.reduce((s,n)=>s+n.length,0);this.transformConfig=(e,o)=>{let s=this.validateConfig(e);return Object.keys(s).reduce((t,m)=>{let d=this.modelSchema.config.def[m].param,p=s[m];return t[d]=p,t},{})};this.transformEmbeddingRequests=e=>({input:e.requests});this.getGetEmbeddingsUrl=(e,o)=>`${this.baseUrl}/embeddings`;this.getGetEmbeddingsHeaders=(e,o)=>this.getDefaultHeaders();this.getGetEmbeddingsData=(e,o)=>h(h({model:this.modelSchema.name},this.transformConfig(e,o)),this.transformEmbeddingRequests(o));this.transformGetEmbeddingsResponse=e=>{let o,s=Ae.safeParse(e);if(s.success){o=typeof s.data.data[0].embedding=="string"?types.Base64EmbeddingLiteral:types.FloatEmbeddingLiteral;let n=s.data.data.map(t=>typeof t.embedding=="string"?{index:t.index,embedding:t.embedding}:{index:t.index,embedding:t.embedding});return {encodingFormat:o,embeddings:n}}throw new provider.ApiRequestError({info:this.modelSchema.name,error:s.error})};this.modelSchema=e,this.apiKey=o.apiKey,o.proxyUrl&&(this.baseUrl=provider.urlWithoutTrailingSlash(o.proxyUrl));}};var Oo="text-embedding-ada-002",Ro="some description",V=provider.EmbeddingModelSchema(je).parse({name:Oo,description:Ro,modalities:_e,maxInputTokens:8192,maxOutputTokens:8192,config:{def:D.base().def,schema:D.base().schema}}),Fe=ve,P=class extends R{constructor(e){super(V,e);}};var Po="openai",Le=class{constructor(){this.version="v1";this.name=Po;this.chatModelFactories={"gpt-4o":{model:O,modelOptions:Oe,modelSchema:H}};this.embeddingModelFactories={"text-embedding-ada-002":{model:P,modelOptions:Fe,modelSchema:V}};}chatModelLiterals(){return Object.keys(this.chatModelFactories)}chatModel(e,o){if(!(e in this.chatModelFactories))throw new Error(`Model ${e} not found`);let s=this.chatModelFactories[e].model,n=this.chatModelFactories[e].modelOptions.parse(o);return new s(n)}chatModelSchema(e){if(!(e in this.chatModelFactories))throw new Error(`Model ${e} not found`);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){if(!(e in this.embeddingModelFactories))throw new Error(`Model ${e} not found`);let s=this.embeddingModelFactories[e].model,n=this.embeddingModelFactories[e].modelOptions.parse(o);return new s(n)}embeddingModelSchema(e){if(!(e in this.embeddingModelFactories))throw new Error(`Model ${e} not found`);return this.embeddingModelFactories[e].modelSchema}embeddingModelSchemas(){return Object.keys(this.embeddingModelFactories).reduce((e,o)=>(e[o]=this.embeddingModelFactories[o].modelSchema,e),{})}};
|
|
23
10
|
|
|
24
|
-
exports.BaseChatModel =
|
|
25
|
-
exports.BaseChatModelOptions =
|
|
26
|
-
exports.BaseConfigDef =
|
|
27
|
-
exports.BaseConfigSchema =
|
|
28
|
-
exports.BaseEmbeddingModel =
|
|
29
|
-
exports.BaseEmbeddingModelOptions =
|
|
30
|
-
exports.BaseWordEmbeddingConfigDef =
|
|
31
|
-
exports.BaseWordEmbeddingConfigSchema =
|
|
32
|
-
exports.GPT4o =
|
|
33
|
-
exports.GPT4oOptions =
|
|
34
|
-
exports.GPT4oSchema =
|
|
35
|
-
exports.OpenAI =
|
|
36
|
-
exports.OpenAIChatModelModalities =
|
|
37
|
-
exports.OpenAIChatModelModalitiesEnum =
|
|
38
|
-
exports.OpenAIChatModelRoles =
|
|
39
|
-
exports.OpenAIChatModelRolesMap =
|
|
40
|
-
exports.OpenAICompleteChatResponse =
|
|
41
|
-
exports.OpenAIConfigs =
|
|
42
|
-
exports.OpenAIEmbeddingModelModalities =
|
|
43
|
-
exports.OpenAIEmbeddingModelModalitiesEnum =
|
|
44
|
-
exports.OpenAIGetEmbeddingsResponse =
|
|
45
|
-
exports.OpenAIStreamChatResponse =
|
|
46
|
-
exports.OpenAIToolCallsCompleteChatResponse =
|
|
47
|
-
exports.OpenAIToolCallsStreamChatResponse =
|
|
48
|
-
exports.OpenAIWordEmbeddingConfigs =
|
|
49
|
-
exports.ProviderLiteral =
|
|
50
|
-
exports.ResponseSchemaConfigDef =
|
|
51
|
-
exports.ResponseSchemaConfigSchema =
|
|
52
|
-
exports.TextEmbeddingAda002 =
|
|
53
|
-
exports.TextEmbeddingAda002Options =
|
|
54
|
-
exports.TextEmbeddingAda002Schema =
|
|
55
|
-
exports.dimensions =
|
|
56
|
-
exports.encodingFormat =
|
|
57
|
-
exports.frequencyPenalty =
|
|
58
|
-
exports.maxTokens =
|
|
59
|
-
exports.presencePenalty =
|
|
60
|
-
exports.responseFormat =
|
|
61
|
-
exports.seed =
|
|
62
|
-
exports.stop =
|
|
63
|
-
exports.temperature =
|
|
64
|
-
exports.toolChoice =
|
|
65
|
-
exports.topP =
|
|
11
|
+
exports.BaseChatModel = x;
|
|
12
|
+
exports.BaseChatModelOptions = xe;
|
|
13
|
+
exports.BaseConfigDef = w;
|
|
14
|
+
exports.BaseConfigSchema = S;
|
|
15
|
+
exports.BaseEmbeddingModel = R;
|
|
16
|
+
exports.BaseEmbeddingModelOptions = ve;
|
|
17
|
+
exports.BaseWordEmbeddingConfigDef = re;
|
|
18
|
+
exports.BaseWordEmbeddingConfigSchema = se;
|
|
19
|
+
exports.GPT4o = O;
|
|
20
|
+
exports.GPT4oOptions = Oe;
|
|
21
|
+
exports.GPT4oSchema = H;
|
|
22
|
+
exports.OpenAI = Le;
|
|
23
|
+
exports.OpenAIChatModelModalities = ue;
|
|
24
|
+
exports.OpenAIChatModelModalitiesEnum = ye;
|
|
25
|
+
exports.OpenAIChatModelRoles = le;
|
|
26
|
+
exports.OpenAIChatModelRolesMap = ce;
|
|
27
|
+
exports.OpenAICompleteChatResponse = Te;
|
|
28
|
+
exports.OpenAIConfigs = k;
|
|
29
|
+
exports.OpenAIEmbeddingModelModalities = _e;
|
|
30
|
+
exports.OpenAIEmbeddingModelModalitiesEnum = je;
|
|
31
|
+
exports.OpenAIGetEmbeddingsResponse = Ae;
|
|
32
|
+
exports.OpenAIStreamChatResponse = be;
|
|
33
|
+
exports.OpenAIToolCallsCompleteChatResponse = to;
|
|
34
|
+
exports.OpenAIToolCallsStreamChatResponse = no;
|
|
35
|
+
exports.OpenAIWordEmbeddingConfigs = D;
|
|
36
|
+
exports.ProviderLiteral = Po;
|
|
37
|
+
exports.ResponseSchemaConfigDef = te;
|
|
38
|
+
exports.ResponseSchemaConfigSchema = ne;
|
|
39
|
+
exports.TextEmbeddingAda002 = P;
|
|
40
|
+
exports.TextEmbeddingAda002Options = Fe;
|
|
41
|
+
exports.TextEmbeddingAda002Schema = V;
|
|
42
|
+
exports.dimensions = $;
|
|
43
|
+
exports.encodingFormat = B;
|
|
44
|
+
exports.frequencyPenalty = v;
|
|
45
|
+
exports.maxTokens = j;
|
|
46
|
+
exports.presencePenalty = F;
|
|
47
|
+
exports.responseFormat = q;
|
|
48
|
+
exports.seed = L;
|
|
49
|
+
exports.stop = A;
|
|
50
|
+
exports.temperature = _;
|
|
51
|
+
exports.toolChoice = U;
|
|
52
|
+
exports.topP = I;
|
|
66
53
|
//# sourceMappingURL=index.js.map
|
|
67
54
|
//# sourceMappingURL=index.js.map
|