@mcp-use/inspector 0.6.1-canary.0 → 0.6.1

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.
@@ -1,11 +1,11 @@
1
- import{C as js,s as Wa,r as qa,k as Ja,g as Ds,ax as Ka,_ as gn,l as zn,i as Oe,t as Ze,U as za,aa as Za,R as Ha,h as Fs,j as Bs,A as xe,T as ht,ay as Va,b as _n,az as Zn,aA as Xa,aB as Ga,aC as Qa,p as Hn,aD as Vn,aE as Ya,e as Xt,a6 as nt,au as ei,a8 as ti,a5 as ni,a9 as Xn,aF as Gt,a2 as si,ak as ri,aG as Bt,P as ai,aH as yn,aI as ii,D as oi,aJ as li,af as Gn,aK as Qn,aj as Yn,aL as ci,aM as ui}from"./index-Du-AzD1y.js";import{i as Us,c as di,O as Ws,d as hi,b as fi,a as qs,S as es,J as ts,R as ns,e as pi,f as mi,g as gi,h as _i,j as yi}from"./index-Cabcpqou.js";import{Z as A,o as wi,s as bi}from"./index-oGUCoBh7.js";import{t as Js,k as vi,q as ki,r as xi}from"./chunk-VL2OQCWN-t9vrh-pu.js";import"./embeddings-DRC9Cvzx.js";import"./index-DRz5BQNA.js";const ke=t=>t();function We(t){return t?!!(/^o\d/.test(t??"")||t.startsWith("gpt-5")&&!t.startsWith("gpt-5-chat")):!1}function Si(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 qe(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(!js.isInstance(t))throw new Error("Invalid generic chat message");return Si(t);default:throw new Error(`Unknown message type: ${e}`)}}function Ai(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 Ci(t,e){let n;return Us(t)?n=di(t):n=t,e?.strict!==void 0&&(n.function.strict=e.strict),n}function Oi(t){return t.anyOf!==void 0&&Array.isArray(t.anyOf)}function Ti(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(Ks(n.parameters,0)),e.push("}) => any;")):e.push(`type ${n.name} = () => any;`),e.push("");return e.push("} // namespace functions"),e.join(`
1
+ import{d as js,g as Ds,q as Wa,r as qa,s as Ja,l as Ka,O as Fs,u as za,f as Bs,v as Za,_ as gn,m as Ha,n as zn,i as Oe,h as Us,S as Zn,J as Hn,t as Ze,w as Va,x as Xa,R as Vn,o as Ga,j as Ws,k as qs,b as xe,T as ht,y as Qa,c as _n,z as Xn,F as Ya,D as ei,E as ti,p as Gn,G as Qn,I as ni,C as Xt,K as si,L as nt,M as ri,N as ai,P as ii,Q as Yn,U as oi,V as li,W as ci,X as Gt,Y as ui,Z as di,$ as hi,a0 as Bt,a1 as fi,a2 as yn,a3 as pi,a4 as mi,a5 as gi,a6 as es,a7 as ts,a8 as ns,a9 as _i,aa as yi}from"./index-CB1s6Wr6.js";import{Z as A,o as wi,s as bi}from"./index-DUf1336L.js";import{t as Js,i as vi,q as ki,r as xi}from"./chunk-VL2OQCWN-iRVOQjqe.js";import"./embeddings-Dcyp0Vlp.js";import"./index-DRz5BQNA.js";const ke=t=>t();function We(t){return t?!!(/^o\d/.test(t??"")||t.startsWith("gpt-5")&&!t.startsWith("gpt-5-chat")):!1}function Si(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 qe(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(!js.isInstance(t))throw new Error("Invalid generic chat message");return Si(t);default:throw new Error(`Unknown message type: ${e}`)}}function Ai(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 Ci(t,e){let n;return Ds(t)?n=Wa(t):n=t,e?.strict!==void 0&&(n.function.strict=e.strict),n}function Oi(t){return t.anyOf!==void 0&&Array.isArray(t.anyOf)}function Ti(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(Ks(n.parameters,0)),e.push("}) => any;")):e.push(`type ${n.name} = () => any;`),e.push("");return e.push("} // namespace functions"),e.join(`
2
2
  `)}function Ks(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}: ${ft(r,e)},`):n.push(`${s}?: ${ft(r,e)},`);return n.map(s=>" ".repeat(e)+s).join(`
3
3
  `)}function ft(t,e){if(Oi(t))return t.anyOf.map(n=>ft(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["{",Ks(t,e+2),"}"].join(`
4
4
  `);case"array":return t.items?`${ft(t.items,e)}[]`:"any[]";default:return""}}function zs(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 wn(t){return"type"in t&&t.type!=="function"}function Ii(t){return t!=null&&typeof t=="object"&&"type"in t&&t.type!=="function"}function pt(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 Zs(t){return"type"in t&&t.type==="custom"&&"custom"in t&&typeof t.custom=="object"&&t.custom!==null}function Pi(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 Ri(t){return t.type==="tool_call"&&"isCustomTool"in t&&t.isCustomTool===!0}function $i(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 Ei(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 Qt(t){return typeof t=="object"&&t!==null&&("name"in t&&t.name==="AbortError"||"message"in t&&String(t.message).includes("FetchRequestCanceledException"))}const Yt=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 k extends Error{}class q extends k{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 Ot({message:s,cause:Yt(n)});const a=n?.error;return e===400?new Hs(e,a,s,r):e===401?new Vs(e,a,s,r):e===403?new Xs(e,a,s,r):e===404?new Gs(e,a,s,r):e===409?new Qs(e,a,s,r):e===422?new Ys(e,a,s,r):e===429?new er(e,a,s,r):e>=500?new tr(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 Ot extends q{constructor({message:e,cause:n}){super(void 0,void 0,e||"Connection error.",void 0),n&&(this.cause=n)}}class Tt extends Ot{constructor({message:e}={}){super({message:e??"Request timed out."})}}class Hs extends q{}class Vs extends q{}class Xs extends q{}class Gs extends q{}class Qs extends q{}class Ys extends q{}class er extends q{}class tr extends q{}class nr extends k{constructor(){super("Could not parse response content as the length limit was reached")}}class sr extends k{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}class Te extends Error{constructor(e){super(e)}}function mt(t){return t!==void 0&&"function"in t&&t.function!==void 0}function Mi(t,e){const n={...t};return Object.defineProperties(n,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:e,enumerable:!1}}),n}function bn(t){return t?.$brand==="auto-parseable-response-format"}function Je(t){return t?.$brand==="auto-parseable-tool"}function Ni(t,e){return!e||!rr(e)?{...t,choices:t.choices.map(n=>(ar(n.message.tool_calls),{...n,message:{...n.message,parsed:null,...n.message.tool_calls?{tool_calls:n.message.tool_calls}:void 0}}))}:vn(t,e)}function vn(t,e){const n=t.choices.map(s=>{if(s.finish_reason==="length")throw new nr;if(s.finish_reason==="content_filter")throw new sr;return ar(s.message.tool_calls),{...s,message:{...s.message,...s.message.tool_calls?{tool_calls:s.message.tool_calls?.map(r=>ji(e,r))??void 0}:void 0,parsed:s.message.content&&!s.message.refusal?Li(e,s.message.content):null}}});return{...t,choices:n}}function Li(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 ji(t,e){const n=t.tools?.find(s=>mt(s)&&s.function?.name===e.function.name);return{...e,function:{...e.function,parsed_arguments:Je(n)?n.$parseRaw(e.function.arguments):n?.function.strict?JSON.parse(e.function.arguments):null}}}function Di(t,e){if(!t||!("tools"in t)||!t.tools)return!1;const n=t.tools?.find(s=>mt(s)&&s.function?.name===e.function.name);return mt(n)&&(Je(n)||n?.function.strict||!1)}function rr(t){return bn(t.response_format)?!0:t.tools?.some(e=>Je(e)||e.type==="function"&&e.function.strict===!0)??!1}function ar(t){for(const e of t||[])if(e.type!=="function")throw new k(`Currently only \`function\` tool calls are supported; Received \`${e.type}\``)}function Fi(t){for(const e of t??[]){if(e.type!=="function")throw new k(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)throw new k(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}const Bi=Symbol("Let zodToJsonSchema decide on which parser to use"),ss={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"},Ui=t=>typeof t=="string"?{...ss,basePath:["#"],definitions:{},name:t}:{...ss,basePath:["#"],definitions:{},...t},en=t=>"_def"in t?t._def:t;function Wi(t){if(!t)return!0;for(const e in t)return!1;return!0}const qi=t=>{const e=Ui(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])=>[en(r),{def:en(r),path:[...e.basePath,e.definitionPath,s],jsonSchema:void 0}]))}};function ir(t,e,n,s){s?.errorMessages&&n&&(t.errorMessage={...t.errorMessage,[e]:n})}function P(t,e,n,s,r){t[e]=n,ir(t,e,s,r)}function Ji(){return{}}function Ki(t,e){const n={type:"array"};return t.type?._def?.typeName!==A.ZodAny&&(n.items=T(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&P(n,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&P(n,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(P(n,"minItems",t.exactLength.value,t.exactLength.message,e),P(n,"maxItems",t.exactLength.value,t.exactLength.message,e)),n}function zi(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?P(n,"minimum",s.value,s.message,e):P(n,"exclusiveMinimum",s.value,s.message,e):(s.inclusive||(n.exclusiveMinimum=!0),P(n,"minimum",s.value,s.message,e));break;case"max":e.target==="jsonSchema7"?s.inclusive?P(n,"maximum",s.value,s.message,e):P(n,"exclusiveMaximum",s.value,s.message,e):(s.inclusive||(n.exclusiveMaximum=!0),P(n,"maximum",s.value,s.message,e));break;case"multipleOf":P(n,"multipleOf",s.value,s.message,e);break}return n}function Zi(){return{type:"boolean"}}function Hi(t,e){return T(t.type._def,e)}const Vi=(t,e)=>T(t.innerType._def,e);function or(t,e,n){const s=n??e.dateStrategy;if(Array.isArray(s))return{anyOf:s.map((r,a)=>or(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 Xi(t,e)}}const Xi=(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":P(n,"minimum",s.value,s.message,e);break;case"max":P(n,"maximum",s.value,s.message,e);break}return n};function Gi(t,e){return{...T(t.innerType._def,e),default:t.defaultValue()}}function Qi(t,e,n){return e.effectStrategy==="input"?T(t.schema._def,e,n):{}}function Yi(t){return{type:"string",enum:[...t.values]}}const eo=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function to(t,e){const n=[T(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),T(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(eo(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 no(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 Ut;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:()=>(Ut===void 0&&(Ut=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Ut),base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/};function lr(t,e){const n={type:"string"};function s(r){return e.patternStrategy==="escape"?so(r):r}if(t.checks)for(const r of t.checks)switch(r.kind){case"min":P(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,r.message,e);break;case"max":P(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":P(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,r.message,e),P(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":{P(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 so=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}}})):P(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:rs(e,s),...n&&s.errorMessages&&{errorMessage:{pattern:n}}})):P(t,"pattern",rs(e,s),n,s)},rs=(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 cr(t,e){if(e.target==="openApi3"&&t.keyType?._def.typeName===A.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((s,r)=>({...s,[r]:T(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",r]})??{}}),{}),additionalProperties:!1};const n={type:"object",additionalProperties:T(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??{}};if(e.target==="openApi3")return n;if(t.keyType?._def.typeName===A.ZodString&&t.keyType._def.checks?.length){const s=Object.entries(lr(t.keyType._def,e)).reduce((r,[a,i])=>a==="type"?r:{...r,[a]:i},{});return{...n,propertyNames:s}}else if(t.keyType?._def.typeName===A.ZodEnum)return{...n,propertyNames:{enum:t.keyType._def.values}};return n}function ro(t,e){if(e.mapStrategy==="record")return cr(t,e);const n=T(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},s=T(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 ao(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 io(){return{not:{}}}function oo(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}const gt={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function lo(t,e){if(e.target==="openApi3")return as(t,e);const n=t.options instanceof Map?Array.from(t.options.values()):t.options;if(n.every(s=>s._def.typeName in gt&&(!s._def.checks||!s._def.checks.length))){const s=n.reduce((r,a)=>{const i=gt[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 as(t,e)}const as=(t,e)=>{const n=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((s,r)=>T(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 co(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:gt[t.innerType._def.typeName],nullable:!0}:{type:[gt[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){const s=T(t.innerType._def,{...e,currentPath:[...e.currentPath]});return s&&"$ref"in s?{allOf:[s],nullable:!0}:s&&{...s,nullable:!0}}const n=T(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}function uo(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",ir(n,"type",s.message,e);break;case"min":e.target==="jsonSchema7"?s.inclusive?P(n,"minimum",s.value,s.message,e):P(n,"exclusiveMinimum",s.value,s.message,e):(s.inclusive||(n.exclusiveMinimum=!0),P(n,"minimum",s.value,s.message,e));break;case"max":e.target==="jsonSchema7"?s.inclusive?P(n,"maximum",s.value,s.message,e):P(n,"exclusiveMaximum",s.value,s.message,e):(s.inclusive||(n.exclusiveMaximum=!0),P(n,"maximum",s.value,s.message,e));break;case"multipleOf":P(n,"multipleOf",s.value,s.message,e);break}return n}function ho(t,e){return e.removeAdditionalStrategy==="strict"?t.catchall._def.typeName==="ZodNever"?t.unknownKeys!=="strict":T(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0:t.catchall._def.typeName==="ZodNever"?t.unknownKeys==="passthrough":T(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0}function fo(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=T(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:ho(t,e)};return n.required.length||delete n.required,n}const po=(t,e)=>{if(e.propertyPath&&e.currentPath.slice(0,e.propertyPath.length).toString()===e.propertyPath.toString())return T(t.innerType._def,{...e,currentPath:e.currentPath});const n=T(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return n?{anyOf:[{not:{}},n]}:{}},mo=(t,e)=>{if(e.pipeStrategy==="input")return T(t.in._def,e);if(e.pipeStrategy==="output")return T(t.out._def,e);const n=T(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),s=T(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",n?"1":"0"]});return{allOf:[n,s].filter(r=>r!==void 0)}};function go(t,e){return T(t.type._def,e)}function _o(t,e){const s={type:"array",uniqueItems:!0,items:T(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&P(s,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&P(s,"maxItems",t.maxSize.value,t.maxSize.message,e),s}function yo(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((n,s)=>T(n._def,{...e,currentPath:[...e.currentPath,"items",`${s}`]})).reduce((n,s)=>s===void 0?n:[...n,s],[]),additionalItems:T(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((n,s)=>T(n._def,{...e,currentPath:[...e.currentPath,"items",`${s}`]})).reduce((n,s)=>s===void 0?n:[...n,s],[])}}function wo(){return{not:{}}}function bo(){return{}}const vo=(t,e)=>T(t.innerType._def,e);function T(t,e,n=!1){const s=e.seen.get(t);if(e.override){const i=e.override?.(t,e,s,n);if(i!==Bi)return i}if(s&&!n){const i=ko(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=So(t,t.typeName,e,n);return a&&Ao(t,e,a),r.jsonSchema=a,a}const ko=(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:xo(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}},xo=(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("/")},So=(t,e,n,s)=>{switch(e){case A.ZodString:return lr(t,n);case A.ZodNumber:return uo(t,n);case A.ZodObject:return fo(t,n);case A.ZodBigInt:return zi(t,n);case A.ZodBoolean:return Zi();case A.ZodDate:return or(t,n);case A.ZodUndefined:return wo();case A.ZodNull:return oo(n);case A.ZodArray:return Ki(t,n);case A.ZodUnion:case A.ZodDiscriminatedUnion:return lo(t,n);case A.ZodIntersection:return to(t,n);case A.ZodTuple:return yo(t,n);case A.ZodRecord:return cr(t,n);case A.ZodLiteral:return no(t,n);case A.ZodEnum:return Yi(t);case A.ZodNativeEnum:return ao(t);case A.ZodNullable:return co(t,n);case A.ZodOptional:return po(t,n);case A.ZodMap:return ro(t,n);case A.ZodSet:return _o(t,n);case A.ZodLazy:return T(t.getter()._def,n);case A.ZodPromise:return go(t,n);case A.ZodNaN:case A.ZodNever:return io();case A.ZodEffects:return Qi(t,n,s);case A.ZodAny:return Ji();case A.ZodUnknown:return bo();case A.ZodDefault:return Gi(t,n);case A.ZodBranded:return Hi(t,n);case A.ZodReadonly:return vo(t,n);case A.ZodCatch:return Vi(t,n);case A.ZodPipeline:return mo(t,n);case A.ZodFunction:case A.ZodVoid:case A.ZodSymbol:return;default:return(r=>{})()}},Ao=(t,e,n)=>(t.description&&(n.description=t.description,e.markdownDescription&&(n.markdownDescription=t.description)),n),Co=(t,e)=>{const n=qi(e),s=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,r=T(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(Wi(n.definitions))return;const c={},l=new Set;for(let h=0;h<500;h++){const u=Object.entries(n.definitions).filter(([p])=>!l.has(p));if(u.length===0)break;for(const[p,d]of u)c[p]=T(en(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 Oo(t,e){return!e||!Io(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)}:ur(t,e)}function ur(t,e){const n=t.output.map(r=>{if(r.type==="function_call")return{...r,parsed_arguments:$o(e,r)};if(r.type==="message"){const a=r.content.map(i=>i.type==="output_text"?{...i,parsed:To(e,i.text)}:i);return{...r,content:a}}return r}),s=Object.assign({},t,{output:n});return Object.getOwnPropertyDescriptor(t,"output_text")||tn(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 To(t,e){return t.text?.format?.type!=="json_schema"?null:"$parseRaw"in t.text?.format?(t.text?.format).$parseRaw(e):JSON.parse(e)}function Io(t){return!!bn(t.text?.format)}function Po(t){return t?.$brand==="auto-parseable-tool"}function Ro(t,e){return t.find(n=>n.type==="function"&&n.name===e)}function $o(t,e){const n=Ro(t.tools??[],e.name);return{...e,...e,parsed_arguments:Po(n)?n.$parseRaw(e.arguments):n?.strict?JSON.parse(e.arguments):null}}function tn(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 Eo(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 nn(t){if(typeof t=="boolean")return!1;if(t.type==="null")return!0;for(const e of t.oneOf??[])if(nn(e))return!0;for(const e of t.anyOf??[])if(nn(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(!nn(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 h=t.allOf;if(Array.isArray(h))if(h.length===1){const p=re(h[0],[...e,"allOf","0"],n);Object.assign(t,p),delete t.allOf}else t.allOf=h.map((p,d)=>re(p,[...e,"allOf",String(d)],n));t.default===null&&delete t.default;const u=t.$ref;if(u&&No(t,1)){if(typeof u!="string")throw new TypeError(`Received non-string $ref - ${u}; path=${e.join("/")}`);const p=Mo(n,u);if(typeof p=="boolean")throw new Error(`Expected \`$ref: ${u}\` to resolve to an object schema but got boolean`);if(!ce(p))throw new Error(`Expected \`$ref: ${u}\` 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 Mo(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 No(t,e){let n=0;for(const s in t)if(n++,n>e)return!0;return!1}function Lo(t,e){return Co(t,{openaiStrictMode:!0,name:e.name,nameStrategy:"duplicate-ref",$refStrategy:"extract-to-root",nullableStrategy:"property"})}function jo(t){return Eo(Js(t,{target:"draft-7"}))}function Do(t){return"_zod"in t}function Fo(t,e,n){return Mi({type:"json_schema",json_schema:{...n,name:e,strict:!0,schema:Do(t)?jo(t):Lo(t,{name:e})}},s=>t.parse(JSON.parse(s)))}const is=["jsonSchema","functionCalling","jsonMode"];function Bo(t,e){if(typeof e<"u"&&!is.includes(e))throw new Error(`Invalid method: ${e}. Supported methods are: ${is.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 Uo(t,e){const n={...t};return Object.defineProperties(n,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:e,enumerable:!1}}),n}function Wo(t,e,n){if(Wa(t))return Fo(t,e,n);if(qa(t))return Uo({type:"json_schema",json_schema:{...n,name:e,strict:!0,schema:Js(t,{cycles:"ref",reused:"ref",override(s){s.jsonSchema.title=e}})}},s=>vi(t,JSON.parse(s)));throw new Error("Unsupported schema response format")}function qo(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 x(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 f(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 dr=function(){const{crypto:t}=globalThis;if(t?.randomUUID)return dr=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 Jo=/^[a-z][a-z0-9+.-]*:/i,Ko=t=>Jo.test(t);let z=t=>(z=Array.isArray,z(t)),os=z;function hr(t){return typeof t!="object"?{}:t??{}}function zo(t){if(!t)return!0;for(const e in t)return!1;return!0}function Zo(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function Wt(t){return t!=null&&typeof t=="object"&&!Array.isArray(t)}const Ho=(t,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new k(`${t} must be an integer`);if(e<0)throw new k(`${t} must be a positive integer`);return e},Vo=t=>{try{return JSON.parse(t)}catch{return}},Ke=t=>new Promise(e=>setTimeout(e,t)),ye="6.8.1",Xo=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function Go(){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 Qo=()=>{const t=Go();if(t==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ye,"X-Stainless-OS":cs(Deno.build.os),"X-Stainless-Arch":ls(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":cs(globalThis.process.platform??"unknown"),"X-Stainless-Arch":ls(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};const e=Yo();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 Yo(){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 ls=t=>t==="x32"?"x32":t==="x86_64"||t==="x64"?"x64":t==="arm"?"arm":t==="aarch64"||t==="arm64"?"arm64":t?`other:${t}`:"unknown",cs=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 us;const el=()=>us??(us=Qo());function tl(){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 fr(...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 pr(t){let e=Symbol.asyncIterator in t?t[Symbol.asyncIterator]():t[Symbol.iterator]();return fr({start(){},async pull(n){const{done:s,value:r}=await e.next();s?n.close():n.enqueue(r)},async cancel(){await e.return?.()}})}function mr(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 nl(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 sl=({headers:t,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)}),gr="RFC3986",_r=t=>String(t),ds={RFC1738:t=>String(t).replace(/%20/g,"+"),RFC3986:_r},rl="RFC1738";let sn=(t,e)=>(sn=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),sn(t,e));const ee=(()=>{const t=[];for(let e=0;e<256;++e)t.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return t})(),qt=1024,al=(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+=qt){const c=a.length>=qt?a.slice(o,o+qt):a,l=[];for(let h=0;h<c.length;++h){let u=c.charCodeAt(h);if(u===45||u===46||u===95||u===126||u>=48&&u<=57||u>=65&&u<=90||u>=97&&u<=122||r===rl&&(u===40||u===41)){l[l.length]=c.charAt(h);continue}if(u<128){l[l.length]=ee[u];continue}if(u<2048){l[l.length]=ee[192|u>>6]+ee[128|u&63];continue}if(u<55296||u>=57344){l[l.length]=ee[224|u>>12]+ee[128|u>>6&63]+ee[128|u&63];continue}h+=1,u=65536+((u&1023)<<10|c.charCodeAt(h)&1023),l[l.length]=ee[240|u>>18]+ee[128|u>>12&63]+ee[128|u>>6&63]+ee[128|u&63]}i+=l.join("")}return i};function il(t){return!t||typeof t!="object"?!1:!!(t.constructor&&t.constructor.isBuffer&&t.constructor.isBuffer(t))}function hs(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 yr={brackets(t){return String(t)+"[]"},comma:"comma",indices(t,e){return String(t)+"["+e+"]"},repeat(t){return String(t)}},wr=function(t,e){Array.prototype.push.apply(t,z(e)?e:[e])};let fs;const L={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:al,encodeValuesOnly:!1,format:gr,formatter:_r,indices:!1,serializeDate(t){return(fs??(fs=Function.prototype.call.bind(Date.prototype.toISOString)))(t)},skipNulls:!1,strictNullHandling:!1};function ol(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"||typeof t=="symbol"||typeof t=="bigint"}const Jt={};function br(t,e,n,s,r,a,i,o,c,l,h,u,p,d,y,w,O,m){let g=t,S=m,I=0,J=!1;for(;(S=S.get(Jt))!==void 0&&!J;){const $=S.get(t);if(I+=1,typeof $<"u"){if($===I)throw new RangeError("Cyclic object value");J=!0}typeof S.get(Jt)>"u"&&(I=0)}if(typeof l=="function"?g=l(e,g):g instanceof Date?g=p?.(g):n==="comma"&&z(g)&&(g=hs(g,function($){return $ instanceof Date?p?.($):$})),g===null){if(a)return c&&!w?c(e,L.encoder,O,"key",d):e;g=""}if(ol(g)||il(g)){if(c){const $=w?e:c(e,L.encoder,O,"key",d);return[y?.($)+"="+y?.(c(g,L.encoder,O,"value",d))]}return[y?.(e)+"="+y?.(String(g))]}const j=[];if(typeof g>"u")return j;let R;if(n==="comma"&&z(g))w&&c&&(g=hs(g,c)),R=[{value:g.length>0?g.join(",")||null:void 0}];else if(z(l))R=l;else{const $=Object.keys(g);R=h?$.sort(h):$}const B=o?String(e).replace(/\./g,"%2E"):String(e),D=s&&z(g)&&g.length===1?B+"[]":B;if(r&&z(g)&&g.length===0)return D+"[]";for(let $=0;$<R.length;++$){const M=R[$],Jn=typeof M=="object"&&typeof M.value<"u"?M.value:g[M];if(i&&Jn===null)continue;const Ft=u&&o?M.replace(/\./g,"%2E"):M,Ua=z(g)?typeof n=="function"?n(D,Ft):D:D+(u?"."+Ft:"["+Ft+"]");m.set(t,I);const Kn=new WeakMap;Kn.set(Jt,m),wr(j,br(Jn,Ua,n,s,r,a,i,o,n==="comma"&&w&&z(g)?null:c,l,h,u,p,d,y,w,O,Kn))}return j}function ll(t=L){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||L.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=gr;if(typeof t.format<"u"){if(!sn(ds,t.format))throw new TypeError("Unknown format option provided.");n=t.format}const s=ds[n];let r=L.filter;(typeof t.filter=="function"||z(t.filter))&&(r=t.filter);let a;if(t.arrayFormat&&t.arrayFormat in yr?a=t.arrayFormat:"indices"in t?a=t.indices?"indices":"repeat":a=L.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:L.allowDots:!!t.allowDots;return{addQueryPrefix:typeof t.addQueryPrefix=="boolean"?t.addQueryPrefix:L.addQueryPrefix,allowDots:i,allowEmptyArrays:typeof t.allowEmptyArrays=="boolean"?!!t.allowEmptyArrays:L.allowEmptyArrays,arrayFormat:a,charset:e,charsetSentinel:typeof t.charsetSentinel=="boolean"?t.charsetSentinel:L.charsetSentinel,commaRoundTrip:!!t.commaRoundTrip,delimiter:typeof t.delimiter>"u"?L.delimiter:t.delimiter,encode:typeof t.encode=="boolean"?t.encode:L.encode,encodeDotInKeys:typeof t.encodeDotInKeys=="boolean"?t.encodeDotInKeys:L.encodeDotInKeys,encoder:typeof t.encoder=="function"?t.encoder:L.encoder,encodeValuesOnly:typeof t.encodeValuesOnly=="boolean"?t.encodeValuesOnly:L.encodeValuesOnly,filter:r,format:n,formatter:s,serializeDate:typeof t.serializeDate=="function"?t.serializeDate:L.serializeDate,skipNulls:typeof t.skipNulls=="boolean"?t.skipNulls:L.skipNulls,sort:typeof t.sort=="function"?t.sort:null,strictNullHandling:typeof t.strictNullHandling=="boolean"?t.strictNullHandling:L.strictNullHandling}}function cl(t,e={}){let n=t;const s=ll(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=yr[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||wr(i,br(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 h=i.join(s.delimiter);let u=s.addQueryPrefix===!0?"?":"";return s.charsetSentinel&&(s.charset==="iso-8859-1"?u+="utf8=%26%2310003%3B&":u+="utf8=%E2%9C%93&"),h.length>0?u+h:""}function ul(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 ps;function kn(t){let e;return(ps??(e=new globalThis.TextEncoder,ps=e.encode.bind(e)))(t)}let ms;function gs(t){let e;return(ms??(e=new globalThis.TextDecoder,ms=e.decode.bind(e)))(t)}var Z,H;class It{constructor(){Z.set(this,void 0),H.set(this,void 0),x(this,Z,new Uint8Array),x(this,H,null)}decode(e){if(e==null)return[];const n=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?kn(e):e;x(this,Z,ul([f(this,Z,"f"),n]));const s=[];let r;for(;(r=dl(f(this,Z,"f"),f(this,H,"f")))!=null;){if(r.carriage&&f(this,H,"f")==null){x(this,H,r.index);continue}if(f(this,H,"f")!=null&&(r.index!==f(this,H,"f")+1||r.carriage)){s.push(gs(f(this,Z,"f").subarray(0,f(this,H,"f")-1))),x(this,Z,f(this,Z,"f").subarray(f(this,H,"f"))),x(this,H,null);continue}const a=f(this,H,"f")!==null?r.preceding-1:r.preceding,i=gs(f(this,Z,"f").subarray(0,a));s.push(i),x(this,Z,f(this,Z,"f").subarray(r.index)),x(this,H,null)}return s}flush(){return f(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 cr(t,e){if(e.target==="openApi3"&&t.keyType?._def.typeName===A.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((s,r)=>({...s,[r]:T(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",r]})??{}}),{}),additionalProperties:!1};const n={type:"object",additionalProperties:T(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??{}};if(e.target==="openApi3")return n;if(t.keyType?._def.typeName===A.ZodString&&t.keyType._def.checks?.length){const s=Object.entries(lr(t.keyType._def,e)).reduce((r,[a,i])=>a==="type"?r:{...r,[a]:i},{});return{...n,propertyNames:s}}else if(t.keyType?._def.typeName===A.ZodEnum)return{...n,propertyNames:{enum:t.keyType._def.values}};return n}function ro(t,e){if(e.mapStrategy==="record")return cr(t,e);const n=T(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},s=T(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 ao(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 io(){return{not:{}}}function oo(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}const gt={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function lo(t,e){if(e.target==="openApi3")return as(t,e);const n=t.options instanceof Map?Array.from(t.options.values()):t.options;if(n.every(s=>s._def.typeName in gt&&(!s._def.checks||!s._def.checks.length))){const s=n.reduce((r,a)=>{const i=gt[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 as(t,e)}const as=(t,e)=>{const n=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((s,r)=>T(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 co(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:gt[t.innerType._def.typeName],nullable:!0}:{type:[gt[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){const s=T(t.innerType._def,{...e,currentPath:[...e.currentPath]});return s&&"$ref"in s?{allOf:[s],nullable:!0}:s&&{...s,nullable:!0}}const n=T(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}function uo(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",ir(n,"type",s.message,e);break;case"min":e.target==="jsonSchema7"?s.inclusive?P(n,"minimum",s.value,s.message,e):P(n,"exclusiveMinimum",s.value,s.message,e):(s.inclusive||(n.exclusiveMinimum=!0),P(n,"minimum",s.value,s.message,e));break;case"max":e.target==="jsonSchema7"?s.inclusive?P(n,"maximum",s.value,s.message,e):P(n,"exclusiveMaximum",s.value,s.message,e):(s.inclusive||(n.exclusiveMaximum=!0),P(n,"maximum",s.value,s.message,e));break;case"multipleOf":P(n,"multipleOf",s.value,s.message,e);break}return n}function ho(t,e){return e.removeAdditionalStrategy==="strict"?t.catchall._def.typeName==="ZodNever"?t.unknownKeys!=="strict":T(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0:t.catchall._def.typeName==="ZodNever"?t.unknownKeys==="passthrough":T(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0}function fo(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=T(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:ho(t,e)};return n.required.length||delete n.required,n}const po=(t,e)=>{if(e.propertyPath&&e.currentPath.slice(0,e.propertyPath.length).toString()===e.propertyPath.toString())return T(t.innerType._def,{...e,currentPath:e.currentPath});const n=T(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return n?{anyOf:[{not:{}},n]}:{}},mo=(t,e)=>{if(e.pipeStrategy==="input")return T(t.in._def,e);if(e.pipeStrategy==="output")return T(t.out._def,e);const n=T(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),s=T(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",n?"1":"0"]});return{allOf:[n,s].filter(r=>r!==void 0)}};function go(t,e){return T(t.type._def,e)}function _o(t,e){const s={type:"array",uniqueItems:!0,items:T(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&P(s,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&P(s,"maxItems",t.maxSize.value,t.maxSize.message,e),s}function yo(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((n,s)=>T(n._def,{...e,currentPath:[...e.currentPath,"items",`${s}`]})).reduce((n,s)=>s===void 0?n:[...n,s],[]),additionalItems:T(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((n,s)=>T(n._def,{...e,currentPath:[...e.currentPath,"items",`${s}`]})).reduce((n,s)=>s===void 0?n:[...n,s],[])}}function wo(){return{not:{}}}function bo(){return{}}const vo=(t,e)=>T(t.innerType._def,e);function T(t,e,n=!1){const s=e.seen.get(t);if(e.override){const i=e.override?.(t,e,s,n);if(i!==Bi)return i}if(s&&!n){const i=ko(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=So(t,t.typeName,e,n);return a&&Ao(t,e,a),r.jsonSchema=a,a}const ko=(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:xo(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}},xo=(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("/")},So=(t,e,n,s)=>{switch(e){case A.ZodString:return lr(t,n);case A.ZodNumber:return uo(t,n);case A.ZodObject:return fo(t,n);case A.ZodBigInt:return zi(t,n);case A.ZodBoolean:return Zi();case A.ZodDate:return or(t,n);case A.ZodUndefined:return wo();case A.ZodNull:return oo(n);case A.ZodArray:return Ki(t,n);case A.ZodUnion:case A.ZodDiscriminatedUnion:return lo(t,n);case A.ZodIntersection:return to(t,n);case A.ZodTuple:return yo(t,n);case A.ZodRecord:return cr(t,n);case A.ZodLiteral:return no(t,n);case A.ZodEnum:return Yi(t);case A.ZodNativeEnum:return ao(t);case A.ZodNullable:return co(t,n);case A.ZodOptional:return po(t,n);case A.ZodMap:return ro(t,n);case A.ZodSet:return _o(t,n);case A.ZodLazy:return T(t.getter()._def,n);case A.ZodPromise:return go(t,n);case A.ZodNaN:case A.ZodNever:return io();case A.ZodEffects:return Qi(t,n,s);case A.ZodAny:return Ji();case A.ZodUnknown:return bo();case A.ZodDefault:return Gi(t,n);case A.ZodBranded:return Hi(t,n);case A.ZodReadonly:return vo(t,n);case A.ZodCatch:return Vi(t,n);case A.ZodPipeline:return mo(t,n);case A.ZodFunction:case A.ZodVoid:case A.ZodSymbol:return;default:return(r=>{})()}},Ao=(t,e,n)=>(t.description&&(n.description=t.description,e.markdownDescription&&(n.markdownDescription=t.description)),n),Co=(t,e)=>{const n=qi(e),s=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,r=T(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(Wi(n.definitions))return;const c={},l=new Set;for(let h=0;h<500;h++){const u=Object.entries(n.definitions).filter(([p])=>!l.has(p));if(u.length===0)break;for(const[p,d]of u)c[p]=T(en(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 Oo(t,e){return!e||!Io(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)}:ur(t,e)}function ur(t,e){const n=t.output.map(r=>{if(r.type==="function_call")return{...r,parsed_arguments:$o(e,r)};if(r.type==="message"){const a=r.content.map(i=>i.type==="output_text"?{...i,parsed:To(e,i.text)}:i);return{...r,content:a}}return r}),s=Object.assign({},t,{output:n});return Object.getOwnPropertyDescriptor(t,"output_text")||tn(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 To(t,e){return t.text?.format?.type!=="json_schema"?null:"$parseRaw"in t.text?.format?(t.text?.format).$parseRaw(e):JSON.parse(e)}function Io(t){return!!bn(t.text?.format)}function Po(t){return t?.$brand==="auto-parseable-tool"}function Ro(t,e){return t.find(n=>n.type==="function"&&n.name===e)}function $o(t,e){const n=Ro(t.tools??[],e.name);return{...e,...e,parsed_arguments:Po(n)?n.$parseRaw(e.arguments):n?.strict?JSON.parse(e.arguments):null}}function tn(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 Eo(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 nn(t){if(typeof t=="boolean")return!1;if(t.type==="null")return!0;for(const e of t.oneOf??[])if(nn(e))return!0;for(const e of t.anyOf??[])if(nn(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(!nn(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 h=t.allOf;if(Array.isArray(h))if(h.length===1){const p=re(h[0],[...e,"allOf","0"],n);Object.assign(t,p),delete t.allOf}else t.allOf=h.map((p,d)=>re(p,[...e,"allOf",String(d)],n));t.default===null&&delete t.default;const u=t.$ref;if(u&&No(t,1)){if(typeof u!="string")throw new TypeError(`Received non-string $ref - ${u}; path=${e.join("/")}`);const p=Mo(n,u);if(typeof p=="boolean")throw new Error(`Expected \`$ref: ${u}\` to resolve to an object schema but got boolean`);if(!ce(p))throw new Error(`Expected \`$ref: ${u}\` 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 Mo(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 No(t,e){let n=0;for(const s in t)if(n++,n>e)return!0;return!1}function Lo(t,e){return Co(t,{openaiStrictMode:!0,name:e.name,nameStrategy:"duplicate-ref",$refStrategy:"extract-to-root",nullableStrategy:"property"})}function jo(t){return Eo(Js(t,{target:"draft-7"}))}function Do(t){return"_zod"in t}function Fo(t,e,n){return Mi({type:"json_schema",json_schema:{...n,name:e,strict:!0,schema:Do(t)?jo(t):Lo(t,{name:e})}},s=>t.parse(JSON.parse(s)))}const is=["jsonSchema","functionCalling","jsonMode"];function Bo(t,e){if(typeof e<"u"&&!is.includes(e))throw new Error(`Invalid method: ${e}. Supported methods are: ${is.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 Uo(t,e){const n={...t};return Object.defineProperties(n,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:e,enumerable:!1}}),n}function Wo(t,e,n){if(qa(t))return Fo(t,e,n);if(Ja(t))return Uo({type:"json_schema",json_schema:{...n,name:e,strict:!0,schema:Js(t,{cycles:"ref",reused:"ref",override(s){s.jsonSchema.title=e}})}},s=>vi(t,JSON.parse(s)));throw new Error("Unsupported schema response format")}function qo(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 x(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 f(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 dr=function(){const{crypto:t}=globalThis;if(t?.randomUUID)return dr=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 Jo=/^[a-z][a-z0-9+.-]*:/i,Ko=t=>Jo.test(t);let z=t=>(z=Array.isArray,z(t)),os=z;function hr(t){return typeof t!="object"?{}:t??{}}function zo(t){if(!t)return!0;for(const e in t)return!1;return!0}function Zo(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function Wt(t){return t!=null&&typeof t=="object"&&!Array.isArray(t)}const Ho=(t,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new k(`${t} must be an integer`);if(e<0)throw new k(`${t} must be a positive integer`);return e},Vo=t=>{try{return JSON.parse(t)}catch{return}},Ke=t=>new Promise(e=>setTimeout(e,t)),ye="6.8.1",Xo=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function Go(){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 Qo=()=>{const t=Go();if(t==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ye,"X-Stainless-OS":cs(Deno.build.os),"X-Stainless-Arch":ls(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":cs(globalThis.process.platform??"unknown"),"X-Stainless-Arch":ls(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};const e=Yo();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 Yo(){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 ls=t=>t==="x32"?"x32":t==="x86_64"||t==="x64"?"x64":t==="arm"?"arm":t==="aarch64"||t==="arm64"?"arm64":t?`other:${t}`:"unknown",cs=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 us;const el=()=>us??(us=Qo());function tl(){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 fr(...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 pr(t){let e=Symbol.asyncIterator in t?t[Symbol.asyncIterator]():t[Symbol.iterator]();return fr({start(){},async pull(n){const{done:s,value:r}=await e.next();s?n.close():n.enqueue(r)},async cancel(){await e.return?.()}})}function mr(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 nl(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 sl=({headers:t,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)}),gr="RFC3986",_r=t=>String(t),ds={RFC1738:t=>String(t).replace(/%20/g,"+"),RFC3986:_r},rl="RFC1738";let sn=(t,e)=>(sn=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),sn(t,e));const ee=(()=>{const t=[];for(let e=0;e<256;++e)t.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return t})(),qt=1024,al=(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+=qt){const c=a.length>=qt?a.slice(o,o+qt):a,l=[];for(let h=0;h<c.length;++h){let u=c.charCodeAt(h);if(u===45||u===46||u===95||u===126||u>=48&&u<=57||u>=65&&u<=90||u>=97&&u<=122||r===rl&&(u===40||u===41)){l[l.length]=c.charAt(h);continue}if(u<128){l[l.length]=ee[u];continue}if(u<2048){l[l.length]=ee[192|u>>6]+ee[128|u&63];continue}if(u<55296||u>=57344){l[l.length]=ee[224|u>>12]+ee[128|u>>6&63]+ee[128|u&63];continue}h+=1,u=65536+((u&1023)<<10|c.charCodeAt(h)&1023),l[l.length]=ee[240|u>>18]+ee[128|u>>12&63]+ee[128|u>>6&63]+ee[128|u&63]}i+=l.join("")}return i};function il(t){return!t||typeof t!="object"?!1:!!(t.constructor&&t.constructor.isBuffer&&t.constructor.isBuffer(t))}function hs(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 yr={brackets(t){return String(t)+"[]"},comma:"comma",indices(t,e){return String(t)+"["+e+"]"},repeat(t){return String(t)}},wr=function(t,e){Array.prototype.push.apply(t,z(e)?e:[e])};let fs;const L={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:al,encodeValuesOnly:!1,format:gr,formatter:_r,indices:!1,serializeDate(t){return(fs??(fs=Function.prototype.call.bind(Date.prototype.toISOString)))(t)},skipNulls:!1,strictNullHandling:!1};function ol(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"||typeof t=="symbol"||typeof t=="bigint"}const Jt={};function br(t,e,n,s,r,a,i,o,c,l,h,u,p,d,y,w,O,m){let g=t,S=m,I=0,J=!1;for(;(S=S.get(Jt))!==void 0&&!J;){const $=S.get(t);if(I+=1,typeof $<"u"){if($===I)throw new RangeError("Cyclic object value");J=!0}typeof S.get(Jt)>"u"&&(I=0)}if(typeof l=="function"?g=l(e,g):g instanceof Date?g=p?.(g):n==="comma"&&z(g)&&(g=hs(g,function($){return $ instanceof Date?p?.($):$})),g===null){if(a)return c&&!w?c(e,L.encoder,O,"key",d):e;g=""}if(ol(g)||il(g)){if(c){const $=w?e:c(e,L.encoder,O,"key",d);return[y?.($)+"="+y?.(c(g,L.encoder,O,"value",d))]}return[y?.(e)+"="+y?.(String(g))]}const j=[];if(typeof g>"u")return j;let R;if(n==="comma"&&z(g))w&&c&&(g=hs(g,c)),R=[{value:g.length>0?g.join(",")||null:void 0}];else if(z(l))R=l;else{const $=Object.keys(g);R=h?$.sort(h):$}const B=o?String(e).replace(/\./g,"%2E"):String(e),D=s&&z(g)&&g.length===1?B+"[]":B;if(r&&z(g)&&g.length===0)return D+"[]";for(let $=0;$<R.length;++$){const M=R[$],Jn=typeof M=="object"&&typeof M.value<"u"?M.value:g[M];if(i&&Jn===null)continue;const Ft=u&&o?M.replace(/\./g,"%2E"):M,Ua=z(g)?typeof n=="function"?n(D,Ft):D:D+(u?"."+Ft:"["+Ft+"]");m.set(t,I);const Kn=new WeakMap;Kn.set(Jt,m),wr(j,br(Jn,Ua,n,s,r,a,i,o,n==="comma"&&w&&z(g)?null:c,l,h,u,p,d,y,w,O,Kn))}return j}function ll(t=L){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||L.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=gr;if(typeof t.format<"u"){if(!sn(ds,t.format))throw new TypeError("Unknown format option provided.");n=t.format}const s=ds[n];let r=L.filter;(typeof t.filter=="function"||z(t.filter))&&(r=t.filter);let a;if(t.arrayFormat&&t.arrayFormat in yr?a=t.arrayFormat:"indices"in t?a=t.indices?"indices":"repeat":a=L.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:L.allowDots:!!t.allowDots;return{addQueryPrefix:typeof t.addQueryPrefix=="boolean"?t.addQueryPrefix:L.addQueryPrefix,allowDots:i,allowEmptyArrays:typeof t.allowEmptyArrays=="boolean"?!!t.allowEmptyArrays:L.allowEmptyArrays,arrayFormat:a,charset:e,charsetSentinel:typeof t.charsetSentinel=="boolean"?t.charsetSentinel:L.charsetSentinel,commaRoundTrip:!!t.commaRoundTrip,delimiter:typeof t.delimiter>"u"?L.delimiter:t.delimiter,encode:typeof t.encode=="boolean"?t.encode:L.encode,encodeDotInKeys:typeof t.encodeDotInKeys=="boolean"?t.encodeDotInKeys:L.encodeDotInKeys,encoder:typeof t.encoder=="function"?t.encoder:L.encoder,encodeValuesOnly:typeof t.encodeValuesOnly=="boolean"?t.encodeValuesOnly:L.encodeValuesOnly,filter:r,format:n,formatter:s,serializeDate:typeof t.serializeDate=="function"?t.serializeDate:L.serializeDate,skipNulls:typeof t.skipNulls=="boolean"?t.skipNulls:L.skipNulls,sort:typeof t.sort=="function"?t.sort:null,strictNullHandling:typeof t.strictNullHandling=="boolean"?t.strictNullHandling:L.strictNullHandling}}function cl(t,e={}){let n=t;const s=ll(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=yr[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||wr(i,br(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 h=i.join(s.delimiter);let u=s.addQueryPrefix===!0?"?":"";return s.charsetSentinel&&(s.charset==="iso-8859-1"?u+="utf8=%26%2310003%3B&":u+="utf8=%E2%9C%93&"),h.length>0?u+h:""}function ul(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 ps;function kn(t){let e;return(ps??(e=new globalThis.TextEncoder,ps=e.encode.bind(e)))(t)}let ms;function gs(t){let e;return(ms??(e=new globalThis.TextDecoder,ms=e.decode.bind(e)))(t)}var Z,H;class It{constructor(){Z.set(this,void 0),H.set(this,void 0),x(this,Z,new Uint8Array),x(this,H,null)}decode(e){if(e==null)return[];const n=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?kn(e):e;x(this,Z,ul([f(this,Z,"f"),n]));const s=[];let r;for(;(r=dl(f(this,Z,"f"),f(this,H,"f")))!=null;){if(r.carriage&&f(this,H,"f")==null){x(this,H,r.index);continue}if(f(this,H,"f")!=null&&(r.index!==f(this,H,"f")+1||r.carriage)){s.push(gs(f(this,Z,"f").subarray(0,f(this,H,"f")-1))),x(this,Z,f(this,Z,"f").subarray(f(this,H,"f"))),x(this,H,null);continue}const a=f(this,H,"f")!==null?r.preceding-1:r.preceding,i=gs(f(this,Z,"f").subarray(0,a));s.push(i),x(this,Z,f(this,Z,"f").subarray(r.index)),x(this,H,null)}return s}flush(){return f(this,Z,"f").length?this.decode(`
9
9
  `):[]}}Z=new WeakMap,H=new WeakMap;It.NEWLINE_CHARS=new Set([`
10
10
  `,"\r"]);It.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function dl(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 hl(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 _t={off:0,error:200,warn:300,info:400,debug:500},_s=(t,e,n)=>{if(t){if(Zo(_t,t))return t;U(n).warn(`${e} was set to ${JSON.stringify(t)}, expected one of ${JSON.stringify(Object.keys(_t))}`)}};function Ie(){}function He(t,e,n){return!e||_t[t]>_t[n]?Ie:e[t].bind(e)}const fl={error:Ie,warn:Ie,info:Ie,debug:Ie};let ys=new WeakMap;function U(t){const e=t.logger,n=t.logLevel??"off";if(!e)return fl;const s=ys.get(e);if(s&&s[0]===n)return s[1];const r={error:He("error",e,n),warn:He("warn",e,n),info:He("info",e,n),debug:He("debug",e,n)};return ys.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,x(this,Ce,s)}static fromSSEResponse(e,n,s){let r=!1;const a=s?U(s):console;async function*i(){if(r)throw new k("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");r=!0;let o=!1;try{for await(const c of pl(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(h){throw a.error("Could not parse message into JSON:",c.data),a.error("From chunk:",c.raw),h}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(h){throw console.error("Could not parse message into JSON:",c.data),console.error("From chunk:",c.raw),h}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(Qt(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 It,c=mr(e);for await(const l of c)for(const h of o.decode(l))yield h;for(const l of o.flush())yield l}async function*i(){if(r)throw new k("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(Qt(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,f(this,Ce,"f")),new ne(()=>r(n),this.controller,f(this,Ce,"f"))]}toReadableStream(){const e=this;let n;return fr({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=kn(JSON.stringify(r)+`
11
11
  `);s.enqueue(i)}catch(r){s.error(r)}},async cancel(){await n.return?.()}})}}async function*pl(t,e){if(!t.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new k("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 k("Attempted to iterate over a response with no body");const n=new gl,s=new It,r=mr(t.body);for await(const a of ml(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*ml(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"?kn(n):n;let r=new Uint8Array(e.length+s.length);r.set(e),r.set(s,e.length),e=r;let a;for(;(a=hl(e))!==-1;)yield e.slice(0,a),e=e.slice(a)}e.length>0&&(yield e)}class gl{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(`
@@ -27,14 +27,14 @@ 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??Un.DEFAULT_TIMEOUT,this.logger=o.logger??console;const c="warn";this.logLevel=c,this.logLevel=_s(o.logLevel,"ClientOptions.logLevel",this)??_s(ge("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??c,this.fetchOptions=o.fetchOptions,this.maxRetries=o.maxRetries??2,this.fetch=o.fetch??tl(),x(this,dt,sl),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 b([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return cl(e,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${ye}`}defaultIdempotencyKey(){return`stainless-node-retry-${dr()}`}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 k?s:new k(`Failed to get token from 'apiKey' function: ${s.message}`,{cause:s})}if(typeof n!="string"||!n)throw new k(`Expected 'apiKey' function argument to return a string but it returned ${n}`);return this.apiKey=n,!0}buildURL(e,n,s){const r=!f(this,pn,"m",Ia).call(this)&&s||this.baseURL,a=Ko(e)?new URL(e):new URL(r+(r.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),i=this.defaultQuery();return zo(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 Pt(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"),h=s===void 0?"":`, retryOf: ${s}`,u=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(Yt),y=Date.now();if(d instanceof globalThis.Error){const m=`retrying, ${n} attempts remaining`;if(r.signal?.aborted)throw new X;const g=Qt(d)||/timed? ?out/i.test(String(d)+("cause"in d?String(d.cause):""));if(n)return U(this).info(`[${l}] connection ${g?"timed out":"failed"} - ${m}`),U(this).debug(`[${l}] connection ${g?"timed out":"failed"} (${m})`,ue({retryOfRequestLogID:s,url:o,durationMs:y-u,message:d.message})),this.retryRequest(r,n,s??l);throw U(this).info(`[${l}] connection ${g?"timed out":"failed"} - error; no more retries left`),U(this).debug(`[${l}] connection ${g?"timed out":"failed"} (error; no more retries left)`,ue({retryOfRequestLogID:s,url:o,durationMs:y-u,message:d.message})),g?new Tt:new Ot({cause:d})}const w=[...d.headers.entries()].filter(([m])=>m==="x-request-id").map(([m,g])=>", "+m+": "+JSON.stringify(g)).join(""),O=`[${l}${h}${w}] ${i.method} ${o} ${d.ok?"succeeded":"failed"} with status ${d.status} in ${y-u}ms`;if(!d.ok){const m=await this.shouldRetry(d);if(n&&m){const R=`retrying, ${n} attempts remaining`;return await nl(d.body),U(this).info(`${O} - ${R}`),U(this).debug(`[${l}] response error (${R})`,ue({retryOfRequestLogID:s,url:d.url,status:d.status,headers:d.headers,durationMs:y-u})),this.retryRequest(r,n,s??l,d.headers)}const g=m?"error; no more retries left":"error; not retryable";U(this).info(`${O} - ${g}`);const S=await d.text().catch(R=>Yt(R).message),I=Vo(S),J=I?void 0:S;throw U(this).debug(`[${l}] response error (${g})`,ue({retryOfRequestLogID:s,url:d.url,status:d.status,headers:d.headers,message:J,durationMs:Date.now()-u})),this.makeStatusError(d.status,I,J,d.headers)}return U(this).info(O),U(this).debug(`[${l}] response start`,ue({retryOfRequestLogID:s,url:d.url,status:d.status,headers:d.headers,durationMs:y-u})),{response:d,options:r,controller:p,requestLogID:l,retryOfRequestLogID:s,startTime:u}}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 yl(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,h={signal:r.signal,...l?{duplex:"half"}:{},method:"GET",...o};i&&(h.method=i.toUpperCase());try{return await this.fetch.call(void 0,e,h)}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 Ke(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&&Ho("timeout",s.timeout),s.timeout=s.timeout??this.timeout;const{bodyHeaders:l,body:h}=this.buildBody({options:s}),u=await this.buildHeaders({options:e,method:r,bodyHeaders:l,retryCount:n});return{req:{method:r,headers:u,...s.signal&&{signal:s.signal},...globalThis.ReadableStream&&h instanceof globalThis.ReadableStream&&{duplex:"half"},...h&&{body:h},...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=b([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))}:{},...el(),"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=b([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:pr(e)}:f(this,dt,"f").call(this,{body:e,headers:s})}}Un=C,dt=new WeakMap,pn=new WeakSet,Ia=function(){return this.baseURL!=="https://api.openai.com/v1"};C.OpenAI=Un;C.DEFAULT_TIMEOUT=6e5;C.OpenAIError=k;C.APIError=q;C.APIConnectionError=Ot;C.APIConnectionTimeoutError=Tt;C.APIUserAbortError=X;C.NotFoundError=Gs;C.ConflictError=Qs;C.RateLimitError=er;C.BadRequestError=Hs;C.AuthenticationError=Vs;C.InternalServerError=tr;C.PermissionDeniedError=Xs;C.UnprocessableEntityError=Ys;C.InvalidWebhookSignatureError=Te;C.toFile=xl;C.Completions=aa;C.Chat=Tn;C.Embeddings=la;C.Files=ua;C.Images=ga;C.Audio=ze;C.Moderations=ya;C.Models=_a;C.FineTuning=Ae;C.Graders=Dn;C.VectorStores=jt;C.Webhooks=Ta;C.Beta=Se;C.Batches=Gr;C.Uploads=Bn;C.Responses=Lt;C.Realtime=Nt;C.Conversations=$n;C.Evals=Mn;C.Containers=Rn;C.Videos=Ca;function Dt(t,e){if(t.function===void 0)return;let n;if(e?.partial)try{n=Ka(t.function.arguments??"{}")}catch{return}else try{n=JSON.parse(t.function.arguments)}catch(r){throw new Ws([`Function "${t.function.name}" arguments:`,"",t.function.arguments,"","are not valid JSON.",`Error: ${r.message}`].join(`
31
- `))}const s={name:t.function.name,args:n,type:"tool_call"};return e?.returnId&&(s.id=t.id),s}function Pa(t){if(t.id===void 0)throw new Error('All OpenAI tool calls must have an "id" field.');return{id:t.id,type:"function",function:{name:t.name,arguments:JSON.stringify(t.args)}}}function At(t,e){return{name:t.function?.name,args:t.function?.arguments,id:t.id,error:e,type:"invalid_tool_call"}}var Ra=class extends hi{static lc_name(){return"JsonOutputToolsParser"}returnId=!1;lc_namespace=["langchain","output_parsers","openai_tools"];lc_serializable=!0;constructor(t){super(t),this.returnId=t?.returnId??this.returnId}_diff(){throw new Error("Not supported.")}async parse(){throw new Error("Not implemented.")}async parseResult(t){return await this.parsePartialResult(t,!1)}async parsePartialResult(t,e=!0){const n=t[0].message;let s;if(Ds(n)&&n.tool_calls?.length?s=n.tool_calls.map(a=>{const{id:i,...o}=a;return this.returnId?{id:i,...o}:o}):n.additional_kwargs.tool_calls!==void 0&&(s=JSON.parse(JSON.stringify(n.additional_kwargs.tool_calls)).map(i=>Dt(i,{returnId:this.returnId,partial:e}))),!s)return[];const r=[];for(const a of s)if(a!==void 0){const i={type:a.name,args:a.args,id:a.id};r.push(i)}return r}},mn=class extends Ra{static lc_name(){return"JsonOutputKeyToolsParser"}lc_namespace=["langchain","output_parsers","openai_tools"];lc_serializable=!0;returnId=!1;keyName;returnSingle=!1;zodSchema;constructor(t){super(t),this.keyName=t.keyName,this.returnSingle=t.returnSingle??this.returnSingle,this.zodSchema=t.zodSchema}async _validateResult(t){if(this.zodSchema===void 0)return t;const e=await Ja(this.zodSchema,t);if(e.success)return e.data;throw new Ws(`Failed to parse. Text: "${JSON.stringify(t,null,2)}". Error: ${JSON.stringify(e.error?.issues)}`,JSON.stringify(t,null,2))}async parsePartialResult(t){const n=(await super.parsePartialResult(t)).filter(r=>r.type===this.keyName);let s=n;if(n.length)return this.returnId||(s=n.map(r=>r.args)),this.returnSingle?s[0]:s}async parseResult(t){const n=(await super.parsePartialResult(t,!1)).filter(a=>a.type===this.keyName);let s=n;return n.length?(this.returnId||(s=n.map(a=>a.args)),this.returnSingle?this._validateResult(s[0]):await Promise.all(s.map(a=>this._validateResult(a)))):void 0}},Fl={};gn(Fl,{JsonOutputKeyToolsParser:()=>mn,JsonOutputToolsParser:()=>Ra,convertLangChainToolCallToOpenAI:()=>Pa,makeInvalidToolCall:()=>At,parseToolCall:()=>Dt});var Wn=class extends fi{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??zn("OPENAI_API_KEY"),this.organization=t?.configuration?.organization??zn("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(!We(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&&Oe(t.json_schema.schema)?Wo(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=Ai(n),r={...this.clientConfig,baseURL:s,timeout:this.timeout,maxRetries:0};r.baseURL||delete r.baseURL,this.client=new C(r)}return{...this.clientConfig,...t}}_convertChatOpenAIToolToCompletionsTool(t,e){return pt(t)?Ei(t.metadata.customTool):qs(t)?e?.strict!==void 0?{...t,function:{...t.function,strict:e.strict}}:t:Ci(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=>wn(s)||pt(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(qe(a)),c=a.name!==void 0?s+await this.getNumTokens(a.name):0;let l=i+n+o+c;const h=a;if(h._getType()==="function"&&(l-=2),h.additional_kwargs?.function_call&&(l+=3),h?.additional_kwargs.function_call?.name&&(l+=await this.getNumTokens(h.additional_kwargs.function_call?.name)),h.additional_kwargs.function_call?.arguments)try{l+=await this.getNumTokens(JSON.stringify(JSON.parse(h.additional_kwargs.function_call?.arguments)))}catch(u){console.error("Error parsing function arguments",u,JSON.stringify(h.additional_kwargs.function_call)),l+=await this.getNumTokens(h.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=Ti(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=Bo(this.model,e?.method);if(o==="jsonMode"){Oe(r)?s=es.fromZodSchema(r):s=new ts;const u=Ze(r);n=this.withConfig({outputVersion:"v0",response_format:{type:"json_object"},ls_structured_output_format:{kwargs:{method:"json_mode"},schema:{title:a??"extract",...u}}})}else if(o==="jsonSchema"){const u={name:a??"extract",description:za(r),schema:r,strict:e?.strict},p=Ze(u.schema);if(n=this.withConfig({outputVersion:"v0",response_format:{type:"json_schema",json_schema:u},ls_structured_output_format:{kwargs:{method:"json_schema"},schema:{title:u.name,description:u.description,...p}}}),Oe(r)){const d=es.fromZodSchema(r);s=Za.from(y=>"parsed"in y.additional_kwargs?y.additional_kwargs.parsed:d)}else s=new ts}else{let u=a??"extract";if(Oe(r)){const p=Ze(r);n=this.withConfig({outputVersion:"v0",tools:[{type:"function",function:{name:u,description:p.description,parameters:p}}],tool_choice:{type:"function",function:{name:u}},ls_structured_output_format:{kwargs:{method:"function_calling"},schema:{title:u,...p}},...e?.strict!==void 0?{strict:e.strict}:{}}),s=new mn({returnSingle:!0,keyName:u,zodSchema:r})}else{let p;typeof r.name=="string"&&typeof r.parameters=="object"&&r.parameters!=null?(p=r,u=r.name):(u=r.title??u,p={name:u,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:u}},ls_structured_output_format:{kwargs:{method:"function_calling"},schema:{title:u,...d}},...e?.strict!==void 0?{strict:e.strict}:{}}),s=new mn({returnSingle:!0,keyName:u})}}if(!i)return n.pipe(s);const c=ns.assign({parsed:(u,p)=>s.invoke(u.raw,p)}),l=ns.assign({parsed:()=>null}),h=c.withFallbacks({fallbacks:[l]});return Ha.from([{raw:n},h])}};function tt(t,e){return t.lc_error_code=e,t.message=`${t.message}
30
+ `);this.baseURL=o.baseURL,this.timeout=o.timeout??Un.DEFAULT_TIMEOUT,this.logger=o.logger??console;const c="warn";this.logLevel=c,this.logLevel=_s(o.logLevel,"ClientOptions.logLevel",this)??_s(ge("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??c,this.fetchOptions=o.fetchOptions,this.maxRetries=o.maxRetries??2,this.fetch=o.fetch??tl(),x(this,dt,sl),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 b([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return cl(e,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${ye}`}defaultIdempotencyKey(){return`stainless-node-retry-${dr()}`}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 k?s:new k(`Failed to get token from 'apiKey' function: ${s.message}`,{cause:s})}if(typeof n!="string"||!n)throw new k(`Expected 'apiKey' function argument to return a string but it returned ${n}`);return this.apiKey=n,!0}buildURL(e,n,s){const r=!f(this,pn,"m",Ia).call(this)&&s||this.baseURL,a=Ko(e)?new URL(e):new URL(r+(r.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),i=this.defaultQuery();return zo(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 Pt(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"),h=s===void 0?"":`, retryOf: ${s}`,u=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(Yt),y=Date.now();if(d instanceof globalThis.Error){const m=`retrying, ${n} attempts remaining`;if(r.signal?.aborted)throw new X;const g=Qt(d)||/timed? ?out/i.test(String(d)+("cause"in d?String(d.cause):""));if(n)return U(this).info(`[${l}] connection ${g?"timed out":"failed"} - ${m}`),U(this).debug(`[${l}] connection ${g?"timed out":"failed"} (${m})`,ue({retryOfRequestLogID:s,url:o,durationMs:y-u,message:d.message})),this.retryRequest(r,n,s??l);throw U(this).info(`[${l}] connection ${g?"timed out":"failed"} - error; no more retries left`),U(this).debug(`[${l}] connection ${g?"timed out":"failed"} (error; no more retries left)`,ue({retryOfRequestLogID:s,url:o,durationMs:y-u,message:d.message})),g?new Tt:new Ot({cause:d})}const w=[...d.headers.entries()].filter(([m])=>m==="x-request-id").map(([m,g])=>", "+m+": "+JSON.stringify(g)).join(""),O=`[${l}${h}${w}] ${i.method} ${o} ${d.ok?"succeeded":"failed"} with status ${d.status} in ${y-u}ms`;if(!d.ok){const m=await this.shouldRetry(d);if(n&&m){const R=`retrying, ${n} attempts remaining`;return await nl(d.body),U(this).info(`${O} - ${R}`),U(this).debug(`[${l}] response error (${R})`,ue({retryOfRequestLogID:s,url:d.url,status:d.status,headers:d.headers,durationMs:y-u})),this.retryRequest(r,n,s??l,d.headers)}const g=m?"error; no more retries left":"error; not retryable";U(this).info(`${O} - ${g}`);const S=await d.text().catch(R=>Yt(R).message),I=Vo(S),J=I?void 0:S;throw U(this).debug(`[${l}] response error (${g})`,ue({retryOfRequestLogID:s,url:d.url,status:d.status,headers:d.headers,message:J,durationMs:Date.now()-u})),this.makeStatusError(d.status,I,J,d.headers)}return U(this).info(O),U(this).debug(`[${l}] response start`,ue({retryOfRequestLogID:s,url:d.url,status:d.status,headers:d.headers,durationMs:y-u})),{response:d,options:r,controller:p,requestLogID:l,retryOfRequestLogID:s,startTime:u}}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 yl(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,h={signal:r.signal,...l?{duplex:"half"}:{},method:"GET",...o};i&&(h.method=i.toUpperCase());try{return await this.fetch.call(void 0,e,h)}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 Ke(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&&Ho("timeout",s.timeout),s.timeout=s.timeout??this.timeout;const{bodyHeaders:l,body:h}=this.buildBody({options:s}),u=await this.buildHeaders({options:e,method:r,bodyHeaders:l,retryCount:n});return{req:{method:r,headers:u,...s.signal&&{signal:s.signal},...globalThis.ReadableStream&&h instanceof globalThis.ReadableStream&&{duplex:"half"},...h&&{body:h},...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=b([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))}:{},...el(),"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=b([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:pr(e)}:f(this,dt,"f").call(this,{body:e,headers:s})}}Un=C,dt=new WeakMap,pn=new WeakSet,Ia=function(){return this.baseURL!=="https://api.openai.com/v1"};C.OpenAI=Un;C.DEFAULT_TIMEOUT=6e5;C.OpenAIError=k;C.APIError=q;C.APIConnectionError=Ot;C.APIConnectionTimeoutError=Tt;C.APIUserAbortError=X;C.NotFoundError=Gs;C.ConflictError=Qs;C.RateLimitError=er;C.BadRequestError=Hs;C.AuthenticationError=Vs;C.InternalServerError=tr;C.PermissionDeniedError=Xs;C.UnprocessableEntityError=Ys;C.InvalidWebhookSignatureError=Te;C.toFile=xl;C.Completions=aa;C.Chat=Tn;C.Embeddings=la;C.Files=ua;C.Images=ga;C.Audio=ze;C.Moderations=ya;C.Models=_a;C.FineTuning=Ae;C.Graders=Dn;C.VectorStores=jt;C.Webhooks=Ta;C.Beta=Se;C.Batches=Gr;C.Uploads=Bn;C.Responses=Lt;C.Realtime=Nt;C.Conversations=$n;C.Evals=Mn;C.Containers=Rn;C.Videos=Ca;function Dt(t,e){if(t.function===void 0)return;let n;if(e?.partial)try{n=Za(t.function.arguments??"{}")}catch{return}else try{n=JSON.parse(t.function.arguments)}catch(r){throw new Fs([`Function "${t.function.name}" arguments:`,"",t.function.arguments,"","are not valid JSON.",`Error: ${r.message}`].join(`
31
+ `))}const s={name:t.function.name,args:n,type:"tool_call"};return e?.returnId&&(s.id=t.id),s}function Pa(t){if(t.id===void 0)throw new Error('All OpenAI tool calls must have an "id" field.');return{id:t.id,type:"function",function:{name:t.name,arguments:JSON.stringify(t.args)}}}function At(t,e){return{name:t.function?.name,args:t.function?.arguments,id:t.id,error:e,type:"invalid_tool_call"}}var Ra=class extends za{static lc_name(){return"JsonOutputToolsParser"}returnId=!1;lc_namespace=["langchain","output_parsers","openai_tools"];lc_serializable=!0;constructor(t){super(t),this.returnId=t?.returnId??this.returnId}_diff(){throw new Error("Not supported.")}async parse(){throw new Error("Not implemented.")}async parseResult(t){return await this.parsePartialResult(t,!1)}async parsePartialResult(t,e=!0){const n=t[0].message;let s;if(Bs(n)&&n.tool_calls?.length?s=n.tool_calls.map(a=>{const{id:i,...o}=a;return this.returnId?{id:i,...o}:o}):n.additional_kwargs.tool_calls!==void 0&&(s=JSON.parse(JSON.stringify(n.additional_kwargs.tool_calls)).map(i=>Dt(i,{returnId:this.returnId,partial:e}))),!s)return[];const r=[];for(const a of s)if(a!==void 0){const i={type:a.name,args:a.args,id:a.id};r.push(i)}return r}},mn=class extends Ra{static lc_name(){return"JsonOutputKeyToolsParser"}lc_namespace=["langchain","output_parsers","openai_tools"];lc_serializable=!0;returnId=!1;keyName;returnSingle=!1;zodSchema;constructor(t){super(t),this.keyName=t.keyName,this.returnSingle=t.returnSingle??this.returnSingle,this.zodSchema=t.zodSchema}async _validateResult(t){if(this.zodSchema===void 0)return t;const e=await Ka(this.zodSchema,t);if(e.success)return e.data;throw new Fs(`Failed to parse. Text: "${JSON.stringify(t,null,2)}". Error: ${JSON.stringify(e.error?.issues)}`,JSON.stringify(t,null,2))}async parsePartialResult(t){const n=(await super.parsePartialResult(t)).filter(r=>r.type===this.keyName);let s=n;if(n.length)return this.returnId||(s=n.map(r=>r.args)),this.returnSingle?s[0]:s}async parseResult(t){const n=(await super.parsePartialResult(t,!1)).filter(a=>a.type===this.keyName);let s=n;return n.length?(this.returnId||(s=n.map(a=>a.args)),this.returnSingle?this._validateResult(s[0]):await Promise.all(s.map(a=>this._validateResult(a)))):void 0}},Fl={};gn(Fl,{JsonOutputKeyToolsParser:()=>mn,JsonOutputToolsParser:()=>Ra,convertLangChainToolCallToOpenAI:()=>Pa,makeInvalidToolCall:()=>At,parseToolCall:()=>Dt});var Wn=class extends Ha{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??zn("OPENAI_API_KEY"),this.organization=t?.configuration?.organization??zn("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(!We(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&&Oe(t.json_schema.schema)?Wo(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=Ai(n),r={...this.clientConfig,baseURL:s,timeout:this.timeout,maxRetries:0};r.baseURL||delete r.baseURL,this.client=new C(r)}return{...this.clientConfig,...t}}_convertChatOpenAIToolToCompletionsTool(t,e){return pt(t)?Ei(t.metadata.customTool):Us(t)?e?.strict!==void 0?{...t,function:{...t.function,strict:e.strict}}:t:Ci(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=>wn(s)||pt(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(qe(a)),c=a.name!==void 0?s+await this.getNumTokens(a.name):0;let l=i+n+o+c;const h=a;if(h._getType()==="function"&&(l-=2),h.additional_kwargs?.function_call&&(l+=3),h?.additional_kwargs.function_call?.name&&(l+=await this.getNumTokens(h.additional_kwargs.function_call?.name)),h.additional_kwargs.function_call?.arguments)try{l+=await this.getNumTokens(JSON.stringify(JSON.parse(h.additional_kwargs.function_call?.arguments)))}catch(u){console.error("Error parsing function arguments",u,JSON.stringify(h.additional_kwargs.function_call)),l+=await this.getNumTokens(h.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=Ti(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=Bo(this.model,e?.method);if(o==="jsonMode"){Oe(r)?s=Zn.fromZodSchema(r):s=new Hn;const u=Ze(r);n=this.withConfig({outputVersion:"v0",response_format:{type:"json_object"},ls_structured_output_format:{kwargs:{method:"json_mode"},schema:{title:a??"extract",...u}}})}else if(o==="jsonSchema"){const u={name:a??"extract",description:Va(r),schema:r,strict:e?.strict},p=Ze(u.schema);if(n=this.withConfig({outputVersion:"v0",response_format:{type:"json_schema",json_schema:u},ls_structured_output_format:{kwargs:{method:"json_schema"},schema:{title:u.name,description:u.description,...p}}}),Oe(r)){const d=Zn.fromZodSchema(r);s=Xa.from(y=>"parsed"in y.additional_kwargs?y.additional_kwargs.parsed:d)}else s=new Hn}else{let u=a??"extract";if(Oe(r)){const p=Ze(r);n=this.withConfig({outputVersion:"v0",tools:[{type:"function",function:{name:u,description:p.description,parameters:p}}],tool_choice:{type:"function",function:{name:u}},ls_structured_output_format:{kwargs:{method:"function_calling"},schema:{title:u,...p}},...e?.strict!==void 0?{strict:e.strict}:{}}),s=new mn({returnSingle:!0,keyName:u,zodSchema:r})}else{let p;typeof r.name=="string"&&typeof r.parameters=="object"&&r.parameters!=null?(p=r,u=r.name):(u=r.title??u,p={name:u,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:u}},ls_structured_output_format:{kwargs:{method:"function_calling"},schema:{title:u,...d}},...e?.strict!==void 0?{strict:e.strict}:{}}),s=new mn({returnSingle:!0,keyName:u})}}if(!i)return n.pipe(s);const c=Vn.assign({parsed:(u,p)=>s.invoke(u.raw,p)}),l=Vn.assign({parsed:()=>null}),h=c.withFallbacks({fallbacks:[l]});return Ga.from([{raw:n},h])}};function tt(t,e){return t.lc_error_code=e,t.message=`${t.message}
32
32
 
33
33
  Troubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${e}/
34
- `,t}function $a(t){if(!t||typeof t!="object")return t;let e;return t.constructor.name===Tt.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=tt(t,"INVALID_TOOL_RESULTS"):"status"in t&&t.status===401?e=tt(t,"MODEL_AUTHENTICATION"):"status"in t&&t.status===429?e=tt(t,"MODEL_RATE_LIMIT"):"status"in t&&t.status===404?e=tt(t,"MODEL_NOT_FOUND"):e=t,e}const Ea={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=Hn({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=Vn(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=Vn(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(!Hn({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`)}},Bl=({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(Dt(l,{returnId:!0}))}catch(h){a.push(At(l,h.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=qo(t.content||"",e.choices?.[0]?.message);return new xe({content:c,tool_calls:r,invalid_tool_calls:a,additional_kwargs:i,response_metadata:o,id:e.id})}default:return new js(t.content||"",t.role??"unknown")}},Ul=({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 Va({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 _n({content:a,tool_call_chunks:c,additional_kwargs:i,id:e.id,response_metadata:o})}else return r==="system"?new Zn({content:a,response_metadata:o}):r==="developer"?new Zn({content:a,response_metadata:o,additional_kwargs:{__openai_role__:"developer"}}):r==="function"?new Xa({content:a,additional_kwargs:i,name:t.name,response_metadata:o}):r==="tool"?new Ga({content:a,additional_kwargs:i,tool_call_id:t.tool_call_id,response_metadata:o}):new Qa({content:a,role:r,response_metadata:o})},Wl=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=Ya(()=>{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}}}},ql=({message:t,model:e})=>{let n=qe(t);if(n==="system"&&We(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"&&ht.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=Wl(a);i&&(yield i)}}return{role:"user",content:Array.from(s(t.contentBlocks))}},Ns=({messages:t,model:e})=>t.flatMap(n=>{if("output_version"in n.response_metadata&&n.response_metadata?.output_version==="v1")return ql({message:n});let s=qe(n);s==="system"&&We(e)&&(s="developer");const r=typeof n.content=="string"?n.content:n.content.map(i=>Fs(i)?Bs(i,Ea):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=""),xe.isInstance(n)&&n.tool_calls?.length?(a.tool_calls=n.tool_calls.map(Pa),a.content=""):(n.additional_kwargs.tool_calls!=null&&(a.tool_calls=n.additional_kwargs.tool_calls),ht.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}),Ct="__openai_function_call_ids__",Ma=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}},Na=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(Dt(c,{returnId:!0}))}catch(l){let h;typeof l=="object"&&l!=null&&"message"in l&&typeof l.message=="string"&&(h=l.message),r.push(At(c,h))}i[Ct]??={},o.id&&(i[Ct][o.call_id]=o.id)}else if(o.type==="reasoning")i.reasoning=o;else if(o.type==="custom_tool_call"){const c=Pi(o);c?s.push(c):r.push(At(o,"Malformed custom tool call"))}else i.tool_outputs??=[],i.tool_outputs.push(o);return new xe({id:e,content:n,tool_calls:s,invalid_tool_calls:r,usage_metadata:Ma(t.usage),additional_kwargs:i,response_metadata:a})},Jl=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}},Kl=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[Ct]={[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=Na(t.response);s=Ma(t.response.usage),t.response.text?.format?.type==="json_schema"&&(i.parsed??=JSON.parse(c.text));for(const[l,h]of Object.entries(t.response))l!=="id"&&(a[l]=h)}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,h)=>({...l,index:h})):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 Xt({text:e.map(c=>c.text).join(""),message:new _n({id:o,content:e,tool_call_chunks:r,usage_metadata:s,additional_kwargs:i,response_metadata:a}),generationInfo:n})},zl=t=>{const e=xe.isInstance(t)&&t.response_metadata?.model_provider==="openai";function*n(){const s=ke(()=>{try{const m=qe(t);return m==="system"||m==="developer"||m==="assistant"||m==="user"?m:"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 m=r.content;(typeof m=="string"&&m.length>0||Array.isArray(m)&&m.length>0)&&(yield r),r=void 0}const h=m=>{r||(r={type:"message",role:s,content:[]}),typeof r.content=="string"?r.content=r.content.length>0?[{type:"input_text",text:r.content},...m]:[...m]:r.content.push(...m)},u=m=>{if(typeof m=="string")return m;try{return JSON.stringify(m??{})}catch{return"{}"}},p=m=>{const g=ke(()=>{const S=m.metadata?.detail;return S==="low"||S==="high"||S==="auto"?S:"auto"});if(m.fileId)return{type:"input_image",detail:g,file_id:m.fileId};if(m.url)return{type:"input_image",detail:g,image_url:m.url};if(m.data){const S=typeof m.data=="string"?m.data:Buffer.from(m.data).toString("base64"),I=m.mimeType??"image/png";return{type:"input_image",detail:g,image_url:`data:${I};base64,${S}`}}},d=m=>{const g=m.metadata?.filename??m.metadata?.name??m.metadata?.title;if(m.fileId&&typeof g=="string")return{type:"input_file",file_id:m.fileId,...g?{filename:g}:{}};if(m.url&&typeof g=="string")return{type:"input_file",file_url:m.url,...g?{filename:g}:{}};if(m.data&&typeof g=="string"){const S=typeof m.data=="string"?m.data:Buffer.from(m.data).toString("base64");return{type:"input_file",file_data:`data:${m.mimeType??"application/octet-stream"};base64,${S}`,...g?{filename:g}:{}}}},y=m=>{const g=ke(()=>{if(Array.isArray(m.summary)){const j=m.summary?.map(R=>R?.text).filter(R=>typeof R=="string")??[];if(j.length>0)return j}return m.reasoning?[m.reasoning]:[]}),S=g.length>0?g.map(J=>({type:"summary_text",text:J})):[{type:"summary_text",text:""}],I={type:"reasoning",id:m.id??"",summary:S};return m.reasoning&&(I.content=[{type:"reasoning_text",text:m.reasoning}]),I},w=m=>({type:"function_call",name:m.name??"",call_id:m.id??"",arguments:u(m.args)}),O=m=>{const g=u(m.output),S=m.status==="success"?"completed":m.status==="error"?"incomplete":void 0;return{type:"function_call_output",call_id:m.toolCallId??"",output:g,...S?{status:S}:{}}};for(const m of t.contentBlocks)if(m.type==="text")h([{type:"input_text",text:m.text}]);else if(m.type!=="invalid_tool_call"){if(m.type==="reasoning")yield*l(),yield y(m);else if(m.type==="tool_call"){yield*l();const g=m.id??"";g&&(a.add(g),o.delete(g)),yield w(m)}else if(m.type==="tool_call_chunk"){if(m.id){const g=o.get(m.id)??{name:m.name,args:[]};m.name&&(g.name=m.name),m.args&&g.args.push(m.args),o.set(m.id,g)}}else if(m.type==="server_tool_call"){yield*l();const g=m.id??"";g&&(i.add(g),c.delete(g)),yield w(m)}else if(m.type==="server_tool_call_chunk"){if(m.id){const g=c.get(m.id)??{name:m.name,args:[]};m.name&&(g.name=m.name),m.args&&g.args.push(m.args),c.set(m.id,g)}}else if(m.type==="server_tool_call_result")yield*l(),yield O(m);else if(m.type!=="audio")if(m.type==="file"){const g=d(m);g&&h([g])}else if(m.type==="image"){const g=p(m);g&&h([g])}else if(m.type==="video"){const g=d(m);g&&h([g])}else m.type==="text-plain"?m.text&&h([{type:"input_text",text:m.text}]):m.type==="non_standard"&&e&&(yield*l(),yield m.value)}yield*l();for(const[m,g]of o){if(!m||a.has(m))continue;const S=g.args.join("");!g.name&&!S||(yield{type:"function_call",call_id:m,name:g.name??"",arguments:S})}for(const[m,g]of c){if(!m||i.has(m))continue;const S=g.args.join("");!g.name&&!S||(yield{type:"function_call",call_id:m,name:g.name??"",arguments:S})}}return Array.from(n())},Ls=({messages:t,zdrEnabled:e,model:n})=>t.flatMap(s=>{const r=s.response_metadata;if(r?.output_version==="v1")return zl(s);const a=s.additional_kwargs;let i=qe(s);if(i==="system"&&We(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(u=>u.type==="computer_screenshot");if(l)return l;const h=o.content.find(u=>u.type==="image_url");if(h)return{type:"computer_screenshot",image_url:typeof h.image_url=="string"?h.image_url:h.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=Jl(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:ke(()=>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?.[Ct];xe.isInstance(s)&&s.tool_calls?.length?o.push(...s.tool_calls.map(p=>Ri(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 h=r?.output?.length?r?.output:a.tool_outputs,u=["computer_call","mcp_call","code_interpreter_call","image_generation_call"];if(h!=null){const d=h?.filter(y=>u.includes(y.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}),Fs(l))return Bs(l,Ea);if(l.type==="text")return{type:"input_text",text:l.text};if(l.type==="image_url"){const h=ke(()=>{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}),u=ke(()=>{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:h,detail:u}}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 Zl=class extends Wn{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:Ii(t?.tool_choice)?t?.tool_choice:(()=>{const r=zs(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:Ls({messages:t,zdrEnabled:this.zdrEnabled??!1,model:this.model}),...n,stream:!1},{signal:e?.signal,...e?.options});return{generations:[{text:s.output_text,message:Na(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:Ls({messages:t,zdrEnabled:this.zdrEnabled??!1,model:this.model}),stream:!0},e);for await(const r of s){const a=Kl(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(wn(s))s.type==="image_generation"&&e?.stream&&(s.partial_images=1),n.push(s);else if(pt(s)){const r=s.metadata.customTool;n.push({type:"custom",name:r.name,description:r.description,format:r.format})}else qs(s)?n.push({type:"function",name:s.function.name,parameters:s.function.parameters,description:s.function.description,strict:e?.strict??null}):Zs(s)&&n.push($i(s));return n}},Hl=class extends Wn{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:zs(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),We(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=Ns({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 y=d.generationInfo?.completion??0;o[y]===void 0?o[y]=d:o[y]=o[y].concat(d)}const c=Object.entries(o).sort(([d],[y])=>parseInt(d,10)-parseInt(y,10)).map(([d,y])=>y),{functions:l,function_call:h}=this.invocationParams(e),u=await this._getEstimatedTokenCountFromPrompt(t,l,h),p=await this._getNumTokensFromGenerations(c);return s.input_tokens=u,s.output_tokens=p,s.total_tokens=u+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:h,completion_tokens_details:u}=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),(h?.audio_tokens!==null||h?.cached_tokens!==null)&&(s.input_token_details={...h?.audio_tokens!==null&&{audio:h?.audio_tokens},...h?.cached_tokens!==null&&{cache_read:h?.cached_tokens}}),(u?.audio_tokens!==null||u?.reasoning_tokens!==null)&&(s.output_token_details={...u?.audio_tokens!==null&&{audio:u?.audio_tokens},...u?.reasoning_tokens!==null&&{reasoning:u?.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}:{}},Ds(w.message)&&(w.message.usage_metadata=s),w.message=new xe(Object.fromEntries(Object.entries(w.message).filter(([O])=>!O.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=Ns({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:h}=l;if(!h)continue;const u=this._convertCompletionsDeltaToBaseMessageChunk(h,c,a);a=h.role??a;const p={prompt:e.promptIndex??0,completion:l.index??0};if(typeof u.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 y=new Xt({message:u,text:u.content,generationInfo:d});yield y,await n?.handleLLMNewToken(y.text??"",p,void 0,void 0,void 0,{chunk:y})}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 Xt({message:new _n({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 Ul({delta:t,rawResponse:e,includeRawResponse:this.__includeRawResponse,defaultRole:n})}_convertCompletionsMessageToBaseMessage(t,e){return Bl({message:t,rawResponse:e,includeRawResponse:this.__includeRawResponse})}},yc=class La extends Wn{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 Zl(e),this.completions=e?.completions??new Hl(e)}_useResponsesApi(e){const n=e?.tools?.some(wn),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(Zs)||e?.tools?.some(pt);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 La(this.fields);return n.defaultOptions={...this.defaultOptions,...e},n}},Vl={};gn(Vl,{BaseLLM:()=>ja,LLM:()=>Xl});var ja=class je extends pi{lc_namespace=["langchain","llms",this._llmType()];async invoke(e,n){const s=je._convertInputToPromptValue(e);return(await this.generatePrompt([s],n,n?.callbacks)).generations[0][0].text}async*_streamResponseChunks(e,n,s){throw new Error("Not implemented.")}_separateRunnableConfigFromCallOptionsCompat(e){const[n,s]=super._separateRunnableConfigFromCallOptions(e);return s.signal=n.signal,[n,s]}async*_streamIterator(e,n){if(this._streamResponseChunks===je.prototype._streamResponseChunks)yield this.invoke(e,n);else{const s=je._convertInputToPromptValue(e),[r,a]=this._separateRunnableConfigFromCallOptionsCompat(n),i=await nt.configure(r.callbacks,this.callbacks,r.tags,this.tags,r.metadata,this.metadata,{verbose:this.verbose}),o={options:a,invocation_params:this?.invocationParams(a),batch_size:1},c=await i?.handleLLMStart(this.toJSON(),[s.toString()],r.runId,void 0,o,void 0,void 0,r.runName);let l=new ei({text:""});try{for await(const h of this._streamResponseChunks(s.toString(),a,c?.[0]))l?l=l.concat(h):l=h,typeof h.text=="string"&&(yield h.text)}catch(h){throw await Promise.all((c??[]).map(u=>u?.handleLLMError(h))),h}await Promise.all((c??[]).map(h=>h?.handleLLMEnd({generations:[[l]]})))}}async generatePrompt(e,n,s){const r=e.map(a=>a.toString());return this.generate(r,n,s)}invocationParams(e){return{}}_flattenLLMResult(e){const n=[];for(let s=0;s<e.generations.length;s+=1){const r=e.generations[s];if(s===0)n.push({generations:[r],llmOutput:e.llmOutput});else{const a=e.llmOutput?{...e.llmOutput,tokenUsage:{}}:void 0;n.push({generations:[r],llmOutput:a})}}return n}async _generateUncached(e,n,s,r){let a;if(r!==void 0&&r.length===e.length)a=r;else{const l=await nt.configure(s.callbacks,this.callbacks,s.tags,this.tags,s.metadata,this.metadata,{verbose:this.verbose}),h={options:n,invocation_params:this?.invocationParams(n),batch_size:e.length};a=await l?.handleLLMStart(this.toJSON(),e,s.runId,void 0,h,void 0,void 0,s?.runName)}const i=!!a?.[0].handlers.find(ti);let o;if(i&&e.length===1&&this._streamResponseChunks!==je.prototype._streamResponseChunks)try{const l=await this._streamResponseChunks(e[0],n,a?.[0]);let h;for await(const u of l)h===void 0?h=u:h=ni(h,u);if(h===void 0)throw new Error("Received empty response from chat model call.");o={generations:[[h]],llmOutput:{}},await a?.[0].handleLLMEnd(o)}catch(l){throw await a?.[0].handleLLMError(l),l}else{try{o=await this._generate(e,n,a?.[0])}catch(h){throw await Promise.all((a??[]).map(u=>u?.handleLLMError(h))),h}const l=this._flattenLLMResult(o);await Promise.all((a??[]).map((h,u)=>h?.handleLLMEnd(l[u])))}const c=a?.map(l=>l.runId)||void 0;return Object.defineProperty(o,Xn,{value:c?{runIds:c}:void 0,configurable:!0}),o}async _generateCached({prompts:e,cache:n,llmStringKey:s,parsedOptions:r,handledOptions:a,runId:i}){const o=await nt.configure(a.callbacks,this.callbacks,a.tags,this.tags,a.metadata,this.metadata,{verbose:this.verbose}),c={options:r,invocation_params:this?.invocationParams(r),batch_size:e.length},l=await o?.handleLLMStart(this.toJSON(),e,i,void 0,c,void 0,void 0,a?.runName),h=[],p=(await Promise.allSettled(e.map(async(w,O)=>{const m=await n.lookup(w,s);return m==null&&h.push(O),m}))).map((w,O)=>({result:w,runManager:l?.[O]})).filter(({result:w})=>w.status==="fulfilled"&&w.value!=null||w.status==="rejected"),d=[];await Promise.all(p.map(async({result:w,runManager:O},m)=>{if(w.status==="fulfilled"){const g=w.value;return d[m]=g.map(S=>(S.generationInfo={...S.generationInfo,tokenUsage:{}},S)),g.length&&await O?.handleLLMNewToken(g[0].text),O?.handleLLMEnd({generations:[g]},void 0,void 0,void 0,{cached:!0})}else return await O?.handleLLMError(w.reason,void 0,void 0,void 0,{cached:!0}),Promise.reject(w.reason)}));const y={generations:d,missingPromptIndices:h,startedRunManagers:l};return Object.defineProperty(y,Xn,{value:l?{runIds:l?.map(w=>w.runId)}:void 0,configurable:!0}),y}async generate(e,n,s){if(!Array.isArray(e))throw new Error("Argument 'prompts' is expected to be a string[]");let r;Array.isArray(n)?r={stop:n}:r=n;const[a,i]=this._separateRunnableConfigFromCallOptionsCompat(r);if(a.callbacks=a.callbacks??s,!this.cache)return this._generateUncached(e,i,a);const{cache:o}=this,c=this._getSerializedCacheKeyParametersForCall(i),{generations:l,missingPromptIndices:h,startedRunManagers:u}=await this._generateCached({prompts:e,cache:o,llmStringKey:c,parsedOptions:i,handledOptions:a,runId:a.runId});let p={};if(h.length>0){const d=await this._generateUncached(h.map(y=>e[y]),i,a,u!==void 0?h.map(y=>u?.[y]):void 0);await Promise.all(d.generations.map(async(y,w)=>{const O=h[w];return l[O]=y,o.update(e[O],c,y)})),p=d.llmOutput??{}}return{generations:l,llmOutput:p}}_identifyingParams(){return{}}_modelType(){return"base_llm"}},Xl=class extends ja{async _generate(t,e,n){return{generations:await Promise.all(t.map((r,a)=>this._call(r,{...e,promptIndex:a},n).then(i=>[{text:i}])))}}},Gl={};gn(Gl,{BaseToolkit:()=>Ql,DynamicStructuredTool:()=>Ba,DynamicTool:()=>Fa,StructuredTool:()=>qn,Tool:()=>Da,ToolInputParsingException:()=>Gt,isLangChainTool:()=>Us,isRunnableToolLike:()=>_i,isStructuredTool:()=>gi,isStructuredToolParams:()=>mi,tool:()=>Yl});var qn=class extends yi{returnDirect=!1;verboseParsingErrors=!1;get lc_namespace(){return["langchain","tools"]}responseFormat="content";defaultConfig;constructor(t){super(t??{}),this.verboseParsingErrors=t?.verboseParsingErrors??this.verboseParsingErrors,this.responseFormat=t?.responseFormat??this.responseFormat,this.defaultConfig=t?.defaultConfig??this.defaultConfig,this.metadata=t?.metadata??this.metadata}async invoke(t,e){let n,s=si(ri(this.defaultConfig,e));return Bt(t)?(n=t.args,s={...s,toolCall:t}):n=t,this.call(n,s)}async call(t,e,n){const s=Bt(t)?t.args:t;let r;if(Oe(this.schema))try{r=await ai(this.schema,s)}catch(d){let y="Received tool input did not match expected schema";throw this.verboseParsingErrors&&(y=`${y}
34
+ `,t}function $a(t){if(!t||typeof t!="object")return t;let e;return t.constructor.name===Tt.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=tt(t,"INVALID_TOOL_RESULTS"):"status"in t&&t.status===401?e=tt(t,"MODEL_AUTHENTICATION"):"status"in t&&t.status===429?e=tt(t,"MODEL_RATE_LIMIT"):"status"in t&&t.status===404?e=tt(t,"MODEL_NOT_FOUND"):e=t,e}const Ea={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=Gn({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=Qn(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=Qn(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(!Gn({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`)}},Bl=({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(Dt(l,{returnId:!0}))}catch(h){a.push(At(l,h.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=qo(t.content||"",e.choices?.[0]?.message);return new xe({content:c,tool_calls:r,invalid_tool_calls:a,additional_kwargs:i,response_metadata:o,id:e.id})}default:return new js(t.content||"",t.role??"unknown")}},Ul=({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 Qa({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 _n({content:a,tool_call_chunks:c,additional_kwargs:i,id:e.id,response_metadata:o})}else return r==="system"?new Xn({content:a,response_metadata:o}):r==="developer"?new Xn({content:a,response_metadata:o,additional_kwargs:{__openai_role__:"developer"}}):r==="function"?new Ya({content:a,additional_kwargs:i,name:t.name,response_metadata:o}):r==="tool"?new ei({content:a,additional_kwargs:i,tool_call_id:t.tool_call_id,response_metadata:o}):new ti({content:a,role:r,response_metadata:o})},Wl=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=ni(()=>{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}}}},ql=({message:t,model:e})=>{let n=qe(t);if(n==="system"&&We(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"&&ht.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=Wl(a);i&&(yield i)}}return{role:"user",content:Array.from(s(t.contentBlocks))}},Ns=({messages:t,model:e})=>t.flatMap(n=>{if("output_version"in n.response_metadata&&n.response_metadata?.output_version==="v1")return ql({message:n});let s=qe(n);s==="system"&&We(e)&&(s="developer");const r=typeof n.content=="string"?n.content:n.content.map(i=>Ws(i)?qs(i,Ea):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=""),xe.isInstance(n)&&n.tool_calls?.length?(a.tool_calls=n.tool_calls.map(Pa),a.content=""):(n.additional_kwargs.tool_calls!=null&&(a.tool_calls=n.additional_kwargs.tool_calls),ht.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}),Ct="__openai_function_call_ids__",Ma=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}},Na=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(Dt(c,{returnId:!0}))}catch(l){let h;typeof l=="object"&&l!=null&&"message"in l&&typeof l.message=="string"&&(h=l.message),r.push(At(c,h))}i[Ct]??={},o.id&&(i[Ct][o.call_id]=o.id)}else if(o.type==="reasoning")i.reasoning=o;else if(o.type==="custom_tool_call"){const c=Pi(o);c?s.push(c):r.push(At(o,"Malformed custom tool call"))}else i.tool_outputs??=[],i.tool_outputs.push(o);return new xe({id:e,content:n,tool_calls:s,invalid_tool_calls:r,usage_metadata:Ma(t.usage),additional_kwargs:i,response_metadata:a})},Jl=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}},Kl=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[Ct]={[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=Na(t.response);s=Ma(t.response.usage),t.response.text?.format?.type==="json_schema"&&(i.parsed??=JSON.parse(c.text));for(const[l,h]of Object.entries(t.response))l!=="id"&&(a[l]=h)}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,h)=>({...l,index:h})):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 Xt({text:e.map(c=>c.text).join(""),message:new _n({id:o,content:e,tool_call_chunks:r,usage_metadata:s,additional_kwargs:i,response_metadata:a}),generationInfo:n})},zl=t=>{const e=xe.isInstance(t)&&t.response_metadata?.model_provider==="openai";function*n(){const s=ke(()=>{try{const m=qe(t);return m==="system"||m==="developer"||m==="assistant"||m==="user"?m:"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 m=r.content;(typeof m=="string"&&m.length>0||Array.isArray(m)&&m.length>0)&&(yield r),r=void 0}const h=m=>{r||(r={type:"message",role:s,content:[]}),typeof r.content=="string"?r.content=r.content.length>0?[{type:"input_text",text:r.content},...m]:[...m]:r.content.push(...m)},u=m=>{if(typeof m=="string")return m;try{return JSON.stringify(m??{})}catch{return"{}"}},p=m=>{const g=ke(()=>{const S=m.metadata?.detail;return S==="low"||S==="high"||S==="auto"?S:"auto"});if(m.fileId)return{type:"input_image",detail:g,file_id:m.fileId};if(m.url)return{type:"input_image",detail:g,image_url:m.url};if(m.data){const S=typeof m.data=="string"?m.data:Buffer.from(m.data).toString("base64"),I=m.mimeType??"image/png";return{type:"input_image",detail:g,image_url:`data:${I};base64,${S}`}}},d=m=>{const g=m.metadata?.filename??m.metadata?.name??m.metadata?.title;if(m.fileId&&typeof g=="string")return{type:"input_file",file_id:m.fileId,...g?{filename:g}:{}};if(m.url&&typeof g=="string")return{type:"input_file",file_url:m.url,...g?{filename:g}:{}};if(m.data&&typeof g=="string"){const S=typeof m.data=="string"?m.data:Buffer.from(m.data).toString("base64");return{type:"input_file",file_data:`data:${m.mimeType??"application/octet-stream"};base64,${S}`,...g?{filename:g}:{}}}},y=m=>{const g=ke(()=>{if(Array.isArray(m.summary)){const j=m.summary?.map(R=>R?.text).filter(R=>typeof R=="string")??[];if(j.length>0)return j}return m.reasoning?[m.reasoning]:[]}),S=g.length>0?g.map(J=>({type:"summary_text",text:J})):[{type:"summary_text",text:""}],I={type:"reasoning",id:m.id??"",summary:S};return m.reasoning&&(I.content=[{type:"reasoning_text",text:m.reasoning}]),I},w=m=>({type:"function_call",name:m.name??"",call_id:m.id??"",arguments:u(m.args)}),O=m=>{const g=u(m.output),S=m.status==="success"?"completed":m.status==="error"?"incomplete":void 0;return{type:"function_call_output",call_id:m.toolCallId??"",output:g,...S?{status:S}:{}}};for(const m of t.contentBlocks)if(m.type==="text")h([{type:"input_text",text:m.text}]);else if(m.type!=="invalid_tool_call"){if(m.type==="reasoning")yield*l(),yield y(m);else if(m.type==="tool_call"){yield*l();const g=m.id??"";g&&(a.add(g),o.delete(g)),yield w(m)}else if(m.type==="tool_call_chunk"){if(m.id){const g=o.get(m.id)??{name:m.name,args:[]};m.name&&(g.name=m.name),m.args&&g.args.push(m.args),o.set(m.id,g)}}else if(m.type==="server_tool_call"){yield*l();const g=m.id??"";g&&(i.add(g),c.delete(g)),yield w(m)}else if(m.type==="server_tool_call_chunk"){if(m.id){const g=c.get(m.id)??{name:m.name,args:[]};m.name&&(g.name=m.name),m.args&&g.args.push(m.args),c.set(m.id,g)}}else if(m.type==="server_tool_call_result")yield*l(),yield O(m);else if(m.type!=="audio")if(m.type==="file"){const g=d(m);g&&h([g])}else if(m.type==="image"){const g=p(m);g&&h([g])}else if(m.type==="video"){const g=d(m);g&&h([g])}else m.type==="text-plain"?m.text&&h([{type:"input_text",text:m.text}]):m.type==="non_standard"&&e&&(yield*l(),yield m.value)}yield*l();for(const[m,g]of o){if(!m||a.has(m))continue;const S=g.args.join("");!g.name&&!S||(yield{type:"function_call",call_id:m,name:g.name??"",arguments:S})}for(const[m,g]of c){if(!m||i.has(m))continue;const S=g.args.join("");!g.name&&!S||(yield{type:"function_call",call_id:m,name:g.name??"",arguments:S})}}return Array.from(n())},Ls=({messages:t,zdrEnabled:e,model:n})=>t.flatMap(s=>{const r=s.response_metadata;if(r?.output_version==="v1")return zl(s);const a=s.additional_kwargs;let i=qe(s);if(i==="system"&&We(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(u=>u.type==="computer_screenshot");if(l)return l;const h=o.content.find(u=>u.type==="image_url");if(h)return{type:"computer_screenshot",image_url:typeof h.image_url=="string"?h.image_url:h.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=Jl(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:ke(()=>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?.[Ct];xe.isInstance(s)&&s.tool_calls?.length?o.push(...s.tool_calls.map(p=>Ri(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 h=r?.output?.length?r?.output:a.tool_outputs,u=["computer_call","mcp_call","code_interpreter_call","image_generation_call"];if(h!=null){const d=h?.filter(y=>u.includes(y.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}),Ws(l))return qs(l,Ea);if(l.type==="text")return{type:"input_text",text:l.text};if(l.type==="image_url"){const h=ke(()=>{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}),u=ke(()=>{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:h,detail:u}}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 Zl=class extends Wn{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:Ii(t?.tool_choice)?t?.tool_choice:(()=>{const r=zs(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:Ls({messages:t,zdrEnabled:this.zdrEnabled??!1,model:this.model}),...n,stream:!1},{signal:e?.signal,...e?.options});return{generations:[{text:s.output_text,message:Na(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:Ls({messages:t,zdrEnabled:this.zdrEnabled??!1,model:this.model}),stream:!0},e);for await(const r of s){const a=Kl(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(wn(s))s.type==="image_generation"&&e?.stream&&(s.partial_images=1),n.push(s);else if(pt(s)){const r=s.metadata.customTool;n.push({type:"custom",name:r.name,description:r.description,format:r.format})}else Us(s)?n.push({type:"function",name:s.function.name,parameters:s.function.parameters,description:s.function.description,strict:e?.strict??null}):Zs(s)&&n.push($i(s));return n}},Hl=class extends Wn{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:zs(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),We(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=Ns({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 y=d.generationInfo?.completion??0;o[y]===void 0?o[y]=d:o[y]=o[y].concat(d)}const c=Object.entries(o).sort(([d],[y])=>parseInt(d,10)-parseInt(y,10)).map(([d,y])=>y),{functions:l,function_call:h}=this.invocationParams(e),u=await this._getEstimatedTokenCountFromPrompt(t,l,h),p=await this._getNumTokensFromGenerations(c);return s.input_tokens=u,s.output_tokens=p,s.total_tokens=u+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:h,completion_tokens_details:u}=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),(h?.audio_tokens!==null||h?.cached_tokens!==null)&&(s.input_token_details={...h?.audio_tokens!==null&&{audio:h?.audio_tokens},...h?.cached_tokens!==null&&{cache_read:h?.cached_tokens}}),(u?.audio_tokens!==null||u?.reasoning_tokens!==null)&&(s.output_token_details={...u?.audio_tokens!==null&&{audio:u?.audio_tokens},...u?.reasoning_tokens!==null&&{reasoning:u?.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}:{}},Bs(w.message)&&(w.message.usage_metadata=s),w.message=new xe(Object.fromEntries(Object.entries(w.message).filter(([O])=>!O.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=Ns({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:h}=l;if(!h)continue;const u=this._convertCompletionsDeltaToBaseMessageChunk(h,c,a);a=h.role??a;const p={prompt:e.promptIndex??0,completion:l.index??0};if(typeof u.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 y=new Xt({message:u,text:u.content,generationInfo:d});yield y,await n?.handleLLMNewToken(y.text??"",p,void 0,void 0,void 0,{chunk:y})}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 Xt({message:new _n({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 Ul({delta:t,rawResponse:e,includeRawResponse:this.__includeRawResponse,defaultRole:n})}_convertCompletionsMessageToBaseMessage(t,e){return Bl({message:t,rawResponse:e,includeRawResponse:this.__includeRawResponse})}},_c=class La extends Wn{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 Zl(e),this.completions=e?.completions??new Hl(e)}_useResponsesApi(e){const n=e?.tools?.some(wn),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(Zs)||e?.tools?.some(pt);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 La(this.fields);return n.defaultOptions={...this.defaultOptions,...e},n}},Vl={};gn(Vl,{BaseLLM:()=>ja,LLM:()=>Xl});var ja=class je extends si{lc_namespace=["langchain","llms",this._llmType()];async invoke(e,n){const s=je._convertInputToPromptValue(e);return(await this.generatePrompt([s],n,n?.callbacks)).generations[0][0].text}async*_streamResponseChunks(e,n,s){throw new Error("Not implemented.")}_separateRunnableConfigFromCallOptionsCompat(e){const[n,s]=super._separateRunnableConfigFromCallOptions(e);return s.signal=n.signal,[n,s]}async*_streamIterator(e,n){if(this._streamResponseChunks===je.prototype._streamResponseChunks)yield this.invoke(e,n);else{const s=je._convertInputToPromptValue(e),[r,a]=this._separateRunnableConfigFromCallOptionsCompat(n),i=await nt.configure(r.callbacks,this.callbacks,r.tags,this.tags,r.metadata,this.metadata,{verbose:this.verbose}),o={options:a,invocation_params:this?.invocationParams(a),batch_size:1},c=await i?.handleLLMStart(this.toJSON(),[s.toString()],r.runId,void 0,o,void 0,void 0,r.runName);let l=new ri({text:""});try{for await(const h of this._streamResponseChunks(s.toString(),a,c?.[0]))l?l=l.concat(h):l=h,typeof h.text=="string"&&(yield h.text)}catch(h){throw await Promise.all((c??[]).map(u=>u?.handleLLMError(h))),h}await Promise.all((c??[]).map(h=>h?.handleLLMEnd({generations:[[l]]})))}}async generatePrompt(e,n,s){const r=e.map(a=>a.toString());return this.generate(r,n,s)}invocationParams(e){return{}}_flattenLLMResult(e){const n=[];for(let s=0;s<e.generations.length;s+=1){const r=e.generations[s];if(s===0)n.push({generations:[r],llmOutput:e.llmOutput});else{const a=e.llmOutput?{...e.llmOutput,tokenUsage:{}}:void 0;n.push({generations:[r],llmOutput:a})}}return n}async _generateUncached(e,n,s,r){let a;if(r!==void 0&&r.length===e.length)a=r;else{const l=await nt.configure(s.callbacks,this.callbacks,s.tags,this.tags,s.metadata,this.metadata,{verbose:this.verbose}),h={options:n,invocation_params:this?.invocationParams(n),batch_size:e.length};a=await l?.handleLLMStart(this.toJSON(),e,s.runId,void 0,h,void 0,void 0,s?.runName)}const i=!!a?.[0].handlers.find(ai);let o;if(i&&e.length===1&&this._streamResponseChunks!==je.prototype._streamResponseChunks)try{const l=await this._streamResponseChunks(e[0],n,a?.[0]);let h;for await(const u of l)h===void 0?h=u:h=ii(h,u);if(h===void 0)throw new Error("Received empty response from chat model call.");o={generations:[[h]],llmOutput:{}},await a?.[0].handleLLMEnd(o)}catch(l){throw await a?.[0].handleLLMError(l),l}else{try{o=await this._generate(e,n,a?.[0])}catch(h){throw await Promise.all((a??[]).map(u=>u?.handleLLMError(h))),h}const l=this._flattenLLMResult(o);await Promise.all((a??[]).map((h,u)=>h?.handleLLMEnd(l[u])))}const c=a?.map(l=>l.runId)||void 0;return Object.defineProperty(o,Yn,{value:c?{runIds:c}:void 0,configurable:!0}),o}async _generateCached({prompts:e,cache:n,llmStringKey:s,parsedOptions:r,handledOptions:a,runId:i}){const o=await nt.configure(a.callbacks,this.callbacks,a.tags,this.tags,a.metadata,this.metadata,{verbose:this.verbose}),c={options:r,invocation_params:this?.invocationParams(r),batch_size:e.length},l=await o?.handleLLMStart(this.toJSON(),e,i,void 0,c,void 0,void 0,a?.runName),h=[],p=(await Promise.allSettled(e.map(async(w,O)=>{const m=await n.lookup(w,s);return m==null&&h.push(O),m}))).map((w,O)=>({result:w,runManager:l?.[O]})).filter(({result:w})=>w.status==="fulfilled"&&w.value!=null||w.status==="rejected"),d=[];await Promise.all(p.map(async({result:w,runManager:O},m)=>{if(w.status==="fulfilled"){const g=w.value;return d[m]=g.map(S=>(S.generationInfo={...S.generationInfo,tokenUsage:{}},S)),g.length&&await O?.handleLLMNewToken(g[0].text),O?.handleLLMEnd({generations:[g]},void 0,void 0,void 0,{cached:!0})}else return await O?.handleLLMError(w.reason,void 0,void 0,void 0,{cached:!0}),Promise.reject(w.reason)}));const y={generations:d,missingPromptIndices:h,startedRunManagers:l};return Object.defineProperty(y,Yn,{value:l?{runIds:l?.map(w=>w.runId)}:void 0,configurable:!0}),y}async generate(e,n,s){if(!Array.isArray(e))throw new Error("Argument 'prompts' is expected to be a string[]");let r;Array.isArray(n)?r={stop:n}:r=n;const[a,i]=this._separateRunnableConfigFromCallOptionsCompat(r);if(a.callbacks=a.callbacks??s,!this.cache)return this._generateUncached(e,i,a);const{cache:o}=this,c=this._getSerializedCacheKeyParametersForCall(i),{generations:l,missingPromptIndices:h,startedRunManagers:u}=await this._generateCached({prompts:e,cache:o,llmStringKey:c,parsedOptions:i,handledOptions:a,runId:a.runId});let p={};if(h.length>0){const d=await this._generateUncached(h.map(y=>e[y]),i,a,u!==void 0?h.map(y=>u?.[y]):void 0);await Promise.all(d.generations.map(async(y,w)=>{const O=h[w];return l[O]=y,o.update(e[O],c,y)})),p=d.llmOutput??{}}return{generations:l,llmOutput:p}}_identifyingParams(){return{}}_modelType(){return"base_llm"}},Xl=class extends ja{async _generate(t,e,n){return{generations:await Promise.all(t.map((r,a)=>this._call(r,{...e,promptIndex:a},n).then(i=>[{text:i}])))}}},Gl={};gn(Gl,{BaseToolkit:()=>Ql,DynamicStructuredTool:()=>Ba,DynamicTool:()=>Fa,StructuredTool:()=>qn,Tool:()=>Da,ToolInputParsingException:()=>Gt,isLangChainTool:()=>Ds,isRunnableToolLike:()=>ci,isStructuredTool:()=>li,isStructuredToolParams:()=>oi,tool:()=>Yl});var qn=class extends ui{returnDirect=!1;verboseParsingErrors=!1;get lc_namespace(){return["langchain","tools"]}responseFormat="content";defaultConfig;constructor(t){super(t??{}),this.verboseParsingErrors=t?.verboseParsingErrors??this.verboseParsingErrors,this.responseFormat=t?.responseFormat??this.responseFormat,this.defaultConfig=t?.defaultConfig??this.defaultConfig,this.metadata=t?.metadata??this.metadata}async invoke(t,e){let n,s=di(hi(this.defaultConfig,e));return Bt(t)?(n=t.args,s={...s,toolCall:t}):n=t,this.call(n,s)}async call(t,e,n){const s=Bt(t)?t.args:t;let r;if(Oe(this.schema))try{r=await fi(this.schema,s)}catch(d){let y="Received tool input did not match expected schema";throw this.verboseParsingErrors&&(y=`${y}
35
35
  Details: ${d.message}`),d instanceof Error&&d.constructor.name==="ZodError"&&(y=`${y}
36
36
 
37
37
  ${ki(d)}`),new Gt(y,JSON.stringify(t))}else{const d=xi(s,this.schema);if(!d.valid){let y="Received tool input did not match expected schema";throw this.verboseParsingErrors&&(y=`${y}
38
38
  Details: ${d.errors.map(w=>`${w.keywordLocation}: ${w.error}`).join(`
39
39
  `)}`),new Gt(y,JSON.stringify(t))}r=s}const a=yn(e),o=await nt.configure(a.callbacks,this.callbacks,a.tags||n,this.tags,a.metadata,this.metadata,{verbose:this.verbose})?.handleToolStart(this.toJSON(),typeof t=="string"?t:JSON.stringify(t),a.runId,void 0,void 0,void 0,a.runName);delete a.runId;let c;try{c=await this._call(r,o,a)}catch(d){throw await o?.handleToolError(d),d}let l,h;if(this.responseFormat==="content_and_artifact")if(Array.isArray(c)&&c.length===2)[l,h]=c;else throw new Error(`Tool response format is "content_and_artifact" but the output was not a two-tuple.
40
- Result: ${JSON.stringify(c)}`);else l=c;let u;Bt(t)&&(u=t.id),!u&&ii(a)&&(u=a.toolCall.id);const p=ec({content:l,artifact:h,toolCallId:u,name:this.name,metadata:this.metadata});return await o?.handleToolEnd(p),p}},Da=class extends qn{schema=wi({input:bi().optional()}).transform(t=>t.input);constructor(t){super(t)}call(t,e){const n=typeof t=="string"||t==null?{input:t}:t;return super.call(n,e)}},Fa=class extends Da{static lc_name(){return"DynamicTool"}name;description;func;constructor(t){super(t),this.name=t.name,this.description=t.description,this.func=t.func,this.returnDirect=t.returnDirect??this.returnDirect}async call(t,e){const n=yn(e);return n.runName===void 0&&(n.runName=this.name),super.call(t,n)}async _call(t,e,n){return this.func(t,e,n)}},Ba=class extends qn{static lc_name(){return"DynamicStructuredTool"}name;description;func;schema;constructor(t){super(t),this.name=t.name,this.description=t.description,this.func=t.func,this.returnDirect=t.returnDirect??this.returnDirect,this.schema=t.schema}async call(t,e,n){const s=yn(e);return s.runName===void 0&&(s.runName=this.name),super.call(t,s,n)}_call(t,e,n){return this.func(t,e,n)}},Ql=class{getTools(){return this.tools}};function Yl(t,e){const n=oi(e.schema),s=li(e.schema);if(!e.schema||n||s)return new Fa({...e,description:e.description??e.schema?.description??`${e.name} tool`,func:async(i,o,c)=>new Promise((l,h)=>{const u=Gn(c,{callbacks:o?.getChild()});Qn.runWithConfig(Yn(u),async()=>{try{l(t(i,u))}catch(p){h(p)}})})});const r=e.schema,a=e.description??e.schema.description??`${e.name} tool`;return new Ba({...e,description:a,schema:r,func:async(i,o,c)=>new Promise((l,h)=>{let u;const p=()=>{c?.signal&&u&&c.signal.removeEventListener("abort",u)};c?.signal&&(u=()=>{p(),h(ui(c.signal))},c.signal.addEventListener("abort",u));const d=Gn(c,{callbacks:o?.getChild()});Qn.runWithConfig(Yn(d),async()=>{try{const y=await t(i,d);if(c?.signal?.aborted){p();return}p(),l(y)}catch(y){p(),h(y)}})})})}function ec(t){const{content:e,artifact:n,toolCallId:s,metadata:r}=t;return s&&!ci(e)?typeof e=="string"||Array.isArray(e)&&e.every(a=>typeof a=="object")?new ht({status:"success",content:e,artifact:n,tool_call_id:s,name:t.name,metadata:r}):new ht({status:"success",content:tc(e),artifact:n,tool_call_id:s,name:t.name,metadata:r}):e}function tc(t){try{return JSON.stringify(t,null,2)??""}catch{return`${t}`}}export{Wn as BaseChatOpenAI,yc as ChatOpenAI,Hl as ChatOpenAICompletions,Zl as ChatOpenAIResponses,C as OpenAIClient,Ai as getEndpoint,qe as messageToOpenAIRole,xl as toFile,$a as wrapOpenAIClientError};
40
+ Result: ${JSON.stringify(c)}`);else l=c;let u;Bt(t)&&(u=t.id),!u&&pi(a)&&(u=a.toolCall.id);const p=ec({content:l,artifact:h,toolCallId:u,name:this.name,metadata:this.metadata});return await o?.handleToolEnd(p),p}},Da=class extends qn{schema=wi({input:bi().optional()}).transform(t=>t.input);constructor(t){super(t)}call(t,e){const n=typeof t=="string"||t==null?{input:t}:t;return super.call(n,e)}},Fa=class extends Da{static lc_name(){return"DynamicTool"}name;description;func;constructor(t){super(t),this.name=t.name,this.description=t.description,this.func=t.func,this.returnDirect=t.returnDirect??this.returnDirect}async call(t,e){const n=yn(e);return n.runName===void 0&&(n.runName=this.name),super.call(t,n)}async _call(t,e,n){return this.func(t,e,n)}},Ba=class extends qn{static lc_name(){return"DynamicStructuredTool"}name;description;func;schema;constructor(t){super(t),this.name=t.name,this.description=t.description,this.func=t.func,this.returnDirect=t.returnDirect??this.returnDirect,this.schema=t.schema}async call(t,e,n){const s=yn(e);return s.runName===void 0&&(s.runName=this.name),super.call(t,s,n)}_call(t,e,n){return this.func(t,e,n)}},Ql=class{getTools(){return this.tools}};function Yl(t,e){const n=mi(e.schema),s=gi(e.schema);if(!e.schema||n||s)return new Fa({...e,description:e.description??e.schema?.description??`${e.name} tool`,func:async(i,o,c)=>new Promise((l,h)=>{const u=es(c,{callbacks:o?.getChild()});ts.runWithConfig(ns(u),async()=>{try{l(t(i,u))}catch(p){h(p)}})})});const r=e.schema,a=e.description??e.schema.description??`${e.name} tool`;return new Ba({...e,description:a,schema:r,func:async(i,o,c)=>new Promise((l,h)=>{let u;const p=()=>{c?.signal&&u&&c.signal.removeEventListener("abort",u)};c?.signal&&(u=()=>{p(),h(yi(c.signal))},c.signal.addEventListener("abort",u));const d=es(c,{callbacks:o?.getChild()});ts.runWithConfig(ns(d),async()=>{try{const y=await t(i,d);if(c?.signal?.aborted){p();return}p(),l(y)}catch(y){p(),h(y)}})})})}function ec(t){const{content:e,artifact:n,toolCallId:s,metadata:r}=t;return s&&!_i(e)?typeof e=="string"||Array.isArray(e)&&e.every(a=>typeof a=="object")?new ht({status:"success",content:e,artifact:n,tool_call_id:s,name:t.name,metadata:r}):new ht({status:"success",content:tc(e),artifact:n,tool_call_id:s,name:t.name,metadata:r}):e}function tc(t){try{return JSON.stringify(t,null,2)??""}catch{return`${t}`}}export{Wn as BaseChatOpenAI,_c as ChatOpenAI,Hl as ChatOpenAICompletions,Zl as ChatOpenAIResponses,C as OpenAIClient,Ai as getEndpoint,qe as messageToOpenAIRole,xl as toFile,$a as wrapOpenAIClientError};