@mcp-use/inspector 0.9.2 → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/client/assets/{browser-BaWfMf0m.js → browser-B0j7NxIO.js} +24 -24
- package/dist/client/assets/{display-A5IEINAP-C7C5ZEWf.js → display-A5IEINAP-D6ub1rVT.js} +2 -2
- package/dist/client/assets/{embeddings-Cd_IFijr.js → embeddings-DSYSWoMY.js} +1 -1
- package/dist/client/assets/{index-D-t8kYzy.js → index-BOKDheu2.js} +1 -1
- package/dist/client/assets/index-BlKiZ9Yy.css +1 -0
- package/dist/client/assets/index-C1fAPMt_.js +8 -0
- package/dist/client/assets/index-C86qnUPq.js +1683 -0
- package/dist/client/assets/{index-BaFuUxbj.js → index-CmrpwsvF.js} +1 -1
- package/dist/client/assets/index-DLvycrCn.js +80 -0
- package/dist/client/assets/{index-BDueMm07.js → index-DMpSV0MO.js} +2 -2
- package/dist/client/assets/{index-Dwx0D9tm.js → index-dcwAFu32.js} +11 -11
- package/dist/client/assets/{index-FfhUz5GP.js → index-jXEm6Yfx.js} +3 -3
- package/dist/client/assets/index-uLaqVHqx.js +71 -0
- package/dist/client/assets/{winston-D_OHtP4E.js → winston-BG6TqujU.js} +1 -1
- package/dist/client/index.html +3 -3
- package/package.json +2 -2
- package/dist/client/assets/index-BxlzAdRz.js +0 -150
- package/dist/client/assets/index-CHNXgq6o.css +0 -1
- package/dist/client/assets/index-CejJnjhQ.js +0 -8
- package/dist/client/assets/index-DZxMwvFi.js +0 -1683
|
@@ -1,24 +1,24 @@
|
|
|
1
|
-
import{
|
|
2
|
-
`)}function
|
|
3
|
-
`)}function ut(t,e){if(Ua(t))return t.anyOf.map(n=>ut(n,e)).join(" | ");switch(t.type){case"string":return t.enum?t.enum.map(n=>`"${n}"`).join(" | "):"string";case"number":return t.enum?t.enum.map(n=>`${n}`).join(" | "):"number";case"integer":return t.enum?t.enum.map(n=>`${n}`).join(" | "):"number";case"boolean":return"boolean";case"null":return"null";case"object":return["{"
|
|
1
|
+
import{E as Ss,aG as S,S as xa,Q as ka,K as jn,g as Ke,x as Ze,a9 as Sa,am as Aa,L as Ca,H as As,I as Cs,z as ke,l as Os,aH as Oa,D as cn,aI as Ln,aJ as Ia,aK as Ta,aL as Ra,J as Dn,aM as Fn,aN as $a,B as Jt,a as Pa}from"./index-DLvycrCn.js";import{e as Ea,j as Ma,h as Na,f as Is,S as Bn,J as Un,R as Wn}from"./index-uLaqVHqx.js";import{t as Ts,d as ja}from"./index-C86qnUPq.js";import{J as qn,c as La,p as Rs,m as Kt}from"./index-C1fAPMt_.js";import"./embeddings-DSYSWoMY.js";import"./index-DRz5BQNA.js";const xe=t=>t();function Be(t){return t?!!(/^o\d/.test(t??"")||t.startsWith("gpt-5")&&!t.startsWith("gpt-5-chat")):!1}function Da(t){return t.role!=="system"&&t.role!=="developer"&&t.role!=="assistant"&&t.role!=="user"&&t.role!=="function"&&t.role!=="tool"&&console.warn(`Unknown message role: ${t.role}`),t.role}function Ue(t){const e=t._getType();switch(e){case"system":return"system";case"ai":return"assistant";case"human":return"user";case"function":return"function";case"tool":return"tool";case"generic":if(!Ss.isInstance(t))throw new Error("Invalid generic chat message");return Da(t);default:throw new Error(`Unknown message type: ${e}`)}}function Fa(t){const{azureOpenAIApiDeploymentName:e,azureOpenAIApiInstanceName:n,azureOpenAIApiKey:s,azureOpenAIBasePath:r,baseURL:a,azureADTokenProvider:i,azureOpenAIEndpoint:o}=t;if((s||i)&&r&&e)return`${r}/${e}`;if((s||i)&&o&&e)return`${o}/openai/deployments/${e}`;if(s||i){if(!n)throw new Error("azureOpenAIApiInstanceName is required when using azureOpenAIApiKey");if(!e)throw new Error("azureOpenAIApiDeploymentName is a required parameter when using azureOpenAIApiKey");return`https://${n}.openai.azure.com/openai/deployments/${e}`}return a}function Ba(t,e){let n;return Ea(t)?n=Ma(t):n=t,e?.strict!==void 0&&(n.function.strict=e.strict),n}function Ua(t){return t.anyOf!==void 0&&Array.isArray(t.anyOf)}function Wa(t){const e=["namespace functions {",""];for(const n of t)n.description&&e.push(`// ${n.description}`),Object.keys(n.parameters.properties??{}).length>0?(e.push(`type ${n.name} = (_: {`),e.push($s(n.parameters,0)),e.push("}) => any;")):e.push(`type ${n.name} = () => any;`),e.push("");return e.push("} // namespace functions"),e.join(`
|
|
2
|
+
`)}function $s(t,e){const n=[];for(const[s,r]of Object.entries(t.properties??{}))r.description&&e<2&&n.push(`// ${r.description}`),t.required?.includes(s)?n.push(`${s}: ${ut(r,e)},`):n.push(`${s}?: ${ut(r,e)},`);return n.map(s=>" ".repeat(e)+s).join(`
|
|
3
|
+
`)}function ut(t,e){if(Ua(t))return t.anyOf.map(n=>ut(n,e)).join(" | ");switch(t.type){case"string":return t.enum?t.enum.map(n=>`"${n}"`).join(" | "):"string";case"number":return t.enum?t.enum.map(n=>`${n}`).join(" | "):"number";case"integer":return t.enum?t.enum.map(n=>`${n}`).join(" | "):"number";case"boolean":return"boolean";case"null":return"null";case"object":return["{",$s(t,e+2),"}"].join(`
|
|
4
4
|
`);case"array":return t.items?`${ut(t.items,e)}[]`:"any[]";default:return""}}function Ps(t){if(t)return t==="any"||t==="required"?"required":t==="auto"?"auto":t==="none"?"none":typeof t=="string"?{type:"function",function:{name:t}}:t}function un(t){return"type"in t&&t.type!=="function"}function qa(t){return t!=null&&typeof t=="object"&&"type"in t&&t.type!=="function"}function dt(t){return typeof t=="object"&&t!==null&&"metadata"in t&&typeof t.metadata=="object"&&t.metadata!==null&&"customTool"in t.metadata&&typeof t.metadata.customTool=="object"&&t.metadata.customTool!==null}function Es(t){return"type"in t&&t.type==="custom"&&"custom"in t&&typeof t.custom=="object"&&t.custom!==null}function Ja(t){if(t.type==="custom_tool_call")return{...t,type:"tool_call",call_id:t.id,id:t.call_id,name:t.name,isCustomTool:!0,args:{input:t.input}}}function Ka(t){return t.type==="tool_call"&&"isCustomTool"in t&&t.isCustomTool===!0}function Za(t){const e=()=>{if(t.custom.format){if(t.custom.format.type==="grammar")return{type:"grammar",definition:t.custom.format.grammar.definition,syntax:t.custom.format.grammar.syntax};if(t.custom.format.type==="text")return{type:"text"}}};return{type:"custom",name:t.custom.name,description:t.custom.description,format:e()}}function za(t){const e=()=>{if(t.format){if(t.format.type==="grammar")return{type:"grammar",grammar:{definition:t.format.definition,syntax:t.format.syntax}};if(t.format.type==="text")return{type:"text"}}};return{type:"custom",custom:{name:t.name,description:t.description,format:e()}}}function Zt(t){return typeof t=="object"&&t!==null&&("name"in t&&t.name==="AbortError"||"message"in t&&String(t.message).includes("FetchRequestCanceledException"))}const zt=t=>{if(t instanceof Error)return t;if(typeof t=="object"&&t!==null){try{if(Object.prototype.toString.call(t)==="[object Error]"){const e=new Error(t.message,t.cause?{cause:t.cause}:{});return t.stack&&(e.stack=t.stack),t.cause&&!e.cause&&(e.cause=t.cause),t.name&&(e.name=t.name),e}}catch{}try{return new Error(JSON.stringify(t))}catch{}}return new Error(t)};class x extends Error{}class q extends x{constructor(e,n,s,r){super(`${q.makeMessage(e,n,s)}`),this.status=e,this.headers=r,this.requestID=r?.get("x-request-id"),this.error=n;const a=n;this.code=a?.code,this.param=a?.param,this.type=a?.type}static makeMessage(e,n,s){const r=n?.message?typeof n.message=="string"?n.message:JSON.stringify(n.message):n?JSON.stringify(n):s;return e&&r?`${e} ${r}`:e?`${e} status code (no body)`:r||"(no status code or body)"}static generate(e,n,s,r){if(!e||!r)return new kt({message:s,cause:zt(n)});const a=n?.error;return e===400?new Ms(e,a,s,r):e===401?new Ns(e,a,s,r):e===403?new js(e,a,s,r):e===404?new Ls(e,a,s,r):e===409?new Ds(e,a,s,r):e===422?new Fs(e,a,s,r):e===429?new Bs(e,a,s,r):e>=500?new Us(e,a,s,r):new q(e,a,s,r)}}class X extends q{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class kt extends q{constructor({message:e,cause:n}){super(void 0,void 0,e||"Connection error.",void 0),n&&(this.cause=n)}}class St extends kt{constructor({message:e}={}){super({message:e??"Request timed out."})}}class Ms extends q{}class Ns extends q{}class js extends q{}class Ls extends q{}class Ds extends q{}class Fs extends q{}class Bs extends q{}class Us extends q{}class Ws extends x{constructor(){super("Could not parse response content as the length limit was reached")}}class qs extends x{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}class Oe extends Error{constructor(e){super(e)}}function ht(t){return t!==void 0&&"function"in t&&t.function!==void 0}function Ha(t,e){const n={...t};return Object.defineProperties(n,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:e,enumerable:!1}}),n}function dn(t){return t?.$brand==="auto-parseable-response-format"}function We(t){return t?.$brand==="auto-parseable-tool"}function Va(t,e){return!e||!Js(e)?{...t,choices:t.choices.map(n=>(Ks(n.message.tool_calls),{...n,message:{...n.message,parsed:null,...n.message.tool_calls?{tool_calls:n.message.tool_calls}:void 0}}))}:hn(t,e)}function hn(t,e){const n=t.choices.map(s=>{if(s.finish_reason==="length")throw new Ws;if(s.finish_reason==="content_filter")throw new qs;return Ks(s.message.tool_calls),{...s,message:{...s.message,...s.message.tool_calls?{tool_calls:s.message.tool_calls?.map(r=>Ga(e,r))??void 0}:void 0,parsed:s.message.content&&!s.message.refusal?Xa(e,s.message.content):null}}});return{...t,choices:n}}function Xa(t,e){return t.response_format?.type!=="json_schema"?null:t.response_format?.type==="json_schema"?"$parseRaw"in t.response_format?t.response_format.$parseRaw(e):JSON.parse(e):null}function Ga(t,e){const n=t.tools?.find(s=>ht(s)&&s.function?.name===e.function.name);return{...e,function:{...e.function,parsed_arguments:We(n)?n.$parseRaw(e.function.arguments):n?.function.strict?JSON.parse(e.function.arguments):null}}}function Qa(t,e){if(!t||!("tools"in t)||!t.tools)return!1;const n=t.tools?.find(s=>ht(s)&&s.function?.name===e.function.name);return ht(n)&&(We(n)||n?.function.strict||!1)}function Js(t){return dn(t.response_format)?!0:t.tools?.some(e=>We(e)||e.type==="function"&&e.function.strict===!0)??!1}function Ks(t){for(const e of t||[])if(e.type!=="function")throw new x(`Currently only \`function\` tool calls are supported; Received \`${e.type}\``)}function Ya(t){for(const e of t??[]){if(e.type!=="function")throw new x(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)throw new x(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}const ei=Symbol("Let zodToJsonSchema decide on which parser to use"),Jn={name:void 0,$refStrategy:"root",effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",nullableStrategy:"from-target",removeAdditionalStrategy:"passthrough",definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},ti=t=>typeof t=="string"?{...Jn,basePath:["#"],definitions:{},name:t}:{...Jn,basePath:["#"],definitions:{},...t},Ht=t=>"_def"in t?t._def:t;function ni(t){if(!t)return!0;for(const e in t)return!1;return!0}const si=t=>{const e=ti(t),n=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,currentPath:n,propertyPath:void 0,seenRefs:new Set,seen:new Map(Object.entries(e.definitions).map(([s,r])=>[Ht(r),{def:Ht(r),path:[...e.basePath,e.definitionPath,s],jsonSchema:void 0}]))}};function Zs(t,e,n,s){s?.errorMessages&&n&&(t.errorMessage={...t.errorMessage,[e]:n})}function T(t,e,n,s,r){t[e]=n,Zs(t,e,s,r)}function ri(){return{}}function ai(t,e){const n={type:"array"};return t.type?._def?.typeName!==S.ZodAny&&(n.items=O(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&T(n,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&T(n,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(T(n,"minItems",t.exactLength.value,t.exactLength.message,e),T(n,"maxItems",t.exactLength.value,t.exactLength.message,e)),n}function ii(t,e){const n={type:"integer",format:"int64"};if(!t.checks)return n;for(const s of t.checks)switch(s.kind){case"min":e.target==="jsonSchema7"?s.inclusive?T(n,"minimum",s.value,s.message,e):T(n,"exclusiveMinimum",s.value,s.message,e):(s.inclusive||(n.exclusiveMinimum=!0),T(n,"minimum",s.value,s.message,e));break;case"max":e.target==="jsonSchema7"?s.inclusive?T(n,"maximum",s.value,s.message,e):T(n,"exclusiveMaximum",s.value,s.message,e):(s.inclusive||(n.exclusiveMaximum=!0),T(n,"maximum",s.value,s.message,e));break;case"multipleOf":T(n,"multipleOf",s.value,s.message,e);break}return n}function oi(){return{type:"boolean"}}function li(t,e){return O(t.type._def,e)}const ci=(t,e)=>O(t.innerType._def,e);function zs(t,e,n){const s=n??e.dateStrategy;if(Array.isArray(s))return{anyOf:s.map((r,a)=>zs(t,e,r))};switch(s){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return ui(t,e)}}const ui=(t,e)=>{const n={type:"integer",format:"unix-time"};if(e.target==="openApi3")return n;for(const s of t.checks)switch(s.kind){case"min":T(n,"minimum",s.value,s.message,e);break;case"max":T(n,"maximum",s.value,s.message,e);break}return n};function di(t,e){return{...O(t.innerType._def,e),default:t.defaultValue()}}function hi(t,e,n){return e.effectStrategy==="input"?O(t.schema._def,e,n):{}}function fi(t){return{type:"string",enum:[...t.values]}}const pi=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function mi(t,e){const n=[O(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),O(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(a=>!!a);let s=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0;const r=[];return n.forEach(a=>{if(pi(a))r.push(...a.allOf),a.unevaluatedProperties===void 0&&(s=void 0);else{let i=a;if("additionalProperties"in a&&a.additionalProperties===!1){const{additionalProperties:o,...c}=a;i=c}else s=void 0;r.push(i)}}),r.length?{allOf:r,...s}:void 0}function _i(t,e){const n=typeof t.value;return n!=="bigint"&&n!=="number"&&n!=="boolean"&&n!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:n==="bigint"?"integer":n,enum:[t.value]}:{type:n==="bigint"?"integer":n,const:t.value}}let Nt;const le={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(Nt===void 0&&(Nt=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Nt),base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/};function Hs(t,e){const n={type:"string"};function s(r){return e.patternStrategy==="escape"?gi(r):r}if(t.checks)for(const r of t.checks)switch(r.kind){case"min":T(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,r.message,e);break;case"max":T(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value,r.message,e);break;case"email":switch(e.emailStrategy){case"format:email":G(n,"email",r.message,e);break;case"format:idn-email":G(n,"idn-email",r.message,e);break;case"pattern:zod":Q(n,le.email,r.message,e);break}break;case"url":G(n,"uri",r.message,e);break;case"uuid":G(n,"uuid",r.message,e);break;case"regex":Q(n,r.regex,r.message,e);break;case"cuid":Q(n,le.cuid,r.message,e);break;case"cuid2":Q(n,le.cuid2,r.message,e);break;case"startsWith":Q(n,RegExp(`^${s(r.value)}`),r.message,e);break;case"endsWith":Q(n,RegExp(`${s(r.value)}$`),r.message,e);break;case"datetime":G(n,"date-time",r.message,e);break;case"date":G(n,"date",r.message,e);break;case"time":G(n,"time",r.message,e);break;case"duration":G(n,"duration",r.message,e);break;case"length":T(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,r.message,e),T(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value,r.message,e);break;case"includes":{Q(n,RegExp(s(r.value)),r.message,e);break}case"ip":{r.version!=="v6"&&G(n,"ipv4",r.message,e),r.version!=="v4"&&G(n,"ipv6",r.message,e);break}case"emoji":Q(n,le.emoji,r.message,e);break;case"ulid":{Q(n,le.ulid,r.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{G(n,"binary",r.message,e);break}case"contentEncoding:base64":{T(n,"contentEncoding","base64",r.message,e);break}case"pattern:zod":{Q(n,le.base64,r.message,e);break}}break}case"nanoid":Q(n,le.nanoid,r.message,e)}return n}const gi=t=>Array.from(t).map(e=>/[a-zA-Z0-9]/.test(e)?e:`\\${e}`).join(""),G=(t,e,n,s)=>{t.format||t.anyOf?.some(r=>r.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&s.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...n&&s.errorMessages&&{errorMessage:{format:n}}})):T(t,"format",e,n,s)},Q=(t,e,n,s)=>{t.pattern||t.allOf?.some(r=>r.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&s.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:Kn(e,s),...n&&s.errorMessages&&{errorMessage:{pattern:n}}})):T(t,"pattern",Kn(e,s),n,s)},Kn=(t,e)=>{const n=typeof t=="function"?t():t;if(!e.applyRegexFlags||!n.flags)return n.source;const s={i:n.flags.includes("i"),m:n.flags.includes("m"),s:n.flags.includes("s")},r=s.i?n.source.toLowerCase():n.source;let a="",i=!1,o=!1,c=!1;for(let l=0;l<r.length;l++){if(i){a+=r[l],i=!1;continue}if(s.i){if(o){if(r[l].match(/[a-z]/)){c?(a+=r[l],a+=`${r[l-2]}-${r[l]}`.toUpperCase(),c=!1):r[l+1]==="-"&&r[l+2]?.match(/[a-z]/)?(a+=r[l],c=!0):a+=`${r[l]}${r[l].toUpperCase()}`;continue}}else if(r[l].match(/[a-z]/)){a+=`[${r[l]}${r[l].toUpperCase()}]`;continue}}if(s.m){if(r[l]==="^"){a+=`(^|(?<=[\r
|
|
5
5
|
]))`;continue}else if(r[l]==="$"){a+=`($|(?=[\r
|
|
6
6
|
]))`;continue}}if(s.s&&r[l]==="."){a+=o?`${r[l]}\r
|
|
7
7
|
`:`[${r[l]}\r
|
|
8
|
-
]`;continue}a+=r[l],r[l]==="\\"?i=!0:o&&r[l]==="]"?o=!1:!o&&r[l]==="["&&(o=!0)}try{const l=new RegExp(a)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),n.source}return a};function Vs(t,e){if(e.target==="openApi3"&&t.keyType?._def.typeName===S.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((s,r)=>({...s,[r]:O(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",r]})??{}}),{}),additionalProperties:!1};const n={type:"object",additionalProperties:O(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??{}};if(e.target==="openApi3")return n;if(t.keyType?._def.typeName===S.ZodString&&t.keyType._def.checks?.length){const s=Object.entries(Hs(t.keyType._def,e)).reduce((r,[a,i])=>a==="type"?r:{...r,[a]:i},{});return{...n,propertyNames:s}}else if(t.keyType?._def.typeName===S.ZodEnum)return{...n,propertyNames:{enum:t.keyType._def.values}};return n}function yi(t,e){if(e.mapStrategy==="record")return Vs(t,e);const n=O(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},s=O(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||{};return{type:"array",maxItems:125,items:{type:"array",items:[n,s],minItems:2,maxItems:2}}}function wi(t){const e=t.values,s=Object.keys(t.values).filter(a=>typeof e[e[a]]!="number").map(a=>e[a]),r=Array.from(new Set(s.map(a=>typeof a)));return{type:r.length===1?r[0]==="string"?"string":"number":["string","number"],enum:s}}function bi(){return{not:{}}}function vi(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}const ft={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function xi(t,e){if(e.target==="openApi3")return Zn(t,e);const n=t.options instanceof Map?Array.from(t.options.values()):t.options;if(n.every(s=>s._def.typeName in ft&&(!s._def.checks||!s._def.checks.length))){const s=n.reduce((r,a)=>{const i=ft[a._def.typeName];return i&&!r.includes(i)?[...r,i]:r},[]);return{type:s.length>1?s:s[0]}}else if(n.every(s=>s._def.typeName==="ZodLiteral"&&!s.description)){const s=n.reduce((r,a)=>{const i=typeof a._def.value;switch(i){case"string":case"number":case"boolean":return[...r,i];case"bigint":return[...r,"integer"];case"object":if(a._def.value===null)return[...r,"null"];case"symbol":case"undefined":case"function":default:return r}},[]);if(s.length===n.length){const r=s.filter((a,i,o)=>o.indexOf(a)===i);return{type:r.length>1?r:r[0],enum:n.reduce((a,i)=>a.includes(i._def.value)?a:[...a,i._def.value],[])}}}else if(n.every(s=>s._def.typeName==="ZodEnum"))return{type:"string",enum:n.reduce((s,r)=>[...s,...r._def.values.filter(a=>!s.includes(a))],[])};return Zn(t,e)}const Zn=(t,e)=>{const n=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((s,r)=>O(s._def,{...e,currentPath:[...e.currentPath,"anyOf",`${r}`]})).filter(s=>!!s&&(!e.strictUnions||typeof s=="object"&&Object.keys(s).length>0));return n.length?{anyOf:n}:void 0};function ki(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"||e.nullableStrategy==="property"?{type:ft[t.innerType._def.typeName],nullable:!0}:{type:[ft[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){const s=O(t.innerType._def,{...e,currentPath:[...e.currentPath]});return s&&"$ref"in s?{allOf:[s],nullable:!0}:s&&{...s,nullable:!0}}const n=O(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}function Si(t,e){const n={type:"number"};if(!t.checks)return n;for(const s of t.checks)switch(s.kind){case"int":n.type="integer",Zs(n,"type",s.message,e);break;case"min":e.target==="jsonSchema7"?s.inclusive?T(n,"minimum",s.value,s.message,e):T(n,"exclusiveMinimum",s.value,s.message,e):(s.inclusive||(n.exclusiveMinimum=!0),T(n,"minimum",s.value,s.message,e));break;case"max":e.target==="jsonSchema7"?s.inclusive?T(n,"maximum",s.value,s.message,e):T(n,"exclusiveMaximum",s.value,s.message,e):(s.inclusive||(n.exclusiveMaximum=!0),T(n,"maximum",s.value,s.message,e));break;case"multipleOf":T(n,"multipleOf",s.value,s.message,e);break}return n}function Ai(t,e){return e.removeAdditionalStrategy==="strict"?t.catchall._def.typeName==="ZodNever"?t.unknownKeys!=="strict":O(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0:t.catchall._def.typeName==="ZodNever"?t.unknownKeys==="passthrough":O(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0}function Ci(t,e){const n={type:"object",...Object.entries(t.shape()).reduce((s,[r,a])=>{if(a===void 0||a._def===void 0)return s;const i=[...e.currentPath,"properties",r],o=O(a._def,{...e,currentPath:i,propertyPath:i});if(o===void 0)return s;if(e.openaiStrictMode&&a.isOptional()&&!a.isNullable()&&typeof a._def?.defaultValue>"u")throw new Error(`Zod field at \`${i.join("/")}\` uses \`.optional()\` without \`.nullable()\` which is not supported by the API. See: https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses#all-fields-must-be-required`);return{properties:{...s.properties,[r]:o},required:a.isOptional()&&!e.openaiStrictMode?s.required:[...s.required,r]}},{properties:{},required:[]}),additionalProperties:Ai(t,e)};return n.required.length||delete n.required,n}const Oi=(t,e)=>{if(e.propertyPath&&e.currentPath.slice(0,e.propertyPath.length).toString()===e.propertyPath.toString())return O(t.innerType._def,{...e,currentPath:e.currentPath});const n=O(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return n?{anyOf:[{not:{}},n]}:{}},Ii=(t,e)=>{if(e.pipeStrategy==="input")return O(t.in._def,e);if(e.pipeStrategy==="output")return O(t.out._def,e);const n=O(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),s=O(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",n?"1":"0"]});return{allOf:[n,s].filter(r=>r!==void 0)}};function Ti(t,e){return O(t.type._def,e)}function $i(t,e){const s={type:"array",uniqueItems:!0,items:O(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&T(s,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&T(s,"maxItems",t.maxSize.value,t.maxSize.message,e),s}function Ri(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((n,s)=>O(n._def,{...e,currentPath:[...e.currentPath,"items",`${s}`]})).reduce((n,s)=>s===void 0?n:[...n,s],[]),additionalItems:O(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((n,s)=>O(n._def,{...e,currentPath:[...e.currentPath,"items",`${s}`]})).reduce((n,s)=>s===void 0?n:[...n,s],[])}}function Pi(){return{not:{}}}function Ei(){return{}}const Mi=(t,e)=>O(t.innerType._def,e);function O(t,e,n=!1){const s=e.seen.get(t);if(e.override){const i=e.override?.(t,e,s,n);if(i!==ei)return i}if(s&&!n){const i=Ni(s,e);if(i!==void 0)return"$ref"in i&&e.seenRefs.add(i.$ref),i}const r={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,r);const a=Li(t,t.typeName,e,n);return a&&Di(t,e,a),r.jsonSchema=a,a}const Ni=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"extract-to-root":const n=t.path.slice(e.basePath.length+1).join("_");return n!==e.name&&e.nameStrategy==="duplicate-ref"&&(e.definitions[n]=t.def),{$ref:[...e.basePath,e.definitionPath,n].join("/")};case"relative":return{$ref:ji(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((s,r)=>e.currentPath[r]===s)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),{}):e.$refStrategy==="seen"?{}:void 0}},ji=(t,e)=>{let n=0;for(;n<t.length&&n<e.length&&t[n]===e[n];n++);return[(t.length-n).toString(),...e.slice(n)].join("/")},Li=(t,e,n,s)=>{switch(e){case S.ZodString:return Hs(t,n);case S.ZodNumber:return Si(t,n);case S.ZodObject:return Ci(t,n);case S.ZodBigInt:return ii(t,n);case S.ZodBoolean:return oi();case S.ZodDate:return zs(t,n);case S.ZodUndefined:return Pi();case S.ZodNull:return vi(n);case S.ZodArray:return ai(t,n);case S.ZodUnion:case S.ZodDiscriminatedUnion:return xi(t,n);case S.ZodIntersection:return mi(t,n);case S.ZodTuple:return Ri(t,n);case S.ZodRecord:return Vs(t,n);case S.ZodLiteral:return _i(t,n);case S.ZodEnum:return fi(t);case S.ZodNativeEnum:return wi(t);case S.ZodNullable:return ki(t,n);case S.ZodOptional:return Oi(t,n);case S.ZodMap:return yi(t,n);case S.ZodSet:return $i(t,n);case S.ZodLazy:return O(t.getter()._def,n);case S.ZodPromise:return Ti(t,n);case S.ZodNaN:case S.ZodNever:return bi();case S.ZodEffects:return hi(t,n,s);case S.ZodAny:return ri();case S.ZodUnknown:return Ei();case S.ZodDefault:return di(t,n);case S.ZodBranded:return li(t,n);case S.ZodReadonly:return Mi(t,n);case S.ZodCatch:return ci(t,n);case S.ZodPipeline:return Ii(t,n);case S.ZodFunction:case S.ZodVoid:case S.ZodSymbol:return;default:return(r=>{})()}},Di=(t,e,n)=>(t.description&&(n.description=t.description,e.markdownDescription&&(n.markdownDescription=t.description)),n),Fi=(t,e)=>{const n=si(e),s=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,r=O(t._def,s===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,s]},!1)??{},a=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;a!==void 0&&(r.title=a);const i=(()=>{if(ni(n.definitions))return;const c={},l=new Set;for(let m=0;m<500;m++){const h=Object.entries(n.definitions).filter(([p])=>!l.has(p));if(h.length===0)break;for(const[p,d]of h)c[p]=O(Ht(d),{...n,currentPath:[...n.basePath,n.definitionPath,p]},!0)??{},l.add(p)}return c})(),o=s===void 0?i?{...r,[n.definitionPath]:i}:r:n.nameStrategy==="duplicate-ref"?{...r,...i||n.seenRefs.size?{[n.definitionPath]:{...i,...n.seenRefs.size?{[s]:r}:void 0}}:void 0}:{$ref:[...n.$refStrategy==="relative"?[]:n.basePath,n.definitionPath,s].join("/"),[n.definitionPath]:{...i,[s]:r}};return n.target==="jsonSchema7"?o.$schema="http://json-schema.org/draft-07/schema#":n.target==="jsonSchema2019-09"&&(o.$schema="https://json-schema.org/draft/2019-09/schema#"),o};function Bi(t,e){return!e||!Wi(e)?{...t,output_parsed:null,output:t.output.map(n=>n.type==="function_call"?{...n,parsed_arguments:null}:n.type==="message"?{...n,content:n.content.map(s=>({...s,parsed:null}))}:n)}:Xs(t,e)}function Xs(t,e){const n=t.output.map(r=>{if(r.type==="function_call")return{...r,parsed_arguments:Ki(e,r)};if(r.type==="message"){const a=r.content.map(i=>i.type==="output_text"?{...i,parsed:Ui(e,i.text)}:i);return{...r,content:a}}return r}),s=Object.assign({},t,{output:n});return Object.getOwnPropertyDescriptor(t,"output_text")||Vt(s),Object.defineProperty(s,"output_parsed",{enumerable:!0,get(){for(const r of s.output)if(r.type==="message"){for(const a of r.content)if(a.type==="output_text"&&a.parsed!==null)return a.parsed}return null}}),s}function Ui(t,e){return t.text?.format?.type!=="json_schema"?null:"$parseRaw"in t.text?.format?(t.text?.format).$parseRaw(e):JSON.parse(e)}function Wi(t){return!!dn(t.text?.format)}function qi(t){return t?.$brand==="auto-parseable-tool"}function Ji(t,e){return t.find(n=>n.type==="function"&&n.name===e)}function Ki(t,e){const n=Ji(t.tools??[],e.name);return{...e,...e,parsed_arguments:qi(n)?n.$parseRaw(e.arguments):n?.strict?JSON.parse(e.arguments):null}}function Vt(t){const e=[];for(const n of t.output)if(n.type==="message")for(const s of n.content)s.type==="output_text"&&e.push(s.text);t.output_text=e.join("")}function Zi(t){if(t.type!=="object")throw new Error(`Root schema must have type: 'object' but got type: ${t.type?`'${t.type}'`:"undefined"}`);const e=structuredClone(t);return re(e,[],e)}function Xt(t){if(typeof t=="boolean")return!1;if(t.type==="null")return!0;for(const e of t.oneOf??[])if(Xt(e))return!0;for(const e of t.anyOf??[])if(Xt(e))return!0;return!1}function re(t,e,n){if(typeof t=="boolean")throw new TypeError(`Expected object schema but got boolean; path=${e.join("/")}`);if(!ce(t))throw new TypeError(`Expected ${JSON.stringify(t)} to be an object; path=${e.join("/")}`);const s=t.$defs;if(ce(s))for(const[p,d]of Object.entries(s))re(d,[...e,"$defs",p],n);const r=t.definitions;if(ce(r))for(const[p,d]of Object.entries(r))re(d,[...e,"definitions",p],n);t.type==="object"&&!("additionalProperties"in t)&&(t.additionalProperties=!1);const i=t.required??[],o=t.properties;if(ce(o)){for(const[p,d]of Object.entries(o))if(!Xt(d)&&!i.includes(p))throw new Error(`Zod field at \`${[...e,"properties",p].join("/")}\` uses \`.optional()\` without \`.nullable()\` which is not supported by the API. See: https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses#all-fields-must-be-required`);t.required=Object.keys(o),t.properties=Object.fromEntries(Object.entries(o).map(([p,d])=>[p,re(d,[...e,"properties",p],n)]))}const c=t.items;ce(c)&&(t.items=re(c,[...e,"items"],n));const l=t.anyOf;Array.isArray(l)&&(t.anyOf=l.map((p,d)=>re(p,[...e,"anyOf",String(d)],n)));const m=t.allOf;if(Array.isArray(m))if(m.length===1){const p=re(m[0],[...e,"allOf","0"],n);Object.assign(t,p),delete t.allOf}else t.allOf=m.map((p,d)=>re(p,[...e,"allOf",String(d)],n));t.default===null&&delete t.default;const h=t.$ref;if(h&&Hi(t,1)){if(typeof h!="string")throw new TypeError(`Received non-string $ref - ${h}; path=${e.join("/")}`);const p=zi(n,h);if(typeof p=="boolean")throw new Error(`Expected \`$ref: ${h}\` to resolve to an object schema but got boolean`);if(!ce(p))throw new Error(`Expected \`$ref: ${h}\` to resolve to an object but got ${JSON.stringify(p)}`);return Object.assign(t,{...p,...t}),delete t.$ref,re(t,e,n)}return t}function zi(t,e){if(!e.startsWith("#/"))throw new Error(`Unexpected $ref format ${JSON.stringify(e)}; Does not start with #/`);const n=e.slice(2).split("/");let s=t;for(const r of n){if(!ce(s))throw new Error(`encountered non-object entry while resolving ${e} - ${JSON.stringify(s)}`);const a=s[r];if(a===void 0)throw new Error(`Key ${r} not found while resolving ${e}`);s=a}return s}function ce(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Hi(t,e){let n=0;for(const s in t)if(n++,n>e)return!0;return!1}function Vi(t,e){return Fi(t,{openaiStrictMode:!0,name:e.name,nameStrategy:"duplicate-ref",$refStrategy:"extract-to-root",nullableStrategy:"property"})}function Xi(t){return Zi(Ts(t,{target:"draft-7"}))}function Gi(t){return"_zod"in t}function Qi(t,e,n){return Ha({type:"json_schema",json_schema:{...n,name:e,strict:!0,schema:Gi(t)?Xi(t):Vi(t,{name:e})}},s=>t.parse(JSON.parse(s)))}const zn=["jsonSchema","functionCalling","jsonMode"];function Yi(t,e){if(typeof e<"u"&&!zn.includes(e))throw new Error(`Invalid method: ${e}. Supported methods are: ${zn.join(", ")}`);const n=!t.startsWith("gpt-3")&&!t.startsWith("gpt-4-")&&t!=="gpt-4";if(n&&!e)return"jsonSchema";if(!n&&e==="jsonSchema")throw new Error(`JSON Schema is not supported for model "${t}". Please use a different method, e.g. "functionCalling" or "jsonMode".`);return e??"functionCalling"}function eo(t,e){const n={...t};return Object.defineProperties(n,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:e,enumerable:!1}}),n}function to(t,e,n){if(Sa(t))return Qi(t,e,n);if(Aa(t))return eo({type:"json_schema",json_schema:{...n,name:e,strict:!0,schema:Ts(t,{cycles:"ref",reused:"ref",override(s){s.jsonSchema.title=e}})}},s=>ja(t,JSON.parse(s)));throw new Error("Unsupported schema response format")}function no(t,e){if(e&&typeof e=="object"&&"images"in e&&Array.isArray(e.images)){const n=e.images.filter(s=>typeof s?.image_url?.url=="string").map(s=>({type:"image",url:s.image_url.url}));return[{type:"text",text:t},...n]}return t}function k(t,e,n,s,r){if(typeof e=="function"?t!==e||!0:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(t,n),n}function u(t,e,n,s){if(n==="a"&&!s)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!s:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return n==="m"?s:n==="a"?s.call(t):s?s.value:e.get(t)}let Gs=function(){const{crypto:t}=globalThis;if(t?.randomUUID)return Gs=t.randomUUID.bind(t),t.randomUUID();const e=new Uint8Array(1),n=t?()=>t.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,s=>(+s^n()&15>>+s/4).toString(16))};const so=/^[a-z][a-z0-9+.-]*:/i,ro=t=>so.test(t);let Z=t=>(Z=Array.isArray,Z(t)),Hn=Z;function Qs(t){return typeof t!="object"?{}:t??{}}function ao(t){if(!t)return!0;for(const e in t)return!1;return!0}function io(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function jt(t){return t!=null&&typeof t=="object"&&!Array.isArray(t)}const oo=(t,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new x(`${t} must be an integer`);if(e<0)throw new x(`${t} must be a positive integer`);return e},lo=t=>{try{return JSON.parse(t)}catch{return}},qe=t=>new Promise(e=>setTimeout(e,t)),ye="6.8.1",co=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function uo(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}const ho=()=>{const t=uo();if(t==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ye,"X-Stainless-OS":Xn(Deno.build.os),"X-Stainless-Arch":Vn(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ye,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(t==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ye,"X-Stainless-OS":Xn(globalThis.process.platform??"unknown"),"X-Stainless-Arch":Vn(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};const e=fo();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ye,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ye,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function fo(){if(typeof navigator>"u"||!navigator)return null;const t=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(const{key:e,pattern:n}of t){const s=n.exec(navigator.userAgent);if(s){const r=s[1]||0,a=s[2]||0,i=s[3]||0;return{browser:e,version:`${r}.${a}.${i}`}}}return null}const Vn=t=>t==="x32"?"x32":t==="x86_64"||t==="x64"?"x64":t==="arm"?"arm":t==="aarch64"||t==="arm64"?"arm64":t?`other:${t}`:"unknown",Xn=t=>(t=t.toLowerCase(),t.includes("ios")?"iOS":t==="android"?"Android":t==="darwin"?"MacOS":t==="win32"?"Windows":t==="freebsd"?"FreeBSD":t==="openbsd"?"OpenBSD":t==="linux"?"Linux":t?`Other:${t}`:"Unknown");let Gn;const po=()=>Gn??(Gn=ho());function mo(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function Ys(...t){const e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...t)}function er(t){let e=Symbol.asyncIterator in t?t[Symbol.asyncIterator]():t[Symbol.iterator]();return Ys({start(){},async pull(n){const{done:s,value:r}=await e.next();s?n.close():n.enqueue(r)},async cancel(){await e.return?.()}})}function tr(t){if(t[Symbol.asyncIterator])return t;const e=t.getReader();return{async next(){try{const n=await e.read();return n?.done&&e.releaseLock(),n}catch(n){throw e.releaseLock(),n}},async return(){const n=e.cancel();return e.releaseLock(),await n,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function _o(t){if(t===null||typeof t!="object")return;if(t[Symbol.asyncIterator]){await t[Symbol.asyncIterator]().return?.();return}const e=t.getReader(),n=e.cancel();e.releaseLock(),await n}const go=({headers:t,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)}),nr="RFC3986",sr=t=>String(t),Qn={RFC1738:t=>String(t).replace(/%20/g,"+"),RFC3986:sr},yo="RFC1738";let Gt=(t,e)=>(Gt=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),Gt(t,e));const ee=(()=>{const t=[];for(let e=0;e<256;++e)t.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return t})(),Lt=1024,wo=(t,e,n,s,r)=>{if(t.length===0)return t;let a=t;if(typeof t=="symbol"?a=Symbol.prototype.toString.call(t):typeof t!="string"&&(a=String(t)),n==="iso-8859-1")return escape(a).replace(/%u[0-9a-f]{4}/gi,function(o){return"%26%23"+parseInt(o.slice(2),16)+"%3B"});let i="";for(let o=0;o<a.length;o+=Lt){const c=a.length>=Lt?a.slice(o,o+Lt):a,l=[];for(let m=0;m<c.length;++m){let h=c.charCodeAt(m);if(h===45||h===46||h===95||h===126||h>=48&&h<=57||h>=65&&h<=90||h>=97&&h<=122||r===yo&&(h===40||h===41)){l[l.length]=c.charAt(m);continue}if(h<128){l[l.length]=ee[h];continue}if(h<2048){l[l.length]=ee[192|h>>6]+ee[128|h&63];continue}if(h<55296||h>=57344){l[l.length]=ee[224|h>>12]+ee[128|h>>6&63]+ee[128|h&63];continue}m+=1,h=65536+((h&1023)<<10|c.charCodeAt(m)&1023),l[l.length]=ee[240|h>>18]+ee[128|h>>12&63]+ee[128|h>>6&63]+ee[128|h&63]}i+=l.join("")}return i};function bo(t){return!t||typeof t!="object"?!1:!!(t.constructor&&t.constructor.isBuffer&&t.constructor.isBuffer(t))}function Yn(t,e){if(Z(t)){const n=[];for(let s=0;s<t.length;s+=1)n.push(e(t[s]));return n}return e(t)}const rr={brackets(t){return String(t)+"[]"},comma:"comma",indices(t,e){return String(t)+"["+e+"]"},repeat(t){return String(t)}},ar=function(t,e){Array.prototype.push.apply(t,Z(e)?e:[e])};let es;const j={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:wo,encodeValuesOnly:!1,format:nr,formatter:sr,indices:!1,serializeDate(t){return(es??(es=Function.prototype.call.bind(Date.prototype.toISOString)))(t)},skipNulls:!1,strictNullHandling:!1};function vo(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"||typeof t=="symbol"||typeof t=="bigint"}const Dt={};function ir(t,e,n,s,r,a,i,o,c,l,m,h,p,d,b,w,R,f){let _=t,C=f,I=0,J=!1;for(;(C=C.get(Dt))!==void 0&&!J;){const P=C.get(t);if(I+=1,typeof P<"u"){if(P===I)throw new RangeError("Cyclic object value");J=!0}typeof C.get(Dt)>"u"&&(I=0)}if(typeof l=="function"?_=l(e,_):_ instanceof Date?_=p?.(_):n==="comma"&&Z(_)&&(_=Yn(_,function(P){return P instanceof Date?p?.(P):P})),_===null){if(a)return c&&!w?c(e,j.encoder,R,"key",d):e;_=""}if(vo(_)||bo(_)){if(c){const P=w?e:c(e,j.encoder,R,"key",d);return[b?.(P)+"="+b?.(c(_,j.encoder,R,"value",d))]}return[b?.(e)+"="+b?.(String(_))]}const L=[];if(typeof _>"u")return L;let $;if(n==="comma"&&Z(_))w&&c&&(_=Yn(_,c)),$=[{value:_.length>0?_.join(",")||null:void 0}];else if(Z(l))$=l;else{const P=Object.keys(_);$=m?P.sort(m):P}const B=o?String(e).replace(/\./g,"%2E"):String(e),D=s&&Z(_)&&_.length===1?B+"[]":B;if(r&&Z(_)&&_.length===0)return D+"[]";for(let P=0;P<$.length;++P){const M=$[P],Mn=typeof M=="object"&&typeof M.value<"u"?M.value:_[M];if(i&&Mn===null)continue;const Mt=h&&o?M.replace(/\./g,"%2E"):M,va=Z(_)?typeof n=="function"?n(D,Mt):D:D+(h?"."+Mt:"["+Mt+"]");f.set(t,I);const Nn=new WeakMap;Nn.set(Dt,f),ar(L,ir(Mn,va,n,s,r,a,i,o,n==="comma"&&w&&Z(_)?null:c,l,m,h,p,d,b,w,R,Nn))}return L}function xo(t=j){if(typeof t.allowEmptyArrays<"u"&&typeof t.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof t.encodeDotInKeys<"u"&&typeof t.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(t.encoder!==null&&typeof t.encoder<"u"&&typeof t.encoder!="function")throw new TypeError("Encoder has to be a function.");const e=t.charset||j.charset;if(typeof t.charset<"u"&&t.charset!=="utf-8"&&t.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let n=nr;if(typeof t.format<"u"){if(!Gt(Qn,t.format))throw new TypeError("Unknown format option provided.");n=t.format}const s=Qn[n];let r=j.filter;(typeof t.filter=="function"||Z(t.filter))&&(r=t.filter);let a;if(t.arrayFormat&&t.arrayFormat in rr?a=t.arrayFormat:"indices"in t?a=t.indices?"indices":"repeat":a=j.arrayFormat,"commaRoundTrip"in t&&typeof t.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");const i=typeof t.allowDots>"u"?t.encodeDotInKeys?!0:j.allowDots:!!t.allowDots;return{addQueryPrefix:typeof t.addQueryPrefix=="boolean"?t.addQueryPrefix:j.addQueryPrefix,allowDots:i,allowEmptyArrays:typeof t.allowEmptyArrays=="boolean"?!!t.allowEmptyArrays:j.allowEmptyArrays,arrayFormat:a,charset:e,charsetSentinel:typeof t.charsetSentinel=="boolean"?t.charsetSentinel:j.charsetSentinel,commaRoundTrip:!!t.commaRoundTrip,delimiter:typeof t.delimiter>"u"?j.delimiter:t.delimiter,encode:typeof t.encode=="boolean"?t.encode:j.encode,encodeDotInKeys:typeof t.encodeDotInKeys=="boolean"?t.encodeDotInKeys:j.encodeDotInKeys,encoder:typeof t.encoder=="function"?t.encoder:j.encoder,encodeValuesOnly:typeof t.encodeValuesOnly=="boolean"?t.encodeValuesOnly:j.encodeValuesOnly,filter:r,format:n,formatter:s,serializeDate:typeof t.serializeDate=="function"?t.serializeDate:j.serializeDate,skipNulls:typeof t.skipNulls=="boolean"?t.skipNulls:j.skipNulls,sort:typeof t.sort=="function"?t.sort:null,strictNullHandling:typeof t.strictNullHandling=="boolean"?t.strictNullHandling:j.strictNullHandling}}function ko(t,e={}){let n=t;const s=xo(e);let r,a;typeof s.filter=="function"?(a=s.filter,n=a("",n)):Z(s.filter)&&(a=s.filter,r=a);const i=[];if(typeof n!="object"||n===null)return"";const o=rr[s.arrayFormat],c=o==="comma"&&s.commaRoundTrip;r||(r=Object.keys(n)),s.sort&&r.sort(s.sort);const l=new WeakMap;for(let p=0;p<r.length;++p){const d=r[p];s.skipNulls&&n[d]===null||ar(i,ir(n[d],d,o,c,s.allowEmptyArrays,s.strictNullHandling,s.skipNulls,s.encodeDotInKeys,s.encode?s.encoder:null,s.filter,s.sort,s.allowDots,s.serializeDate,s.format,s.formatter,s.encodeValuesOnly,s.charset,l))}const m=i.join(s.delimiter);let h=s.addQueryPrefix===!0?"?":"";return s.charsetSentinel&&(s.charset==="iso-8859-1"?h+="utf8=%26%2310003%3B&":h+="utf8=%E2%9C%93&"),m.length>0?h+m:""}function So(t){let e=0;for(const r of t)e+=r.length;const n=new Uint8Array(e);let s=0;for(const r of t)n.set(r,s),s+=r.length;return n}let ts;function fn(t){let e;return(ts??(e=new globalThis.TextEncoder,ts=e.encode.bind(e)))(t)}let ns;function ss(t){let e;return(ns??(e=new globalThis.TextDecoder,ns=e.decode.bind(e)))(t)}var z,H;class At{constructor(){z.set(this,void 0),H.set(this,void 0),k(this,z,new Uint8Array),k(this,H,null)}decode(e){if(e==null)return[];const n=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?fn(e):e;k(this,z,So([u(this,z,"f"),n]));const s=[];let r;for(;(r=Ao(u(this,z,"f"),u(this,H,"f")))!=null;){if(r.carriage&&u(this,H,"f")==null){k(this,H,r.index);continue}if(u(this,H,"f")!=null&&(r.index!==u(this,H,"f")+1||r.carriage)){s.push(ss(u(this,z,"f").subarray(0,u(this,H,"f")-1))),k(this,z,u(this,z,"f").subarray(u(this,H,"f"))),k(this,H,null);continue}const a=u(this,H,"f")!==null?r.preceding-1:r.preceding,i=ss(u(this,z,"f").subarray(0,a));s.push(i),k(this,z,u(this,z,"f").subarray(r.index)),k(this,H,null)}return s}flush(){return u(this,z,"f").length?this.decode(`
|
|
8
|
+
]`;continue}a+=r[l],r[l]==="\\"?i=!0:o&&r[l]==="]"?o=!1:!o&&r[l]==="["&&(o=!0)}try{const l=new RegExp(a)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),n.source}return a};function Vs(t,e){if(e.target==="openApi3"&&t.keyType?._def.typeName===S.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((s,r)=>({...s,[r]:O(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",r]})??{}}),{}),additionalProperties:!1};const n={type:"object",additionalProperties:O(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??{}};if(e.target==="openApi3")return n;if(t.keyType?._def.typeName===S.ZodString&&t.keyType._def.checks?.length){const s=Object.entries(Hs(t.keyType._def,e)).reduce((r,[a,i])=>a==="type"?r:{...r,[a]:i},{});return{...n,propertyNames:s}}else if(t.keyType?._def.typeName===S.ZodEnum)return{...n,propertyNames:{enum:t.keyType._def.values}};return n}function yi(t,e){if(e.mapStrategy==="record")return Vs(t,e);const n=O(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},s=O(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||{};return{type:"array",maxItems:125,items:{type:"array",items:[n,s],minItems:2,maxItems:2}}}function wi(t){const e=t.values,s=Object.keys(t.values).filter(a=>typeof e[e[a]]!="number").map(a=>e[a]),r=Array.from(new Set(s.map(a=>typeof a)));return{type:r.length===1?r[0]==="string"?"string":"number":["string","number"],enum:s}}function bi(){return{not:{}}}function vi(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}const ft={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function xi(t,e){if(e.target==="openApi3")return Zn(t,e);const n=t.options instanceof Map?Array.from(t.options.values()):t.options;if(n.every(s=>s._def.typeName in ft&&(!s._def.checks||!s._def.checks.length))){const s=n.reduce((r,a)=>{const i=ft[a._def.typeName];return i&&!r.includes(i)?[...r,i]:r},[]);return{type:s.length>1?s:s[0]}}else if(n.every(s=>s._def.typeName==="ZodLiteral"&&!s.description)){const s=n.reduce((r,a)=>{const i=typeof a._def.value;switch(i){case"string":case"number":case"boolean":return[...r,i];case"bigint":return[...r,"integer"];case"object":if(a._def.value===null)return[...r,"null"];case"symbol":case"undefined":case"function":default:return r}},[]);if(s.length===n.length){const r=s.filter((a,i,o)=>o.indexOf(a)===i);return{type:r.length>1?r:r[0],enum:n.reduce((a,i)=>a.includes(i._def.value)?a:[...a,i._def.value],[])}}}else if(n.every(s=>s._def.typeName==="ZodEnum"))return{type:"string",enum:n.reduce((s,r)=>[...s,...r._def.values.filter(a=>!s.includes(a))],[])};return Zn(t,e)}const Zn=(t,e)=>{const n=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((s,r)=>O(s._def,{...e,currentPath:[...e.currentPath,"anyOf",`${r}`]})).filter(s=>!!s&&(!e.strictUnions||typeof s=="object"&&Object.keys(s).length>0));return n.length?{anyOf:n}:void 0};function ki(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"||e.nullableStrategy==="property"?{type:ft[t.innerType._def.typeName],nullable:!0}:{type:[ft[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){const s=O(t.innerType._def,{...e,currentPath:[...e.currentPath]});return s&&"$ref"in s?{allOf:[s],nullable:!0}:s&&{...s,nullable:!0}}const n=O(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}function Si(t,e){const n={type:"number"};if(!t.checks)return n;for(const s of t.checks)switch(s.kind){case"int":n.type="integer",Zs(n,"type",s.message,e);break;case"min":e.target==="jsonSchema7"?s.inclusive?T(n,"minimum",s.value,s.message,e):T(n,"exclusiveMinimum",s.value,s.message,e):(s.inclusive||(n.exclusiveMinimum=!0),T(n,"minimum",s.value,s.message,e));break;case"max":e.target==="jsonSchema7"?s.inclusive?T(n,"maximum",s.value,s.message,e):T(n,"exclusiveMaximum",s.value,s.message,e):(s.inclusive||(n.exclusiveMaximum=!0),T(n,"maximum",s.value,s.message,e));break;case"multipleOf":T(n,"multipleOf",s.value,s.message,e);break}return n}function Ai(t,e){return e.removeAdditionalStrategy==="strict"?t.catchall._def.typeName==="ZodNever"?t.unknownKeys!=="strict":O(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0:t.catchall._def.typeName==="ZodNever"?t.unknownKeys==="passthrough":O(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0}function Ci(t,e){const n={type:"object",...Object.entries(t.shape()).reduce((s,[r,a])=>{if(a===void 0||a._def===void 0)return s;const i=[...e.currentPath,"properties",r],o=O(a._def,{...e,currentPath:i,propertyPath:i});if(o===void 0)return s;if(e.openaiStrictMode&&a.isOptional()&&!a.isNullable()&&typeof a._def?.defaultValue>"u")throw new Error(`Zod field at \`${i.join("/")}\` uses \`.optional()\` without \`.nullable()\` which is not supported by the API. See: https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses#all-fields-must-be-required`);return{properties:{...s.properties,[r]:o},required:a.isOptional()&&!e.openaiStrictMode?s.required:[...s.required,r]}},{properties:{},required:[]}),additionalProperties:Ai(t,e)};return n.required.length||delete n.required,n}const Oi=(t,e)=>{if(e.propertyPath&&e.currentPath.slice(0,e.propertyPath.length).toString()===e.propertyPath.toString())return O(t.innerType._def,{...e,currentPath:e.currentPath});const n=O(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return n?{anyOf:[{not:{}},n]}:{}},Ii=(t,e)=>{if(e.pipeStrategy==="input")return O(t.in._def,e);if(e.pipeStrategy==="output")return O(t.out._def,e);const n=O(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),s=O(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",n?"1":"0"]});return{allOf:[n,s].filter(r=>r!==void 0)}};function Ti(t,e){return O(t.type._def,e)}function Ri(t,e){const s={type:"array",uniqueItems:!0,items:O(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&T(s,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&T(s,"maxItems",t.maxSize.value,t.maxSize.message,e),s}function $i(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((n,s)=>O(n._def,{...e,currentPath:[...e.currentPath,"items",`${s}`]})).reduce((n,s)=>s===void 0?n:[...n,s],[]),additionalItems:O(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((n,s)=>O(n._def,{...e,currentPath:[...e.currentPath,"items",`${s}`]})).reduce((n,s)=>s===void 0?n:[...n,s],[])}}function Pi(){return{not:{}}}function Ei(){return{}}const Mi=(t,e)=>O(t.innerType._def,e);function O(t,e,n=!1){const s=e.seen.get(t);if(e.override){const i=e.override?.(t,e,s,n);if(i!==ei)return i}if(s&&!n){const i=Ni(s,e);if(i!==void 0)return"$ref"in i&&e.seenRefs.add(i.$ref),i}const r={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,r);const a=Li(t,t.typeName,e,n);return a&&Di(t,e,a),r.jsonSchema=a,a}const Ni=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"extract-to-root":const n=t.path.slice(e.basePath.length+1).join("_");return n!==e.name&&e.nameStrategy==="duplicate-ref"&&(e.definitions[n]=t.def),{$ref:[...e.basePath,e.definitionPath,n].join("/")};case"relative":return{$ref:ji(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((s,r)=>e.currentPath[r]===s)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),{}):e.$refStrategy==="seen"?{}:void 0}},ji=(t,e)=>{let n=0;for(;n<t.length&&n<e.length&&t[n]===e[n];n++);return[(t.length-n).toString(),...e.slice(n)].join("/")},Li=(t,e,n,s)=>{switch(e){case S.ZodString:return Hs(t,n);case S.ZodNumber:return Si(t,n);case S.ZodObject:return Ci(t,n);case S.ZodBigInt:return ii(t,n);case S.ZodBoolean:return oi();case S.ZodDate:return zs(t,n);case S.ZodUndefined:return Pi();case S.ZodNull:return vi(n);case S.ZodArray:return ai(t,n);case S.ZodUnion:case S.ZodDiscriminatedUnion:return xi(t,n);case S.ZodIntersection:return mi(t,n);case S.ZodTuple:return $i(t,n);case S.ZodRecord:return Vs(t,n);case S.ZodLiteral:return _i(t,n);case S.ZodEnum:return fi(t);case S.ZodNativeEnum:return wi(t);case S.ZodNullable:return ki(t,n);case S.ZodOptional:return Oi(t,n);case S.ZodMap:return yi(t,n);case S.ZodSet:return Ri(t,n);case S.ZodLazy:return O(t.getter()._def,n);case S.ZodPromise:return Ti(t,n);case S.ZodNaN:case S.ZodNever:return bi();case S.ZodEffects:return hi(t,n,s);case S.ZodAny:return ri();case S.ZodUnknown:return Ei();case S.ZodDefault:return di(t,n);case S.ZodBranded:return li(t,n);case S.ZodReadonly:return Mi(t,n);case S.ZodCatch:return ci(t,n);case S.ZodPipeline:return Ii(t,n);case S.ZodFunction:case S.ZodVoid:case S.ZodSymbol:return;default:return(r=>{})()}},Di=(t,e,n)=>(t.description&&(n.description=t.description,e.markdownDescription&&(n.markdownDescription=t.description)),n),Fi=(t,e)=>{const n=si(e),s=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,r=O(t._def,s===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,s]},!1)??{},a=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;a!==void 0&&(r.title=a);const i=(()=>{if(ni(n.definitions))return;const c={},l=new Set;for(let m=0;m<500;m++){const h=Object.entries(n.definitions).filter(([p])=>!l.has(p));if(h.length===0)break;for(const[p,d]of h)c[p]=O(Ht(d),{...n,currentPath:[...n.basePath,n.definitionPath,p]},!0)??{},l.add(p)}return c})(),o=s===void 0?i?{...r,[n.definitionPath]:i}:r:n.nameStrategy==="duplicate-ref"?{...r,...i||n.seenRefs.size?{[n.definitionPath]:{...i,...n.seenRefs.size?{[s]:r}:void 0}}:void 0}:{$ref:[...n.$refStrategy==="relative"?[]:n.basePath,n.definitionPath,s].join("/"),[n.definitionPath]:{...i,[s]:r}};return n.target==="jsonSchema7"?o.$schema="http://json-schema.org/draft-07/schema#":n.target==="jsonSchema2019-09"&&(o.$schema="https://json-schema.org/draft/2019-09/schema#"),o};function Bi(t,e){return!e||!Wi(e)?{...t,output_parsed:null,output:t.output.map(n=>n.type==="function_call"?{...n,parsed_arguments:null}:n.type==="message"?{...n,content:n.content.map(s=>({...s,parsed:null}))}:n)}:Xs(t,e)}function Xs(t,e){const n=t.output.map(r=>{if(r.type==="function_call")return{...r,parsed_arguments:Ki(e,r)};if(r.type==="message"){const a=r.content.map(i=>i.type==="output_text"?{...i,parsed:Ui(e,i.text)}:i);return{...r,content:a}}return r}),s=Object.assign({},t,{output:n});return Object.getOwnPropertyDescriptor(t,"output_text")||Vt(s),Object.defineProperty(s,"output_parsed",{enumerable:!0,get(){for(const r of s.output)if(r.type==="message"){for(const a of r.content)if(a.type==="output_text"&&a.parsed!==null)return a.parsed}return null}}),s}function Ui(t,e){return t.text?.format?.type!=="json_schema"?null:"$parseRaw"in t.text?.format?(t.text?.format).$parseRaw(e):JSON.parse(e)}function Wi(t){return!!dn(t.text?.format)}function qi(t){return t?.$brand==="auto-parseable-tool"}function Ji(t,e){return t.find(n=>n.type==="function"&&n.name===e)}function Ki(t,e){const n=Ji(t.tools??[],e.name);return{...e,...e,parsed_arguments:qi(n)?n.$parseRaw(e.arguments):n?.strict?JSON.parse(e.arguments):null}}function Vt(t){const e=[];for(const n of t.output)if(n.type==="message")for(const s of n.content)s.type==="output_text"&&e.push(s.text);t.output_text=e.join("")}function Zi(t){if(t.type!=="object")throw new Error(`Root schema must have type: 'object' but got type: ${t.type?`'${t.type}'`:"undefined"}`);const e=structuredClone(t);return re(e,[],e)}function Xt(t){if(typeof t=="boolean")return!1;if(t.type==="null")return!0;for(const e of t.oneOf??[])if(Xt(e))return!0;for(const e of t.anyOf??[])if(Xt(e))return!0;return!1}function re(t,e,n){if(typeof t=="boolean")throw new TypeError(`Expected object schema but got boolean; path=${e.join("/")}`);if(!ce(t))throw new TypeError(`Expected ${JSON.stringify(t)} to be an object; path=${e.join("/")}`);const s=t.$defs;if(ce(s))for(const[p,d]of Object.entries(s))re(d,[...e,"$defs",p],n);const r=t.definitions;if(ce(r))for(const[p,d]of Object.entries(r))re(d,[...e,"definitions",p],n);t.type==="object"&&!("additionalProperties"in t)&&(t.additionalProperties=!1);const i=t.required??[],o=t.properties;if(ce(o)){for(const[p,d]of Object.entries(o))if(!Xt(d)&&!i.includes(p))throw new Error(`Zod field at \`${[...e,"properties",p].join("/")}\` uses \`.optional()\` without \`.nullable()\` which is not supported by the API. See: https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses#all-fields-must-be-required`);t.required=Object.keys(o),t.properties=Object.fromEntries(Object.entries(o).map(([p,d])=>[p,re(d,[...e,"properties",p],n)]))}const c=t.items;ce(c)&&(t.items=re(c,[...e,"items"],n));const l=t.anyOf;Array.isArray(l)&&(t.anyOf=l.map((p,d)=>re(p,[...e,"anyOf",String(d)],n)));const m=t.allOf;if(Array.isArray(m))if(m.length===1){const p=re(m[0],[...e,"allOf","0"],n);Object.assign(t,p),delete t.allOf}else t.allOf=m.map((p,d)=>re(p,[...e,"allOf",String(d)],n));t.default===null&&delete t.default;const h=t.$ref;if(h&&Hi(t,1)){if(typeof h!="string")throw new TypeError(`Received non-string $ref - ${h}; path=${e.join("/")}`);const p=zi(n,h);if(typeof p=="boolean")throw new Error(`Expected \`$ref: ${h}\` to resolve to an object schema but got boolean`);if(!ce(p))throw new Error(`Expected \`$ref: ${h}\` to resolve to an object but got ${JSON.stringify(p)}`);return Object.assign(t,{...p,...t}),delete t.$ref,re(t,e,n)}return t}function zi(t,e){if(!e.startsWith("#/"))throw new Error(`Unexpected $ref format ${JSON.stringify(e)}; Does not start with #/`);const n=e.slice(2).split("/");let s=t;for(const r of n){if(!ce(s))throw new Error(`encountered non-object entry while resolving ${e} - ${JSON.stringify(s)}`);const a=s[r];if(a===void 0)throw new Error(`Key ${r} not found while resolving ${e}`);s=a}return s}function ce(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Hi(t,e){let n=0;for(const s in t)if(n++,n>e)return!0;return!1}function Vi(t,e){return Fi(t,{openaiStrictMode:!0,name:e.name,nameStrategy:"duplicate-ref",$refStrategy:"extract-to-root",nullableStrategy:"property"})}function Xi(t){return Zi(Ts(t,{target:"draft-7"}))}function Gi(t){return"_zod"in t}function Qi(t,e,n){return Ha({type:"json_schema",json_schema:{...n,name:e,strict:!0,schema:Gi(t)?Xi(t):Vi(t,{name:e})}},s=>t.parse(JSON.parse(s)))}const zn=["jsonSchema","functionCalling","jsonMode"];function Yi(t,e){if(typeof e<"u"&&!zn.includes(e))throw new Error(`Invalid method: ${e}. Supported methods are: ${zn.join(", ")}`);const n=!t.startsWith("gpt-3")&&!t.startsWith("gpt-4-")&&t!=="gpt-4";if(n&&!e)return"jsonSchema";if(!n&&e==="jsonSchema")throw new Error(`JSON Schema is not supported for model "${t}". Please use a different method, e.g. "functionCalling" or "jsonMode".`);return e??"functionCalling"}function eo(t,e){const n={...t};return Object.defineProperties(n,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:e,enumerable:!1}}),n}function to(t,e,n){if(xa(t))return Qi(t,e,n);if(ka(t))return eo({type:"json_schema",json_schema:{...n,name:e,strict:!0,schema:Ts(t,{cycles:"ref",reused:"ref",override(s){s.jsonSchema.title=e}})}},s=>ja(t,JSON.parse(s)));throw new Error("Unsupported schema response format")}function no(t,e){if(e&&typeof e=="object"&&"images"in e&&Array.isArray(e.images)){const n=e.images.filter(s=>typeof s?.image_url?.url=="string").map(s=>({type:"image",url:s.image_url.url}));return[{type:"text",text:t},...n]}return t}function k(t,e,n,s,r){if(typeof e=="function"?t!==e||!0:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(t,n),n}function u(t,e,n,s){if(n==="a"&&!s)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!s:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return n==="m"?s:n==="a"?s.call(t):s?s.value:e.get(t)}let Gs=function(){const{crypto:t}=globalThis;if(t?.randomUUID)return Gs=t.randomUUID.bind(t),t.randomUUID();const e=new Uint8Array(1),n=t?()=>t.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,s=>(+s^n()&15>>+s/4).toString(16))};const so=/^[a-z][a-z0-9+.-]*:/i,ro=t=>so.test(t);let Z=t=>(Z=Array.isArray,Z(t)),Hn=Z;function Qs(t){return typeof t!="object"?{}:t??{}}function ao(t){if(!t)return!0;for(const e in t)return!1;return!0}function io(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function jt(t){return t!=null&&typeof t=="object"&&!Array.isArray(t)}const oo=(t,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new x(`${t} must be an integer`);if(e<0)throw new x(`${t} must be a positive integer`);return e},lo=t=>{try{return JSON.parse(t)}catch{return}},qe=t=>new Promise(e=>setTimeout(e,t)),ye="6.8.1",co=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function uo(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}const ho=()=>{const t=uo();if(t==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ye,"X-Stainless-OS":Xn(Deno.build.os),"X-Stainless-Arch":Vn(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ye,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(t==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ye,"X-Stainless-OS":Xn(globalThis.process.platform??"unknown"),"X-Stainless-Arch":Vn(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};const e=fo();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ye,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ye,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function fo(){if(typeof navigator>"u"||!navigator)return null;const t=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(const{key:e,pattern:n}of t){const s=n.exec(navigator.userAgent);if(s){const r=s[1]||0,a=s[2]||0,i=s[3]||0;return{browser:e,version:`${r}.${a}.${i}`}}}return null}const Vn=t=>t==="x32"?"x32":t==="x86_64"||t==="x64"?"x64":t==="arm"?"arm":t==="aarch64"||t==="arm64"?"arm64":t?`other:${t}`:"unknown",Xn=t=>(t=t.toLowerCase(),t.includes("ios")?"iOS":t==="android"?"Android":t==="darwin"?"MacOS":t==="win32"?"Windows":t==="freebsd"?"FreeBSD":t==="openbsd"?"OpenBSD":t==="linux"?"Linux":t?`Other:${t}`:"Unknown");let Gn;const po=()=>Gn??(Gn=ho());function mo(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function Ys(...t){const e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...t)}function er(t){let e=Symbol.asyncIterator in t?t[Symbol.asyncIterator]():t[Symbol.iterator]();return Ys({start(){},async pull(n){const{done:s,value:r}=await e.next();s?n.close():n.enqueue(r)},async cancel(){await e.return?.()}})}function tr(t){if(t[Symbol.asyncIterator])return t;const e=t.getReader();return{async next(){try{const n=await e.read();return n?.done&&e.releaseLock(),n}catch(n){throw e.releaseLock(),n}},async return(){const n=e.cancel();return e.releaseLock(),await n,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function _o(t){if(t===null||typeof t!="object")return;if(t[Symbol.asyncIterator]){await t[Symbol.asyncIterator]().return?.();return}const e=t.getReader(),n=e.cancel();e.releaseLock(),await n}const go=({headers:t,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)}),nr="RFC3986",sr=t=>String(t),Qn={RFC1738:t=>String(t).replace(/%20/g,"+"),RFC3986:sr},yo="RFC1738";let Gt=(t,e)=>(Gt=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),Gt(t,e));const ee=(()=>{const t=[];for(let e=0;e<256;++e)t.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return t})(),Lt=1024,wo=(t,e,n,s,r)=>{if(t.length===0)return t;let a=t;if(typeof t=="symbol"?a=Symbol.prototype.toString.call(t):typeof t!="string"&&(a=String(t)),n==="iso-8859-1")return escape(a).replace(/%u[0-9a-f]{4}/gi,function(o){return"%26%23"+parseInt(o.slice(2),16)+"%3B"});let i="";for(let o=0;o<a.length;o+=Lt){const c=a.length>=Lt?a.slice(o,o+Lt):a,l=[];for(let m=0;m<c.length;++m){let h=c.charCodeAt(m);if(h===45||h===46||h===95||h===126||h>=48&&h<=57||h>=65&&h<=90||h>=97&&h<=122||r===yo&&(h===40||h===41)){l[l.length]=c.charAt(m);continue}if(h<128){l[l.length]=ee[h];continue}if(h<2048){l[l.length]=ee[192|h>>6]+ee[128|h&63];continue}if(h<55296||h>=57344){l[l.length]=ee[224|h>>12]+ee[128|h>>6&63]+ee[128|h&63];continue}m+=1,h=65536+((h&1023)<<10|c.charCodeAt(m)&1023),l[l.length]=ee[240|h>>18]+ee[128|h>>12&63]+ee[128|h>>6&63]+ee[128|h&63]}i+=l.join("")}return i};function bo(t){return!t||typeof t!="object"?!1:!!(t.constructor&&t.constructor.isBuffer&&t.constructor.isBuffer(t))}function Yn(t,e){if(Z(t)){const n=[];for(let s=0;s<t.length;s+=1)n.push(e(t[s]));return n}return e(t)}const rr={brackets(t){return String(t)+"[]"},comma:"comma",indices(t,e){return String(t)+"["+e+"]"},repeat(t){return String(t)}},ar=function(t,e){Array.prototype.push.apply(t,Z(e)?e:[e])};let es;const j={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:wo,encodeValuesOnly:!1,format:nr,formatter:sr,indices:!1,serializeDate(t){return(es??(es=Function.prototype.call.bind(Date.prototype.toISOString)))(t)},skipNulls:!1,strictNullHandling:!1};function vo(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"||typeof t=="symbol"||typeof t=="bigint"}const Dt={};function ir(t,e,n,s,r,a,i,o,c,l,m,h,p,d,b,w,$,f){let _=t,C=f,I=0,J=!1;for(;(C=C.get(Dt))!==void 0&&!J;){const P=C.get(t);if(I+=1,typeof P<"u"){if(P===I)throw new RangeError("Cyclic object value");J=!0}typeof C.get(Dt)>"u"&&(I=0)}if(typeof l=="function"?_=l(e,_):_ instanceof Date?_=p?.(_):n==="comma"&&Z(_)&&(_=Yn(_,function(P){return P instanceof Date?p?.(P):P})),_===null){if(a)return c&&!w?c(e,j.encoder,$,"key",d):e;_=""}if(vo(_)||bo(_)){if(c){const P=w?e:c(e,j.encoder,$,"key",d);return[b?.(P)+"="+b?.(c(_,j.encoder,$,"value",d))]}return[b?.(e)+"="+b?.(String(_))]}const L=[];if(typeof _>"u")return L;let R;if(n==="comma"&&Z(_))w&&c&&(_=Yn(_,c)),R=[{value:_.length>0?_.join(",")||null:void 0}];else if(Z(l))R=l;else{const P=Object.keys(_);R=m?P.sort(m):P}const B=o?String(e).replace(/\./g,"%2E"):String(e),D=s&&Z(_)&&_.length===1?B+"[]":B;if(r&&Z(_)&&_.length===0)return D+"[]";for(let P=0;P<R.length;++P){const M=R[P],Mn=typeof M=="object"&&typeof M.value<"u"?M.value:_[M];if(i&&Mn===null)continue;const Mt=h&&o?M.replace(/\./g,"%2E"):M,va=Z(_)?typeof n=="function"?n(D,Mt):D:D+(h?"."+Mt:"["+Mt+"]");f.set(t,I);const Nn=new WeakMap;Nn.set(Dt,f),ar(L,ir(Mn,va,n,s,r,a,i,o,n==="comma"&&w&&Z(_)?null:c,l,m,h,p,d,b,w,$,Nn))}return L}function xo(t=j){if(typeof t.allowEmptyArrays<"u"&&typeof t.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof t.encodeDotInKeys<"u"&&typeof t.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(t.encoder!==null&&typeof t.encoder<"u"&&typeof t.encoder!="function")throw new TypeError("Encoder has to be a function.");const e=t.charset||j.charset;if(typeof t.charset<"u"&&t.charset!=="utf-8"&&t.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let n=nr;if(typeof t.format<"u"){if(!Gt(Qn,t.format))throw new TypeError("Unknown format option provided.");n=t.format}const s=Qn[n];let r=j.filter;(typeof t.filter=="function"||Z(t.filter))&&(r=t.filter);let a;if(t.arrayFormat&&t.arrayFormat in rr?a=t.arrayFormat:"indices"in t?a=t.indices?"indices":"repeat":a=j.arrayFormat,"commaRoundTrip"in t&&typeof t.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");const i=typeof t.allowDots>"u"?t.encodeDotInKeys?!0:j.allowDots:!!t.allowDots;return{addQueryPrefix:typeof t.addQueryPrefix=="boolean"?t.addQueryPrefix:j.addQueryPrefix,allowDots:i,allowEmptyArrays:typeof t.allowEmptyArrays=="boolean"?!!t.allowEmptyArrays:j.allowEmptyArrays,arrayFormat:a,charset:e,charsetSentinel:typeof t.charsetSentinel=="boolean"?t.charsetSentinel:j.charsetSentinel,commaRoundTrip:!!t.commaRoundTrip,delimiter:typeof t.delimiter>"u"?j.delimiter:t.delimiter,encode:typeof t.encode=="boolean"?t.encode:j.encode,encodeDotInKeys:typeof t.encodeDotInKeys=="boolean"?t.encodeDotInKeys:j.encodeDotInKeys,encoder:typeof t.encoder=="function"?t.encoder:j.encoder,encodeValuesOnly:typeof t.encodeValuesOnly=="boolean"?t.encodeValuesOnly:j.encodeValuesOnly,filter:r,format:n,formatter:s,serializeDate:typeof t.serializeDate=="function"?t.serializeDate:j.serializeDate,skipNulls:typeof t.skipNulls=="boolean"?t.skipNulls:j.skipNulls,sort:typeof t.sort=="function"?t.sort:null,strictNullHandling:typeof t.strictNullHandling=="boolean"?t.strictNullHandling:j.strictNullHandling}}function ko(t,e={}){let n=t;const s=xo(e);let r,a;typeof s.filter=="function"?(a=s.filter,n=a("",n)):Z(s.filter)&&(a=s.filter,r=a);const i=[];if(typeof n!="object"||n===null)return"";const o=rr[s.arrayFormat],c=o==="comma"&&s.commaRoundTrip;r||(r=Object.keys(n)),s.sort&&r.sort(s.sort);const l=new WeakMap;for(let p=0;p<r.length;++p){const d=r[p];s.skipNulls&&n[d]===null||ar(i,ir(n[d],d,o,c,s.allowEmptyArrays,s.strictNullHandling,s.skipNulls,s.encodeDotInKeys,s.encode?s.encoder:null,s.filter,s.sort,s.allowDots,s.serializeDate,s.format,s.formatter,s.encodeValuesOnly,s.charset,l))}const m=i.join(s.delimiter);let h=s.addQueryPrefix===!0?"?":"";return s.charsetSentinel&&(s.charset==="iso-8859-1"?h+="utf8=%26%2310003%3B&":h+="utf8=%E2%9C%93&"),m.length>0?h+m:""}function So(t){let e=0;for(const r of t)e+=r.length;const n=new Uint8Array(e);let s=0;for(const r of t)n.set(r,s),s+=r.length;return n}let ts;function fn(t){let e;return(ts??(e=new globalThis.TextEncoder,ts=e.encode.bind(e)))(t)}let ns;function ss(t){let e;return(ns??(e=new globalThis.TextDecoder,ns=e.decode.bind(e)))(t)}var z,H;class At{constructor(){z.set(this,void 0),H.set(this,void 0),k(this,z,new Uint8Array),k(this,H,null)}decode(e){if(e==null)return[];const n=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?fn(e):e;k(this,z,So([u(this,z,"f"),n]));const s=[];let r;for(;(r=Ao(u(this,z,"f"),u(this,H,"f")))!=null;){if(r.carriage&&u(this,H,"f")==null){k(this,H,r.index);continue}if(u(this,H,"f")!=null&&(r.index!==u(this,H,"f")+1||r.carriage)){s.push(ss(u(this,z,"f").subarray(0,u(this,H,"f")-1))),k(this,z,u(this,z,"f").subarray(u(this,H,"f"))),k(this,H,null);continue}const a=u(this,H,"f")!==null?r.preceding-1:r.preceding,i=ss(u(this,z,"f").subarray(0,a));s.push(i),k(this,z,u(this,z,"f").subarray(r.index)),k(this,H,null)}return s}flush(){return u(this,z,"f").length?this.decode(`
|
|
9
9
|
`):[]}}z=new WeakMap,H=new WeakMap;At.NEWLINE_CHARS=new Set([`
|
|
10
10
|
`,"\r"]);At.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function Ao(t,e){for(let r=e??0;r<t.length;r++){if(t[r]===10)return{preceding:r,index:r+1,carriage:!1};if(t[r]===13)return{preceding:r,index:r+1,carriage:!0}}return null}function Co(t){for(let s=0;s<t.length-1;s++){if(t[s]===10&&t[s+1]===10||t[s]===13&&t[s+1]===13)return s+2;if(t[s]===13&&t[s+1]===10&&s+3<t.length&&t[s+2]===13&&t[s+3]===10)return s+4}return-1}const pt={off:0,error:200,warn:300,info:400,debug:500},rs=(t,e,n)=>{if(t){if(io(pt,t))return t;U(n).warn(`${e} was set to ${JSON.stringify(t)}, expected one of ${JSON.stringify(Object.keys(pt))}`)}};function Ie(){}function ze(t,e,n){return!e||pt[t]>pt[n]?Ie:e[t].bind(e)}const Oo={error:Ie,warn:Ie,info:Ie,debug:Ie};let as=new WeakMap;function U(t){const e=t.logger,n=t.logLevel??"off";if(!e)return Oo;const s=as.get(e);if(s&&s[0]===n)return s[1];const r={error:ze("error",e,n),warn:ze("warn",e,n),info:ze("info",e,n),debug:ze("debug",e,n)};return as.set(e,[n,r]),r}const ue=t=>(t.options&&(t.options={...t.options},delete t.options.headers),t.headers&&(t.headers=Object.fromEntries((t.headers instanceof Headers?[...t.headers]:Object.entries(t.headers)).map(([e,n])=>[e,e.toLowerCase()==="authorization"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":n]))),"retryOfRequestLogID"in t&&(t.retryOfRequestLogID&&(t.retryOf=t.retryOfRequestLogID),delete t.retryOfRequestLogID),t);var Ce;class ne{constructor(e,n,s){this.iterator=e,Ce.set(this,void 0),this.controller=n,k(this,Ce,s)}static fromSSEResponse(e,n,s){let r=!1;const a=s?U(s):console;async function*i(){if(r)throw new x("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");r=!0;let o=!1;try{for await(const c of Io(e,n))if(!o){if(c.data.startsWith("[DONE]")){o=!0;continue}if(c.event===null||!c.event.startsWith("thread.")){let l;try{l=JSON.parse(c.data)}catch(m){throw a.error("Could not parse message into JSON:",c.data),a.error("From chunk:",c.raw),m}if(l&&l.error)throw new q(void 0,l.error,void 0,e.headers);yield l}else{let l;try{l=JSON.parse(c.data)}catch(m){throw console.error("Could not parse message into JSON:",c.data),console.error("From chunk:",c.raw),m}if(c.event=="error")throw new q(void 0,l.error,l.message,void 0);yield{event:c.event,data:l}}}o=!0}catch(c){if(Zt(c))return;throw c}finally{o||n.abort()}}return new ne(i,n,s)}static fromReadableStream(e,n,s){let r=!1;async function*a(){const o=new At,c=tr(e);for await(const l of c)for(const m of o.decode(l))yield m;for(const l of o.flush())yield l}async function*i(){if(r)throw new x("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");r=!0;let o=!1;try{for await(const c of a())o||c&&(yield JSON.parse(c));o=!0}catch(c){if(Zt(c))return;throw c}finally{o||n.abort()}}return new ne(i,n,s)}[(Ce=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){const e=[],n=[],s=this.iterator(),r=a=>({next:()=>{if(a.length===0){const i=s.next();e.push(i),n.push(i)}return a.shift()}});return[new ne(()=>r(e),this.controller,u(this,Ce,"f")),new ne(()=>r(n),this.controller,u(this,Ce,"f"))]}toReadableStream(){const e=this;let n;return Ys({async start(){n=e[Symbol.asyncIterator]()},async pull(s){try{const{value:r,done:a}=await n.next();if(a)return s.close();const i=fn(JSON.stringify(r)+`
|
|
11
|
-
`);s.enqueue(i)}catch(r){s.error(r)}},async cancel(){await n.return?.()}})}}async function*Io(t,e){if(!t.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new x("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new x("Attempted to iterate over a response with no body");const n=new
|
|
12
|
-
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],a}if(this.chunks.push(e),e.startsWith(":"))return null;let[n,s,r]
|
|
11
|
+
`);s.enqueue(i)}catch(r){s.error(r)}},async cancel(){await n.return?.()}})}}async function*Io(t,e){if(!t.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new x("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new x("Attempted to iterate over a response with no body");const n=new Ro,s=new At,r=tr(t.body);for await(const a of To(r))for(const i of s.decode(a)){const o=n.decode(i);o&&(yield o)}for(const a of s.flush()){const i=n.decode(a);i&&(yield i)}}async function*To(t){let e=new Uint8Array;for await(const n of t){if(n==null)continue;const s=n instanceof ArrayBuffer?new Uint8Array(n):typeof n=="string"?fn(n):n;let r=new Uint8Array(e.length+s.length);r.set(e),r.set(s,e.length),e=r;let a;for(;(a=Co(e))!==-1;)yield e.slice(0,a),e=e.slice(a)}e.length>0&&(yield e)}class Ro{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;const a={event:this.event,data:this.data.join(`
|
|
12
|
+
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],a}if(this.chunks.push(e),e.startsWith(":"))return null;let[n,s,r]=$o(e,":");return r.startsWith(" ")&&(r=r.substring(1)),n==="event"?this.event=r:n==="data"&&this.data.push(r),null}}function $o(t,e){const n=t.indexOf(e);return n!==-1?[t.substring(0,n),e,t.substring(n+e.length)]:[t,"",""]}async function or(t,e){const{response:n,requestLogID:s,retryOfRequestLogID:r,startTime:a}=e,i=await(async()=>{if(e.options.stream)return U(t).debug("response",n.status,n.url,n.headers,n.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(n,e.controller,t):ne.fromSSEResponse(n,e.controller,t);if(n.status===204)return null;if(e.options.__binaryResponse)return n;const c=n.headers.get("content-type")?.split(";")[0]?.trim();if(c?.includes("application/json")||c?.endsWith("+json")){const h=await n.json();return lr(h,n)}return await n.text()})();return U(t).debug(`[${s}] response parsed`,ue({retryOfRequestLogID:r,url:n.url,status:n.status,body:i,durationMs:Date.now()-a})),i}function lr(t,e){return!t||typeof t!="object"||Array.isArray(t)?t:Object.defineProperty(t,"_request_id",{value:e.headers.get("x-request-id"),enumerable:!1})}var Te;class Ct extends Promise{constructor(e,n,s=or){super(r=>{r(null)}),this.responsePromise=n,this.parseResponse=s,Te.set(this,void 0),k(this,Te,e)}_thenUnwrap(e){return new Ct(u(this,Te,"f"),this.responsePromise,async(n,s)=>lr(e(await this.parseResponse(n,s),s),s.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){const[e,n]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:n,request_id:n.headers.get("x-request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(u(this,Te,"f"),e))),this.parsedPromise}then(e,n){return this.parse().then(e,n)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}}Te=new WeakMap;var He;class pn{constructor(e,n,s,r){He.set(this,void 0),k(this,He,e),this.options=r,this.response=n,this.body=s}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){const e=this.nextPageRequestOptions();if(!e)throw new x("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await u(this,He,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(He=new WeakMap,Symbol.asyncIterator)](){for await(const e of this.iterPages())for(const n of e.getPaginatedItems())yield n}}class Po extends Ct{constructor(e,n,s){super(e,n,async(r,a)=>new s(r,a.response,await or(r,a),a.options))}async*[Symbol.asyncIterator](){const e=await this;for await(const n of e)yield n}}class Ot extends pn{constructor(e,n,s,r){super(e,n,s,r),this.data=s.data||[],this.object=s.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}}class E extends pn{constructor(e,n,s,r){super(e,n,s,r),this.data=s.data||[],this.has_more=s.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){const e=this.getPaginatedItems(),n=e[e.length-1]?.id;return n?{...this.options,query:{...Qs(this.options.query),after:n}}:null}}class mt extends pn{constructor(e,n,s,r){super(e,n,s,r),this.data=s.data||[],this.has_more=s.has_more||!1,this.last_id=s.last_id||""}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){const e=this.last_id;return e?{...this.options,query:{...Qs(this.options.query),after:e}}:null}}const cr=()=>{if(typeof File>"u"){const{process:t}=globalThis,e=typeof t?.versions?.node=="string"&&parseInt(t.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(e?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function je(t,e,n){return cr(),new File(t,e??"unknown_file",n)}function tt(t){return(typeof t=="object"&&t!==null&&("name"in t&&t.name&&String(t.name)||"url"in t&&t.url&&String(t.url)||"filename"in t&&t.filename&&String(t.filename)||"path"in t&&t.path&&String(t.path))||"").split(/[\\/]/).pop()||void 0}const mn=t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function",is=async(t,e)=>Qt(t.body)?{...t,body:await ur(t.body,e)}:t,pe=async(t,e)=>({...t,body:await ur(t.body,e)}),os=new WeakMap;function Eo(t){const e=typeof t=="function"?t:t.fetch,n=os.get(e);if(n)return n;const s=(async()=>{try{const r="Response"in e?e.Response:(await e("data:,")).constructor,a=new FormData;return a.toString()!==await new r(a).text()}catch{return!0}})();return os.set(e,s),s}const ur=async(t,e)=>{if(!await Eo(e))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");const n=new FormData;return await Promise.all(Object.entries(t||{}).map(([s,r])=>Yt(n,s,r))),n},dr=t=>t instanceof Blob&&"name"in t,Mo=t=>typeof t=="object"&&t!==null&&(t instanceof Response||mn(t)||dr(t)),Qt=t=>{if(Mo(t))return!0;if(Array.isArray(t))return t.some(Qt);if(t&&typeof t=="object"){for(const e in t)if(Qt(t[e]))return!0}return!1},Yt=async(t,e,n)=>{if(n!==void 0){if(n==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")t.append(e,String(n));else if(n instanceof Response)t.append(e,je([await n.blob()],tt(n)));else if(mn(n))t.append(e,je([await new Response(er(n)).blob()],tt(n)));else if(dr(n))t.append(e,n,tt(n));else if(Array.isArray(n))await Promise.all(n.map(s=>Yt(t,e+"[]",s)));else if(typeof n=="object")await Promise.all(Object.entries(n).map(([s,r])=>Yt(t,`${e}[${s}]`,r)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${n} instead`)}},hr=t=>t!=null&&typeof t=="object"&&typeof t.size=="number"&&typeof t.type=="string"&&typeof t.text=="function"&&typeof t.slice=="function"&&typeof t.arrayBuffer=="function",No=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&hr(t),jo=t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function";async function Lo(t,e,n){if(cr(),t=await t,No(t))return t instanceof File?t:je([await t.arrayBuffer()],t.name);if(jo(t)){const r=await t.blob();return e||(e=new URL(t.url).pathname.split(/[\\/]/).pop()),je(await en(r),e,n)}const s=await en(t);if(e||(e=tt(t)),!n?.type){const r=s.find(a=>typeof a=="object"&&"type"in a&&a.type);typeof r=="string"&&(n={...n,type:r})}return je(s,e,n)}async function en(t){let e=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)e.push(t);else if(hr(t))e.push(t instanceof Blob?t:await t.arrayBuffer());else if(mn(t))for await(const n of t)e.push(...await en(n));else{const n=t?.constructor?.name;throw new Error(`Unexpected data type: ${typeof t}${n?`; constructor: ${n}`:""}${Do(t)}`)}return e}function Do(t){return typeof t!="object"||t===null?"":`; props: [${Object.getOwnPropertyNames(t).map(n=>`"${n}"`).join(", ")}]`}class v{constructor(e){this._client=e}}function fr(t){return t.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}const ls=Object.freeze(Object.create(null)),Fo=(t=fr)=>function(n,...s){if(n.length===1)return n[0];let r=!1;const a=[],i=n.reduce((m,h,p)=>{/[?#]/.test(h)&&(r=!0);const d=s[p];let b=(r?encodeURIComponent:t)(""+d);return p!==s.length&&(d==null||typeof d=="object"&&d.toString===Object.getPrototypeOf(Object.getPrototypeOf(d.hasOwnProperty??ls)??ls)?.toString)&&(b=d+"",a.push({start:m.length+h.length,length:b.length,error:`Value of type ${Object.prototype.toString.call(d).slice(8,-1)} is not a valid path parameter`})),m+h+(p===s.length?"":b)},""),o=i.split(/[?#]/,1)[0],c=new RegExp("(?<=^|\\/)(?:\\.|%2e){1,2}(?=\\/|$)","gi");let l;for(;(l=c.exec(o))!==null;)a.push({start:l.index,length:l[0].length,error:`Value "${l[0]}" can't be safely passed as a path parameter`});if(a.sort((m,h)=>m.start-h.start),a.length>0){let m=0;const h=a.reduce((p,d)=>{const b=" ".repeat(d.start-m),w="^".repeat(d.length);return m=d.start+d.length,p+b+w},"");throw new x(`Path parameters result in path with invalid segments:
|
|
13
13
|
${a.map(p=>p.error).join(`
|
|
14
14
|
`)}
|
|
15
15
|
${i}
|
|
16
|
-
${h}`)}return i},g=Fo(fr);let pr=class extends v{list(e,n={},s){return this._client.getAPIList(g`/chat/completions/${e}/messages`,E,{query:n,...s})}};const _t=t=>t?.role==="assistant",mr=t=>t?.role==="tool";var tn,nt,st,$e,Re,rt,Pe,ae,Ee,gt,yt,we,_r;class _n{constructor(){tn.add(this),this.controller=new AbortController,nt.set(this,void 0),st.set(this,()=>{}),$e.set(this,()=>{}),Re.set(this,void 0),rt.set(this,()=>{}),Pe.set(this,()=>{}),ae.set(this,{}),Ee.set(this,!1),gt.set(this,!1),yt.set(this,!1),we.set(this,!1),k(this,nt,new Promise((e,n)=>{k(this,st,e,"f"),k(this,$e,n,"f")})),k(this,Re,new Promise((e,n)=>{k(this,rt,e,"f"),k(this,Pe,n,"f")})),u(this,nt,"f").catch(()=>{}),u(this,Re,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},u(this,tn,"m",_r).bind(this))},0)}_connected(){this.ended||(u(this,st,"f").call(this),this._emit("connect"))}get ended(){return u(this,Ee,"f")}get errored(){return u(this,gt,"f")}get aborted(){return u(this,yt,"f")}abort(){this.controller.abort()}on(e,n){return(u(this,ae,"f")[e]||(u(this,ae,"f")[e]=[])).push({listener:n}),this}off(e,n){const s=u(this,ae,"f")[e];if(!s)return this;const r=s.findIndex(a=>a.listener===n);return r>=0&&s.splice(r,1),this}once(e,n){return(u(this,ae,"f")[e]||(u(this,ae,"f")[e]=[])).push({listener:n,once:!0}),this}emitted(e){return new Promise((n,s)=>{k(this,we,!0),e!=="error"&&this.once("error",s),this.once(e,n)})}async done(){k(this,we,!0),await u(this,Re,"f")}_emit(e,...n){if(u(this,Ee,"f"))return;e==="end"&&(k(this,Ee,!0),u(this,rt,"f").call(this));const s=u(this,ae,"f")[e];if(s&&(u(this,ae,"f")[e]=s.filter(r=>!r.once),s.forEach(({listener:r})=>r(...n))),e==="abort"){const r=n[0];!u(this,we,"f")&&!s?.length&&Promise.reject(r),u(this,$e,"f").call(this,r),u(this,Pe,"f").call(this,r),this._emit("end");return}if(e==="error"){const r=n[0];!u(this,we,"f")&&!s?.length&&Promise.reject(r),u(this,$e,"f").call(this,r),u(this,Pe,"f").call(this,r),this._emit("end")}}_emitFinal(){}}nt=new WeakMap,st=new WeakMap,$e=new WeakMap,Re=new WeakMap,rt=new WeakMap,Pe=new WeakMap,ae=new WeakMap,Ee=new WeakMap,gt=new WeakMap,yt=new WeakMap,we=new WeakMap,tn=new WeakSet,_r=function(e){if(k(this,gt,!0),e instanceof Error&&e.name==="AbortError"&&(e=new X),e instanceof X)return k(this,yt,!0),this._emit("abort",e);if(e instanceof x)return this._emit("error",e);if(e instanceof Error){const n=new x(e.message);return n.cause=e,this._emit("error",n)}return this._emit("error",new x(String(e)))};function Bo(t){return typeof t.parse=="function"}var K,nn,wt,sn,rn,an,gr,yr;const Uo=10;class wr extends _n{constructor(){super(...arguments),K.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){this._chatCompletions.push(e),this._emit("chatCompletion",e);const n=e.choices[0]?.message;return n&&this._addMessage(n),e}_addMessage(e,n=!0){if("content"in e||(e.content=null),this.messages.push(e),n){if(this._emit("message",e),mr(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(_t(e)&&e.tool_calls)for(const s of e.tool_calls)s.type==="function"&&this._emit("functionToolCall",s.function)}}async finalChatCompletion(){await this.done();const e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new x("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),u(this,K,"m",nn).call(this)}async finalMessage(){return await this.done(),u(this,K,"m",wt).call(this)}async finalFunctionToolCall(){return await this.done(),u(this,K,"m",sn).call(this)}async finalFunctionToolCallResult(){return await this.done(),u(this,K,"m",rn).call(this)}async totalUsage(){return await this.done(),u(this,K,"m",an).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){const e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);const n=u(this,K,"m",wt).call(this);n&&this._emit("finalMessage",n);const s=u(this,K,"m",nn).call(this);s&&this._emit("finalContent",s);const r=u(this,K,"m",sn).call(this);r&&this._emit("finalFunctionToolCall",r);const a=u(this,K,"m",rn).call(this);a!=null&&this._emit("finalFunctionToolCallResult",a),this._chatCompletions.some(i=>i.usage)&&this._emit("totalUsage",u(this,K,"m",an).call(this))}async _createChatCompletion(e,n,s){const r=s?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),u(this,K,"m",gr).call(this,n);const a=await e.chat.completions.create({...n,stream:!1},{...s,signal:this.controller.signal});return this._connected(),this._addChatCompletion(hn(a,n))}async _runChatCompletion(e,n,s){for(const r of n.messages)this._addMessage(r,!1);return await this._createChatCompletion(e,n,s)}async _runTools(e,n,s){const r="tool",{tool_choice:a="auto",stream:i,...o}=n,c=typeof a!="string"&&a.type==="function"&&a?.function?.name,{maxChatCompletions:l=Uo}=s||{},m=n.tools.map(d=>{if(We(d)){if(!d.$callback)throw new x("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:d.$callback,name:d.function.name,description:d.function.description||"",parameters:d.function.parameters,parse:d.$parseRaw,strict:!0}}}return d}),h={};for(const d of m)d.type==="function"&&(h[d.function.name||d.function.function.name]=d.function);const p="tools"in n?m.map(d=>d.type==="function"?{type:"function",function:{name:d.function.name||d.function.function.name,parameters:d.function.parameters,description:d.function.description,strict:d.function.strict}}:d):void 0;for(const d of n.messages)this._addMessage(d,!1);for(let d=0;d<l;++d){const w=(await this._createChatCompletion(e,{...o,tool_choice:a,tools:p,messages:[...this.messages]},s)).choices[0]?.message;if(!w)throw new x("missing message in ChatCompletion response");if(!w.tool_calls?.length)return;for(const R of w.tool_calls){if(R.type!=="function")continue;const f=R.id,{name:_,arguments:C}=R.function,I=h[_];if(I){if(c&&c!==_){const B=`Invalid tool_call: ${JSON.stringify(_)}. ${JSON.stringify(c)} requested. Please try again`;this._addMessage({role:r,tool_call_id:f,content:B});continue}}else{const B=`Invalid tool_call: ${JSON.stringify(_)}. Available options are: ${Object.keys(h).map(D=>JSON.stringify(D)).join(", ")}. Please try again`;this._addMessage({role:r,tool_call_id:f,content:B});continue}let J;try{J=Bo(I)?await I.parse(C):C}catch(B){const D=B instanceof Error?B.message:String(B);this._addMessage({role:r,tool_call_id:f,content:D});continue}const L=await I.function(J,this),$=u(this,K,"m",yr).call(this,L);if(this._addMessage({role:r,tool_call_id:f,content:$}),c)return}}}}K=new WeakSet,nn=function(){return u(this,K,"m",wt).call(this).content??null},wt=function(){let e=this.messages.length;for(;e-- >0;){const n=this.messages[e];if(_t(n))return{...n,content:n.content??null,refusal:n.refusal??null}}throw new x("stream ended without producing a ChatCompletionMessage with role=assistant")},sn=function(){for(let e=this.messages.length-1;e>=0;e--){const n=this.messages[e];if(_t(n)&&n?.tool_calls?.length)return n.tool_calls.filter(s=>s.type==="function").at(-1)?.function}},rn=function(){for(let e=this.messages.length-1;e>=0;e--){const n=this.messages[e];if(mr(n)&&n.content!=null&&typeof n.content=="string"&&this.messages.some(s=>s.role==="assistant"&&s.tool_calls?.some(r=>r.type==="function"&&r.id===n.tool_call_id)))return n.content}},an=function(){const e={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(const{usage:n}of this._chatCompletions)n&&(e.completion_tokens+=n.completion_tokens,e.prompt_tokens+=n.prompt_tokens,e.total_tokens+=n.total_tokens);return e},gr=function(e){if(e.n!=null&&e.n>1)throw new x("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},yr=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};class gn extends wr{static runTools(e,n,s){const r=new gn,a={...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"runTools"}};return r._run(()=>r._runTools(e,n,a)),r}_addMessage(e,n=!0){super._addMessage(e,n),_t(e)&&e.content&&this._emit("content",e.content)}}const br=1,vr=2,xr=4,kr=8,Sr=16,Ar=32,Cr=64,Or=128,Ir=256,Tr=Or|Ir,$r=Sr|Ar|Tr|Cr,Rr=br|vr|$r,Pr=xr|kr,Wo=Rr|Pr,F={STR:br,NUM:vr,ARR:xr,OBJ:kr,NULL:Sr,BOOL:Ar,NAN:Cr,INFINITY:Or,MINUS_INFINITY:Ir,INF:Tr,SPECIAL:$r,ATOM:Rr,COLLECTION:Pr,ALL:Wo};class qo extends Error{}class Jo extends Error{}function Ko(t,e=F.ALL){if(typeof t!="string")throw new TypeError(`expecting str, got ${typeof t}`);if(!t.trim())throw new Error(`${t} is empty`);return Zo(t.trim(),e)}const Zo=(t,e)=>{const n=t.length;let s=0;const r=p=>{throw new qo(`${p} at position ${s}`)},a=p=>{throw new Jo(`${p} at position ${s}`)},i=()=>(h(),s>=n&&r("Unexpected end of input"),t[s]==='"'?o():t[s]==="{"?c():t[s]==="["?l():t.substring(s,s+4)==="null"||F.NULL&e&&n-s<4&&"null".startsWith(t.substring(s))?(s+=4,null):t.substring(s,s+4)==="true"||F.BOOL&e&&n-s<4&&"true".startsWith(t.substring(s))?(s+=4,!0):t.substring(s,s+5)==="false"||F.BOOL&e&&n-s<5&&"false".startsWith(t.substring(s))?(s+=5,!1):t.substring(s,s+8)==="Infinity"||F.INFINITY&e&&n-s<8&&"Infinity".startsWith(t.substring(s))?(s+=8,1/0):t.substring(s,s+9)==="-Infinity"||F.MINUS_INFINITY&e&&1<n-s&&n-s<9&&"-Infinity".startsWith(t.substring(s))?(s+=9,-1/0):t.substring(s,s+3)==="NaN"||F.NAN&e&&n-s<3&&"NaN".startsWith(t.substring(s))?(s+=3,NaN):m()),o=()=>{const p=s;let d=!1;for(s++;s<n&&(t[s]!=='"'||d&&t[s-1]==="\\");)d=t[s]==="\\"?!d:!1,s++;if(t.charAt(s)=='"')try{return JSON.parse(t.substring(p,++s-Number(d)))}catch(b){a(String(b))}else if(F.STR&e)try{return JSON.parse(t.substring(p,s-Number(d))+'"')}catch{return JSON.parse(t.substring(p,t.lastIndexOf("\\"))+'"')}r("Unterminated string literal")},c=()=>{s++,h();const p={};try{for(;t[s]!=="}";){if(h(),s>=n&&F.OBJ&e)return p;const d=o();h(),s++;try{const b=i();Object.defineProperty(p,d,{value:b,writable:!0,enumerable:!0,configurable:!0})}catch(b){if(F.OBJ&e)return p;throw b}h(),t[s]===","&&s++}}catch{if(F.OBJ&e)return p;r("Expected '}' at end of object")}return s++,p},l=()=>{s++;const p=[];try{for(;t[s]!=="]";)p.push(i()),h(),t[s]===","&&s++}catch{if(F.ARR&e)return p;r("Expected ']' at end of array")}return s++,p},m=()=>{if(s===0){t==="-"&&F.NUM&e&&r("Not sure what '-' is");try{return JSON.parse(t)}catch(d){if(F.NUM&e)try{return t[t.length-1]==="."?JSON.parse(t.substring(0,t.lastIndexOf("."))):JSON.parse(t.substring(0,t.lastIndexOf("e")))}catch{}a(String(d))}}const p=s;for(t[s]==="-"&&s++;t[s]&&!",]}".includes(t[s]);)s++;s==n&&!(F.NUM&e)&&r("Unterminated number literal");try{return JSON.parse(t.substring(p,s))}catch{t.substring(p,s)==="-"&&F.NUM&e&&r("Not sure what '-' is");try{return JSON.parse(t.substring(p,t.lastIndexOf("e")))}catch(b){a(String(b))}}},h=()=>{for(;s<n&&`
|
|
17
|
-
\r `.includes(t[s]);)s++};return i()},cs=t=>Ko(t,F.ALL^F.NUM);var N,se,me,ie,Ft,Ve,Bt,Ut,Wt,Xe,qt,us;class Fe extends wr{constructor(e){super(),N.add(this),se.set(this,void 0),me.set(this,void 0),ie.set(this,void 0),k(this,se,e),k(this,me,[])}get currentChatCompletionSnapshot(){return u(this,ie,"f")}static fromReadableStream(e){const n=new Fe(null);return n._run(()=>n._fromReadableStream(e)),n}static createChatCompletion(e,n,s){const r=new Fe(n);return r._run(()=>r._runChatCompletion(e,{...n,stream:!0},{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),r}async _createChatCompletion(e,n,s){super._createChatCompletion;const r=s?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),u(this,N,"m",Ft).call(this);const a=await e.chat.completions.create({...n,stream:!0},{...s,signal:this.controller.signal});this._connected();for await(const i of a)u(this,N,"m",Bt).call(this,i);if(a.controller.signal?.aborted)throw new X;return this._addChatCompletion(u(this,N,"m",Xe).call(this))}async _fromReadableStream(e,n){const s=n?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),u(this,N,"m",Ft).call(this),this._connected();const r=ne.fromReadableStream(e,this.controller);let a;for await(const i of r)a&&a!==i.id&&this._addChatCompletion(u(this,N,"m",Xe).call(this)),u(this,N,"m",Bt).call(this,i),a=i.id;if(r.controller.signal?.aborted)throw new X;return this._addChatCompletion(u(this,N,"m",Xe).call(this))}[(se=new WeakMap,me=new WeakMap,ie=new WeakMap,N=new WeakSet,Ft=function(){this.ended||k(this,ie,void 0)},Ve=function(n){let s=u(this,me,"f")[n.index];return s||(s={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},u(this,me,"f")[n.index]=s,s)},Bt=function(n){if(this.ended)return;const s=u(this,N,"m",us).call(this,n);this._emit("chunk",n,s);for(const r of n.choices){const a=s.choices[r.index];r.delta.content!=null&&a.message?.role==="assistant"&&a.message?.content&&(this._emit("content",r.delta.content,a.message.content),this._emit("content.delta",{delta:r.delta.content,snapshot:a.message.content,parsed:a.message.parsed})),r.delta.refusal!=null&&a.message?.role==="assistant"&&a.message?.refusal&&this._emit("refusal.delta",{delta:r.delta.refusal,snapshot:a.message.refusal}),r.logprobs?.content!=null&&a.message?.role==="assistant"&&this._emit("logprobs.content.delta",{content:r.logprobs?.content,snapshot:a.logprobs?.content??[]}),r.logprobs?.refusal!=null&&a.message?.role==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:r.logprobs?.refusal,snapshot:a.logprobs?.refusal??[]});const i=u(this,N,"m",Ve).call(this,a);a.finish_reason&&(u(this,N,"m",Wt).call(this,a),i.current_tool_call_index!=null&&u(this,N,"m",Ut).call(this,a,i.current_tool_call_index));for(const o of r.delta.tool_calls??[])i.current_tool_call_index!==o.index&&(u(this,N,"m",Wt).call(this,a),i.current_tool_call_index!=null&&u(this,N,"m",Ut).call(this,a,i.current_tool_call_index)),i.current_tool_call_index=o.index;for(const o of r.delta.tool_calls??[]){const c=a.message.tool_calls?.[o.index];c?.type&&(c?.type==="function"?this._emit("tool_calls.function.arguments.delta",{name:c.function?.name,index:o.index,arguments:c.function.arguments,parsed_arguments:c.function.parsed_arguments,arguments_delta:o.function?.arguments??""}):(c?.type,void 0))}}},Ut=function(n,s){if(u(this,N,"m",Ve).call(this,n).done_tool_calls.has(s))return;const a=n.message.tool_calls?.[s];if(!a)throw new Error("no tool call snapshot");if(!a.type)throw new Error("tool call snapshot missing `type`");if(a.type==="function"){const i=u(this,se,"f")?.tools?.find(o=>ht(o)&&o.function.name===a.function.name);this._emit("tool_calls.function.arguments.done",{name:a.function.name,index:s,arguments:a.function.arguments,parsed_arguments:We(i)?i.$parseRaw(a.function.arguments):i?.function.strict?JSON.parse(a.function.arguments):null})}else a.type},Wt=function(n){const s=u(this,N,"m",Ve).call(this,n);if(n.message.content&&!s.content_done){s.content_done=!0;const r=u(this,N,"m",qt).call(this);this._emit("content.done",{content:n.message.content,parsed:r?r.$parseRaw(n.message.content):null})}n.message.refusal&&!s.refusal_done&&(s.refusal_done=!0,this._emit("refusal.done",{refusal:n.message.refusal})),n.logprobs?.content&&!s.logprobs_content_done&&(s.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:n.logprobs.content})),n.logprobs?.refusal&&!s.logprobs_refusal_done&&(s.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:n.logprobs.refusal}))},Xe=function(){if(this.ended)throw new x("stream has ended, this shouldn't happen");const n=u(this,ie,"f");if(!n)throw new x("request ended without sending any chunks");return k(this,ie,void 0),k(this,me,[]),zo(n,u(this,se,"f"))},qt=function(){const n=u(this,se,"f")?.response_format;return dn(n)?n:null},us=function(n){var s,r,a,i;let o=u(this,ie,"f");const{choices:c,...l}=n;o?Object.assign(o,l):o=k(this,ie,{...l,choices:[]});for(const{delta:m,finish_reason:h,index:p,logprobs:d=null,...b}of n.choices){let w=o.choices[p];if(w||(w=o.choices[p]={finish_reason:h,index:p,message:{},logprobs:d,...b}),d)if(!w.logprobs)w.logprobs=Object.assign({},d);else{const{content:L,refusal
|
|
16
|
+
${h}`)}return i},g=Fo(fr);let pr=class extends v{list(e,n={},s){return this._client.getAPIList(g`/chat/completions/${e}/messages`,E,{query:n,...s})}};const _t=t=>t?.role==="assistant",mr=t=>t?.role==="tool";var tn,nt,st,Re,$e,rt,Pe,ae,Ee,gt,yt,we,_r;class _n{constructor(){tn.add(this),this.controller=new AbortController,nt.set(this,void 0),st.set(this,()=>{}),Re.set(this,()=>{}),$e.set(this,void 0),rt.set(this,()=>{}),Pe.set(this,()=>{}),ae.set(this,{}),Ee.set(this,!1),gt.set(this,!1),yt.set(this,!1),we.set(this,!1),k(this,nt,new Promise((e,n)=>{k(this,st,e,"f"),k(this,Re,n,"f")})),k(this,$e,new Promise((e,n)=>{k(this,rt,e,"f"),k(this,Pe,n,"f")})),u(this,nt,"f").catch(()=>{}),u(this,$e,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},u(this,tn,"m",_r).bind(this))},0)}_connected(){this.ended||(u(this,st,"f").call(this),this._emit("connect"))}get ended(){return u(this,Ee,"f")}get errored(){return u(this,gt,"f")}get aborted(){return u(this,yt,"f")}abort(){this.controller.abort()}on(e,n){return(u(this,ae,"f")[e]||(u(this,ae,"f")[e]=[])).push({listener:n}),this}off(e,n){const s=u(this,ae,"f")[e];if(!s)return this;const r=s.findIndex(a=>a.listener===n);return r>=0&&s.splice(r,1),this}once(e,n){return(u(this,ae,"f")[e]||(u(this,ae,"f")[e]=[])).push({listener:n,once:!0}),this}emitted(e){return new Promise((n,s)=>{k(this,we,!0),e!=="error"&&this.once("error",s),this.once(e,n)})}async done(){k(this,we,!0),await u(this,$e,"f")}_emit(e,...n){if(u(this,Ee,"f"))return;e==="end"&&(k(this,Ee,!0),u(this,rt,"f").call(this));const s=u(this,ae,"f")[e];if(s&&(u(this,ae,"f")[e]=s.filter(r=>!r.once),s.forEach(({listener:r})=>r(...n))),e==="abort"){const r=n[0];!u(this,we,"f")&&!s?.length&&Promise.reject(r),u(this,Re,"f").call(this,r),u(this,Pe,"f").call(this,r),this._emit("end");return}if(e==="error"){const r=n[0];!u(this,we,"f")&&!s?.length&&Promise.reject(r),u(this,Re,"f").call(this,r),u(this,Pe,"f").call(this,r),this._emit("end")}}_emitFinal(){}}nt=new WeakMap,st=new WeakMap,Re=new WeakMap,$e=new WeakMap,rt=new WeakMap,Pe=new WeakMap,ae=new WeakMap,Ee=new WeakMap,gt=new WeakMap,yt=new WeakMap,we=new WeakMap,tn=new WeakSet,_r=function(e){if(k(this,gt,!0),e instanceof Error&&e.name==="AbortError"&&(e=new X),e instanceof X)return k(this,yt,!0),this._emit("abort",e);if(e instanceof x)return this._emit("error",e);if(e instanceof Error){const n=new x(e.message);return n.cause=e,this._emit("error",n)}return this._emit("error",new x(String(e)))};function Bo(t){return typeof t.parse=="function"}var K,nn,wt,sn,rn,an,gr,yr;const Uo=10;class wr extends _n{constructor(){super(...arguments),K.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){this._chatCompletions.push(e),this._emit("chatCompletion",e);const n=e.choices[0]?.message;return n&&this._addMessage(n),e}_addMessage(e,n=!0){if("content"in e||(e.content=null),this.messages.push(e),n){if(this._emit("message",e),mr(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(_t(e)&&e.tool_calls)for(const s of e.tool_calls)s.type==="function"&&this._emit("functionToolCall",s.function)}}async finalChatCompletion(){await this.done();const e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new x("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),u(this,K,"m",nn).call(this)}async finalMessage(){return await this.done(),u(this,K,"m",wt).call(this)}async finalFunctionToolCall(){return await this.done(),u(this,K,"m",sn).call(this)}async finalFunctionToolCallResult(){return await this.done(),u(this,K,"m",rn).call(this)}async totalUsage(){return await this.done(),u(this,K,"m",an).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){const e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);const n=u(this,K,"m",wt).call(this);n&&this._emit("finalMessage",n);const s=u(this,K,"m",nn).call(this);s&&this._emit("finalContent",s);const r=u(this,K,"m",sn).call(this);r&&this._emit("finalFunctionToolCall",r);const a=u(this,K,"m",rn).call(this);a!=null&&this._emit("finalFunctionToolCallResult",a),this._chatCompletions.some(i=>i.usage)&&this._emit("totalUsage",u(this,K,"m",an).call(this))}async _createChatCompletion(e,n,s){const r=s?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),u(this,K,"m",gr).call(this,n);const a=await e.chat.completions.create({...n,stream:!1},{...s,signal:this.controller.signal});return this._connected(),this._addChatCompletion(hn(a,n))}async _runChatCompletion(e,n,s){for(const r of n.messages)this._addMessage(r,!1);return await this._createChatCompletion(e,n,s)}async _runTools(e,n,s){const r="tool",{tool_choice:a="auto",stream:i,...o}=n,c=typeof a!="string"&&a.type==="function"&&a?.function?.name,{maxChatCompletions:l=Uo}=s||{},m=n.tools.map(d=>{if(We(d)){if(!d.$callback)throw new x("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:d.$callback,name:d.function.name,description:d.function.description||"",parameters:d.function.parameters,parse:d.$parseRaw,strict:!0}}}return d}),h={};for(const d of m)d.type==="function"&&(h[d.function.name||d.function.function.name]=d.function);const p="tools"in n?m.map(d=>d.type==="function"?{type:"function",function:{name:d.function.name||d.function.function.name,parameters:d.function.parameters,description:d.function.description,strict:d.function.strict}}:d):void 0;for(const d of n.messages)this._addMessage(d,!1);for(let d=0;d<l;++d){const w=(await this._createChatCompletion(e,{...o,tool_choice:a,tools:p,messages:[...this.messages]},s)).choices[0]?.message;if(!w)throw new x("missing message in ChatCompletion response");if(!w.tool_calls?.length)return;for(const $ of w.tool_calls){if($.type!=="function")continue;const f=$.id,{name:_,arguments:C}=$.function,I=h[_];if(I){if(c&&c!==_){const B=`Invalid tool_call: ${JSON.stringify(_)}. ${JSON.stringify(c)} requested. Please try again`;this._addMessage({role:r,tool_call_id:f,content:B});continue}}else{const B=`Invalid tool_call: ${JSON.stringify(_)}. Available options are: ${Object.keys(h).map(D=>JSON.stringify(D)).join(", ")}. Please try again`;this._addMessage({role:r,tool_call_id:f,content:B});continue}let J;try{J=Bo(I)?await I.parse(C):C}catch(B){const D=B instanceof Error?B.message:String(B);this._addMessage({role:r,tool_call_id:f,content:D});continue}const L=await I.function(J,this),R=u(this,K,"m",yr).call(this,L);if(this._addMessage({role:r,tool_call_id:f,content:R}),c)return}}}}K=new WeakSet,nn=function(){return u(this,K,"m",wt).call(this).content??null},wt=function(){let e=this.messages.length;for(;e-- >0;){const n=this.messages[e];if(_t(n))return{...n,content:n.content??null,refusal:n.refusal??null}}throw new x("stream ended without producing a ChatCompletionMessage with role=assistant")},sn=function(){for(let e=this.messages.length-1;e>=0;e--){const n=this.messages[e];if(_t(n)&&n?.tool_calls?.length)return n.tool_calls.filter(s=>s.type==="function").at(-1)?.function}},rn=function(){for(let e=this.messages.length-1;e>=0;e--){const n=this.messages[e];if(mr(n)&&n.content!=null&&typeof n.content=="string"&&this.messages.some(s=>s.role==="assistant"&&s.tool_calls?.some(r=>r.type==="function"&&r.id===n.tool_call_id)))return n.content}},an=function(){const e={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(const{usage:n}of this._chatCompletions)n&&(e.completion_tokens+=n.completion_tokens,e.prompt_tokens+=n.prompt_tokens,e.total_tokens+=n.total_tokens);return e},gr=function(e){if(e.n!=null&&e.n>1)throw new x("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},yr=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};class gn extends wr{static runTools(e,n,s){const r=new gn,a={...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"runTools"}};return r._run(()=>r._runTools(e,n,a)),r}_addMessage(e,n=!0){super._addMessage(e,n),_t(e)&&e.content&&this._emit("content",e.content)}}const br=1,vr=2,xr=4,kr=8,Sr=16,Ar=32,Cr=64,Or=128,Ir=256,Tr=Or|Ir,Rr=Sr|Ar|Tr|Cr,$r=br|vr|Rr,Pr=xr|kr,Wo=$r|Pr,F={STR:br,NUM:vr,ARR:xr,OBJ:kr,NULL:Sr,BOOL:Ar,NAN:Cr,INFINITY:Or,MINUS_INFINITY:Ir,INF:Tr,SPECIAL:Rr,ATOM:$r,COLLECTION:Pr,ALL:Wo};class qo extends Error{}class Jo extends Error{}function Ko(t,e=F.ALL){if(typeof t!="string")throw new TypeError(`expecting str, got ${typeof t}`);if(!t.trim())throw new Error(`${t} is empty`);return Zo(t.trim(),e)}const Zo=(t,e)=>{const n=t.length;let s=0;const r=p=>{throw new qo(`${p} at position ${s}`)},a=p=>{throw new Jo(`${p} at position ${s}`)},i=()=>(h(),s>=n&&r("Unexpected end of input"),t[s]==='"'?o():t[s]==="{"?c():t[s]==="["?l():t.substring(s,s+4)==="null"||F.NULL&e&&n-s<4&&"null".startsWith(t.substring(s))?(s+=4,null):t.substring(s,s+4)==="true"||F.BOOL&e&&n-s<4&&"true".startsWith(t.substring(s))?(s+=4,!0):t.substring(s,s+5)==="false"||F.BOOL&e&&n-s<5&&"false".startsWith(t.substring(s))?(s+=5,!1):t.substring(s,s+8)==="Infinity"||F.INFINITY&e&&n-s<8&&"Infinity".startsWith(t.substring(s))?(s+=8,1/0):t.substring(s,s+9)==="-Infinity"||F.MINUS_INFINITY&e&&1<n-s&&n-s<9&&"-Infinity".startsWith(t.substring(s))?(s+=9,-1/0):t.substring(s,s+3)==="NaN"||F.NAN&e&&n-s<3&&"NaN".startsWith(t.substring(s))?(s+=3,NaN):m()),o=()=>{const p=s;let d=!1;for(s++;s<n&&(t[s]!=='"'||d&&t[s-1]==="\\");)d=t[s]==="\\"?!d:!1,s++;if(t.charAt(s)=='"')try{return JSON.parse(t.substring(p,++s-Number(d)))}catch(b){a(String(b))}else if(F.STR&e)try{return JSON.parse(t.substring(p,s-Number(d))+'"')}catch{return JSON.parse(t.substring(p,t.lastIndexOf("\\"))+'"')}r("Unterminated string literal")},c=()=>{s++,h();const p={};try{for(;t[s]!=="}";){if(h(),s>=n&&F.OBJ&e)return p;const d=o();h(),s++;try{const b=i();Object.defineProperty(p,d,{value:b,writable:!0,enumerable:!0,configurable:!0})}catch(b){if(F.OBJ&e)return p;throw b}h(),t[s]===","&&s++}}catch{if(F.OBJ&e)return p;r("Expected '}' at end of object")}return s++,p},l=()=>{s++;const p=[];try{for(;t[s]!=="]";)p.push(i()),h(),t[s]===","&&s++}catch{if(F.ARR&e)return p;r("Expected ']' at end of array")}return s++,p},m=()=>{if(s===0){t==="-"&&F.NUM&e&&r("Not sure what '-' is");try{return JSON.parse(t)}catch(d){if(F.NUM&e)try{return t[t.length-1]==="."?JSON.parse(t.substring(0,t.lastIndexOf("."))):JSON.parse(t.substring(0,t.lastIndexOf("e")))}catch{}a(String(d))}}const p=s;for(t[s]==="-"&&s++;t[s]&&!",]}".includes(t[s]);)s++;s==n&&!(F.NUM&e)&&r("Unterminated number literal");try{return JSON.parse(t.substring(p,s))}catch{t.substring(p,s)==="-"&&F.NUM&e&&r("Not sure what '-' is");try{return JSON.parse(t.substring(p,t.lastIndexOf("e")))}catch(b){a(String(b))}}},h=()=>{for(;s<n&&`
|
|
17
|
+
\r `.includes(t[s]);)s++};return i()},cs=t=>Ko(t,F.ALL^F.NUM);var N,se,me,ie,Ft,Ve,Bt,Ut,Wt,Xe,qt,us;class Fe extends wr{constructor(e){super(),N.add(this),se.set(this,void 0),me.set(this,void 0),ie.set(this,void 0),k(this,se,e),k(this,me,[])}get currentChatCompletionSnapshot(){return u(this,ie,"f")}static fromReadableStream(e){const n=new Fe(null);return n._run(()=>n._fromReadableStream(e)),n}static createChatCompletion(e,n,s){const r=new Fe(n);return r._run(()=>r._runChatCompletion(e,{...n,stream:!0},{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),r}async _createChatCompletion(e,n,s){super._createChatCompletion;const r=s?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),u(this,N,"m",Ft).call(this);const a=await e.chat.completions.create({...n,stream:!0},{...s,signal:this.controller.signal});this._connected();for await(const i of a)u(this,N,"m",Bt).call(this,i);if(a.controller.signal?.aborted)throw new X;return this._addChatCompletion(u(this,N,"m",Xe).call(this))}async _fromReadableStream(e,n){const s=n?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),u(this,N,"m",Ft).call(this),this._connected();const r=ne.fromReadableStream(e,this.controller);let a;for await(const i of r)a&&a!==i.id&&this._addChatCompletion(u(this,N,"m",Xe).call(this)),u(this,N,"m",Bt).call(this,i),a=i.id;if(r.controller.signal?.aborted)throw new X;return this._addChatCompletion(u(this,N,"m",Xe).call(this))}[(se=new WeakMap,me=new WeakMap,ie=new WeakMap,N=new WeakSet,Ft=function(){this.ended||k(this,ie,void 0)},Ve=function(n){let s=u(this,me,"f")[n.index];return s||(s={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},u(this,me,"f")[n.index]=s,s)},Bt=function(n){if(this.ended)return;const s=u(this,N,"m",us).call(this,n);this._emit("chunk",n,s);for(const r of n.choices){const a=s.choices[r.index];r.delta.content!=null&&a.message?.role==="assistant"&&a.message?.content&&(this._emit("content",r.delta.content,a.message.content),this._emit("content.delta",{delta:r.delta.content,snapshot:a.message.content,parsed:a.message.parsed})),r.delta.refusal!=null&&a.message?.role==="assistant"&&a.message?.refusal&&this._emit("refusal.delta",{delta:r.delta.refusal,snapshot:a.message.refusal}),r.logprobs?.content!=null&&a.message?.role==="assistant"&&this._emit("logprobs.content.delta",{content:r.logprobs?.content,snapshot:a.logprobs?.content??[]}),r.logprobs?.refusal!=null&&a.message?.role==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:r.logprobs?.refusal,snapshot:a.logprobs?.refusal??[]});const i=u(this,N,"m",Ve).call(this,a);a.finish_reason&&(u(this,N,"m",Wt).call(this,a),i.current_tool_call_index!=null&&u(this,N,"m",Ut).call(this,a,i.current_tool_call_index));for(const o of r.delta.tool_calls??[])i.current_tool_call_index!==o.index&&(u(this,N,"m",Wt).call(this,a),i.current_tool_call_index!=null&&u(this,N,"m",Ut).call(this,a,i.current_tool_call_index)),i.current_tool_call_index=o.index;for(const o of r.delta.tool_calls??[]){const c=a.message.tool_calls?.[o.index];c?.type&&(c?.type==="function"?this._emit("tool_calls.function.arguments.delta",{name:c.function?.name,index:o.index,arguments:c.function.arguments,parsed_arguments:c.function.parsed_arguments,arguments_delta:o.function?.arguments??""}):(c?.type,void 0))}}},Ut=function(n,s){if(u(this,N,"m",Ve).call(this,n).done_tool_calls.has(s))return;const a=n.message.tool_calls?.[s];if(!a)throw new Error("no tool call snapshot");if(!a.type)throw new Error("tool call snapshot missing `type`");if(a.type==="function"){const i=u(this,se,"f")?.tools?.find(o=>ht(o)&&o.function.name===a.function.name);this._emit("tool_calls.function.arguments.done",{name:a.function.name,index:s,arguments:a.function.arguments,parsed_arguments:We(i)?i.$parseRaw(a.function.arguments):i?.function.strict?JSON.parse(a.function.arguments):null})}else a.type},Wt=function(n){const s=u(this,N,"m",Ve).call(this,n);if(n.message.content&&!s.content_done){s.content_done=!0;const r=u(this,N,"m",qt).call(this);this._emit("content.done",{content:n.message.content,parsed:r?r.$parseRaw(n.message.content):null})}n.message.refusal&&!s.refusal_done&&(s.refusal_done=!0,this._emit("refusal.done",{refusal:n.message.refusal})),n.logprobs?.content&&!s.logprobs_content_done&&(s.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:n.logprobs.content})),n.logprobs?.refusal&&!s.logprobs_refusal_done&&(s.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:n.logprobs.refusal}))},Xe=function(){if(this.ended)throw new x("stream has ended, this shouldn't happen");const n=u(this,ie,"f");if(!n)throw new x("request ended without sending any chunks");return k(this,ie,void 0),k(this,me,[]),zo(n,u(this,se,"f"))},qt=function(){const n=u(this,se,"f")?.response_format;return dn(n)?n:null},us=function(n){var s,r,a,i;let o=u(this,ie,"f");const{choices:c,...l}=n;o?Object.assign(o,l):o=k(this,ie,{...l,choices:[]});for(const{delta:m,finish_reason:h,index:p,logprobs:d=null,...b}of n.choices){let w=o.choices[p];if(w||(w=o.choices[p]={finish_reason:h,index:p,message:{},logprobs:d,...b}),d)if(!w.logprobs)w.logprobs=Object.assign({},d);else{const{content:L,refusal:R,...B}=d;Object.assign(w.logprobs,B),L&&((s=w.logprobs).content??(s.content=[]),w.logprobs.content.push(...L)),R&&((r=w.logprobs).refusal??(r.refusal=[]),w.logprobs.refusal.push(...R))}if(h&&(w.finish_reason=h,u(this,se,"f")&&Js(u(this,se,"f")))){if(h==="length")throw new Ws;if(h==="content_filter")throw new qs}if(Object.assign(w,b),!m)continue;const{content:$,refusal:f,function_call:_,role:C,tool_calls:I,...J}=m;if(Object.assign(w.message,J),f&&(w.message.refusal=(w.message.refusal||"")+f),C&&(w.message.role=C),_&&(w.message.function_call?(_.name&&(w.message.function_call.name=_.name),_.arguments&&((a=w.message.function_call).arguments??(a.arguments=""),w.message.function_call.arguments+=_.arguments)):w.message.function_call=_),$&&(w.message.content=(w.message.content||"")+$,!w.message.refusal&&u(this,N,"m",qt).call(this)&&(w.message.parsed=cs(w.message.content))),I){w.message.tool_calls||(w.message.tool_calls=[]);for(const{index:L,id:R,type:B,function:D,...P}of I){const M=(i=w.message.tool_calls)[L]??(i[L]={});Object.assign(M,P),R&&(M.id=R),B&&(M.type=B),D&&(M.function??(M.function={name:D.name??"",arguments:""})),D?.name&&(M.function.name=D.name),D?.arguments&&(M.function.arguments+=D.arguments,Qa(u(this,se,"f"),M)&&(M.function.parsed_arguments=cs(M.function.arguments)))}}}return o},Symbol.asyncIterator)](){const e=[],n=[];let s=!1;return this.on("chunk",r=>{const a=n.shift();a?a.resolve(r):e.push(r)}),this.on("end",()=>{s=!0;for(const r of n)r.resolve(void 0);n.length=0}),this.on("abort",r=>{s=!0;for(const a of n)a.reject(r);n.length=0}),this.on("error",r=>{s=!0;for(const a of n)a.reject(r);n.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:s?{value:void 0,done:!0}:new Promise((a,i)=>n.push({resolve:a,reject:i})).then(a=>a?{value:a,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new ne(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function zo(t,e){const{id:n,choices:s,created:r,model:a,system_fingerprint:i,...o}=t,c={...o,id:n,choices:s.map(({message:l,finish_reason:m,index:h,logprobs:p,...d})=>{if(!m)throw new x(`missing finish_reason for choice ${h}`);const{content:b=null,function_call:w,tool_calls:$,...f}=l,_=l.role;if(!_)throw new x(`missing role for choice ${h}`);if(w){const{arguments:C,name:I}=w;if(C==null)throw new x(`missing function_call.arguments for choice ${h}`);if(!I)throw new x(`missing function_call.name for choice ${h}`);return{...d,message:{content:b,function_call:{arguments:C,name:I},role:_,refusal:l.refusal??null},finish_reason:m,index:h,logprobs:p}}return $?{...d,index:h,finish_reason:m,logprobs:p,message:{...f,role:_,content:b,refusal:l.refusal??null,tool_calls:$.map((C,I)=>{const{function:J,type:L,id:R,...B}=C,{arguments:D,name:P,...M}=J||{};if(R==null)throw new x(`missing choices[${h}].tool_calls[${I}].id
|
|
18
18
|
${Ge(t)}`);if(L==null)throw new x(`missing choices[${h}].tool_calls[${I}].type
|
|
19
19
|
${Ge(t)}`);if(P==null)throw new x(`missing choices[${h}].tool_calls[${I}].function.name
|
|
20
20
|
${Ge(t)}`);if(D==null)throw new x(`missing choices[${h}].tool_calls[${I}].function.arguments
|
|
21
|
-
${Ge(t)}`);return{...B,id:$,type:L,function:{...M,name:P,arguments:D}}})}}:{...d,message:{...f,content:b,role:_,refusal:l.refusal??null},finish_reason:m,index:h,logprobs:p}}),created:r,model:a,object:"chat.completion",...i?{system_fingerprint:i}:{}};return Va(c,e)}function Ge(t){return JSON.stringify(t)}class bt extends Fe{static fromReadableStream(e){const n=new bt(null);return n._run(()=>n._fromReadableStream(e)),n}static runTools(e,n,s){const r=new bt(n),a={...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"runTools"}};return r._run(()=>r._runTools(e,n,a)),r}}let yn=class extends v{constructor(){super(...arguments),this.messages=new pr(this._client)}create(e,n){return this._client.post("/chat/completions",{body:e,...n,stream:e.stream??!1})}retrieve(e,n){return this._client.get(g`/chat/completions/${e}`,n)}update(e,n,s){return this._client.post(g`/chat/completions/${e}`,{body:n,...s})}list(e={},n){return this._client.getAPIList("/chat/completions",E,{query:e,...n})}delete(e,n){return this._client.delete(g`/chat/completions/${e}`,n)}parse(e,n){return Ya(e.tools),this._client.chat.completions.create(e,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(s=>hn(s,e))}runTools(e,n){return e.stream?bt.runTools(this._client,e,n):gn.runTools(this._client,e,n)}stream(e,n){return Fe.createChatCompletion(this._client,e,n)}};yn.Messages=pr;class wn extends v{constructor(){super(...arguments),this.completions=new yn(this._client)}}wn.Completions=yn;const Er=Symbol("brand.privateNullableHeaders");function*Ho(t){if(!t)return;if(Er in t){const{values:s,nulls:r}=t;yield*s.entries();for(const a of r)yield[a,null];return}let e=!1,n;t instanceof Headers?n=t.entries():Hn(t)?n=t:(e=!0,n=Object.entries(t??{}));for(let s of n){const r=s[0];if(typeof r!="string")throw new TypeError("expected header name to be a string");const a=Hn(s[1])?s[1]:[s[1]];let i=!1;for(const o of a)o!==void 0&&(e&&!i&&(i=!0,yield[r,null]),yield[r,o])}}const y=t=>{const e=new Headers,n=new Set;for(const s of t){const r=new Set;for(const[a,i]of Ho(s)){const o=a.toLowerCase();r.has(o)||(e.delete(a),r.add(o)),i===null?(e.delete(a),n.add(o)):(e.append(a,i),n.delete(o))}}return{[Er]:!0,values:e,nulls:n}};class Mr extends v{create(e,n){return this._client.post("/audio/speech",{body:e,...n,headers:y([{Accept:"application/octet-stream"},n?.headers]),__binaryResponse:!0})}}class Nr extends v{create(e,n){return this._client.post("/audio/transcriptions",pe({body:e,...n,stream:e.stream??!1,__metadata:{model:e.model}},this._client))}}class jr extends v{create(e,n){return this._client.post("/audio/translations",pe({body:e,...n,__metadata:{model:e.model}},this._client))}}class Je extends v{constructor(){super(...arguments),this.transcriptions=new Nr(this._client),this.translations=new jr(this._client),this.speech=new Mr(this._client)}}Je.Transcriptions=Nr;Je.Translations=jr;Je.Speech=Mr;class Lr extends v{create(e,n){return this._client.post("/batches",{body:e,...n})}retrieve(e,n){return this._client.get(g`/batches/${e}`,n)}list(e={},n){return this._client.getAPIList("/batches",E,{query:e,...n})}cancel(e,n){return this._client.post(g`/batches/${e}/cancel`,n)}}class Dr extends v{create(e,n){return this._client.post("/assistants",{body:e,...n,headers:y([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}retrieve(e,n){return this._client.get(g`/assistants/${e}`,{...n,headers:y([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}update(e,n,s){return this._client.post(g`/assistants/${e}`,{body:n,...s,headers:y([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}list(e={},n){return this._client.getAPIList("/assistants",E,{query:e,...n,headers:y([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}delete(e,n){return this._client.delete(g`/assistants/${e}`,{...n,headers:y([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}}let Fr=class extends v{create(e,n){return this._client.post("/realtime/sessions",{body:e,...n,headers:y([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}};class Br extends v{create(e,n){return this._client.post("/realtime/transcription_sessions",{body:e,...n,headers:y([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}}let It=class extends v{constructor(){super(...arguments),this.sessions=new Fr(this._client),this.transcriptionSessions=new Br(this._client)}};It.Sessions=Fr;It.TranscriptionSessions=Br;class Ur extends v{create(e,n){return this._client.post("/chatkit/sessions",{body:e,...n,headers:y([{"OpenAI-Beta":"chatkit_beta=v1"},n?.headers])})}cancel(e,n){return this._client.post(g`/chatkit/sessions/${e}/cancel`,{...n,headers:y([{"OpenAI-Beta":"chatkit_beta=v1"},n?.headers])})}}let Wr=class extends v{retrieve(e,n){return this._client.get(g`/chatkit/threads/${e}`,{...n,headers:y([{"OpenAI-Beta":"chatkit_beta=v1"},n?.headers])})}list(e={},n){return this._client.getAPIList("/chatkit/threads",mt,{query:e,...n,headers:y([{"OpenAI-Beta":"chatkit_beta=v1"},n?.headers])})}delete(e,n){return this._client.delete(g`/chatkit/threads/${e}`,{...n,headers:y([{"OpenAI-Beta":"chatkit_beta=v1"},n?.headers])})}listItems(e,n={},s){return this._client.getAPIList(g`/chatkit/threads/${e}/items`,mt,{query:n,...s,headers:y([{"OpenAI-Beta":"chatkit_beta=v1"},s?.headers])})}};class Tt extends v{constructor(){super(...arguments),this.sessions=new Ur(this._client),this.threads=new Wr(this._client)}}Tt.Sessions=Ur;Tt.Threads=Wr;class qr extends v{create(e,n,s){return this._client.post(g`/threads/${e}/messages`,{body:n,...s,headers:y([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}retrieve(e,n,s){const{thread_id:r}=n;return this._client.get(g`/threads/${r}/messages/${e}`,{...s,headers:y([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}update(e,n,s){const{thread_id:r,...a}=n;return this._client.post(g`/threads/${r}/messages/${e}`,{body:a,...s,headers:y([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}list(e,n={},s){return this._client.getAPIList(g`/threads/${e}/messages`,E,{query:n,...s,headers:y([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}delete(e,n,s){const{thread_id:r}=n;return this._client.delete(g`/threads/${r}/messages/${e}`,{...s,headers:y([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}}class Jr extends v{retrieve(e,n,s){const{thread_id:r,run_id:a,...i}=n;return this._client.get(g`/threads/${r}/runs/${a}/steps/${e}`,{query:i,...s,headers:y([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}list(e,n,s){const{thread_id:r,...a}=n;return this._client.getAPIList(g`/threads/${r}/runs/${e}/steps`,E,{query:a,...s,headers:y([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}}const Vo=t=>{if(typeof Buffer<"u"){const e=Buffer.from(t,"base64");return Array.from(new Float32Array(e.buffer,e.byteOffset,e.length/Float32Array.BYTES_PER_ELEMENT))}else{const e=atob(t),n=e.length,s=new Uint8Array(n);for(let r=0;r<n;r++)s[r]=e.charCodeAt(r);return Array.from(new Float32Array(s.buffer))}};var Xo={};const _e=t=>{if(typeof globalThis.process<"u")return Xo?.[t]?.trim()??void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(t)?.trim()};var W,he,on,te,at,Y,fe,ve,de,vt,V,it,ot,Le,Me,Ne,ds,hs,fs,ps,ms,_s,gs;class De extends _n{constructor(){super(...arguments),W.add(this),on.set(this,[]),te.set(this,{}),at.set(this,{}),Y.set(this,void 0),fe.set(this,void 0),ve.set(this,void 0),de.set(this,void 0),vt.set(this,void 0),V.set(this,void 0),it.set(this,void 0),ot.set(this,void 0),Le.set(this,void 0)}[(on=new WeakMap,te=new WeakMap,at=new WeakMap,Y=new WeakMap,fe=new WeakMap,ve=new WeakMap,de=new WeakMap,vt=new WeakMap,V=new WeakMap,it=new WeakMap,ot=new WeakMap,Le=new WeakMap,W=new WeakSet,Symbol.asyncIterator)](){const e=[],n=[];let s=!1;return this.on("event",r=>{const a=n.shift();a?a.resolve(r):e.push(r)}),this.on("end",()=>{s=!0;for(const r of n)r.resolve(void 0);n.length=0}),this.on("abort",r=>{s=!0;for(const a of n)a.reject(r);n.length=0}),this.on("error",r=>{s=!0;for(const a of n)a.reject(r);n.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:s?{value:void 0,done:!0}:new Promise((a,i)=>n.push({resolve:a,reject:i})).then(a=>a?{value:a,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){const n=new he;return n._run(()=>n._fromReadableStream(e)),n}async _fromReadableStream(e,n){const s=n?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),this._connected();const r=ne.fromReadableStream(e,this.controller);for await(const a of r)u(this,W,"m",Me).call(this,a);if(r.controller.signal?.aborted)throw new X;return this._addRun(u(this,W,"m",Ne).call(this))}toReadableStream(){return new ne(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,n,s,r){const a=new he;return a._run(()=>a._runToolAssistantStream(e,n,s,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),a}async _createToolAssistantStream(e,n,s,r){const a=r?.signal;a&&(a.aborted&&this.controller.abort(),a.addEventListener("abort",()=>this.controller.abort()));const i={...s,stream:!0},o=await e.submitToolOutputs(n,i,{...r,signal:this.controller.signal});this._connected();for await(const c of o)u(this,W,"m",Me).call(this,c);if(o.controller.signal?.aborted)throw new X;return this._addRun(u(this,W,"m",Ne).call(this))}static createThreadAssistantStream(e,n,s){const r=new he;return r._run(()=>r._threadAssistantStream(e,n,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),r}static createAssistantStream(e,n,s,r){const a=new he;return a._run(()=>a._runAssistantStream(e,n,s,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),a}currentEvent(){return u(this,it,"f")}currentRun(){return u(this,ot,"f")}currentMessageSnapshot(){return u(this,Y,"f")}currentRunStepSnapshot(){return u(this,Le,"f")}async finalRunSteps(){return await this.done(),Object.values(u(this,te,"f"))}async finalMessages(){return await this.done(),Object.values(u(this,at,"f"))}async finalRun(){if(await this.done(),!u(this,fe,"f"))throw Error("Final run was not received.");return u(this,fe,"f")}async _createThreadAssistantStream(e,n,s){const r=s?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort()));const a={...n,stream:!0},i=await e.createAndRun(a,{...s,signal:this.controller.signal});this._connected();for await(const o of i)u(this,W,"m",Me).call(this,o);if(i.controller.signal?.aborted)throw new X;return this._addRun(u(this,W,"m",Ne).call(this))}async _createAssistantStream(e,n,s,r){const a=r?.signal;a&&(a.aborted&&this.controller.abort(),a.addEventListener("abort",()=>this.controller.abort()));const i={...s,stream:!0},o=await e.create(n,i,{...r,signal:this.controller.signal});this._connected();for await(const c of o)u(this,W,"m",Me).call(this,c);if(o.controller.signal?.aborted)throw new X;return this._addRun(u(this,W,"m",Ne).call(this))}static accumulateDelta(e,n){for(const[s,r]of Object.entries(n)){if(!e.hasOwnProperty(s)){e[s]=r;continue}let a=e[s];if(a==null){e[s]=r;continue}if(s==="index"||s==="type"){e[s]=r;continue}if(typeof a=="string"&&typeof r=="string")a+=r;else if(typeof a=="number"&&typeof r=="number")a+=r;else if(jt(a)&&jt(r))a=this.accumulateDelta(a,r);else if(Array.isArray(a)&&Array.isArray(r)){if(a.every(i=>typeof i=="string"||typeof i=="number")){a.push(...r);continue}for(const i of r){if(!jt(i))throw new Error(`Expected array delta entry to be an object but got: ${i}`);const o=i.index;if(o==null)throw console.error(i),new Error("Expected array delta entry to have an `index` property");if(typeof o!="number")throw new Error(`Expected array delta entry \`index\` property to be a number but got ${o}`);const c=a[o];c==null?a.push(i):a[o]=this.accumulateDelta(c,i)}continue}else throw Error(`Unhandled record type: ${s}, deltaValue: ${r}, accValue: ${a}`);e[s]=a}return e}_addRun(e){return e}async _threadAssistantStream(e,n,s){return await this._createThreadAssistantStream(n,e,s)}async _runAssistantStream(e,n,s,r){return await this._createAssistantStream(n,e,s,r)}async _runToolAssistantStream(e,n,s,r){return await this._createToolAssistantStream(n,e,s,r)}}he=De,Me=function(e){if(!this.ended)switch(k(this,it,e),u(this,W,"m",fs).call(this,e),e.event){case"thread.created":break;case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":case"thread.run.requires_action":case"thread.run.completed":case"thread.run.incomplete":case"thread.run.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":u(this,W,"m",gs).call(this,e);break;case"thread.run.step.created":case"thread.run.step.in_progress":case"thread.run.step.delta":case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":u(this,W,"m",hs).call(this,e);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":u(this,W,"m",ds).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier")}},Ne=function(){if(this.ended)throw new x("stream has ended, this shouldn't happen");if(!u(this,fe,"f"))throw Error("Final run has not been received");return u(this,fe,"f")},ds=function(e){const[n,s]=u(this,W,"m",ms).call(this,e,u(this,Y,"f"));k(this,Y,n),u(this,at,"f")[n.id]=n;for(const r of s){const a=n.content[r.index];a?.type=="text"&&this._emit("textCreated",a.text)}switch(e.event){case"thread.message.created":this._emit("messageCreated",e.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",e.data.delta,n),e.data.delta.content)for(const r of e.data.delta.content){if(r.type=="text"&&r.text){let a=r.text,i=n.content[r.index];if(i&&i.type=="text")this._emit("textDelta",a,i.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(r.index!=u(this,ve,"f")){if(u(this,de,"f"))switch(u(this,de,"f").type){case"text":this._emit("textDone",u(this,de,"f").text,u(this,Y,"f"));break;case"image_file":this._emit("imageFileDone",u(this,de,"f").image_file,u(this,Y,"f"));break}k(this,ve,r.index)}k(this,de,n.content[r.index])}break;case"thread.message.completed":case"thread.message.incomplete":if(u(this,ve,"f")!==void 0){const r=e.data.content[u(this,ve,"f")];if(r)switch(r.type){case"image_file":this._emit("imageFileDone",r.image_file,u(this,Y,"f"));break;case"text":this._emit("textDone",r.text,u(this,Y,"f"));break}}u(this,Y,"f")&&this._emit("messageDone",e.data),k(this,Y,void 0)}},hs=function(e){const n=u(this,W,"m",ps).call(this,e);switch(k(this,Le,n),e.event){case"thread.run.step.created":this._emit("runStepCreated",e.data);break;case"thread.run.step.delta":const s=e.data.delta;if(s.step_details&&s.step_details.type=="tool_calls"&&s.step_details.tool_calls&&n.step_details.type=="tool_calls")for(const a of s.step_details.tool_calls)a.index==u(this,vt,"f")?this._emit("toolCallDelta",a,n.step_details.tool_calls[a.index]):(u(this,V,"f")&&this._emit("toolCallDone",u(this,V,"f")),k(this,vt,a.index),k(this,V,n.step_details.tool_calls[a.index]),u(this,V,"f")&&this._emit("toolCallCreated",u(this,V,"f")));this._emit("runStepDelta",e.data.delta,n);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":k(this,Le,void 0),e.data.step_details.type=="tool_calls"&&u(this,V,"f")&&(this._emit("toolCallDone",u(this,V,"f")),k(this,V,void 0)),this._emit("runStepDone",e.data,n);break}},fs=function(e){u(this,on,"f").push(e),this._emit("event",e)},ps=function(e){switch(e.event){case"thread.run.step.created":return u(this,te,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let n=u(this,te,"f")[e.data.id];if(!n)throw Error("Received a RunStepDelta before creation of a snapshot");let s=e.data;if(s.delta){const r=he.accumulateDelta(n,s.delta);u(this,te,"f")[e.data.id]=r}return u(this,te,"f")[e.data.id];case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":case"thread.run.step.in_progress":u(this,te,"f")[e.data.id]=e.data;break}if(u(this,te,"f")[e.data.id])return u(this,te,"f")[e.data.id];throw new Error("No snapshot available")},ms=function(e,n){let s=[];switch(e.event){case"thread.message.created":return[e.data,s];case"thread.message.delta":if(!n)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let r=e.data;if(r.delta.content)for(const a of r.delta.content)if(a.index in n.content){let i=n.content[a.index];n.content[a.index]=u(this,W,"m",_s).call(this,a,i)}else n.content[a.index]=a,s.push(a);return[n,s];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(n)return[n,s];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},_s=function(e,n){return he.accumulateDelta(n,e)},gs=function(e){switch(k(this,ot,e.data),e.event){case"thread.run.created":break;case"thread.run.queued":break;case"thread.run.in_progress":break;case"thread.run.requires_action":case"thread.run.cancelled":case"thread.run.failed":case"thread.run.completed":case"thread.run.expired":case"thread.run.incomplete":k(this,fe,e.data),u(this,V,"f")&&(this._emit("toolCallDone",u(this,V,"f")),k(this,V,void 0));break}};let bn=class extends v{constructor(){super(...arguments),this.steps=new Jr(this._client)}create(e,n,s){const{include:r,...a}=n;return this._client.post(g`/threads/${e}/runs`,{query:{include:r},body:a,...s,headers:y([{"OpenAI-Beta":"assistants=v2"},s?.headers]),stream:n.stream??!1})}retrieve(e,n,s){const{thread_id:r}=n;return this._client.get(g`/threads/${r}/runs/${e}`,{...s,headers:y([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}update(e,n,s){const{thread_id:r,...a}=n;return this._client.post(g`/threads/${r}/runs/${e}`,{body:a,...s,headers:y([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}list(e,n={},s){return this._client.getAPIList(g`/threads/${e}/runs`,E,{query:n,...s,headers:y([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}cancel(e,n,s){const{thread_id:r}=n;return this._client.post(g`/threads/${r}/runs/${e}/cancel`,{...s,headers:y([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}async createAndPoll(e,n,s){const r=await this.create(e,n,s);return await this.poll(r.id,{thread_id:e},s)}createAndStream(e,n,s){return De.createAssistantStream(e,this._client.beta.threads.runs,n,s)}async poll(e,n,s){const r=y([s?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":s?.pollIntervalMs?.toString()??void 0}]);for(;;){const{data:a,response:i}=await this.retrieve(e,n,{...s,headers:{...s?.headers,...r}}).withResponse();switch(a.status){case"queued":case"in_progress":case"cancelling":let o=5e3;if(s?.pollIntervalMs)o=s.pollIntervalMs;else{const c=i.headers.get("openai-poll-after-ms");if(c){const l=parseInt(c);isNaN(l)||(o=l)}}await qe(o);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return a}}}stream(e,n,s){return De.createAssistantStream(e,this._client.beta.threads.runs,n,s)}submitToolOutputs(e,n,s){const{thread_id:r,...a}=n;return this._client.post(g`/threads/${r}/runs/${e}/submit_tool_outputs`,{body:a,...s,headers:y([{"OpenAI-Beta":"assistants=v2"},s?.headers]),stream:n.stream??!1})}async submitToolOutputsAndPoll(e,n,s){const r=await this.submitToolOutputs(e,n,s);return await this.poll(r.id,n,s)}submitToolOutputsStream(e,n,s){return De.createToolAssistantStream(e,this._client.beta.threads.runs,n,s)}};bn.Steps=Jr;class $t extends v{constructor(){super(...arguments),this.runs=new bn(this._client),this.messages=new qr(this._client)}create(e={},n){return this._client.post("/threads",{body:e,...n,headers:y([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}retrieve(e,n){return this._client.get(g`/threads/${e}`,{...n,headers:y([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}update(e,n,s){return this._client.post(g`/threads/${e}`,{body:n,...s,headers:y([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}delete(e,n){return this._client.delete(g`/threads/${e}`,{...n,headers:y([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}createAndRun(e,n){return this._client.post("/threads/runs",{body:e,...n,headers:y([{"OpenAI-Beta":"assistants=v2"},n?.headers]),stream:e.stream??!1})}async createAndRunPoll(e,n){const s=await this.createAndRun(e,n);return await this.runs.poll(s.id,{thread_id:s.thread_id},n)}createAndRunStream(e,n){return De.createThreadAssistantStream(e,this._client.beta.threads,n)}}$t.Runs=bn;$t.Messages=qr;class Se extends v{constructor(){super(...arguments),this.realtime=new It(this._client),this.chatkit=new Tt(this._client),this.assistants=new Dr(this._client),this.threads=new $t(this._client)}}Se.Realtime=It;Se.ChatKit=Tt;Se.Assistants=Dr;Se.Threads=$t;class Kr extends v{create(e,n){return this._client.post("/completions",{body:e,...n,stream:e.stream??!1})}}class Zr extends v{retrieve(e,n,s){const{container_id:r}=n;return this._client.get(g`/containers/${r}/files/${e}/content`,{...s,headers:y([{Accept:"application/binary"},s?.headers]),__binaryResponse:!0})}}let vn=class extends v{constructor(){super(...arguments),this.content=new Zr(this._client)}create(e,n,s){return this._client.post(g`/containers/${e}/files`,pe({body:n,...s},this._client))}retrieve(e,n,s){const{container_id:r}=n;return this._client.get(g`/containers/${r}/files/${e}`,s)}list(e,n={},s){return this._client.getAPIList(g`/containers/${e}/files`,E,{query:n,...s})}delete(e,n,s){const{container_id:r}=n;return this._client.delete(g`/containers/${r}/files/${e}`,{...s,headers:y([{Accept:"*/*"},s?.headers])})}};vn.Content=Zr;class xn extends v{constructor(){super(...arguments),this.files=new vn(this._client)}create(e,n){return this._client.post("/containers",{body:e,...n})}retrieve(e,n){return this._client.get(g`/containers/${e}`,n)}list(e={},n){return this._client.getAPIList("/containers",E,{query:e,...n})}delete(e,n){return this._client.delete(g`/containers/${e}`,{...n,headers:y([{Accept:"*/*"},n?.headers])})}}xn.Files=vn;class zr extends v{create(e,n,s){const{include:r,...a}=n;return this._client.post(g`/conversations/${e}/items`,{query:{include:r},body:a,...s})}retrieve(e,n,s){const{conversation_id:r,...a}=n;return this._client.get(g`/conversations/${r}/items/${e}`,{query:a,...s})}list(e,n={},s){return this._client.getAPIList(g`/conversations/${e}/items`,mt,{query:n,...s})}delete(e,n,s){const{conversation_id:r}=n;return this._client.delete(g`/conversations/${r}/items/${e}`,s)}}class kn extends v{constructor(){super(...arguments),this.items=new zr(this._client)}create(e={},n){return this._client.post("/conversations",{body:e,...n})}retrieve(e,n){return this._client.get(g`/conversations/${e}`,n)}update(e,n,s){return this._client.post(g`/conversations/${e}`,{body:n,...s})}delete(e,n){return this._client.delete(g`/conversations/${e}`,n)}}kn.Items=zr;class Hr extends v{create(e,n){const s=!!e.encoding_format;let r=s?e.encoding_format:"base64";s&&U(this._client).debug("embeddings/user defined encoding_format:",e.encoding_format);const a=this._client.post("/embeddings",{body:{...e,encoding_format:r},...n});return s?a:(U(this._client).debug("embeddings/decoding base64 embeddings from base64"),a._thenUnwrap(i=>(i&&i.data&&i.data.forEach(o=>{const c=o.embedding;o.embedding=Vo(c)}),i)))}}class Vr extends v{retrieve(e,n,s){const{eval_id:r,run_id:a}=n;return this._client.get(g`/evals/${r}/runs/${a}/output_items/${e}`,s)}list(e,n,s){const{eval_id:r,...a}=n;return this._client.getAPIList(g`/evals/${r}/runs/${e}/output_items`,E,{query:a,...s})}}class Sn extends v{constructor(){super(...arguments),this.outputItems=new Vr(this._client)}create(e,n,s){return this._client.post(g`/evals/${e}/runs`,{body:n,...s})}retrieve(e,n,s){const{eval_id:r}=n;return this._client.get(g`/evals/${r}/runs/${e}`,s)}list(e,n={},s){return this._client.getAPIList(g`/evals/${e}/runs`,E,{query:n,...s})}delete(e,n,s){const{eval_id:r}=n;return this._client.delete(g`/evals/${r}/runs/${e}`,s)}cancel(e,n,s){const{eval_id:r}=n;return this._client.post(g`/evals/${r}/runs/${e}`,s)}}Sn.OutputItems=Vr;class An extends v{constructor(){super(...arguments),this.runs=new Sn(this._client)}create(e,n){return this._client.post("/evals",{body:e,...n})}retrieve(e,n){return this._client.get(g`/evals/${e}`,n)}update(e,n,s){return this._client.post(g`/evals/${e}`,{body:n,...s})}list(e={},n){return this._client.getAPIList("/evals",E,{query:e,...n})}delete(e,n){return this._client.delete(g`/evals/${e}`,n)}}An.Runs=Sn;let Xr=class extends v{create(e,n){return this._client.post("/files",pe({body:e,...n},this._client))}retrieve(e,n){return this._client.get(g`/files/${e}`,n)}list(e={},n){return this._client.getAPIList("/files",E,{query:e,...n})}delete(e,n){return this._client.delete(g`/files/${e}`,n)}content(e,n){return this._client.get(g`/files/${e}/content`,{...n,headers:y([{Accept:"application/binary"},n?.headers]),__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:n=5e3,maxWait:s=1800*1e3}={}){const r=new Set(["processed","error","deleted"]),a=Date.now();let i=await this.retrieve(e);for(;!i.status||!r.has(i.status);)if(await qe(n),i=await this.retrieve(e),Date.now()-a>s)throw new St({message:`Giving up on waiting for file ${e} to finish processing after ${s} milliseconds.`});return i}};class Gr extends v{}let Qr=class extends v{run(e,n){return this._client.post("/fine_tuning/alpha/graders/run",{body:e,...n})}validate(e,n){return this._client.post("/fine_tuning/alpha/graders/validate",{body:e,...n})}};class Cn extends v{constructor(){super(...arguments),this.graders=new Qr(this._client)}}Cn.Graders=Qr;class Yr extends v{create(e,n,s){return this._client.getAPIList(g`/fine_tuning/checkpoints/${e}/permissions`,Ot,{body:n,method:"post",...s})}retrieve(e,n={},s){return this._client.get(g`/fine_tuning/checkpoints/${e}/permissions`,{query:n,...s})}delete(e,n,s){const{fine_tuned_model_checkpoint:r}=n;return this._client.delete(g`/fine_tuning/checkpoints/${r}/permissions/${e}`,s)}}let On=class extends v{constructor(){super(...arguments),this.permissions=new Yr(this._client)}};On.Permissions=Yr;class ea extends v{list(e,n={},s){return this._client.getAPIList(g`/fine_tuning/jobs/${e}/checkpoints`,E,{query:n,...s})}}class In extends v{constructor(){super(...arguments),this.checkpoints=new ea(this._client)}create(e,n){return this._client.post("/fine_tuning/jobs",{body:e,...n})}retrieve(e,n){return this._client.get(g`/fine_tuning/jobs/${e}`,n)}list(e={},n){return this._client.getAPIList("/fine_tuning/jobs",E,{query:e,...n})}cancel(e,n){return this._client.post(g`/fine_tuning/jobs/${e}/cancel`,n)}listEvents(e,n={},s){return this._client.getAPIList(g`/fine_tuning/jobs/${e}/events`,E,{query:n,...s})}pause(e,n){return this._client.post(g`/fine_tuning/jobs/${e}/pause`,n)}resume(e,n){return this._client.post(g`/fine_tuning/jobs/${e}/resume`,n)}}In.Checkpoints=ea;class Ae extends v{constructor(){super(...arguments),this.methods=new Gr(this._client),this.jobs=new In(this._client),this.checkpoints=new On(this._client),this.alpha=new Cn(this._client)}}Ae.Methods=Gr;Ae.Jobs=In;Ae.Checkpoints=On;Ae.Alpha=Cn;class ta extends v{}class Tn extends v{constructor(){super(...arguments),this.graderModels=new ta(this._client)}}Tn.GraderModels=ta;class na extends v{createVariation(e,n){return this._client.post("/images/variations",pe({body:e,...n},this._client))}edit(e,n){return this._client.post("/images/edits",pe({body:e,...n,stream:e.stream??!1},this._client))}generate(e,n){return this._client.post("/images/generations",{body:e,...n,stream:e.stream??!1})}}class sa extends v{retrieve(e,n){return this._client.get(g`/models/${e}`,n)}list(e){return this._client.getAPIList("/models",Ot,e)}delete(e,n){return this._client.delete(g`/models/${e}`,n)}}class ra extends v{create(e,n){return this._client.post("/moderations",{body:e,...n})}}class aa extends v{accept(e,n,s){return this._client.post(g`/realtime/calls/${e}/accept`,{body:n,...s,headers:y([{Accept:"*/*"},s?.headers])})}hangup(e,n){return this._client.post(g`/realtime/calls/${e}/hangup`,{...n,headers:y([{Accept:"*/*"},n?.headers])})}refer(e,n,s){return this._client.post(g`/realtime/calls/${e}/refer`,{body:n,...s,headers:y([{Accept:"*/*"},s?.headers])})}reject(e,n={},s){return this._client.post(g`/realtime/calls/${e}/reject`,{body:n,...s,headers:y([{Accept:"*/*"},s?.headers])})}}class ia extends v{create(e,n){return this._client.post("/realtime/client_secrets",{body:e,...n})}}class Rt extends v{constructor(){super(...arguments),this.clientSecrets=new ia(this._client),this.calls=new aa(this._client)}}Rt.ClientSecrets=ia;Rt.Calls=aa;var ge,Qe,oe,Ye,ys,ws,bs,vs;class $n extends _n{constructor(e){super(),ge.add(this),Qe.set(this,void 0),oe.set(this,void 0),Ye.set(this,void 0),k(this,Qe,e)}static createResponse(e,n,s){const r=new $n(n);return r._run(()=>r._createOrRetrieveResponse(e,n,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),r}async _createOrRetrieveResponse(e,n,s){const r=s?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),u(this,ge,"m",ys).call(this);let a,i=null;"response_id"in n?(a=await e.responses.retrieve(n.response_id,{stream:!0},{...s,signal:this.controller.signal,stream:!0}),i=n.starting_after??null):a=await e.responses.create({...n,stream:!0},{...s,signal:this.controller.signal}),this._connected();for await(const o of a)u(this,ge,"m",ws).call(this,o,i);if(a.controller.signal?.aborted)throw new X;return u(this,ge,"m",bs).call(this)}[(Qe=new WeakMap,oe=new WeakMap,Ye=new WeakMap,ge=new WeakSet,ys=function(){this.ended||k(this,oe,void 0)},ws=function(n,s){if(this.ended)return;const r=(i,o)=>{(s==null||o.sequence_number>s)&&this._emit(i,o)},a=u(this,ge,"m",vs).call(this,n);switch(r("event",n),n.type){case"response.output_text.delta":{const i=a.output[n.output_index];if(!i)throw new x(`missing output at index ${n.output_index}`);if(i.type==="message"){const o=i.content[n.content_index];if(!o)throw new x(`missing content at index ${n.content_index}`);if(o.type!=="output_text")throw new x(`expected content to be 'output_text', got ${o.type}`);r("response.output_text.delta",{...n,snapshot:o.text})}break}case"response.function_call_arguments.delta":{const i=a.output[n.output_index];if(!i)throw new x(`missing output at index ${n.output_index}`);i.type==="function_call"&&r("response.function_call_arguments.delta",{...n,snapshot:i.arguments});break}default:r(n.type,n);break}},bs=function(){if(this.ended)throw new x("stream has ended, this shouldn't happen");const n=u(this,oe,"f");if(!n)throw new x("request ended without sending any events");k(this,oe,void 0);const s=Go(n,u(this,Qe,"f"));return k(this,Ye,s),s},vs=function(n){let s=u(this,oe,"f");if(!s){if(n.type!=="response.created")throw new x(`When snapshot hasn't been set yet, expected 'response.created' event, got ${n.type}`);return s=k(this,oe,n.response),s}switch(n.type){case"response.output_item.added":{s.output.push(n.item);break}case"response.content_part.added":{const r=s.output[n.output_index];if(!r)throw new x(`missing output at index ${n.output_index}`);const a=r.type,i=n.part;a==="message"&&i.type!=="reasoning_text"?r.content.push(i):a==="reasoning"&&i.type==="reasoning_text"&&(r.content||(r.content=[]),r.content.push(i));break}case"response.output_text.delta":{const r=s.output[n.output_index];if(!r)throw new x(`missing output at index ${n.output_index}`);if(r.type==="message"){const a=r.content[n.content_index];if(!a)throw new x(`missing content at index ${n.content_index}`);if(a.type!=="output_text")throw new x(`expected content to be 'output_text', got ${a.type}`);a.text+=n.delta}break}case"response.function_call_arguments.delta":{const r=s.output[n.output_index];if(!r)throw new x(`missing output at index ${n.output_index}`);r.type==="function_call"&&(r.arguments+=n.delta);break}case"response.reasoning_text.delta":{const r=s.output[n.output_index];if(!r)throw new x(`missing output at index ${n.output_index}`);if(r.type==="reasoning"){const a=r.content?.[n.content_index];if(!a)throw new x(`missing content at index ${n.content_index}`);if(a.type!=="reasoning_text")throw new x(`expected content to be 'reasoning_text', got ${a.type}`);a.text+=n.delta}break}case"response.completed":{k(this,oe,n.response);break}}return s},Symbol.asyncIterator)](){const e=[],n=[];let s=!1;return this.on("event",r=>{const a=n.shift();a?a.resolve(r):e.push(r)}),this.on("end",()=>{s=!0;for(const r of n)r.resolve(void 0);n.length=0}),this.on("abort",r=>{s=!0;for(const a of n)a.reject(r);n.length=0}),this.on("error",r=>{s=!0;for(const a of n)a.reject(r);n.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:s?{value:void 0,done:!0}:new Promise((a,i)=>n.push({resolve:a,reject:i})).then(a=>a?{value:a,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();const e=u(this,Ye,"f");if(!e)throw new x("stream ended without producing a ChatCompletion");return e}}function Go(t,e){return Bi(t,e)}class oa extends v{list(e,n={},s){return this._client.getAPIList(g`/responses/${e}/input_items`,E,{query:n,...s})}}class la extends v{count(e={},n){return this._client.post("/responses/input_tokens",{body:e,...n})}}class Pt extends v{constructor(){super(...arguments),this.inputItems=new oa(this._client),this.inputTokens=new la(this._client)}create(e,n){return this._client.post("/responses",{body:e,...n,stream:e.stream??!1})._thenUnwrap(s=>("object"in s&&s.object==="response"&&Vt(s),s))}retrieve(e,n={},s){return this._client.get(g`/responses/${e}`,{query:n,...s,stream:n?.stream??!1})._thenUnwrap(r=>("object"in r&&r.object==="response"&&Vt(r),r))}delete(e,n){return this._client.delete(g`/responses/${e}`,{...n,headers:y([{Accept:"*/*"},n?.headers])})}parse(e,n){return this._client.responses.create(e,n)._thenUnwrap(s=>Xs(s,e))}stream(e,n){return $n.createResponse(this._client,e,n)}cancel(e,n){return this._client.post(g`/responses/${e}/cancel`,n)}}Pt.InputItems=oa;Pt.InputTokens=la;class ca extends v{create(e,n,s){return this._client.post(g`/uploads/${e}/parts`,pe({body:n,...s},this._client))}}class Rn extends v{constructor(){super(...arguments),this.parts=new ca(this._client)}create(e,n){return this._client.post("/uploads",{body:e,...n})}cancel(e,n){return this._client.post(g`/uploads/${e}/cancel`,n)}complete(e,n,s){return this._client.post(g`/uploads/${e}/complete`,{body:n,...s})}}Rn.Parts=ca;const Qo=async t=>{const e=await Promise.allSettled(t),n=e.filter(r=>r.status==="rejected");if(n.length){for(const r of n)console.error(r.reason);throw new Error(`${n.length} promise(s) failed - see the above errors`)}const s=[];for(const r of e)r.status==="fulfilled"&&s.push(r.value);return s};class ua extends v{create(e,n,s){return this._client.post(g`/vector_stores/${e}/file_batches`,{body:n,...s,headers:y([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}retrieve(e,n,s){const{vector_store_id:r}=n;return this._client.get(g`/vector_stores/${r}/file_batches/${e}`,{...s,headers:y([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}cancel(e,n,s){const{vector_store_id:r}=n;return this._client.post(g`/vector_stores/${r}/file_batches/${e}/cancel`,{...s,headers:y([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}async createAndPoll(e,n,s){const r=await this.create(e,n);return await this.poll(e,r.id,s)}listFiles(e,n,s){const{vector_store_id:r,...a}=n;return this._client.getAPIList(g`/vector_stores/${r}/file_batches/${e}/files`,E,{query:a,...s,headers:y([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}async poll(e,n,s){const r=y([s?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":s?.pollIntervalMs?.toString()??void 0}]);for(;;){const{data:a,response:i}=await this.retrieve(n,{vector_store_id:e},{...s,headers:r}).withResponse();switch(a.status){case"in_progress":let o=5e3;if(s?.pollIntervalMs)o=s.pollIntervalMs;else{const c=i.headers.get("openai-poll-after-ms");if(c){const l=parseInt(c);isNaN(l)||(o=l)}}await qe(o);break;case"failed":case"cancelled":case"completed":return a}}}async uploadAndPoll(e,{files:n,fileIds:s=[]},r){if(n==null||n.length==0)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");const a=r?.maxConcurrency??5,i=Math.min(a,n.length),o=this._client,c=n.values(),l=[...s];async function m(p){for(let d of p){const b=await o.files.create({file:d,purpose:"assistants"},r);l.push(b.id)}}const h=Array(i).fill(c).map(m);return await Qo(h),await this.createAndPoll(e,{file_ids:l})}}class da extends v{create(e,n,s){return this._client.post(g`/vector_stores/${e}/files`,{body:n,...s,headers:y([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}retrieve(e,n,s){const{vector_store_id:r}=n;return this._client.get(g`/vector_stores/${r}/files/${e}`,{...s,headers:y([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}update(e,n,s){const{vector_store_id:r,...a}=n;return this._client.post(g`/vector_stores/${r}/files/${e}`,{body:a,...s,headers:y([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}list(e,n={},s){return this._client.getAPIList(g`/vector_stores/${e}/files`,E,{query:n,...s,headers:y([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}delete(e,n,s){const{vector_store_id:r}=n;return this._client.delete(g`/vector_stores/${r}/files/${e}`,{...s,headers:y([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}async createAndPoll(e,n,s){const r=await this.create(e,n,s);return await this.poll(e,r.id,s)}async poll(e,n,s){const r=y([s?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":s?.pollIntervalMs?.toString()??void 0}]);for(;;){const a=await this.retrieve(n,{vector_store_id:e},{...s,headers:r}).withResponse(),i=a.data;switch(i.status){case"in_progress":let o=5e3;if(s?.pollIntervalMs)o=s.pollIntervalMs;else{const c=a.response.headers.get("openai-poll-after-ms");if(c){const l=parseInt(c);isNaN(l)||(o=l)}}await qe(o);break;case"failed":case"completed":return i}}}async upload(e,n,s){const r=await this._client.files.create({file:n,purpose:"assistants"},s);return this.create(e,{file_id:r.id},s)}async uploadAndPoll(e,n,s){const r=await this.upload(e,n,s);return await this.poll(e,r.id,s)}content(e,n,s){const{vector_store_id:r}=n;return this._client.getAPIList(g`/vector_stores/${r}/files/${e}/content`,Ot,{...s,headers:y([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}}class Et extends v{constructor(){super(...arguments),this.files=new da(this._client),this.fileBatches=new ua(this._client)}create(e,n){return this._client.post("/vector_stores",{body:e,...n,headers:y([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}retrieve(e,n){return this._client.get(g`/vector_stores/${e}`,{...n,headers:y([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}update(e,n,s){return this._client.post(g`/vector_stores/${e}`,{body:n,...s,headers:y([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}list(e={},n){return this._client.getAPIList("/vector_stores",E,{query:e,...n,headers:y([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}delete(e,n){return this._client.delete(g`/vector_stores/${e}`,{...n,headers:y([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}search(e,n,s){return this._client.getAPIList(g`/vector_stores/${e}/search`,Ot,{body:n,method:"post",...s,headers:y([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}}Et.Files=da;Et.FileBatches=ua;class ha extends v{create(e,n){return this._client.post("/videos",is({body:e,...n},this._client))}retrieve(e,n){return this._client.get(g`/videos/${e}`,n)}list(e={},n){return this._client.getAPIList("/videos",mt,{query:e,...n})}delete(e,n){return this._client.delete(g`/videos/${e}`,n)}downloadContent(e,n={},s){return this._client.get(g`/videos/${e}/content`,{query:n,...s,headers:y([{Accept:"application/binary"},s?.headers]),__binaryResponse:!0})}remix(e,n,s){return this._client.post(g`/videos/${e}/remix`,is({body:n,...s},this._client))}}var be,fa,lt;class pa extends v{constructor(){super(...arguments),be.add(this)}async unwrap(e,n,s=this._client.webhookSecret,r=300){return await this.verifySignature(e,n,s,r),JSON.parse(e)}async verifySignature(e,n,s=this._client.webhookSecret,r=300){if(typeof crypto>"u"||typeof crypto.subtle.importKey!="function"||typeof crypto.subtle.verify!="function")throw new Error("Webhook signature verification is only supported when the `crypto` global is defined");u(this,be,"m",fa).call(this,s);const a=y([n]).values,i=u(this,be,"m",lt).call(this,a,"webhook-signature"),o=u(this,be,"m",lt).call(this,a,"webhook-timestamp"),c=u(this,be,"m",lt).call(this,a,"webhook-id"),l=parseInt(o,10);if(isNaN(l))throw new Oe("Invalid webhook timestamp format");const m=Math.floor(Date.now()/1e3);if(m-l>r)throw new Oe("Webhook timestamp is too old");if(l>m+r)throw new Oe("Webhook timestamp is too new");const h=i.split(" ").map(w=>w.startsWith("v1,")?w.substring(3):w),p=s.startsWith("whsec_")?Buffer.from(s.replace("whsec_",""),"base64"):Buffer.from(s,"utf-8"),d=c?`${c}.${o}.${e}`:`${o}.${e}`,b=await crypto.subtle.importKey("raw",p,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(const w of h)try{const R=Buffer.from(w,"base64");if(await crypto.subtle.verify("HMAC",b,R,new TextEncoder().encode(d)))return}catch{continue}throw new Oe("The given webhook signature does not match the expected signature")}}be=new WeakSet,fa=function(e){if(typeof e!="string"||e.length===0)throw new Error("The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET, on the client class, OpenAI({ webhookSecret: '123' }), or passed to this function")},lt=function(e,n){if(!e)throw new Error("Headers are required");const s=e.get(n);if(s==null)throw new Error(`Missing required header: ${n}`);return s};var ln,Pn,ct,ma;class A{constructor({baseURL:e=_e("OPENAI_BASE_URL"),apiKey:n=_e("OPENAI_API_KEY"),organization:s=_e("OPENAI_ORG_ID")??null,project:r=_e("OPENAI_PROJECT_ID")??null,webhookSecret:a=_e("OPENAI_WEBHOOK_SECRET")??null,...i}={}){if(ln.add(this),ct.set(this,void 0),this.completions=new Kr(this),this.chat=new wn(this),this.embeddings=new Hr(this),this.files=new Xr(this),this.images=new na(this),this.audio=new Je(this),this.moderations=new ra(this),this.models=new sa(this),this.fineTuning=new Ae(this),this.graders=new Tn(this),this.vectorStores=new Et(this),this.webhooks=new pa(this),this.beta=new Se(this),this.batches=new Lr(this),this.uploads=new Rn(this),this.responses=new Pt(this),this.realtime=new Rt(this),this.conversations=new kn(this),this.evals=new An(this),this.containers=new xn(this),this.videos=new ha(this),n===void 0)throw new x("Missing credentials. Please pass an `apiKey`, or set the `OPENAI_API_KEY` environment variable.");const o={apiKey:n,organization:s,project:r,webhookSecret:a,...i,baseURL:e||"https://api.openai.com/v1"};if(!o.dangerouslyAllowBrowser&&co())throw new x(`It looks like you're running in a browser-like environment.
|
|
21
|
+
${Ge(t)}`);return{...B,id:R,type:L,function:{...M,name:P,arguments:D}}})}}:{...d,message:{...f,content:b,role:_,refusal:l.refusal??null},finish_reason:m,index:h,logprobs:p}}),created:r,model:a,object:"chat.completion",...i?{system_fingerprint:i}:{}};return Va(c,e)}function Ge(t){return JSON.stringify(t)}class bt extends Fe{static fromReadableStream(e){const n=new bt(null);return n._run(()=>n._fromReadableStream(e)),n}static runTools(e,n,s){const r=new bt(n),a={...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"runTools"}};return r._run(()=>r._runTools(e,n,a)),r}}let yn=class extends v{constructor(){super(...arguments),this.messages=new pr(this._client)}create(e,n){return this._client.post("/chat/completions",{body:e,...n,stream:e.stream??!1})}retrieve(e,n){return this._client.get(g`/chat/completions/${e}`,n)}update(e,n,s){return this._client.post(g`/chat/completions/${e}`,{body:n,...s})}list(e={},n){return this._client.getAPIList("/chat/completions",E,{query:e,...n})}delete(e,n){return this._client.delete(g`/chat/completions/${e}`,n)}parse(e,n){return Ya(e.tools),this._client.chat.completions.create(e,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(s=>hn(s,e))}runTools(e,n){return e.stream?bt.runTools(this._client,e,n):gn.runTools(this._client,e,n)}stream(e,n){return Fe.createChatCompletion(this._client,e,n)}};yn.Messages=pr;class wn extends v{constructor(){super(...arguments),this.completions=new yn(this._client)}}wn.Completions=yn;const Er=Symbol("brand.privateNullableHeaders");function*Ho(t){if(!t)return;if(Er in t){const{values:s,nulls:r}=t;yield*s.entries();for(const a of r)yield[a,null];return}let e=!1,n;t instanceof Headers?n=t.entries():Hn(t)?n=t:(e=!0,n=Object.entries(t??{}));for(let s of n){const r=s[0];if(typeof r!="string")throw new TypeError("expected header name to be a string");const a=Hn(s[1])?s[1]:[s[1]];let i=!1;for(const o of a)o!==void 0&&(e&&!i&&(i=!0,yield[r,null]),yield[r,o])}}const y=t=>{const e=new Headers,n=new Set;for(const s of t){const r=new Set;for(const[a,i]of Ho(s)){const o=a.toLowerCase();r.has(o)||(e.delete(a),r.add(o)),i===null?(e.delete(a),n.add(o)):(e.append(a,i),n.delete(o))}}return{[Er]:!0,values:e,nulls:n}};class Mr extends v{create(e,n){return this._client.post("/audio/speech",{body:e,...n,headers:y([{Accept:"application/octet-stream"},n?.headers]),__binaryResponse:!0})}}class Nr extends v{create(e,n){return this._client.post("/audio/transcriptions",pe({body:e,...n,stream:e.stream??!1,__metadata:{model:e.model}},this._client))}}class jr extends v{create(e,n){return this._client.post("/audio/translations",pe({body:e,...n,__metadata:{model:e.model}},this._client))}}class Je extends v{constructor(){super(...arguments),this.transcriptions=new Nr(this._client),this.translations=new jr(this._client),this.speech=new Mr(this._client)}}Je.Transcriptions=Nr;Je.Translations=jr;Je.Speech=Mr;class Lr extends v{create(e,n){return this._client.post("/batches",{body:e,...n})}retrieve(e,n){return this._client.get(g`/batches/${e}`,n)}list(e={},n){return this._client.getAPIList("/batches",E,{query:e,...n})}cancel(e,n){return this._client.post(g`/batches/${e}/cancel`,n)}}class Dr extends v{create(e,n){return this._client.post("/assistants",{body:e,...n,headers:y([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}retrieve(e,n){return this._client.get(g`/assistants/${e}`,{...n,headers:y([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}update(e,n,s){return this._client.post(g`/assistants/${e}`,{body:n,...s,headers:y([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}list(e={},n){return this._client.getAPIList("/assistants",E,{query:e,...n,headers:y([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}delete(e,n){return this._client.delete(g`/assistants/${e}`,{...n,headers:y([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}}let Fr=class extends v{create(e,n){return this._client.post("/realtime/sessions",{body:e,...n,headers:y([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}};class Br extends v{create(e,n){return this._client.post("/realtime/transcription_sessions",{body:e,...n,headers:y([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}}let It=class extends v{constructor(){super(...arguments),this.sessions=new Fr(this._client),this.transcriptionSessions=new Br(this._client)}};It.Sessions=Fr;It.TranscriptionSessions=Br;class Ur extends v{create(e,n){return this._client.post("/chatkit/sessions",{body:e,...n,headers:y([{"OpenAI-Beta":"chatkit_beta=v1"},n?.headers])})}cancel(e,n){return this._client.post(g`/chatkit/sessions/${e}/cancel`,{...n,headers:y([{"OpenAI-Beta":"chatkit_beta=v1"},n?.headers])})}}let Wr=class extends v{retrieve(e,n){return this._client.get(g`/chatkit/threads/${e}`,{...n,headers:y([{"OpenAI-Beta":"chatkit_beta=v1"},n?.headers])})}list(e={},n){return this._client.getAPIList("/chatkit/threads",mt,{query:e,...n,headers:y([{"OpenAI-Beta":"chatkit_beta=v1"},n?.headers])})}delete(e,n){return this._client.delete(g`/chatkit/threads/${e}`,{...n,headers:y([{"OpenAI-Beta":"chatkit_beta=v1"},n?.headers])})}listItems(e,n={},s){return this._client.getAPIList(g`/chatkit/threads/${e}/items`,mt,{query:n,...s,headers:y([{"OpenAI-Beta":"chatkit_beta=v1"},s?.headers])})}};class Tt extends v{constructor(){super(...arguments),this.sessions=new Ur(this._client),this.threads=new Wr(this._client)}}Tt.Sessions=Ur;Tt.Threads=Wr;class qr extends v{create(e,n,s){return this._client.post(g`/threads/${e}/messages`,{body:n,...s,headers:y([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}retrieve(e,n,s){const{thread_id:r}=n;return this._client.get(g`/threads/${r}/messages/${e}`,{...s,headers:y([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}update(e,n,s){const{thread_id:r,...a}=n;return this._client.post(g`/threads/${r}/messages/${e}`,{body:a,...s,headers:y([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}list(e,n={},s){return this._client.getAPIList(g`/threads/${e}/messages`,E,{query:n,...s,headers:y([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}delete(e,n,s){const{thread_id:r}=n;return this._client.delete(g`/threads/${r}/messages/${e}`,{...s,headers:y([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}}class Jr extends v{retrieve(e,n,s){const{thread_id:r,run_id:a,...i}=n;return this._client.get(g`/threads/${r}/runs/${a}/steps/${e}`,{query:i,...s,headers:y([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}list(e,n,s){const{thread_id:r,...a}=n;return this._client.getAPIList(g`/threads/${r}/runs/${e}/steps`,E,{query:a,...s,headers:y([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}}const Vo=t=>{if(typeof Buffer<"u"){const e=Buffer.from(t,"base64");return Array.from(new Float32Array(e.buffer,e.byteOffset,e.length/Float32Array.BYTES_PER_ELEMENT))}else{const e=atob(t),n=e.length,s=new Uint8Array(n);for(let r=0;r<n;r++)s[r]=e.charCodeAt(r);return Array.from(new Float32Array(s.buffer))}};var Xo={};const _e=t=>{if(typeof globalThis.process<"u")return Xo?.[t]?.trim()??void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(t)?.trim()};var W,he,on,te,at,Y,fe,ve,de,vt,V,it,ot,Le,Me,Ne,ds,hs,fs,ps,ms,_s,gs;class De extends _n{constructor(){super(...arguments),W.add(this),on.set(this,[]),te.set(this,{}),at.set(this,{}),Y.set(this,void 0),fe.set(this,void 0),ve.set(this,void 0),de.set(this,void 0),vt.set(this,void 0),V.set(this,void 0),it.set(this,void 0),ot.set(this,void 0),Le.set(this,void 0)}[(on=new WeakMap,te=new WeakMap,at=new WeakMap,Y=new WeakMap,fe=new WeakMap,ve=new WeakMap,de=new WeakMap,vt=new WeakMap,V=new WeakMap,it=new WeakMap,ot=new WeakMap,Le=new WeakMap,W=new WeakSet,Symbol.asyncIterator)](){const e=[],n=[];let s=!1;return this.on("event",r=>{const a=n.shift();a?a.resolve(r):e.push(r)}),this.on("end",()=>{s=!0;for(const r of n)r.resolve(void 0);n.length=0}),this.on("abort",r=>{s=!0;for(const a of n)a.reject(r);n.length=0}),this.on("error",r=>{s=!0;for(const a of n)a.reject(r);n.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:s?{value:void 0,done:!0}:new Promise((a,i)=>n.push({resolve:a,reject:i})).then(a=>a?{value:a,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){const n=new he;return n._run(()=>n._fromReadableStream(e)),n}async _fromReadableStream(e,n){const s=n?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),this._connected();const r=ne.fromReadableStream(e,this.controller);for await(const a of r)u(this,W,"m",Me).call(this,a);if(r.controller.signal?.aborted)throw new X;return this._addRun(u(this,W,"m",Ne).call(this))}toReadableStream(){return new ne(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,n,s,r){const a=new he;return a._run(()=>a._runToolAssistantStream(e,n,s,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),a}async _createToolAssistantStream(e,n,s,r){const a=r?.signal;a&&(a.aborted&&this.controller.abort(),a.addEventListener("abort",()=>this.controller.abort()));const i={...s,stream:!0},o=await e.submitToolOutputs(n,i,{...r,signal:this.controller.signal});this._connected();for await(const c of o)u(this,W,"m",Me).call(this,c);if(o.controller.signal?.aborted)throw new X;return this._addRun(u(this,W,"m",Ne).call(this))}static createThreadAssistantStream(e,n,s){const r=new he;return r._run(()=>r._threadAssistantStream(e,n,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),r}static createAssistantStream(e,n,s,r){const a=new he;return a._run(()=>a._runAssistantStream(e,n,s,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),a}currentEvent(){return u(this,it,"f")}currentRun(){return u(this,ot,"f")}currentMessageSnapshot(){return u(this,Y,"f")}currentRunStepSnapshot(){return u(this,Le,"f")}async finalRunSteps(){return await this.done(),Object.values(u(this,te,"f"))}async finalMessages(){return await this.done(),Object.values(u(this,at,"f"))}async finalRun(){if(await this.done(),!u(this,fe,"f"))throw Error("Final run was not received.");return u(this,fe,"f")}async _createThreadAssistantStream(e,n,s){const r=s?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort()));const a={...n,stream:!0},i=await e.createAndRun(a,{...s,signal:this.controller.signal});this._connected();for await(const o of i)u(this,W,"m",Me).call(this,o);if(i.controller.signal?.aborted)throw new X;return this._addRun(u(this,W,"m",Ne).call(this))}async _createAssistantStream(e,n,s,r){const a=r?.signal;a&&(a.aborted&&this.controller.abort(),a.addEventListener("abort",()=>this.controller.abort()));const i={...s,stream:!0},o=await e.create(n,i,{...r,signal:this.controller.signal});this._connected();for await(const c of o)u(this,W,"m",Me).call(this,c);if(o.controller.signal?.aborted)throw new X;return this._addRun(u(this,W,"m",Ne).call(this))}static accumulateDelta(e,n){for(const[s,r]of Object.entries(n)){if(!e.hasOwnProperty(s)){e[s]=r;continue}let a=e[s];if(a==null){e[s]=r;continue}if(s==="index"||s==="type"){e[s]=r;continue}if(typeof a=="string"&&typeof r=="string")a+=r;else if(typeof a=="number"&&typeof r=="number")a+=r;else if(jt(a)&&jt(r))a=this.accumulateDelta(a,r);else if(Array.isArray(a)&&Array.isArray(r)){if(a.every(i=>typeof i=="string"||typeof i=="number")){a.push(...r);continue}for(const i of r){if(!jt(i))throw new Error(`Expected array delta entry to be an object but got: ${i}`);const o=i.index;if(o==null)throw console.error(i),new Error("Expected array delta entry to have an `index` property");if(typeof o!="number")throw new Error(`Expected array delta entry \`index\` property to be a number but got ${o}`);const c=a[o];c==null?a.push(i):a[o]=this.accumulateDelta(c,i)}continue}else throw Error(`Unhandled record type: ${s}, deltaValue: ${r}, accValue: ${a}`);e[s]=a}return e}_addRun(e){return e}async _threadAssistantStream(e,n,s){return await this._createThreadAssistantStream(n,e,s)}async _runAssistantStream(e,n,s,r){return await this._createAssistantStream(n,e,s,r)}async _runToolAssistantStream(e,n,s,r){return await this._createToolAssistantStream(n,e,s,r)}}he=De,Me=function(e){if(!this.ended)switch(k(this,it,e),u(this,W,"m",fs).call(this,e),e.event){case"thread.created":break;case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":case"thread.run.requires_action":case"thread.run.completed":case"thread.run.incomplete":case"thread.run.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":u(this,W,"m",gs).call(this,e);break;case"thread.run.step.created":case"thread.run.step.in_progress":case"thread.run.step.delta":case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":u(this,W,"m",hs).call(this,e);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":u(this,W,"m",ds).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier")}},Ne=function(){if(this.ended)throw new x("stream has ended, this shouldn't happen");if(!u(this,fe,"f"))throw Error("Final run has not been received");return u(this,fe,"f")},ds=function(e){const[n,s]=u(this,W,"m",ms).call(this,e,u(this,Y,"f"));k(this,Y,n),u(this,at,"f")[n.id]=n;for(const r of s){const a=n.content[r.index];a?.type=="text"&&this._emit("textCreated",a.text)}switch(e.event){case"thread.message.created":this._emit("messageCreated",e.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",e.data.delta,n),e.data.delta.content)for(const r of e.data.delta.content){if(r.type=="text"&&r.text){let a=r.text,i=n.content[r.index];if(i&&i.type=="text")this._emit("textDelta",a,i.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(r.index!=u(this,ve,"f")){if(u(this,de,"f"))switch(u(this,de,"f").type){case"text":this._emit("textDone",u(this,de,"f").text,u(this,Y,"f"));break;case"image_file":this._emit("imageFileDone",u(this,de,"f").image_file,u(this,Y,"f"));break}k(this,ve,r.index)}k(this,de,n.content[r.index])}break;case"thread.message.completed":case"thread.message.incomplete":if(u(this,ve,"f")!==void 0){const r=e.data.content[u(this,ve,"f")];if(r)switch(r.type){case"image_file":this._emit("imageFileDone",r.image_file,u(this,Y,"f"));break;case"text":this._emit("textDone",r.text,u(this,Y,"f"));break}}u(this,Y,"f")&&this._emit("messageDone",e.data),k(this,Y,void 0)}},hs=function(e){const n=u(this,W,"m",ps).call(this,e);switch(k(this,Le,n),e.event){case"thread.run.step.created":this._emit("runStepCreated",e.data);break;case"thread.run.step.delta":const s=e.data.delta;if(s.step_details&&s.step_details.type=="tool_calls"&&s.step_details.tool_calls&&n.step_details.type=="tool_calls")for(const a of s.step_details.tool_calls)a.index==u(this,vt,"f")?this._emit("toolCallDelta",a,n.step_details.tool_calls[a.index]):(u(this,V,"f")&&this._emit("toolCallDone",u(this,V,"f")),k(this,vt,a.index),k(this,V,n.step_details.tool_calls[a.index]),u(this,V,"f")&&this._emit("toolCallCreated",u(this,V,"f")));this._emit("runStepDelta",e.data.delta,n);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":k(this,Le,void 0),e.data.step_details.type=="tool_calls"&&u(this,V,"f")&&(this._emit("toolCallDone",u(this,V,"f")),k(this,V,void 0)),this._emit("runStepDone",e.data,n);break}},fs=function(e){u(this,on,"f").push(e),this._emit("event",e)},ps=function(e){switch(e.event){case"thread.run.step.created":return u(this,te,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let n=u(this,te,"f")[e.data.id];if(!n)throw Error("Received a RunStepDelta before creation of a snapshot");let s=e.data;if(s.delta){const r=he.accumulateDelta(n,s.delta);u(this,te,"f")[e.data.id]=r}return u(this,te,"f")[e.data.id];case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":case"thread.run.step.in_progress":u(this,te,"f")[e.data.id]=e.data;break}if(u(this,te,"f")[e.data.id])return u(this,te,"f")[e.data.id];throw new Error("No snapshot available")},ms=function(e,n){let s=[];switch(e.event){case"thread.message.created":return[e.data,s];case"thread.message.delta":if(!n)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let r=e.data;if(r.delta.content)for(const a of r.delta.content)if(a.index in n.content){let i=n.content[a.index];n.content[a.index]=u(this,W,"m",_s).call(this,a,i)}else n.content[a.index]=a,s.push(a);return[n,s];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(n)return[n,s];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},_s=function(e,n){return he.accumulateDelta(n,e)},gs=function(e){switch(k(this,ot,e.data),e.event){case"thread.run.created":break;case"thread.run.queued":break;case"thread.run.in_progress":break;case"thread.run.requires_action":case"thread.run.cancelled":case"thread.run.failed":case"thread.run.completed":case"thread.run.expired":case"thread.run.incomplete":k(this,fe,e.data),u(this,V,"f")&&(this._emit("toolCallDone",u(this,V,"f")),k(this,V,void 0));break}};let bn=class extends v{constructor(){super(...arguments),this.steps=new Jr(this._client)}create(e,n,s){const{include:r,...a}=n;return this._client.post(g`/threads/${e}/runs`,{query:{include:r},body:a,...s,headers:y([{"OpenAI-Beta":"assistants=v2"},s?.headers]),stream:n.stream??!1})}retrieve(e,n,s){const{thread_id:r}=n;return this._client.get(g`/threads/${r}/runs/${e}`,{...s,headers:y([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}update(e,n,s){const{thread_id:r,...a}=n;return this._client.post(g`/threads/${r}/runs/${e}`,{body:a,...s,headers:y([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}list(e,n={},s){return this._client.getAPIList(g`/threads/${e}/runs`,E,{query:n,...s,headers:y([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}cancel(e,n,s){const{thread_id:r}=n;return this._client.post(g`/threads/${r}/runs/${e}/cancel`,{...s,headers:y([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}async createAndPoll(e,n,s){const r=await this.create(e,n,s);return await this.poll(r.id,{thread_id:e},s)}createAndStream(e,n,s){return De.createAssistantStream(e,this._client.beta.threads.runs,n,s)}async poll(e,n,s){const r=y([s?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":s?.pollIntervalMs?.toString()??void 0}]);for(;;){const{data:a,response:i}=await this.retrieve(e,n,{...s,headers:{...s?.headers,...r}}).withResponse();switch(a.status){case"queued":case"in_progress":case"cancelling":let o=5e3;if(s?.pollIntervalMs)o=s.pollIntervalMs;else{const c=i.headers.get("openai-poll-after-ms");if(c){const l=parseInt(c);isNaN(l)||(o=l)}}await qe(o);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return a}}}stream(e,n,s){return De.createAssistantStream(e,this._client.beta.threads.runs,n,s)}submitToolOutputs(e,n,s){const{thread_id:r,...a}=n;return this._client.post(g`/threads/${r}/runs/${e}/submit_tool_outputs`,{body:a,...s,headers:y([{"OpenAI-Beta":"assistants=v2"},s?.headers]),stream:n.stream??!1})}async submitToolOutputsAndPoll(e,n,s){const r=await this.submitToolOutputs(e,n,s);return await this.poll(r.id,n,s)}submitToolOutputsStream(e,n,s){return De.createToolAssistantStream(e,this._client.beta.threads.runs,n,s)}};bn.Steps=Jr;class Rt extends v{constructor(){super(...arguments),this.runs=new bn(this._client),this.messages=new qr(this._client)}create(e={},n){return this._client.post("/threads",{body:e,...n,headers:y([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}retrieve(e,n){return this._client.get(g`/threads/${e}`,{...n,headers:y([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}update(e,n,s){return this._client.post(g`/threads/${e}`,{body:n,...s,headers:y([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}delete(e,n){return this._client.delete(g`/threads/${e}`,{...n,headers:y([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}createAndRun(e,n){return this._client.post("/threads/runs",{body:e,...n,headers:y([{"OpenAI-Beta":"assistants=v2"},n?.headers]),stream:e.stream??!1})}async createAndRunPoll(e,n){const s=await this.createAndRun(e,n);return await this.runs.poll(s.id,{thread_id:s.thread_id},n)}createAndRunStream(e,n){return De.createThreadAssistantStream(e,this._client.beta.threads,n)}}Rt.Runs=bn;Rt.Messages=qr;class Se extends v{constructor(){super(...arguments),this.realtime=new It(this._client),this.chatkit=new Tt(this._client),this.assistants=new Dr(this._client),this.threads=new Rt(this._client)}}Se.Realtime=It;Se.ChatKit=Tt;Se.Assistants=Dr;Se.Threads=Rt;class Kr extends v{create(e,n){return this._client.post("/completions",{body:e,...n,stream:e.stream??!1})}}class Zr extends v{retrieve(e,n,s){const{container_id:r}=n;return this._client.get(g`/containers/${r}/files/${e}/content`,{...s,headers:y([{Accept:"application/binary"},s?.headers]),__binaryResponse:!0})}}let vn=class extends v{constructor(){super(...arguments),this.content=new Zr(this._client)}create(e,n,s){return this._client.post(g`/containers/${e}/files`,pe({body:n,...s},this._client))}retrieve(e,n,s){const{container_id:r}=n;return this._client.get(g`/containers/${r}/files/${e}`,s)}list(e,n={},s){return this._client.getAPIList(g`/containers/${e}/files`,E,{query:n,...s})}delete(e,n,s){const{container_id:r}=n;return this._client.delete(g`/containers/${r}/files/${e}`,{...s,headers:y([{Accept:"*/*"},s?.headers])})}};vn.Content=Zr;class xn extends v{constructor(){super(...arguments),this.files=new vn(this._client)}create(e,n){return this._client.post("/containers",{body:e,...n})}retrieve(e,n){return this._client.get(g`/containers/${e}`,n)}list(e={},n){return this._client.getAPIList("/containers",E,{query:e,...n})}delete(e,n){return this._client.delete(g`/containers/${e}`,{...n,headers:y([{Accept:"*/*"},n?.headers])})}}xn.Files=vn;class zr extends v{create(e,n,s){const{include:r,...a}=n;return this._client.post(g`/conversations/${e}/items`,{query:{include:r},body:a,...s})}retrieve(e,n,s){const{conversation_id:r,...a}=n;return this._client.get(g`/conversations/${r}/items/${e}`,{query:a,...s})}list(e,n={},s){return this._client.getAPIList(g`/conversations/${e}/items`,mt,{query:n,...s})}delete(e,n,s){const{conversation_id:r}=n;return this._client.delete(g`/conversations/${r}/items/${e}`,s)}}class kn extends v{constructor(){super(...arguments),this.items=new zr(this._client)}create(e={},n){return this._client.post("/conversations",{body:e,...n})}retrieve(e,n){return this._client.get(g`/conversations/${e}`,n)}update(e,n,s){return this._client.post(g`/conversations/${e}`,{body:n,...s})}delete(e,n){return this._client.delete(g`/conversations/${e}`,n)}}kn.Items=zr;class Hr extends v{create(e,n){const s=!!e.encoding_format;let r=s?e.encoding_format:"base64";s&&U(this._client).debug("embeddings/user defined encoding_format:",e.encoding_format);const a=this._client.post("/embeddings",{body:{...e,encoding_format:r},...n});return s?a:(U(this._client).debug("embeddings/decoding base64 embeddings from base64"),a._thenUnwrap(i=>(i&&i.data&&i.data.forEach(o=>{const c=o.embedding;o.embedding=Vo(c)}),i)))}}class Vr extends v{retrieve(e,n,s){const{eval_id:r,run_id:a}=n;return this._client.get(g`/evals/${r}/runs/${a}/output_items/${e}`,s)}list(e,n,s){const{eval_id:r,...a}=n;return this._client.getAPIList(g`/evals/${r}/runs/${e}/output_items`,E,{query:a,...s})}}class Sn extends v{constructor(){super(...arguments),this.outputItems=new Vr(this._client)}create(e,n,s){return this._client.post(g`/evals/${e}/runs`,{body:n,...s})}retrieve(e,n,s){const{eval_id:r}=n;return this._client.get(g`/evals/${r}/runs/${e}`,s)}list(e,n={},s){return this._client.getAPIList(g`/evals/${e}/runs`,E,{query:n,...s})}delete(e,n,s){const{eval_id:r}=n;return this._client.delete(g`/evals/${r}/runs/${e}`,s)}cancel(e,n,s){const{eval_id:r}=n;return this._client.post(g`/evals/${r}/runs/${e}`,s)}}Sn.OutputItems=Vr;class An extends v{constructor(){super(...arguments),this.runs=new Sn(this._client)}create(e,n){return this._client.post("/evals",{body:e,...n})}retrieve(e,n){return this._client.get(g`/evals/${e}`,n)}update(e,n,s){return this._client.post(g`/evals/${e}`,{body:n,...s})}list(e={},n){return this._client.getAPIList("/evals",E,{query:e,...n})}delete(e,n){return this._client.delete(g`/evals/${e}`,n)}}An.Runs=Sn;let Xr=class extends v{create(e,n){return this._client.post("/files",pe({body:e,...n},this._client))}retrieve(e,n){return this._client.get(g`/files/${e}`,n)}list(e={},n){return this._client.getAPIList("/files",E,{query:e,...n})}delete(e,n){return this._client.delete(g`/files/${e}`,n)}content(e,n){return this._client.get(g`/files/${e}/content`,{...n,headers:y([{Accept:"application/binary"},n?.headers]),__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:n=5e3,maxWait:s=1800*1e3}={}){const r=new Set(["processed","error","deleted"]),a=Date.now();let i=await this.retrieve(e);for(;!i.status||!r.has(i.status);)if(await qe(n),i=await this.retrieve(e),Date.now()-a>s)throw new St({message:`Giving up on waiting for file ${e} to finish processing after ${s} milliseconds.`});return i}};class Gr extends v{}let Qr=class extends v{run(e,n){return this._client.post("/fine_tuning/alpha/graders/run",{body:e,...n})}validate(e,n){return this._client.post("/fine_tuning/alpha/graders/validate",{body:e,...n})}};class Cn extends v{constructor(){super(...arguments),this.graders=new Qr(this._client)}}Cn.Graders=Qr;class Yr extends v{create(e,n,s){return this._client.getAPIList(g`/fine_tuning/checkpoints/${e}/permissions`,Ot,{body:n,method:"post",...s})}retrieve(e,n={},s){return this._client.get(g`/fine_tuning/checkpoints/${e}/permissions`,{query:n,...s})}delete(e,n,s){const{fine_tuned_model_checkpoint:r}=n;return this._client.delete(g`/fine_tuning/checkpoints/${r}/permissions/${e}`,s)}}let On=class extends v{constructor(){super(...arguments),this.permissions=new Yr(this._client)}};On.Permissions=Yr;class ea extends v{list(e,n={},s){return this._client.getAPIList(g`/fine_tuning/jobs/${e}/checkpoints`,E,{query:n,...s})}}class In extends v{constructor(){super(...arguments),this.checkpoints=new ea(this._client)}create(e,n){return this._client.post("/fine_tuning/jobs",{body:e,...n})}retrieve(e,n){return this._client.get(g`/fine_tuning/jobs/${e}`,n)}list(e={},n){return this._client.getAPIList("/fine_tuning/jobs",E,{query:e,...n})}cancel(e,n){return this._client.post(g`/fine_tuning/jobs/${e}/cancel`,n)}listEvents(e,n={},s){return this._client.getAPIList(g`/fine_tuning/jobs/${e}/events`,E,{query:n,...s})}pause(e,n){return this._client.post(g`/fine_tuning/jobs/${e}/pause`,n)}resume(e,n){return this._client.post(g`/fine_tuning/jobs/${e}/resume`,n)}}In.Checkpoints=ea;class Ae extends v{constructor(){super(...arguments),this.methods=new Gr(this._client),this.jobs=new In(this._client),this.checkpoints=new On(this._client),this.alpha=new Cn(this._client)}}Ae.Methods=Gr;Ae.Jobs=In;Ae.Checkpoints=On;Ae.Alpha=Cn;class ta extends v{}class Tn extends v{constructor(){super(...arguments),this.graderModels=new ta(this._client)}}Tn.GraderModels=ta;class na extends v{createVariation(e,n){return this._client.post("/images/variations",pe({body:e,...n},this._client))}edit(e,n){return this._client.post("/images/edits",pe({body:e,...n,stream:e.stream??!1},this._client))}generate(e,n){return this._client.post("/images/generations",{body:e,...n,stream:e.stream??!1})}}class sa extends v{retrieve(e,n){return this._client.get(g`/models/${e}`,n)}list(e){return this._client.getAPIList("/models",Ot,e)}delete(e,n){return this._client.delete(g`/models/${e}`,n)}}class ra extends v{create(e,n){return this._client.post("/moderations",{body:e,...n})}}class aa extends v{accept(e,n,s){return this._client.post(g`/realtime/calls/${e}/accept`,{body:n,...s,headers:y([{Accept:"*/*"},s?.headers])})}hangup(e,n){return this._client.post(g`/realtime/calls/${e}/hangup`,{...n,headers:y([{Accept:"*/*"},n?.headers])})}refer(e,n,s){return this._client.post(g`/realtime/calls/${e}/refer`,{body:n,...s,headers:y([{Accept:"*/*"},s?.headers])})}reject(e,n={},s){return this._client.post(g`/realtime/calls/${e}/reject`,{body:n,...s,headers:y([{Accept:"*/*"},s?.headers])})}}class ia extends v{create(e,n){return this._client.post("/realtime/client_secrets",{body:e,...n})}}class $t extends v{constructor(){super(...arguments),this.clientSecrets=new ia(this._client),this.calls=new aa(this._client)}}$t.ClientSecrets=ia;$t.Calls=aa;var ge,Qe,oe,Ye,ys,ws,bs,vs;class Rn extends _n{constructor(e){super(),ge.add(this),Qe.set(this,void 0),oe.set(this,void 0),Ye.set(this,void 0),k(this,Qe,e)}static createResponse(e,n,s){const r=new Rn(n);return r._run(()=>r._createOrRetrieveResponse(e,n,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),r}async _createOrRetrieveResponse(e,n,s){const r=s?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),u(this,ge,"m",ys).call(this);let a,i=null;"response_id"in n?(a=await e.responses.retrieve(n.response_id,{stream:!0},{...s,signal:this.controller.signal,stream:!0}),i=n.starting_after??null):a=await e.responses.create({...n,stream:!0},{...s,signal:this.controller.signal}),this._connected();for await(const o of a)u(this,ge,"m",ws).call(this,o,i);if(a.controller.signal?.aborted)throw new X;return u(this,ge,"m",bs).call(this)}[(Qe=new WeakMap,oe=new WeakMap,Ye=new WeakMap,ge=new WeakSet,ys=function(){this.ended||k(this,oe,void 0)},ws=function(n,s){if(this.ended)return;const r=(i,o)=>{(s==null||o.sequence_number>s)&&this._emit(i,o)},a=u(this,ge,"m",vs).call(this,n);switch(r("event",n),n.type){case"response.output_text.delta":{const i=a.output[n.output_index];if(!i)throw new x(`missing output at index ${n.output_index}`);if(i.type==="message"){const o=i.content[n.content_index];if(!o)throw new x(`missing content at index ${n.content_index}`);if(o.type!=="output_text")throw new x(`expected content to be 'output_text', got ${o.type}`);r("response.output_text.delta",{...n,snapshot:o.text})}break}case"response.function_call_arguments.delta":{const i=a.output[n.output_index];if(!i)throw new x(`missing output at index ${n.output_index}`);i.type==="function_call"&&r("response.function_call_arguments.delta",{...n,snapshot:i.arguments});break}default:r(n.type,n);break}},bs=function(){if(this.ended)throw new x("stream has ended, this shouldn't happen");const n=u(this,oe,"f");if(!n)throw new x("request ended without sending any events");k(this,oe,void 0);const s=Go(n,u(this,Qe,"f"));return k(this,Ye,s),s},vs=function(n){let s=u(this,oe,"f");if(!s){if(n.type!=="response.created")throw new x(`When snapshot hasn't been set yet, expected 'response.created' event, got ${n.type}`);return s=k(this,oe,n.response),s}switch(n.type){case"response.output_item.added":{s.output.push(n.item);break}case"response.content_part.added":{const r=s.output[n.output_index];if(!r)throw new x(`missing output at index ${n.output_index}`);const a=r.type,i=n.part;a==="message"&&i.type!=="reasoning_text"?r.content.push(i):a==="reasoning"&&i.type==="reasoning_text"&&(r.content||(r.content=[]),r.content.push(i));break}case"response.output_text.delta":{const r=s.output[n.output_index];if(!r)throw new x(`missing output at index ${n.output_index}`);if(r.type==="message"){const a=r.content[n.content_index];if(!a)throw new x(`missing content at index ${n.content_index}`);if(a.type!=="output_text")throw new x(`expected content to be 'output_text', got ${a.type}`);a.text+=n.delta}break}case"response.function_call_arguments.delta":{const r=s.output[n.output_index];if(!r)throw new x(`missing output at index ${n.output_index}`);r.type==="function_call"&&(r.arguments+=n.delta);break}case"response.reasoning_text.delta":{const r=s.output[n.output_index];if(!r)throw new x(`missing output at index ${n.output_index}`);if(r.type==="reasoning"){const a=r.content?.[n.content_index];if(!a)throw new x(`missing content at index ${n.content_index}`);if(a.type!=="reasoning_text")throw new x(`expected content to be 'reasoning_text', got ${a.type}`);a.text+=n.delta}break}case"response.completed":{k(this,oe,n.response);break}}return s},Symbol.asyncIterator)](){const e=[],n=[];let s=!1;return this.on("event",r=>{const a=n.shift();a?a.resolve(r):e.push(r)}),this.on("end",()=>{s=!0;for(const r of n)r.resolve(void 0);n.length=0}),this.on("abort",r=>{s=!0;for(const a of n)a.reject(r);n.length=0}),this.on("error",r=>{s=!0;for(const a of n)a.reject(r);n.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:s?{value:void 0,done:!0}:new Promise((a,i)=>n.push({resolve:a,reject:i})).then(a=>a?{value:a,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();const e=u(this,Ye,"f");if(!e)throw new x("stream ended without producing a ChatCompletion");return e}}function Go(t,e){return Bi(t,e)}class oa extends v{list(e,n={},s){return this._client.getAPIList(g`/responses/${e}/input_items`,E,{query:n,...s})}}class la extends v{count(e={},n){return this._client.post("/responses/input_tokens",{body:e,...n})}}class Pt extends v{constructor(){super(...arguments),this.inputItems=new oa(this._client),this.inputTokens=new la(this._client)}create(e,n){return this._client.post("/responses",{body:e,...n,stream:e.stream??!1})._thenUnwrap(s=>("object"in s&&s.object==="response"&&Vt(s),s))}retrieve(e,n={},s){return this._client.get(g`/responses/${e}`,{query:n,...s,stream:n?.stream??!1})._thenUnwrap(r=>("object"in r&&r.object==="response"&&Vt(r),r))}delete(e,n){return this._client.delete(g`/responses/${e}`,{...n,headers:y([{Accept:"*/*"},n?.headers])})}parse(e,n){return this._client.responses.create(e,n)._thenUnwrap(s=>Xs(s,e))}stream(e,n){return Rn.createResponse(this._client,e,n)}cancel(e,n){return this._client.post(g`/responses/${e}/cancel`,n)}}Pt.InputItems=oa;Pt.InputTokens=la;class ca extends v{create(e,n,s){return this._client.post(g`/uploads/${e}/parts`,pe({body:n,...s},this._client))}}class $n extends v{constructor(){super(...arguments),this.parts=new ca(this._client)}create(e,n){return this._client.post("/uploads",{body:e,...n})}cancel(e,n){return this._client.post(g`/uploads/${e}/cancel`,n)}complete(e,n,s){return this._client.post(g`/uploads/${e}/complete`,{body:n,...s})}}$n.Parts=ca;const Qo=async t=>{const e=await Promise.allSettled(t),n=e.filter(r=>r.status==="rejected");if(n.length){for(const r of n)console.error(r.reason);throw new Error(`${n.length} promise(s) failed - see the above errors`)}const s=[];for(const r of e)r.status==="fulfilled"&&s.push(r.value);return s};class ua extends v{create(e,n,s){return this._client.post(g`/vector_stores/${e}/file_batches`,{body:n,...s,headers:y([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}retrieve(e,n,s){const{vector_store_id:r}=n;return this._client.get(g`/vector_stores/${r}/file_batches/${e}`,{...s,headers:y([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}cancel(e,n,s){const{vector_store_id:r}=n;return this._client.post(g`/vector_stores/${r}/file_batches/${e}/cancel`,{...s,headers:y([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}async createAndPoll(e,n,s){const r=await this.create(e,n);return await this.poll(e,r.id,s)}listFiles(e,n,s){const{vector_store_id:r,...a}=n;return this._client.getAPIList(g`/vector_stores/${r}/file_batches/${e}/files`,E,{query:a,...s,headers:y([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}async poll(e,n,s){const r=y([s?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":s?.pollIntervalMs?.toString()??void 0}]);for(;;){const{data:a,response:i}=await this.retrieve(n,{vector_store_id:e},{...s,headers:r}).withResponse();switch(a.status){case"in_progress":let o=5e3;if(s?.pollIntervalMs)o=s.pollIntervalMs;else{const c=i.headers.get("openai-poll-after-ms");if(c){const l=parseInt(c);isNaN(l)||(o=l)}}await qe(o);break;case"failed":case"cancelled":case"completed":return a}}}async uploadAndPoll(e,{files:n,fileIds:s=[]},r){if(n==null||n.length==0)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");const a=r?.maxConcurrency??5,i=Math.min(a,n.length),o=this._client,c=n.values(),l=[...s];async function m(p){for(let d of p){const b=await o.files.create({file:d,purpose:"assistants"},r);l.push(b.id)}}const h=Array(i).fill(c).map(m);return await Qo(h),await this.createAndPoll(e,{file_ids:l})}}class da extends v{create(e,n,s){return this._client.post(g`/vector_stores/${e}/files`,{body:n,...s,headers:y([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}retrieve(e,n,s){const{vector_store_id:r}=n;return this._client.get(g`/vector_stores/${r}/files/${e}`,{...s,headers:y([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}update(e,n,s){const{vector_store_id:r,...a}=n;return this._client.post(g`/vector_stores/${r}/files/${e}`,{body:a,...s,headers:y([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}list(e,n={},s){return this._client.getAPIList(g`/vector_stores/${e}/files`,E,{query:n,...s,headers:y([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}delete(e,n,s){const{vector_store_id:r}=n;return this._client.delete(g`/vector_stores/${r}/files/${e}`,{...s,headers:y([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}async createAndPoll(e,n,s){const r=await this.create(e,n,s);return await this.poll(e,r.id,s)}async poll(e,n,s){const r=y([s?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":s?.pollIntervalMs?.toString()??void 0}]);for(;;){const a=await this.retrieve(n,{vector_store_id:e},{...s,headers:r}).withResponse(),i=a.data;switch(i.status){case"in_progress":let o=5e3;if(s?.pollIntervalMs)o=s.pollIntervalMs;else{const c=a.response.headers.get("openai-poll-after-ms");if(c){const l=parseInt(c);isNaN(l)||(o=l)}}await qe(o);break;case"failed":case"completed":return i}}}async upload(e,n,s){const r=await this._client.files.create({file:n,purpose:"assistants"},s);return this.create(e,{file_id:r.id},s)}async uploadAndPoll(e,n,s){const r=await this.upload(e,n,s);return await this.poll(e,r.id,s)}content(e,n,s){const{vector_store_id:r}=n;return this._client.getAPIList(g`/vector_stores/${r}/files/${e}/content`,Ot,{...s,headers:y([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}}class Et extends v{constructor(){super(...arguments),this.files=new da(this._client),this.fileBatches=new ua(this._client)}create(e,n){return this._client.post("/vector_stores",{body:e,...n,headers:y([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}retrieve(e,n){return this._client.get(g`/vector_stores/${e}`,{...n,headers:y([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}update(e,n,s){return this._client.post(g`/vector_stores/${e}`,{body:n,...s,headers:y([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}list(e={},n){return this._client.getAPIList("/vector_stores",E,{query:e,...n,headers:y([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}delete(e,n){return this._client.delete(g`/vector_stores/${e}`,{...n,headers:y([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}search(e,n,s){return this._client.getAPIList(g`/vector_stores/${e}/search`,Ot,{body:n,method:"post",...s,headers:y([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}}Et.Files=da;Et.FileBatches=ua;class ha extends v{create(e,n){return this._client.post("/videos",is({body:e,...n},this._client))}retrieve(e,n){return this._client.get(g`/videos/${e}`,n)}list(e={},n){return this._client.getAPIList("/videos",mt,{query:e,...n})}delete(e,n){return this._client.delete(g`/videos/${e}`,n)}downloadContent(e,n={},s){return this._client.get(g`/videos/${e}/content`,{query:n,...s,headers:y([{Accept:"application/binary"},s?.headers]),__binaryResponse:!0})}remix(e,n,s){return this._client.post(g`/videos/${e}/remix`,is({body:n,...s},this._client))}}var be,fa,lt;class pa extends v{constructor(){super(...arguments),be.add(this)}async unwrap(e,n,s=this._client.webhookSecret,r=300){return await this.verifySignature(e,n,s,r),JSON.parse(e)}async verifySignature(e,n,s=this._client.webhookSecret,r=300){if(typeof crypto>"u"||typeof crypto.subtle.importKey!="function"||typeof crypto.subtle.verify!="function")throw new Error("Webhook signature verification is only supported when the `crypto` global is defined");u(this,be,"m",fa).call(this,s);const a=y([n]).values,i=u(this,be,"m",lt).call(this,a,"webhook-signature"),o=u(this,be,"m",lt).call(this,a,"webhook-timestamp"),c=u(this,be,"m",lt).call(this,a,"webhook-id"),l=parseInt(o,10);if(isNaN(l))throw new Oe("Invalid webhook timestamp format");const m=Math.floor(Date.now()/1e3);if(m-l>r)throw new Oe("Webhook timestamp is too old");if(l>m+r)throw new Oe("Webhook timestamp is too new");const h=i.split(" ").map(w=>w.startsWith("v1,")?w.substring(3):w),p=s.startsWith("whsec_")?Buffer.from(s.replace("whsec_",""),"base64"):Buffer.from(s,"utf-8"),d=c?`${c}.${o}.${e}`:`${o}.${e}`,b=await crypto.subtle.importKey("raw",p,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(const w of h)try{const $=Buffer.from(w,"base64");if(await crypto.subtle.verify("HMAC",b,$,new TextEncoder().encode(d)))return}catch{continue}throw new Oe("The given webhook signature does not match the expected signature")}}be=new WeakSet,fa=function(e){if(typeof e!="string"||e.length===0)throw new Error("The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET, on the client class, OpenAI({ webhookSecret: '123' }), or passed to this function")},lt=function(e,n){if(!e)throw new Error("Headers are required");const s=e.get(n);if(s==null)throw new Error(`Missing required header: ${n}`);return s};var ln,Pn,ct,ma;class A{constructor({baseURL:e=_e("OPENAI_BASE_URL"),apiKey:n=_e("OPENAI_API_KEY"),organization:s=_e("OPENAI_ORG_ID")??null,project:r=_e("OPENAI_PROJECT_ID")??null,webhookSecret:a=_e("OPENAI_WEBHOOK_SECRET")??null,...i}={}){if(ln.add(this),ct.set(this,void 0),this.completions=new Kr(this),this.chat=new wn(this),this.embeddings=new Hr(this),this.files=new Xr(this),this.images=new na(this),this.audio=new Je(this),this.moderations=new ra(this),this.models=new sa(this),this.fineTuning=new Ae(this),this.graders=new Tn(this),this.vectorStores=new Et(this),this.webhooks=new pa(this),this.beta=new Se(this),this.batches=new Lr(this),this.uploads=new $n(this),this.responses=new Pt(this),this.realtime=new $t(this),this.conversations=new kn(this),this.evals=new An(this),this.containers=new xn(this),this.videos=new ha(this),n===void 0)throw new x("Missing credentials. Please pass an `apiKey`, or set the `OPENAI_API_KEY` environment variable.");const o={apiKey:n,organization:s,project:r,webhookSecret:a,...i,baseURL:e||"https://api.openai.com/v1"};if(!o.dangerouslyAllowBrowser&&co())throw new x(`It looks like you're running in a browser-like environment.
|
|
22
22
|
|
|
23
23
|
This is disabled by default, as it risks exposing your secret API credentials to attackers.
|
|
24
24
|
If you understand the risks and have appropriate mitigations in place,
|
|
@@ -27,7 +27,7 @@ you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
|
|
|
27
27
|
new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
|
|
28
28
|
|
|
29
29
|
https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
|
|
30
|
-
`);this.baseURL=o.baseURL,this.timeout=o.timeout??Pn.DEFAULT_TIMEOUT,this.logger=o.logger??console;const c="warn";this.logLevel=c,this.logLevel=rs(o.logLevel,"ClientOptions.logLevel",this)??rs(_e("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??c,this.fetchOptions=o.fetchOptions,this.maxRetries=o.maxRetries??2,this.fetch=o.fetch??mo(),k(this,ct,go),this._options=o,this.apiKey=typeof n=="string"?n:"Missing Key",this.organization=s,this.project=r,this.webhookSecret=a}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:n}){}async authHeaders(e){return y([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return ko(e,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${ye}`}defaultIdempotencyKey(){return`stainless-node-retry-${Gs()}`}makeStatusError(e,n,s,r){return q.generate(e,n,s,r)}async _callApiKey(){const e=this._options.apiKey;if(typeof e!="function")return!1;let n;try{n=await e()}catch(s){throw s instanceof x?s:new x(`Failed to get token from 'apiKey' function: ${s.message}`,{cause:s})}if(typeof n!="string"||!n)throw new x(`Expected 'apiKey' function argument to return a string but it returned ${n}`);return this.apiKey=n,!0}buildURL(e,n,s){const r=!u(this,ln,"m",ma).call(this)&&s||this.baseURL,a=ro(e)?new URL(e):new URL(r+(r.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),i=this.defaultQuery();return ao(i)||(n={...i,...n}),typeof n=="object"&&n&&!Array.isArray(n)&&(a.search=this.stringifyQuery(n)),a.toString()}async prepareOptions(e){await this._callApiKey()}async prepareRequest(e,{url:n,options:s}){}get(e,n){return this.methodRequest("get",e,n)}post(e,n){return this.methodRequest("post",e,n)}patch(e,n){return this.methodRequest("patch",e,n)}put(e,n){return this.methodRequest("put",e,n)}delete(e,n){return this.methodRequest("delete",e,n)}methodRequest(e,n,s){return this.request(Promise.resolve(s).then(r=>({method:e,path:n,...r})))}request(e,n=null){return new Ct(this,this.makeRequest(e,n,void 0))}async makeRequest(e,n,s){const r=await e,a=r.maxRetries??this.maxRetries;n==null&&(n=a),await this.prepareOptions(r);const{req:i,url:o,timeout:c}=await this.buildRequest(r,{retryCount:a-n});await this.prepareRequest(i,{url:o,options:r});const l="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),m=s===void 0?"":`, retryOf: ${s}`,h=Date.now();if(U(this).debug(`[${l}] sending request`,ue({retryOfRequestLogID:s,method:r.method,url:o,options:r,headers:i.headers})),r.signal?.aborted)throw new X;const p=new AbortController,d=await this.fetchWithTimeout(o,i,c,p).catch(zt),b=Date.now();if(d instanceof globalThis.Error){const f=`retrying, ${n} attempts remaining`;if(r.signal?.aborted)throw new X;const _=Zt(d)||/timed? ?out/i.test(String(d)+("cause"in d?String(d.cause):""));if(n)return U(this).info(`[${l}] connection ${_?"timed out":"failed"} - ${f}`),U(this).debug(`[${l}] connection ${_?"timed out":"failed"} (${f})`,ue({retryOfRequestLogID:s,url:o,durationMs:b-h,message:d.message})),this.retryRequest(r,n,s??l);throw U(this).info(`[${l}] connection ${_?"timed out":"failed"} - error; no more retries left`),U(this).debug(`[${l}] connection ${_?"timed out":"failed"} (error; no more retries left)`,ue({retryOfRequestLogID:s,url:o,durationMs:b-h,message:d.message})),_?new St:new kt({cause:d})}const w=[...d.headers.entries()].filter(([f])=>f==="x-request-id").map(([f,_])=>", "+f+": "+JSON.stringify(_)).join(""),R=`[${l}${m}${w}] ${i.method} ${o} ${d.ok?"succeeded":"failed"} with status ${d.status} in ${b-h}ms`;if(!d.ok){const f=await this.shouldRetry(d);if(n&&f){const $=`retrying, ${n} attempts remaining`;return await _o(d.body),U(this).info(`${R} - ${$}`),U(this).debug(`[${l}] response error (${$})`,ue({retryOfRequestLogID:s,url:d.url,status:d.status,headers:d.headers,durationMs:b-h})),this.retryRequest(r,n,s??l,d.headers)}const _=f?"error; no more retries left":"error; not retryable";U(this).info(`${R} - ${_}`);const C=await d.text().catch($=>zt($).message),I=lo(C),J=I?void 0:C;throw U(this).debug(`[${l}] response error (${_})`,ue({retryOfRequestLogID:s,url:d.url,status:d.status,headers:d.headers,message:J,durationMs:Date.now()-h})),this.makeStatusError(d.status,I,J,d.headers)}return U(this).info(R),U(this).debug(`[${l}] response start`,ue({retryOfRequestLogID:s,url:d.url,status:d.status,headers:d.headers,durationMs:b-h})),{response:d,options:r,controller:p,requestLogID:l,retryOfRequestLogID:s,startTime:h}}getAPIList(e,n,s){return this.requestAPIList(n,{method:"get",path:e,...s})}requestAPIList(e,n){const s=this.makeRequest(n,null,void 0);return new Po(this,s,e)}async fetchWithTimeout(e,n,s,r){const{signal:a,method:i,...o}=n||{};a&&a.addEventListener("abort",()=>r.abort());const c=setTimeout(()=>r.abort(),s),l=globalThis.ReadableStream&&o.body instanceof globalThis.ReadableStream||typeof o.body=="object"&&o.body!==null&&Symbol.asyncIterator in o.body,m={signal:r.signal,...l?{duplex:"half"}:{},method:"GET",...o};i&&(m.method=i.toUpperCase());try{return await this.fetch.call(void 0,e,m)}finally{clearTimeout(c)}}async shouldRetry(e){const n=e.headers.get("x-should-retry");return n==="true"?!0:n==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,n,s,r){let a;const i=r?.get("retry-after-ms");if(i){const c=parseFloat(i);Number.isNaN(c)||(a=c)}const o=r?.get("retry-after");if(o&&!a){const c=parseFloat(o);Number.isNaN(c)?a=Date.parse(o)-Date.now():a=c*1e3}if(!(a&&0<=a&&a<60*1e3)){const c=e.maxRetries??this.maxRetries;a=this.calculateDefaultRetryTimeoutMillis(n,c)}return await qe(a),this.makeRequest(e,n-1,s)}calculateDefaultRetryTimeoutMillis(e,n){const a=n-e,i=Math.min(.5*Math.pow(2,a),8),o=1-Math.random()*.25;return i*o*1e3}async buildRequest(e,{retryCount:n=0}={}){const s={...e},{method:r,path:a,query:i,defaultBaseURL:o}=s,c=this.buildURL(a,i,o);"timeout"in s&&oo("timeout",s.timeout),s.timeout=s.timeout??this.timeout;const{bodyHeaders:l,body:m}=this.buildBody({options:s}),h=await this.buildHeaders({options:e,method:r,bodyHeaders:l,retryCount:n});return{req:{method:r,headers:h,...s.signal&&{signal:s.signal},...globalThis.ReadableStream&&m instanceof globalThis.ReadableStream&&{duplex:"half"},...m&&{body:m},...this.fetchOptions??{},...s.fetchOptions??{}},url:c,timeout:s.timeout}}async buildHeaders({options:e,method:n,bodyHeaders:s,retryCount:r}){let a={};this.idempotencyHeader&&n!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),a[this.idempotencyHeader]=e.idempotencyKey);const i=y([a,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(r),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...po(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders(e),this._options.defaultHeaders,s,e.headers]);return this.validateHeaders(i),i.values}buildBody({options:{body:e,headers:n}}){if(!e)return{bodyHeaders:void 0,body:void 0};const s=y([n]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&s.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:er(e)}:u(this,ct,"f").call(this,{body:e,headers:s})}}Pn=A,ct=new WeakMap,ln=new WeakSet,ma=function(){return this.baseURL!=="https://api.openai.com/v1"};A.OpenAI=Pn;A.DEFAULT_TIMEOUT=6e5;A.OpenAIError=x;A.APIError=q;A.APIConnectionError=kt;A.APIConnectionTimeoutError=St;A.APIUserAbortError=X;A.NotFoundError=Ls;A.ConflictError=Ds;A.RateLimitError=Bs;A.BadRequestError=Ms;A.AuthenticationError=Ns;A.InternalServerError=Us;A.PermissionDeniedError=js;A.UnprocessableEntityError=Fs;A.InvalidWebhookSignatureError=Oe;A.toFile=Lo;A.Completions=Kr;A.Chat=wn;A.Embeddings=Hr;A.Files=Xr;A.Images=na;A.Audio=Je;A.Moderations=ra;A.Models=sa;A.FineTuning=Ae;A.Graders=Tn;A.VectorStores=Et;A.Webhooks=pa;A.Beta=Se;A.Batches=Lr;A.Uploads=Rn;A.Responses=Pt;A.Realtime=Rt;A.Conversations=kn;A.Evals=An;A.Containers=xn;A.Videos=ha;var En=class extends Ca{temperature;topP;frequencyPenalty;presencePenalty;n;logitBias;model="gpt-3.5-turbo";modelKwargs;stop;stopSequences;user;timeout;streaming=!1;streamUsage=!0;maxTokens;logprobs;topLogprobs;apiKey;organization;__includeRawResponse;client;clientConfig;supportsStrictToolCalling;audio;modalities;reasoning;zdrEnabled;service_tier;promptCacheKey;verbosity;defaultOptions;_llmType(){return"openai"}static lc_name(){return"ChatOpenAI"}get callKeys(){return[...super.callKeys,"options","function_call","functions","tools","tool_choice","promptIndex","response_format","seed","reasoning","service_tier"]}lc_serializable=!0;get lc_secrets(){return{apiKey:"OPENAI_API_KEY",organization:"OPENAI_ORGANIZATION"}}get lc_aliases(){return{apiKey:"openai_api_key",modelName:"model"}}get lc_serializable_keys(){return["configuration","logprobs","topLogprobs","prefixMessages","supportsStrictToolCalling","modalities","audio","temperature","maxTokens","topP","frequencyPenalty","presencePenalty","n","logitBias","user","streaming","streamUsage","model","modelName","modelKwargs","stop","stopSequences","timeout","apiKey","cache","maxConcurrency","maxRetries","verbose","callbacks","tags","metadata","disableStreaming","zdrEnabled","reasoning","promptCacheKey","verbosity"]}getLsParams(t){const e=this.invocationParams(t);return{ls_provider:"openai",ls_model_name:this.model,ls_model_type:"chat",ls_temperature:e.temperature??void 0,ls_max_tokens:e.max_tokens??void 0,ls_stop:t.stop}}_identifyingParams(){return{model_name:this.model,...this.invocationParams(),...this.clientConfig}}identifyingParams(){return this._identifyingParams()}constructor(t){super(t??{});const e=typeof t?.configuration?.apiKey=="string"?t?.configuration?.apiKey:void 0;this.apiKey=t?.apiKey??e??jn("OPENAI_API_KEY"),this.organization=t?.configuration?.organization??jn("OPENAI_ORGANIZATION"),this.model=t?.model??t?.modelName??this.model,this.modelKwargs=t?.modelKwargs??{},this.timeout=t?.timeout,this.temperature=t?.temperature??this.temperature,this.topP=t?.topP??this.topP,this.frequencyPenalty=t?.frequencyPenalty??this.frequencyPenalty,this.presencePenalty=t?.presencePenalty??this.presencePenalty,this.logprobs=t?.logprobs,this.topLogprobs=t?.topLogprobs,this.n=t?.n??this.n,this.logitBias=t?.logitBias,this.stop=t?.stopSequences??t?.stop,this.stopSequences=this.stop,this.user=t?.user,this.__includeRawResponse=t?.__includeRawResponse,this.audio=t?.audio,this.modalities=t?.modalities,this.reasoning=t?.reasoning,this.maxTokens=t?.maxCompletionTokens??t?.maxTokens,this.promptCacheKey=t?.promptCacheKey??this.promptCacheKey,this.verbosity=t?.verbosity??this.verbosity,this.disableStreaming=t?.disableStreaming===!0,this.streaming=t?.streaming===!0,this.disableStreaming&&(this.streaming=!1),t?.streaming===!1&&(this.disableStreaming=!0),this.streamUsage=t?.streamUsage??this.streamUsage,this.disableStreaming&&(this.streamUsage=!1),this.clientConfig={apiKey:this.apiKey,organization:this.organization,dangerouslyAllowBrowser:!0,...t?.configuration},t?.supportsStrictToolCalling!==void 0&&(this.supportsStrictToolCalling=t.supportsStrictToolCalling),t?.service_tier!==void 0&&(this.service_tier=t.service_tier),this.zdrEnabled=t?.zdrEnabled??!1}_getReasoningParams(t){if(!Be(this.model))return;let e;return this.reasoning!==void 0&&(e={...e,...this.reasoning}),t?.reasoning!==void 0&&(e={...e,...t.reasoning}),e}_getResponseFormat(t){return t&&t.type==="json_schema"&&t.json_schema.schema&&Ke(t.json_schema.schema)?to(t.json_schema.schema,t.json_schema.name,{description:t.json_schema.description}):t}_combineCallOptions(t){return{...this.defaultOptions,...t??{}}}_getClientOptions(t){if(!this.client){const n={baseURL:this.clientConfig.baseURL},s=Fa(n),r={...this.clientConfig,baseURL:s,timeout:this.timeout,maxRetries:0};r.baseURL||delete r.baseURL,this.client=new A(r)}return{...this.clientConfig,...t}}_convertChatOpenAIToolToCompletionsTool(t,e){return dt(t)?za(t.metadata.customTool):As(t)?e?.strict!==void 0?{...t,function:{...t.function,strict:e.strict}}:t:Ba(t,e)}bindTools(t,e){let n;return e?.strict!==void 0?n=e.strict:this.supportsStrictToolCalling!==void 0&&(n=this.supportsStrictToolCalling),this.withConfig({tools:t.map(s=>un(s)||dt(s)?s:this._convertChatOpenAIToolToCompletionsTool(s,{strict:n})),...e})}async stream(t,e){return super.stream(t,this._combineCallOptions(e))}async invoke(t,e){return super.invoke(t,this._combineCallOptions(e))}_combineLLMOutput(...t){return t.reduce((e,n)=>(n&&n.tokenUsage&&(e.tokenUsage.completionTokens+=n.tokenUsage.completionTokens??0,e.tokenUsage.promptTokens+=n.tokenUsage.promptTokens??0,e.tokenUsage.totalTokens+=n.tokenUsage.totalTokens??0),e),{tokenUsage:{completionTokens:0,promptTokens:0,totalTokens:0}})}async getNumTokensFromMessages(t){let e=0,n=0,s=0;this.model==="gpt-3.5-turbo-0301"?(n=4,s=-1):(n=3,s=1);const r=await Promise.all(t.map(async a=>{const i=await this.getNumTokens(a.content),o=await this.getNumTokens(Ue(a)),c=a.name!==void 0?s+await this.getNumTokens(a.name):0;let l=i+n+o+c;const m=a;if(m._getType()==="function"&&(l-=2),m.additional_kwargs?.function_call&&(l+=3),m?.additional_kwargs.function_call?.name&&(l+=await this.getNumTokens(m.additional_kwargs.function_call?.name)),m.additional_kwargs.function_call?.arguments)try{l+=await this.getNumTokens(JSON.stringify(JSON.parse(m.additional_kwargs.function_call?.arguments)))}catch(h){console.error("Error parsing function arguments",h,JSON.stringify(m.additional_kwargs.function_call)),l+=await this.getNumTokens(m.additional_kwargs.function_call?.arguments)}return e+=l,l}));return e+=3,{totalCount:e,countPerMessage:r}}async _getNumTokensFromGenerations(t){return(await Promise.all(t.map(async n=>n.message.additional_kwargs?.function_call?(await this.getNumTokensFromMessages([n.message])).countPerMessage[0]:await this.getNumTokens(n.message.content)))).reduce((n,s)=>n+s,0)}async _getEstimatedTokenCountFromPrompt(t,e,n){let s=(await this.getNumTokensFromMessages(t)).totalCount;if(e&&n!=="auto"){const r=Wa(e);s+=await this.getNumTokens(r),s+=9}return e&&t.find(r=>r._getType()==="system")&&(s-=4),n==="none"?s+=1:typeof n=="object"&&(s+=await this.getNumTokens(n.name)+4),s}_getStructuredOutputMethod(t){const e={...t};if(!this.model.startsWith("gpt-3")&&!this.model.startsWith("gpt-4-")&&this.model!=="gpt-4"){if(e?.method===void 0)return"jsonSchema"}else e.method==="jsonSchema"&&console.warn(`[WARNING]: JSON Schema is not supported for model "${this.model}". Falling back to tool calling.`);return e.method}withStructuredOutput(t,e){let n,s;const{schema:r,name:a,includeRaw:i}={...e,schema:t};if(e?.strict!==void 0&&e.method==="jsonMode")throw new Error("Argument `strict` is only supported for `method` = 'function_calling'");const o=Yi(this.model,e?.method);if(o==="jsonMode"){Ke(r)?s=Ln.fromZodSchema(r):s=new Dn;const h=Ze(r);n=this.withConfig({outputVersion:"v0",response_format:{type:"json_object"},ls_structured_output_format:{kwargs:{method:"json_mode"},schema:{title:a??"extract",...h}}})}else if(o==="jsonSchema"){const h={name:a??"extract",description:Oa(r),schema:r,strict:e?.strict},p=Ze(h.schema);if(n=this.withConfig({outputVersion:"v0",response_format:{type:"json_schema",json_schema:h},ls_structured_output_format:{kwargs:{method:"json_schema"},schema:{title:h.name,description:h.description,...p}}}),Ke(r)){const d=Ln.fromZodSchema(r);s=Ia.from(b=>"parsed"in b.additional_kwargs?b.additional_kwargs.parsed:d)}else s=new Dn}else{let h=a??"extract";if(Ke(r)){const p=Ze(r);n=this.withConfig({outputVersion:"v0",tools:[{type:"function",function:{name:h,description:p.description,parameters:p}}],tool_choice:{type:"function",function:{name:h}},ls_structured_output_format:{kwargs:{method:"function_calling"},schema:{title:h,...p}},...e?.strict!==void 0?{strict:e.strict}:{}}),s=new qn({returnSingle:!0,keyName:h,zodSchema:r})}else{let p;typeof r.name=="string"&&typeof r.parameters=="object"&&r.parameters!=null?(p=r,h=r.name):(h=r.title??h,p={name:h,description:r.description??"",parameters:r});const d=Ze(r);n=this.withConfig({outputVersion:"v0",tools:[{type:"function",function:p}],tool_choice:{type:"function",function:{name:h}},ls_structured_output_format:{kwargs:{method:"function_calling"},schema:{title:h,...d}},...e?.strict!==void 0?{strict:e.strict}:{}}),s=new qn({returnSingle:!0,keyName:h})}}if(!i)return n.pipe(s);const c=Fn.assign({parsed:(h,p)=>s.invoke(h.raw,p)}),l=Fn.assign({parsed:()=>null}),m=c.withFallbacks({fallbacks:[l]});return Ta.from([{raw:n},m])}};function et(t,e){return t.lc_error_code=e,t.message=`${t.message}
|
|
30
|
+
`);this.baseURL=o.baseURL,this.timeout=o.timeout??Pn.DEFAULT_TIMEOUT,this.logger=o.logger??console;const c="warn";this.logLevel=c,this.logLevel=rs(o.logLevel,"ClientOptions.logLevel",this)??rs(_e("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??c,this.fetchOptions=o.fetchOptions,this.maxRetries=o.maxRetries??2,this.fetch=o.fetch??mo(),k(this,ct,go),this._options=o,this.apiKey=typeof n=="string"?n:"Missing Key",this.organization=s,this.project=r,this.webhookSecret=a}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:n}){}async authHeaders(e){return y([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return ko(e,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${ye}`}defaultIdempotencyKey(){return`stainless-node-retry-${Gs()}`}makeStatusError(e,n,s,r){return q.generate(e,n,s,r)}async _callApiKey(){const e=this._options.apiKey;if(typeof e!="function")return!1;let n;try{n=await e()}catch(s){throw s instanceof x?s:new x(`Failed to get token from 'apiKey' function: ${s.message}`,{cause:s})}if(typeof n!="string"||!n)throw new x(`Expected 'apiKey' function argument to return a string but it returned ${n}`);return this.apiKey=n,!0}buildURL(e,n,s){const r=!u(this,ln,"m",ma).call(this)&&s||this.baseURL,a=ro(e)?new URL(e):new URL(r+(r.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),i=this.defaultQuery();return ao(i)||(n={...i,...n}),typeof n=="object"&&n&&!Array.isArray(n)&&(a.search=this.stringifyQuery(n)),a.toString()}async prepareOptions(e){await this._callApiKey()}async prepareRequest(e,{url:n,options:s}){}get(e,n){return this.methodRequest("get",e,n)}post(e,n){return this.methodRequest("post",e,n)}patch(e,n){return this.methodRequest("patch",e,n)}put(e,n){return this.methodRequest("put",e,n)}delete(e,n){return this.methodRequest("delete",e,n)}methodRequest(e,n,s){return this.request(Promise.resolve(s).then(r=>({method:e,path:n,...r})))}request(e,n=null){return new Ct(this,this.makeRequest(e,n,void 0))}async makeRequest(e,n,s){const r=await e,a=r.maxRetries??this.maxRetries;n==null&&(n=a),await this.prepareOptions(r);const{req:i,url:o,timeout:c}=await this.buildRequest(r,{retryCount:a-n});await this.prepareRequest(i,{url:o,options:r});const l="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),m=s===void 0?"":`, retryOf: ${s}`,h=Date.now();if(U(this).debug(`[${l}] sending request`,ue({retryOfRequestLogID:s,method:r.method,url:o,options:r,headers:i.headers})),r.signal?.aborted)throw new X;const p=new AbortController,d=await this.fetchWithTimeout(o,i,c,p).catch(zt),b=Date.now();if(d instanceof globalThis.Error){const f=`retrying, ${n} attempts remaining`;if(r.signal?.aborted)throw new X;const _=Zt(d)||/timed? ?out/i.test(String(d)+("cause"in d?String(d.cause):""));if(n)return U(this).info(`[${l}] connection ${_?"timed out":"failed"} - ${f}`),U(this).debug(`[${l}] connection ${_?"timed out":"failed"} (${f})`,ue({retryOfRequestLogID:s,url:o,durationMs:b-h,message:d.message})),this.retryRequest(r,n,s??l);throw U(this).info(`[${l}] connection ${_?"timed out":"failed"} - error; no more retries left`),U(this).debug(`[${l}] connection ${_?"timed out":"failed"} (error; no more retries left)`,ue({retryOfRequestLogID:s,url:o,durationMs:b-h,message:d.message})),_?new St:new kt({cause:d})}const w=[...d.headers.entries()].filter(([f])=>f==="x-request-id").map(([f,_])=>", "+f+": "+JSON.stringify(_)).join(""),$=`[${l}${m}${w}] ${i.method} ${o} ${d.ok?"succeeded":"failed"} with status ${d.status} in ${b-h}ms`;if(!d.ok){const f=await this.shouldRetry(d);if(n&&f){const R=`retrying, ${n} attempts remaining`;return await _o(d.body),U(this).info(`${$} - ${R}`),U(this).debug(`[${l}] response error (${R})`,ue({retryOfRequestLogID:s,url:d.url,status:d.status,headers:d.headers,durationMs:b-h})),this.retryRequest(r,n,s??l,d.headers)}const _=f?"error; no more retries left":"error; not retryable";U(this).info(`${$} - ${_}`);const C=await d.text().catch(R=>zt(R).message),I=lo(C),J=I?void 0:C;throw U(this).debug(`[${l}] response error (${_})`,ue({retryOfRequestLogID:s,url:d.url,status:d.status,headers:d.headers,message:J,durationMs:Date.now()-h})),this.makeStatusError(d.status,I,J,d.headers)}return U(this).info($),U(this).debug(`[${l}] response start`,ue({retryOfRequestLogID:s,url:d.url,status:d.status,headers:d.headers,durationMs:b-h})),{response:d,options:r,controller:p,requestLogID:l,retryOfRequestLogID:s,startTime:h}}getAPIList(e,n,s){return this.requestAPIList(n,{method:"get",path:e,...s})}requestAPIList(e,n){const s=this.makeRequest(n,null,void 0);return new Po(this,s,e)}async fetchWithTimeout(e,n,s,r){const{signal:a,method:i,...o}=n||{};a&&a.addEventListener("abort",()=>r.abort());const c=setTimeout(()=>r.abort(),s),l=globalThis.ReadableStream&&o.body instanceof globalThis.ReadableStream||typeof o.body=="object"&&o.body!==null&&Symbol.asyncIterator in o.body,m={signal:r.signal,...l?{duplex:"half"}:{},method:"GET",...o};i&&(m.method=i.toUpperCase());try{return await this.fetch.call(void 0,e,m)}finally{clearTimeout(c)}}async shouldRetry(e){const n=e.headers.get("x-should-retry");return n==="true"?!0:n==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,n,s,r){let a;const i=r?.get("retry-after-ms");if(i){const c=parseFloat(i);Number.isNaN(c)||(a=c)}const o=r?.get("retry-after");if(o&&!a){const c=parseFloat(o);Number.isNaN(c)?a=Date.parse(o)-Date.now():a=c*1e3}if(!(a&&0<=a&&a<60*1e3)){const c=e.maxRetries??this.maxRetries;a=this.calculateDefaultRetryTimeoutMillis(n,c)}return await qe(a),this.makeRequest(e,n-1,s)}calculateDefaultRetryTimeoutMillis(e,n){const a=n-e,i=Math.min(.5*Math.pow(2,a),8),o=1-Math.random()*.25;return i*o*1e3}async buildRequest(e,{retryCount:n=0}={}){const s={...e},{method:r,path:a,query:i,defaultBaseURL:o}=s,c=this.buildURL(a,i,o);"timeout"in s&&oo("timeout",s.timeout),s.timeout=s.timeout??this.timeout;const{bodyHeaders:l,body:m}=this.buildBody({options:s}),h=await this.buildHeaders({options:e,method:r,bodyHeaders:l,retryCount:n});return{req:{method:r,headers:h,...s.signal&&{signal:s.signal},...globalThis.ReadableStream&&m instanceof globalThis.ReadableStream&&{duplex:"half"},...m&&{body:m},...this.fetchOptions??{},...s.fetchOptions??{}},url:c,timeout:s.timeout}}async buildHeaders({options:e,method:n,bodyHeaders:s,retryCount:r}){let a={};this.idempotencyHeader&&n!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),a[this.idempotencyHeader]=e.idempotencyKey);const i=y([a,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(r),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...po(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders(e),this._options.defaultHeaders,s,e.headers]);return this.validateHeaders(i),i.values}buildBody({options:{body:e,headers:n}}){if(!e)return{bodyHeaders:void 0,body:void 0};const s=y([n]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&s.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:er(e)}:u(this,ct,"f").call(this,{body:e,headers:s})}}Pn=A,ct=new WeakMap,ln=new WeakSet,ma=function(){return this.baseURL!=="https://api.openai.com/v1"};A.OpenAI=Pn;A.DEFAULT_TIMEOUT=6e5;A.OpenAIError=x;A.APIError=q;A.APIConnectionError=kt;A.APIConnectionTimeoutError=St;A.APIUserAbortError=X;A.NotFoundError=Ls;A.ConflictError=Ds;A.RateLimitError=Bs;A.BadRequestError=Ms;A.AuthenticationError=Ns;A.InternalServerError=Us;A.PermissionDeniedError=js;A.UnprocessableEntityError=Fs;A.InvalidWebhookSignatureError=Oe;A.toFile=Lo;A.Completions=Kr;A.Chat=wn;A.Embeddings=Hr;A.Files=Xr;A.Images=na;A.Audio=Je;A.Moderations=ra;A.Models=sa;A.FineTuning=Ae;A.Graders=Tn;A.VectorStores=Et;A.Webhooks=pa;A.Beta=Se;A.Batches=Lr;A.Uploads=$n;A.Responses=Pt;A.Realtime=$t;A.Conversations=kn;A.Evals=An;A.Containers=xn;A.Videos=ha;var En=class extends Na{temperature;topP;frequencyPenalty;presencePenalty;n;logitBias;model="gpt-3.5-turbo";modelKwargs;stop;stopSequences;user;timeout;streaming=!1;streamUsage=!0;maxTokens;logprobs;topLogprobs;apiKey;organization;__includeRawResponse;client;clientConfig;supportsStrictToolCalling;audio;modalities;reasoning;zdrEnabled;service_tier;promptCacheKey;verbosity;defaultOptions;_llmType(){return"openai"}static lc_name(){return"ChatOpenAI"}get callKeys(){return[...super.callKeys,"options","function_call","functions","tools","tool_choice","promptIndex","response_format","seed","reasoning","service_tier"]}lc_serializable=!0;get lc_secrets(){return{apiKey:"OPENAI_API_KEY",organization:"OPENAI_ORGANIZATION"}}get lc_aliases(){return{apiKey:"openai_api_key",modelName:"model"}}get lc_serializable_keys(){return["configuration","logprobs","topLogprobs","prefixMessages","supportsStrictToolCalling","modalities","audio","temperature","maxTokens","topP","frequencyPenalty","presencePenalty","n","logitBias","user","streaming","streamUsage","model","modelName","modelKwargs","stop","stopSequences","timeout","apiKey","cache","maxConcurrency","maxRetries","verbose","callbacks","tags","metadata","disableStreaming","zdrEnabled","reasoning","promptCacheKey","verbosity"]}getLsParams(t){const e=this.invocationParams(t);return{ls_provider:"openai",ls_model_name:this.model,ls_model_type:"chat",ls_temperature:e.temperature??void 0,ls_max_tokens:e.max_tokens??void 0,ls_stop:t.stop}}_identifyingParams(){return{model_name:this.model,...this.invocationParams(),...this.clientConfig}}identifyingParams(){return this._identifyingParams()}constructor(t){super(t??{});const e=typeof t?.configuration?.apiKey=="string"?t?.configuration?.apiKey:void 0;this.apiKey=t?.apiKey??e??jn("OPENAI_API_KEY"),this.organization=t?.configuration?.organization??jn("OPENAI_ORGANIZATION"),this.model=t?.model??t?.modelName??this.model,this.modelKwargs=t?.modelKwargs??{},this.timeout=t?.timeout,this.temperature=t?.temperature??this.temperature,this.topP=t?.topP??this.topP,this.frequencyPenalty=t?.frequencyPenalty??this.frequencyPenalty,this.presencePenalty=t?.presencePenalty??this.presencePenalty,this.logprobs=t?.logprobs,this.topLogprobs=t?.topLogprobs,this.n=t?.n??this.n,this.logitBias=t?.logitBias,this.stop=t?.stopSequences??t?.stop,this.stopSequences=this.stop,this.user=t?.user,this.__includeRawResponse=t?.__includeRawResponse,this.audio=t?.audio,this.modalities=t?.modalities,this.reasoning=t?.reasoning,this.maxTokens=t?.maxCompletionTokens??t?.maxTokens,this.promptCacheKey=t?.promptCacheKey??this.promptCacheKey,this.verbosity=t?.verbosity??this.verbosity,this.disableStreaming=t?.disableStreaming===!0,this.streaming=t?.streaming===!0,this.disableStreaming&&(this.streaming=!1),t?.streaming===!1&&(this.disableStreaming=!0),this.streamUsage=t?.streamUsage??this.streamUsage,this.disableStreaming&&(this.streamUsage=!1),this.clientConfig={apiKey:this.apiKey,organization:this.organization,dangerouslyAllowBrowser:!0,...t?.configuration},t?.supportsStrictToolCalling!==void 0&&(this.supportsStrictToolCalling=t.supportsStrictToolCalling),t?.service_tier!==void 0&&(this.service_tier=t.service_tier),this.zdrEnabled=t?.zdrEnabled??!1}_getReasoningParams(t){if(!Be(this.model))return;let e;return this.reasoning!==void 0&&(e={...e,...this.reasoning}),t?.reasoning!==void 0&&(e={...e,...t.reasoning}),e}_getResponseFormat(t){return t&&t.type==="json_schema"&&t.json_schema.schema&&Ke(t.json_schema.schema)?to(t.json_schema.schema,t.json_schema.name,{description:t.json_schema.description}):t}_combineCallOptions(t){return{...this.defaultOptions,...t??{}}}_getClientOptions(t){if(!this.client){const n={baseURL:this.clientConfig.baseURL},s=Fa(n),r={...this.clientConfig,baseURL:s,timeout:this.timeout,maxRetries:0};r.baseURL||delete r.baseURL,this.client=new A(r)}return{...this.clientConfig,...t}}_convertChatOpenAIToolToCompletionsTool(t,e){return dt(t)?za(t.metadata.customTool):Is(t)?e?.strict!==void 0?{...t,function:{...t.function,strict:e.strict}}:t:Ba(t,e)}bindTools(t,e){let n;return e?.strict!==void 0?n=e.strict:this.supportsStrictToolCalling!==void 0&&(n=this.supportsStrictToolCalling),this.withConfig({tools:t.map(s=>un(s)||dt(s)?s:this._convertChatOpenAIToolToCompletionsTool(s,{strict:n})),...e})}async stream(t,e){return super.stream(t,this._combineCallOptions(e))}async invoke(t,e){return super.invoke(t,this._combineCallOptions(e))}_combineLLMOutput(...t){return t.reduce((e,n)=>(n&&n.tokenUsage&&(e.tokenUsage.completionTokens+=n.tokenUsage.completionTokens??0,e.tokenUsage.promptTokens+=n.tokenUsage.promptTokens??0,e.tokenUsage.totalTokens+=n.tokenUsage.totalTokens??0),e),{tokenUsage:{completionTokens:0,promptTokens:0,totalTokens:0}})}async getNumTokensFromMessages(t){let e=0,n=0,s=0;this.model==="gpt-3.5-turbo-0301"?(n=4,s=-1):(n=3,s=1);const r=await Promise.all(t.map(async a=>{const i=await this.getNumTokens(a.content),o=await this.getNumTokens(Ue(a)),c=a.name!==void 0?s+await this.getNumTokens(a.name):0;let l=i+n+o+c;const m=a;if(m._getType()==="function"&&(l-=2),m.additional_kwargs?.function_call&&(l+=3),m?.additional_kwargs.function_call?.name&&(l+=await this.getNumTokens(m.additional_kwargs.function_call?.name)),m.additional_kwargs.function_call?.arguments)try{l+=await this.getNumTokens(JSON.stringify(JSON.parse(m.additional_kwargs.function_call?.arguments)))}catch(h){console.error("Error parsing function arguments",h,JSON.stringify(m.additional_kwargs.function_call)),l+=await this.getNumTokens(m.additional_kwargs.function_call?.arguments)}return e+=l,l}));return e+=3,{totalCount:e,countPerMessage:r}}async _getNumTokensFromGenerations(t){return(await Promise.all(t.map(async n=>n.message.additional_kwargs?.function_call?(await this.getNumTokensFromMessages([n.message])).countPerMessage[0]:await this.getNumTokens(n.message.content)))).reduce((n,s)=>n+s,0)}async _getEstimatedTokenCountFromPrompt(t,e,n){let s=(await this.getNumTokensFromMessages(t)).totalCount;if(e&&n!=="auto"){const r=Wa(e);s+=await this.getNumTokens(r),s+=9}return e&&t.find(r=>r._getType()==="system")&&(s-=4),n==="none"?s+=1:typeof n=="object"&&(s+=await this.getNumTokens(n.name)+4),s}_getStructuredOutputMethod(t){const e={...t};if(!this.model.startsWith("gpt-3")&&!this.model.startsWith("gpt-4-")&&this.model!=="gpt-4"){if(e?.method===void 0)return"jsonSchema"}else e.method==="jsonSchema"&&console.warn(`[WARNING]: JSON Schema is not supported for model "${this.model}". Falling back to tool calling.`);return e.method}withStructuredOutput(t,e){let n,s;const{schema:r,name:a,includeRaw:i}={...e,schema:t};if(e?.strict!==void 0&&e.method==="jsonMode")throw new Error("Argument `strict` is only supported for `method` = 'function_calling'");const o=Yi(this.model,e?.method);if(o==="jsonMode"){Ke(r)?s=Bn.fromZodSchema(r):s=new Un;const h=Ze(r);n=this.withConfig({outputVersion:"v0",response_format:{type:"json_object"},ls_structured_output_format:{kwargs:{method:"json_mode"},schema:{title:a??"extract",...h}}})}else if(o==="jsonSchema"){const h={name:a??"extract",description:Sa(r),schema:r,strict:e?.strict},p=Ze(h.schema);if(n=this.withConfig({outputVersion:"v0",response_format:{type:"json_schema",json_schema:h},ls_structured_output_format:{kwargs:{method:"json_schema"},schema:{title:h.name,description:h.description,...p}}}),Ke(r)){const d=Bn.fromZodSchema(r);s=Aa.from(b=>"parsed"in b.additional_kwargs?b.additional_kwargs.parsed:d)}else s=new Un}else{let h=a??"extract";if(Ke(r)){const p=Ze(r);n=this.withConfig({outputVersion:"v0",tools:[{type:"function",function:{name:h,description:p.description,parameters:p}}],tool_choice:{type:"function",function:{name:h}},ls_structured_output_format:{kwargs:{method:"function_calling"},schema:{title:h,...p}},...e?.strict!==void 0?{strict:e.strict}:{}}),s=new qn({returnSingle:!0,keyName:h,zodSchema:r})}else{let p;typeof r.name=="string"&&typeof r.parameters=="object"&&r.parameters!=null?(p=r,h=r.name):(h=r.title??h,p={name:h,description:r.description??"",parameters:r});const d=Ze(r);n=this.withConfig({outputVersion:"v0",tools:[{type:"function",function:p}],tool_choice:{type:"function",function:{name:h}},ls_structured_output_format:{kwargs:{method:"function_calling"},schema:{title:h,...d}},...e?.strict!==void 0?{strict:e.strict}:{}}),s=new qn({returnSingle:!0,keyName:h})}}if(!i)return n.pipe(s);const c=Wn.assign({parsed:(h,p)=>s.invoke(h.raw,p)}),l=Wn.assign({parsed:()=>null}),m=c.withFallbacks({fallbacks:[l]});return Ca.from([{raw:n},m])}};function et(t,e){return t.lc_error_code=e,t.message=`${t.message}
|
|
31
31
|
|
|
32
32
|
Troubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${e}/
|
|
33
|
-
`,t}function _a(t){if(!t||typeof t!="object")return t;let e;return t.constructor.name===St.name&&"message"in t&&typeof t.message=="string"?(e=new Error(t.message),e.name="TimeoutError"):t.constructor.name===X.name&&"message"in t&&typeof t.message=="string"?(e=new Error(t.message),e.name="AbortError"):"status"in t&&t.status===400&&"message"in t&&typeof t.message=="string"&&t.message.includes("tool_calls")?e=et(t,"INVALID_TOOL_RESULTS"):"status"in t&&t.status===401?e=et(t,"MODEL_AUTHENTICATION"):"status"in t&&t.status===429?e=et(t,"MODEL_RATE_LIMIT"):"status"in t&&t.status===404?e=et(t,"MODEL_NOT_FOUND"):e=t,e}const ga={providerName:"ChatOpenAI",fromStandardTextBlock(t){return{type:"text",text:t.text}},fromStandardImageBlock(t){if(t.source_type==="url")return{type:"image_url",image_url:{url:t.url,...t.metadata?.detail?{detail:t.metadata.detail}:{}}};if(t.source_type==="base64")return{type:"image_url",image_url:{url:`data:${t.mime_type??""};base64,${t.data}`,...t.metadata?.detail?{detail:t.metadata.detail}:{}}};throw new Error(`Image content blocks with source_type ${t.source_type} are not supported for ChatOpenAI`)},fromStandardAudioBlock(t){if(t.source_type==="url"){const e=Un({dataUrl:t.url});if(!e)throw new Error(`URL audio blocks with source_type ${t.source_type} must be formatted as a data URL for ChatOpenAI`);const n=e.mime_type||t.mime_type||"";let s;try{s=Wn(n)}catch{throw new Error(`Audio blocks with source_type ${t.source_type} must have mime type of audio/wav or audio/mp3`)}if(s.type!=="audio"||s.subtype!=="wav"&&s.subtype!=="mp3")throw new Error(`Audio blocks with source_type ${t.source_type} must have mime type of audio/wav or audio/mp3`);return{type:"input_audio",input_audio:{format:s.subtype,data:e.data}}}if(t.source_type==="base64"){let e;try{e=Wn(t.mime_type??"")}catch{throw new Error(`Audio blocks with source_type ${t.source_type} must have mime type of audio/wav or audio/mp3`)}if(e.type!=="audio"||e.subtype!=="wav"&&e.subtype!=="mp3")throw new Error(`Audio blocks with source_type ${t.source_type} must have mime type of audio/wav or audio/mp3`);return{type:"input_audio",input_audio:{format:e.subtype,data:t.data}}}throw new Error(`Audio content blocks with source_type ${t.source_type} are not supported for ChatOpenAI`)},fromStandardFileBlock(t){if(t.source_type==="url"){if(!Un({dataUrl:t.url}))throw new Error(`URL file blocks with source_type ${t.source_type} must be formatted as a data URL for ChatOpenAI`);return{type:"file",file:{file_data:t.url,...t.metadata?.filename||t.metadata?.name?{filename:t.metadata?.filename||t.metadata?.name}:{}}}}if(t.source_type==="base64")return{type:"file",file:{file_data:`data:${t.mime_type??""};base64,${t.data}`,...t.metadata?.filename||t.metadata?.name||t.metadata?.title?{filename:t.metadata?.filename||t.metadata?.name||t.metadata?.title}:{}}};if(t.source_type==="id")return{type:"file",file:{file_id:t.id}};throw new Error(`File content blocks with source_type ${t.source_type} are not supported for ChatOpenAI`)}},Yo=({message:t,rawResponse:e,includeRawResponse:n})=>{const s=t.tool_calls;switch(t.role){case"assistant":{const r=[],a=[];for(const l of s??[])try{r.push($s(l,{returnId:!0}))}catch(m){a.push(Kt(l,m.message))}const i={function_call:t.function_call,tool_calls:s};n!==void 0&&(i.__raw_response=e);const o={model_provider:"openai",model_name:e.model,...e.system_fingerprint?{usage:{...e.usage},system_fingerprint:e.system_fingerprint}:{}};t.audio&&(i.audio=t.audio);const c=no(t.content||"",e.choices?.[0]?.message);return new ke({content:c,tool_calls:r,invalid_tool_calls:a,additional_kwargs:i,response_metadata:o,id:e.id})}default:return new Ss(t.content||"",t.role??"unknown")}},el=({delta:t,rawResponse:e,includeRawResponse:n,defaultRole:s})=>{const r=t.role??s,a=t.content??"";let i;t.function_call?i={function_call:t.function_call}:t.tool_calls?i={tool_calls:t.tool_calls}:i={},n&&(i.__raw_response=e),t.audio&&(i.audio={...t.audio,index:e.choices[0].index});const o={model_provider:"openai",usage:{...e.usage}};if(r==="user")return new $a({content:a,response_metadata:o});if(r==="assistant"){const c=[];if(Array.isArray(t.tool_calls))for(const l of t.tool_calls)c.push({name:l.function?.name,args:l.function?.arguments,id:l.id,index:l.index,type:"tool_call_chunk"});return new cn({content:a,tool_call_chunks:c,additional_kwargs:i,id:e.id,response_metadata:o})}else return r==="system"?new Bn({content:a,response_metadata:o}):r==="developer"?new Bn({content:a,response_metadata:o,additional_kwargs:{__openai_role__:"developer"}}):r==="function"?new Ra({content:a,additional_kwargs:i,name:t.name,response_metadata:o}):r==="tool"?new Pa({content:a,additional_kwargs:i,tool_call_id:t.tool_call_id,response_metadata:o}):new Ea({content:a,role:r,response_metadata:o})},tl=t=>{if(t.type==="image"){if(t.url)return{type:"image_url",image_url:{url:t.url}};if(t.data)return{type:"image_url",image_url:{url:`data:${t.mimeType};base64,${t.data}`}}}if(t.type==="audio"&&t.data){const e=Ma(()=>{const[,n]=t.mimeType.split("/");return n==="wav"||n==="mp3"?n:"wav"});return{type:"input_audio",input_audio:{data:t.data.toString(),format:e}}}if(t.type==="file"){if(t.data)return{type:"file",file:{file_data:t.data.toString()}};if(t.fileId)return{type:"file",file:{file_id:t.fileId}}}},nl=({message:t,model:e})=>{let n=Ue(t);if(n==="system"&&Be(e)&&(n="developer"),n==="developer")return{role:"developer",content:t.contentBlocks.filter(r=>r.type==="text")};if(n==="system")return{role:"system",content:t.contentBlocks.filter(r=>r.type==="text")};if(n==="assistant")return{role:"assistant",content:t.contentBlocks.filter(r=>r.type==="text")};if(n==="tool"&&Is.isInstance(t))return{role:"tool",tool_call_id:t.tool_call_id,content:t.contentBlocks.filter(r=>r.type==="text")};if(n==="function")return{role:"function",name:t.name??"",content:t.contentBlocks.filter(r=>r.type==="text").join("")};function*s(r){for(const a of r){a.type==="text"&&(yield{type:"text",text:a.text});const i=tl(a);i&&(yield i)}}return{role:"user",content:Array.from(s(t.contentBlocks))}},xs=({messages:t,model:e})=>t.flatMap(n=>{if("output_version"in n.response_metadata&&n.response_metadata?.output_version==="v1")return nl({message:n});let s=Ue(n);s==="system"&&Be(e)&&(s="developer");const r=typeof n.content=="string"?n.content:n.content.map(i=>Cs(i)?Os(i,ga):i),a={role:s,content:r};if(n.name!=null&&(a.name=n.name),n.additional_kwargs.function_call!=null&&(a.function_call=n.additional_kwargs.function_call,a.content=""),ke.isInstance(n)&&n.tool_calls?.length?(a.tool_calls=n.tool_calls.map(La),a.content=""):(n.additional_kwargs.tool_calls!=null&&(a.tool_calls=n.additional_kwargs.tool_calls),Is.isInstance(n)&&n.tool_call_id!=null&&(a.tool_call_id=n.tool_call_id)),n.additional_kwargs.audio&&typeof n.additional_kwargs.audio=="object"&&"id"in n.additional_kwargs.audio){const i={role:"assistant",audio:{id:n.additional_kwargs.audio.id}};return[a,i]}return a}),xt="__openai_function_call_ids__",ya=t=>{const e={...t?.input_tokens_details?.cached_tokens!=null&&{cache_read:t?.input_tokens_details?.cached_tokens}},n={...t?.output_tokens_details?.reasoning_tokens!=null&&{reasoning:t?.output_tokens_details?.reasoning_tokens}};return{input_tokens:t?.input_tokens??0,output_tokens:t?.output_tokens??0,total_tokens:t?.total_tokens??0,input_token_details:e,output_token_details:n}},wa=t=>{if(t.error){const o=new Error(t.error.message);throw o.name=t.error.code,o}let e;const n=[],s=[],r=[],a={model_provider:"openai",model:t.model,created_at:t.created_at,id:t.id,incomplete_details:t.incomplete_details,metadata:t.metadata,object:t.object,status:t.status,user:t.user,service_tier:t.service_tier,model_name:t.model},i={};for(const o of t.output)if(o.type==="message")e=o.id,n.push(...o.content.flatMap(c=>c.type==="output_text"?("parsed"in c&&c.parsed!=null&&(i.parsed=c.parsed),{type:"text",text:c.text,annotations:c.annotations}):c.type==="refusal"?(i.refusal=c.refusal,[]):c));else if(o.type==="function_call"){const c={function:{name:o.name,arguments:o.arguments},id:o.call_id};try{s.push($s(c,{returnId:!0}))}catch(l){let m;typeof l=="object"&&l!=null&&"message"in l&&typeof l.message=="string"&&(m=l.message),r.push(Kt(c,m))}i[xt]??={},o.id&&(i[xt][o.call_id]=o.id)}else if(o.type==="reasoning")i.reasoning=o;else if(o.type==="custom_tool_call"){const c=Ja(o);c?s.push(c):r.push(Kt(o,"Malformed custom tool call"))}else i.tool_outputs??=[],i.tool_outputs.push(o);return new ke({id:e,content:n,tool_calls:s,invalid_tool_calls:r,usage_metadata:ya(t.usage),additional_kwargs:i,response_metadata:a})},sl=t=>{const e=(t.summary.length>1?t.summary.reduce((n,s)=>{const r=n[n.length-1];return r.index===s.index?r.text+=s.text:n.push(s),n},[{...t.summary[0]}]):t.summary).map(n=>Object.fromEntries(Object.entries(n).filter(([s])=>s!=="index")));return{...t,summary:e}},rl=t=>{const e=[];let n={},s;const r=[],a={model_provider:"openai"},i={};let o;if(t.type==="response.output_text.delta")e.push({type:"text",text:t.delta,index:t.content_index});else if(t.type==="response.output_text.annotation.added")e.push({type:"text",text:"",annotations:[t.annotation],index:t.content_index});else if(t.type==="response.output_item.added"&&t.item.type==="message")o=t.item.id;else if(t.type==="response.output_item.added"&&t.item.type==="function_call")r.push({type:"tool_call_chunk",name:t.item.name,args:t.item.arguments,id:t.item.call_id,index:t.output_index}),i[xt]={[t.item.call_id]:t.item.id};else if(t.type==="response.output_item.done"&&["web_search_call","file_search_call","computer_call","code_interpreter_call","mcp_call","mcp_list_tools","mcp_approval_request","image_generation_call","custom_tool_call"].includes(t.item.type))i.tool_outputs=[t.item];else if(t.type==="response.created")a.id=t.response.id,a.model_name=t.response.model,a.model=t.response.model;else if(t.type==="response.completed"){const c=wa(t.response);s=ya(t.response.usage),t.response.text?.format?.type==="json_schema"&&(i.parsed??=JSON.parse(c.text));for(const[l,m]of Object.entries(t.response))l!=="id"&&(a[l]=m)}else if(t.type==="response.function_call_arguments.delta"||t.type==="response.custom_tool_call_input.delta")r.push({type:"tool_call_chunk",args:t.delta,index:t.output_index});else if(t.type==="response.web_search_call.completed"||t.type==="response.file_search_call.completed")n={tool_outputs:{id:t.item_id,type:t.type.replace("response.","").replace(".completed",""),status:"completed"}};else if(t.type==="response.refusal.done")i.refusal=t.refusal;else if(t.type==="response.output_item.added"&&"item"in t&&t.item.type==="reasoning"){const c=t.item.summary?t.item.summary.map((l,m)=>({...l,index:m})):void 0;i.reasoning={id:t.item.id,type:t.item.type,...c?{summary:c}:{}}}else if(t.type==="response.reasoning_summary_part.added")i.reasoning={type:"reasoning",summary:[{...t.part,index:t.summary_index}]};else if(t.type==="response.reasoning_summary_text.delta")i.reasoning={type:"reasoning",summary:[{text:t.delta,type:"summary_text",index:t.summary_index}]};else return t.type==="response.image_generation_call.partial_image",null;return new Jt({text:e.map(c=>c.text).join(""),message:new cn({id:o,content:e,tool_call_chunks:r,usage_metadata:s,additional_kwargs:i,response_metadata:a}),generationInfo:n})},al=t=>{const e=ke.isInstance(t)&&t.response_metadata?.model_provider==="openai";function*n(){const s=xe(()=>{try{const f=Ue(t);return f==="system"||f==="developer"||f==="assistant"||f==="user"?f:"assistant"}catch{return"assistant"}});let r;const a=new Set,i=new Set,o=new Map,c=new Map;function*l(){if(!r)return;const f=r.content;(typeof f=="string"&&f.length>0||Array.isArray(f)&&f.length>0)&&(yield r),r=void 0}const m=f=>{r||(r={type:"message",role:s,content:[]}),typeof r.content=="string"?r.content=r.content.length>0?[{type:"input_text",text:r.content},...f]:[...f]:r.content.push(...f)},h=f=>{if(typeof f=="string")return f;try{return JSON.stringify(f??{})}catch{return"{}"}},p=f=>{const _=xe(()=>{const C=f.metadata?.detail;return C==="low"||C==="high"||C==="auto"?C:"auto"});if(f.fileId)return{type:"input_image",detail:_,file_id:f.fileId};if(f.url)return{type:"input_image",detail:_,image_url:f.url};if(f.data){const C=typeof f.data=="string"?f.data:Buffer.from(f.data).toString("base64"),I=f.mimeType??"image/png";return{type:"input_image",detail:_,image_url:`data:${I};base64,${C}`}}},d=f=>{const _=f.metadata?.filename??f.metadata?.name??f.metadata?.title;if(f.fileId&&typeof _=="string")return{type:"input_file",file_id:f.fileId,..._?{filename:_}:{}};if(f.url&&typeof _=="string")return{type:"input_file",file_url:f.url,..._?{filename:_}:{}};if(f.data&&typeof _=="string"){const C=typeof f.data=="string"?f.data:Buffer.from(f.data).toString("base64");return{type:"input_file",file_data:`data:${f.mimeType??"application/octet-stream"};base64,${C}`,..._?{filename:_}:{}}}},b=f=>{const _=xe(()=>{if(Array.isArray(f.summary)){const L=f.summary?.map($=>$?.text).filter($=>typeof $=="string")??[];if(L.length>0)return L}return f.reasoning?[f.reasoning]:[]}),C=_.length>0?_.map(J=>({type:"summary_text",text:J})):[{type:"summary_text",text:""}],I={type:"reasoning",id:f.id??"",summary:C};return f.reasoning&&(I.content=[{type:"reasoning_text",text:f.reasoning}]),I},w=f=>({type:"function_call",name:f.name??"",call_id:f.id??"",arguments:h(f.args)}),R=f=>{const _=h(f.output),C=f.status==="success"?"completed":f.status==="error"?"incomplete":void 0;return{type:"function_call_output",call_id:f.toolCallId??"",output:_,...C?{status:C}:{}}};for(const f of t.contentBlocks)if(f.type==="text")m([{type:"input_text",text:f.text}]);else if(f.type!=="invalid_tool_call"){if(f.type==="reasoning")yield*l(),yield b(f);else if(f.type==="tool_call"){yield*l();const _=f.id??"";_&&(a.add(_),o.delete(_)),yield w(f)}else if(f.type==="tool_call_chunk"){if(f.id){const _=o.get(f.id)??{name:f.name,args:[]};f.name&&(_.name=f.name),f.args&&_.args.push(f.args),o.set(f.id,_)}}else if(f.type==="server_tool_call"){yield*l();const _=f.id??"";_&&(i.add(_),c.delete(_)),yield w(f)}else if(f.type==="server_tool_call_chunk"){if(f.id){const _=c.get(f.id)??{name:f.name,args:[]};f.name&&(_.name=f.name),f.args&&_.args.push(f.args),c.set(f.id,_)}}else if(f.type==="server_tool_call_result")yield*l(),yield R(f);else if(f.type!=="audio")if(f.type==="file"){const _=d(f);_&&m([_])}else if(f.type==="image"){const _=p(f);_&&m([_])}else if(f.type==="video"){const _=d(f);_&&m([_])}else f.type==="text-plain"?f.text&&m([{type:"input_text",text:f.text}]):f.type==="non_standard"&&e&&(yield*l(),yield f.value)}yield*l();for(const[f,_]of o){if(!f||a.has(f))continue;const C=_.args.join("");!_.name&&!C||(yield{type:"function_call",call_id:f,name:_.name??"",arguments:C})}for(const[f,_]of c){if(!f||i.has(f))continue;const C=_.args.join("");!_.name&&!C||(yield{type:"function_call",call_id:f,name:_.name??"",arguments:C})}}return Array.from(n())},ks=({messages:t,zdrEnabled:e,model:n})=>t.flatMap(s=>{const r=s.response_metadata;if(r?.output_version==="v1")return al(s);const a=s.additional_kwargs;let i=Ue(s);if(i==="system"&&Be(n)&&(i="developer"),i==="function")throw new Error("Function messages are not supported in Responses API");if(i==="tool"){const o=s;return a?.type==="computer_call_output"?{type:"computer_call_output",output:(()=>{if(typeof o.content=="string")return{type:"computer_screenshot",image_url:o.content};if(Array.isArray(o.content)){const l=o.content.find(h=>h.type==="computer_screenshot");if(l)return l;const m=o.content.find(h=>h.type==="image_url");if(m)return{type:"computer_screenshot",image_url:typeof m.image_url=="string"?m.image_url:m.image_url.url}}throw new Error("Invalid computer call output")})(),call_id:o.tool_call_id}:o.additional_kwargs?.customTool?{type:"custom_tool_call_output",call_id:o.tool_call_id,output:o.content}:{type:"function_call_output",call_id:o.tool_call_id,id:o.id?.startsWith("fc_")?o.id:void 0,output:typeof o.content!="string"?JSON.stringify(o.content):o.content}}if(i==="assistant"){if(!e&&r?.output!=null&&Array.isArray(r?.output)&&r?.output.length>0&&r?.output.every(p=>"type"in p))return r?.output;const o=[];if(a?.reasoning&&!e){const p=sl(a.reasoning);o.push(p)}let{content:c}=s;a?.refusal&&(typeof c=="string"&&(c=[{type:"output_text",text:c,annotations:[]}]),c=[...c,{type:"refusal",refusal:a.refusal}]),(typeof c=="string"||c.length>0)&&o.push({type:"message",role:"assistant",...s.id&&!e&&s.id.startsWith("msg_")?{id:s.id}:{},content:xe(()=>typeof c=="string"?c:c.flatMap(p=>p.type==="text"?{type:"output_text",text:p.text,annotations:p.annotations??[]}:p.type==="output_text"||p.type==="refusal"?p:[]))});const l=a?.[xt];ke.isInstance(s)&&s.tool_calls?.length?o.push(...s.tool_calls.map(p=>Ka(p)?{type:"custom_tool_call",id:p.call_id,call_id:p.id??"",input:p.args.input,name:p.name}:{type:"function_call",name:p.name,arguments:JSON.stringify(p.args),call_id:p.id,...e?{}:{id:l?.[p.id]}})):a?.tool_calls&&o.push(...a.tool_calls.map(p=>({type:"function_call",name:p.function.name,call_id:p.id,arguments:p.function.arguments,...e?{}:{id:l?.[p.id]}})));const m=r?.output?.length?r?.output:a.tool_outputs,h=["computer_call","mcp_call","code_interpreter_call","image_generation_call"];if(m!=null){const d=m?.filter(b=>h.includes(b.type));d.length>0&&o.push(...d)}return o}if(i==="user"||i==="system"||i==="developer"){if(typeof s.content=="string")return{type:"message",role:i,content:s.content};const o=[],c=s.content.flatMap(l=>{if(l.type==="mcp_approval_response"&&o.push({type:"mcp_approval_response",approval_request_id:l.approval_request_id,approve:l.approve}),Cs(l))return Os(l,ga);if(l.type==="text")return{type:"input_text",text:l.text};if(l.type==="image_url"){const m=xe(()=>{if(typeof l.image_url=="string")return l.image_url;if(typeof l.image_url=="object"&&l.image_url!==null&&"url"in l.image_url)return l.image_url.url}),h=xe(()=>{if(typeof l.image_url=="string")return"auto";if(typeof l.image_url=="object"&&l.image_url!==null&&"detail"in l.image_url)return l.image_url.detail});return{type:"input_image",image_url:m,detail:h}}return l.type==="input_text"||l.type==="input_image"||l.type==="input_file"?l:[]});return c.length>0&&o.push({type:"message",role:i,content:c}),o}return console.warn(`Unsupported role found when converting to OpenAI Responses API: ${i}`),[]});var il=class extends En{invocationParams(t){let e;t?.strict!==void 0?e=t.strict:this.supportsStrictToolCalling!==void 0&&(e=this.supportsStrictToolCalling);const n={model:this.model,temperature:this.temperature,top_p:this.topP,user:this.user,stream:this.streaming,previous_response_id:t?.previous_response_id,truncation:t?.truncation,include:t?.include,tools:t?.tools?.length?this._reduceChatOpenAITools(t.tools,{stream:this.streaming,strict:e}):void 0,tool_choice:qa(t?.tool_choice)?t?.tool_choice:(()=>{const r=Ps(t?.tool_choice);if(typeof r=="object"&&"type"in r){if(r.type==="function")return{type:"function",name:r.function.name};if(r.type==="allowed_tools")return{type:"allowed_tools",mode:r.allowed_tools.mode,tools:r.allowed_tools.tools};if(r.type==="custom")return{type:"custom",name:r.custom.name}}})(),text:(()=>{if(t?.text)return t.text;const r=this._getResponseFormat(t?.response_format);return r?.type==="json_schema"?r.json_schema.schema!=null?{format:{type:"json_schema",schema:r.json_schema.schema,description:r.json_schema.description,name:r.json_schema.name,strict:r.json_schema.strict},verbosity:t?.verbosity}:void 0:{format:r,verbosity:t?.verbosity}})(),parallel_tool_calls:t?.parallel_tool_calls,max_output_tokens:this.maxTokens===-1?void 0:this.maxTokens,prompt_cache_key:t?.promptCacheKey??this.promptCacheKey,...this.zdrEnabled?{store:!1}:{},...this.modelKwargs},s=this._getReasoningParams(t);return s!==void 0&&(n.reasoning=s),n}async _generate(t,e){const n=this.invocationParams(e);if(n.stream){const s=this._streamResponseChunks(t,e);let r;for await(const a of s)a.message.response_metadata={...a.generationInfo,...a.message.response_metadata},r=r?.concat(a)??a;return{generations:r?[r]:[],llmOutput:{estimatedTokenUsage:r?.message?.usage_metadata}}}else{const s=await this.completionWithRetry({input:ks({messages:t,zdrEnabled:this.zdrEnabled??!1,model:this.model}),...n,stream:!1},{signal:e?.signal,...e?.options});return{generations:[{text:s.output_text,message:wa(s)}],llmOutput:{id:s.id,estimatedTokenUsage:s.usage?{promptTokens:s.usage.input_tokens,completionTokens:s.usage.output_tokens,totalTokens:s.usage.total_tokens}:void 0}}}}async*_streamResponseChunks(t,e,n){const s=await this.completionWithRetry({...this.invocationParams(e),input:ks({messages:t,zdrEnabled:this.zdrEnabled??!1,model:this.model}),stream:!0},e);for await(const r of s){const a=rl(r);a!=null&&(yield a,await n?.handleLLMNewToken(a.text||"",{prompt:e.promptIndex??0,completion:0},void 0,void 0,void 0,{chunk:a}))}}async completionWithRetry(t,e){return this.caller.call(async()=>{const n=this._getClientOptions(e);try{return t.text?.format?.type==="json_schema"&&!t.stream?await this.client.responses.parse(t,n):await this.client.responses.create(t,n)}catch(s){throw _a(s)}})}_reduceChatOpenAITools(t,e){const n=[];for(const s of t)if(un(s))s.type==="image_generation"&&e?.stream&&(s.partial_images=1),n.push(s);else if(dt(s)){const r=s.metadata.customTool;n.push({type:"custom",name:r.name,description:r.description,format:r.format})}else As(s)?n.push({type:"function",name:s.function.name,parameters:s.function.parameters,description:s.function.description,strict:e?.strict??null}):Es(s)&&n.push(Za(s));return n}},ol=class extends En{invocationParams(t,e){let n;t?.strict!==void 0?n=t.strict:this.supportsStrictToolCalling!==void 0&&(n=this.supportsStrictToolCalling);let s={};t?.stream_options!==void 0?s={stream_options:t.stream_options}:this.streamUsage&&(this.streaming||e?.streaming)&&(s={stream_options:{include_usage:!0}});const r={model:this.model,temperature:this.temperature,top_p:this.topP,frequency_penalty:this.frequencyPenalty,presence_penalty:this.presencePenalty,logprobs:this.logprobs,top_logprobs:this.topLogprobs,n:this.n,logit_bias:this.logitBias,stop:t?.stop??this.stopSequences,user:this.user,stream:this.streaming,functions:t?.functions,function_call:t?.function_call,tools:t?.tools?.length?t.tools.map(i=>this._convertChatOpenAIToolToCompletionsTool(i,{strict:n})):void 0,tool_choice:Ps(t?.tool_choice),response_format:this._getResponseFormat(t?.response_format),seed:t?.seed,...s,parallel_tool_calls:t?.parallel_tool_calls,...this.audio||t?.audio?{audio:this.audio||t?.audio}:{},...this.modalities||t?.modalities?{modalities:this.modalities||t?.modalities}:{},...this.modelKwargs,prompt_cache_key:t?.promptCacheKey??this.promptCacheKey,verbosity:t?.verbosity??this.verbosity};t?.prediction!==void 0&&(r.prediction=t.prediction),this.service_tier!==void 0&&(r.service_tier=this.service_tier),t?.service_tier!==void 0&&(r.service_tier=t.service_tier);const a=this._getReasoningParams(t);return a!==void 0&&a.effort!==void 0&&(r.reasoning_effort=a.effort),Be(r.model)?r.max_completion_tokens=this.maxTokens===-1?void 0:this.maxTokens:r.max_tokens=this.maxTokens===-1?void 0:this.maxTokens,r}async _generate(t,e,n){const s={},r=this.invocationParams(e),a=xs({messages:t,model:this.model});if(r.stream){const i=this._streamResponseChunks(t,e,n),o={};for await(const d of i){d.message.response_metadata={...d.generationInfo,...d.message.response_metadata};const b=d.generationInfo?.completion??0;o[b]===void 0?o[b]=d:o[b]=o[b].concat(d)}const c=Object.entries(o).sort(([d],[b])=>parseInt(d,10)-parseInt(b,10)).map(([d,b])=>b),{functions:l,function_call:m}=this.invocationParams(e),h=await this._getEstimatedTokenCountFromPrompt(t,l,m),p=await this._getNumTokensFromGenerations(c);return s.input_tokens=h,s.output_tokens=p,s.total_tokens=h+p,{generations:c,llmOutput:{estimatedTokenUsage:{promptTokens:s.input_tokens,completionTokens:s.output_tokens,totalTokens:s.total_tokens}}}}else{const i=await this.completionWithRetry({...r,stream:!1,messages:a},{signal:e?.signal,...e?.options}),{completion_tokens:o,prompt_tokens:c,total_tokens:l,prompt_tokens_details:m,completion_tokens_details:h}=i?.usage??{};o&&(s.output_tokens=(s.output_tokens??0)+o),c&&(s.input_tokens=(s.input_tokens??0)+c),l&&(s.total_tokens=(s.total_tokens??0)+l),(m?.audio_tokens!==null||m?.cached_tokens!==null)&&(s.input_token_details={...m?.audio_tokens!==null&&{audio:m?.audio_tokens},...m?.cached_tokens!==null&&{cache_read:m?.cached_tokens}}),(h?.audio_tokens!==null||h?.reasoning_tokens!==null)&&(s.output_token_details={...h?.audio_tokens!==null&&{audio:h?.audio_tokens},...h?.reasoning_tokens!==null&&{reasoning:h?.reasoning_tokens}});const p=[];for(const d of i?.choices??[]){const w={text:d.message?.content??"",message:this._convertCompletionsMessageToBaseMessage(d.message??{role:"assistant"},i)};w.generationInfo={...d.finish_reason?{finish_reason:d.finish_reason}:{},...d.logprobs?{logprobs:d.logprobs}:{}},Na(w.message)&&(w.message.usage_metadata=s),w.message=new ke(Object.fromEntries(Object.entries(w.message).filter(([R])=>!R.startsWith("lc_")))),p.push(w)}return{generations:p,llmOutput:{tokenUsage:{promptTokens:s.input_tokens,completionTokens:s.output_tokens,totalTokens:s.total_tokens}}}}}async*_streamResponseChunks(t,e,n){const s=xs({messages:t,model:this.model}),r={...this.invocationParams(e,{streaming:!0}),messages:s,stream:!0};let a;const i=await this.completionWithRetry(r,e);let o;for await(const c of i){const l=c?.choices?.[0];if(c.usage&&(o=c.usage),!l)continue;const{delta:m}=l;if(!m)continue;const h=this._convertCompletionsDeltaToBaseMessageChunk(m,c,a);a=m.role??a;const p={prompt:e.promptIndex??0,completion:l.index??0};if(typeof h.content!="string"){console.log("[WARNING]: Received non-string content from OpenAI. This is currently not supported.");continue}const d={...p};l.finish_reason!=null&&(d.finish_reason=l.finish_reason,d.system_fingerprint=c.system_fingerprint,d.model_name=c.model,d.service_tier=c.service_tier),this.logprobs&&(d.logprobs=l.logprobs);const b=new Jt({message:h,text:h.content,generationInfo:d});yield b,await n?.handleLLMNewToken(b.text??"",p,void 0,void 0,void 0,{chunk:b})}if(o){const c={...o.prompt_tokens_details?.audio_tokens!==null&&{audio:o.prompt_tokens_details?.audio_tokens},...o.prompt_tokens_details?.cached_tokens!==null&&{cache_read:o.prompt_tokens_details?.cached_tokens}},l={...o.completion_tokens_details?.audio_tokens!==null&&{audio:o.completion_tokens_details?.audio_tokens},...o.completion_tokens_details?.reasoning_tokens!==null&&{reasoning:o.completion_tokens_details?.reasoning_tokens}};yield new Jt({message:new cn({content:"",response_metadata:{usage:{...o}},usage_metadata:{input_tokens:o.prompt_tokens,output_tokens:o.completion_tokens,total_tokens:o.total_tokens,...Object.keys(c).length>0&&{input_token_details:c},...Object.keys(l).length>0&&{output_token_details:l}}}),text:""})}if(e.signal?.aborted)throw new Error("AbortError")}async completionWithRetry(t,e){const n=this._getClientOptions(e),s=t.response_format&&t.response_format.type==="json_schema";return this.caller.call(async()=>{try{return s&&!t.stream?await this.client.chat.completions.parse(t,n):await this.client.chat.completions.create(t,n)}catch(r){throw _a(r)}})}_convertCompletionsDeltaToBaseMessageChunk(t,e,n){return el({delta:t,rawResponse:e,includeRawResponse:this.__includeRawResponse,defaultRole:n})}_convertCompletionsMessageToBaseMessage(t,e){return Yo({message:t,rawResponse:e,includeRawResponse:this.__includeRawResponse})}},kl=class ba extends En{useResponsesApi=!1;responses;completions;get lc_serializable_keys(){return[...super.lc_serializable_keys,"useResponsesApi"]}get callKeys(){return[...super.callKeys,"useResponsesApi"]}constructor(e){super(e),this.fields=e,this.useResponsesApi=e?.useResponsesApi??!1,this.responses=e?.responses??new il(e),this.completions=e?.completions??new ol(e)}_useResponsesApi(e){const n=e?.tools?.some(un),s=e?.previous_response_id!=null||e?.text!=null||e?.truncation!=null||e?.include!=null||e?.reasoning?.summary!=null||this.reasoning?.summary!=null,r=e?.tools?.some(Es)||e?.tools?.some(dt);return this.useResponsesApi||n||s||r}getLsParams(e){const n=this._combineCallOptions(e);return this._useResponsesApi(e)?this.responses.getLsParams(n):this.completions.getLsParams(n)}invocationParams(e){const n=this._combineCallOptions(e);return this._useResponsesApi(e)?this.responses.invocationParams(n):this.completions.invocationParams(n)}async _generate(e,n,s){return this._useResponsesApi(n)?this.responses._generate(e,n):this.completions._generate(e,n,s)}async*_streamResponseChunks(e,n,s){if(this._useResponsesApi(n)){yield*this.responses._streamResponseChunks(e,this._combineCallOptions(n),s);return}yield*this.completions._streamResponseChunks(e,this._combineCallOptions(n),s)}withConfig(e){const n=new ba(this.fields);return n.defaultOptions={...this.defaultOptions,...e},n}};export{En as BaseChatOpenAI,kl as ChatOpenAI,ol as ChatOpenAICompletions,il as ChatOpenAIResponses,A as OpenAIClient,Fa as getEndpoint,Ue as messageToOpenAIRole,Lo as toFile,_a as wrapOpenAIClientError};
|
|
33
|
+
`,t}function _a(t){if(!t||typeof t!="object")return t;let e;return t.constructor.name===St.name&&"message"in t&&typeof t.message=="string"?(e=new Error(t.message),e.name="TimeoutError"):t.constructor.name===X.name&&"message"in t&&typeof t.message=="string"?(e=new Error(t.message),e.name="AbortError"):"status"in t&&t.status===400&&"message"in t&&typeof t.message=="string"&&t.message.includes("tool_calls")?e=et(t,"INVALID_TOOL_RESULTS"):"status"in t&&t.status===401?e=et(t,"MODEL_AUTHENTICATION"):"status"in t&&t.status===429?e=et(t,"MODEL_RATE_LIMIT"):"status"in t&&t.status===404?e=et(t,"MODEL_NOT_FOUND"):e=t,e}const ga={providerName:"ChatOpenAI",fromStandardTextBlock(t){return{type:"text",text:t.text}},fromStandardImageBlock(t){if(t.source_type==="url")return{type:"image_url",image_url:{url:t.url,...t.metadata?.detail?{detail:t.metadata.detail}:{}}};if(t.source_type==="base64")return{type:"image_url",image_url:{url:`data:${t.mime_type??""};base64,${t.data}`,...t.metadata?.detail?{detail:t.metadata.detail}:{}}};throw new Error(`Image content blocks with source_type ${t.source_type} are not supported for ChatOpenAI`)},fromStandardAudioBlock(t){if(t.source_type==="url"){const e=Dn({dataUrl:t.url});if(!e)throw new Error(`URL audio blocks with source_type ${t.source_type} must be formatted as a data URL for ChatOpenAI`);const n=e.mime_type||t.mime_type||"";let s;try{s=Fn(n)}catch{throw new Error(`Audio blocks with source_type ${t.source_type} must have mime type of audio/wav or audio/mp3`)}if(s.type!=="audio"||s.subtype!=="wav"&&s.subtype!=="mp3")throw new Error(`Audio blocks with source_type ${t.source_type} must have mime type of audio/wav or audio/mp3`);return{type:"input_audio",input_audio:{format:s.subtype,data:e.data}}}if(t.source_type==="base64"){let e;try{e=Fn(t.mime_type??"")}catch{throw new Error(`Audio blocks with source_type ${t.source_type} must have mime type of audio/wav or audio/mp3`)}if(e.type!=="audio"||e.subtype!=="wav"&&e.subtype!=="mp3")throw new Error(`Audio blocks with source_type ${t.source_type} must have mime type of audio/wav or audio/mp3`);return{type:"input_audio",input_audio:{format:e.subtype,data:t.data}}}throw new Error(`Audio content blocks with source_type ${t.source_type} are not supported for ChatOpenAI`)},fromStandardFileBlock(t){if(t.source_type==="url"){if(!Dn({dataUrl:t.url}))throw new Error(`URL file blocks with source_type ${t.source_type} must be formatted as a data URL for ChatOpenAI`);return{type:"file",file:{file_data:t.url,...t.metadata?.filename||t.metadata?.name?{filename:t.metadata?.filename||t.metadata?.name}:{}}}}if(t.source_type==="base64")return{type:"file",file:{file_data:`data:${t.mime_type??""};base64,${t.data}`,...t.metadata?.filename||t.metadata?.name||t.metadata?.title?{filename:t.metadata?.filename||t.metadata?.name||t.metadata?.title}:{}}};if(t.source_type==="id")return{type:"file",file:{file_id:t.id}};throw new Error(`File content blocks with source_type ${t.source_type} are not supported for ChatOpenAI`)}},Yo=({message:t,rawResponse:e,includeRawResponse:n})=>{const s=t.tool_calls;switch(t.role){case"assistant":{const r=[],a=[];for(const l of s??[])try{r.push(Rs(l,{returnId:!0}))}catch(m){a.push(Kt(l,m.message))}const i={function_call:t.function_call,tool_calls:s};n!==void 0&&(i.__raw_response=e);const o={model_provider:"openai",model_name:e.model,...e.system_fingerprint?{usage:{...e.usage},system_fingerprint:e.system_fingerprint}:{}};t.audio&&(i.audio=t.audio);const c=no(t.content||"",e.choices?.[0]?.message);return new ke({content:c,tool_calls:r,invalid_tool_calls:a,additional_kwargs:i,response_metadata:o,id:e.id})}default:return new Ss(t.content||"",t.role??"unknown")}},el=({delta:t,rawResponse:e,includeRawResponse:n,defaultRole:s})=>{const r=t.role??s,a=t.content??"";let i;t.function_call?i={function_call:t.function_call}:t.tool_calls?i={tool_calls:t.tool_calls}:i={},n&&(i.__raw_response=e),t.audio&&(i.audio={...t.audio,index:e.choices[0].index});const o={model_provider:"openai",usage:{...e.usage}};if(r==="user")return new Oa({content:a,response_metadata:o});if(r==="assistant"){const c=[];if(Array.isArray(t.tool_calls))for(const l of t.tool_calls)c.push({name:l.function?.name,args:l.function?.arguments,id:l.id,index:l.index,type:"tool_call_chunk"});return new cn({content:a,tool_call_chunks:c,additional_kwargs:i,id:e.id,response_metadata:o})}else return r==="system"?new Ln({content:a,response_metadata:o}):r==="developer"?new Ln({content:a,response_metadata:o,additional_kwargs:{__openai_role__:"developer"}}):r==="function"?new Ia({content:a,additional_kwargs:i,name:t.name,response_metadata:o}):r==="tool"?new Ta({content:a,additional_kwargs:i,tool_call_id:t.tool_call_id,response_metadata:o}):new Ra({content:a,role:r,response_metadata:o})},tl=t=>{if(t.type==="image"){if(t.url)return{type:"image_url",image_url:{url:t.url}};if(t.data)return{type:"image_url",image_url:{url:`data:${t.mimeType};base64,${t.data}`}}}if(t.type==="audio"&&t.data){const e=$a(()=>{const[,n]=t.mimeType.split("/");return n==="wav"||n==="mp3"?n:"wav"});return{type:"input_audio",input_audio:{data:t.data.toString(),format:e}}}if(t.type==="file"){if(t.data)return{type:"file",file:{file_data:t.data.toString()}};if(t.fileId)return{type:"file",file:{file_id:t.fileId}}}},nl=({message:t,model:e})=>{let n=Ue(t);if(n==="system"&&Be(e)&&(n="developer"),n==="developer")return{role:"developer",content:t.contentBlocks.filter(r=>r.type==="text")};if(n==="system")return{role:"system",content:t.contentBlocks.filter(r=>r.type==="text")};if(n==="assistant")return{role:"assistant",content:t.contentBlocks.filter(r=>r.type==="text")};if(n==="tool"&&Os.isInstance(t))return{role:"tool",tool_call_id:t.tool_call_id,content:t.contentBlocks.filter(r=>r.type==="text")};if(n==="function")return{role:"function",name:t.name??"",content:t.contentBlocks.filter(r=>r.type==="text").join("")};function*s(r){for(const a of r){a.type==="text"&&(yield{type:"text",text:a.text});const i=tl(a);i&&(yield i)}}return{role:"user",content:Array.from(s(t.contentBlocks))}},xs=({messages:t,model:e})=>t.flatMap(n=>{if("output_version"in n.response_metadata&&n.response_metadata?.output_version==="v1")return nl({message:n});let s=Ue(n);s==="system"&&Be(e)&&(s="developer");const r=typeof n.content=="string"?n.content:n.content.map(i=>As(i)?Cs(i,ga):i),a={role:s,content:r};if(n.name!=null&&(a.name=n.name),n.additional_kwargs.function_call!=null&&(a.function_call=n.additional_kwargs.function_call,a.content=""),ke.isInstance(n)&&n.tool_calls?.length?(a.tool_calls=n.tool_calls.map(La),a.content=""):(n.additional_kwargs.tool_calls!=null&&(a.tool_calls=n.additional_kwargs.tool_calls),Os.isInstance(n)&&n.tool_call_id!=null&&(a.tool_call_id=n.tool_call_id)),n.additional_kwargs.audio&&typeof n.additional_kwargs.audio=="object"&&"id"in n.additional_kwargs.audio){const i={role:"assistant",audio:{id:n.additional_kwargs.audio.id}};return[a,i]}return a}),xt="__openai_function_call_ids__",ya=t=>{const e={...t?.input_tokens_details?.cached_tokens!=null&&{cache_read:t?.input_tokens_details?.cached_tokens}},n={...t?.output_tokens_details?.reasoning_tokens!=null&&{reasoning:t?.output_tokens_details?.reasoning_tokens}};return{input_tokens:t?.input_tokens??0,output_tokens:t?.output_tokens??0,total_tokens:t?.total_tokens??0,input_token_details:e,output_token_details:n}},wa=t=>{if(t.error){const o=new Error(t.error.message);throw o.name=t.error.code,o}let e;const n=[],s=[],r=[],a={model_provider:"openai",model:t.model,created_at:t.created_at,id:t.id,incomplete_details:t.incomplete_details,metadata:t.metadata,object:t.object,status:t.status,user:t.user,service_tier:t.service_tier,model_name:t.model},i={};for(const o of t.output)if(o.type==="message")e=o.id,n.push(...o.content.flatMap(c=>c.type==="output_text"?("parsed"in c&&c.parsed!=null&&(i.parsed=c.parsed),{type:"text",text:c.text,annotations:c.annotations}):c.type==="refusal"?(i.refusal=c.refusal,[]):c));else if(o.type==="function_call"){const c={function:{name:o.name,arguments:o.arguments},id:o.call_id};try{s.push(Rs(c,{returnId:!0}))}catch(l){let m;typeof l=="object"&&l!=null&&"message"in l&&typeof l.message=="string"&&(m=l.message),r.push(Kt(c,m))}i[xt]??={},o.id&&(i[xt][o.call_id]=o.id)}else if(o.type==="reasoning")i.reasoning=o;else if(o.type==="custom_tool_call"){const c=Ja(o);c?s.push(c):r.push(Kt(o,"Malformed custom tool call"))}else i.tool_outputs??=[],i.tool_outputs.push(o);return new ke({id:e,content:n,tool_calls:s,invalid_tool_calls:r,usage_metadata:ya(t.usage),additional_kwargs:i,response_metadata:a})},sl=t=>{const e=(t.summary.length>1?t.summary.reduce((n,s)=>{const r=n[n.length-1];return r.index===s.index?r.text+=s.text:n.push(s),n},[{...t.summary[0]}]):t.summary).map(n=>Object.fromEntries(Object.entries(n).filter(([s])=>s!=="index")));return{...t,summary:e}},rl=t=>{const e=[];let n={},s;const r=[],a={model_provider:"openai"},i={};let o;if(t.type==="response.output_text.delta")e.push({type:"text",text:t.delta,index:t.content_index});else if(t.type==="response.output_text.annotation.added")e.push({type:"text",text:"",annotations:[t.annotation],index:t.content_index});else if(t.type==="response.output_item.added"&&t.item.type==="message")o=t.item.id;else if(t.type==="response.output_item.added"&&t.item.type==="function_call")r.push({type:"tool_call_chunk",name:t.item.name,args:t.item.arguments,id:t.item.call_id,index:t.output_index}),i[xt]={[t.item.call_id]:t.item.id};else if(t.type==="response.output_item.done"&&["web_search_call","file_search_call","computer_call","code_interpreter_call","mcp_call","mcp_list_tools","mcp_approval_request","image_generation_call","custom_tool_call"].includes(t.item.type))i.tool_outputs=[t.item];else if(t.type==="response.created")a.id=t.response.id,a.model_name=t.response.model,a.model=t.response.model;else if(t.type==="response.completed"){const c=wa(t.response);s=ya(t.response.usage),t.response.text?.format?.type==="json_schema"&&(i.parsed??=JSON.parse(c.text));for(const[l,m]of Object.entries(t.response))l!=="id"&&(a[l]=m)}else if(t.type==="response.function_call_arguments.delta"||t.type==="response.custom_tool_call_input.delta")r.push({type:"tool_call_chunk",args:t.delta,index:t.output_index});else if(t.type==="response.web_search_call.completed"||t.type==="response.file_search_call.completed")n={tool_outputs:{id:t.item_id,type:t.type.replace("response.","").replace(".completed",""),status:"completed"}};else if(t.type==="response.refusal.done")i.refusal=t.refusal;else if(t.type==="response.output_item.added"&&"item"in t&&t.item.type==="reasoning"){const c=t.item.summary?t.item.summary.map((l,m)=>({...l,index:m})):void 0;i.reasoning={id:t.item.id,type:t.item.type,...c?{summary:c}:{}}}else if(t.type==="response.reasoning_summary_part.added")i.reasoning={type:"reasoning",summary:[{...t.part,index:t.summary_index}]};else if(t.type==="response.reasoning_summary_text.delta")i.reasoning={type:"reasoning",summary:[{text:t.delta,type:"summary_text",index:t.summary_index}]};else return t.type==="response.image_generation_call.partial_image",null;return new Jt({text:e.map(c=>c.text).join(""),message:new cn({id:o,content:e,tool_call_chunks:r,usage_metadata:s,additional_kwargs:i,response_metadata:a}),generationInfo:n})},al=t=>{const e=ke.isInstance(t)&&t.response_metadata?.model_provider==="openai";function*n(){const s=xe(()=>{try{const f=Ue(t);return f==="system"||f==="developer"||f==="assistant"||f==="user"?f:"assistant"}catch{return"assistant"}});let r;const a=new Set,i=new Set,o=new Map,c=new Map;function*l(){if(!r)return;const f=r.content;(typeof f=="string"&&f.length>0||Array.isArray(f)&&f.length>0)&&(yield r),r=void 0}const m=f=>{r||(r={type:"message",role:s,content:[]}),typeof r.content=="string"?r.content=r.content.length>0?[{type:"input_text",text:r.content},...f]:[...f]:r.content.push(...f)},h=f=>{if(typeof f=="string")return f;try{return JSON.stringify(f??{})}catch{return"{}"}},p=f=>{const _=xe(()=>{const C=f.metadata?.detail;return C==="low"||C==="high"||C==="auto"?C:"auto"});if(f.fileId)return{type:"input_image",detail:_,file_id:f.fileId};if(f.url)return{type:"input_image",detail:_,image_url:f.url};if(f.data){const C=typeof f.data=="string"?f.data:Buffer.from(f.data).toString("base64"),I=f.mimeType??"image/png";return{type:"input_image",detail:_,image_url:`data:${I};base64,${C}`}}},d=f=>{const _=f.metadata?.filename??f.metadata?.name??f.metadata?.title;if(f.fileId&&typeof _=="string")return{type:"input_file",file_id:f.fileId,..._?{filename:_}:{}};if(f.url&&typeof _=="string")return{type:"input_file",file_url:f.url,..._?{filename:_}:{}};if(f.data&&typeof _=="string"){const C=typeof f.data=="string"?f.data:Buffer.from(f.data).toString("base64");return{type:"input_file",file_data:`data:${f.mimeType??"application/octet-stream"};base64,${C}`,..._?{filename:_}:{}}}},b=f=>{const _=xe(()=>{if(Array.isArray(f.summary)){const L=f.summary?.map(R=>R?.text).filter(R=>typeof R=="string")??[];if(L.length>0)return L}return f.reasoning?[f.reasoning]:[]}),C=_.length>0?_.map(J=>({type:"summary_text",text:J})):[{type:"summary_text",text:""}],I={type:"reasoning",id:f.id??"",summary:C};return f.reasoning&&(I.content=[{type:"reasoning_text",text:f.reasoning}]),I},w=f=>({type:"function_call",name:f.name??"",call_id:f.id??"",arguments:h(f.args)}),$=f=>{const _=h(f.output),C=f.status==="success"?"completed":f.status==="error"?"incomplete":void 0;return{type:"function_call_output",call_id:f.toolCallId??"",output:_,...C?{status:C}:{}}};for(const f of t.contentBlocks)if(f.type==="text")m([{type:"input_text",text:f.text}]);else if(f.type!=="invalid_tool_call"){if(f.type==="reasoning")yield*l(),yield b(f);else if(f.type==="tool_call"){yield*l();const _=f.id??"";_&&(a.add(_),o.delete(_)),yield w(f)}else if(f.type==="tool_call_chunk"){if(f.id){const _=o.get(f.id)??{name:f.name,args:[]};f.name&&(_.name=f.name),f.args&&_.args.push(f.args),o.set(f.id,_)}}else if(f.type==="server_tool_call"){yield*l();const _=f.id??"";_&&(i.add(_),c.delete(_)),yield w(f)}else if(f.type==="server_tool_call_chunk"){if(f.id){const _=c.get(f.id)??{name:f.name,args:[]};f.name&&(_.name=f.name),f.args&&_.args.push(f.args),c.set(f.id,_)}}else if(f.type==="server_tool_call_result")yield*l(),yield $(f);else if(f.type!=="audio")if(f.type==="file"){const _=d(f);_&&m([_])}else if(f.type==="image"){const _=p(f);_&&m([_])}else if(f.type==="video"){const _=d(f);_&&m([_])}else f.type==="text-plain"?f.text&&m([{type:"input_text",text:f.text}]):f.type==="non_standard"&&e&&(yield*l(),yield f.value)}yield*l();for(const[f,_]of o){if(!f||a.has(f))continue;const C=_.args.join("");!_.name&&!C||(yield{type:"function_call",call_id:f,name:_.name??"",arguments:C})}for(const[f,_]of c){if(!f||i.has(f))continue;const C=_.args.join("");!_.name&&!C||(yield{type:"function_call",call_id:f,name:_.name??"",arguments:C})}}return Array.from(n())},ks=({messages:t,zdrEnabled:e,model:n})=>t.flatMap(s=>{const r=s.response_metadata;if(r?.output_version==="v1")return al(s);const a=s.additional_kwargs;let i=Ue(s);if(i==="system"&&Be(n)&&(i="developer"),i==="function")throw new Error("Function messages are not supported in Responses API");if(i==="tool"){const o=s;return a?.type==="computer_call_output"?{type:"computer_call_output",output:(()=>{if(typeof o.content=="string")return{type:"computer_screenshot",image_url:o.content};if(Array.isArray(o.content)){const l=o.content.find(h=>h.type==="computer_screenshot");if(l)return l;const m=o.content.find(h=>h.type==="image_url");if(m)return{type:"computer_screenshot",image_url:typeof m.image_url=="string"?m.image_url:m.image_url.url}}throw new Error("Invalid computer call output")})(),call_id:o.tool_call_id}:o.additional_kwargs?.customTool?{type:"custom_tool_call_output",call_id:o.tool_call_id,output:o.content}:{type:"function_call_output",call_id:o.tool_call_id,id:o.id?.startsWith("fc_")?o.id:void 0,output:typeof o.content!="string"?JSON.stringify(o.content):o.content}}if(i==="assistant"){if(!e&&r?.output!=null&&Array.isArray(r?.output)&&r?.output.length>0&&r?.output.every(p=>"type"in p))return r?.output;const o=[];if(a?.reasoning&&!e){const p=sl(a.reasoning);o.push(p)}let{content:c}=s;a?.refusal&&(typeof c=="string"&&(c=[{type:"output_text",text:c,annotations:[]}]),c=[...c,{type:"refusal",refusal:a.refusal}]),(typeof c=="string"||c.length>0)&&o.push({type:"message",role:"assistant",...s.id&&!e&&s.id.startsWith("msg_")?{id:s.id}:{},content:xe(()=>typeof c=="string"?c:c.flatMap(p=>p.type==="text"?{type:"output_text",text:p.text,annotations:p.annotations??[]}:p.type==="output_text"||p.type==="refusal"?p:[]))});const l=a?.[xt];ke.isInstance(s)&&s.tool_calls?.length?o.push(...s.tool_calls.map(p=>Ka(p)?{type:"custom_tool_call",id:p.call_id,call_id:p.id??"",input:p.args.input,name:p.name}:{type:"function_call",name:p.name,arguments:JSON.stringify(p.args),call_id:p.id,...e?{}:{id:l?.[p.id]}})):a?.tool_calls&&o.push(...a.tool_calls.map(p=>({type:"function_call",name:p.function.name,call_id:p.id,arguments:p.function.arguments,...e?{}:{id:l?.[p.id]}})));const m=r?.output?.length?r?.output:a.tool_outputs,h=["computer_call","mcp_call","code_interpreter_call","image_generation_call"];if(m!=null){const d=m?.filter(b=>h.includes(b.type));d.length>0&&o.push(...d)}return o}if(i==="user"||i==="system"||i==="developer"){if(typeof s.content=="string")return{type:"message",role:i,content:s.content};const o=[],c=s.content.flatMap(l=>{if(l.type==="mcp_approval_response"&&o.push({type:"mcp_approval_response",approval_request_id:l.approval_request_id,approve:l.approve}),As(l))return Cs(l,ga);if(l.type==="text")return{type:"input_text",text:l.text};if(l.type==="image_url"){const m=xe(()=>{if(typeof l.image_url=="string")return l.image_url;if(typeof l.image_url=="object"&&l.image_url!==null&&"url"in l.image_url)return l.image_url.url}),h=xe(()=>{if(typeof l.image_url=="string")return"auto";if(typeof l.image_url=="object"&&l.image_url!==null&&"detail"in l.image_url)return l.image_url.detail});return{type:"input_image",image_url:m,detail:h}}return l.type==="input_text"||l.type==="input_image"||l.type==="input_file"?l:[]});return c.length>0&&o.push({type:"message",role:i,content:c}),o}return console.warn(`Unsupported role found when converting to OpenAI Responses API: ${i}`),[]});var il=class extends En{invocationParams(t){let e;t?.strict!==void 0?e=t.strict:this.supportsStrictToolCalling!==void 0&&(e=this.supportsStrictToolCalling);const n={model:this.model,temperature:this.temperature,top_p:this.topP,user:this.user,stream:this.streaming,previous_response_id:t?.previous_response_id,truncation:t?.truncation,include:t?.include,tools:t?.tools?.length?this._reduceChatOpenAITools(t.tools,{stream:this.streaming,strict:e}):void 0,tool_choice:qa(t?.tool_choice)?t?.tool_choice:(()=>{const r=Ps(t?.tool_choice);if(typeof r=="object"&&"type"in r){if(r.type==="function")return{type:"function",name:r.function.name};if(r.type==="allowed_tools")return{type:"allowed_tools",mode:r.allowed_tools.mode,tools:r.allowed_tools.tools};if(r.type==="custom")return{type:"custom",name:r.custom.name}}})(),text:(()=>{if(t?.text)return t.text;const r=this._getResponseFormat(t?.response_format);return r?.type==="json_schema"?r.json_schema.schema!=null?{format:{type:"json_schema",schema:r.json_schema.schema,description:r.json_schema.description,name:r.json_schema.name,strict:r.json_schema.strict},verbosity:t?.verbosity}:void 0:{format:r,verbosity:t?.verbosity}})(),parallel_tool_calls:t?.parallel_tool_calls,max_output_tokens:this.maxTokens===-1?void 0:this.maxTokens,prompt_cache_key:t?.promptCacheKey??this.promptCacheKey,...this.zdrEnabled?{store:!1}:{},...this.modelKwargs},s=this._getReasoningParams(t);return s!==void 0&&(n.reasoning=s),n}async _generate(t,e){const n=this.invocationParams(e);if(n.stream){const s=this._streamResponseChunks(t,e);let r;for await(const a of s)a.message.response_metadata={...a.generationInfo,...a.message.response_metadata},r=r?.concat(a)??a;return{generations:r?[r]:[],llmOutput:{estimatedTokenUsage:r?.message?.usage_metadata}}}else{const s=await this.completionWithRetry({input:ks({messages:t,zdrEnabled:this.zdrEnabled??!1,model:this.model}),...n,stream:!1},{signal:e?.signal,...e?.options});return{generations:[{text:s.output_text,message:wa(s)}],llmOutput:{id:s.id,estimatedTokenUsage:s.usage?{promptTokens:s.usage.input_tokens,completionTokens:s.usage.output_tokens,totalTokens:s.usage.total_tokens}:void 0}}}}async*_streamResponseChunks(t,e,n){const s=await this.completionWithRetry({...this.invocationParams(e),input:ks({messages:t,zdrEnabled:this.zdrEnabled??!1,model:this.model}),stream:!0},e);for await(const r of s){const a=rl(r);a!=null&&(yield a,await n?.handleLLMNewToken(a.text||"",{prompt:e.promptIndex??0,completion:0},void 0,void 0,void 0,{chunk:a}))}}async completionWithRetry(t,e){return this.caller.call(async()=>{const n=this._getClientOptions(e);try{return t.text?.format?.type==="json_schema"&&!t.stream?await this.client.responses.parse(t,n):await this.client.responses.create(t,n)}catch(s){throw _a(s)}})}_reduceChatOpenAITools(t,e){const n=[];for(const s of t)if(un(s))s.type==="image_generation"&&e?.stream&&(s.partial_images=1),n.push(s);else if(dt(s)){const r=s.metadata.customTool;n.push({type:"custom",name:r.name,description:r.description,format:r.format})}else Is(s)?n.push({type:"function",name:s.function.name,parameters:s.function.parameters,description:s.function.description,strict:e?.strict??null}):Es(s)&&n.push(Za(s));return n}},ol=class extends En{invocationParams(t,e){let n;t?.strict!==void 0?n=t.strict:this.supportsStrictToolCalling!==void 0&&(n=this.supportsStrictToolCalling);let s={};t?.stream_options!==void 0?s={stream_options:t.stream_options}:this.streamUsage&&(this.streaming||e?.streaming)&&(s={stream_options:{include_usage:!0}});const r={model:this.model,temperature:this.temperature,top_p:this.topP,frequency_penalty:this.frequencyPenalty,presence_penalty:this.presencePenalty,logprobs:this.logprobs,top_logprobs:this.topLogprobs,n:this.n,logit_bias:this.logitBias,stop:t?.stop??this.stopSequences,user:this.user,stream:this.streaming,functions:t?.functions,function_call:t?.function_call,tools:t?.tools?.length?t.tools.map(i=>this._convertChatOpenAIToolToCompletionsTool(i,{strict:n})):void 0,tool_choice:Ps(t?.tool_choice),response_format:this._getResponseFormat(t?.response_format),seed:t?.seed,...s,parallel_tool_calls:t?.parallel_tool_calls,...this.audio||t?.audio?{audio:this.audio||t?.audio}:{},...this.modalities||t?.modalities?{modalities:this.modalities||t?.modalities}:{},...this.modelKwargs,prompt_cache_key:t?.promptCacheKey??this.promptCacheKey,verbosity:t?.verbosity??this.verbosity};t?.prediction!==void 0&&(r.prediction=t.prediction),this.service_tier!==void 0&&(r.service_tier=this.service_tier),t?.service_tier!==void 0&&(r.service_tier=t.service_tier);const a=this._getReasoningParams(t);return a!==void 0&&a.effort!==void 0&&(r.reasoning_effort=a.effort),Be(r.model)?r.max_completion_tokens=this.maxTokens===-1?void 0:this.maxTokens:r.max_tokens=this.maxTokens===-1?void 0:this.maxTokens,r}async _generate(t,e,n){const s={},r=this.invocationParams(e),a=xs({messages:t,model:this.model});if(r.stream){const i=this._streamResponseChunks(t,e,n),o={};for await(const d of i){d.message.response_metadata={...d.generationInfo,...d.message.response_metadata};const b=d.generationInfo?.completion??0;o[b]===void 0?o[b]=d:o[b]=o[b].concat(d)}const c=Object.entries(o).sort(([d],[b])=>parseInt(d,10)-parseInt(b,10)).map(([d,b])=>b),{functions:l,function_call:m}=this.invocationParams(e),h=await this._getEstimatedTokenCountFromPrompt(t,l,m),p=await this._getNumTokensFromGenerations(c);return s.input_tokens=h,s.output_tokens=p,s.total_tokens=h+p,{generations:c,llmOutput:{estimatedTokenUsage:{promptTokens:s.input_tokens,completionTokens:s.output_tokens,totalTokens:s.total_tokens}}}}else{const i=await this.completionWithRetry({...r,stream:!1,messages:a},{signal:e?.signal,...e?.options}),{completion_tokens:o,prompt_tokens:c,total_tokens:l,prompt_tokens_details:m,completion_tokens_details:h}=i?.usage??{};o&&(s.output_tokens=(s.output_tokens??0)+o),c&&(s.input_tokens=(s.input_tokens??0)+c),l&&(s.total_tokens=(s.total_tokens??0)+l),(m?.audio_tokens!==null||m?.cached_tokens!==null)&&(s.input_token_details={...m?.audio_tokens!==null&&{audio:m?.audio_tokens},...m?.cached_tokens!==null&&{cache_read:m?.cached_tokens}}),(h?.audio_tokens!==null||h?.reasoning_tokens!==null)&&(s.output_token_details={...h?.audio_tokens!==null&&{audio:h?.audio_tokens},...h?.reasoning_tokens!==null&&{reasoning:h?.reasoning_tokens}});const p=[];for(const d of i?.choices??[]){const w={text:d.message?.content??"",message:this._convertCompletionsMessageToBaseMessage(d.message??{role:"assistant"},i)};w.generationInfo={...d.finish_reason?{finish_reason:d.finish_reason}:{},...d.logprobs?{logprobs:d.logprobs}:{}},Pa(w.message)&&(w.message.usage_metadata=s),w.message=new ke(Object.fromEntries(Object.entries(w.message).filter(([$])=>!$.startsWith("lc_")))),p.push(w)}return{generations:p,llmOutput:{tokenUsage:{promptTokens:s.input_tokens,completionTokens:s.output_tokens,totalTokens:s.total_tokens}}}}}async*_streamResponseChunks(t,e,n){const s=xs({messages:t,model:this.model}),r={...this.invocationParams(e,{streaming:!0}),messages:s,stream:!0};let a;const i=await this.completionWithRetry(r,e);let o;for await(const c of i){const l=c?.choices?.[0];if(c.usage&&(o=c.usage),!l)continue;const{delta:m}=l;if(!m)continue;const h=this._convertCompletionsDeltaToBaseMessageChunk(m,c,a);a=m.role??a;const p={prompt:e.promptIndex??0,completion:l.index??0};if(typeof h.content!="string"){console.log("[WARNING]: Received non-string content from OpenAI. This is currently not supported.");continue}const d={...p};l.finish_reason!=null&&(d.finish_reason=l.finish_reason,d.system_fingerprint=c.system_fingerprint,d.model_name=c.model,d.service_tier=c.service_tier),this.logprobs&&(d.logprobs=l.logprobs);const b=new Jt({message:h,text:h.content,generationInfo:d});yield b,await n?.handleLLMNewToken(b.text??"",p,void 0,void 0,void 0,{chunk:b})}if(o){const c={...o.prompt_tokens_details?.audio_tokens!==null&&{audio:o.prompt_tokens_details?.audio_tokens},...o.prompt_tokens_details?.cached_tokens!==null&&{cache_read:o.prompt_tokens_details?.cached_tokens}},l={...o.completion_tokens_details?.audio_tokens!==null&&{audio:o.completion_tokens_details?.audio_tokens},...o.completion_tokens_details?.reasoning_tokens!==null&&{reasoning:o.completion_tokens_details?.reasoning_tokens}};yield new Jt({message:new cn({content:"",response_metadata:{usage:{...o}},usage_metadata:{input_tokens:o.prompt_tokens,output_tokens:o.completion_tokens,total_tokens:o.total_tokens,...Object.keys(c).length>0&&{input_token_details:c},...Object.keys(l).length>0&&{output_token_details:l}}}),text:""})}if(e.signal?.aborted)throw new Error("AbortError")}async completionWithRetry(t,e){const n=this._getClientOptions(e),s=t.response_format&&t.response_format.type==="json_schema";return this.caller.call(async()=>{try{return s&&!t.stream?await this.client.chat.completions.parse(t,n):await this.client.chat.completions.create(t,n)}catch(r){throw _a(r)}})}_convertCompletionsDeltaToBaseMessageChunk(t,e,n){return el({delta:t,rawResponse:e,includeRawResponse:this.__includeRawResponse,defaultRole:n})}_convertCompletionsMessageToBaseMessage(t,e){return Yo({message:t,rawResponse:e,includeRawResponse:this.__includeRawResponse})}},Sl=class ba extends En{useResponsesApi=!1;responses;completions;get lc_serializable_keys(){return[...super.lc_serializable_keys,"useResponsesApi"]}get callKeys(){return[...super.callKeys,"useResponsesApi"]}constructor(e){super(e),this.fields=e,this.useResponsesApi=e?.useResponsesApi??!1,this.responses=e?.responses??new il(e),this.completions=e?.completions??new ol(e)}_useResponsesApi(e){const n=e?.tools?.some(un),s=e?.previous_response_id!=null||e?.text!=null||e?.truncation!=null||e?.include!=null||e?.reasoning?.summary!=null||this.reasoning?.summary!=null,r=e?.tools?.some(Es)||e?.tools?.some(dt);return this.useResponsesApi||n||s||r}getLsParams(e){const n=this._combineCallOptions(e);return this._useResponsesApi(e)?this.responses.getLsParams(n):this.completions.getLsParams(n)}invocationParams(e){const n=this._combineCallOptions(e);return this._useResponsesApi(e)?this.responses.invocationParams(n):this.completions.invocationParams(n)}async _generate(e,n,s){return this._useResponsesApi(n)?this.responses._generate(e,n):this.completions._generate(e,n,s)}async*_streamResponseChunks(e,n,s){if(this._useResponsesApi(n)){yield*this.responses._streamResponseChunks(e,this._combineCallOptions(n),s);return}yield*this.completions._streamResponseChunks(e,this._combineCallOptions(n),s)}withConfig(e){const n=new ba(this.fields);return n.defaultOptions={...this.defaultOptions,...e},n}};export{En as BaseChatOpenAI,Sl as ChatOpenAI,ol as ChatOpenAICompletions,il as ChatOpenAIResponses,A as OpenAIClient,Fa as getEndpoint,Ue as messageToOpenAIRole,Lo as toFile,_a as wrapOpenAIClientError};
|