@adaline/openai 0.6.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,11 +1,19 @@
1
- import { RangeConfigItem, CONFIG, SelectBooleanConfigItem, SelectStringConfigItem, ObjectSchemaConfigItem, ChatModelSchema, EmbeddingModelSchema, MultiStringConfigItem, urlWithoutTrailingSlash, InvalidConfigError, InvalidMessagesError, InvalidToolsError, ApiResponseError, ApiRequestError, InvalidEmbeddingRequestsError } from '@adaline/provider';
2
- import { z as z$1 } from 'zod';
3
- import { SystemRoleLiteral, UserRoleLiteral, AssistantRoleLiteral, ToolRoleLiteral, TextModalityLiteral, ImageModalityLiteral, ToolCallModalityLiteral, ToolResponseModalityLiteral, EmbeddingTextModalityLiteral, EmbeddingTokenModalityLiteral, Message, Tool, createTextMessage, createToolCallMessage, EmbeddingRequests, Base64EmbeddingLiteral, FloatEmbeddingLiteral, createPartialTextMessage, createPartialToolCallMessage } from '@adaline/types';
1
+ import { z } from 'zod';
2
+ import { RangeConfigItem, CONFIG, SelectBooleanConfigItem, SelectStringConfigItem, ObjectSchemaConfigItem, ChatModelSchema, EmbeddingModelSchema, MultiStringConfigItem, urlWithoutTrailingSlash, InvalidModelRequestError, removeUndefinedEntries, InvalidConfigError, InvalidMessagesError, InvalidToolsError, ModelResponseError, InvalidEmbeddingRequestsError, ProviderError } from '@adaline/provider';
3
+ import { SystemRoleLiteral, UserRoleLiteral, AssistantRoleLiteral, ToolRoleLiteral, TextModalityLiteral, ImageModalityLiteral, ToolCallModalityLiteral, ToolResponseModalityLiteral, EmbeddingTextModalityLiteral, EmbeddingTokenModalityLiteral, Config, UrlImageContentTypeLiteral, Message, Tool, createTextMessage, createToolCallMessage, EmbeddingRequests, Base64EmbeddingLiteral, FloatEmbeddingLiteral, createPartialTextMessage, createPartialToolCallMessage } from '@adaline/types';
4
4
 
5
- var Ne=Object.defineProperty,He=Object.defineProperties;var Ke=Object.getOwnPropertyDescriptors;var oe=Object.getOwnPropertySymbols;var Ve=Object.prototype.hasOwnProperty,We=Object.prototype.propertyIsEnumerable;var Je=(l,e)=>(e=Symbol[l])?e:Symbol.for("Symbol."+l);var te=(l,e,o)=>e in l?Ne(l,e,{enumerable:!0,configurable:!0,writable:!0,value:o}):l[e]=o,h=(l,e)=>{for(var o in e||(e={}))Ve.call(e,o)&&te(l,o,e[o]);if(oe)for(var o of oe(e))We.call(e,o)&&te(l,o,e[o]);return l},E=(l,e)=>He(l,Ke(e));var k=(l,e,o)=>new Promise((a,t)=>{var n=i=>{try{m(o.next(i));}catch(p){t(p);}},r=i=>{try{m(o.throw(i));}catch(p){t(p);}},m=i=>i.done?a(i.value):Promise.resolve(i.value).then(n,r);m((o=o.apply(l,e)).next());}),Ye=function(l,e){this[0]=l,this[1]=e;},se=(l,e,o)=>{var a=(r,m,i,p)=>{try{var c=o[r](m),g=(m=c.value)instanceof Ye,b=c.done;Promise.resolve(g?m[0]:m).then(T=>g?a(r==="return"?r:"next",m[1]?{done:T.done,value:T.value}:T,i,p):i({value:T,done:b})).catch(T=>a("throw",T,i,p));}catch(T){p(T);}},t=r=>n[r]=m=>new Promise((i,p)=>a(r,m,i,p)),n={};return o=o.apply(l,e),n[Je("asyncIterator")]=()=>n,t("next"),t("throw"),t("return"),n};var U=RangeConfigItem({param:"temperature",title:CONFIG.TEMPERATURE.title,description:CONFIG.TEMPERATURE.description,min:0,max:2,step:.01,default:1}),v=l=>RangeConfigItem({param:"max_tokens",title:CONFIG.MAX_TOKENS.title,description:CONFIG.MAX_TOKENS.description,min:0,max:l,step:1,default:0}),L=l=>MultiStringConfigItem({param:"stop",title:CONFIG.STOP(l).title,description:CONFIG.STOP(l).description,max:l}),F=RangeConfigItem({param:"top_p",title:CONFIG.TOP_P.title,description:CONFIG.TOP_P.description,min:0,max:1,step:.01,default:1}),B=RangeConfigItem({param:"frequency_penalty",title:CONFIG.FREQUENCY_PENALTY.title,description:CONFIG.FREQUENCY_PENALTY.description,min:-2,max:2,step:.01,default:0}),q=RangeConfigItem({param:"presence_penalty",title:CONFIG.PRESENCE_PENALTY.title,description:CONFIG.PRESENCE_PENALTY.description,min:-2,max:2,step:.01,default: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}),D=SelectBooleanConfigItem({param:"logprobs",title:"LogProbs",description:"Whether to return log probabilities of the output tokens or not. If true, returns the log probabilities of each output token returned.",default:!1}),$=RangeConfigItem({param:"top_logprobs",title:"Top logprobs",description:"The number of most likely tokens to return at each token position, each with an associated log probability. 'logprobs' must be set to true if this parameter is used.",min:0,max:20,step:1,default:0}),G=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"]}),N=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 R=(l,e)=>z$1.object({temperature:U.schema,maxTokens:v(l).schema,stop:L(e).schema,topP:F.schema,frequencyPenalty:B.schema,presencePenalty:q.schema,seed:z.schema.transform(o=>o===0?void 0:o),logProbs:D.schema,topLogProbs:$.schema,responseFormat:G.schema,toolChoice:N.schema}),w=(l,e)=>({temperature:U.def,maxTokens:v(l).def,stop:L(e).def,topP:F.def,frequencyPenalty:B.def,presencePenalty:q.def,seed:z.def,responseFormat:G.def,logProbs:D.def,topLogProbs:$.def,toolChoice:N.def});var to=["object","array","number","string","boolean","enum"],re=z$1.enum(to),so=z$1.object({anyOf:z$1.array(z$1.any()).optional(),type:z$1.union([re,z$1.array(z$1.union([re,z$1.literal("null")]))]).optional(),default:z$1.any().optional(),title:z$1.string().optional(),description:z$1.string().max(4096).optional(),properties:z$1.record(z$1.any()).optional(),required:z$1.array(z$1.string()).optional(),minItems:z$1.number().int().min(0).optional(),maxItems:z$1.number().int().optional(),items:z$1.record(z$1.any()).optional(),enum:z$1.array(z$1.union([z$1.string(),z$1.number(),z$1.boolean(),z$1.null()])).optional(),minimum:z$1.number().optional(),maximum:z$1.number().optional(),minLength:z$1.number().int().min(0).optional(),maxLength:z$1.number().int().optional(),$ref:z$1.string().optional()}),no=z$1.object({type:z$1.enum(["object"]),required:z$1.array(z$1.string()),$defs:z$1.record(z$1.any()).optional(),properties:z$1.record(so),additionalProperties:z$1.literal(!1)}),ro=z$1.object({name:z$1.string().regex(/^[a-zA-Z0-9_]{1,64}$/).max(64),description:z$1.string().max(4096),strict:z$1.boolean().optional(),schema:no}).optional(),ae=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:ro}),ie=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"]}),me=(l,e)=>E(h({},w(l,e)),{responseFormat:ie.def,responseSchema:ae.def}),le=(l,e)=>R(l,e).extend({responseFormat:ie.schema,responseSchema:ae.schema});var H=SelectStringConfigItem({param:"encoding_format",title:"Encoding format",description:"Select the encoding format for the word embedding.",default:"float",choices:["float","base64"]}),K=RangeConfigItem({param:"dimensions",title:"Dimensions",description:"Select the number of dimensions for the word embedding.",min:1,max:1024,step:1,default:1024});var de=()=>z$1.object({encodingFormat:H.schema,dimensions:K.schema}),pe=()=>({encodingFormat:H.def,dimensions:K.def});var V={base:(l,e)=>({def:w(l,e),schema:R(l,e)}),responseSchema:(l,e)=>({def:me(l,e),schema:le(l,e)})},W={base:()=>({def:pe(),schema:de()})};var ue=z$1.enum([SystemRoleLiteral,UserRoleLiteral,AssistantRoleLiteral,ToolRoleLiteral]),ye={system:SystemRoleLiteral,user:UserRoleLiteral,assistant:AssistantRoleLiteral,tool:ToolRoleLiteral};var Me=[TextModalityLiteral,ImageModalityLiteral,ToolCallModalityLiteral,ToolResponseModalityLiteral],Ee=z$1.enum([TextModalityLiteral,ImageModalityLiteral,ToolCallModalityLiteral,ToolResponseModalityLiteral]);var x=z$1.object({token:z$1.string(),logprob:z$1.number(),bytes:z$1.array(z$1.number()).nullable()}),Oe=z$1.object({content:z$1.array(x.extend({top_logprobs:z$1.array(x)})).nullable(),refusal:z$1.array(x.extend({top_logprobs:z$1.array(x)})).nullable()}).nullable(),co=z$1.array(z$1.object({id:z$1.string().min(1),type:z$1.enum(["function"]),function:z$1.object({name:z$1.string(),arguments:z$1.string()})})),Re=z$1.object({id:z$1.string(),object:z$1.literal("chat.completion"),created:z$1.number(),model:z$1.string(),system_fingerprint:z$1.string(),choices:z$1.array(z$1.object({index:z$1.number(),message:z$1.object({role:z$1.string(),content:z$1.string().nullable().optional(),tool_calls:co.optional(),refusal:z$1.string().nullable().optional()}),logprobs:Oe,finish_reason:z$1.string()})),usage:z$1.object({prompt_tokens:z$1.number(),completion_tokens:z$1.number(),total_tokens:z$1.number()})}),ho=z$1.array(z$1.object({index:z$1.number().int(),id:z$1.string().min(1).optional(),type:z$1.enum(["function"]).optional(),function:z$1.object({name:z$1.string().min(1).optional(),arguments:z$1.string().optional()}).optional()})),we=z$1.object({id:z$1.string(),object:z$1.string(),created:z$1.number(),model:z$1.string(),system_fingerprint:z$1.string().nullable(),choices:z$1.array(z$1.object({index:z$1.number(),delta:z$1.object({content:z$1.string().nullable().optional(),tool_calls:ho.optional(),refusal:z$1.string().nullable().optional()}).or(z$1.object({})),logprobs:Oe,finish_reason:z$1.string().nullable()})),usage:z$1.object({prompt_tokens:z$1.number(),completion_tokens:z$1.number(),total_tokens:z$1.number()}).nullable().optional()});var je=z$1.object({apiKey:z$1.string(),baseUrl:z$1.string().url(),completeChatUrl:z$1.string().url().optional(),streamChatUrl:z$1.string().url().optional(),organization:z$1.string().optional()}),P=class{constructor(e,o){this.version="v1";this.modelSchema=e,this.apiKey=o.apiKey,this.baseUrl=urlWithoutTrailingSlash(o.baseUrl),this.streamChatUrl=urlWithoutTrailingSlash(o.streamChatUrl||`${this.baseUrl}/chat/completions`),this.completeChatUrl=urlWithoutTrailingSlash(o.completeChatUrl||`${this.baseUrl}/chat/completions`),this.organization=o.organization;}getTokenCount(e){return e.reduce((o,a)=>o+a.content.map(t=>t.modality==="text"?t.value:"").join(" ").length,0)}getDefaultBaseUrl(){return this.baseUrl}getDefaultHeaders(){return h({Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},this.organization?{"OpenAI-Organization":this.organization}:{})}getDefaultParams(){return {model:this.modelSchema.name}}transformConfig(e,o,a){let t=e.toolChoice;delete e.toolChoice;let n=this.modelSchema.config.schema.safeParse(e);if(!n.success)throw new InvalidConfigError({info:this.modelSchema.name,error:n.error});let r=n.data;t!==void 0&&(r.toolChoice=t),Object.keys(r).forEach(i=>{if(!(i in this.modelSchema.config.def))throw new InvalidConfigError({info:this.modelSchema.name,error:new Error(`Invalid config key: '${i}'`)})});let m=Object.keys(r).reduce((i,p)=>{let c=this.modelSchema.config.def[p],g=c.param,b=r[p];return g==="max_tokens"&&c.type==="range"&&b===0?i[g]=c.max:i[g]=b,i},{});if("tool_choice"in m&&m.tool_choice!==void 0){let i=m.tool_choice;if(!a||a&&a.length===0)throw new InvalidConfigError({info:this.modelSchema.name,error:new Error("'tools' are required when 'toolChoice' is specified")});if(a&&a.length>0){let p=this.modelSchema.config.def.toolChoice;if(!p.choices.includes(i))if(a.map(c=>c.definition.schema.name).includes(i))m.tool_choice={type:"function",function:{name:i}};else throw new InvalidConfigError({info:this.modelSchema.name,error:new Error(`Invalid 'toolChoice': '${i}' is not part of provided tools or
6
- one of '${p.choices.join(", ")}'`)})}}if("response_format"in m&&m.response_format!==void 0){let i=m.response_format;if(i==="json_schema")if("response_schema"in m)m.response_format={type:"json_schema",json_schema:m.response_schema},delete m.response_schema;else throw new InvalidConfigError({info:this.modelSchema.name,error:new Error("'responseSchema' is required in config when 'responseFormat' is 'json_schema'")});else m.response_format={type:i};}return m}transformMessages(e){if(!e||e&&e.length===0)return {messages:[]};let o=e.map(t=>{let n=Message().safeParse(t);if(!n.success)throw new InvalidMessagesError({info:this.modelSchema.name,error:n.error});return n.data});return o.forEach(t=>{t.content.forEach(n=>{if(!this.modelSchema.modalities.includes(n.modality))throw new InvalidMessagesError({info:this.modelSchema.name,error:new Error(`model: '${this.modelSchema.name}' does not support modality: '${n.modality}'`)})});}),{messages:o.map(t=>{switch(t.role){case SystemRoleLiteral:{let n=[];return t.content.forEach(r=>{if(r.modality===TextModalityLiteral)n.push({type:"text",text:r.value});else throw new InvalidMessagesError({info:this.modelSchema.name,error:new Error(`role: '${SystemRoleLiteral}' cannot have content with modality '${r.modality}'`)})}),{role:this.modelSchema.roles[t.role],content:n}}case AssistantRoleLiteral:{let n=[],r=[];return t.content.forEach(m=>{if(m.modality===TextModalityLiteral)n.push({type:"text",text:m.value});else if(m.modality===ToolCallModalityLiteral)r.push({id:m.id,type:"function",function:{name:m.name,arguments:m.arguments}});else throw new InvalidMessagesError({info:this.modelSchema.name,error:new Error(`role: '${AssistantRoleLiteral}' cannot have content with modality '${m.modality}'`)})}),h({role:this.modelSchema.roles[t.role],content:n},r.length>0?{tool_calls:r}:{})}case UserRoleLiteral:{let n=[],r=[];t.content.forEach(i=>{if(i.modality===TextModalityLiteral)n.push({type:"text",text:i.value});else if(i.modality===ImageModalityLiteral)r.push({type:"image_url",image_url:{url:i.value.type==="url"?i.value.url:i.value.base64,detail:i.detail}});else throw new InvalidMessagesError({info:this.modelSchema.name,error:new Error(`role: '${UserRoleLiteral}' cannot have content with modality '${i.modality}'`)})});let m=[...n,...r];return {role:this.modelSchema.roles[t.role],content:m}}case ToolRoleLiteral:{if(t.content.length!==1)throw new InvalidMessagesError({info:this.modelSchema.name,error:new Error(`role: '${ToolRoleLiteral}' must have exactly one content item`)});if(t.content[0].modality!==ToolResponseModalityLiteral)throw new InvalidMessagesError({info:this.modelSchema.name,error:new Error(`role: '${ToolRoleLiteral}' must have content with modality '${ToolResponseModalityLiteral}'`)});let n=t.content[0];return {role:this.modelSchema.roles[t.role],tool_call_id:n.id,content:n.data}}default:throw new InvalidMessagesError({info:this.modelSchema.name,error:new Error(`Invalid role: '${t.role}'`)})}})}}transformTools(e){return !e||e&&e.length===0?{tools:[]}:{tools:e.map(t=>{let n=Tool().safeParse(t);if(!n.success)throw new InvalidToolsError({info:this.modelSchema.name,error:n.error});return n.data}).map(t=>({type:"function",function:t.definition.schema}))}}getCompleteChatUrl(e,o,a){return this.completeChatUrl}getCompleteChatHeaders(e,o,a){return k(this,null,function*(){return new Promise(t=>{t(this.getDefaultHeaders());})})}getCompleteChatData(e,o,a){let t=this.transformConfig(e,o,a),n=this.transformMessages(o);if(n.messages&&n.messages.length===0)throw new InvalidMessagesError({info:this.modelSchema.name,error:new Error("Messages are required")});let r=a?this.transformTools(a):{};return h(h(h(h({},this.getDefaultParams()),t),n),r)}transformCompleteChatResponse(e){let o=Re.safeParse(e);if(o.success){if(o.data.choices.length===0)throw new ApiResponseError({info:this.modelSchema.name,error:new Error("No choices in response")});let a=o.data,t=[],n=a.choices[0].message;n.content&&t.push(createTextMessage(AssistantRoleLiteral,n.content)),n.refusal&&t.push(createTextMessage(AssistantRoleLiteral,n.refusal)),n.tool_calls&&n.tool_calls.forEach((p,c)=>{t.push(createToolCallMessage(AssistantRoleLiteral,c,p.id,p.function.name,p.function.arguments));});let r={promptTokens:a.usage.prompt_tokens,completionTokens:a.usage.completion_tokens,totalTokens:a.usage.total_tokens},m=[],i=a.choices[0].logprobs;return i&&(i.content&&m.push(...i.content.map(p=>({token:p.token,logProb:p.logprob,bytes:p.bytes,topLogProbs:p.top_logprobs.map(c=>({token:c.token,logProb:c.logprob,bytes:c.bytes}))}))),i.refusal&&m.push(...i.refusal.map(p=>({token:p.token,logProb:p.logprob,bytes:p.bytes,topLogProbs:p.top_logprobs.map(c=>({token:c.token,logProb:c.logprob,bytes:c.bytes}))})))),{messages:t,usage:r,logProbs:m}}throw new ApiRequestError({info:this.modelSchema.name,error:o.error})}getStreamChatUrl(e,o,a){return this.streamChatUrl}getStreamChatHeaders(e,o,a){return k(this,null,function*(){return new Promise(t=>{t(this.getDefaultHeaders());})})}getStreamChatData(e,o,a){let t=this.transformConfig(e,o,a),n=this.transformMessages(o);if(n.messages&&n.messages.length===0)throw new InvalidMessagesError({info:this.modelSchema.name,error:new Error("Messages are required")});let r=a?this.transformTools(a):{};return h(h(h(h({stream:!0,stream_options:{include_usage:!0}},this.getDefaultParams()),t),n),r)}transformStreamChatResponseChunk(e,o){return se(this,null,function*(){var t,n;let a=(o+e).split(`
7
- `).filter(r=>r.trim()!=="");for(let r of a){if(r==="data: [DONE]")return;if(r.startsWith("data: {")&&r.endsWith("}")){let m;try{m=JSON.parse(r.substring(6));}catch(p){throw new ApiResponseError({info:this.modelSchema.name,error:new Error(`malformed JSON received in stream : ${r}`)})}let i=we.safeParse(m);if(i.success){let p={partialMessages:[]},c=i.data;if(c.choices.length>0){let g=c.choices[0].delta;if(g!==void 0&&Object.keys(g).length!==0){if("content"in g&&g.content!==null)p.partialMessages.push(createPartialTextMessage(AssistantRoleLiteral,g.content));else if("refusal"in g&&g.refusal!==null)p.partialMessages.push(createPartialTextMessage(AssistantRoleLiteral,g.refusal));else if("tool_calls"in g&&g.tool_calls!==void 0){let b=g.tool_calls.at(0);p.partialMessages.push(createPartialToolCallMessage(AssistantRoleLiteral,b.index,b.id,(t=b.function)==null?void 0:t.name,(n=b.function)==null?void 0:n.arguments));}}}c.usage&&(p.usage={promptTokens:c.usage.prompt_tokens,completionTokens:c.usage.completion_tokens,totalTokens:c.usage.total_tokens}),yield {partialResponse:p,buffer:o};}else throw new ApiResponseError({info:this.modelSchema.name,error:i.error})}}})}};var Eo="gpt-4o",Oo="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.",X=ChatModelSchema(ue,Ee).parse({name:Eo,description:Oo,maxInputTokens:128e3,maxOutputTokens:128e3,roles:ye,modalities:Me,config:{def:V.base(128e3,4).def,schema:V.base(128e3,4).schema}}),ke=je,_=class extends P{constructor(e){super(X,e);}};var Le=[EmbeddingTextModalityLiteral,EmbeddingTokenModalityLiteral],Fe=z$1.enum([EmbeddingTextModalityLiteral,EmbeddingTokenModalityLiteral]);var Be=z$1.object({object:z$1.literal("list"),model:z$1.string(),data:z$1.array(z$1.object({index:z$1.number(),object:z$1.literal("embedding"),embedding:z$1.array(z$1.number()).or(z$1.string().base64())})),usage:z$1.object({prompt_tokens:z$1.number().nonnegative(),total_tokens:z$1.number().nonnegative()})});var De=z$1.object({apiKey:z$1.string(),baseUrl:z$1.string().url(),getEmbeddingsUrl:z$1.string().url().optional()}),I=class{constructor(e,o){this.version="v1";this.getDefaultBaseUrl=()=>this.baseUrl;this.getDefaultHeaders=()=>({Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"});this.getDefaultParams=()=>({model:this.modelSchema.name});this.getTokenCount=e=>e.requests.reduce((o,a)=>o+a.length,0);this.transformConfig=(e,o)=>{let a=this.modelSchema.config.schema.safeParse(e);if(!a.success)throw new InvalidConfigError({info:this.modelSchema.name,error:a.error});let t=a.data;return Object.keys(t).forEach(r=>{if(!this.modelSchema.config.def[r])throw new InvalidConfigError({info:this.modelSchema.name,error:new Error(`Invalid config key: '${r}'`)})}),Object.keys(t).reduce((r,m)=>{let p=this.modelSchema.config.def[m].param,c=t[m];return r[p]=c,r},{})};this.transformEmbeddingRequests=e=>{let o=EmbeddingRequests().safeParse(e);if(!o.success)throw new InvalidEmbeddingRequestsError({info:this.modelSchema.name,error:o.error});return {input:o.data.requests}};this.getGetEmbeddingsUrl=(e,o)=>this.getEmbeddingsUrl;this.getGetEmbeddingsHeaders=(e,o)=>this.getDefaultHeaders();this.getGetEmbeddingsData=(e,o)=>h(h(h({},this.getDefaultParams()),this.transformConfig(e,o)),this.transformEmbeddingRequests(o));this.transformGetEmbeddingsResponse=e=>{let o,a=Be.safeParse(e);if(a.success){let t=a.data;o=typeof t.data[0].embedding=="string"?Base64EmbeddingLiteral:FloatEmbeddingLiteral;let n=t.data.map(r=>typeof r.embedding=="string"?{index:r.index,embedding:r.embedding}:{index:r.index,embedding:r.embedding});return {encodingFormat:o,embeddings:n,usage:{totalTokens:t.usage.total_tokens}}}throw new ApiRequestError({info:this.modelSchema.name,error:a.error})};this.modelSchema=e,this.apiKey=o.apiKey,this.baseUrl=urlWithoutTrailingSlash(o.baseUrl),this.getEmbeddingsUrl=urlWithoutTrailingSlash(o.getEmbeddingsUrl||`${this.baseUrl}/embeddings`);}};var jo="text-embedding-ada-002",ko="some description",ee=EmbeddingModelSchema(Fe).parse({name:jo,description:ko,modalities:Le,maxInputTokens:8192,maxOutputTokens:8192,config:{def:W.base().def,schema:W.base().schema}}),$e=De,j=class extends I{constructor(e){super(ee,e);}};var Uo="openai",Ge=class{constructor(){this.version="v1";this.name=Uo;this.baseUrl="https://api.openai.com/v1";this.chatModelFactories={"gpt-4o":{model:_,modelOptions:ke,modelSchema:X}};this.embeddingModelFactories={"text-embedding-ada-002":{model:j,modelOptions:$e,modelSchema:ee}};}chatModelLiterals(){return Object.keys(this.chatModelFactories)}chatModel(e,o){var r;if(!(e in this.chatModelFactories))throw new Error(`Model ${e} not found`);let a=this.chatModelFactories[e].model,t=E(h({},o),{baseUrl:(r=o.baseUrl)!=null?r:this.baseUrl}),n=this.chatModelFactories[e].modelOptions.parse(t);return new a(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){var r;if(!(e in this.embeddingModelFactories))throw new Error(`Model ${e} not found`);let a=this.embeddingModelFactories[e].model,t=E(h({},o),{baseUrl:(r=o.baseUrl)!=null?r:this.baseUrl}),n=this.embeddingModelFactories[e].modelOptions.parse(t);return new a(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),{})}};
5
+ var et=Object.defineProperty,tt=Object.defineProperties;var ot=Object.getOwnPropertyDescriptors;var de=Object.getOwnPropertySymbols;var nt=Object.prototype.hasOwnProperty,st=Object.prototype.propertyIsEnumerable;var at=(p,e)=>(e=Symbol[p])?e:Symbol.for("Symbol."+p);var ce=(p,e,o)=>e in p?et(p,e,{enumerable:!0,configurable:!0,writable:!0,value:o}):p[e]=o,y=(p,e)=>{for(var o in e||(e={}))nt.call(e,o)&&ce(p,o,e[o]);if(de)for(var o of de(e))st.call(e,o)&&ce(p,o,e[o]);return p},x=(p,e)=>tt(p,ot(e));var R=(p,e,o)=>new Promise((t,n)=>{var i=l=>{try{r(o.next(l));}catch(c){n(c);}},s=l=>{try{r(o.throw(l));}catch(c){n(c);}},r=l=>l.done?t(l.value):Promise.resolve(l.value).then(i,s);r((o=o.apply(p,e)).next());}),rt=function(p,e){this[0]=p,this[1]=e;},ue=(p,e,o)=>{var t=(s,r,l,c)=>{try{var d=o[s](r),h=(r=d.value)instanceof rt,f=d.done;Promise.resolve(h?r[0]:r).then(g=>h?t(s==="return"?s:"next",r[1]?{done:g.done,value:g.value}:g,l,c):l({value:g,done:f})).catch(g=>t("throw",g,l,c));}catch(g){c(g);}},n=s=>i[s]=r=>new Promise((l,c)=>t(s,r,l,c)),i={};return o=o.apply(p,e),i[at("asyncIterator")]=()=>i,n("next"),n("throw"),n("return"),i};var B=RangeConfigItem({param:"temperature",title:CONFIG.TEMPERATURE.title,description:CONFIG.TEMPERATURE.description,min:0,max:2,step:.01,default:1}),N=p=>RangeConfigItem({param:"max_tokens",title:CONFIG.MAX_TOKENS.title,description:CONFIG.MAX_TOKENS.description,min:0,max:p,step:1,default:0}),G=p=>MultiStringConfigItem({param:"stop",title:CONFIG.STOP(p).title,description:CONFIG.STOP(p).description,max:p}),K=RangeConfigItem({param:"top_p",title:CONFIG.TOP_P.title,description:CONFIG.TOP_P.description,min:0,max:1,step:.01,default:1}),V=RangeConfigItem({param:"frequency_penalty",title:CONFIG.FREQUENCY_PENALTY.title,description:CONFIG.FREQUENCY_PENALTY.description,min:-2,max:2,step:.01,default:0}),H=RangeConfigItem({param:"presence_penalty",title:CONFIG.PRESENCE_PENALTY.title,description:CONFIG.PRESENCE_PENALTY.description,min:-2,max:2,step:.01,default:0}),J=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}),W=SelectBooleanConfigItem({param:"logprobs",title:"LogProbs",description:"Whether to return log probabilities of the output tokens or not. If true, returns the log probabilities of each output token returned.",default:!1}),Y=RangeConfigItem({param:"top_logprobs",title:"Top logprobs",description:"The number of most likely tokens to return at each token position, each with an associated log probability. 'logprobs' must be set to true if this parameter is used.",min:0,max:20,step:1,default: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"]}),Q=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 q=(p,e)=>z.object({temperature:B.schema,maxTokens:N(p).schema,stop:G(e).schema,topP:K.schema,frequencyPenalty:V.schema,presencePenalty:H.schema,seed:J.schema.transform(o=>o===0?void 0:o),logProbs:W.schema,topLogProbs:Y.schema,responseFormat:Z.schema,toolChoice:Q.schema}),w=(p,e)=>({temperature:B.def,maxTokens:N(p).def,stop:G(e).def,topP:K.def,frequencyPenalty:V.def,presencePenalty:H.def,seed:J.def,responseFormat:Z.def,logProbs:W.def,topLogProbs:Y.def,toolChoice:Q.def});var ct=["object","array","number","string","boolean","enum"],fe=z.enum(ct),ut=z.object({anyOf:z.array(z.any()).optional(),type:z.union([fe,z.array(z.union([fe,z.literal("null")]))]).optional(),default:z.any().optional(),title:z.string().optional(),description:z.string().max(4096).optional(),properties:z.record(z.any()).optional(),required:z.array(z.string()).optional(),minItems:z.number().int().min(0).optional(),maxItems:z.number().int().optional(),items:z.record(z.any()).optional(),enum:z.array(z.union([z.string(),z.number(),z.boolean(),z.null()])).optional(),minimum:z.number().optional(),maximum:z.number().optional(),minLength:z.number().int().min(0).optional(),maxLength:z.number().int().optional(),$ref:z.string().optional()}),ht=z.object({type:z.enum(["object"]),required:z.array(z.string()),$defs:z.record(z.any()).optional(),properties:z.record(ut),additionalProperties:z.literal(!1)}),ft=z.object({name:z.string().regex(/^[a-zA-Z0-9_]{1,64}$/).max(64),description:z.string().max(4096),strict:z.boolean().optional(),schema:ht}).optional(),ge=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:ft}),ye=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"]}),be=(p,e)=>x(y({},w(p,e)),{responseFormat:ye.def,responseSchema:ge.def}),Te=(p,e)=>q(p,e).extend({responseFormat:ye.schema,responseSchema:ge.schema});var X=SelectStringConfigItem({param:"encoding_format",title:"Encoding format",description:"Select the encoding format for the word embedding.",default:"float",choices:["float","base64"]}),ee=RangeConfigItem({param:"dimensions",title:"Dimensions",description:"Select the number of dimensions for the word embedding.",min:1,max:1024,step:1,default:1024});var Ce=()=>z.object({encodingFormat:X.schema,dimensions:ee.schema}),Me=()=>({encodingFormat:X.def,dimensions:ee.def});var te={base:(p,e)=>({def:w(p,e),schema:q(p,e)}),responseSchema:(p,e)=>({def:be(p,e),schema:Te(p,e)})},oe={base:()=>({def:Me(),schema:Ce()})};var Se=z.enum([SystemRoleLiteral,UserRoleLiteral,AssistantRoleLiteral,ToolRoleLiteral]),Ae={system:SystemRoleLiteral,user:UserRoleLiteral,assistant:AssistantRoleLiteral,tool:ToolRoleLiteral};var Pe=[TextModalityLiteral,ImageModalityLiteral,ToolCallModalityLiteral,ToolResponseModalityLiteral],je=z.enum([TextModalityLiteral,ImageModalityLiteral,ToolCallModalityLiteral,ToolResponseModalityLiteral]);var P=z.object({token:z.string(),logprob:z.number(),bytes:z.array(z.number()).nullable()}),ve=z.object({content:z.array(P.extend({top_logprobs:z.array(P)})).nullable(),refusal:z.array(P.extend({top_logprobs:z.array(P)})).nullable()}).nullable(),Mt=z.array(z.object({id:z.string().min(1),type:z.enum(["function"]),function:z.object({name:z.string(),arguments:z.string()})})),ke=z.object({id:z.string(),object:z.literal("chat.completion"),created:z.number(),model:z.string(),system_fingerprint:z.string(),choices:z.array(z.object({index:z.number(),message:z.object({role:z.string(),content:z.string().nullable().optional(),tool_calls:Mt.optional(),refusal:z.string().nullable().optional()}),logprobs:ve,finish_reason:z.string()})),usage:z.object({prompt_tokens:z.number(),completion_tokens:z.number(),total_tokens:z.number()})}),Rt=z.array(z.object({index:z.number().int(),id:z.string().min(1).optional(),type:z.enum(["function"]).optional(),function:z.object({name:z.string().min(1).optional(),arguments:z.string().optional()}).optional()})),Ue=z.object({id:z.string(),object:z.string(),created:z.number(),model:z.string(),system_fingerprint:z.string().nullable(),choices:z.array(z.object({index:z.number(),delta:z.object({content:z.string().nullable().optional(),tool_calls:Rt.optional(),refusal:z.string().nullable().optional()}).or(z.object({})),logprobs:ve,finish_reason:z.string().nullable()})),usage:z.object({prompt_tokens:z.number(),completion_tokens:z.number(),total_tokens:z.number()}).nullable().optional()});var Ot=z.object({type:z.literal("function"),function:z.object({name:z.string().min(1),description:z.string().min(1).optional(),strict:z.boolean().optional(),parameters:z.any()})}),It=z.enum(["none","auto","required"]),Et=z.object({type:z.literal("function"),function:z.object({name:z.string().min(1)})}),St=z.object({type:z.enum(["text","json_object"])}).or(z.object({type:z.literal("json_schema"),json_schema:z.object({name:z.string().min(1),description:z.string().min(1).optional(),strict:z.boolean().optional(),schema:z.any()})})),ne=z.object({text:z.string().min(1),type:z.literal("text")}),At=z.object({type:z.literal("image_url"),image_url:z.object({url:z.string().url().min(1),detail:z.enum(["low","high","auto"]).optional()})}),xt=z.object({id:z.string().min(1),type:z.literal("function"),function:z.object({name:z.string().min(1),arguments:z.string().min(1)})}),_t=z.object({role:z.literal("system"),content:z.string().min(1).or(z.array(ne).min(1))}),qt=z.object({role:z.literal("user"),content:z.string().min(1).or(z.array(z.union([ne,At])).min(1))}),wt=z.object({role:z.literal("assistant"),content:z.string().min(1).or(z.array(ne).min(1)).optional(),tool_calls:z.array(xt).min(1).optional()}).refine(p=>!(!p.content&&!p.tool_calls),{message:"one of 'content' or 'tool_calls' must be provided",path:["content","tool_calls"]}),Pt=z.object({role:z.literal("tool"),tool_call_id:z.string().min(1),content:z.string().min(1)}),jt=z.union([_t,qt,wt,Pt]),Fe=z.object({model:z.string().min(1).optional(),messages:z.array(jt).min(1).optional(),frequency_penalty:z.number().min(-2).max(2).nullable().optional(),logprobs:z.boolean().nullable().optional(),top_logprobs:z.number().min(0).max(20).nullable().optional(),max_tokens:z.number().min(0).nullable().optional(),presence_penalty:z.number().min(-2).max(2).nullable().optional(),response_format:St.optional(),seed:z.number().nullable().optional(),stop:z.string().or(z.array(z.string()).max(4)).nullable().optional(),temperature:z.number().min(0).max(2).nullable().optional(),top_p:z.number().min(0).max(1).nullable().optional(),tools:z.array(Ot).optional(),tool_choice:It.or(Et).optional()}).refine(p=>!(p.tool_choice&&(!p.tools||p.tools.length===0)),{message:"'tools' must be provided if 'tool_choice' is provided",path:["tools"]});var re=z.object({apiKey:z.string(),baseUrl:z.string().url(),completeChatUrl:z.string().url().optional(),streamChatUrl:z.string().url().optional(),organization:z.string().optional()}),k=class{constructor(e,o){this.version="v1";let t=re.parse(o);this.modelSchema=e,this.apiKey=t.apiKey,this.baseUrl=urlWithoutTrailingSlash(t.baseUrl),this.streamChatUrl=urlWithoutTrailingSlash(t.streamChatUrl||`${this.baseUrl}/chat/completions`),this.completeChatUrl=urlWithoutTrailingSlash(t.completeChatUrl||`${this.baseUrl}/chat/completions`),this.organization=t.organization;}getDefaultBaseUrl(){return this.baseUrl}getDefaultHeaders(){return y({Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},this.organization?{"OpenAI-Organization":this.organization}:{})}getDefaultParams(){return {model:this.modelSchema.name}}getRetryDelay(e){let o=r=>{let l=/(\d+)(h|m|s|ms)/g,c={h:36e5,m:6e4,s:1e3,ms:1},d,h=0;for(;(d=l.exec(r))!==null;){let f=parseInt(d[1]),g=d[2];h+=f*c[g];}return h},t=0,n=0,i=!0;e["x-ratelimit-reset-requests"]&&(t=o(e["x-ratelimit-reset-requests"])),e["x-ratelimit-reset-tokens"]&&(n=o(e["x-ratelimit-reset-tokens"]));let s=Math.max(t,n);return {shouldRetry:i,delayMs:s}}getTokenCount(e){return e.reduce((o,t)=>o+t.content.map(n=>n.modality==="text"?n.value:"").join(" ").length,0)}transformModelRequest(e){let o=Fe.safeParse(e);if(!o.success)throw new InvalidModelRequestError({info:"Invalid model request",cause:o.error});let t=o.data,n=t.model,i={seed:t.seed,maxTokens:t.max_tokens,temperature:t.temperature,topP:t.top_p,presencePenalty:t.presence_penalty,frequencyPenalty:t.frequency_penalty,stop:t.stop,logProbs:t.logprobs,topLogProbs:t.top_logprobs,toolChoice:t.tool_choice,responseFormat:t.response_format},s=Config().parse(removeUndefinedEntries(i));s.responseFormat&&s.responseFormat.type==="json_schema"&&!s.responseFormat.json_schema&&(s.responseSchema={name:s.responseFormat.json_schema.name,description:s.responseFormat.json_schema.description||"",strict:s.responseFormat.json_schema.strict,schema:s.responseFormat.json_schema.parameters});let r=[],l={};t.messages&&t.messages.forEach(d=>{let h=d.role;switch(h){case"system":{let f=d.content;if(typeof f=="string")r.push({role:h,content:[{modality:TextModalityLiteral,value:f}]});else {let g=f.map(T=>({modality:TextModalityLiteral,value:T.text}));r.push({role:h,content:g});}}break;case"user":{let f=d.content;if(typeof f=="string")r.push({role:h,content:[{modality:TextModalityLiteral,value:f}]});else {let g=f.map(T=>T.type==="text"?{modality:TextModalityLiteral,value:T.text}:{modality:ImageModalityLiteral,detail:T.image_url.detail||"auto",value:{type:UrlImageContentTypeLiteral,url:T.image_url.url}});r.push({role:h,content:g});}}break;case"assistant":{let f=[];if(d.content){let g=d.content;typeof g=="string"?f.push({modality:TextModalityLiteral,value:g}):g.forEach(T=>{f.push({modality:TextModalityLiteral,value:T.text});});}d.tool_calls&&d.tool_calls.forEach((T,Xe)=>{let D={modality:ToolCallModalityLiteral,id:T.id,index:Xe,name:T.function.name,arguments:T.function.arguments};f.push(D),l[D.id]=D;}),r.push({role:h,content:f});}break;case"tool":{let f=d;r.push({role:h,content:[{modality:ToolResponseModalityLiteral,id:f.tool_call_id,index:l[f.tool_call_id].index,name:l[f.tool_call_id].name,data:f.content}]});}break}});let c=[];return t.tools&&t.tools.forEach(d=>{c.push({type:"function",definition:{schema:{name:d.function.name,description:d.function.description||"",strict:d.function.strict,parameters:d.function.parameters}}});}),{modelName:n,config:s,messages:r,tools:c}}transformConfig(e,o,t){let n=e.toolChoice;delete e.toolChoice;let i=this.modelSchema.config.schema.safeParse(e);if(!i.success)throw new InvalidConfigError({info:`Invalid config for model : '${this.modelSchema.name}'`,cause:i.error});let s=i.data;n!==void 0&&(s.toolChoice=n),Object.keys(s).forEach(l=>{if(!(l in this.modelSchema.config.def))throw new InvalidConfigError({info:`Invalid config for model : '${this.modelSchema.name}'`,cause:new Error(`Invalid config key : '${l}',
6
+ available keys : [${Object.keys(this.modelSchema.config.def).join(", ")}]`)})});let r=Object.keys(s).reduce((l,c)=>{let d=this.modelSchema.config.def[c],h=d.param,f=s[c];return h==="max_tokens"&&d.type==="range"&&f===0?l[h]=d.max:l[h]=f,l},{});if("tool_choice"in r&&r.tool_choice!==void 0){let l=r.tool_choice;if(!t||t&&t.length===0)throw new InvalidConfigError({info:`Invalid config for model : '${this.modelSchema.name}'`,cause:new Error("'tools' are required when 'toolChoice' is specified")});if(t&&t.length>0){let c=this.modelSchema.config.def.toolChoice;if(!c.choices.includes(l))if(t.map(d=>d.definition.schema.name).includes(l))r.tool_choice={type:"function",function:{name:l}};else throw new InvalidConfigError({info:`Invalid config for model : '${this.modelSchema.name}'`,cause:new Error(`toolChoice : '${l}' is not part of provided 'tools' names or
7
+ one of [${c.choices.join(", ")}]`)})}}if("response_format"in r&&r.response_format!==void 0){let l=r.response_format;if(l==="json_schema")if("response_schema"in r)r.response_format={type:"json_schema",json_schema:r.response_schema},delete r.response_schema;else throw new InvalidConfigError({info:`Invalid config for model : '${this.modelSchema.name}'`,cause:new Error("'responseSchema' is required in config when 'responseFormat' is 'json_schema'")});else r.response_format={type:l};}return r}transformMessages(e){if(!e||e&&e.length===0)return {messages:[]};let o=e.map(n=>{let i=Message().safeParse(n);if(!i.success)throw new InvalidMessagesError({info:"Invalid messages",cause:i.error});return i.data});return o.forEach(n=>{n.content.forEach(i=>{if(!this.modelSchema.modalities.includes(i.modality))throw new InvalidMessagesError({info:`Invalid message content for model : '${this.modelSchema.name}'`,cause:new Error(`model : '${this.modelSchema.name}' does not support modality : '${i.modality}',
8
+ available modalities : [${this.modelSchema.modalities.join(", ")}]`)})});}),{messages:o.map(n=>{switch(n.role){case SystemRoleLiteral:{let i=[];return n.content.forEach(s=>{if(s.modality===TextModalityLiteral)i.push({type:"text",text:s.value});else throw new InvalidMessagesError({info:`Invalid message 'role' and 'modality' combination for model : ${this.modelSchema.name}`,cause:new Error(`role : '${n.role}' cannot have content with modality : '${s.modality}'`)})}),{role:this.modelSchema.roles[n.role],content:i}}case AssistantRoleLiteral:{let i=[],s=[];return n.content.forEach(r=>{if(r.modality===TextModalityLiteral)i.push({type:"text",text:r.value});else if(r.modality===ToolCallModalityLiteral)s.push({id:r.id,type:"function",function:{name:r.name,arguments:r.arguments}});else throw new InvalidMessagesError({info:`Invalid message 'role' and 'modality' combination for model : ${this.modelSchema.name}`,cause:new Error(`role : '${n.role}' cannot have content with modality : '${r.modality}'`)})}),y({role:this.modelSchema.roles[n.role],content:i},s.length>0?{tool_calls:s}:{})}case UserRoleLiteral:{let i=[],s=[];n.content.forEach(l=>{if(l.modality===TextModalityLiteral)i.push({type:"text",text:l.value});else if(l.modality===ImageModalityLiteral)s.push({type:"image_url",image_url:{url:l.value.type==="url"?l.value.url:l.value.base64,detail:l.detail}});else throw new InvalidMessagesError({info:`Invalid message 'role' and 'modality' combination for model : ${this.modelSchema.name}`,cause:new Error(`role : '${n.role}' cannot have content with modality : '${l.modality}'`)})});let r=[...i,...s];return {role:this.modelSchema.roles[n.role],content:r}}case ToolRoleLiteral:{if(n.content.length!==1)throw new InvalidMessagesError({info:`Invalid message for role : '${n.role}'`,cause:new Error(`role : '${n.role}' must have exactly one content item`)});if(n.content[0].modality!==ToolResponseModalityLiteral)throw new InvalidMessagesError({info:`Invalid message 'role' and 'modality' combination for model : ${this.modelSchema.name}`,cause:new Error(`role : '${n.role}' must have content with modality : '${ToolResponseModalityLiteral}'`)});let i=n.content[0];return {role:this.modelSchema.roles[n.role],tool_call_id:i.id,content:i.data}}default:throw new InvalidMessagesError({info:`Invalid message 'role' for model : ${this.modelSchema.name}`,cause:new Error(`role : '${n.role}' is not supported,
9
+ available roles : [${Object.keys(this.modelSchema.roles).join(", ")}]`)})}})}}transformTools(e){if(!this.modelSchema.modalities.includes(ToolCallModalityLiteral))throw new InvalidToolsError({info:`Invalid tool 'modality' for model : ${this.modelSchema.name}`,cause:new Error(`model : '${this.modelSchema.name}' does not support tool modality : '${ToolCallModalityLiteral}'`)});return !e||e&&e.length===0?{tools:[]}:{tools:e.map(n=>{let i=Tool().safeParse(n);if(!i.success)throw new InvalidToolsError({info:"Invalid tools",cause:i.error});return i.data}).map(n=>({type:"function",function:n.definition.schema}))}}getCompleteChatUrl(e,o,t){return R(this,null,function*(){return new Promise(n=>{n(this.completeChatUrl);})})}getCompleteChatHeaders(e,o,t){return R(this,null,function*(){return new Promise(n=>{n(this.getDefaultHeaders());})})}getCompleteChatData(e,o,t){return R(this,null,function*(){let n=this.transformConfig(e,o,t),i=this.transformMessages(o);if(i.messages&&i.messages.length===0)throw new InvalidMessagesError({info:"Messages are required",cause:new Error("Messages are required")});let s=t?this.transformTools(t):{};return new Promise(r=>{r(y(y(y(y({},this.getDefaultParams()),n),i),s));})})}transformCompleteChatResponse(e){let o=ke.safeParse(e);if(o.success){if(o.data.choices.length===0)throw new ModelResponseError({info:"Invalid response from model",cause:new Error(`No choices in response : ${JSON.stringify(o.data)}`)});let t=o.data,n=[],i=t.choices[0].message;i.content&&n.push(createTextMessage(AssistantRoleLiteral,i.content)),i.refusal&&n.push(createTextMessage(AssistantRoleLiteral,i.refusal)),i.tool_calls&&i.tool_calls.forEach((c,d)=>{n.push(createToolCallMessage(AssistantRoleLiteral,d,c.id,c.function.name,c.function.arguments));});let s={promptTokens:t.usage.prompt_tokens,completionTokens:t.usage.completion_tokens,totalTokens:t.usage.total_tokens},r=[],l=t.choices[0].logprobs;return l&&(l.content&&r.push(...l.content.map(c=>({token:c.token,logProb:c.logprob,bytes:c.bytes,topLogProbs:c.top_logprobs.map(d=>({token:d.token,logProb:d.logprob,bytes:d.bytes}))}))),l.refusal&&r.push(...l.refusal.map(c=>({token:c.token,logProb:c.logprob,bytes:c.bytes,topLogProbs:c.top_logprobs.map(d=>({token:d.token,logProb:d.logprob,bytes:d.bytes}))})))),{messages:n,usage:s,logProbs:r}}throw new ModelResponseError({info:"Invalid response from model",cause:o.error})}getStreamChatUrl(e,o,t){return R(this,null,function*(){return new Promise(n=>{n(this.streamChatUrl);})})}getStreamChatHeaders(e,o,t){return R(this,null,function*(){return new Promise(n=>{n(this.getDefaultHeaders());})})}getStreamChatData(e,o,t){return R(this,null,function*(){let n=this.transformConfig(e,o,t),i=this.transformMessages(o);if(i.messages&&i.messages.length===0)throw new InvalidMessagesError({info:"Messages are required",cause:new Error("Messages are required")});let s=t?this.transformTools(t):{};return new Promise(r=>{r(y(y(y(y({stream:!0,stream_options:{include_usage:!0}},this.getDefaultParams()),n),i),s));})})}transformStreamChatResponseChunk(e,o){return ue(this,null,function*(){var n,i;let t=(o+e).split(`
10
+ `).filter(s=>s.trim()!=="");for(let s of t){if(s==="data: [DONE]")return;if(s.startsWith("data: {")&&s.endsWith("}")){let r;try{r=JSON.parse(s.substring(6));}catch(c){throw new ModelResponseError({info:"Malformed JSON received in stream",cause:new Error(`Malformed JSON received in stream : ${r}`)})}let l=Ue.safeParse(r);if(l.success){let c={partialMessages:[]},d=l.data;if(d.choices.length>0){let h=d.choices[0].delta;if(h!==void 0&&Object.keys(h).length!==0){if("content"in h&&h.content!==null)c.partialMessages.push(createPartialTextMessage(AssistantRoleLiteral,h.content));else if("refusal"in h&&h.refusal!==null)c.partialMessages.push(createPartialTextMessage(AssistantRoleLiteral,h.refusal));else if("tool_calls"in h&&h.tool_calls!==void 0){let f=h.tool_calls.at(0);c.partialMessages.push(createPartialToolCallMessage(AssistantRoleLiteral,f.index,f.id,(n=f.function)==null?void 0:n.name,(i=f.function)==null?void 0:i.arguments));}}}d.usage&&(c.usage={promptTokens:d.usage.prompt_tokens,completionTokens:d.usage.completion_tokens,totalTokens:d.usage.total_tokens}),yield {partialResponse:c,buffer:o};}else throw new ModelResponseError({info:"Invalid response from model",cause:l.error})}}})}};var Vt="gpt-4o",Ht="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.",ie=ChatModelSchema(Se,je).parse({name:Vt,description:Ht,maxInputTokens:128e3,maxOutputTokens:128e3,roles:Ae,modalities:Pe,config:{def:te.base(128e3,4).def,schema:te.base(128e3,4).schema}}),Be=re,U=class extends k{constructor(e){super(ie,e);}};var Ke=[EmbeddingTextModalityLiteral,EmbeddingTokenModalityLiteral],Ve=z.enum([EmbeddingTextModalityLiteral,EmbeddingTokenModalityLiteral]);var He=z.object({object:z.literal("list"),model:z.string(),data:z.array(z.object({index:z.number(),object:z.literal("embedding"),embedding:z.array(z.number()).or(z.string().base64())})),usage:z.object({prompt_tokens:z.number().nonnegative(),total_tokens:z.number().nonnegative()})});var Wt=z.string().min(1).or(z.array(z.string().min(1)).min(1)).or(z.array(z.number().int().nonnegative()).min(1)).or(z.array(z.array(z.number().int().nonnegative()).min(1)).min(1)),Je=z.object({model:z.string().min(1).optional(),input:Wt.optional(),encoding_format:z.enum(["float","base64"]).optional(),dimensions:z.number().int().min(1).optional()});var me=z.object({apiKey:z.string(),baseUrl:z.string().url(),getEmbeddingsUrl:z.string().url().optional()}),$=class{constructor(e,o){this.version="v1";let t=me.parse(o);this.modelSchema=e,this.apiKey=t.apiKey,this.baseUrl=urlWithoutTrailingSlash(t.baseUrl),this.getEmbeddingsUrl=urlWithoutTrailingSlash(t.getEmbeddingsUrl||`${this.baseUrl}/embeddings`);}getDefaultBaseUrl(){return this.baseUrl}getDefaultHeaders(){return {Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"}}getDefaultParams(){return {model:this.modelSchema.name}}getRetryDelay(e){let o=r=>{let l=/(\d+)(h|m|s|ms)/g,c={h:36e5,m:6e4,s:1e3,ms:1},d,h=0;for(;(d=l.exec(r))!==null;){let f=parseInt(d[1]),g=d[2];h+=f*c[g];}return h},t=0,n=0,i=!0;e["x-ratelimit-reset-requests"]&&(t=o(e["x-ratelimit-reset-requests"])),e["x-ratelimit-reset-tokens"]&&(n=o(e["x-ratelimit-reset-tokens"]));let s=Math.max(t,n);return {shouldRetry:i,delayMs:s}}getTokenCount(e){return e.requests.reduce((o,t)=>o+t.length,0)}transformModelRequest(e){let o=Je.safeParse(e);if(!o.success)throw new InvalidModelRequestError({info:"Invalid model request",cause:o.error});let t=o.data,n=t.model,i={encodingFormat:t.encoding_format,dimensions:t.dimensions},s=Config().parse(removeUndefinedEntries(i)),r,l;return t.input&&(typeof t.input=="string"?l=EmbeddingTextModalityLiteral:typeof t.input[0]=="string"?l=EmbeddingTextModalityLiteral:l=EmbeddingTokenModalityLiteral,l===EmbeddingTextModalityLiteral?typeof t.input=="string"?r={modality:l,requests:[t.input]}:r={modality:l,requests:t.input}:typeof t.input[0]=="number"?r={modality:l,requests:[t.input]}:r={modality:l,requests:t.input}),{modelName:n,config:s,embeddingRequests:r}}transformConfig(e,o){let t=this.modelSchema.config.schema.safeParse(e);if(!t.success)throw new InvalidConfigError({info:`Invalid config for model : '${this.modelSchema.name}'`,cause:t.error});let n=t.data;return Object.keys(n).forEach(s=>{if(!this.modelSchema.config.def[s])throw new InvalidConfigError({info:`Invalid config for model : '${this.modelSchema.name}'`,cause:new Error(`Invalid config key : '${s}',
11
+ available keys : [${Object.keys(this.modelSchema.config.def).join(", ")}]`)})}),Object.keys(n).reduce((s,r)=>{let c=this.modelSchema.config.def[r].param,d=n[r];return s[c]=d,s},{})}transformEmbeddingRequests(e){let o=EmbeddingRequests().safeParse(e);if(!o.success)throw new InvalidEmbeddingRequestsError({info:"Invalid embedding requests",cause:o.error});return {input:o.data.requests}}getGetEmbeddingsUrl(e,o){return R(this,null,function*(){return new Promise(t=>{t(this.getEmbeddingsUrl);})})}getGetEmbeddingsHeaders(e,o){return R(this,null,function*(){return new Promise(t=>{t(this.getDefaultHeaders());})})}getGetEmbeddingsData(e,o){return R(this,null,function*(){return new Promise(t=>{t(y(y(y({},this.getDefaultParams()),this.transformConfig(e,o)),this.transformEmbeddingRequests(o)));})})}transformGetEmbeddingsResponse(e){let o,t=He.safeParse(e);if(t.success){let n=t.data;o=typeof n.data[0].embedding=="string"?Base64EmbeddingLiteral:FloatEmbeddingLiteral;let i=n.data.map(s=>typeof s.embedding=="string"?{index:s.index,embedding:s.embedding}:{index:s.index,embedding:s.embedding});return {encodingFormat:o,embeddings:i,usage:{totalTokens:n.usage.total_tokens}}}throw new ModelResponseError({info:"Invalid response from model",cause:t.error})}};var ro="text-embedding-ada-002",io="some description",pe=EmbeddingModelSchema(Ve).parse({name:ro,description:io,modalities:Ke,maxInputTokens:8192,maxOutputTokens:8192,config:{def:oe.base().def,schema:oe.base().schema}}),Ze=me,L=class extends ${constructor(e){super(pe,e);}};var lo="openai",Qe=class{constructor(){this.version="v1";this.name=lo;this.baseUrl="https://api.openai.com/v1";this.chatModelFactories={"gpt-4o":{model:U,modelOptions:Be,modelSchema:ie}};this.embeddingModelFactories={"text-embedding-ada-002":{model:L,modelOptions:Ze,modelSchema:pe}};}chatModelLiterals(){return Object.keys(this.chatModelFactories)}chatModel(e,o){var s;if(!(e in this.chatModelFactories))throw new ProviderError({info:`OpenAI chat model: ${e} not found`,cause:new Error(`OpenAI chat model: ${e} not found, available chat models:
12
+ ${this.chatModelLiterals().join(", ")}`)});let t=this.chatModelFactories[e].model,n=x(y({},o),{baseUrl:(s=o.baseUrl)!=null?s:this.baseUrl}),i=this.chatModelFactories[e].modelOptions.parse(n);return new t(i)}chatModelSchema(e){if(!(e in this.chatModelFactories))throw new ProviderError({info:`OpenAI chat model: ${e} not found`,cause:new Error(`OpenAI chat model: ${e} not found, available chat models:
13
+ ${this.chatModelLiterals().join(", ")}`)});return this.chatModelFactories[e].modelSchema}chatModelSchemas(){return Object.keys(this.chatModelFactories).reduce((e,o)=>(e[o]=this.chatModelFactories[o].modelSchema,e),{})}embeddingModelLiterals(){return Object.keys(this.embeddingModelFactories)}embeddingModel(e,o){var s;if(!(e in this.embeddingModelFactories))throw new ProviderError({info:`OpenAI embedding model: ${e} not found`,cause:new Error(`OpenAI embedding model: ${e} not found, available embedding models:
14
+ ${this.embeddingModelLiterals().join(", ")}`)});let t=this.embeddingModelFactories[e].model,n=x(y({},o),{baseUrl:(s=o.baseUrl)!=null?s:this.baseUrl}),i=this.embeddingModelFactories[e].modelOptions.parse(n);return new t(i)}embeddingModelSchema(e){if(!(e in this.embeddingModelFactories))throw new ProviderError({info:`OpenAI embedding model: ${e} not found`,cause:new Error(`OpenAI embedding model: ${e} not found, available embedding models:
15
+ ${this.embeddingModelLiterals().join(", ")}`)});return this.embeddingModelFactories[e].modelSchema}embeddingModelSchemas(){return Object.keys(this.embeddingModelFactories).reduce((e,o)=>(e[o]=this.embeddingModelFactories[o].modelSchema,e),{})}};
8
16
 
9
- export { P as BaseChatModel, je as BaseChatModelOptions, w as BaseConfigDef, R as BaseConfigSchema, I as BaseEmbeddingModel, De as BaseEmbeddingModelOptions, pe as BaseWordEmbeddingConfigDef, de as BaseWordEmbeddingConfigSchema, _ as GPT4o, ke as GPT4oOptions, X as GPT4oSchema, Ge as OpenAI, Me as OpenAIChatModelModalities, Ee as OpenAIChatModelModalitiesEnum, ue as OpenAIChatModelRoles, ye as OpenAIChatModelRolesMap, Re as OpenAICompleteChatResponse, V as OpenAIConfigs, Le as OpenAIEmbeddingModelModalities, Fe as OpenAIEmbeddingModelModalitiesEnum, Be as OpenAIGetEmbeddingsResponse, we as OpenAIStreamChatResponse, co as OpenAIToolCallsCompleteChatResponse, ho as OpenAIToolCallsStreamChatResponse, W as OpenAIWordEmbeddingConfigs, Uo as ProviderLiteral, me as ResponseSchemaConfigDef, le as ResponseSchemaConfigSchema, j as TextEmbeddingAda002, $e as TextEmbeddingAda002Options, ee as TextEmbeddingAda002Schema, K as dimensions, H as encodingFormat, B as frequencyPenalty, D as logProbs, v as maxTokens, q as presencePenalty, G as responseFormat, z as seed, L as stop, U as temperature, N as toolChoice, $ as topLogProbs, F as topP };
17
+ export { k as BaseChatModel, re as BaseChatModelOptions, $ as BaseEmbeddingModel, me as BaseEmbeddingModelOptions, w as ChatModelBaseConfigDef, q as ChatModelBaseConfigSchema, be as ChatModelResponseSchemaConfigDef, Te as ChatModelResponseSchemaConfigSchema, Me as EmbeddingModelBaseConfigDef, Ce as EmbeddingModelBaseConfigSchema, U as GPT4o, Be as GPT4oOptions, ie as GPT4oSchema, Qe as OpenAI, te as OpenAIChatModelConfigs, Pe as OpenAIChatModelModalities, je as OpenAIChatModelModalitiesEnum, Se as OpenAIChatModelRoles, Ae as OpenAIChatModelRolesMap, Fe as OpenAIChatRequest, wt as OpenAIChatRequestAssistantMessage, At as OpenAIChatRequestImageContent, jt as OpenAIChatRequestMessage, St as OpenAIChatRequestResponseFormat, _t as OpenAIChatRequestSystemMessage, ne as OpenAIChatRequestTextContent, Ot as OpenAIChatRequestTool, xt as OpenAIChatRequestToolCallContent, It as OpenAIChatRequestToolChoiceEnum, Et as OpenAIChatRequestToolChoiceFunction, Pt as OpenAIChatRequestToolMessage, qt as OpenAIChatRequestUserMessage, ke as OpenAICompleteChatResponse, oe as OpenAIEmbeddingModelConfigs, Ke as OpenAIEmbeddingModelModalities, Ve as OpenAIEmbeddingModelModalitiesEnum, Je as OpenAIEmbeddingRequest, Wt as OpenAIEmbeddingRequestInput, He as OpenAIGetEmbeddingsResponse, Ue as OpenAIStreamChatResponse, Mt as OpenAIToolCallsCompleteChatResponse, Rt as OpenAIToolCallsStreamChatResponse, lo as ProviderLiteral, L as TextEmbeddingAda002, Ze as TextEmbeddingAda002Options, pe as TextEmbeddingAda002Schema, ee as dimensions, X as encodingFormat, V as frequencyPenalty, W as logProbs, N as maxTokens, H as presencePenalty, Z as responseFormat, J as seed, G as stop, B as temperature, Q as toolChoice, Y as topLogProbs, K as topP };
10
18
  //# sourceMappingURL=index.mjs.map
11
19
  //# sourceMappingURL=index.mjs.map