@adaline/openai 0.23.0 → 0.25.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.d.mts +3 -3
- package/dist/index.d.ts +3 -3
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/package.json +3 -3
package/dist/index.d.mts
CHANGED
|
@@ -1902,7 +1902,7 @@ declare const OpenAIStreamChatResponse: z.ZodObject<{
|
|
|
1902
1902
|
object: z.ZodString;
|
|
1903
1903
|
created: z.ZodNumber;
|
|
1904
1904
|
model: z.ZodString;
|
|
1905
|
-
system_fingerprint: z.ZodNullable<z.ZodString
|
|
1905
|
+
system_fingerprint: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
1906
1906
|
choices: z.ZodArray<z.ZodObject<{
|
|
1907
1907
|
index: z.ZodNumber;
|
|
1908
1908
|
delta: z.ZodUnion<[z.ZodObject<{
|
|
@@ -2217,7 +2217,7 @@ declare const OpenAIStreamChatResponse: z.ZodObject<{
|
|
|
2217
2217
|
id: string;
|
|
2218
2218
|
model: string;
|
|
2219
2219
|
created: number;
|
|
2220
|
-
system_fingerprint
|
|
2220
|
+
system_fingerprint?: string | null | undefined;
|
|
2221
2221
|
usage?: {
|
|
2222
2222
|
prompt_tokens: number;
|
|
2223
2223
|
completion_tokens: number;
|
|
@@ -2267,7 +2267,7 @@ declare const OpenAIStreamChatResponse: z.ZodObject<{
|
|
|
2267
2267
|
id: string;
|
|
2268
2268
|
model: string;
|
|
2269
2269
|
created: number;
|
|
2270
|
-
system_fingerprint
|
|
2270
|
+
system_fingerprint?: string | null | undefined;
|
|
2271
2271
|
usage?: {
|
|
2272
2272
|
prompt_tokens: number;
|
|
2273
2273
|
completion_tokens: number;
|
package/dist/index.d.ts
CHANGED
|
@@ -1902,7 +1902,7 @@ declare const OpenAIStreamChatResponse: z.ZodObject<{
|
|
|
1902
1902
|
object: z.ZodString;
|
|
1903
1903
|
created: z.ZodNumber;
|
|
1904
1904
|
model: z.ZodString;
|
|
1905
|
-
system_fingerprint: z.ZodNullable<z.ZodString
|
|
1905
|
+
system_fingerprint: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
1906
1906
|
choices: z.ZodArray<z.ZodObject<{
|
|
1907
1907
|
index: z.ZodNumber;
|
|
1908
1908
|
delta: z.ZodUnion<[z.ZodObject<{
|
|
@@ -2217,7 +2217,7 @@ declare const OpenAIStreamChatResponse: z.ZodObject<{
|
|
|
2217
2217
|
id: string;
|
|
2218
2218
|
model: string;
|
|
2219
2219
|
created: number;
|
|
2220
|
-
system_fingerprint
|
|
2220
|
+
system_fingerprint?: string | null | undefined;
|
|
2221
2221
|
usage?: {
|
|
2222
2222
|
prompt_tokens: number;
|
|
2223
2223
|
completion_tokens: number;
|
|
@@ -2267,7 +2267,7 @@ declare const OpenAIStreamChatResponse: z.ZodObject<{
|
|
|
2267
2267
|
id: string;
|
|
2268
2268
|
model: string;
|
|
2269
2269
|
created: number;
|
|
2270
|
-
system_fingerprint
|
|
2270
|
+
system_fingerprint?: string | null | undefined;
|
|
2271
2271
|
usage?: {
|
|
2272
2272
|
prompt_tokens: number;
|
|
2273
2273
|
completion_tokens: number;
|
package/dist/index.js
CHANGED
|
@@ -6,7 +6,7 @@ var types = require('@adaline/types');
|
|
|
6
6
|
|
|
7
7
|
var Xt=Object.defineProperty,Zt=Object.defineProperties;var en=Object.getOwnPropertyDescriptors;var Qo=Object.getOwnPropertySymbols;var on=Object.prototype.hasOwnProperty,tn=Object.prototype.propertyIsEnumerable;var nn=(n,e)=>(e=Symbol[n])?e:Symbol.for("Symbol."+n);var Xo=(n,e,t)=>e in n?Xt(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,M=(n,e)=>{for(var t in e||(e={}))on.call(e,t)&&Xo(n,t,e[t]);if(Qo)for(var t of Qo(e))tn.call(e,t)&&Xo(n,t,e[t]);return n},v=(n,e)=>Zt(n,en(e));var A=(n,e,t)=>new Promise((o,s)=>{var a=l=>{try{i(t.next(l));}catch(h){s(h);}},d=l=>{try{i(t.throw(l));}catch(h){s(h);}},i=l=>l.done?o(l.value):Promise.resolve(l.value).then(a,d);i((t=t.apply(n,e)).next());}),sn=function(n,e){this[0]=n,this[1]=e;},te=(n,e,t)=>{var o=(d,i,l,h)=>{try{var c=t[d](i),O=(i=c.value)instanceof sn,g=c.done;Promise.resolve(O?i[0]:i).then(y=>O?o(d==="return"?d:"next",i[1]?{done:y.done,value:y.value}:y,l,h):l({value:y,done:g})).catch(y=>o("throw",y,l,h));}catch(y){h(y);}},s=d=>a[d]=i=>new Promise((l,h)=>o(d,i,l,h)),a={};return t=t.apply(n,e),a[nn("asyncIterator")]=()=>a,s("next"),s("throw"),s("return"),a};var je=provider.RangeConfigItem({param:"temperature",title:provider.CHAT_CONFIG.TEMPERATURE.title,description:provider.CHAT_CONFIG.TEMPERATURE.description,min:0,max:2,step:.01,default:1}),De=n=>provider.RangeConfigItem({param:"max_completion_tokens",title:provider.CHAT_CONFIG.MAX_TOKENS.title,description:provider.CHAT_CONFIG.MAX_TOKENS.description,min:0,max:n,step:1,default:0}),Fe=n=>provider.MultiStringConfigItem({param:"stop",title:provider.CHAT_CONFIG.STOP(n).title,description:provider.CHAT_CONFIG.STOP(n).description,max:n}),$e=provider.RangeConfigItem({param:"top_p",title:provider.CHAT_CONFIG.TOP_P.title,description:provider.CHAT_CONFIG.TOP_P.description,min:0,max:1,step:.01,default:1}),Ne=provider.RangeConfigItem({param:"frequency_penalty",title:provider.CHAT_CONFIG.FREQUENCY_PENALTY.title,description:provider.CHAT_CONFIG.FREQUENCY_PENALTY.description,min:-2,max:2,step:.01,default:0}),Ue=provider.RangeConfigItem({param:"presence_penalty",title:provider.CHAT_CONFIG.PRESENCE_PENALTY.title,description:provider.CHAT_CONFIG.PRESENCE_PENALTY.description,min:-2,max:2,step:.01,default:0}),He=provider.RangeConfigItem({param:"seed",title:provider.CHAT_CONFIG.SEED.title,description:provider.CHAT_CONFIG.SEED.description,min:0,max:1e6,step:1,default:0}),Ve=provider.SelectBooleanConfigItem({param:"logprobs",title:provider.CHAT_CONFIG.LOG_PROBS.title,description:provider.CHAT_CONFIG.LOG_PROBS.description,default:!1}),Ke=provider.RangeConfigItem({param:"top_logprobs",title:provider.CHAT_CONFIG.TOP_LOG_PROBS.title,description:provider.CHAT_CONFIG.TOP_LOG_PROBS.description,min:0,max:20,step:1,default:0}),Je=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 N=(n,e)=>zod.z.object({temperature:je.schema,maxTokens:De(n).schema,stop:Fe(e).schema,topP:$e.schema,frequencyPenalty:Ne.schema,presencePenalty:Ue.schema,seed:He.schema.transform(t=>t===0?void 0:t),logProbs:Ve.schema,topLogProbs:Ke.schema,toolChoice:Je.schema}),U=(n,e)=>({temperature:je.def,maxTokens:De(n).def,stop:Fe(e).def,topP:$e.def,frequencyPenalty:Ne.def,presencePenalty:Ue.def,seed:He.def,logProbs:Ve.def,topLogProbs:Ke.def,toolChoice:Je.def});var Zo=provider.ObjectSchemaConfigItem({param:"response_schema",title:provider.CHAT_CONFIG.RESPONSE_SCHEMA.title,description:provider.CHAT_CONFIG.RESPONSE_SCHEMA.description,objectSchema:types.ResponseSchema}),et=provider.SelectStringConfigItem({param:"response_format",title:provider.CHAT_CONFIG.RESPONSE_FORMAT_WITH_SCHEMA.title,description:provider.CHAT_CONFIG.RESPONSE_FORMAT_WITH_SCHEMA.description,default:"text",choices:["text","json_object","json_schema"]}),se=(n,e)=>v(M({},U(n,e)),{responseFormat:et.def,responseSchema:Zo.def}),ae=(n,e)=>N(n,e).extend({responseFormat:et.schema,responseSchema:Zo.schema});var tt=provider.RangeConfigItem({param:"temperature",title:provider.CHAT_CONFIG.TEMPERATURE.title,description:provider.CHAT_CONFIG.TEMPERATURE.description,min:1,max:1,step:.01,default:1}),nt=(n,e)=>v(M({},se(n,e)),{temperature:tt.def}),st=(n,e)=>ae(n,e).extend({temperature:tt.schema});var it=provider.SelectStringConfigItem({param:"response_format",title:provider.CHAT_CONFIG.RESPONSE_FORMAT.title,description:provider.CHAT_CONFIG.RESPONSE_FORMAT.description,default:"text",choices:["text","json_object"]}),rt=(n,e)=>v(M({},U(n,e)),{responseFormat:it.def}),lt=(n,e)=>N(n,e).extend({responseFormat:it.schema});var We=provider.SelectStringConfigItem({param:"encoding_format",title:"Encoding format",description:"Select the encoding format for the word embedding.",default:"float",choices:["float","base64"]}),Ye=n=>provider.RangeConfigItem({param:"dimensions",title:"Dimensions",description:"Select the number of dimensions for the word embedding.",min:1,max:n,step:1,default:n});var ie=()=>zod.z.object({encodingFormat:We.schema}),re=()=>({encodingFormat:We.def});var pt=n=>ie().extend({dimensions:Ye(n).schema}),mt=n=>v(M({},re()),{dimensions:Ye(n).def});var m={base:(n,e)=>({def:U(n,e),schema:N(n,e)}),responseFormat:(n,e)=>({def:rt(n,e),schema:lt(n,e)}),responseSchema:(n,e)=>({def:se(n,e),schema:ae(n,e)}),oSeries:(n,e)=>({def:nt(n,e),schema:st(n,e)})},k={base:()=>({def:re(),schema:ie()}),dimensions:n=>({def:mt(n),schema:pt(n)})};var gn="openai",D=class{constructor(){this.version="v1";this.name=gn;this.chatModelFactories={[oo]:{model:me,modelOptions:ut,modelSchema:to},[Qe]:{model:le,modelOptions:ct,modelSchema:Xe},[Ze]:{model:pe,modelOptions:ht,modelSchema:eo},[no]:{model:de,modelOptions:ft,modelSchema:so},[ao]:{model:ce,modelOptions:_t,modelSchema:io},[ro]:{model:he,modelOptions:Tt,modelSchema:lo},[po]:{model:ue,modelOptions:gt,modelSchema:mo},[co]:{model:fe,modelOptions:yt,modelSchema:ho},[uo]:{model:_e,modelOptions:Mt,modelSchema:fo},[_o]:{model:Te,modelOptions:Ot,modelSchema:To},[Mo]:{model:ye,modelOptions:bt,modelSchema:Oo},[Po]:{model:Oe,modelOptions:St,modelSchema:So},[Io]:{model:Ce,modelOptions:It,modelSchema:xo},[Co]:{model:Me,modelOptions:Pt,modelSchema:bo},[go]:{model:ge,modelOptions:Ct,modelSchema:yo},[Go]:{model:Se,modelOptions:Et,modelSchema:vo},[qo]:{model:Ie,modelOptions:Rt,modelSchema:ko},[Lo]:{model:xe,modelOptions:wt,modelSchema:zo},[Ao]:{model:be,modelOptions:xt,modelSchema:Eo},[Ro]:{model:Pe,modelOptions:At,modelSchema:wo}};this.embeddingModelFactories={[Bo]:{model:Ae,modelOptions:Gt,modelSchema:jo},[Do]:{model:Ee,modelOptions:vt,modelSchema:Fo},[$o]:{model:Re,modelOptions:qt,modelSchema:No}};}chatModelLiterals(){return Object.keys(this.chatModelFactories)}chatModelSchemas(){return Object.keys(this.chatModelFactories).reduce((e,t)=>(e[t]=this.chatModelFactories[t].modelSchema,e),{})}chatModel(e){let t=e.modelName;if(!(t in this.chatModelFactories))throw new provider.ProviderError({info:`OpenAI chat model: ${t} not found`,cause:new Error(`OpenAI chat model: ${t} not found, available chat models:
|
|
8
8
|
[${this.chatModelLiterals().join(", ")}]`)});let o=this.chatModelFactories[t].model,s=this.chatModelFactories[t].modelOptions.parse(e);return new o(s)}embeddingModelLiterals(){return Object.keys(this.embeddingModelFactories)}embeddingModelSchemas(){return Object.keys(this.embeddingModelFactories).reduce((e,t)=>(e[t]=this.embeddingModelFactories[t].modelSchema,e),{})}embeddingModel(e){let t=e.modelName;if(!(t in this.embeddingModelFactories))throw new provider.ProviderError({info:`OpenAI embedding model: ${t} not found`,cause:new Error(`OpenAI embedding model: ${t} not found, available embedding models:
|
|
9
|
-
[${this.embeddingModelLiterals().join(", ")}]`)});let o=this.embeddingModelFactories[t].model,s=this.embeddingModelFactories[t].modelOptions.parse(e);return new o(s)}};D.baseUrl="https://api.openai.com/v1";var _=zod.z.enum([types.SystemRoleLiteral,types.UserRoleLiteral,types.AssistantRoleLiteral,types.ToolRoleLiteral]),T={system:types.SystemRoleLiteral,user:types.UserRoleLiteral,assistant:types.AssistantRoleLiteral,tool:types.ToolRoleLiteral},H=zod.z.enum([types.UserRoleLiteral,types.AssistantRoleLiteral]),V={user:types.UserRoleLiteral,assistant:types.AssistantRoleLiteral};var P=[types.TextModalityLiteral,types.ImageModalityLiteral,types.ToolCallModalityLiteral,types.ToolResponseModalityLiteral],S=zod.z.enum([types.TextModalityLiteral,types.ImageModalityLiteral,types.ToolCallModalityLiteral,types.ToolResponseModalityLiteral]),J=[types.TextModalityLiteral],W=zod.z.enum([types.TextModalityLiteral]),I=[types.TextModalityLiteral,types.ToolCallModalityLiteral,types.ToolResponseModalityLiteral],x=zod.z.enum([types.TextModalityLiteral,types.ToolCallModalityLiteral,types.ToolResponseModalityLiteral]);var ke=zod.z.object({token:zod.z.string(),logprob:zod.z.number(),bytes:zod.z.array(zod.z.number()).nullable()}),jt=zod.z.object({content:zod.z.array(ke.extend({top_logprobs:zod.z.array(ke)})).nullable().optional(),refusal:zod.z.array(ke.extend({top_logprobs:zod.z.array(ke)})).nullable().optional()}).nullable(),yn=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()})})),Dt=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.string().nullable(),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:yn.optional(),refusal:zod.z.string().nullable().optional()}),logprobs:jt.optional(),finish_reason:zod.z.string()})),usage:zod.z.object({prompt_tokens:zod.z.number(),completion_tokens:zod.z.number(),total_tokens:zod.z.number()})}),Mn=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()})),Ft=zod.z.object({id:zod.z.string(),object:zod.z.string(),created:zod.z.number(),model:zod.z.string(),system_fingerprint:zod.z.string().nullable(),choices:zod.z.array(zod.z.object({index:zod.z.number(),delta:zod.z.object({content:zod.z.string().nullable().optional(),tool_calls:Mn.optional(),refusal:zod.z.string().nullable().optional()}).or(zod.z.object({})),logprobs:jt,finish_reason:zod.z.string().nullable()})),usage:zod.z.object({prompt_tokens:zod.z.number(),completion_tokens:zod.z.number(),total_tokens:zod.z.number()}).nullable().optional()});var On=zod.z.object({type:zod.z.literal("function"),function:zod.z.object({name:zod.z.string().min(1),description:zod.z.string().min(1).optional(),strict:zod.z.boolean().optional(),parameters:zod.z.any()})}),Cn=zod.z.enum(["none","auto","required"]),bn=zod.z.object({type:zod.z.literal("function"),function:zod.z.object({name:zod.z.string().min(1)})}),Pn=zod.z.object({type:zod.z.enum(["text","json_object"])}).or(zod.z.object({type:zod.z.literal("json_schema"),json_schema:zod.z.object({name:zod.z.string().min(1),description:zod.z.string().min(1).optional(),strict:zod.z.boolean().optional(),schema:zod.z.any()})})),Ho=zod.z.object({text:zod.z.string().min(1),type:zod.z.literal("text")}),Sn=zod.z.object({type:zod.z.literal("image_url"),image_url:zod.z.object({url:zod.z.string().url().min(1),detail:zod.z.enum(["low","high","auto"]).optional()})}),In=zod.z.object({id:zod.z.string().min(1),type:zod.z.literal("function"),function:zod.z.object({name:zod.z.string().min(1),arguments:zod.z.string().min(1)})}),xn=zod.z.object({role:zod.z.literal("system"),content:zod.z.string().min(1).or(zod.z.array(Ho).min(1))}),An=zod.z.object({role:zod.z.literal("user"),content:zod.z.string().min(1).or(zod.z.array(zod.z.union([Ho,Sn])).min(1))}),En=zod.z.object({role:zod.z.literal("assistant"),content:zod.z.string().min(1).or(zod.z.array(Ho).min(1)).optional(),tool_calls:zod.z.array(In).min(1).optional()}),Rn=zod.z.object({role:zod.z.literal("tool"),tool_call_id:zod.z.string().min(1),content:zod.z.string().min(1)}),wn=zod.z.union([xn,An,En,Rn]),Le=zod.z.object({model:zod.z.string().min(1).optional(),messages:zod.z.array(wn).min(1),frequency_penalty:zod.z.number().min(-2).max(2).nullable().optional(),logprobs:zod.z.boolean().nullable().optional(),top_logprobs:zod.z.number().min(0).max(20).nullable().optional(),max_completion_tokens:zod.z.number().min(0).nullable().optional(),presence_penalty:zod.z.number().min(-2).max(2).nullable().optional(),response_format:Pn.optional(),seed:zod.z.number().nullable().optional(),stop:zod.z.string().or(zod.z.array(zod.z.string()).max(4)).nullable().optional(),temperature:zod.z.number().min(0).max(2).nullable().optional(),top_p:zod.z.number().min(0).max(1).nullable().optional(),tools:zod.z.array(On).optional(),tool_choice:Cn.or(bn).optional()});var $t=Le;var u=zod.z.object({modelName:zod.z.string(),apiKey:zod.z.string(),baseUrl:zod.z.string().url().optional(),completeChatUrl:zod.z.string().url().optional(),streamChatUrl:zod.z.string().url().optional(),organization:zod.z.string().optional()}),f=class{constructor(e,t){this.version="v1";let o=u.parse(t);this.modelSchema=e,this.modelName=o.modelName,this.apiKey=o.apiKey,this.baseUrl=provider.urlWithoutTrailingSlash(o.baseUrl||D.baseUrl),this.streamChatUrl=provider.urlWithoutTrailingSlash(o.streamChatUrl||`${this.baseUrl}/chat/completions`),this.completeChatUrl=provider.urlWithoutTrailingSlash(o.completeChatUrl||`${this.baseUrl}/chat/completions`),this.organization=o.organization;}getDefaultBaseUrl(){return this.baseUrl}getDefaultHeaders(){return M({Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},this.organization?{"OpenAI-Organization":this.organization}:{})}getDefaultParams(){return {model:this.modelName}}getRetryDelay(e){let t=i=>{let l=/(\d+)(h|m|s|ms)/g,h={h:36e5,m:6e4,s:1e3,ms:1},c,O=0;for(;(c=l.exec(i))!==null;){let g=parseInt(c[1]),y=c[2];O+=g*h[y];}return O},o=0,s=0,a=!0;e["x-ratelimit-reset-requests"]&&(o=t(e["x-ratelimit-reset-requests"])),e["x-ratelimit-reset-tokens"]&&(s=t(e["x-ratelimit-reset-tokens"]));let d=Math.max(o,s);return {shouldRetry:a,delayMs:d}}getTokenCount(e){return e.reduce((t,o)=>t+o.content.map(s=>s.modality==="text"?s.value:"").join(" ").length,0)}transformModelRequest(e){let t=Le.safeParse(e);if(!t.success)throw new provider.InvalidModelRequestError({info:"Invalid model request",cause:t.error});let o=t.data,s=o.model;if(o.tool_choice&&(!o.tools||o.tools.length===0))throw new provider.InvalidModelRequestError({info:`Invalid model request for model : '${this.modelName}'`,cause:new Error("'tools' are required when 'tool_choice' is specified")});let a={};o.response_format&&(a.responseFormat=o.response_format.type,o.response_format.type==="json_schema"&&(a.responseSchema={name:o.response_format.json_schema.name,description:o.response_format.json_schema.description||"",strict:o.response_format.json_schema.strict,schema:o.response_format.json_schema.schema})),o.tool_choice&&(typeof o.tool_choice=="string"?a.toolChoice=o.tool_choice:a.toolChoice=o.tool_choice.function.name),a.seed=o.seed,a.maxTokens=o.max_completion_tokens,a.temperature=o.temperature,a.topP=o.top_p,a.presencePenalty=o.presence_penalty,a.frequencyPenalty=o.frequency_penalty,a.stop=o.stop,a.logProbs=o.logprobs,a.topLogProbs=o.top_logprobs;let d=types.Config().parse(provider.removeUndefinedEntries(a)),i=[],l={};o.messages.forEach(c=>{let O=c.role;switch(O){case"system":{let g=c.content;if(typeof g=="string")i.push({role:O,content:[{modality:types.TextModalityLiteral,value:g}]});else {let y=g.map(C=>({modality:types.TextModalityLiteral,value:C.text}));i.push({role:O,content:y});}}break;case"user":{let g=c.content;if(typeof g=="string")i.push({role:O,content:[{modality:types.TextModalityLiteral,value:g}]});else {let y=g.map(C=>C.type==="text"?{modality:types.TextModalityLiteral,value:C.text}:C.image_url.url.startsWith("data:")?{modality:types.ImageModalityLiteral,detail:C.image_url.detail||"auto",value:{type:types.Base64ImageContentTypeLiteral,base64:C.image_url.url,media_type:provider.getMimeTypeFromBase64(C.image_url.url)}}:{modality:types.ImageModalityLiteral,detail:C.image_url.detail||"auto",value:{type:types.UrlImageContentTypeLiteral,url:C.image_url.url}});i.push({role:O,content:y});}}break;case"assistant":{let g=[];if(!c.content&&!c.tool_calls)throw new provider.InvalidModelRequestError({info:`Invalid model request for model : '${this.modelName}'`,cause:new Error("one of'content' or 'tool_calls' must be provided")});if(c.content){let y=c.content;typeof y=="string"?g.push({modality:types.TextModalityLiteral,value:y}):y.forEach(C=>{g.push({modality:types.TextModalityLiteral,value:C.text});});}c.tool_calls&&c.tool_calls.forEach((C,E)=>{let z={modality:types.ToolCallModalityLiteral,id:C.id,index:E,name:C.function.name,arguments:C.function.arguments};g.push(z),l[z.id]=z;}),i.push({role:O,content:g});}break;case"tool":{let g=c;i.push({role:O,content:[{modality:types.ToolResponseModalityLiteral,id:g.tool_call_id,index:l[g.tool_call_id].index,name:l[g.tool_call_id].name,data:g.content}]});}break}});let h=[];return o.tools&&o.tools.forEach(c=>{h.push({type:"function",definition:{schema:{name:c.function.name,description:c.function.description||"",strict:c.function.strict,parameters:c.function.parameters}}});}),{modelName:s,config:d,messages:i,tools:h.length>0?h:void 0}}transformConfig(e,t,o){let s=e.toolChoice;delete e.toolChoice;let a=this.modelSchema.config.schema.safeParse(e);if(!a.success)throw new provider.InvalidConfigError({info:`Invalid config for model : '${this.modelName}'`,cause:a.error});let d=a.data;s!==void 0&&(d.toolChoice=s),Object.keys(d).forEach(l=>{if(!(l in this.modelSchema.config.def))throw new provider.InvalidConfigError({info:`Invalid config for model : '${this.modelName}'`,cause:new Error(`Invalid config key : '${l}',
|
|
9
|
+
[${this.embeddingModelLiterals().join(", ")}]`)});let o=this.embeddingModelFactories[t].model,s=this.embeddingModelFactories[t].modelOptions.parse(e);return new o(s)}};D.baseUrl="https://api.openai.com/v1";var _=zod.z.enum([types.SystemRoleLiteral,types.UserRoleLiteral,types.AssistantRoleLiteral,types.ToolRoleLiteral]),T={system:types.SystemRoleLiteral,user:types.UserRoleLiteral,assistant:types.AssistantRoleLiteral,tool:types.ToolRoleLiteral},H=zod.z.enum([types.UserRoleLiteral,types.AssistantRoleLiteral]),V={user:types.UserRoleLiteral,assistant:types.AssistantRoleLiteral};var P=[types.TextModalityLiteral,types.ImageModalityLiteral,types.ToolCallModalityLiteral,types.ToolResponseModalityLiteral],S=zod.z.enum([types.TextModalityLiteral,types.ImageModalityLiteral,types.ToolCallModalityLiteral,types.ToolResponseModalityLiteral]),J=[types.TextModalityLiteral],W=zod.z.enum([types.TextModalityLiteral]),I=[types.TextModalityLiteral,types.ToolCallModalityLiteral,types.ToolResponseModalityLiteral],x=zod.z.enum([types.TextModalityLiteral,types.ToolCallModalityLiteral,types.ToolResponseModalityLiteral]);var ke=zod.z.object({token:zod.z.string(),logprob:zod.z.number(),bytes:zod.z.array(zod.z.number()).nullable()}),jt=zod.z.object({content:zod.z.array(ke.extend({top_logprobs:zod.z.array(ke)})).nullable().optional(),refusal:zod.z.array(ke.extend({top_logprobs:zod.z.array(ke)})).nullable().optional()}).nullable(),yn=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()})})),Dt=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.string().nullable(),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:yn.optional(),refusal:zod.z.string().nullable().optional()}),logprobs:jt.optional(),finish_reason:zod.z.string()})),usage:zod.z.object({prompt_tokens:zod.z.number(),completion_tokens:zod.z.number(),total_tokens:zod.z.number()})}),Mn=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()})),Ft=zod.z.object({id:zod.z.string(),object:zod.z.string(),created:zod.z.number(),model:zod.z.string(),system_fingerprint:zod.z.string().nullable().optional(),choices:zod.z.array(zod.z.object({index:zod.z.number(),delta:zod.z.object({content:zod.z.string().nullable().optional(),tool_calls:Mn.optional(),refusal:zod.z.string().nullable().optional()}).or(zod.z.object({})),logprobs:jt,finish_reason:zod.z.string().nullable()})),usage:zod.z.object({prompt_tokens:zod.z.number(),completion_tokens:zod.z.number(),total_tokens:zod.z.number()}).nullable().optional()});var On=zod.z.object({type:zod.z.literal("function"),function:zod.z.object({name:zod.z.string().min(1),description:zod.z.string().min(1).optional(),strict:zod.z.boolean().optional(),parameters:zod.z.any()})}),Cn=zod.z.enum(["none","auto","required"]),bn=zod.z.object({type:zod.z.literal("function"),function:zod.z.object({name:zod.z.string().min(1)})}),Pn=zod.z.object({type:zod.z.enum(["text","json_object"])}).or(zod.z.object({type:zod.z.literal("json_schema"),json_schema:zod.z.object({name:zod.z.string().min(1),description:zod.z.string().min(1).optional(),strict:zod.z.boolean().optional(),schema:zod.z.any()})})),Ho=zod.z.object({text:zod.z.string().min(1),type:zod.z.literal("text")}),Sn=zod.z.object({type:zod.z.literal("image_url"),image_url:zod.z.object({url:zod.z.string().url().min(1),detail:zod.z.enum(["low","high","auto"]).optional()})}),In=zod.z.object({id:zod.z.string().min(1),type:zod.z.literal("function"),function:zod.z.object({name:zod.z.string().min(1),arguments:zod.z.string().min(1)})}),xn=zod.z.object({role:zod.z.literal("system"),content:zod.z.string().min(1).or(zod.z.array(Ho).min(1))}),An=zod.z.object({role:zod.z.literal("user"),content:zod.z.string().min(1).or(zod.z.array(zod.z.union([Ho,Sn])).min(1))}),En=zod.z.object({role:zod.z.literal("assistant"),content:zod.z.string().min(1).or(zod.z.array(Ho).min(1)).optional(),tool_calls:zod.z.array(In).min(1).optional()}),Rn=zod.z.object({role:zod.z.literal("tool"),tool_call_id:zod.z.string().min(1),content:zod.z.string().min(1)}),wn=zod.z.union([xn,An,En,Rn]),Le=zod.z.object({model:zod.z.string().min(1).optional(),messages:zod.z.array(wn).min(1),frequency_penalty:zod.z.number().min(-2).max(2).nullable().optional(),logprobs:zod.z.boolean().nullable().optional(),top_logprobs:zod.z.number().min(0).max(20).nullable().optional(),max_completion_tokens:zod.z.number().min(0).nullable().optional(),presence_penalty:zod.z.number().min(-2).max(2).nullable().optional(),response_format:Pn.optional(),seed:zod.z.number().nullable().optional(),stop:zod.z.string().or(zod.z.array(zod.z.string()).max(4)).nullable().optional(),temperature:zod.z.number().min(0).max(2).nullable().optional(),top_p:zod.z.number().min(0).max(1).nullable().optional(),tools:zod.z.array(On).optional(),tool_choice:Cn.or(bn).optional()});var $t=Le;var u=zod.z.object({modelName:zod.z.string(),apiKey:zod.z.string(),baseUrl:zod.z.string().url().optional(),completeChatUrl:zod.z.string().url().optional(),streamChatUrl:zod.z.string().url().optional(),organization:zod.z.string().optional()}),f=class{constructor(e,t){this.version="v1";let o=u.parse(t);this.modelSchema=e,this.modelName=o.modelName,this.apiKey=o.apiKey,this.baseUrl=provider.urlWithoutTrailingSlash(o.baseUrl||D.baseUrl),this.streamChatUrl=provider.urlWithoutTrailingSlash(o.streamChatUrl||`${this.baseUrl}/chat/completions`),this.completeChatUrl=provider.urlWithoutTrailingSlash(o.completeChatUrl||`${this.baseUrl}/chat/completions`),this.organization=o.organization;}getDefaultBaseUrl(){return this.baseUrl}getDefaultHeaders(){return M({Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},this.organization?{"OpenAI-Organization":this.organization}:{})}getDefaultParams(){return {model:this.modelName}}getRetryDelay(e){let t=i=>{let l=/(\d+)(h|m|s|ms)/g,h={h:36e5,m:6e4,s:1e3,ms:1},c,O=0;for(;(c=l.exec(i))!==null;){let g=parseInt(c[1]),y=c[2];O+=g*h[y];}return O},o=0,s=0,a=!0;e["x-ratelimit-reset-requests"]&&(o=t(e["x-ratelimit-reset-requests"])),e["x-ratelimit-reset-tokens"]&&(s=t(e["x-ratelimit-reset-tokens"]));let d=Math.max(o,s);return {shouldRetry:a,delayMs:d}}getTokenCount(e){return e.reduce((t,o)=>t+o.content.map(s=>s.modality==="text"?s.value:"").join(" ").length,0)}transformModelRequest(e){let t=Le.safeParse(e);if(!t.success)throw new provider.InvalidModelRequestError({info:"Invalid model request",cause:t.error});let o=t.data,s=o.model;if(o.tool_choice&&(!o.tools||o.tools.length===0))throw new provider.InvalidModelRequestError({info:`Invalid model request for model : '${this.modelName}'`,cause:new Error("'tools' are required when 'tool_choice' is specified")});let a={};o.response_format&&(a.responseFormat=o.response_format.type,o.response_format.type==="json_schema"&&(a.responseSchema={name:o.response_format.json_schema.name,description:o.response_format.json_schema.description||"",strict:o.response_format.json_schema.strict,schema:o.response_format.json_schema.schema})),o.tool_choice&&(typeof o.tool_choice=="string"?a.toolChoice=o.tool_choice:a.toolChoice=o.tool_choice.function.name),a.seed=o.seed,a.maxTokens=o.max_completion_tokens,a.temperature=o.temperature,a.topP=o.top_p,a.presencePenalty=o.presence_penalty,a.frequencyPenalty=o.frequency_penalty,a.stop=o.stop,a.logProbs=o.logprobs,a.topLogProbs=o.top_logprobs;let d=types.Config().parse(provider.removeUndefinedEntries(a)),i=[],l={};o.messages.forEach(c=>{let O=c.role;switch(O){case"system":{let g=c.content;if(typeof g=="string")i.push({role:O,content:[{modality:types.TextModalityLiteral,value:g}]});else {let y=g.map(C=>({modality:types.TextModalityLiteral,value:C.text}));i.push({role:O,content:y});}}break;case"user":{let g=c.content;if(typeof g=="string")i.push({role:O,content:[{modality:types.TextModalityLiteral,value:g}]});else {let y=g.map(C=>C.type==="text"?{modality:types.TextModalityLiteral,value:C.text}:C.image_url.url.startsWith("data:")?{modality:types.ImageModalityLiteral,detail:C.image_url.detail||"auto",value:{type:types.Base64ImageContentTypeLiteral,base64:C.image_url.url,media_type:provider.getMimeTypeFromBase64(C.image_url.url)}}:{modality:types.ImageModalityLiteral,detail:C.image_url.detail||"auto",value:{type:types.UrlImageContentTypeLiteral,url:C.image_url.url}});i.push({role:O,content:y});}}break;case"assistant":{let g=[];if(!c.content&&!c.tool_calls)throw new provider.InvalidModelRequestError({info:`Invalid model request for model : '${this.modelName}'`,cause:new Error("one of'content' or 'tool_calls' must be provided")});if(c.content){let y=c.content;typeof y=="string"?g.push({modality:types.TextModalityLiteral,value:y}):y.forEach(C=>{g.push({modality:types.TextModalityLiteral,value:C.text});});}c.tool_calls&&c.tool_calls.forEach((C,E)=>{let z={modality:types.ToolCallModalityLiteral,id:C.id,index:E,name:C.function.name,arguments:C.function.arguments};g.push(z),l[z.id]=z;}),i.push({role:O,content:g});}break;case"tool":{let g=c;i.push({role:O,content:[{modality:types.ToolResponseModalityLiteral,id:g.tool_call_id,index:l[g.tool_call_id].index,name:l[g.tool_call_id].name,data:g.content}]});}break}});let h=[];return o.tools&&o.tools.forEach(c=>{h.push({type:"function",definition:{schema:{name:c.function.name,description:c.function.description||"",strict:c.function.strict,parameters:c.function.parameters}}});}),{modelName:s,config:d,messages:i,tools:h.length>0?h:void 0}}transformConfig(e,t,o){let s=e.toolChoice;delete e.toolChoice;let a=this.modelSchema.config.schema.safeParse(e);if(!a.success)throw new provider.InvalidConfigError({info:`Invalid config for model : '${this.modelName}'`,cause:a.error});let d=a.data;s!==void 0&&(d.toolChoice=s),Object.keys(d).forEach(l=>{if(!(l in this.modelSchema.config.def))throw new provider.InvalidConfigError({info:`Invalid config for model : '${this.modelName}'`,cause:new Error(`Invalid config key : '${l}',
|
|
10
10
|
available keys : [${Object.keys(this.modelSchema.config.def).join(", ")}]`)})});let i=Object.keys(d).reduce((l,h)=>{let c=this.modelSchema.config.def[h],O=c.param,g=d[h];return O==="max_completion_tokens"&&c.type==="range"&&g===0?l[O]=c.max:l[O]=g,l},{});if(i.top_logprobs&&!i.logprobs)throw new provider.InvalidConfigError({info:`Invalid config for model : '${this.modelName}'`,cause:new Error("'logprobs' must be 'true' when 'top_logprobs' is specified")});if("tool_choice"in i&&i.tool_choice!==void 0){let l=i.tool_choice;if(!o||o&&o.length===0)throw new provider.InvalidConfigError({info:`Invalid config for model : '${this.modelName}'`,cause:new Error("'tools' are required when 'toolChoice' is specified")});if(o&&o.length>0){let h=this.modelSchema.config.def.toolChoice;if(!h.choices.includes(l))if(o.map(c=>c.definition.schema.name).includes(l))i.tool_choice={type:"function",function:{name:l}};else throw new provider.InvalidConfigError({info:`Invalid config for model : '${this.modelName}'`,cause:new Error(`toolChoice : '${l}' is not part of provided 'tools' names or
|
|
11
11
|
one of [${h.choices.join(", ")}]`)})}}if("response_format"in i&&i.response_format!==void 0){let l=i.response_format;if(l==="json_schema")if("response_schema"in i)i.response_format={type:"json_schema",json_schema:i.response_schema},delete i.response_schema;else throw new provider.InvalidConfigError({info:`Invalid config for model : '${this.modelName}'`,cause:new Error("'responseSchema' is required in config when 'responseFormat' is 'json_schema'")});else i.response_format={type:l};}return i}transformMessages(e){if(!e||e&&e.length===0)return {messages:[]};let t=e.map(s=>{let a=types.Message().safeParse(s);if(!a.success)throw new provider.InvalidMessagesError({info:"Invalid messages",cause:a.error});return a.data});return t.forEach(s=>{s.content.forEach(a=>{if(!this.modelSchema.modalities.includes(a.modality))throw new provider.InvalidMessagesError({info:`Invalid message content for model : '${this.modelName}'`,cause:new Error(`model : '${this.modelName}' does not support modality : '${a.modality}',
|
|
12
12
|
available modalities : [${this.modelSchema.modalities.join(", ")}]`)})});}),t.forEach(s=>{if(!Object.keys(this.modelSchema.roles).includes(s.role))throw new provider.InvalidMessagesError({info:`Invalid message content for model : '${this.modelName}'`,cause:new Error(`model : '${this.modelName}' does not support role : '${s.role}',
|