@adaline/openai
Version:
Adaline OpenAI
17 lines (15 loc) • 79.1 kB
JavaScript
'use strict';
var zod = require('zod');
var provider = require('@adaline/provider');
var types = require('@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,s)=>e in i?Ns(i,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):i[e]=s,b=(i,e)=>{for(var s in e||(e={}))Us.call(e,s)&&cn(i,s,e[s]);if(dn)for(var s of dn(e))Bs.call(e,s)&&cn(i,s,e[s]);return i},q=(i,e)=>qs(i,zs(e));var k=(i,e,s)=>new Promise((o,t)=>{var n=p=>{try{l(s.next(p));}catch(g){t(g);}},r=p=>{try{l(s.throw(p));}catch(g){t(g);}},l=p=>p.done?o(p.value):Promise.resolve(p.value).then(n,r);l((s=s.apply(i,e)).next());}),un=function(i,e){this[0]=i,this[1]=e;},ie=(i,e,s)=>{var o=(r,l,p,g)=>{try{var T=s[r](l),x=(l=T.value)instanceof un,O=T.done;Promise.resolve(x?l[0]:l).then(I=>x?o(r==="return"?r:"next",l[1]?{done:I.done,value:I.value}:I,p,g):p({value:I,done:O})).catch(I=>o("throw",I,p,g));}catch(I){g(I);}},t=r=>n[r]=l=>new Promise((p,g)=>o(r,l,p,g)),n={};return s=s.apply(i,e),n[ye("asyncIterator")]=()=>n,t("next"),t("throw"),t("return"),n},Me=i=>{var e=i[ye("asyncIterator")],s=!1,o,t={};return e==null?(e=i[ye("iterator")](),o=n=>t[n]=r=>e[n](r)):(e=e.call(i),o=n=>t[n]=r=>{if(s){if(s=!1,n==="throw")throw r;return r}return s=!0,{done:!1,value:new un(new Promise(l=>{var p=e[n](r);p instanceof Object||js("Object expected"),l(p);}),1)}}),t[ye("iterator")]=()=>t,o("next"),"throw"in e?o("throw"):t.throw=n=>{throw n},"return"in e&&o("return"),t};var $o=provider.RangeConfigItem({param:"temperature",title:provider.CHAT_CONFIG.TEMPERATURE.title,description:provider.CHAT_CONFIG.TEMPERATURE.description,min:0,max:2,step:.01,default:1}),Fo=i=>provider.RangeConfigItem({param:"max_completion_tokens",title:provider.CHAT_CONFIG.MAX_TOKENS.title,description:provider.CHAT_CONFIG.MAX_TOKENS.description,min:0,max:i,step:1,default:0}),Ho=i=>provider.MultiStringConfigItem({param:"stop",title:provider.CHAT_CONFIG.STOP(i).title,description:provider.CHAT_CONFIG.STOP(i).description,max:i}),Vo=provider.RangeConfigItem({param:"top_p",title:provider.CHAT_CONFIG.TOP_P.title,description:provider.CHAT_CONFIG.TOP_P.description,min:0,max:1,step:.01,default:1}),Ko=provider.RangeConfigItem({param:"frequency_penalty",title:provider.CHAT_CONFIG.FREQUENCY_PENALTY.title,description:provider.CHAT_CONFIG.FREQUENCY_PENALTY.description,min:-2,max:2,step:.01,default:0}),Jo=provider.RangeConfigItem({param:"presence_penalty",title:provider.CHAT_CONFIG.PRESENCE_PENALTY.title,description:provider.CHAT_CONFIG.PRESENCE_PENALTY.description,min:-2,max:2,step:.01,default:0}),Wo=provider.RangeConfigItem({param:"seed",title:provider.CHAT_CONFIG.SEED.title,description:provider.CHAT_CONFIG.SEED.description,min:0,max:1e6,step:1,default:0}),Yo=provider.SelectBooleanConfigItem({param:"logprobs",title:provider.CHAT_CONFIG.LOG_PROBS.title,description:provider.CHAT_CONFIG.LOG_PROBS.description,default:!1}),Qo=provider.RangeConfigItem({param:"top_logprobs",title:provider.CHAT_CONFIG.TOP_LOG_PROBS.title,description:provider.CHAT_CONFIG.TOP_LOG_PROBS.description,min:0,max:20,step:1,default:0}),Xo=provider.SelectStringConfigItem({param:"tool_choice",title:"Tool choice",description:"Controls which (if any) tool is called by the model. 'none' means the model will not call a function. 'auto' means the model can pick between generating a message or calling a tool.",default:"auto",choices:["auto","required","none"]}),Zo=provider.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=provider.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)=>zod.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(s=>s===0?void 0:s),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=provider.ObjectSchemaConfigItem({param:"response_schema",title:provider.CHAT_CONFIG.RESPONSE_SCHEMA.title,description:provider.CHAT_CONFIG.RESPONSE_SCHEMA.description,objectSchema:types.ResponseSchema}),fn=provider.SelectStringConfigItem({param:"response_format",title:provider.CHAT_CONFIG.RESPONSE_FORMAT_WITH_SCHEMA.title,description:provider.CHAT_CONFIG.RESPONSE_FORMAT_WITH_SCHEMA.description,default:"text",choices:["text","json_object","json_schema"]}),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=provider.RangeConfigItem({param:"temperature",title:provider.CHAT_CONFIG.TEMPERATURE.title,description:provider.CHAT_CONFIG.TEMPERATURE.description,min:1,max:1,step:.01,default:1}),Mn=provider.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=provider.SelectStringConfigItem({param:"response_format",title:provider.CHAT_CONFIG.RESPONSE_FORMAT.title,description:provider.CHAT_CONFIG.RESPONSE_FORMAT.description,default:"text",choices:["text","json_object"]}),xn=(i,e)=>q(b({},Q(i,e)),{responseFormat:bn.def}),Sn=(i,e)=>Y(i,e).extend({responseFormat:bn.schema});var ot=provider.SelectStringConfigItem({param:"encoding_format",title:"Encoding format",description:"Select the encoding format for the word embedding.",default:"float",choices:["float","base64"]}),tt=i=>provider.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=()=>zod.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 f={"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:De,modelOptions:Dn,modelSchema:lt},[Le]:{model:Ne,modelOptions:Ln,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},[Dt]:{model:Ao,modelOptions:as,modelSchema:Lt},[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:Do,modelOptions:cs,modelSchema:Jt}};}chatModelLiterals(){return Object.keys(this.chatModelFactories)}chatModelSchemas(){return Object.keys(this.chatModelFactories).reduce((e,s)=>(e[s]=this.chatModelFactories[s].modelSchema,e),{})}chatModel(e){let s=e.modelName;if(!(s in this.chatModelFactories))throw new provider.ProviderError({info:`OpenAI chat model: ${s} not found`,cause:new Error(`OpenAI chat model: ${s} not found, available chat models:
[${this.chatModelLiterals().join(", ")}]`)});let o=this.chatModelFactories[s].model,t=this.chatModelFactories[s].modelOptions.parse(e);return new o(t)}embeddingModelLiterals(){return Object.keys(this.embeddingModelFactories)}embeddingModelSchemas(){return Object.keys(this.embeddingModelFactories).reduce((e,s)=>(e[s]=this.embeddingModelFactories[s].modelSchema,e),{})}embeddingModel(e){let s=e.modelName;if(!(s in this.embeddingModelFactories))throw new provider.ProviderError({info:`OpenAI embedding model: ${s} not found`,cause:new Error(`OpenAI embedding model: ${s} not found, available embedding models:
[${this.embeddingModelLiterals().join(", ")}]`)});let o=this.embeddingModelFactories[s].model,t=this.embeddingModelFactories[s].modelOptions.parse(e);return new o(t)}};J.baseUrl="https://api.openai.com/v1";var d=zod.z.enum([types.SystemRoleLiteral,types.UserRoleLiteral,types.AssistantRoleLiteral,types.ToolRoleLiteral]),c={system:types.SystemRoleLiteral,user:types.UserRoleLiteral,assistant:types.AssistantRoleLiteral,tool:types.ToolRoleLiteral};var y=[types.TextModalityLiteral,types.ImageModalityLiteral,types.ToolCallModalityLiteral,types.ToolResponseModalityLiteral],M=zod.z.enum([types.TextModalityLiteral,types.ImageModalityLiteral,types.ToolCallModalityLiteral,types.ToolResponseModalityLiteral]),fl=[types.TextModalityLiteral],gl=zod.z.enum([types.TextModalityLiteral]),w=[types.TextModalityLiteral,types.ToolCallModalityLiteral,types.ToolResponseModalityLiteral],v=zod.z.enum([types.TextModalityLiteral,types.ToolCallModalityLiteral,types.ToolResponseModalityLiteral]);var qo=zod.z.object({token:zod.z.string(),logprob:zod.z.number(),bytes:zod.z.array(zod.z.number()).nullable()}),Ts=zod.z.object({content:zod.z.array(qo.extend({top_logprobs:zod.z.array(qo)})).nullable().optional(),refusal:zod.z.array(qo.extend({top_logprobs:zod.z.array(qo)})).nullable().optional()}).nullable(),si=zod.z.array(zod.z.object({id:zod.z.string().min(1),type:zod.z.enum(["function"]),function:zod.z.object({name:zod.z.string(),arguments:zod.z.string()})})),ys=zod.z.object({id:zod.z.string(),object:zod.z.literal("chat.completion"),created:zod.z.number(),model:zod.z.string(),system_fingerprint:zod.z.string().nullable(),choices:zod.z.array(zod.z.object({index:zod.z.number(),message:zod.z.object({role:zod.z.string(),content:zod.z.string().nullable().optional(),tool_calls:si.optional(),refusal:zod.z.string().nullable().optional()}),logprobs:Ts.optional(),finish_reason:zod.z.string()})),usage:zod.z.object({prompt_tokens:zod.z.number(),completion_tokens:zod.z.number(),total_tokens:zod.z.number()})}),ii=zod.z.array(zod.z.object({index:zod.z.number().int(),id:zod.z.string().min(1).optional(),type:zod.z.enum(["function"]).optional(),function:zod.z.object({name:zod.z.string().min(1).optional(),arguments:zod.z.string().optional()}).optional()})),Ms=zod.z.object({id:zod.z.string(),object:zod.z.string(),created:zod.z.number(),model:zod.z.string(),system_fingerprint:zod.z.string().nullable().optional(),choices:zod.z.array(zod.z.object({index:zod.z.number(),delta:zod.z.object({content:zod.z.string().nullable().optional(),tool_calls:ii.optional(),refusal:zod.z.string().nullable().optional()}).or(zod.z.object({})),logprobs:Ts.optional(),finish_reason:zod.z.string().nullable()})),usage:zod.z.object({prompt_tokens:zod.z.number(),completion_tokens:zod.z.number(),total_tokens:zod.z.number()}).nullable().optional()});var ai=zod.z.object({type:zod.z.literal("function"),function:zod.z.object({name:zod.z.string().min(1),description:zod.z.string().min(1).optional(),strict:zod.z.boolean().optional(),parameters:zod.z.any()})}),ri=zod.z.enum(["none","auto","required"]),li=zod.z.object({type:zod.z.literal("function"),function:zod.z.object({name:zod.z.string().min(1)})}),pi=zod.z.object({type:zod.z.enum(["text","json_object"])}).or(zod.z.object({type:zod.z.literal("json_schema"),json_schema:zod.z.object({name:zod.z.string().min(1),description:zod.z.string().min(1).optional(),strict:zod.z.boolean().optional(),schema:zod.z.any()})})),Yt=zod.z.object({text:zod.z.string().min(1),type:zod.z.literal("text")}),mi=zod.z.object({type:zod.z.literal("image_url"),image_url:zod.z.object({url:zod.z.string().url().min(1),detail:zod.z.enum(["low","high","auto"]).optional()})}),di=zod.z.object({id:zod.z.string().min(1),type:zod.z.literal("function"),function:zod.z.object({name:zod.z.string().min(1),arguments:zod.z.string().min(1)})}),ci=zod.z.object({role:zod.z.literal("system"),content:zod.z.string().min(1).or(zod.z.array(Yt).min(1))}),ui=zod.z.object({role:zod.z.literal("user"),content:zod.z.string().min(1).or(zod.z.array(zod.z.union([Yt,mi])).min(1))}),hi=zod.z.object({role:zod.z.literal("assistant"),content:zod.z.string().min(1).or(zod.z.array(Yt).min(1)).optional(),tool_calls:zod.z.array(di).min(1).optional()}),fi=zod.z.object({role:zod.z.literal("tool"),tool_call_id:zod.z.string().min(1),content:zod.z.string().min(1)}),gi=zod.z.union([ci,ui,hi,fi]),Cs=zod.z.object({model:zod.z.string().min(1).optional(),messages:zod.z.array(gi).min(1),frequency_penalty:zod.z.number().min(-2).max(2).nullable().optional(),logprobs:zod.z.boolean().nullable().optional(),top_logprobs:zod.z.number().min(0).max(20).nullable().optional(),max_completion_tokens:zod.z.number().min(0).nullable().optional(),presence_penalty:zod.z.number().min(-2).max(2).nullable().optional(),response_format:pi.optional(),seed:zod.z.number().nullable().optional(),stop:zod.z.string().or(zod.z.array(zod.z.string()).max(4)).nullable().optional(),temperature:zod.z.number().min(0).max(2).nullable().optional(),top_p:zod.z.number().min(0).max(1).nullable().optional(),tools:zod.z.array(ai).optional(),tool_choice:ri.or(li).optional(),reasoning_effort:zod.z.enum(["minimal","low","medium","high"]).optional(),verbosity:zod.z.enum(["low","medium","high"]).optional()});var h=zod.z.object({modelName:zod.z.string(),apiKey:zod.z.string(),baseUrl:zod.z.string().url().optional(),completeChatUrl:zod.z.string().url().optional(),streamChatUrl:zod.z.string().url().optional(),organization:zod.z.string().optional()}),u=class{constructor(e,s){this.version="v1";let o=h.parse(s);this.modelSchema=e,this.modelName=o.modelName,this.apiKey=o.apiKey,this.baseUrl=provider.urlWithoutTrailingSlash(o.baseUrl||J.baseUrl),this.streamChatUrl=provider.urlWithoutTrailingSlash(o.streamChatUrl||`${this.baseUrl}/chat/completions`),this.completeChatUrl=provider.urlWithoutTrailingSlash(o.completeChatUrl||`${this.baseUrl}/chat/completions`),this.organization=o.organization;}getDefaultBaseUrl(){return this.baseUrl}getDefaultHeaders(){return b({Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},this.organization?{"OpenAI-Organization":this.organization}:{})}getDefaultParams(){return {model:this.modelName}}getRetryDelay(e,s){let o=p=>{let g=/(\d+)(h|m|s|ms)/g,T={h:36e5,m:6e4,s:1e3,ms:1},x,O=0;for(;(x=g.exec(p))!==null;){let I=parseInt(x[1]),R=x[2];O+=I*T[R];}return O},t=0,n=0,r=!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 l=Math.max(t,n);return {shouldRetry:r,delayMs:l}}getTokenCount(e){return e.reduce((s,o)=>s+o.content.map(t=>t.modality==="text"?t.value:"").join(" ").length,0)}transformModelRequest(e){let s=Cs.safeParse(e);if(!s.success)throw new provider.InvalidModelRequestError({info:"Invalid model request",cause:s.error});let o=s.data,t=o.model;if(o.tool_choice&&(!o.tools||o.tools.length===0))throw new provider.InvalidModelRequestError({info:`Invalid model request for model : '${this.modelName}'`,cause:new Error("'tools' are required when 'tool_choice' is specified")});let n={};o.response_format&&(n.responseFormat=o.response_format.type,o.response_format.type==="json_schema"&&(n.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"?n.toolChoice=o.tool_choice:n.toolChoice=o.tool_choice.function.name),n.seed=o.seed,n.maxTokens=o.max_completion_tokens,n.temperature=o.temperature,n.topP=o.top_p,n.presencePenalty=o.presence_penalty,n.frequencyPenalty=o.frequency_penalty,n.stop=o.stop,n.logProbs=o.logprobs,n.topLogProbs=o.top_logprobs,n.reasoningEffort=o.reasoning_effort,n.verbosity=o.verbosity;let r=types.Config().parse(provider.removeUndefinedEntries(n)),l=[],p={};o.messages.forEach(T=>{let x=T.role;switch(x){case"system":{let O=T.content;if(typeof O=="string")l.push({role:x,content:[{modality:types.TextModalityLiteral,value:O}]});else {let I=O.map(R=>({modality:types.TextModalityLiteral,value:R.text}));l.push({role:x,content:I});}}break;case"user":{let O=T.content;if(typeof O=="string")l.push({role:x,content:[{modality:types.TextModalityLiteral,value:O}]});else {let I=O.map(R=>R.type==="text"?{modality:types.TextModalityLiteral,value:R.text}:R.image_url.url.startsWith("data:")?{modality:types.ImageModalityLiteral,detail:R.image_url.detail||"auto",value:{type:types.Base64ImageContentTypeLiteral,base64:R.image_url.url,mediaType:provider.getMimeTypeFromBase64(R.image_url.url)}}:{modality:types.ImageModalityLiteral,detail:R.image_url.detail||"auto",value:{type:types.UrlImageContentTypeLiteral,url:R.image_url.url}});l.push({role:x,content:I});}}break;case"assistant":{let O=[];if(!T.content&&!T.tool_calls)throw new provider.InvalidModelRequestError({info:`Invalid model request for model : '${this.modelName}'`,cause:new Error("one of'content' or 'tool_calls' must be provided")});if(T.content){let I=T.content;typeof I=="string"?O.push({modality:types.TextModalityLiteral,value:I}):I.forEach(R=>{O.push({modality:types.TextModalityLiteral,value:R.text});});}T.tool_calls&&T.tool_calls.forEach((R,D)=>{let S={modality:types.ToolCallModalityLiteral,id:R.id,index:D,name:R.function.name,arguments:R.function.arguments};O.push(S),p[S.id]=S;}),l.push({role:x,content:O});}break;case"tool":{let O=T;l.push({role:x,content:[{modality:types.ToolResponseModalityLiteral,id:O.tool_call_id,index:p[O.tool_call_id].index,name:p[O.tool_call_id].name,data:O.content}]});}break}});let g=[];return o.tools&&o.tools.forEach(T=>{g.push({type:"function",definition:{schema:{name:T.function.name,description:T.function.description||"",strict:T.function.strict,parameters:T.function.parameters}}});}),{modelName:t,config:r,messages:l,tools:g.length>0?g:void 0}}transformConfig(e,s,o){let t=e.toolChoice;delete e.toolChoice;let n=this.modelSchema.config.schema.safeParse(e);if(!n.success)throw new provider.InvalidConfigError({info:`Invalid config for model : '${this.modelName}'`,cause:n.error});let r=n.data;t!==void 0&&(r.toolChoice=t),Object.keys(r).forEach(p=>{if(!(p in this.modelSchema.config.def))throw new provider.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,g)=>{let T=this.modelSchema.config.def[g],x=T.param,O=r[g];return x==="max_completion_tokens"&&T.type==="range"&&O===0?p[x]=T.max:p[x]=O,p},{});if(l.top_logprobs&&!l.logprobs)throw new provider.InvalidConfigError({info:`Invalid config for model : '${this.modelName}'`,cause:new Error("'logprobs' must be 'true' when 'top_logprobs' is specified")});if("tool_choice"in l&&l.tool_choice!==void 0){let p=l.tool_choice;if(!o||o&&o.length===0)throw new provider.InvalidConfigError({info:`Invalid config for model : '${this.modelName}'`,cause:new Error("'tools' are required when 'toolChoice' is specified")});if(o&&o.length>0){let g=this.modelSchema.config.def.toolChoice;if(!g.choices.includes(p))if(o.map(T=>T.definition.schema.name).includes(p))l.tool_choice={type:"function",function:{name:p}};else throw new provider.InvalidConfigError({info:`Invalid config for model : '${this.modelName}'`,cause:new Error(`toolChoice : '${p}' is not part of provided 'tools' names or
one of [${g.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 provider.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 s=e.map(t=>{let n=types.Message().safeParse(t);if(!n.success)throw new provider.InvalidMessagesError({info:"Invalid messages",cause:n.error});return n.data});return s.forEach(t=>{t.content.forEach(n=>{if(!this.modelSchema.modalities.includes(n.modality))throw new provider.InvalidMessagesError({info:`Invalid message content for model : '${this.modelName}'`,cause:new Error(`model : '${this.modelName}' does not support modality : '${n.modality}',
available modalities : [${this.modelSchema.modalities.join(", ")}]`)})});}),s.forEach(t=>{if(!Object.keys(this.modelSchema.roles).includes(t.role))throw new provider.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(", ")}]`)})}),s.forEach(t=>{t.content=t.content.filter(n=>n.modality!=="error"&&n.modality!=="search-result");}),{messages:s.map(t=>{switch(t.role){case types.SystemRoleLiteral:{let n=[];return t.content.forEach(r=>{if(r.modality===types.TextModalityLiteral)n.push({type:"text",text:r.value});else throw new provider.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:n}}case types.AssistantRoleLiteral:{let n=[],r=[];return t.content.forEach(l=>{if(l.modality===types.TextModalityLiteral)n.push({type:"text",text:l.value});else if(l.modality===types.ToolCallModalityLiteral)r.push({id:l.id,type:"function",function:{name:l.name,arguments:l.arguments}});else throw new provider.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:n},r.length>0?{tool_calls:r}:{})}case types.UserRoleLiteral:{let n=[],r=[];t.content.forEach(p=>{if(p.modality===types.TextModalityLiteral)n.push({type:"text",text:p.value});else if(p.modality===types.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 provider.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=[...n,...r];return {role:this.modelSchema.roles[t.role],content:l}}case types.ToolRoleLiteral:{if(t.content.length!==1)throw new provider.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!==types.ToolResponseModalityLiteral)throw new provider.InvalidMessagesError({info:`Invalid message 'role' and 'modality' combination for model : ${this.modelName}`,cause:new Error(`role : '${t.role}' must have content with modality : '${types.ToolResponseModalityLiteral}'`)});let n=t.content[0];return {role:this.modelSchema.roles[t.role],tool_call_id:n.id,content:n.data}}default:throw new provider.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(types.ToolCallModalityLiteral))throw new provider.InvalidToolsError({info:`Invalid tool 'modality' for model : ${this.modelName}`,cause:new Error(`model : '${this.modelName}' does not support tool modality : '${types.ToolCallModalityLiteral}'`)});return !e||e&&e.length===0?{tools:[]}:{tools:e.map(t=>{let n=types.Tool().safeParse(t);if(!n.success)throw new provider.InvalidToolsError({info:"Invalid tools",cause:n.error});return n.data}).map(t=>({type:"function",function:t.definition.schema}))}}getCompleteChatUrl(e,s,o){return k(this,null,function*(){return new Promise(t=>{t(this.completeChatUrl);})})}getCompleteChatHeaders(e,s,o){return k(this,null,function*(){return new Promise(t=>{t(this.getDefaultHeaders());})})}getCompleteChatData(e,s,o){return k(this,null,function*(){let t=this.transformConfig(e,s,o),n=this.transformMessages(s);if(n.messages&&n.messages.length===0)throw new provider.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),n),r));})})}transformCompleteChatResponse(e){let s=ys.safeParse(e);if(s.success){if(s.data.choices.length===0)throw new provider.ModelResponseError({info:"Invalid response from model",cause:new Error(`No choices in response : ${JSON.stringify(s.data)}`)});let o=s.data,t=[{role:types.AssistantRoleLiteral,content:[]}],n=o.choices[0].message;n.content&&t[0].content.push(types.createTextContent(n.content)),n.refusal&&t[0].content.push(types.createTextContent(n.refusal)),n.tool_calls&&n.tool_calls.forEach((g,T)=>{t[0].content.push(types.createToolCallContent(T,g.id,g.function.name,g.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(g=>({token:g.token,logProb:g.logprob,bytes:g.bytes,topLogProbs:g.top_logprobs.map(T=>({token:T.token,logProb:T.logprob,bytes:T.bytes}))}))),p.refusal&&l.push(...p.refusal.map(g=>({token:g.token,logProb:g.logprob,bytes:g.bytes,topLogProbs:g.top_logprobs.map(T=>({token:T.token,logProb:T.logprob,bytes:T.bytes}))})))),{messages:t,usage:r,logProbs:l}}throw new provider.ModelResponseError({info:"Invalid response from model",cause:s.error})}getStreamChatUrl(e,s,o){return k(this,null,function*(){return new Promise(t=>{t(this.streamChatUrl);})})}getStreamChatHeaders(e,s,o){return k(this,null,function*(){return new Promise(t=>{t(this.getDefaultHeaders());})})}getStreamChatData(e,s,o){return k(this,null,function*(){let t=this.transformConfig(e,s,o),n=this.transformMessages(s);if(n.messages&&n.messages.length===0)throw new provider.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),n),r));})})}transformStreamChatResponseChunk(e,s){return ie(this,null,function*(){var l,p;let o=s+e,t=[],n="",r=0;for(;r<o.length;){let g=o.indexOf(`
`,r);if(g===-1){n=o.substring(r);break}else {let T=o.substring(r,g).trim();T&&t.push(T),r=g+1;}}for(let g of t){if(g==="data: [DONE]")return;if(g.startsWith("data: ")){let T=g.substring(6);try{let x=JSON.parse(T),O=Ms.safeParse(x);if(O.success){let I={partialMessages:[]},R=O.data;if(R.choices.length>0){let D=R.choices[0].delta;if(D!==void 0&&Object.keys(D).length!==0){if("content"in D&&D.content!==null)I.partialMessages.push(types.createPartialTextMessage(types.AssistantRoleLiteral,D.content));else if("refusal"in D&&D.refusal!==null)I.partialMessages.push(types.createPartialTextMessage(types.AssistantRoleLiteral,D.refusal));else if("tool_calls"in D&&D.tool_calls!==void 0){let S=D.tool_calls.at(0);I.partialMessages.push(types.createPartialToolCallMessage(types.AssistantRoleLiteral,S.index,S.id,(l=S.function)==null?void 0:l.name,(p=S.function)==null?void 0:p.arguments));}}}R.usage&&(I.usage={promptTokens:R.usage.prompt_tokens,completionTokens:R.usage.completion_tokens,totalTokens:R.usage.total_tokens}),yield {partialResponse:I,buffer:n};}else throw new provider.ModelResponseError({info:"Invalid response from model",cause:O.error})}catch(x){throw new provider.ModelResponseError({info:`Malformed JSON received in stream: ${T}`,cause:x})}}}yield {partialResponse:{partialMessages:[]},buffer:n};})}transformProxyStreamChatResponseChunk(e,s,o,t,n){return ie(this,null,function*(){yield*Me(this.transformStreamChatResponseChunk(e,s));})}getProxyStreamChatUrl(e,s,o){return k(this,null,function*(){return new Promise(t=>{t(this.streamChatUrl);})})}getProxyCompleteChatUrl(e,s,o){return k(this,null,function*(){return new Promise(t=>{t(this.completeChatUrl);})})}getProxyCompleteChatHeaders(e,s,o){return k(this,null,function*(){if(!s)return {};let t=b({},s);return delete t.host,delete t["content-length"],t})}getProxyStreamChatHeaders(e,s,o){return k(this,null,function*(){return yield this.getProxyCompleteChatHeaders(e,s,o)})}getModelPricing(){if(!(this.modelName in f))throw new provider.ModelResponseError({info:`Invalid model pricing for model : '${this.modelName}'`,cause:new Error(`No pricing configuration found for model "${this.modelName}"`)});return f[this.modelName]}};var sn=zod.z.object({modelName:zod.z.string(),apiKey:zod.z.string(),baseUrl:zod.z.string().url().optional(),organization:zod.z.string().optional()}),Bo=class{constructor(e,s){this.version="v1";let o=sn.parse(s);this.modelSchema=e,this.modelName=o.modelName,this.apiKey=o.apiKey,this.baseUrl=provider.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,s){let o=p=>{let g=/(\d+)(h|m|s|ms)/g,T={h:36e5,m:6e4,s:1e3,ms:1},x,O=0;for(;(x=g.exec(p))!==null;){let I=parseInt(x[1]),R=x[2];O+=I*T[R];}return O},t=0,n=0,r=!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 l=Math.max(t,n);return {shouldRetry:r,delayMs:l}}getTokenCount(e){return e.reduce((s,o)=>s+o.content.map(t=>t.modality==="text"?t.value:"").join(" ").length,0)}transformModelRequest(e){throw new provider.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,s,o){let t=types.Config().parse(e),n={};for(let p of Object.keys(this.modelSchema.config.def)){let g=this.modelSchema.config.def[p],T=g==null?void 0:g.param;T&&t[p]!==void 0&&(n[T]=t[p]);}let r=t.toolChoice;if(r!==void 0)if(o&&o.length>0){let p=r,g=o.map(T=>T.definition.schema.name);if(["none","auto","required"].includes(p))n.tool_choice=p;else if(g.includes(p))n.tool_choice={type:"function",function:{name:p}};else throw new provider.InvalidConfigError({info:`Invalid tool choice for model : '${this.modelName}'`,cause:new Error(`Tool with name '${p}' not found in tools`)})}else throw new provider.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 provider.InvalidConfigError({info:`Invalid response schema for model : '${this.modelName}'`,cause:new Error("Response schema is required when response format is 'json_schema'")});n.response_format={type:l,json_schema:n.response_schema},delete n.response_schema;}else n.response_format={type:l};return "reasoning_effort"in n&&n.reasoning_effort!==void 0&&(n.reasoning={effort:n.reasoning_effort},delete n.reasoning_effort),"verbosity"in n&&n.verbosity!==void 0&&(n.text={verbosity:n.verbosity},delete n.verbosity),n}transformMessages(e){if(!e||e.length===0)return {messages:[]};let s=e.map(t=>{let n=types.Message().safeParse(t);if(!n.success)throw new provider.InvalidMessagesError({info:"Invalid messages",cause:n.error});return n.data});return s.forEach(t=>{t.content.forEach(n=>{if(!this.modelSchema.modalities.includes(n.modality))throw new provider.InvalidMessagesError({info:`Invalid message content for model : '${this.modelName}'`,cause:new Error(`model : '${this.modelName}' does not support modality : '${n.modality}'`)})});}),s.forEach(t=>{if(!Object.keys(this.modelSchema.roles).includes(t.role))throw new provider.InvalidMessagesError({info:`Invalid message content for model : '${this.modelName}'`,cause:new Error(`model : '${this.modelName}' does not support role : '${t.role}'`)})}),s.forEach(t=>{t.content=t.content.filter(n=>n.modality!=="error"&&n.modality!=="search-result");}),{messages:s.map(t=>{switch(t.role){case types.SystemRoleLiteral:{let n=[];return t.content.forEach(r=>{if(r.modality===types.TextModalityLiteral)n.push({type:"input_text",text:r.value});else throw new provider.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:n}}case types.AssistantRoleLiteral:{let n=[];return t.content.forEach(r=>{if(r.modality===types.TextModalityLiteral)n.push({type:"output_text",text:r.value});else throw r.modality===types.ToolCallModalityLiteral?new provider.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 provider.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:n}}case types.UserRoleLiteral:{let n=[];return t.content.forEach(r=>{if(r.modality===types.TextModalityLiteral)n.push({type:"input_text",text:r.value});else if(r.modality===types.ImageModalityLiteral){let l=r.value,p=l.type==="url"?l.url:l.base64;n.push({type:"image_url",image_url:{url:p,detail:r.detail}});}else throw new provider.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:n}}case types.ToolRoleLiteral:{if(t.content.length!==1)throw new provider.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!==types.ToolResponseModalityLiteral)throw new provider.InvalidMessagesError({info:`Invalid message 'role' and 'modality' combination for model : ${this.modelName}`,cause:new Error(`role : '${t.role}' must have content with modality : '${types.ToolResponseModalityLiteral}'`)});let n=t.content[0];return {role:this.modelSchema.roles[t.role],tool_call_id:n.id,content:n.data}}default:throw new provider.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(types.ToolCallModalityLiteral))throw new provider.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 n=types.Tool().safeParse(t);if(!n.success)throw new provider.InvalidToolsError({info:"Invalid tools",cause:n.error});return n.data}).map(t=>({type:"function",function:t.definition.schema}))}}getCompleteChatUrl(e,s,o){return k(this,null,function*(){return Promise.resolve(this.responsesUrl)})}getCompleteChatHeaders(e,s,o){return k(this,null,function*(){return Promise.resolve(this.getDefaultHeaders())})}getCompleteChatData(e,s,o){return k(this,null,function*(){let t=this.transformConfig(e,s,o),n=this.transformMessages(s);if(n.messages&&n.messages.length===0)throw new provider.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:n.messages}))})}transformCompleteChatResponse(e){var n,r,l,p,g,T,x,O,I,R,D;let s=(e==null?void 0:e.output)||(e==null?void 0:e.outputs);if(!s||!Array.isArray(s)||s.length===0)throw new provider.ModelResponseError({info:"Invalid response from model",cause:new Error(`No output in response : ${JSON.stringify(e)}`)});let o=[{role:types.AssistantRoleLiteral,content:[]}];for(let S of s)if((S==null?void 0:S.type)==="message"&&Array.isArray(S.content))S.content.forEach(A=>{var B,C,L,H,G,P;if((A==null?void 0:A.type)==="text"||(A==null?void 0:A.type)==="output_text")A.text&&o[0].content.push(types.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(types.createToolCallContent((B=V.index)!=null?B:0,(C=V.id)!=null?C:"",(H=(L=V.function)==null?void 0:L.name)!=null?H:"",(P=(G=V.function)==null?void 0:G.arguments)!=null?P:""));}});else if(((S==null?void 0:S.type)==="text"||(S==null?void 0:S.type)==="output_text")&&(S!=null&&S.text))o[0].content.push(types.createTextContent(S.text));else if((S==null?void 0:S.type)==="tool_call"&&S.tool_call){let A=S.tool_call;o[0].content.push(types.createToolCallContent((n=A.index)!=null?n:0,(r=A.id)!=null?r:"",(p=(l=A.function)==null?void 0:l.name)!=null?p:"",(T=(g=A.function)==null?void 0:g.arguments)!=null?T:""));}if(o[0].content.length===0){let S=s[0],A=(S==null?void 0:S.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(types.createTextContent(B.join(`
`)));else throw new provider.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:(O=(x=t.input_tokens)!=null?x:t.prompt_tokens)!=null?O:0,completionTokens:(R=(I=t.output_tokens)!=null?I:t.completion_tokens)!=null?R:0,totalTokens:(D=t.total_tokens)!=null?D:(t.input_tokens||0)+(t.output_tokens||0)}}}getStreamChatUrl(e,s,o){return k(this,null,function*(){return Promise.resolve(this.responsesUrl)})}getStreamChatHeaders(e,s,o){return k(this,null,function*(){return Promise.resolve(q(b({},this.getDefaultHeaders()),{Accept:"text/event-stream"}))})}getStreamChatData(e,s,o){return k(this,null,function*(){let t=this.transformConfig(e,s,o),n=this.transformMessages(s);if(n.messages&&n.messages.length===0)throw new provider.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:n.messages,stream:!0}))})}transformStreamChatResponseChunk(e,s){return ie(this,null,function*(){var l,p,g,T,x,O,I,R,D,S;let o=s+e,t=[],n="",r=0;for(;r<o.length;){let A=o.indexOf(`
`,r);if(A===-1){n=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),L={partialMessages:[]},H=!1;if((C.type==="response.output_text.delta"||C.type==="output_text.delta")&&typeof C.delta=="string"&&C.delta.length>0&&(L.partialMessages.push(types.createPartialTextMessage(types.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&&(L.partialMessages.push(types.createPartialTextMessage(types.AssistantRoleLiteral,G.text)),H=!0);}if(!H&&C.delta){let G=C.delta;typeof G=="string"&&G.length>0?(L.partialMessages.push(types.createPartialTextMessage(types.AssistantRoleLiteral,G)),H=!0):G&&typeof G=="object"&&G.text!==void 0&&G.text!==null?(L.partialMessages.push(types.createPartialTextMessage(types.AssistantRoleLiteral,G.text)),H=!0):Array.isArray(G.content)&&G.content.forEach(P=>{var V,me,de,ce;if((P==null?void 0:P.type)==="output_text"&&(P!=null&&P.text))L.partialMessages.push(types.createPartialTextMessage(types.AssistantRoleLiteral,P.text)),H=!0;else if((P==null?void 0:P.type)==="tool_call"&&(P!=null&&P.tool_call)){let E=P.tool_call;L.partialMessages.push(types.createPartialToolCallMessage(types.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;L.partialMessages.push(types.createPartialToolCallMessage(types.AssistantRoleLiteral,(p=G.index)!=null?p:0,(g=G.id)!=null?g:"",(T=G.function)==null?void 0:T.name,(x=G.function)==null?void 0:x.arguments));}if(!C.delta&&(C.output||C.outputs)){let G=C.output||C.outputs;Array.isArray(G)&&G.forEach(P=>{var V,me,de,ce;if((P==null?void 0:P.type)==="message"&&Array.isArray(P.content))P.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))L.partialMessages.push(types.createPartialTextMessage(types.AssistantRoleLiteral,E.text));else if((E==null?void 0:E.type)==="tool_call"&&(E!=null&&E.tool_call)){let Te=E.tool_call;L.partialMessages.push(types.createPartialToolCallMessage(types.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(((P==null?void 0:P.type)==="text"||(P==null?void 0:P.type)==="output_text")&&(P!=null&&P.text))L.partialMessages.push(types.createPartialTextMessage(types.AssistantRoleLiteral,P.text));else if((P==null?void 0:P.type)==="tool_call"&&(P!=null&&P.tool_call)){let E=P.tool_call;L.partialMessages.push(types.createPartialToolCallMessage(types.AssistantRoleLiteral,(V=E.index)!=null?V:0,(me=E.id)!=null?me:"",(de=E.function)