@adaline/openai
Version:
Adaline OpenAI
15 lines (14 loc) • 75.7 kB
JavaScript
import { z } from 'zod';
import { RangeConfigItem, CHAT_CONFIG, SelectBooleanConfigItem, SelectStringConfigItem, ObjectSchemaConfigItem, ChatModelSchema, EmbeddingModelSchema, MultiStringConfigItem, ProviderError, urlWithoutTrailingSlash, InvalidModelRequestError, removeUndefinedEntries, getMimeTypeFromBase64, InvalidConfigError, InvalidMessagesError, InvalidToolsError, ModelResponseError, InvalidEmbeddingRequestsError } from '@adaline/provider';
import { ResponseSchema, SystemRoleLiteral, UserRoleLiteral, AssistantRoleLiteral, ToolRoleLiteral, TextModalityLiteral, ImageModalityLiteral, ToolCallModalityLiteral, ToolResponseModalityLiteral, EmbeddingTextModalityLiteral, EmbeddingTokenModalityLiteral, Config, Base64ImageContentTypeLiteral, UrlImageContentTypeLiteral, Message, Tool, createTextContent, createToolCallContent, EmbeddingRequests, Base64EmbeddingLiteral, FloatEmbeddingLiteral, createPartialTextMessage, createPartialToolCallMessage } from '@adaline/types';
var Ns=Object.defineProperty,qs=Object.defineProperties;var zs=Object.getOwnPropertyDescriptors;var dn=Object.getOwnPropertySymbols;var Us=Object.prototype.hasOwnProperty,Bs=Object.prototype.propertyIsEnumerable;var ye=(i,e)=>(e=Symbol[i])?e:Symbol.for("Symbol."+i),js=i=>{throw TypeError(i)};var cn=(i,e,n)=>e in i?Ns(i,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):i[e]=n,b=(i,e)=>{for(var n in e||(e={}))Us.call(e,n)&&cn(i,n,e[n]);if(dn)for(var n of dn(e))Bs.call(e,n)&&cn(i,n,e[n]);return i},q=(i,e)=>qs(i,zs(e));var k=(i,e,n)=>new Promise((o,t)=>{var s=p=>{try{l(n.next(p));}catch(_){t(_);}},r=p=>{try{l(n.throw(p));}catch(_){t(_);}},l=p=>p.done?o(p.value):Promise.resolve(p.value).then(s,r);l((n=n.apply(i,e)).next());}),un=function(i,e){this[0]=i,this[1]=e;},ie=(i,e,n)=>{var o=(r,l,p,_)=>{try{var f=n[r](l),I=(l=f.value)instanceof un,P=f.done;Promise.resolve(I?l[0]:l).then(S=>I?o(r==="return"?r:"next",l[1]?{done:S.done,value:S.value}:S,p,_):p({value:S,done:P})).catch(S=>o("throw",S,p,_));}catch(S){_(S);}},t=r=>s[r]=l=>new Promise((p,_)=>o(r,l,p,_)),s={};return n=n.apply(i,e),s[ye("asyncIterator")]=()=>s,t("next"),t("throw"),t("return"),s},Me=i=>{var e=i[ye("asyncIterator")],n=!1,o,t={};return e==null?(e=i[ye("iterator")](),o=s=>t[s]=r=>e[s](r)):(e=e.call(i),o=s=>t[s]=r=>{if(n){if(n=!1,s==="throw")throw r;return r}return n=!0,{done:!1,value:new un(new Promise(l=>{var p=e[s](r);p instanceof Object||js("Object expected"),l(p);}),1)}}),t[ye("iterator")]=()=>t,o("next"),"throw"in e?o("throw"):t.throw=s=>{throw s},"return"in e&&o("return"),t};var $o=RangeConfigItem({param:"temperature",title:CHAT_CONFIG.TEMPERATURE.title,description:CHAT_CONFIG.TEMPERATURE.description,min:0,max:2,step:.01,default:1}),Fo=i=>RangeConfigItem({param:"max_completion_tokens",title:CHAT_CONFIG.MAX_TOKENS.title,description:CHAT_CONFIG.MAX_TOKENS.description,min:0,max:i,step:1,default:0}),Ho=i=>MultiStringConfigItem({param:"stop",title:CHAT_CONFIG.STOP(i).title,description:CHAT_CONFIG.STOP(i).description,max:i}),Vo=RangeConfigItem({param:"top_p",title:CHAT_CONFIG.TOP_P.title,description:CHAT_CONFIG.TOP_P.description,min:0,max:1,step:.01,default:1}),Ko=RangeConfigItem({param:"frequency_penalty",title:CHAT_CONFIG.FREQUENCY_PENALTY.title,description:CHAT_CONFIG.FREQUENCY_PENALTY.description,min:-2,max:2,step:.01,default:0}),Jo=RangeConfigItem({param:"presence_penalty",title:CHAT_CONFIG.PRESENCE_PENALTY.title,description:CHAT_CONFIG.PRESENCE_PENALTY.description,min:-2,max:2,step:.01,default:0}),Wo=RangeConfigItem({param:"seed",title:CHAT_CONFIG.SEED.title,description:CHAT_CONFIG.SEED.description,min:0,max:1e6,step:1,default:0}),Yo=SelectBooleanConfigItem({param:"logprobs",title:CHAT_CONFIG.LOG_PROBS.title,description:CHAT_CONFIG.LOG_PROBS.description,default:!1}),Qo=RangeConfigItem({param:"top_logprobs",title:CHAT_CONFIG.TOP_LOG_PROBS.title,description:CHAT_CONFIG.TOP_LOG_PROBS.description,min:0,max:20,step:1,default:0}),Xo=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"]}),Zo=SelectStringConfigItem({param:"reasoning_effort",title:"Reasoning Effort",description:"Controls the depth of the model's reasoning before delivering an answer. 'minimal' prioritizes speed, 'high' engages in deep reasoning.",default:"medium",choices:["minimal","low","medium","high"]}),et=SelectStringConfigItem({param:"verbosity",title:"Verbosity",description:"Controls the length and detail of the model's responses, independent of reasoning depth. 'low' generates concise answers, 'high' provides comprehensive responses.",default:"medium",choices:["low","medium","high"]});var Y=(i,e)=>z.object({temperature:$o.schema,maxTokens:Fo(i).schema,stop:Ho(e).schema,topP:Vo.schema,frequencyPenalty:Ko.schema,presencePenalty:Jo.schema,seed:Wo.schema.transform(n=>n===0?void 0:n),logProbs:Yo.schema,topLogProbs:Qo.schema,toolChoice:Xo.schema}),Q=(i,e)=>({temperature:$o.def,maxTokens:Fo(i).def,stop:Ho(e).def,topP:Vo.def,frequencyPenalty:Ko.def,presencePenalty:Jo.def,seed:Wo.def,logProbs:Yo.def,topLogProbs:Qo.def,toolChoice:Xo.def});var hn=ObjectSchemaConfigItem({param:"response_schema",title:CHAT_CONFIG.RESPONSE_SCHEMA.title,description:CHAT_CONFIG.RESPONSE_SCHEMA.description,objectSchema:ResponseSchema}),fn=SelectStringConfigItem({param:"response_format",title:CHAT_CONFIG.RESPONSE_FORMAT_WITH_SCHEMA.title,description:CHAT_CONFIG.RESPONSE_FORMAT_WITH_SCHEMA.description,default:"text",choices:["text","json_object","json_schema"]}),ee=(i,e)=>q(b({},Q(i,e)),{responseFormat:fn.def,responseSchema:hn.def}),oe=(i,e)=>Y(i,e).extend({responseFormat:fn.schema,responseSchema:hn.schema});var gn=(i,e)=>q(b({},Q(i,e)),{reasoningEffort:Zo.def,verbosity:et.def,responseFormat:ee(i,e).responseFormat,responseSchema:ee(i,e).responseSchema}),_n=(i,e)=>Y(i,e).extend({reasoningEffort:Zo.schema,verbosity:et.schema,responseFormat:oe(i,e).shape.responseFormat,responseSchema:oe(i,e).shape.responseSchema});var yn=RangeConfigItem({param:"temperature",title:CHAT_CONFIG.TEMPERATURE.title,description:CHAT_CONFIG.TEMPERATURE.description,min:1,max:1,step:.01,default:1}),Mn=SelectStringConfigItem({param:"reasoning_effort",title:"Reasoning Effort",description:"Constrains effort on reasoning for reasoning models. Reducing reasoning effort can result in faster responses and fewer tokens used on reasoning in a response.",default:"medium",choices:["low","medium","high"]}),Cn=(i,e)=>q(b({},ee(i,e)),{temperature:yn.def,reasoningEffort:Mn.def}),On=(i,e)=>oe(i,e).extend({temperature:yn.schema,reasoningEffort:Mn.schema});var bn=SelectStringConfigItem({param:"response_format",title:CHAT_CONFIG.RESPONSE_FORMAT.title,description:CHAT_CONFIG.RESPONSE_FORMAT.description,default:"text",choices:["text","json_object"]}),xn=(i,e)=>q(b({},Q(i,e)),{responseFormat:bn.def}),Sn=(i,e)=>Y(i,e).extend({responseFormat:bn.schema});var ot=SelectStringConfigItem({param:"encoding_format",title:"Encoding format",description:"Select the encoding format for the word embedding.",default:"float",choices:["float","base64"]}),tt=i=>RangeConfigItem({param:"dimensions",title:"Dimensions",description:"Select the number of dimensions for the word embedding.",min:1,max:i,step:1,default:i});var Oe=()=>z.object({encodingFormat:ot.schema}),Pe=()=>({encodingFormat:ot.def});var In=i=>Oe().extend({dimensions:tt(i).schema}),Rn=i=>q(b({},Pe()),{dimensions:tt(i).def});var a={base:(i,e)=>({def:Q(i,e),schema:Y(i,e)}),responseFormat:(i,e)=>({def:xn(i,e),schema:Sn(i,e)}),responseSchema:(i,e)=>({def:ee(i,e),schema:oe(i,e)}),oSeries:(i,e)=>({def:Cn(i,e),schema:On(i,e)}),gpt5:(i,e)=>({def:gn(i,e),schema:_n(i,e)})},K={base:()=>({def:Pe(),schema:Oe()}),dimensions:i=>({def:Rn(i),schema:In(i)})};var g={"gpt-3.5-turbo-0125":{modelName:"gpt-3.5-turbo-0125",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:.5,outputPricePerMillion:1.5}}}]},"gpt-3.5-turbo-1106":{modelName:"gpt-3.5-turbo-1106",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:.5,outputPricePerMillion:1.5}}}]},"gpt-3.5-turbo":{modelName:"gpt-3.5-turbo",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:.5,outputPricePerMillion:1.5}}}]},"gpt-4-0125-preview":{modelName:"gpt-4-0125-preview",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:30,outputPricePerMillion:60}}}]},"gpt-4-0613":{modelName:"gpt-4-0613",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:30,outputPricePerMillion:60}}}]},"gpt-4-1106-preview":{modelName:"gpt-4-1106-preview",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:30,outputPricePerMillion:60}}}]},"gpt-4-turbo-2024-04-09":{modelName:"gpt-4-turbo-2024-04-09",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:10,outputPricePerMillion:30}}}]},"gpt-4-turbo-preview":{modelName:"gpt-4-turbo-preview",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:10,outputPricePerMillion:30}}}]},"gpt-4-turbo":{modelName:"gpt-4-turbo",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:10,outputPricePerMillion:30}}}]},"gpt-4":{modelName:"gpt-4",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:30,outputPricePerMillion:60}}}]},"gpt-4o-2024-05-13":{modelName:"gpt-4o-2024-05-13",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:5,outputPricePerMillion:20}}}]},"gpt-4o-2024-08-06":{modelName:"gpt-4o-2024-08-06",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:2.5,outputPricePerMillion:10}}}]},"gpt-4o-mini-2024-07-18":{modelName:"gpt-4o-mini-2024-07-18",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:.6,outputPricePerMillion:2.4}}}]},"gpt-4o-mini":{modelName:"gpt-4o-mini",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:.6,outputPricePerMillion:2.4}}}]},"gpt-4o":{modelName:"gpt-4o",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:5,outputPricePerMillion:20}}}]},"o1-2024-12-17":{modelName:"o1-2024-12-17",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:15,outputPricePerMillion:60}}}]},o1:{modelName:"o1",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:15,outputPricePerMillion:60}}}]},"o3-mini-2025-01-31":{modelName:"o3-mini-2025-01-31",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:1.1,outputPricePerMillion:4.4}}}]},"o3-mini":{modelName:"o3-mini",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:1.1,outputPricePerMillion:4.4}}}]},"o3-2025-04-16":{modelName:"o3-2025-04-16",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:10,outputPricePerMillion:40}}}]},o3:{modelName:"o3",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:10,outputPricePerMillion:40}}}]},"o4-mini-2025-04-16":{modelName:"o4-mini-2025-04-16",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:1.1,outputPricePerMillion:4.4}}}]},"o4-mini":{modelName:"o4-mini",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:1.1,outputPricePerMillion:4.4}}}]},"gpt-4.1":{modelName:"gpt-4.1",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:2,outputPricePerMillion:8}}}]},"gpt-4.1-mini":{modelName:"gpt-4.1-mini",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:.4,outputPricePerMillion:1.6}}}]},"gpt-4.1-nano":{modelName:"gpt-4.1-nano",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:.1,outputPricePerMillion:.4}}}]},"gpt-5":{modelName:"gpt-5",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:1.25,outputPricePerMillion:10}}}]},"gpt-5-mini":{modelName:"gpt-5-mini",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:.25,outputPricePerMillion:2}}}]},"gpt-5-nano":{modelName:"gpt-5-nano",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:.05,outputPricePerMillion:.4}}}]},"gpt-5-chat-latest":{modelName:"gpt-5-chat-latest",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:1.25,outputPricePerMillion:10}}}]},"gpt-5.1":{modelName:"gpt-5.1",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:1.5,outputPricePerMillion:12}}}]},"gpt-5.2":{modelName:"gpt-5.2",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:1.75,outputPricePerMillion:14}}}]},"gpt-5.2-chat-latest":{modelName:"gpt-5.2-chat-latest",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:1.75,outputPricePerMillion:14}}}]},"gpt-5.2-pro":{modelName:"gpt-5.2-pro",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:21,outputPricePerMillion:168}}}]}};var ti="openai",J=class{constructor(){this.version="v1";this.name=ti;this.chatModelFactories={[Re]:{model:Ae,modelOptions:kn,modelSchema:it},[be]:{model:xe,modelOptions:En,modelSchema:nt},[Se]:{model:Ie,modelOptions:Gn,modelSchema:st},[Ee]:{model:Ge,modelOptions:wn,modelSchema:at},[ke]:{model:we,modelOptions:vn,modelSchema:rt},[ve]:{model:Le,modelOptions:Ln,modelSchema:lt},[De]:{model:Ne,modelOptions:Dn,modelSchema:pt},[qe]:{model:ze,modelOptions:Nn,modelSchema:mt},[Ue]:{model:Be,modelOptions:qn,modelSchema:dt},[Ye]:{model:Qe,modelOptions:$n,modelSchema:gt},[je]:{model:$e,modelOptions:zn,modelSchema:ct},[Fe]:{model:He,modelOptions:Un,modelSchema:ut},[Je]:{model:We,modelOptions:jn,modelSchema:ft},[Ve]:{model:Ke,modelOptions:Bn,modelSchema:ht},[Xe]:{model:Ze,modelOptions:Fn,modelSchema:_t},[eo]:{model:oo,modelOptions:Hn,modelSchema:Tt},[to]:{model:no,modelOptions:Vn,modelSchema:yt},[so]:{model:io,modelOptions:Kn,modelSchema:Mt},[ao]:{model:ro,modelOptions:Jn,modelSchema:Ct},[lo]:{model:po,modelOptions:Wn,modelSchema:Ot},[mo]:{model:co,modelOptions:Yn,modelSchema:Pt},[fo]:{model:go,modelOptions:Xn,modelSchema:xt},[yo]:{model:Mo,modelOptions:es,modelSchema:It},[Co]:{model:Oo,modelOptions:os,modelSchema:Rt},[_o]:{model:To,modelOptions:Zn,modelSchema:St},[uo]:{model:ho,modelOptions:Qn,modelSchema:bt},[xo]:{model:So,modelOptions:ns,modelSchema:Et},[Po]:{model:bo,modelOptions:ts,modelSchema:At},[Nt]:{model:Eo,modelOptions:rs,modelSchema:qt},[Lt]:{model:Ao,modelOptions:as,modelSchema:Dt},[Gt]:{model:Io,modelOptions:ss,modelSchema:kt},[wt]:{model:Ro,modelOptions:is,modelSchema:vt},[zt]:{model:Go,modelOptions:ls,modelSchema:Ut},[Bt]:{model:ko,modelOptions:ps,modelSchema:jt}};this.embeddingModelFactories={[$t]:{model:wo,modelOptions:ms,modelSchema:Ft},[Ht]:{model:vo,modelOptions:ds,modelSchema:Vt},[Kt]:{model:Lo,modelOptions:cs,modelSchema:Jt}};}chatModelLiterals(){return Object.keys(this.chatModelFactories)}chatModelSchemas(){return Object.keys(this.chatModelFactories).reduce((e,n)=>(e[n]=this.chatModelFactories[n].modelSchema,e),{})}chatModel(e){let n=e.modelName;if(!(n in this.chatModelFactories))throw new ProviderError({info:`OpenAI chat model: ${n} not found`,cause:new Error(`OpenAI chat model: ${n} not found, available chat models:
[${this.chatModelLiterals().join(", ")}]`)});let o=this.chatModelFactories[n].model,t=this.chatModelFactories[n].modelOptions.parse(e);return new o(t)}embeddingModelLiterals(){return Object.keys(this.embeddingModelFactories)}embeddingModelSchemas(){return Object.keys(this.embeddingModelFactories).reduce((e,n)=>(e[n]=this.embeddingModelFactories[n].modelSchema,e),{})}embeddingModel(e){let n=e.modelName;if(!(n in this.embeddingModelFactories))throw new ProviderError({info:`OpenAI embedding model: ${n} not found`,cause:new Error(`OpenAI embedding model: ${n} not found, available embedding models:
[${this.embeddingModelLiterals().join(", ")}]`)});let o=this.embeddingModelFactories[n].model,t=this.embeddingModelFactories[n].modelOptions.parse(e);return new o(t)}};J.baseUrl="https://api.openai.com/v1";var d=z.enum([SystemRoleLiteral,UserRoleLiteral,AssistantRoleLiteral,ToolRoleLiteral]),c={system:SystemRoleLiteral,user:UserRoleLiteral,assistant:AssistantRoleLiteral,tool:ToolRoleLiteral};var y=[TextModalityLiteral,ImageModalityLiteral,ToolCallModalityLiteral,ToolResponseModalityLiteral],M=z.enum([TextModalityLiteral,ImageModalityLiteral,ToolCallModalityLiteral,ToolResponseModalityLiteral]),fl=[TextModalityLiteral],gl=z.enum([TextModalityLiteral]),w=[TextModalityLiteral,ToolCallModalityLiteral,ToolResponseModalityLiteral],v=z.enum([TextModalityLiteral,ToolCallModalityLiteral,ToolResponseModalityLiteral]);var qo=z.object({token:z.string(),logprob:z.number(),bytes:z.array(z.number()).nullable()}),Ts=z.object({content:z.array(qo.extend({top_logprobs:z.array(qo)})).nullable().optional(),refusal:z.array(qo.extend({top_logprobs:z.array(qo)})).nullable().optional()}).nullable(),si=z.array(z.object({id:z.string().min(1),type:z.enum(["function"]),function:z.object({name:z.string(),arguments:z.string()})})),ys=z.object({id:z.string(),object:z.literal("chat.completion"),created:z.number(),model:z.string(),system_fingerprint:z.string().nullable(),choices:z.array(z.object({index:z.number(),message:z.object({role:z.string(),content:z.string().nullable().optional(),tool_calls:si.optional(),refusal:z.string().nullable().optional()}),logprobs:Ts.optional(),finish_reason:z.string()})),usage:z.object({prompt_tokens:z.number(),completion_tokens:z.number(),total_tokens:z.number()})}),ii=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()})),Ms=z.object({id:z.string(),object:z.string(),created:z.number(),model:z.string(),system_fingerprint:z.string().nullable().optional(),choices:z.array(z.object({index:z.number(),delta:z.object({content:z.string().nullable().optional(),tool_calls:ii.optional(),refusal:z.string().nullable().optional()}).or(z.object({})),logprobs:Ts.optional(),finish_reason:z.string().nullable()})),usage:z.object({prompt_tokens:z.number(),completion_tokens:z.number(),total_tokens:z.number()}).nullable().optional()});var ai=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()})}),ri=z.enum(["none","auto","required"]),li=z.object({type:z.literal("function"),function:z.object({name:z.string().min(1)})}),pi=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()})})),Yt=z.object({text:z.string().min(1),type:z.literal("text")}),mi=z.object({type:z.literal("image_url"),image_url:z.object({url:z.string().url().min(1),detail:z.enum(["low","high","auto"]).optional()})}),di=z.object({id:z.string().min(1),type:z.literal("function"),function:z.object({name:z.string().min(1),arguments:z.string().min(1)})}),ci=z.object({role:z.literal("system"),content:z.string().min(1).or(z.array(Yt).min(1))}),ui=z.object({role:z.literal("user"),content:z.string().min(1).or(z.array(z.union([Yt,mi])).min(1))}),hi=z.object({role:z.literal("assistant"),content:z.string().min(1).or(z.array(Yt).min(1)).optional(),tool_calls:z.array(di).min(1).optional()}),fi=z.object({role:z.literal("tool"),tool_call_id:z.string().min(1),content:z.string().min(1)}),gi=z.union([ci,ui,hi,fi]),Cs=z.object({model:z.string().min(1).optional(),messages:z.array(gi).min(1),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_completion_tokens:z.number().min(0).nullable().optional(),presence_penalty:z.number().min(-2).max(2).nullable().optional(),response_format:pi.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(ai).optional(),tool_choice:ri.or(li).optional(),reasoning_effort:z.enum(["minimal","low","medium","high"]).optional(),verbosity:z.enum(["low","medium","high"]).optional()});var h=z.object({modelName:z.string(),apiKey:z.string(),baseUrl:z.string().url().optional(),completeChatUrl:z.string().url().optional(),streamChatUrl:z.string().url().optional(),organization:z.string().optional()}),u=class{constructor(e,n){this.version="v1";let o=h.parse(n);this.modelSchema=e,this.modelName=o.modelName,this.apiKey=o.apiKey,this.baseUrl=urlWithoutTrailingSlash(o.baseUrl||J.baseUrl),this.streamChatUrl=urlWithoutTrailingSlash(o.streamChatUrl||`${this.baseUrl}/chat/completions`),this.completeChatUrl=urlWithoutTrailingSlash(o.completeChatUrl||`${this.baseUrl}/chat/completions`),this.organization=o.organization;}getDefaultBaseUrl(){return this.baseUrl}getDefaultHeaders(){return b({Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},this.organization?{"OpenAI-Organization":this.organization}:{})}getDefaultParams(){return {model:this.modelName}}getRetryDelay(e){let n=l=>{let p=/(\d+)(h|m|s|ms)/g,_={h:36e5,m:6e4,s:1e3,ms:1},f,I=0;for(;(f=p.exec(l))!==null;){let P=parseInt(f[1]),S=f[2];I+=P*_[S];}return I},o=0,t=0,s=!0;e["x-ratelimit-reset-requests"]&&(o=n(e["x-ratelimit-reset-requests"])),e["x-ratelimit-reset-tokens"]&&(t=n(e["x-ratelimit-reset-tokens"]));let r=Math.max(o,t);return {shouldRetry:s,delayMs:r}}getTokenCount(e){return e.reduce((n,o)=>n+o.content.map(t=>t.modality==="text"?t.value:"").join(" ").length,0)}transformModelRequest(e){let n=Cs.safeParse(e);if(!n.success)throw new InvalidModelRequestError({info:"Invalid model request",cause:n.error});let o=n.data,t=o.model;if(o.tool_choice&&(!o.tools||o.tools.length===0))throw new InvalidModelRequestError({info:`Invalid model request for model : '${this.modelName}'`,cause:new Error("'tools' are required when 'tool_choice' is specified")});let s={};o.response_format&&(s.responseFormat=o.response_format.type,o.response_format.type==="json_schema"&&(s.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"?s.toolChoice=o.tool_choice:s.toolChoice=o.tool_choice.function.name),s.seed=o.seed,s.maxTokens=o.max_completion_tokens,s.temperature=o.temperature,s.topP=o.top_p,s.presencePenalty=o.presence_penalty,s.frequencyPenalty=o.frequency_penalty,s.stop=o.stop,s.logProbs=o.logprobs,s.topLogProbs=o.top_logprobs,s.reasoningEffort=o.reasoning_effort,s.verbosity=o.verbosity;let r=Config().parse(removeUndefinedEntries(s)),l=[],p={};o.messages.forEach(f=>{let I=f.role;switch(I){case"system":{let P=f.content;if(typeof P=="string")l.push({role:I,content:[{modality:TextModalityLiteral,value:P}]});else {let S=P.map(R=>({modality:TextModalityLiteral,value:R.text}));l.push({role:I,content:S});}}break;case"user":{let P=f.content;if(typeof P=="string")l.push({role:I,content:[{modality:TextModalityLiteral,value:P}]});else {let S=P.map(R=>R.type==="text"?{modality:TextModalityLiteral,value:R.text}:R.image_url.url.startsWith("data:")?{modality:ImageModalityLiteral,detail:R.image_url.detail||"auto",value:{type:Base64ImageContentTypeLiteral,base64:R.image_url.url,mediaType:getMimeTypeFromBase64(R.image_url.url)}}:{modality:ImageModalityLiteral,detail:R.image_url.detail||"auto",value:{type:UrlImageContentTypeLiteral,url:R.image_url.url}});l.push({role:I,content:S});}}break;case"assistant":{let P=[];if(!f.content&&!f.tool_calls)throw new InvalidModelRequestError({info:`Invalid model request for model : '${this.modelName}'`,cause:new Error("one of'content' or 'tool_calls' must be provided")});if(f.content){let S=f.content;typeof S=="string"?P.push({modality:TextModalityLiteral,value:S}):S.forEach(R=>{P.push({modality:TextModalityLiteral,value:R.text});});}f.tool_calls&&f.tool_calls.forEach((R,L)=>{let x={modality:ToolCallModalityLiteral,id:R.id,index:L,name:R.function.name,arguments:R.function.arguments};P.push(x),p[x.id]=x;}),l.push({role:I,content:P});}break;case"tool":{let P=f;l.push({role:I,content:[{modality:ToolResponseModalityLiteral,id:P.tool_call_id,index:p[P.tool_call_id].index,name:p[P.tool_call_id].name,data:P.content}]});}break}});let _=[];return o.tools&&o.tools.forEach(f=>{_.push({type:"function",definition:{schema:{name:f.function.name,description:f.function.description||"",strict:f.function.strict,parameters:f.function.parameters}}});}),{modelName:t,config:r,messages:l,tools:_.length>0?_:void 0}}transformConfig(e,n,o){let t=e.toolChoice;delete e.toolChoice;let s=this.modelSchema.config.schema.safeParse(e);if(!s.success)throw new InvalidConfigError({info:`Invalid config for model : '${this.modelName}'`,cause:s.error});let r=s.data;t!==void 0&&(r.toolChoice=t),Object.keys(r).forEach(p=>{if(!(p in this.modelSchema.config.def))throw new InvalidConfigError({info:`Invalid config for model : '${this.modelName}'`,cause:new Error(`Invalid config key : '${p}',
available keys : [${Object.keys(this.modelSchema.config.def).join(", ")}]`)})});let l=Object.keys(r).reduce((p,_)=>{let f=this.modelSchema.config.def[_],I=f.param,P=r[_];return I==="max_completion_tokens"&&f.type==="range"&&P===0?p[I]=f.max:p[I]=P,p},{});if(l.top_logprobs&&!l.logprobs)throw new InvalidConfigError({info:`Invalid config for model : '${this.modelName}'`,cause:new Error("'logprobs' must be 'true' when 'top_logprobs' is specified")});if("tool_choice"in l&&l.tool_choice!==void 0){let p=l.tool_choice;if(!o||o&&o.length===0)throw new InvalidConfigError({info:`Invalid config for model : '${this.modelName}'`,cause:new Error("'tools' are required when 'toolChoice' is specified")});if(o&&o.length>0){let _=this.modelSchema.config.def.toolChoice;if(!_.choices.includes(p))if(o.map(f=>f.definition.schema.name).includes(p))l.tool_choice={type:"function",function:{name:p}};else throw new InvalidConfigError({info:`Invalid config for model : '${this.modelName}'`,cause:new Error(`toolChoice : '${p}' is not part of provided 'tools' names or
one of [${_.choices.join(", ")}]`)})}}if("response_format"in l&&l.response_format!==void 0){let p=l.response_format;if(p==="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 InvalidConfigError({info:`Invalid config for model : '${this.modelName}'`,cause:new Error("'responseSchema' is required in config when 'responseFormat' is 'json_schema'")});else l.response_format={type:p};}return l}transformMessages(e){if(!e||e&&e.length===0)return {messages:[]};let n=e.map(t=>{let s=Message().safeParse(t);if(!s.success)throw new InvalidMessagesError({info:"Invalid messages",cause:s.error});return s.data});return n.forEach(t=>{t.content.forEach(s=>{if(!this.modelSchema.modalities.includes(s.modality))throw new InvalidMessagesError({info:`Invalid message content for model : '${this.modelName}'`,cause:new Error(`model : '${this.modelName}' does not support modality : '${s.modality}',
available modalities : [${this.modelSchema.modalities.join(", ")}]`)})});}),n.forEach(t=>{if(!Object.keys(this.modelSchema.roles).includes(t.role))throw new InvalidMessagesError({info:`Invalid message content for model : '${this.modelName}'`,cause:new Error(`model : '${this.modelName}' does not support role : '${t.role}',
available roles : [${Object.keys(this.modelSchema.roles).join(", ")}]`)})}),n.forEach(t=>{t.content=t.content.filter(s=>s.modality!=="error"&&s.modality!=="search-result");}),{messages:n.map(t=>{switch(t.role){case SystemRoleLiteral:{let s=[];return t.content.forEach(r=>{if(r.modality===TextModalityLiteral)s.push({type:"text",text:r.value});else throw new InvalidMessagesError({info:`Invalid message 'role' and 'modality' combination for model : ${this.modelName}`,cause:new Error(`role : '${t.role}' cannot have content with modality : '${r.modality}'`)})}),{role:this.modelSchema.roles[t.role],content:s}}case AssistantRoleLiteral:{let s=[],r=[];return t.content.forEach(l=>{if(l.modality===TextModalityLiteral)s.push({type:"text",text:l.value});else if(l.modality===ToolCallModalityLiteral)r.push({id:l.id,type:"function",function:{name:l.name,arguments:l.arguments}});else throw new InvalidMessagesError({info:`Invalid message 'role' and 'modality' combination for model : ${this.modelName}`,cause:new Error(`role : '${t.role}' cannot have content with modality : '${l.modality}'`)})}),b({role:this.modelSchema.roles[t.role],content:s},r.length>0?{tool_calls:r}:{})}case UserRoleLiteral:{let s=[],r=[];t.content.forEach(p=>{if(p.modality===TextModalityLiteral)s.push({type:"text",text:p.value});else if(p.modality===ImageModalityLiteral)r.push({type:"image_url",image_url:{url:p.value.type==="url"?p.value.url:p.value.base64,detail:p.detail}});else throw new InvalidMessagesError({info:`Invalid message 'role' and 'modality' combination for model : ${this.modelName}`,cause:new Error(`role : '${t.role}' cannot have content with modality : '${p.modality}'`)})});let l=[...s,...r];return {role:this.modelSchema.roles[t.role],content:l}}case ToolRoleLiteral:{if(t.content.length!==1)throw new InvalidMessagesError({info:`Invalid message for role : '${t.role}'`,cause:new Error(`role : '${t.role}' must have exactly one content item`)});if(t.content[0].modality!==ToolResponseModalityLiteral)throw new InvalidMessagesError({info:`Invalid message 'role' and 'modality' combination for model : ${this.modelName}`,cause:new Error(`role : '${t.role}' must have content with modality : '${ToolResponseModalityLiteral}'`)});let s=t.content[0];return {role:this.modelSchema.roles[t.role],tool_call_id:s.id,content:s.data}}default:throw new InvalidMessagesError({info:`Invalid message 'role' for model : ${this.modelName}`,cause:new Error(`role : '${t.role}' is not supported,
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.modelName}`,cause:new Error(`model : '${this.modelName}' does not support tool modality : '${ToolCallModalityLiteral}'`)});return !e||e&&e.length===0?{tools:[]}:{tools:e.map(t=>{let s=Tool().safeParse(t);if(!s.success)throw new InvalidToolsError({info:"Invalid tools",cause:s.error});return s.data}).map(t=>({type:"function",function:t.definition.schema}))}}getCompleteChatUrl(e,n,o){return k(this,null,function*(){return new Promise(t=>{t(this.completeChatUrl);})})}getCompleteChatHeaders(e,n,o){return k(this,null,function*(){return new Promise(t=>{t(this.getDefaultHeaders());})})}getCompleteChatData(e,n,o){return k(this,null,function*(){let t=this.transformConfig(e,n,o),s=this.transformMessages(n);if(s.messages&&s.messages.length===0)throw new InvalidMessagesError({info:"Messages are required",cause:new Error("Messages are required")});let r=o?this.transformTools(o):{};return new Promise(l=>{l(b(b(b(b({},this.getDefaultParams()),t),s),r));})})}transformCompleteChatResponse(e){let n=ys.safeParse(e);if(n.success){if(n.data.choices.length===0)throw new ModelResponseError({info:"Invalid response from model",cause:new Error(`No choices in response : ${JSON.stringify(n.data)}`)});let o=n.data,t=[{role:AssistantRoleLiteral,content:[]}],s=o.choices[0].message;s.content&&t[0].content.push(createTextContent(s.content)),s.refusal&&t[0].content.push(createTextContent(s.refusal)),s.tool_calls&&s.tool_calls.forEach((_,f)=>{t[0].content.push(createToolCallContent(f,_.id,_.function.name,_.function.arguments));});let r={promptTokens:o.usage.prompt_tokens,completionTokens:o.usage.completion_tokens,totalTokens:o.usage.total_tokens},l=[],p=o.choices[0].logprobs;return p&&(p.content&&l.push(...p.content.map(_=>({token:_.token,logProb:_.logprob,bytes:_.bytes,topLogProbs:_.top_logprobs.map(f=>({token:f.token,logProb:f.logprob,bytes:f.bytes}))}))),p.refusal&&l.push(...p.refusal.map(_=>({token:_.token,logProb:_.logprob,bytes:_.bytes,topLogProbs:_.top_logprobs.map(f=>({token:f.token,logProb:f.logprob,bytes:f.bytes}))})))),{messages:t,usage:r,logProbs:l}}throw new ModelResponseError({info:"Invalid response from model",cause:n.error})}getStreamChatUrl(e,n,o){return k(this,null,function*(){return new Promise(t=>{t(this.streamChatUrl);})})}getStreamChatHeaders(e,n,o){return k(this,null,function*(){return new Promise(t=>{t(this.getDefaultHeaders());})})}getStreamChatData(e,n,o){return k(this,null,function*(){let t=this.transformConfig(e,n,o),s=this.transformMessages(n);if(s.messages&&s.messages.length===0)throw new InvalidMessagesError({info:"Messages are required",cause:new Error("Messages are required")});let r=o?this.transformTools(o):{};return new Promise(l=>{l(b(b(b(b({stream:!0,stream_options:{include_usage:!0}},this.getDefaultParams()),t),s),r));})})}transformStreamChatResponseChunk(e,n){return ie(this,null,function*(){var l,p;let o=n+e,t=[],s="",r=0;for(;r<o.length;){let _=o.indexOf(`
`,r);if(_===-1){s=o.substring(r);break}else {let f=o.substring(r,_).trim();f&&t.push(f),r=_+1;}}for(let _ of t){if(_==="data: [DONE]")return;if(_.startsWith("data: ")){let f=_.substring(6);try{let I=JSON.parse(f),P=Ms.safeParse(I);if(P.success){let S={partialMessages:[]},R=P.data;if(R.choices.length>0){let L=R.choices[0].delta;if(L!==void 0&&Object.keys(L).length!==0){if("content"in L&&L.content!==null)S.partialMessages.push(createPartialTextMessage(AssistantRoleLiteral,L.content));else if("refusal"in L&&L.refusal!==null)S.partialMessages.push(createPartialTextMessage(AssistantRoleLiteral,L.refusal));else if("tool_calls"in L&&L.tool_calls!==void 0){let x=L.tool_calls.at(0);S.partialMessages.push(createPartialToolCallMessage(AssistantRoleLiteral,x.index,x.id,(l=x.function)==null?void 0:l.name,(p=x.function)==null?void 0:p.arguments));}}}R.usage&&(S.usage={promptTokens:R.usage.prompt_tokens,completionTokens:R.usage.completion_tokens,totalTokens:R.usage.total_tokens}),yield {partialResponse:S,buffer:s};}else throw new ModelResponseError({info:"Invalid response from model",cause:P.error})}catch(I){throw new ModelResponseError({info:`Malformed JSON received in stream: ${f}`,cause:I})}}}yield {partialResponse:{partialMessages:[]},buffer:s};})}transformProxyStreamChatResponseChunk(e,n,o,t,s){return ie(this,null,function*(){yield*Me(this.transformStreamChatResponseChunk(e,n));})}getProxyStreamChatUrl(e,n,o){return k(this,null,function*(){return new Promise(t=>{t(this.streamChatUrl);})})}getProxyCompleteChatUrl(e,n,o){return k(this,null,function*(){return new Promise(t=>{t(this.completeChatUrl);})})}getProxyCompleteChatHeaders(e,n,o){return k(this,null,function*(){if(!n)return {};let t=b({},n);return delete t.host,delete t["content-length"],t})}getProxyStreamChatHeaders(e,n,o){return k(this,null,function*(){return yield this.getProxyCompleteChatHeaders(e,n,o)})}getModelPricing(){if(!(this.modelName in g))throw new ModelResponseError({info:`Invalid model pricing for model : '${this.modelName}'`,cause:new Error(`No pricing configuration found for model "${this.modelName}"`)});return g[this.modelName]}};var sn=z.object({modelName:z.string(),apiKey:z.string(),baseUrl:z.string().url().optional(),organization:z.string().optional()}),Bo=class{constructor(e,n){this.version="v1";let o=sn.parse(n);this.modelSchema=e,this.modelName=o.modelName,this.apiKey=o.apiKey,this.baseUrl=urlWithoutTrailingSlash(o.baseUrl||J.baseUrl),this.responsesUrl=`${this.baseUrl}/responses`,this.organization=o.organization;}getDefaultBaseUrl(){return this.baseUrl}getDefaultHeaders(){return b({Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},this.organization?{"OpenAI-Organization":this.organization}:{})}getDefaultParams(){return {model:this.modelName}}getRetryDelay(e){let n=l=>{let p=/(\d+)(h|m|s|ms)/g,_={h:36e5,m:6e4,s:1e3,ms:1},f,I=0;for(;(f=p.exec(l))!==null;){let P=parseInt(f[1]),S=f[2];I+=P*_[S];}return I},o=0,t=0,s=!0;e["x-ratelimit-reset-requests"]&&(o=n(e["x-ratelimit-reset-requests"])),e["x-ratelimit-reset-tokens"]&&(t=n(e["x-ratelimit-reset-tokens"]));let r=Math.max(o,t);return {shouldRetry:s,delayMs:r}}getTokenCount(e){return e.reduce((n,o)=>n+o.content.map(t=>t.modality==="text"?t.value:"").join(" ").length,0)}transformModelRequest(e){throw new ModelResponseError({info:"transformModelRequest not supported for Responses API models",cause:new Error("Use the standard gateway interface with config, messages, and tools parameters")})}transformConfig(e,n,o){let t=Config().parse(e),s={};for(let p of Object.keys(this.modelSchema.config.def)){let _=this.modelSchema.config.def[p],f=_==null?void 0:_.param;f&&t[p]!==void 0&&(s[f]=t[p]);}let r=t.toolChoice;if(r!==void 0)if(o&&o.length>0){let p=r,_=o.map(f=>f.definition.schema.name);if(["none","auto","required"].includes(p))s.tool_choice=p;else if(_.includes(p))s.tool_choice={type:"function",function:{name:p}};else throw new InvalidConfigError({info:`Invalid tool choice for model : '${this.modelName}'`,cause:new Error(`Tool with name '${p}' not found in tools`)})}else throw new InvalidConfigError({info:`Invalid tool choice for model : '${this.modelName}'`,cause:new Error("Tools are required when tool_choice is specified")});let l=t.responseFormat;if(l!==void 0)if(l==="json_schema"){if(!t.responseSchema)throw new InvalidConfigError({info:`Invalid response schema for model : '${this.modelName}'`,cause:new Error("Response schema is required when response format is 'json_schema'")});s.response_format={type:l,json_schema:s.response_schema},delete s.response_schema;}else s.response_format={type:l};return "reasoning_effort"in s&&s.reasoning_effort!==void 0&&(s.reasoning={effort:s.reasoning_effort},delete s.reasoning_effort),"verbosity"in s&&s.verbosity!==void 0&&(s.text={verbosity:s.verbosity},delete s.verbosity),s}transformMessages(e){if(!e||e.length===0)return {messages:[]};let n=e.map(t=>{let s=Message().safeParse(t);if(!s.success)throw new InvalidMessagesError({info:"Invalid messages",cause:s.error});return s.data});return n.forEach(t=>{t.content.forEach(s=>{if(!this.modelSchema.modalities.includes(s.modality))throw new InvalidMessagesError({info:`Invalid message content for model : '${this.modelName}'`,cause:new Error(`model : '${this.modelName}' does not support modality : '${s.modality}'`)})});}),n.forEach(t=>{if(!Object.keys(this.modelSchema.roles).includes(t.role))throw new InvalidMessagesError({info:`Invalid message content for model : '${this.modelName}'`,cause:new Error(`model : '${this.modelName}' does not support role : '${t.role}'`)})}),n.forEach(t=>{t.content=t.content.filter(s=>s.modality!=="error"&&s.modality!=="search-result");}),{messages:n.map(t=>{switch(t.role){case SystemRoleLiteral:{let s=[];return t.content.forEach(r=>{if(r.modality===TextModalityLiteral)s.push({type:"input_text",text:r.value});else throw new InvalidMessagesError({info:`Invalid message 'role' and 'modality' combination for model : ${this.modelName}`,cause:new Error(`role : '${t.role}' cannot have content with modality : '${r.modality}'`)})}),{role:this.modelSchema.roles[t.role],content:s}}case AssistantRoleLiteral:{let s=[];return t.content.forEach(r=>{if(r.modality===TextModalityLiteral)s.push({type:"output_text",text:r.value});else throw r.modality===ToolCallModalityLiteral?new InvalidMessagesError({info:`Invalid message 'role' and 'modality' combination for model : ${this.modelName}`,cause:new Error("tool calls in message history are not supported for Responses API")}):new InvalidMessagesError({info:`Invalid message 'role' and 'modality' combination for model : ${this.modelName}`,cause:new Error(`role : '${t.role}' cannot have content with modality : '${r.modality}'`)})}),{role:this.modelSchema.roles[t.role],content:s}}case UserRoleLiteral:{let s=[];return t.content.forEach(r=>{if(r.modality===TextModalityLiteral)s.push({type:"input_text",text:r.value});else if(r.modality===ImageModalityLiteral){let l=r.value,p=l.type==="url"?l.url:l.base64;s.push({type:"image_url",image_url:{url:p,detail:r.detail}});}else throw new InvalidMessagesError({info:`Invalid message 'role' and 'modality' combination for model : ${this.modelName}`,cause:new Error(`role : '${t.role}' cannot have content with modality : '${r.modality}'`)})}),{role:this.modelSchema.roles[t.role],content:s}}case ToolRoleLiteral:{if(t.content.length!==1)throw new InvalidMessagesError({info:`Invalid message for role : '${t.role}'`,cause:new Error(`role : '${t.role}' must have exactly one content item`)});if(t.content[0].modality!==ToolResponseModalityLiteral)throw new InvalidMessagesError({info:`Invalid message 'role' and 'modality' combination for model : ${this.modelName}`,cause:new Error(`role : '${t.role}' must have content with modality : '${ToolResponseModalityLiteral}'`)});let s=t.content[0];return {role:this.modelSchema.roles[t.role],tool_call_id:s.id,content:s.data}}default:throw new InvalidMessagesError({info:`Invalid message 'role' for model : ${this.modelName}`,cause:new Error(`role : '${t.role}' is not supported`)})}})}}transformTools(e){if(!e||e.length===0)return {tools:[]};if(!this.modelSchema.modalities.includes(ToolCallModalityLiteral))throw new InvalidToolsError({info:`Invalid tool 'modality' for model : ${this.modelName}`,cause:new Error(`model : '${this.modelName}' does not support tool modality`)});return {tools:e.map(t=>{let s=Tool().safeParse(t);if(!s.success)throw new InvalidToolsError({info:"Invalid tools",cause:s.error});return s.data}).map(t=>({type:"function",function:t.definition.schema}))}}getCompleteChatUrl(e,n,o){return k(this,null,function*(){return Promise.resolve(this.responsesUrl)})}getCompleteChatHeaders(e,n,o){return k(this,null,function*(){return Promise.resolve(this.getDefaultHeaders())})}getCompleteChatData(e,n,o){return k(this,null,function*(){let t=this.transformConfig(e,n,o),s=this.transformMessages(n);if(s.messages&&s.messages.length===0)throw new InvalidMessagesError({info:"Messages are required",cause:new Error("Messages are required")});let r=o?this.transformTools(o):{};return Promise.resolve(q(b(b(b({},this.getDefaultParams()),t),r),{input:s.messages}))})}transformCompleteChatResponse(e){var s,r,l,p,_,f,I,P,S,R,L;let n=(e==null?void 0:e.output)||(e==null?void 0:e.outputs);if(!n||!Array.isArray(n)||n.length===0)throw new ModelResponseError({info:"Invalid response from model",cause:new Error(`No output in response : ${JSON.stringify(e)}`)});let o=[{role:AssistantRoleLiteral,content:[]}];for(let x of n)if((x==null?void 0:x.type)==="message"&&Array.isArray(x.content))x.content.forEach(A=>{var B,C,D,H,G,O;if((A==null?void 0:A.type)==="text"||(A==null?void 0:A.type)==="output_text")A.text&&o[0].content.push(createTextContent(A.text));else if((A==null?void 0:A.type)==="tool_call"&&A.tool_call){let V=A.tool_call;o[0].content.push(createToolCallContent((B=V.index)!=null?B:0,(C=V.id)!=null?C:"",(H=(D=V.function)==null?void 0:D.name)!=null?H:"",(O=(G=V.function)==null?void 0:G.arguments)!=null?O:""));}});else if(((x==null?void 0:x.type)==="text"||(x==null?void 0:x.type)==="output_text")&&(x!=null&&x.text))o[0].content.push(createTextContent(x.text));else if((x==null?void 0:x.type)==="tool_call"&&x.tool_call){let A=x.tool_call;o[0].content.push(createToolCallContent((s=A.index)!=null?s:0,(r=A.id)!=null?r:"",(p=(l=A.function)==null?void 0:l.name)!=null?p:"",(f=(_=A.function)==null?void 0:_.arguments)!=null?f:""));}if(o[0].content.length===0){let x=n[0],A=(x==null?void 0:x.content)||[],B=[];if(A.forEach(C=>{((C==null?void 0:C.type)==="text"||(C==null?void 0:C.type)==="output_text")&&(C!=null&&C.text)&&B.push(C.text);}),B.length>0)o[0].content.push(createTextContent(B.join(`
`)));else throw new ModelResponseError({info:"Invalid response from model",cause:new Error(`No text content found in response : ${JSON.stringify(e)}`)})}let t=e.usage||{};return {messages:o,usage:{promptTokens:(P=(I=t.input_tokens)!=null?I:t.prompt_tokens)!=null?P:0,completionTokens:(R=(S=t.output_tokens)!=null?S:t.completion_tokens)!=null?R:0,totalTokens:(L=t.total_tokens)!=null?L:(t.input_tokens||0)+(t.output_tokens||0)}}}getStreamChatUrl(e,n,o){return k(this,null,function*(){return Promise.resolve(this.responsesUrl)})}getStreamChatHeaders(e,n,o){return k(this,null,function*(){return Promise.resolve(q(b({},this.getDefaultHeaders()),{Accept:"text/event-stream"}))})}getStreamChatData(e,n,o){return k(this,null,function*(){let t=this.transformConfig(e,n,o),s=this.transformMessages(n);if(s.messages&&s.messages.length===0)throw new InvalidMessagesError({info:"Messages are required",cause:new Error("Messages are required")});let r=o?this.transformTools(o):{};return Promise.resolve(q(b(b(b({},this.getDefaultParams()),t),r),{input:s.messages,stream:!0}))})}transformStreamChatResponseChunk(e,n){return ie(this,null,function*(){var l,p,_,f,I,P,S,R,L,x;let o=n+e,t=[],s="",r=0;for(;r<o.length;){let A=o.indexOf(`
`,r);if(A===-1){s=o.substring(r);break}else {let B=o.substring(r,A).trim();B&&t.push(B),r=A+1;}}for(let A of t){if(A==="data: [DONE]")return;if(A.startsWith("data: ")){let B=A.substring(6);try{let C=JSON.parse(B),D={partialMessages:[]},H=!1;if((C.type==="response.output_text.delta"||C.type==="output_text.delta")&&typeof C.delta=="string"&&C.delta.length>0&&(D.partialMessages.push(createPartialTextMessage(AssistantRoleLiteral,C.delta)),H=!0),C.type==="response.content_part.added"&&C.part){let G=C.part;G.type==="output_text"&&typeof G.text=="string"&&G.text.length>0&&(D.partialMessages.push(createPartialTextMessage(AssistantRoleLiteral,G.text)),H=!0);}if(!H&&C.delta){let G=C.delta;typeof G=="string"&&G.length>0?(D.partialMessages.push(createPartialTextMessage(AssistantRoleLiteral,G)),H=!0):G&&typeof G=="object"&&G.text!==void 0&&G.text!==null?(D.partialMessages.push(createPartialTextMessage(AssistantRoleLiteral,G.text)),H=!0):Array.isArray(G.content)&&G.content.forEach(O=>{var V,me,de,ce;if((O==null?void 0:O.type)==="output_text"&&(O!=null&&O.text))D.partialMessages.push(createPartialTextMessage(AssistantRoleLiteral,O.text)),H=!0;else if((O==null?void 0:O.type)==="tool_call"&&(O!=null&&O.tool_call)){let E=O.tool_call;D.partialMessages.push(createPartialToolCallMessage(AssistantRoleLiteral,(V=E.index)!=null?V:0,(me=E.id)!=null?me:"",(de=E.function)==null?void 0:de.name,(ce=E.function)==null?void 0:ce.arguments)),H=!0;}});}if((C.type==="tool_call"||C.type==="tool_call.delta"||C.type==="response.tool_call.delta")&&(l=C.delta)!=null&&l.tool_call){let G=C.delta.tool_call;D.partialMessages.push(createPartialToolCallMessage(AssistantRoleLiteral,(p=G.index)!=null?p:0,(_=G.id)!=null?_:"",(f=G.function)==null?void 0:f.name,(I=G.function)==null?void 0:I.arguments));}if(!C.delta&&(C.output||C.outputs)){let G=C.output||C.outputs;Array.isArray(G)&&G.forEach(O=>{var V,me,de,ce;if((O==null?void 0:O.type)==="message"&&Array.isArray(O.content))O.content.forEach(E=>{var rn,ln,pn,mn;if(((E==null?void 0:E.type)==="text"||(E==null?void 0:E.type)==="output_text")&&(E!=null&&E.text))D.partialMessages.push(createPartialTextMessage(AssistantRoleLiteral,E.text));else if((E==null?void 0:E.type)==="tool_call"&&(E!=null&&E.tool_call)){let Te=E.tool_call;D.partialMessages.push(createPartialToolCallMessage(AssistantRoleLiteral,(rn=Te.index)!=null?rn:0,(ln=Te.id)!=null?ln:"",(pn=Te.function)==null?void 0:pn.name,(mn=Te.function)==null?void 0:mn.arguments));}});else if(((O==null?void 0:O.type)==="text"||(O==null?void 0:O.type)==="output_text")&&(O!=null&&O.text))D.partialMessages.push(createPartialTextMessage(AssistantRoleLiteral,O.text));else if((O==null?void 0:O.type)==="tool_call"&&(O!=null&&O.tool_call)){let E=O.tool_call;D.partialMessages.push(createPartialToolCallMessage(AssistantRoleLiteral,(V=E.index)!=null?V:0,(me=E.id)!=null?me:"",(de=E.function)==null?void 0:de.name,(ce=E.function)==null?void 0:ce.arguments));}});}C.usage&&(D.usage={promptTokens:(S=(P=C.usage.input_tokens)!=null?P:C.usage.prompt_tokens)!=null?S:0,completionTokens:(L=(R=C.usage.output_tokens)!=null?R:C.usage.completion_tokens)!=null?L:0,totalTokens:(x=C.usage.total_tokens)!=null?x:(C.usage.input_tokens||0)+(C.usage.output_tokens||0)}),(D.partialMessages.length>0||D.usage)&&(yield {partialResponse:D,buffer:s});}catch(C){throw new ModelResponseError({info:`Malformed JSON received in stream: ${B}`,cause:C})}}}})}transformProxyStreamChatResponseChunk(e,n,o,t,s){return ie(this,null,function*(){yield*Me(this.transformStreamChatResponseChunk(e,n));})}getProxyStreamChatUrl(e,n,o){return k(this,null,function*(){return Promise.resolve(this.responsesUrl)})}getProxyCompleteChatUrl(e,n,o){return k(this,null,function*(){return Promise.resolve(this.responsesUrl)})}getProxyCompleteChatHeaders(e,n,o){return k(this,null,function*(){if(!n)return {};let t=b({},n);return delete t.host,delete t["content-length"],t})}getProxyStreamChatHeaders(e,n,o){return k(this,null,function*(){let t=yield this.getProxyCompleteChatHeaders(e,n,o);return q(b({},t),{Accept:"text/event-stream"})})}getModelPricing(){if(!(this.modelName in g))throw new ModelResponseError({info:`Inval