@arcgis/ai-components 5.2.0-next.70 → 5.2.0-next.72

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.
Files changed (98) hide show
  1. package/LICENSE.md +4 -2
  2. package/dist/agent-utils/types.d.ts +1 -1
  3. package/dist/agentic-workflow/AgenticWorkflowRuntime.d.ts +24 -0
  4. package/dist/agentic-workflow/Edge.d.ts +16 -0
  5. package/dist/agentic-workflow/WebAgent.d.ts +39 -0
  6. package/dist/agentic-workflow/jsonTypes.d.ts +186 -0
  7. package/dist/agentic-workflow/nodes/AgentNode.d.ts +26 -0
  8. package/dist/agentic-workflow/nodes/BaseNode.d.ts +35 -0
  9. package/dist/agentic-workflow/nodes/EndMessageNode.d.ts +25 -0
  10. package/dist/agentic-workflow/nodes/StartNode.d.ts +21 -0
  11. package/dist/agentic-workflow/nodes/support/Prompt.d.ts +20 -0
  12. package/dist/agentic-workflow/types.d.ts +29 -0
  13. package/dist/cdn/{PUFTYLJ2.js → 33BF35AO.js} +1 -1
  14. package/dist/cdn/55M2HE4U.js +2 -0
  15. package/dist/cdn/5RZGG4F2.js +2 -0
  16. package/dist/cdn/5SF6DEMO.js +2 -0
  17. package/dist/cdn/{MW5S2XCB.js → 5SFZS2RD.js} +1 -1
  18. package/dist/cdn/6QJFOL6M.js +2 -0
  19. package/dist/cdn/BAB3MK4Y.js +2 -0
  20. package/dist/cdn/BMBV6Y2A.js +2 -0
  21. package/dist/cdn/D3RKQSWS.js +2 -0
  22. package/dist/cdn/DBHLKLKM.js +2 -0
  23. package/dist/cdn/{CXW5URTF.js → DWYODVWW.js} +1 -1
  24. package/dist/cdn/{TFT6HK3O.js → E7KEOJZG.js} +1 -1
  25. package/dist/cdn/FSMHR7GK.js +2 -0
  26. package/dist/cdn/HO2YDJI2.js +6 -0
  27. package/dist/cdn/{KQHLOYKL.js → I4L45WQS.js} +1 -1
  28. package/dist/cdn/IGQFAL3H.js +2 -0
  29. package/dist/cdn/JYVBCHR6.js +6 -0
  30. package/dist/cdn/{XETNZW4D.js → NJJYZP3R.js} +1 -1
  31. package/dist/cdn/NSXX2KYS.js +2 -0
  32. package/dist/cdn/OFRFP4BX.js +2 -0
  33. package/dist/cdn/OUFGJV3R.js +2 -0
  34. package/dist/cdn/PAUIFUMO.js +2 -0
  35. package/dist/cdn/RWM5T4XB.js +180 -0
  36. package/dist/cdn/{YHQJ66WJ.js → S3XUYAUX.js} +1 -1
  37. package/dist/cdn/S6ZAQRC6.js +2 -0
  38. package/dist/cdn/SRFLL6ET.js +2 -0
  39. package/dist/cdn/UZL6UVE4.js +2 -0
  40. package/dist/cdn/{GP6NDTUE.js → WDOM6Z5O.js} +2 -2
  41. package/dist/cdn/WQKNV6KK.js +2 -0
  42. package/dist/cdn/{ICYUPLZM.js → WZFC5HUX.js} +1 -1
  43. package/dist/cdn/XPTCV6YV.js +2 -0
  44. package/dist/cdn/Y5UFOH54.js +2 -0
  45. package/dist/cdn/{E5ZKBC24.js → Z4XUJQ2I.js} +2 -2
  46. package/dist/cdn/{SXHH575T.js → ZJEWP2ND.js} +20 -24
  47. package/dist/cdn/agent-utils/index.js +1 -1
  48. package/dist/cdn/agent-utils/middlewares/humanInTheLoop.js +1 -1
  49. package/dist/cdn/agent-utils/middlewares/middleware.js +1 -1
  50. package/dist/cdn/agent-utils/middlewares/trace.js +1 -1
  51. package/dist/cdn/index.js +1 -1
  52. package/dist/chunks/adapter.js +668 -679
  53. package/dist/chunks/baseAgentState.js +56 -0
  54. package/dist/chunks/dataExplorationGraph.js +13 -13
  55. package/dist/chunks/generateLayerDescriptions.js +189 -235
  56. package/dist/chunks/navigationGraph.js +28 -28
  57. package/dist/chunks/orchestrator.js +1 -1
  58. package/dist/chunks/state.js +20 -26
  59. package/dist/chunks/utils2.js +3 -3
  60. package/dist/components/arcgis-assistant-agent/customElement.d.ts +13 -1
  61. package/dist/components/arcgis-assistant-agent/customElement.js +513 -12
  62. package/dist/components/arcgis-assistant-data-exploration-agent/customElement.js +1 -1
  63. package/dist/components/arcgis-assistant-help-agent/customElement.js +1 -1
  64. package/dist/components/arcgis-assistant-knowledge-agent/customElement.js +1 -1
  65. package/dist/components/arcgis-assistant-layer-styling-agent/customElement.js +1 -1
  66. package/dist/components/arcgis-assistant-navigation-agent/customElement.js +1 -1
  67. package/dist/docs/api.json +1 -1
  68. package/dist/docs/docs.json +1 -1
  69. package/dist/docs/vscode.html-custom-data.json +1 -1
  70. package/dist/docs/web-types.json +1 -1
  71. package/dist/loader.js +1 -1
  72. package/dist/types/lumina.d.ts +1 -1
  73. package/dist/types/preact.d.ts +1 -1
  74. package/dist/types/react.d.ts +1 -1
  75. package/dist/types/stencil.d.ts +1 -1
  76. package/dist/utils/index.js +26 -25
  77. package/package.json +4 -4
  78. package/dist/cdn/3DJDRAGV.js +0 -2
  79. package/dist/cdn/4CEMUECT.js +0 -2
  80. package/dist/cdn/4PCAK3ET.js +0 -2
  81. package/dist/cdn/57OMVTIU.js +0 -2
  82. package/dist/cdn/6U7TEAAJ.js +0 -2
  83. package/dist/cdn/BE7ZN5FZ.js +0 -2
  84. package/dist/cdn/BNSJO6X2.js +0 -2
  85. package/dist/cdn/CMDRED5H.js +0 -2
  86. package/dist/cdn/DTIVDIDY.js +0 -2
  87. package/dist/cdn/HBLRVXEB.js +0 -2
  88. package/dist/cdn/HQXPPYMD.js +0 -2
  89. package/dist/cdn/IEHPNCTL.js +0 -2
  90. package/dist/cdn/LHLO6PTD.js +0 -2
  91. package/dist/cdn/OWXCOUIQ.js +0 -2
  92. package/dist/cdn/PVE7Q43N.js +0 -2
  93. package/dist/cdn/ST5FQYT7.js +0 -180
  94. package/dist/cdn/WUNCZOGU.js +0 -2
  95. package/dist/cdn/WVPU4QOO.js +0 -2
  96. package/dist/cdn/WXWO5D3W.js +0 -2
  97. package/dist/cdn/XCRR2EEG.js +0 -6
  98. package/dist/cdn/ZS6SXJP2.js +0 -2
@@ -1,21 +1,21 @@
1
1
  /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
- import{b as Go}from"./R74ZHFA6.js";import{a as rt}from"./HJG7QM2R.js";import{b as Ai,c as Ii,d as bi}from"./ICYUPLZM.js";import{K as pi,L as mi,M as Bs,N as Fn,O as Dt,P as Bn,Q as di,R as fi,T as hi,U as _i,V as qs,W as gi,X as qn,Y as Wn,Z as yi,ha as re}from"./TFT6HK3O.js";import{Ab as li,C as Un,D as Ln,E as Us,Sb as E,U as Ls,V as Qo,X as ei,Xb as Lt,ca as ae,da as Ds,fa as Ut,fc as ci,ga as Ks,ha as ti,kb as ns,la as ri,o as Xo,ob as Kn,p as pe,pa as si,pb as ai,qb as ui,sb as os,tc as Fs,ua as Dn,v as Yo,w as js,xa as ni,yc as Ws}from"./LUY6V4TP.js";import{a as ue}from"./VXFQANGJ.js";import{$ as ii,Dd as x,j as oi}from"./MWYBF3F3.js";export default $arcgis.t(([Yu,Qu,Vp,Jp])=>{function is(t,e){return t.lc_error_code=e,t.message=`${t.message}
2
+ import{a as os,b as Ai,c as Ii,d as bi}from"./HO2YDJI2.js";import{b as Go}from"./R74ZHFA6.js";import{a as rt}from"./HJG7QM2R.js";import{b as xi,c as wi,d as Pi}from"./WZFC5HUX.js";import{K as pi,L as mi,M as Bs,N as Fn,O as Dt,P as Bn,Q as di,R as fi,T as hi,U as _i,V as qs,X as gi,Y as qn,Z as Wn,_ as yi,ia as ke}from"./E7KEOJZG.js";import{Ab as li,C as Un,D as Dn,E as Us,Sb as E,U as Ds,V as Qo,X as ei,Xb as Ut,ca as ie,da as Ls,fa as jt,fc as ci,ga as Ks,ha as ti,kb as ss,la as ri,o as Xo,ob as Kn,p as ce,pa as si,pb as ai,qb as ui,sb as ns,tc as Fs,ua as Ln,v as Yo,w as js,xa as ni,yc as Ws}from"./LUY6V4TP.js";import{a as ae}from"./VXFQANGJ.js";import{$ as ii,Dd as x,j as oi}from"./MWYBF3F3.js";export default $arcgis.t(([tl,rl,Vp,Jp])=>{function is(t,e){return t.lc_error_code=e,t.message=`${t.message}
3
3
 
4
4
  Troubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${e}/
5
- `,t}function k(t,e,r,s,n){if(s==="m")throw new TypeError("Private method is not writable");if(s==="a"&&!n)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return s==="a"?n.call(t,r):n?n.value=r:e.set(t,r),r}function d(t,e,r,s){if(r==="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 r==="m"?s:r==="a"?s.call(t):s?s.value:e.get(t)}var Hn=function(){let{crypto:t}=globalThis;if(t?.randomUUID)return Hn=t.randomUUID.bind(t),t.randomUUID();let e=new Uint8Array(1),r=t?()=>t.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,s=>(+s^r()&15>>+s/4).toString(16))};function as(t){return typeof t=="object"&&t!==null&&("name"in t&&t.name==="AbortError"||"message"in t&&String(t.message).includes("FetchRequestCanceledException"))}var us=t=>{if(t instanceof Error)return t;if(typeof t=="object"&&t!==null){try{if(Object.prototype.toString.call(t)==="[object Error]"){let 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)};var P=class extends Error{},U=class t extends P{constructor(e,r,s,n){super(`${t.makeMessage(e,r,s)}`),this.status=e,this.headers=n,this.requestID=n?.get("x-request-id"),this.error=r;let o=r;this.code=o?.code,this.param=o?.param,this.type=o?.type}static makeMessage(e,r,s){let n=r?.message?typeof r.message=="string"?r.message:JSON.stringify(r.message):r?JSON.stringify(r):s;return e&&n?`${e} ${n}`:e?`${e} status code (no body)`:n||"(no status code or body)"}static generate(e,r,s,n){if(!e||!n)return new De({message:s,cause:us(r)});let o=r?.error;return e===400?new Kt(e,o,s,n):e===401?new Ft(e,o,s,n):e===403?new Bt(e,o,s,n):e===404?new qt(e,o,s,n):e===409?new Wt(e,o,s,n):e===422?new Ht(e,o,s,n):e===429?new Zt(e,o,s,n):e>=500?new Vt(e,o,s,n):new t(e,o,s,n)}},L=class extends U{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},De=class extends U{constructor({message:e,cause:r}){super(void 0,void 0,e||"Connection error.",void 0),r&&(this.cause=r)}},Ae=class extends De{constructor({message:e}={}){super({message:e??"Request timed out."})}},Kt=class extends U{},Ft=class extends U{},Bt=class extends U{},qt=class extends U{},Wt=class extends U{},Ht=class extends U{},Zt=class extends U{},Vt=class extends U{},Jt=class extends P{constructor(){super("Could not parse response content as the length limit was reached")}},Gt=class extends P{constructor(){super("Could not parse response content as the request was rejected by the content filter")}},Ie=class extends Error{constructor(e){super(e)}},st=class extends U{constructor(e,r,s){let n="OAuth2 authentication error",o;if(r&&typeof r=="object"){let i=r;o=i.error;let a=i.error_description;a&&typeof a=="string"?n=a:o&&(n=o)}super(e,r,n,s),this.error_code=o}},ls=class extends P{constructor(e,r,s){super(e),this.provider=r,this.cause=s}};var cl=/^[a-z][a-z0-9+.-]*:/i,xi=t=>cl.test(t),Y=t=>(Y=Array.isArray,Y(t)),Zn=Y;function Hs(t){return typeof t!="object"?{}:t??{}}function Vn(t){if(!t)return!0;for(let e in t)return!1;return!0}function wi(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function cs(t){return t!=null&&typeof t=="object"&&!Array.isArray(t)}var Pi=(t,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new P(`${t} must be an integer`);if(e<0)throw new P(`${t} must be a positive integer`);return e};var Oi=t=>{try{return JSON.parse(t)}catch{return}};var be=t=>new Promise(e=>setTimeout(e,t));var Ke="6.45.0";var Ci=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function pl(){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"}var ml=()=>{let t=pl();if(t==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ke,"X-Stainless-OS":vi(Deno.build.os),"X-Stainless-Arch":ki(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":Ke,"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":Ke,"X-Stainless-OS":vi(globalThis.process.platform??"unknown"),"X-Stainless-Arch":ki(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=dl();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ke,"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":Ke,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function dl(){if(typeof navigator>"u"||!navigator)return null;let 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(let{key:e,pattern:r}of t){let s=r.exec(navigator.userAgent);if(s){let n=s[1]||0,o=s[2]||0,i=s[3]||0;return{browser:e,version:`${n}.${o}.${i}`}}}return null}var ki=t=>t==="x32"?"x32":t==="x86_64"||t==="x64"?"x64":t==="arm"?"arm":t==="aarch64"||t==="arm64"?"arm64":t?`other:${t}`:"unknown",vi=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"),Ti,Ri=()=>Ti??(Ti=ml());function Zs(){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 Jn(...t){let 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 Vs(t){let e=Symbol.asyncIterator in t?t[Symbol.asyncIterator]():t[Symbol.iterator]();return Jn({start(){},async pull(r){let{done:s,value:n}=await e.next();s?r.close():r.enqueue(n)},async cancel(){await e.return?.()}})}function Gn(t){if(t[Symbol.asyncIterator])return t;let e=t.getReader();return{async next(){try{let r=await e.read();return r?.done&&e.releaseLock(),r}catch(r){throw e.releaseLock(),r}},async return(){let r=e.cancel();return e.releaseLock(),await r,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function Xn(t){if(t===null||typeof t!="object")return;if(t[Symbol.asyncIterator]){await t[Symbol.asyncIterator]().return?.();return}let e=t.getReader(),r=e.cancel();e.releaseLock(),await r}var Si=({headers:t,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});var Yn="RFC3986",Qn=t=>String(t),eo={RFC1738:t=>String(t).replace(/%20/g,"+"),RFC3986:Qn},$i="RFC1738";var Js=(t,e)=>(Js=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),Js(t,e)),xe=(()=>{let t=[];for(let e=0;e<256;++e)t.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return t})();var to=1024,Mi=(t,e,r,s,n)=>{if(t.length===0)return t;let o=t;if(typeof t=="symbol"?o=Symbol.prototype.toString.call(t):typeof t!="string"&&(o=String(t)),r==="iso-8859-1")return escape(o).replace(/%u[0-9a-f]{4}/gi,function(a){return"%26%23"+parseInt(a.slice(2),16)+"%3B"});let i="";for(let a=0;a<o.length;a+=to){let c=o.length>=to?o.slice(a,a+to):o,u=[];for(let f=0;f<c.length;++f){let h=c.charCodeAt(f);if(h===45||h===46||h===95||h===126||h>=48&&h<=57||h>=65&&h<=90||h>=97&&h<=122||n===$i&&(h===40||h===41)){u[u.length]=c.charAt(f);continue}if(h<128){u[u.length]=xe[h];continue}if(h<2048){u[u.length]=xe[192|h>>6]+xe[128|h&63];continue}if(h<55296||h>=57344){u[u.length]=xe[224|h>>12]+xe[128|h>>6&63]+xe[128|h&63];continue}f+=1,h=65536+((h&1023)<<10|c.charCodeAt(f)&1023),u[u.length]=xe[240|h>>18]+xe[128|h>>12&63]+xe[128|h>>6&63]+xe[128|h&63]}i+=u.join("")}return i};function Ni(t){return!t||typeof t!="object"?!1:!!(t.constructor&&t.constructor.isBuffer&&t.constructor.isBuffer(t))}function ro(t,e){if(Y(t)){let r=[];for(let s=0;s<t.length;s+=1)r.push(e(t[s]));return r}return e(t)}var ji={brackets(t){return String(t)+"[]"},comma:"comma",indices(t,e){return String(t)+"["+e+"]"},repeat(t){return String(t)}},Ui=function(t,e){Array.prototype.push.apply(t,Y(e)?e:[e])},zi,W={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:Mi,encodeValuesOnly:!1,format:Yn,formatter:Qn,indices:!1,serializeDate(t){return(zi??(zi=Function.prototype.call.bind(Date.prototype.toISOString)))(t)},skipNulls:!1,strictNullHandling:!1};function hl(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"||typeof t=="symbol"||typeof t=="bigint"}var so={};function Li(t,e,r,s,n,o,i,a,c,u,f,h,g,A,I,b,_,m){let y=t,O=m,R=0,N=!1;for(;(O=O.get(so))!==void 0&&!N;){let F=O.get(t);if(R+=1,typeof F<"u"){if(F===R)throw new RangeError("Cyclic object value");N=!0}typeof O.get(so)>"u"&&(R=0)}if(typeof u=="function"?y=u(e,y):y instanceof Date?y=g?.(y):r==="comma"&&Y(y)&&(y=ro(y,function(F){return F instanceof Date?g?.(F):F})),y===null){if(o)return c&&!b?c(e,W.encoder,_,"key",A):e;y=""}if(hl(y)||Ni(y)){if(c){let F=b?e:c(e,W.encoder,_,"key",A);return[I?.(F)+"="+I?.(c(y,W.encoder,_,"value",A))]}return[I?.(e)+"="+I?.(String(y))]}let z=[];if(typeof y>"u")return z;let j;if(r==="comma"&&Y(y))b&&c&&(y=ro(y,c)),j=[{value:y.length>0?y.join(",")||null:void 0}];else if(Y(u))j=u;else{let F=Object.keys(y);j=f?F.sort(f):F}let D=a?String(e).replace(/\./g,"%2E"):String(e),X=s&&Y(y)&&y.length===1?D+"[]":D;if(n&&Y(y)&&y.length===0)return X+"[]";for(let F=0;F<j.length;++F){let q=j[F],Vo=typeof q=="object"&&typeof q.value<"u"?q.value:y[q];if(i&&Vo===null)continue;let jn=h&&a?q.replace(/\./g,"%2E"):q,ul=Y(y)?typeof r=="function"?r(X,jn):X:X+(h?"."+jn:"["+jn+"]");m.set(t,R);let Jo=new WeakMap;Jo.set(so,m),Ui(z,Li(Vo,ul,r,s,n,o,i,a,r==="comma"&&b&&Y(y)?null:c,u,f,h,g,A,I,b,_,Jo))}return z}function _l(t=W){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.");let e=t.charset||W.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 r=Yn;if(typeof t.format<"u"){if(!Js(eo,t.format))throw new TypeError("Unknown format option provided.");r=t.format}let s=eo[r],n=W.filter;(typeof t.filter=="function"||Y(t.filter))&&(n=t.filter);let o;if(t.arrayFormat&&t.arrayFormat in ji?o=t.arrayFormat:"indices"in t?o=t.indices?"indices":"repeat":o=W.arrayFormat,"commaRoundTrip"in t&&typeof t.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let i=typeof t.allowDots>"u"?t.encodeDotInKeys?!0:W.allowDots:!!t.allowDots;return{addQueryPrefix:typeof t.addQueryPrefix=="boolean"?t.addQueryPrefix:W.addQueryPrefix,allowDots:i,allowEmptyArrays:typeof t.allowEmptyArrays=="boolean"?!!t.allowEmptyArrays:W.allowEmptyArrays,arrayFormat:o,charset:e,charsetSentinel:typeof t.charsetSentinel=="boolean"?t.charsetSentinel:W.charsetSentinel,commaRoundTrip:!!t.commaRoundTrip,delimiter:typeof t.delimiter>"u"?W.delimiter:t.delimiter,encode:typeof t.encode=="boolean"?t.encode:W.encode,encodeDotInKeys:typeof t.encodeDotInKeys=="boolean"?t.encodeDotInKeys:W.encodeDotInKeys,encoder:typeof t.encoder=="function"?t.encoder:W.encoder,encodeValuesOnly:typeof t.encodeValuesOnly=="boolean"?t.encodeValuesOnly:W.encodeValuesOnly,filter:n,format:r,formatter:s,serializeDate:typeof t.serializeDate=="function"?t.serializeDate:W.serializeDate,skipNulls:typeof t.skipNulls=="boolean"?t.skipNulls:W.skipNulls,sort:typeof t.sort=="function"?t.sort:null,strictNullHandling:typeof t.strictNullHandling=="boolean"?t.strictNullHandling:W.strictNullHandling}}function Di(t,e={}){let r=t,s=_l(e),n,o;typeof s.filter=="function"?(o=s.filter,r=o("",r)):Y(s.filter)&&(o=s.filter,n=o);let i=[];if(typeof r!="object"||r===null)return"";let a=ji[s.arrayFormat],c=a==="comma"&&s.commaRoundTrip;n||(n=Object.keys(r)),s.sort&&n.sort(s.sort);let u=new WeakMap;for(let g=0;g<n.length;++g){let A=n[g];s.skipNulls&&r[A]===null||Ui(i,Li(r[A],A,a,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,u))}let f=i.join(s.delimiter),h=s.addQueryPrefix===!0?"?":"";return s.charsetSentinel&&(s.charset==="iso-8859-1"?h+="utf8=%26%2310003%3B&":h+="utf8=%E2%9C%93&"),f.length>0?h+f:""}function Ki(t){return Di(t,{arrayFormat:"brackets"})}function qi(t){let e=0;for(let n of t)e+=n.length;let r=new Uint8Array(e),s=0;for(let n of t)r.set(n,s),s+=n.length;return r}var Fi;function Xt(t){let e;return(Fi??(e=new globalThis.TextEncoder,Fi=e.encode.bind(e)))(t)}var Bi;function no(t){let e;return(Bi??(e=new globalThis.TextDecoder,Bi=e.decode.bind(e)))(t)}var se,ne,nt=class{constructor(){se.set(this,void 0),ne.set(this,void 0),k(this,se,new Uint8Array,"f"),k(this,ne,null,"f")}decode(e){if(e==null)return[];let r=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?Xt(e):e;k(this,se,qi([d(this,se,"f"),r]),"f");let s=[],n;for(;(n=yl(d(this,se,"f"),d(this,ne,"f")))!=null;){if(n.carriage&&d(this,ne,"f")==null){k(this,ne,n.index,"f");continue}if(d(this,ne,"f")!=null&&(n.index!==d(this,ne,"f")+1||n.carriage)){s.push(no(d(this,se,"f").subarray(0,d(this,ne,"f")-1))),k(this,se,d(this,se,"f").subarray(d(this,ne,"f")),"f"),k(this,ne,null,"f");continue}let o=d(this,ne,"f")!==null?n.preceding-1:n.preceding,i=no(d(this,se,"f").subarray(0,o));s.push(i),k(this,se,d(this,se,"f").subarray(n.index),"f"),k(this,ne,null,"f")}return s}flush(){return d(this,se,"f").length?this.decode(`
6
- `):[]}};se=new WeakMap,ne=new WeakMap;nt.NEWLINE_CHARS=new Set([`
7
- `,"\r"]);nt.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function yl(t,e){for(let n=e??0;n<t.length;n++){if(t[n]===10)return{preceding:n,index:n+1,carriage:!1};if(t[n]===13)return{preceding:n,index:n+1,carriage:!0}}return null}function Wi(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}var Xs={off:0,error:200,warn:300,info:400,debug:500},oo=(t,e,r)=>{if(t){if(wi(Xs,t))return t;K(r).warn(`${e} was set to ${JSON.stringify(t)}, expected one of ${JSON.stringify(Object.keys(Xs))}`)}};function ps(){}function Gs(t,e,r){return!e||Xs[t]>Xs[r]?ps:e[t].bind(e)}var Al={error:ps,warn:ps,info:ps,debug:ps},Hi=new WeakMap;function K(t){let e=t.logger,r=t.logLevel??"off";if(!e)return Al;let s=Hi.get(e);if(s&&s[0]===r)return s[1];let n={error:Gs("error",e,r),warn:Gs("warn",e,r),info:Gs("info",e,r),debug:Gs("debug",e,r)};return Hi.set(e,[r,n]),n}var ve=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,r])=>[e,e.toLowerCase()==="authorization"||e.toLowerCase()==="api-key"||e.toLowerCase()==="x-api-key"||e.toLowerCase()==="x-amz-security-token"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":r]))),"retryOfRequestLogID"in t&&(t.retryOfRequestLogID&&(t.retryOf=t.retryOfRequestLogID),delete t.retryOfRequestLogID),t);var ms,we=class t{constructor(e,r,s){this.iterator=e,ms.set(this,void 0),this.controller=r,k(this,ms,s,"f")}static fromSSEResponse(e,r,s,n){let o=!1,i=s?K(s):console;async function*a(){if(o)throw new P("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let c=!1;try{for await(let u of Il(e,r))if(!c){if(u.data.startsWith("[DONE]")){c=!0;continue}if(u.event===null||!u.event.startsWith("thread.")){let f;try{f=JSON.parse(u.data)}catch(h){throw i.error("Could not parse message into JSON:",u.data),i.error("From chunk:",u.raw),h}if(f&&f.error)throw new U(void 0,f.error,void 0,e.headers);yield n?{event:u.event,data:f}:f}else{let f;try{f=JSON.parse(u.data)}catch(h){throw console.error("Could not parse message into JSON:",u.data),console.error("From chunk:",u.raw),h}if(u.event=="error")throw new U(void 0,f.error,f.message,void 0);yield{event:u.event,data:f}}}c=!0}catch(u){if(as(u))return;throw u}finally{c||r.abort()}}return new t(a,r,s)}static fromReadableStream(e,r,s){let n=!1;async function*o(){let a=new nt,c=Gn(e);for await(let u of c)for(let f of a.decode(u))yield f;for(let u of a.flush())yield u}async function*i(){if(n)throw new P("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let a=!1;try{for await(let c of o())a||c&&(yield JSON.parse(c));a=!0}catch(c){if(as(c))return;throw c}finally{a||r.abort()}}return new t(i,r,s)}[(ms=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],r=[],s=this.iterator(),n=o=>({next:()=>{if(o.length===0){let i=s.next();e.push(i),r.push(i)}return o.shift()}});return[new t(()=>n(e),this.controller,d(this,ms,"f")),new t(()=>n(r),this.controller,d(this,ms,"f"))]}toReadableStream(){let e=this,r;return Jn({async start(){r=e[Symbol.asyncIterator]()},async pull(s){try{let{value:n,done:o}=await r.next();if(o)return s.close();let i=Xt(JSON.stringify(n)+`
8
- `);s.enqueue(i)}catch(n){s.error(n)}},async cancel(){await r.return?.()}})}};async function*Il(t,e){if(!t.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new P("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 P("Attempted to iterate over a response with no body");let r=new io,s=new nt,n=Gn(t.body);for await(let o of bl(n))for(let i of s.decode(o)){let a=r.decode(i);a&&(yield a)}for(let o of s.flush()){let i=r.decode(o);i&&(yield i)}}async function*bl(t){let e=new Uint8Array;for await(let r of t){if(r==null)continue;let s=r instanceof ArrayBuffer?new Uint8Array(r):typeof r=="string"?Xt(r):r,n=new Uint8Array(e.length+s.length);n.set(e),n.set(s,e.length),e=n;let o;for(;(o=Wi(e))!==-1;)yield e.slice(0,o),e=e.slice(o)}e.length>0&&(yield e)}var io=class{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;let o={event:this.event,data:this.data.join(`
9
- `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],o}if(this.chunks.push(e),e.startsWith(":"))return null;let[r,s,n]=xl(e,":");return n.startsWith(" ")&&(n=n.substring(1)),r==="event"?this.event=n:r==="data"&&this.data.push(n),null}};function xl(t,e){let r=t.indexOf(e);return r!==-1?[t.substring(0,r),e,t.substring(r+e.length)]:[t,"",""]}async function Ys(t,e){let{response:r,requestLogID:s,retryOfRequestLogID:n,startTime:o}=e,i=await(async()=>{if(e.options.stream)return K(t).debug("response",r.status,r.url,r.headers,r.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(r,e.controller,t,e.options.__synthesizeEventData):we.fromSSEResponse(r,e.controller,t,e.options.__synthesizeEventData);if(r.status===204)return null;if(e.options.__binaryResponse)return r;let c=r.headers.get("content-type")?.split(";")[0]?.trim();if(c?.includes("application/json")||c?.endsWith("+json")){if(r.headers.get("content-length")==="0")return;let g=await r.json();return ao(g,r)}return await r.text()})();return K(t).debug(`[${s}] response parsed`,ve({retryOfRequestLogID:n,url:r.url,status:r.status,body:i,durationMs:Date.now()-o})),i}function ao(t,e){return!t||typeof t!="object"||Array.isArray(t)?t:Object.defineProperty(t,"_request_id",{value:e.headers.get("x-request-id"),enumerable:!1})}var ds,ot=class t extends Promise{constructor(e,r,s=Ys){super(n=>{n(null)}),this.responsePromise=r,this.parseResponse=s,ds.set(this,void 0),k(this,ds,e,"f")}_thenUnwrap(e){return new t(d(this,ds,"f"),this.responsePromise,async(r,s)=>ao(e(await this.parseResponse(r,s),s),s.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,r]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:r,request_id:r.headers.get("x-request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(d(this,ds,"f"),e))),this.parsedPromise}then(e,r){return this.parse().then(e,r)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}};ds=new WeakMap;var Qs,Yt=class{constructor(e,r,s,n){Qs.set(this,void 0),k(this,Qs,e,"f"),this.options=n,this.response=r,this.body=s}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new P("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await d(this,Qs,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(Qs=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let r of e.getPaginatedItems())yield r}},fs=class extends ot{constructor(e,r,s){super(e,r,async(n,o)=>new s(n,o.response,await Ys(n,o),o.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let r of e)yield r}},Q=class extends Yt{constructor(e,r,s,n){super(e,r,s,n),this.data=s.data||[],this.object=s.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}},C=class extends Yt{constructor(e,r,s,n){super(e,r,s,n),this.data=s.data||[],this.has_more=s.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.getPaginatedItems(),r=e[e.length-1]?.id;return r?{...this.options,query:{...Hs(this.options.query),after:r}}:null}},$=class extends Yt{constructor(e,r,s,n){super(e,r,s,n),this.data=s.data||[],this.has_more=s.has_more||!1,this.last_id=s.last_id||""}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.last_id;return e?{...this.options,query:{...Hs(this.options.query),after:e}}:null}},B=class extends Yt{constructor(e,r,s,n){super(e,r,s,n),this.data=s.data||[],this.has_more=s.has_more||!1,this.next=s.next||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.next;return e?{...this.options,query:{...Hs(this.options.query),after:e}}:null}};var Pl={jwt:"urn:ietf:params:oauth:token-type:jwt",id:"urn:ietf:params:oauth:token-type:id_token"},Ol="urn:ietf:params:oauth:grant-type:token-exchange",en=class{constructor(e,r){this.cachedToken=null,this.refreshPromise=null,this.tokenExchangeUrl="https://auth.openai.com/oauth/token",this.config=e,this.fetch=r??Zs()}async getToken(){if(!this.cachedToken||this.isTokenExpired(this.cachedToken)){if(this.refreshPromise)return await this.refreshPromise;this.refreshPromise=this.refreshToken();try{return await this.refreshPromise}finally{this.refreshPromise=null}}return this.needsRefresh(this.cachedToken)&&!this.refreshPromise&&(this.refreshPromise=this.refreshToken().finally(()=>{this.refreshPromise=null})),this.cachedToken.token}async refreshToken(){let e=await this.config.provider.getToken(),r={grant_type:Ol,subject_token:e,subject_token_type:Pl[this.config.provider.tokenType],identity_provider_id:this.config.identityProviderId,service_account_id:this.config.serviceAccountId};this.config.clientId&&(r.client_id=this.config.clientId);let s=await this.fetch(this.tokenExchangeUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!s.ok){let c=await s.text(),u;try{u=JSON.parse(c)}catch{}throw s.status===400||s.status===401||s.status===403?new st(s.status,u,s.headers):U.generate(s.status,u,`Token exchange failed with status ${s.status}`,s.headers)}let n=await s.json();if(typeof n!="object"||n===null||!("access_token"in n)||typeof n.access_token!="string"||n.access_token.trim().length===0)throw new P("Token exchange response missing 'access_token' field");let o=n.access_token,i=n.expires_in??3600,a=Date.now()+i*1e3;return this.cachedToken={token:o,expiresAt:a},o}isTokenExpired(e){return Date.now()>=e.expiresAt}needsRefresh(e){let s=(this.config.refreshBufferSeconds??1200)*1e3;return Date.now()>=e.expiresAt-s}invalidateToken(){this.cachedToken=null,this.refreshPromise=null}};var co=()=>{if(typeof File>"u"){let{process:t}=globalThis,e=typeof t?.versions?.node=="string"&&parseInt(t.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(e?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function Qt(t,e,r){return co(),new File(t,e??"unknown_file",r)}function hs(t){return(typeof t=="object"&&t!==null&&("name"in t&&t.name&&String(t.name)||"url"in t&&t.url&&String(t.url)||"filename"in t&&t.filename&&String(t.filename)||"path"in t&&t.path&&String(t.path))||"").split(/[\\/]/).pop()||void 0}var tn=t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function",Fe=async(t,e)=>uo(t.body)?{...t,body:await Vi(t.body,e)}:t,ee=async(t,e)=>({...t,body:await Vi(t.body,e)}),Zi=new WeakMap;function kl(t){let e=typeof t=="function"?t:t.fetch,r=Zi.get(e);if(r)return r;let s=(async()=>{try{let n="Response"in e?e.Response:(await e("data:,")).constructor,o=new FormData;return o.toString()!==await new n(o).text()}catch{return!0}})();return Zi.set(e,s),s}var Vi=async(t,e)=>{if(!await kl(e))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let r=new FormData;return await Promise.all(Object.entries(t||{}).map(([s,n])=>lo(r,s,n))),r},Ji=t=>t instanceof Blob&&"name"in t,vl=t=>typeof t=="object"&&t!==null&&(t instanceof Response||tn(t)||Ji(t)),uo=t=>{if(vl(t))return!0;if(Array.isArray(t))return t.some(uo);if(t&&typeof t=="object"){for(let e in t)if(uo(t[e]))return!0}return!1},lo=async(t,e,r)=>{if(r!==void 0){if(r==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof r=="string"||typeof r=="number"||typeof r=="boolean")t.append(e,String(r));else if(r instanceof Response)t.append(e,Qt([await r.blob()],hs(r)));else if(tn(r))t.append(e,Qt([await new Response(Vs(r)).blob()],hs(r)));else if(Ji(r))t.append(e,r,hs(r));else if(Array.isArray(r))await Promise.all(r.map(s=>lo(t,e+"[]",s)));else if(typeof r=="object")await Promise.all(Object.entries(r).map(([s,n])=>lo(t,`${e}[${s}]`,n)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${r} instead`)}};var Gi=t=>t!=null&&typeof t=="object"&&typeof t.size=="number"&&typeof t.type=="string"&&typeof t.text=="function"&&typeof t.slice=="function"&&typeof t.arrayBuffer=="function",Tl=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&Gi(t),Cl=t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function";async function _s(t,e,r){if(co(),t=await t,Tl(t))return t instanceof File?t:Qt([await t.arrayBuffer()],t.name);if(Cl(t)){let n=await t.blob();return e||(e=new URL(t.url).pathname.split(/[\\/]/).pop()),Qt(await po(n),e,r)}let s=await po(t);if(e||(e=hs(t)),!r?.type){let n=s.find(o=>typeof o=="object"&&"type"in o&&o.type);typeof n=="string"&&(r={...r,type:n})}return Qt(s,e,r)}async function po(t){let e=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)e.push(t);else if(Gi(t))e.push(t instanceof Blob?t:await t.arrayBuffer());else if(tn(t))for await(let r of t)e.push(...await po(r));else{let r=t?.constructor?.name;throw new Error(`Unexpected data type: ${typeof t}${r?`; constructor: ${r}`:""}${Rl(t)}`)}return e}function Rl(t){return typeof t!="object"||t===null?"":`; props: [${Object.getOwnPropertyNames(t).map(r=>`"${r}"`).join(", ")}]`}var p=class{constructor(e){this._client=e}};function Yi(t){return t.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var Xi=Object.freeze(Object.create(null)),Sl=(t=Yi)=>function(r,...s){if(r.length===1)return r[0];let n=!1,o=[],i=r.reduce((f,h,g)=>{/[?#]/.test(h)&&(n=!0);let A=s[g],I=(n?encodeURIComponent:t)(""+A);return g!==s.length&&(A==null||typeof A=="object"&&A.toString===Object.getPrototypeOf(Object.getPrototypeOf(A.hasOwnProperty??Xi)??Xi)?.toString)&&(I=A+"",o.push({start:f.length+h.length,length:I.length,error:`Value of type ${Object.prototype.toString.call(A).slice(8,-1)} is not a valid path parameter`})),f+h+(g===s.length?"":I)},""),a=i.split(/[?#]/,1)[0],c=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,u;for(;(u=c.exec(a))!==null;)o.push({start:u.index,length:u[0].length,error:`Value "${u[0]}" can't be safely passed as a path parameter`});if(o.sort((f,h)=>f.start-h.start),o.length>0){let f=0,h=o.reduce((g,A)=>{let I=" ".repeat(A.start-f),b="^".repeat(A.length);return f=A.start+A.length,g+I+b},"");throw new P(`Path parameters result in path with invalid segments:
5
+ `,t}function k(t,e,r,s,n){if(s==="m")throw new TypeError("Private method is not writable");if(s==="a"&&!n)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return s==="a"?n.call(t,r):n?n.value=r:e.set(t,r),r}function d(t,e,r,s){if(r==="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 r==="m"?s:r==="a"?s.call(t):s?s.value:e.get(t)}var Hn=function(){let{crypto:t}=globalThis;if(t?.randomUUID)return Hn=t.randomUUID.bind(t),t.randomUUID();let e=new Uint8Array(1),r=t?()=>t.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,s=>(+s^r()&15>>+s/4).toString(16))};function as(t){return typeof t=="object"&&t!==null&&("name"in t&&t.name==="AbortError"||"message"in t&&String(t.message).includes("FetchRequestCanceledException"))}var us=t=>{if(t instanceof Error)return t;if(typeof t=="object"&&t!==null){try{if(Object.prototype.toString.call(t)==="[object Error]"){let 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)};var P=class extends Error{},U=class t extends P{constructor(e,r,s,n){super(`${t.makeMessage(e,r,s)}`),this.status=e,this.headers=n,this.requestID=n?.get("x-request-id"),this.error=r;let o=r;this.code=o?.code,this.param=o?.param,this.type=o?.type}static makeMessage(e,r,s){let n=r?.message?typeof r.message=="string"?r.message:JSON.stringify(r.message):r?JSON.stringify(r):s;return e&&n?`${e} ${n}`:e?`${e} status code (no body)`:n||"(no status code or body)"}static generate(e,r,s,n){if(!e||!n)return new Le({message:s,cause:us(r)});let o=r?.error;return e===400?new Lt(e,o,s,n):e===401?new Kt(e,o,s,n):e===403?new Ft(e,o,s,n):e===404?new Bt(e,o,s,n):e===409?new qt(e,o,s,n):e===422?new Wt(e,o,s,n):e===429?new Ht(e,o,s,n):e>=500?new Zt(e,o,s,n):new t(e,o,s,n)}},D=class extends U{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},Le=class extends U{constructor({message:e,cause:r}){super(void 0,void 0,e||"Connection error.",void 0),r&&(this.cause=r)}},ye=class extends Le{constructor({message:e}={}){super({message:e??"Request timed out."})}},Lt=class extends U{},Kt=class extends U{},Ft=class extends U{},Bt=class extends U{},qt=class extends U{},Wt=class extends U{},Ht=class extends U{},Zt=class extends U{},Vt=class extends P{constructor(){super("Could not parse response content as the length limit was reached")}},Jt=class extends P{constructor(){super("Could not parse response content as the request was rejected by the content filter")}},Ae=class extends Error{constructor(e){super(e)}},st=class extends U{constructor(e,r,s){let n="OAuth2 authentication error",o;if(r&&typeof r=="object"){let i=r;o=i.error;let a=i.error_description;a&&typeof a=="string"?n=a:o&&(n=o)}super(e,r,n,s),this.error_code=o}},ls=class extends P{constructor(e,r,s){super(e),this.provider=r,this.cause=s}};var cl=/^[a-z][a-z0-9+.-]*:/i,Oi=t=>cl.test(t),Y=t=>(Y=Array.isArray,Y(t)),Zn=Y;function Hs(t){return typeof t!="object"?{}:t??{}}function Vn(t){if(!t)return!0;for(let e in t)return!1;return!0}function ki(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function cs(t){return t!=null&&typeof t=="object"&&!Array.isArray(t)}var vi=(t,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new P(`${t} must be an integer`);if(e<0)throw new P(`${t} must be a positive integer`);return e};var Ti=t=>{try{return JSON.parse(t)}catch{return}};var Ie=t=>new Promise(e=>setTimeout(e,t));var Ke="6.45.0";var Si=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function pl(){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"}var ml=()=>{let t=pl();if(t==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ke,"X-Stainless-OS":Ri(Deno.build.os),"X-Stainless-Arch":Ci(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":Ke,"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":Ke,"X-Stainless-OS":Ri(globalThis.process.platform??"unknown"),"X-Stainless-Arch":Ci(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=dl();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ke,"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":Ke,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function dl(){if(typeof navigator>"u"||!navigator)return null;let 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(let{key:e,pattern:r}of t){let s=r.exec(navigator.userAgent);if(s){let n=s[1]||0,o=s[2]||0,i=s[3]||0;return{browser:e,version:`${n}.${o}.${i}`}}}return null}var Ci=t=>t==="x32"?"x32":t==="x86_64"||t==="x64"?"x64":t==="arm"?"arm":t==="aarch64"||t==="arm64"?"arm64":t?`other:${t}`:"unknown",Ri=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"),Ei,$i=()=>Ei??(Ei=ml());function Zs(){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 Jn(...t){let 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 Vs(t){let e=Symbol.asyncIterator in t?t[Symbol.asyncIterator]():t[Symbol.iterator]();return Jn({start(){},async pull(r){let{done:s,value:n}=await e.next();s?r.close():r.enqueue(n)},async cancel(){await e.return?.()}})}function Gn(t){if(t[Symbol.asyncIterator])return t;let e=t.getReader();return{async next(){try{let r=await e.read();return r?.done&&e.releaseLock(),r}catch(r){throw e.releaseLock(),r}},async return(){let r=e.cancel();return e.releaseLock(),await r,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function Xn(t){if(t===null||typeof t!="object")return;if(t[Symbol.asyncIterator]){await t[Symbol.asyncIterator]().return?.();return}let e=t.getReader(),r=e.cancel();e.releaseLock(),await r}var Ni=({headers:t,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});var Yn="RFC3986",Qn=t=>String(t),eo={RFC1738:t=>String(t).replace(/%20/g,"+"),RFC3986:Qn},zi="RFC1738";var Js=(t,e)=>(Js=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),Js(t,e)),be=(()=>{let t=[];for(let e=0;e<256;++e)t.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return t})();var to=1024,ji=(t,e,r,s,n)=>{if(t.length===0)return t;let o=t;if(typeof t=="symbol"?o=Symbol.prototype.toString.call(t):typeof t!="string"&&(o=String(t)),r==="iso-8859-1")return escape(o).replace(/%u[0-9a-f]{4}/gi,function(a){return"%26%23"+parseInt(a.slice(2),16)+"%3B"});let i="";for(let a=0;a<o.length;a+=to){let c=o.length>=to?o.slice(a,a+to):o,u=[];for(let f=0;f<c.length;++f){let h=c.charCodeAt(f);if(h===45||h===46||h===95||h===126||h>=48&&h<=57||h>=65&&h<=90||h>=97&&h<=122||n===zi&&(h===40||h===41)){u[u.length]=c.charAt(f);continue}if(h<128){u[u.length]=be[h];continue}if(h<2048){u[u.length]=be[192|h>>6]+be[128|h&63];continue}if(h<55296||h>=57344){u[u.length]=be[224|h>>12]+be[128|h>>6&63]+be[128|h&63];continue}f+=1,h=65536+((h&1023)<<10|c.charCodeAt(f)&1023),u[u.length]=be[240|h>>18]+be[128|h>>12&63]+be[128|h>>6&63]+be[128|h&63]}i+=u.join("")}return i};function Ui(t){return!t||typeof t!="object"?!1:!!(t.constructor&&t.constructor.isBuffer&&t.constructor.isBuffer(t))}function ro(t,e){if(Y(t)){let r=[];for(let s=0;s<t.length;s+=1)r.push(e(t[s]));return r}return e(t)}var Li={brackets(t){return String(t)+"[]"},comma:"comma",indices(t,e){return String(t)+"["+e+"]"},repeat(t){return String(t)}},Ki=function(t,e){Array.prototype.push.apply(t,Y(e)?e:[e])},Di,W={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:ji,encodeValuesOnly:!1,format:Yn,formatter:Qn,indices:!1,serializeDate(t){return(Di??(Di=Function.prototype.call.bind(Date.prototype.toISOString)))(t)},skipNulls:!1,strictNullHandling:!1};function hl(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"||typeof t=="symbol"||typeof t=="bigint"}var so={};function Fi(t,e,r,s,n,o,i,a,c,u,f,h,g,A,I,b,_,m){let y=t,O=m,R=0,N=!1;for(;(O=O.get(so))!==void 0&&!N;){let F=O.get(t);if(R+=1,typeof F<"u"){if(F===R)throw new RangeError("Cyclic object value");N=!0}typeof O.get(so)>"u"&&(R=0)}if(typeof u=="function"?y=u(e,y):y instanceof Date?y=g?.(y):r==="comma"&&Y(y)&&(y=ro(y,function(F){return F instanceof Date?g?.(F):F})),y===null){if(o)return c&&!b?c(e,W.encoder,_,"key",A):e;y=""}if(hl(y)||Ui(y)){if(c){let F=b?e:c(e,W.encoder,_,"key",A);return[I?.(F)+"="+I?.(c(y,W.encoder,_,"value",A))]}return[I?.(e)+"="+I?.(String(y))]}let z=[];if(typeof y>"u")return z;let j;if(r==="comma"&&Y(y))b&&c&&(y=ro(y,c)),j=[{value:y.length>0?y.join(",")||null:void 0}];else if(Y(u))j=u;else{let F=Object.keys(y);j=f?F.sort(f):F}let L=a?String(e).replace(/\./g,"%2E"):String(e),X=s&&Y(y)&&y.length===1?L+"[]":L;if(n&&Y(y)&&y.length===0)return X+"[]";for(let F=0;F<j.length;++F){let q=j[F],Vo=typeof q=="object"&&typeof q.value<"u"?q.value:y[q];if(i&&Vo===null)continue;let jn=h&&a?q.replace(/\./g,"%2E"):q,ul=Y(y)?typeof r=="function"?r(X,jn):X:X+(h?"."+jn:"["+jn+"]");m.set(t,R);let Jo=new WeakMap;Jo.set(so,m),Ki(z,Fi(Vo,ul,r,s,n,o,i,a,r==="comma"&&b&&Y(y)?null:c,u,f,h,g,A,I,b,_,Jo))}return z}function _l(t=W){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.");let e=t.charset||W.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 r=Yn;if(typeof t.format<"u"){if(!Js(eo,t.format))throw new TypeError("Unknown format option provided.");r=t.format}let s=eo[r],n=W.filter;(typeof t.filter=="function"||Y(t.filter))&&(n=t.filter);let o;if(t.arrayFormat&&t.arrayFormat in Li?o=t.arrayFormat:"indices"in t?o=t.indices?"indices":"repeat":o=W.arrayFormat,"commaRoundTrip"in t&&typeof t.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let i=typeof t.allowDots>"u"?t.encodeDotInKeys?!0:W.allowDots:!!t.allowDots;return{addQueryPrefix:typeof t.addQueryPrefix=="boolean"?t.addQueryPrefix:W.addQueryPrefix,allowDots:i,allowEmptyArrays:typeof t.allowEmptyArrays=="boolean"?!!t.allowEmptyArrays:W.allowEmptyArrays,arrayFormat:o,charset:e,charsetSentinel:typeof t.charsetSentinel=="boolean"?t.charsetSentinel:W.charsetSentinel,commaRoundTrip:!!t.commaRoundTrip,delimiter:typeof t.delimiter>"u"?W.delimiter:t.delimiter,encode:typeof t.encode=="boolean"?t.encode:W.encode,encodeDotInKeys:typeof t.encodeDotInKeys=="boolean"?t.encodeDotInKeys:W.encodeDotInKeys,encoder:typeof t.encoder=="function"?t.encoder:W.encoder,encodeValuesOnly:typeof t.encodeValuesOnly=="boolean"?t.encodeValuesOnly:W.encodeValuesOnly,filter:n,format:r,formatter:s,serializeDate:typeof t.serializeDate=="function"?t.serializeDate:W.serializeDate,skipNulls:typeof t.skipNulls=="boolean"?t.skipNulls:W.skipNulls,sort:typeof t.sort=="function"?t.sort:null,strictNullHandling:typeof t.strictNullHandling=="boolean"?t.strictNullHandling:W.strictNullHandling}}function Bi(t,e={}){let r=t,s=_l(e),n,o;typeof s.filter=="function"?(o=s.filter,r=o("",r)):Y(s.filter)&&(o=s.filter,n=o);let i=[];if(typeof r!="object"||r===null)return"";let a=Li[s.arrayFormat],c=a==="comma"&&s.commaRoundTrip;n||(n=Object.keys(r)),s.sort&&n.sort(s.sort);let u=new WeakMap;for(let g=0;g<n.length;++g){let A=n[g];s.skipNulls&&r[A]===null||Ki(i,Fi(r[A],A,a,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,u))}let f=i.join(s.delimiter),h=s.addQueryPrefix===!0?"?":"";return s.charsetSentinel&&(s.charset==="iso-8859-1"?h+="utf8=%26%2310003%3B&":h+="utf8=%E2%9C%93&"),f.length>0?h+f:""}function qi(t){return Bi(t,{arrayFormat:"brackets"})}function Zi(t){let e=0;for(let n of t)e+=n.length;let r=new Uint8Array(e),s=0;for(let n of t)r.set(n,s),s+=n.length;return r}var Wi;function Gt(t){let e;return(Wi??(e=new globalThis.TextEncoder,Wi=e.encode.bind(e)))(t)}var Hi;function no(t){let e;return(Hi??(e=new globalThis.TextDecoder,Hi=e.decode.bind(e)))(t)}var re,se,nt=class{constructor(){re.set(this,void 0),se.set(this,void 0),k(this,re,new Uint8Array,"f"),k(this,se,null,"f")}decode(e){if(e==null)return[];let r=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?Gt(e):e;k(this,re,Zi([d(this,re,"f"),r]),"f");let s=[],n;for(;(n=yl(d(this,re,"f"),d(this,se,"f")))!=null;){if(n.carriage&&d(this,se,"f")==null){k(this,se,n.index,"f");continue}if(d(this,se,"f")!=null&&(n.index!==d(this,se,"f")+1||n.carriage)){s.push(no(d(this,re,"f").subarray(0,d(this,se,"f")-1))),k(this,re,d(this,re,"f").subarray(d(this,se,"f")),"f"),k(this,se,null,"f");continue}let o=d(this,se,"f")!==null?n.preceding-1:n.preceding,i=no(d(this,re,"f").subarray(0,o));s.push(i),k(this,re,d(this,re,"f").subarray(n.index),"f"),k(this,se,null,"f")}return s}flush(){return d(this,re,"f").length?this.decode(`
6
+ `):[]}};re=new WeakMap,se=new WeakMap;nt.NEWLINE_CHARS=new Set([`
7
+ `,"\r"]);nt.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function yl(t,e){for(let n=e??0;n<t.length;n++){if(t[n]===10)return{preceding:n,index:n+1,carriage:!1};if(t[n]===13)return{preceding:n,index:n+1,carriage:!0}}return null}function Vi(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}var Xs={off:0,error:200,warn:300,info:400,debug:500},oo=(t,e,r)=>{if(t){if(ki(Xs,t))return t;K(r).warn(`${e} was set to ${JSON.stringify(t)}, expected one of ${JSON.stringify(Object.keys(Xs))}`)}};function ps(){}function Gs(t,e,r){return!e||Xs[t]>Xs[r]?ps:e[t].bind(e)}var Al={error:ps,warn:ps,info:ps,debug:ps},Ji=new WeakMap;function K(t){let e=t.logger,r=t.logLevel??"off";if(!e)return Al;let s=Ji.get(e);if(s&&s[0]===r)return s[1];let n={error:Gs("error",e,r),warn:Gs("warn",e,r),info:Gs("info",e,r),debug:Gs("debug",e,r)};return Ji.set(e,[r,n]),n}var ve=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,r])=>[e,e.toLowerCase()==="authorization"||e.toLowerCase()==="api-key"||e.toLowerCase()==="x-api-key"||e.toLowerCase()==="x-amz-security-token"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":r]))),"retryOfRequestLogID"in t&&(t.retryOfRequestLogID&&(t.retryOf=t.retryOfRequestLogID),delete t.retryOfRequestLogID),t);var ms,xe=class t{constructor(e,r,s){this.iterator=e,ms.set(this,void 0),this.controller=r,k(this,ms,s,"f")}static fromSSEResponse(e,r,s,n){let o=!1,i=s?K(s):console;async function*a(){if(o)throw new P("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let c=!1;try{for await(let u of Il(e,r))if(!c){if(u.data.startsWith("[DONE]")){c=!0;continue}if(u.event===null||!u.event.startsWith("thread.")){let f;try{f=JSON.parse(u.data)}catch(h){throw i.error("Could not parse message into JSON:",u.data),i.error("From chunk:",u.raw),h}if(f&&f.error)throw new U(void 0,f.error,void 0,e.headers);yield n?{event:u.event,data:f}:f}else{let f;try{f=JSON.parse(u.data)}catch(h){throw console.error("Could not parse message into JSON:",u.data),console.error("From chunk:",u.raw),h}if(u.event=="error")throw new U(void 0,f.error,f.message,void 0);yield{event:u.event,data:f}}}c=!0}catch(u){if(as(u))return;throw u}finally{c||r.abort()}}return new t(a,r,s)}static fromReadableStream(e,r,s){let n=!1;async function*o(){let a=new nt,c=Gn(e);for await(let u of c)for(let f of a.decode(u))yield f;for(let u of a.flush())yield u}async function*i(){if(n)throw new P("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let a=!1;try{for await(let c of o())a||c&&(yield JSON.parse(c));a=!0}catch(c){if(as(c))return;throw c}finally{a||r.abort()}}return new t(i,r,s)}[(ms=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],r=[],s=this.iterator(),n=o=>({next:()=>{if(o.length===0){let i=s.next();e.push(i),r.push(i)}return o.shift()}});return[new t(()=>n(e),this.controller,d(this,ms,"f")),new t(()=>n(r),this.controller,d(this,ms,"f"))]}toReadableStream(){let e=this,r;return Jn({async start(){r=e[Symbol.asyncIterator]()},async pull(s){try{let{value:n,done:o}=await r.next();if(o)return s.close();let i=Gt(JSON.stringify(n)+`
8
+ `);s.enqueue(i)}catch(n){s.error(n)}},async cancel(){await r.return?.()}})}};async function*Il(t,e){if(!t.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new P("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 P("Attempted to iterate over a response with no body");let r=new io,s=new nt,n=Gn(t.body);for await(let o of bl(n))for(let i of s.decode(o)){let a=r.decode(i);a&&(yield a)}for(let o of s.flush()){let i=r.decode(o);i&&(yield i)}}async function*bl(t){let e=new Uint8Array;for await(let r of t){if(r==null)continue;let s=r instanceof ArrayBuffer?new Uint8Array(r):typeof r=="string"?Gt(r):r,n=new Uint8Array(e.length+s.length);n.set(e),n.set(s,e.length),e=n;let o;for(;(o=Vi(e))!==-1;)yield e.slice(0,o),e=e.slice(o)}e.length>0&&(yield e)}var io=class{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;let o={event:this.event,data:this.data.join(`
9
+ `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],o}if(this.chunks.push(e),e.startsWith(":"))return null;let[r,s,n]=xl(e,":");return n.startsWith(" ")&&(n=n.substring(1)),r==="event"?this.event=n:r==="data"&&this.data.push(n),null}};function xl(t,e){let r=t.indexOf(e);return r!==-1?[t.substring(0,r),e,t.substring(r+e.length)]:[t,"",""]}async function Ys(t,e){let{response:r,requestLogID:s,retryOfRequestLogID:n,startTime:o}=e,i=await(async()=>{if(e.options.stream)return K(t).debug("response",r.status,r.url,r.headers,r.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(r,e.controller,t,e.options.__synthesizeEventData):xe.fromSSEResponse(r,e.controller,t,e.options.__synthesizeEventData);if(r.status===204)return null;if(e.options.__binaryResponse)return r;let c=r.headers.get("content-type")?.split(";")[0]?.trim();if(c?.includes("application/json")||c?.endsWith("+json")){if(r.headers.get("content-length")==="0")return;let g=await r.json();return ao(g,r)}return await r.text()})();return K(t).debug(`[${s}] response parsed`,ve({retryOfRequestLogID:n,url:r.url,status:r.status,body:i,durationMs:Date.now()-o})),i}function ao(t,e){return!t||typeof t!="object"||Array.isArray(t)?t:Object.defineProperty(t,"_request_id",{value:e.headers.get("x-request-id"),enumerable:!1})}var ds,ot=class t extends Promise{constructor(e,r,s=Ys){super(n=>{n(null)}),this.responsePromise=r,this.parseResponse=s,ds.set(this,void 0),k(this,ds,e,"f")}_thenUnwrap(e){return new t(d(this,ds,"f"),this.responsePromise,async(r,s)=>ao(e(await this.parseResponse(r,s),s),s.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,r]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:r,request_id:r.headers.get("x-request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(d(this,ds,"f"),e))),this.parsedPromise}then(e,r){return this.parse().then(e,r)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}};ds=new WeakMap;var Qs,Xt=class{constructor(e,r,s,n){Qs.set(this,void 0),k(this,Qs,e,"f"),this.options=n,this.response=r,this.body=s}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new P("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await d(this,Qs,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(Qs=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let r of e.getPaginatedItems())yield r}},fs=class extends ot{constructor(e,r,s){super(e,r,async(n,o)=>new s(n,o.response,await Ys(n,o),o.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let r of e)yield r}},Q=class extends Xt{constructor(e,r,s,n){super(e,r,s,n),this.data=s.data||[],this.object=s.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}},C=class extends Xt{constructor(e,r,s,n){super(e,r,s,n),this.data=s.data||[],this.has_more=s.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.getPaginatedItems(),r=e[e.length-1]?.id;return r?{...this.options,query:{...Hs(this.options.query),after:r}}:null}},$=class extends Xt{constructor(e,r,s,n){super(e,r,s,n),this.data=s.data||[],this.has_more=s.has_more||!1,this.last_id=s.last_id||""}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.last_id;return e?{...this.options,query:{...Hs(this.options.query),after:e}}:null}},B=class extends Xt{constructor(e,r,s,n){super(e,r,s,n),this.data=s.data||[],this.has_more=s.has_more||!1,this.next=s.next||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.next;return e?{...this.options,query:{...Hs(this.options.query),after:e}}:null}};var Pl={jwt:"urn:ietf:params:oauth:token-type:jwt",id:"urn:ietf:params:oauth:token-type:id_token"},Ol="urn:ietf:params:oauth:grant-type:token-exchange",en=class{constructor(e,r){this.cachedToken=null,this.refreshPromise=null,this.tokenExchangeUrl="https://auth.openai.com/oauth/token",this.config=e,this.fetch=r??Zs()}async getToken(){if(!this.cachedToken||this.isTokenExpired(this.cachedToken)){if(this.refreshPromise)return await this.refreshPromise;this.refreshPromise=this.refreshToken();try{return await this.refreshPromise}finally{this.refreshPromise=null}}return this.needsRefresh(this.cachedToken)&&!this.refreshPromise&&(this.refreshPromise=this.refreshToken().finally(()=>{this.refreshPromise=null})),this.cachedToken.token}async refreshToken(){let e=await this.config.provider.getToken(),r={grant_type:Ol,subject_token:e,subject_token_type:Pl[this.config.provider.tokenType],identity_provider_id:this.config.identityProviderId,service_account_id:this.config.serviceAccountId};this.config.clientId&&(r.client_id=this.config.clientId);let s=await this.fetch(this.tokenExchangeUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!s.ok){let c=await s.text(),u;try{u=JSON.parse(c)}catch{}throw s.status===400||s.status===401||s.status===403?new st(s.status,u,s.headers):U.generate(s.status,u,`Token exchange failed with status ${s.status}`,s.headers)}let n=await s.json();if(typeof n!="object"||n===null||!("access_token"in n)||typeof n.access_token!="string"||n.access_token.trim().length===0)throw new P("Token exchange response missing 'access_token' field");let o=n.access_token,i=n.expires_in??3600,a=Date.now()+i*1e3;return this.cachedToken={token:o,expiresAt:a},o}isTokenExpired(e){return Date.now()>=e.expiresAt}needsRefresh(e){let s=(this.config.refreshBufferSeconds??1200)*1e3;return Date.now()>=e.expiresAt-s}invalidateToken(){this.cachedToken=null,this.refreshPromise=null}};var co=()=>{if(typeof File>"u"){let{process:t}=globalThis,e=typeof t?.versions?.node=="string"&&parseInt(t.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(e?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function Yt(t,e,r){return co(),new File(t,e??"unknown_file",r)}function hs(t){return(typeof t=="object"&&t!==null&&("name"in t&&t.name&&String(t.name)||"url"in t&&t.url&&String(t.url)||"filename"in t&&t.filename&&String(t.filename)||"path"in t&&t.path&&String(t.path))||"").split(/[\\/]/).pop()||void 0}var tn=t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function",Fe=async(t,e)=>uo(t.body)?{...t,body:await Xi(t.body,e)}:t,ee=async(t,e)=>({...t,body:await Xi(t.body,e)}),Gi=new WeakMap;function kl(t){let e=typeof t=="function"?t:t.fetch,r=Gi.get(e);if(r)return r;let s=(async()=>{try{let n="Response"in e?e.Response:(await e("data:,")).constructor,o=new FormData;return o.toString()!==await new n(o).text()}catch{return!0}})();return Gi.set(e,s),s}var Xi=async(t,e)=>{if(!await kl(e))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let r=new FormData;return await Promise.all(Object.entries(t||{}).map(([s,n])=>lo(r,s,n))),r},Yi=t=>t instanceof Blob&&"name"in t,vl=t=>typeof t=="object"&&t!==null&&(t instanceof Response||tn(t)||Yi(t)),uo=t=>{if(vl(t))return!0;if(Array.isArray(t))return t.some(uo);if(t&&typeof t=="object"){for(let e in t)if(uo(t[e]))return!0}return!1},lo=async(t,e,r)=>{if(r!==void 0){if(r==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof r=="string"||typeof r=="number"||typeof r=="boolean")t.append(e,String(r));else if(r instanceof Response)t.append(e,Yt([await r.blob()],hs(r)));else if(tn(r))t.append(e,Yt([await new Response(Vs(r)).blob()],hs(r)));else if(Yi(r))t.append(e,r,hs(r));else if(Array.isArray(r))await Promise.all(r.map(s=>lo(t,e+"[]",s)));else if(typeof r=="object")await Promise.all(Object.entries(r).map(([s,n])=>lo(t,`${e}[${s}]`,n)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${r} instead`)}};var Qi=t=>t!=null&&typeof t=="object"&&typeof t.size=="number"&&typeof t.type=="string"&&typeof t.text=="function"&&typeof t.slice=="function"&&typeof t.arrayBuffer=="function",Tl=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&Qi(t),Cl=t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function";async function _s(t,e,r){if(co(),t=await t,Tl(t))return t instanceof File?t:Yt([await t.arrayBuffer()],t.name);if(Cl(t)){let n=await t.blob();return e||(e=new URL(t.url).pathname.split(/[\\/]/).pop()),Yt(await po(n),e,r)}let s=await po(t);if(e||(e=hs(t)),!r?.type){let n=s.find(o=>typeof o=="object"&&"type"in o&&o.type);typeof n=="string"&&(r={...r,type:n})}return Yt(s,e,r)}async function po(t){let e=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)e.push(t);else if(Qi(t))e.push(t instanceof Blob?t:await t.arrayBuffer());else if(tn(t))for await(let r of t)e.push(...await po(r));else{let r=t?.constructor?.name;throw new Error(`Unexpected data type: ${typeof t}${r?`; constructor: ${r}`:""}${Rl(t)}`)}return e}function Rl(t){return typeof t!="object"||t===null?"":`; props: [${Object.getOwnPropertyNames(t).map(r=>`"${r}"`).join(", ")}]`}var p=class{constructor(e){this._client=e}};function ta(t){return t.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var ea=Object.freeze(Object.create(null)),Sl=(t=ta)=>function(r,...s){if(r.length===1)return r[0];let n=!1,o=[],i=r.reduce((f,h,g)=>{/[?#]/.test(h)&&(n=!0);let A=s[g],I=(n?encodeURIComponent:t)(""+A);return g!==s.length&&(A==null||typeof A=="object"&&A.toString===Object.getPrototypeOf(Object.getPrototypeOf(A.hasOwnProperty??ea)??ea)?.toString)&&(I=A+"",o.push({start:f.length+h.length,length:I.length,error:`Value of type ${Object.prototype.toString.call(A).slice(8,-1)} is not a valid path parameter`})),f+h+(g===s.length?"":I)},""),a=i.split(/[?#]/,1)[0],c=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,u;for(;(u=c.exec(a))!==null;)o.push({start:u.index,length:u[0].length,error:`Value "${u[0]}" can't be safely passed as a path parameter`});if(o.sort((f,h)=>f.start-h.start),o.length>0){let f=0,h=o.reduce((g,A)=>{let I=" ".repeat(A.start-f),b="^".repeat(A.length);return f=A.start+A.length,g+I+b},"");throw new P(`Path parameters result in path with invalid segments:
10
10
  ${o.map(g=>g.error).join(`
11
11
  `)}
12
12
  ${i}
13
- ${h}`)}return i},l=Sl(Yi);var it=class extends p{list(e,r={},s){return this._client.getAPIList(l`/chat/completions/${e}/messages`,C,{query:r,...s,__security:{bearerAuth:!0}})}};function gs(t){return t!==void 0&&"function"in t&&t.function!==void 0}function ea(t,e){let r={...t};return Object.defineProperties(r,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:e,enumerable:!1}}),r}function ys(t){return t?.$brand==="auto-parseable-response-format"}function at(t){return t?.$brand==="auto-parseable-tool"}function ta(t,e){return!e||!mo(e)?{...t,choices:t.choices.map(r=>(sa(r.message.tool_calls),{...r,message:{...r.message,parsed:null,...r.message.tool_calls?{tool_calls:r.message.tool_calls}:void 0}}))}:As(t,e)}function As(t,e){let r=t.choices.map(s=>{if(s.finish_reason==="length")throw new Jt;if(s.finish_reason==="content_filter")throw new Gt;return sa(s.message.tool_calls),{...s,message:{...s.message,...s.message.tool_calls?{tool_calls:s.message.tool_calls?.map(n=>Nl(e,n))??void 0}:void 0,parsed:s.message.content&&!s.message.refusal?Ml(e,s.message.content):null}}});return{...t,choices:r}}function Ml(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 Nl(t,e){let r=t.tools?.find(s=>gs(s)&&s.function?.name===e.function.name);return{...e,function:{...e.function,parsed_arguments:at(r)?r.$parseRaw(e.function.arguments):r?.function.strict?JSON.parse(e.function.arguments):null}}}function ra(t,e){if(!t||!("tools"in t)||!t.tools)return!1;let r=t.tools?.find(s=>gs(s)&&s.function?.name===e.function.name);return gs(r)&&(at(r)||r?.function.strict||!1)}function mo(t){return ys(t.response_format)?!0:t.tools?.some(e=>at(e)||e.type==="function"&&e.function.strict===!0)??!1}function sa(t){for(let e of t||[])if(e.type!=="function")throw new P(`Currently only \`function\` tool calls are supported; Received \`${e.type}\``)}function na(t){for(let e of t??[]){if(e.type!=="function")throw new P(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)throw new P(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var er=t=>t?.role==="assistant",fo=t=>t?.role==="tool";var rn,sn,nn,Is,bs,on,xs,Te,an,ws,un,ln,tr,oa,ia,Be=class{constructor(){rn.add(this),this.controller=new AbortController,sn.set(this,void 0),nn.set(this,()=>{}),Is.set(this,()=>{}),bs.set(this,void 0),on.set(this,()=>{}),xs.set(this,()=>{}),Te.set(this,{}),an.set(this,[]),ws.set(this,!1),un.set(this,!1),ln.set(this,!1),tr.set(this,!1),k(this,sn,new Promise((e,r)=>{k(this,nn,e,"f"),k(this,Is,r,"f")}),"f"),k(this,bs,new Promise((e,r)=>{k(this,on,e,"f"),k(this,xs,r,"f")}),"f"),d(this,sn,"f").catch(()=>{}),d(this,bs,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},d(this,rn,"m",ia).bind(this))},0)}_connected(){this.ended||(d(this,nn,"f").call(this),this._emit("connect"))}get ended(){return d(this,ws,"f")}get errored(){return d(this,un,"f")}get aborted(){return d(this,ln,"f")}abort(){this.controller.abort()}_listenForAbort(e){if(!e||this.ended)return;if(e.aborted){this.controller.abort();return}let r=()=>this.controller.abort();e.addEventListener("abort",r,{once:!0}),d(this,an,"f").push({signal:e,listener:r})}on(e,r){return(d(this,Te,"f")[e]||(d(this,Te,"f")[e]=[])).push({listener:r}),this}off(e,r){let s=d(this,Te,"f")[e];if(!s)return this;let n=s.findIndex(o=>o.listener===r);return n>=0&&s.splice(n,1),this}once(e,r){return(d(this,Te,"f")[e]||(d(this,Te,"f")[e]=[])).push({listener:r,once:!0}),this}emitted(e){return new Promise((r,s)=>{k(this,tr,!0,"f"),e!=="error"&&this.once("error",s),this.once(e,r)})}async done(){k(this,tr,!0,"f"),await d(this,bs,"f")}_emit(e,...r){if(d(this,ws,"f"))return;e==="end"&&(d(this,rn,"m",oa).call(this),k(this,ws,!0,"f"),d(this,on,"f").call(this));let s=d(this,Te,"f")[e];if(s&&(d(this,Te,"f")[e]=s.filter(n=>!n.once),s.forEach(({listener:n})=>n(...r))),e==="abort"){let n=r[0];!d(this,tr,"f")&&!s?.length&&Promise.reject(n),d(this,Is,"f").call(this,n),d(this,xs,"f").call(this,n),this._emit("end");return}if(e==="error"){let n=r[0];!d(this,tr,"f")&&!s?.length&&Promise.reject(n),d(this,Is,"f").call(this,n),d(this,xs,"f").call(this,n),this._emit("end")}}_emitFinal(){}};sn=new WeakMap,nn=new WeakMap,Is=new WeakMap,bs=new WeakMap,on=new WeakMap,xs=new WeakMap,Te=new WeakMap,an=new WeakMap,ws=new WeakMap,un=new WeakMap,ln=new WeakMap,tr=new WeakMap,rn=new WeakSet,oa=function(){for(let{signal:e,listener:r}of d(this,an,"f").splice(0))e.removeEventListener("abort",r)},ia=function(e){if(k(this,un,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new L),e instanceof L)return k(this,ln,!0,"f"),this._emit("abort",e);if(e instanceof P)return this._emit("error",e);if(e instanceof Error){let r=new P(e.message);return r.cause=e,this._emit("error",r)}return this._emit("error",new P(String(e)))};function aa(t){return typeof t.parse=="function"}var te,ho,cn,_o,go,yo,ua,la,zl=10,rr=class extends Be{constructor(){super(...arguments),te.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){this._chatCompletions.push(e),this._emit("chatCompletion",e);let r=e.choices[0]?.message;return r&&this._addMessage(r),e}_addMessage(e,r=!0){if("content"in e||(e.content=null),this.messages.push(e),r){if(this._emit("message",e),fo(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(er(e)&&e.tool_calls)for(let s of e.tool_calls)s.type==="function"&&this._emit("functionToolCall",s.function)}}async finalChatCompletion(){await this.done();let e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new P("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),d(this,te,"m",ho).call(this)}async finalMessage(){return await this.done(),d(this,te,"m",cn).call(this)}async finalFunctionToolCall(){return await this.done(),d(this,te,"m",_o).call(this)}async finalFunctionToolCallResult(){return await this.done(),d(this,te,"m",go).call(this)}async totalUsage(){return await this.done(),d(this,te,"m",yo).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);let r=d(this,te,"m",cn).call(this);r&&this._emit("finalMessage",r);let s=d(this,te,"m",ho).call(this);s&&this._emit("finalContent",s);let n=d(this,te,"m",_o).call(this);n&&this._emit("finalFunctionToolCall",n);let o=d(this,te,"m",go).call(this);o!=null&&this._emit("finalFunctionToolCallResult",o),this._chatCompletions.some(i=>i.usage)&&this._emit("totalUsage",d(this,te,"m",yo).call(this))}async _createChatCompletion(e,r,s){this._listenForAbort(s?.signal),d(this,te,"m",ua).call(this,r);let n=await e.chat.completions.create({...r,stream:!1},{...s,signal:this.controller.signal});return this._connected(),this._addChatCompletion(As(n,r))}async _runChatCompletion(e,r,s){for(let n of r.messages)this._addMessage(n,!1);return await this._createChatCompletion(e,r,s)}async _runTools(e,r,s,n){let o="tool",{tool_choice:i="auto",stream:a,...c}=r,u=typeof i!="string"&&i.type==="function"&&i?.function?.name,{maxChatCompletions:f=zl,afterCompletion:h}=n||{},g=r.tools.map(_=>{if(at(_)){if(!_.$callback)throw new P("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:_.$callback,name:_.function.name,description:_.function.description||"",parameters:_.function.parameters,parse:_.$parseRaw,strict:!0}}}return _}),A={};for(let _ of g)_.type==="function"&&(A[_.function.name||_.function.function.name]=_.function);let I="tools"in r?g.map(_=>_.type==="function"?{type:"function",function:{name:_.function.name||_.function.function.name,parameters:_.function.parameters,description:_.function.description,strict:_.function.strict}}:_):void 0;for(let _ of r.messages)this._addMessage(_,!1);let b=async _=>{if(_.type!=="function")return{message:void 0,functionCalled:!1};let m=_.id,{name:y,arguments:O}=_.function,R=A[y];if(!R){let j=`Invalid tool_call: ${JSON.stringify(y)}. Available options are: ${Object.keys(A).map(D=>JSON.stringify(D)).join(", ")}. Please try again`;return{message:{role:o,tool_call_id:m,content:j},functionCalled:!1}}if(u&&u!==y){let j=`Invalid tool_call: ${JSON.stringify(y)}. ${JSON.stringify(u)} requested. Please try again`;return{message:{role:o,tool_call_id:m,content:j},functionCalled:!1}}let N;if(aa(R)){let j;try{j=await R.parse(O)}catch(D){let X=D instanceof Error?D.message:String(D);return{message:{role:o,tool_call_id:m,content:X},functionCalled:!1}}N=await R.function(j,s)}else N=await R.function(O,s);let z=d(this,te,"m",la).call(this,N);return{message:{role:o,tool_call_id:m,content:z},functionCalled:!0}};for(let _=0;_<f;++_){let m=await this._createChatCompletion(e,{...c,tool_choice:i,tools:I,messages:[...this.messages]},n),y=m.choices[0]?.message;if(!y)throw new P("missing message in ChatCompletion response");if(!y.tool_calls?.length){await h?.(m,s);return}if(u||r.parallel_tool_calls===!1)for(let O of y.tool_calls){let R=await b(O);if(R.message&&this._addMessage(R.message),u&&R.functionCalled){await h?.(m,s);return}}else{let O=await Promise.allSettled(y.tool_calls.map(b));for(let R of O)if(R.status==="rejected")throw R.reason;for(let R of O)R.status==="fulfilled"&&R.value.message&&this._addMessage(R.value.message)}await h?.(m,s)}}};te=new WeakSet,ho=function(){return d(this,te,"m",cn).call(this).content??null},cn=function(){let e=this.messages.length;for(;e-- >0;){let r=this.messages[e];if(er(r))return{...r,content:r.content??null,refusal:r.refusal??null}}throw new P("stream ended without producing a ChatCompletionMessage with role=assistant")},_o=function(){for(let e=this.messages.length-1;e>=0;e--){let r=this.messages[e];if(er(r)&&r?.tool_calls?.length)for(let s=r.tool_calls.length-1;s>=0;s--){let n=r.tool_calls[s];if(n?.type==="function")return n.function}}},go=function(){for(let e=this.messages.length-1;e>=0;e--){let r=this.messages[e];if(fo(r)&&r.content!=null&&typeof r.content=="string"&&this.messages.some(s=>s.role==="assistant"&&s.tool_calls?.some(n=>n.type==="function"&&n.id===r.tool_call_id)))return r.content}},yo=function(){let e={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(let{usage:r}of this._chatCompletions)r&&(e.completion_tokens+=r.completion_tokens,e.prompt_tokens+=r.prompt_tokens,e.total_tokens+=r.total_tokens);return e},ua=function(e){if(e.n!=null&&e.n>1)throw new P("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},la=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};var Ps=class t extends rr{static runTools(e,r,s){let n=new t,o={...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"runTools"}};return n._run(()=>n._runTools(e,r,n,o)),n}_addMessage(e,r=!0){super._addMessage(e,r),er(e)&&e.content&&this._emit("content",e.content)}};var Z={STR:1,NUM:2,ARR:4,OBJ:8,NULL:16,BOOL:32,NAN:64,INFINITY:128,MINUS_INFINITY:256,INF:384,SPECIAL:496,ATOM:499,COLLECTION:12,ALL:511},Ao=class extends Error{},Io=class extends Error{};function jl(t,e=Z.ALL){if(typeof t!="string")throw new TypeError(`expecting str, got ${typeof t}`);if(!t.trim())throw new Error(`${t} is empty`);return Ul(t.trim(),e)}var Ul=(t,e)=>{let r=t.length,s=0,n=g=>{throw new Ao(`${g} at position ${s}`)},o=g=>{throw new Io(`${g} at position ${s}`)},i=()=>(h(),s>=r&&n("Unexpected end of input"),t[s]==='"'?a():t[s]==="{"?c():t[s]==="["?u():t.substring(s,s+4)==="null"||Z.NULL&e&&r-s<4&&"null".startsWith(t.substring(s))?(s+=4,null):t.substring(s,s+4)==="true"||Z.BOOL&e&&r-s<4&&"true".startsWith(t.substring(s))?(s+=4,!0):t.substring(s,s+5)==="false"||Z.BOOL&e&&r-s<5&&"false".startsWith(t.substring(s))?(s+=5,!1):t.substring(s,s+8)==="Infinity"||Z.INFINITY&e&&r-s<8&&"Infinity".startsWith(t.substring(s))?(s+=8,1/0):t.substring(s,s+9)==="-Infinity"||Z.MINUS_INFINITY&e&&1<r-s&&r-s<9&&"-Infinity".startsWith(t.substring(s))?(s+=9,-1/0):t.substring(s,s+3)==="NaN"||Z.NAN&e&&r-s<3&&"NaN".startsWith(t.substring(s))?(s+=3,NaN):f()),a=()=>{let g=s,A=!1;for(s++;s<r&&(t[s]!=='"'||A&&t[s-1]==="\\");)A=t[s]==="\\"?!A:!1,s++;if(t.charAt(s)=='"')try{return JSON.parse(t.substring(g,++s-Number(A)))}catch(I){o(String(I))}else if(Z.STR&e)try{return JSON.parse(t.substring(g,s-Number(A))+'"')}catch{return JSON.parse(t.substring(g,t.lastIndexOf("\\"))+'"')}n("Unterminated string literal")},c=()=>{s++,h();let g={};try{for(;t[s]!=="}";){if(h(),s>=r&&Z.OBJ&e)return g;let A=a();h(),s++;try{let I=i();Object.defineProperty(g,A,{value:I,writable:!0,enumerable:!0,configurable:!0})}catch(I){if(Z.OBJ&e)return g;throw I}h(),t[s]===","&&s++}}catch{if(Z.OBJ&e)return g;n("Expected '}' at end of object")}return s++,g},u=()=>{s++;let g=[];try{for(;t[s]!=="]";)g.push(i()),h(),t[s]===","&&s++}catch{if(Z.ARR&e)return g;n("Expected ']' at end of array")}return s++,g},f=()=>{if(s===0){t==="-"&&Z.NUM&e&&n("Not sure what '-' is");try{return JSON.parse(t)}catch(A){if(Z.NUM&e)try{return t[t.length-1]==="."?JSON.parse(t.substring(0,t.lastIndexOf("."))):JSON.parse(t.substring(0,t.lastIndexOf("e")))}catch{}o(String(A))}}let g=s;for(t[s]==="-"&&s++;t[s]&&!",]}".includes(t[s]);)s++;s==r&&!(Z.NUM&e)&&n("Unterminated number literal");try{return JSON.parse(t.substring(g,s))}catch{t.substring(g,s)==="-"&&Z.NUM&e&&n("Not sure what '-' is");try{return JSON.parse(t.substring(g,t.lastIndexOf("e")))}catch(I){o(String(I))}}},h=()=>{for(;s<r&&`
14
- \r `.includes(t[s]);)s++};return i()},bo=t=>jl(t,Z.ALL^Z.NUM);var H,Ce,sr,qe,xo,pn,wo,Po,Oo,mn,ko,ca,ut=class t extends rr{constructor(e){super(),H.add(this),Ce.set(this,void 0),sr.set(this,void 0),qe.set(this,void 0),k(this,Ce,e,"f"),k(this,sr,[],"f")}get currentChatCompletionSnapshot(){return d(this,qe,"f")}static fromReadableStream(e){let r=new t(null);return r._run(()=>r._fromReadableStream(e)),r}static createChatCompletion(e,r,s){let n=new t(r);return n._run(()=>n._runChatCompletion(e,{...r,stream:!0},{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),n}async _createChatCompletion(e,r,s){super._createChatCompletion,this._listenForAbort(s?.signal),d(this,H,"m",xo).call(this);let n=await e.chat.completions.create({...r,stream:!0},{...s,signal:this.controller.signal});this._connected();for await(let o of n)d(this,H,"m",wo).call(this,o);if(n.controller.signal?.aborted)throw new L;return this._addChatCompletion(d(this,H,"m",mn).call(this))}async _fromReadableStream(e,r){this._listenForAbort(r?.signal),d(this,H,"m",xo).call(this),this._connected();let s=we.fromReadableStream(e,this.controller),n;for await(let o of s)n&&n!==o.id&&this._addChatCompletion(d(this,H,"m",mn).call(this)),d(this,H,"m",wo).call(this,o),n=o.id;if(s.controller.signal?.aborted)throw new L;return this._addChatCompletion(d(this,H,"m",mn).call(this))}[(Ce=new WeakMap,sr=new WeakMap,qe=new WeakMap,H=new WeakSet,xo=function(){this.ended||k(this,qe,void 0,"f")},pn=function(r){let s=d(this,sr,"f")[r.index];return s||(s={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},d(this,sr,"f")[r.index]=s,s)},wo=function(r){if(this.ended)return;let s=d(this,H,"m",ca).call(this,r);this._emit("chunk",r,s);for(let n of r.choices){let o=s.choices[n.index];n.delta.content!=null&&o.message?.role==="assistant"&&o.message?.content&&(this._emit("content",n.delta.content,o.message.content),this._emit("content.delta",{delta:n.delta.content,snapshot:o.message.content,parsed:o.message.parsed})),n.delta.refusal!=null&&o.message?.role==="assistant"&&o.message?.refusal&&this._emit("refusal.delta",{delta:n.delta.refusal,snapshot:o.message.refusal}),n.logprobs?.content!=null&&o.message?.role==="assistant"&&this._emit("logprobs.content.delta",{content:n.logprobs?.content,snapshot:o.logprobs?.content??[]}),n.logprobs?.refusal!=null&&o.message?.role==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:n.logprobs?.refusal,snapshot:o.logprobs?.refusal??[]});let i=d(this,H,"m",pn).call(this,o);o.finish_reason&&(d(this,H,"m",Oo).call(this,o),i.current_tool_call_index!=null&&d(this,H,"m",Po).call(this,o,i.current_tool_call_index));for(let a of n.delta.tool_calls??[])i.current_tool_call_index!==a.index&&(d(this,H,"m",Oo).call(this,o),i.current_tool_call_index!=null&&d(this,H,"m",Po).call(this,o,i.current_tool_call_index)),i.current_tool_call_index=a.index;for(let a of n.delta.tool_calls??[]){let c=o.message.tool_calls?.[a.index];c?.type&&(c?.type==="function"?this._emit("tool_calls.function.arguments.delta",{name:c.function?.name,index:a.index,arguments:c.function.arguments,parsed_arguments:c.function.parsed_arguments,arguments_delta:a.function?.arguments??""}):(c?.type,void 0))}}},Po=function(r,s){if(d(this,H,"m",pn).call(this,r).done_tool_calls.has(s))return;let o=r.message.tool_calls?.[s];if(!o)throw new Error("no tool call snapshot");if(!o.type)throw new Error("tool call snapshot missing `type`");if(o.type==="function"){let i=d(this,Ce,"f")?.tools?.find(a=>gs(a)&&a.function.name===o.function.name);this._emit("tool_calls.function.arguments.done",{name:o.function.name,index:s,arguments:o.function.arguments,parsed_arguments:at(i)?i.$parseRaw(o.function.arguments):i?.function.strict?JSON.parse(o.function.arguments):null})}else o.type},Oo=function(r){let s=d(this,H,"m",pn).call(this,r);if(r.message.content&&!s.content_done){s.content_done=!0;let n=d(this,H,"m",ko).call(this);this._emit("content.done",{content:r.message.content,parsed:n?n.$parseRaw(r.message.content):null})}r.message.refusal&&!s.refusal_done&&(s.refusal_done=!0,this._emit("refusal.done",{refusal:r.message.refusal})),r.logprobs?.content&&!s.logprobs_content_done&&(s.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:r.logprobs.content})),r.logprobs?.refusal&&!s.logprobs_refusal_done&&(s.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:r.logprobs.refusal}))},mn=function(){if(this.ended)throw new P("stream has ended, this shouldn't happen");let r=d(this,qe,"f");if(!r)throw new P("request ended without sending any chunks");return k(this,qe,void 0,"f"),k(this,sr,[],"f"),Ll(r,d(this,Ce,"f"))},ko=function(){let r=d(this,Ce,"f")?.response_format;return ys(r)?r:null},ca=function(r){var s,n,o,i;let a=d(this,qe,"f"),{choices:c,...u}=r;a?Object.assign(a,u):a=k(this,qe,{...u,choices:[]},"f");for(let{delta:f,finish_reason:h,index:g,logprobs:A=null,...I}of r.choices){let b=a.choices[g];if(b||(b=a.choices[g]={finish_reason:h,index:g,message:{},logprobs:A,...I}),A)if(!b.logprobs)b.logprobs=Object.assign({},A);else{let{content:z,refusal:j,...D}=A;Object.assign(b.logprobs,D),z&&((s=b.logprobs).content??(s.content=[]),b.logprobs.content.push(...z)),j&&((n=b.logprobs).refusal??(n.refusal=[]),b.logprobs.refusal.push(...j))}if(h&&(b.finish_reason=h,d(this,Ce,"f")&&mo(d(this,Ce,"f")))){if(h==="length")throw new Jt;if(h==="content_filter")throw new Gt}if(Object.assign(b,I),!f)continue;let{content:_,refusal:m,function_call:y,role:O,tool_calls:R,...N}=f;if(Object.assign(b.message,N),m&&(b.message.refusal=(b.message.refusal||"")+m),O&&(b.message.role=O),y&&(b.message.function_call?(y.name&&(b.message.function_call.name=y.name),y.arguments&&((o=b.message.function_call).arguments??(o.arguments=""),b.message.function_call.arguments+=y.arguments)):b.message.function_call=y),_&&(b.message.content=(b.message.content||"")+_,!b.message.refusal&&d(this,H,"m",ko).call(this)&&(b.message.parsed=b.message.content.trim()?bo(b.message.content):null)),R){b.message.tool_calls||(b.message.tool_calls=[]);for(let{index:z,id:j,type:D,function:X,...F}of R){let q=(i=b.message.tool_calls)[z]??(i[z]={});Object.assign(q,F),j&&(q.id=j),D&&(q.type=D),X&&(q.function??(q.function={name:X.name??"",arguments:""})),X?.name&&(q.function.name=X.name),X?.arguments&&(q.function.arguments+=X.arguments,ra(d(this,Ce,"f"),q)&&(q.function.parsed_arguments=bo(q.function.arguments)))}}}return a},Symbol.asyncIterator)](){let e=[],r=[],s=!1;return this.on("chunk",n=>{let o=r.shift();o?o.resolve(n):e.push(n)}),this.on("end",()=>{s=!0;for(let n of r)n.resolve(void 0);r.length=0}),this.on("abort",n=>{s=!0;for(let o of r)o.reject(n);r.length=0}),this.on("error",n=>{s=!0;for(let o of r)o.reject(n);r.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:s?{value:void 0,done:!0}:new Promise((o,i)=>r.push({resolve:o,reject:i})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new we(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};function Ll(t,e){let{id:r,choices:s,created:n,model:o,system_fingerprint:i,...a}=t,c={...a,id:r,choices:s.map(({message:u,finish_reason:f,index:h,logprobs:g,...A})=>{if(!f)throw new P(`missing finish_reason for choice ${h}`);let{content:I=null,function_call:b,tool_calls:_,...m}=u,y=u.role;if(!y)throw new P(`missing role for choice ${h}`);if(b){let{arguments:O,name:R}=b;if(O==null)throw new P(`missing function_call.arguments for choice ${h}`);if(!R)throw new P(`missing function_call.name for choice ${h}`);return{...A,message:{content:I,function_call:{arguments:O,name:R},role:y,refusal:u.refusal??null},finish_reason:f,index:h,logprobs:g}}return _?{...A,index:h,finish_reason:f,logprobs:g,message:{...m,role:y,content:I,refusal:u.refusal??null,tool_calls:_.map((O,R)=>{let{function:N,type:z,id:j,...D}=O,{arguments:X,name:F,...q}=N||{};if(j==null)throw new P(`missing choices[${h}].tool_calls[${R}].id
13
+ ${h}`)}return i},l=Sl(ta);var it=class extends p{list(e,r={},s){return this._client.getAPIList(l`/chat/completions/${e}/messages`,C,{query:r,...s,__security:{bearerAuth:!0}})}};function gs(t){return t!==void 0&&"function"in t&&t.function!==void 0}function sa(t,e){let r={...t};return Object.defineProperties(r,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:e,enumerable:!1}}),r}function ys(t){return t?.$brand==="auto-parseable-response-format"}function at(t){return t?.$brand==="auto-parseable-tool"}function na(t,e){return!e||!mo(e)?{...t,choices:t.choices.map(r=>(ia(r.message.tool_calls),{...r,message:{...r.message,parsed:null,...r.message.tool_calls?{tool_calls:r.message.tool_calls}:void 0}}))}:As(t,e)}function As(t,e){let r=t.choices.map(s=>{if(s.finish_reason==="length")throw new Vt;if(s.finish_reason==="content_filter")throw new Jt;return ia(s.message.tool_calls),{...s,message:{...s.message,...s.message.tool_calls?{tool_calls:s.message.tool_calls?.map(n=>Nl(e,n))??void 0}:void 0,parsed:s.message.content&&!s.message.refusal?Ml(e,s.message.content):null}}});return{...t,choices:r}}function Ml(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 Nl(t,e){let r=t.tools?.find(s=>gs(s)&&s.function?.name===e.function.name);return{...e,function:{...e.function,parsed_arguments:at(r)?r.$parseRaw(e.function.arguments):r?.function.strict?JSON.parse(e.function.arguments):null}}}function oa(t,e){if(!t||!("tools"in t)||!t.tools)return!1;let r=t.tools?.find(s=>gs(s)&&s.function?.name===e.function.name);return gs(r)&&(at(r)||r?.function.strict||!1)}function mo(t){return ys(t.response_format)?!0:t.tools?.some(e=>at(e)||e.type==="function"&&e.function.strict===!0)??!1}function ia(t){for(let e of t||[])if(e.type!=="function")throw new P(`Currently only \`function\` tool calls are supported; Received \`${e.type}\``)}function aa(t){for(let e of t??[]){if(e.type!=="function")throw new P(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)throw new P(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var Qt=t=>t?.role==="assistant",fo=t=>t?.role==="tool";var rn,sn,nn,Is,bs,on,xs,Te,an,ws,un,ln,er,ua,la,Be=class{constructor(){rn.add(this),this.controller=new AbortController,sn.set(this,void 0),nn.set(this,()=>{}),Is.set(this,()=>{}),bs.set(this,void 0),on.set(this,()=>{}),xs.set(this,()=>{}),Te.set(this,{}),an.set(this,[]),ws.set(this,!1),un.set(this,!1),ln.set(this,!1),er.set(this,!1),k(this,sn,new Promise((e,r)=>{k(this,nn,e,"f"),k(this,Is,r,"f")}),"f"),k(this,bs,new Promise((e,r)=>{k(this,on,e,"f"),k(this,xs,r,"f")}),"f"),d(this,sn,"f").catch(()=>{}),d(this,bs,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},d(this,rn,"m",la).bind(this))},0)}_connected(){this.ended||(d(this,nn,"f").call(this),this._emit("connect"))}get ended(){return d(this,ws,"f")}get errored(){return d(this,un,"f")}get aborted(){return d(this,ln,"f")}abort(){this.controller.abort()}_listenForAbort(e){if(!e||this.ended)return;if(e.aborted){this.controller.abort();return}let r=()=>this.controller.abort();e.addEventListener("abort",r,{once:!0}),d(this,an,"f").push({signal:e,listener:r})}on(e,r){return(d(this,Te,"f")[e]||(d(this,Te,"f")[e]=[])).push({listener:r}),this}off(e,r){let s=d(this,Te,"f")[e];if(!s)return this;let n=s.findIndex(o=>o.listener===r);return n>=0&&s.splice(n,1),this}once(e,r){return(d(this,Te,"f")[e]||(d(this,Te,"f")[e]=[])).push({listener:r,once:!0}),this}emitted(e){return new Promise((r,s)=>{k(this,er,!0,"f"),e!=="error"&&this.once("error",s),this.once(e,r)})}async done(){k(this,er,!0,"f"),await d(this,bs,"f")}_emit(e,...r){if(d(this,ws,"f"))return;e==="end"&&(d(this,rn,"m",ua).call(this),k(this,ws,!0,"f"),d(this,on,"f").call(this));let s=d(this,Te,"f")[e];if(s&&(d(this,Te,"f")[e]=s.filter(n=>!n.once),s.forEach(({listener:n})=>n(...r))),e==="abort"){let n=r[0];!d(this,er,"f")&&!s?.length&&Promise.reject(n),d(this,Is,"f").call(this,n),d(this,xs,"f").call(this,n),this._emit("end");return}if(e==="error"){let n=r[0];!d(this,er,"f")&&!s?.length&&Promise.reject(n),d(this,Is,"f").call(this,n),d(this,xs,"f").call(this,n),this._emit("end")}}_emitFinal(){}};sn=new WeakMap,nn=new WeakMap,Is=new WeakMap,bs=new WeakMap,on=new WeakMap,xs=new WeakMap,Te=new WeakMap,an=new WeakMap,ws=new WeakMap,un=new WeakMap,ln=new WeakMap,er=new WeakMap,rn=new WeakSet,ua=function(){for(let{signal:e,listener:r}of d(this,an,"f").splice(0))e.removeEventListener("abort",r)},la=function(e){if(k(this,un,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new D),e instanceof D)return k(this,ln,!0,"f"),this._emit("abort",e);if(e instanceof P)return this._emit("error",e);if(e instanceof Error){let r=new P(e.message);return r.cause=e,this._emit("error",r)}return this._emit("error",new P(String(e)))};function ca(t){return typeof t.parse=="function"}var te,ho,cn,_o,go,yo,pa,ma,zl=10,tr=class extends Be{constructor(){super(...arguments),te.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){this._chatCompletions.push(e),this._emit("chatCompletion",e);let r=e.choices[0]?.message;return r&&this._addMessage(r),e}_addMessage(e,r=!0){if("content"in e||(e.content=null),this.messages.push(e),r){if(this._emit("message",e),fo(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(Qt(e)&&e.tool_calls)for(let s of e.tool_calls)s.type==="function"&&this._emit("functionToolCall",s.function)}}async finalChatCompletion(){await this.done();let e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new P("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),d(this,te,"m",ho).call(this)}async finalMessage(){return await this.done(),d(this,te,"m",cn).call(this)}async finalFunctionToolCall(){return await this.done(),d(this,te,"m",_o).call(this)}async finalFunctionToolCallResult(){return await this.done(),d(this,te,"m",go).call(this)}async totalUsage(){return await this.done(),d(this,te,"m",yo).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);let r=d(this,te,"m",cn).call(this);r&&this._emit("finalMessage",r);let s=d(this,te,"m",ho).call(this);s&&this._emit("finalContent",s);let n=d(this,te,"m",_o).call(this);n&&this._emit("finalFunctionToolCall",n);let o=d(this,te,"m",go).call(this);o!=null&&this._emit("finalFunctionToolCallResult",o),this._chatCompletions.some(i=>i.usage)&&this._emit("totalUsage",d(this,te,"m",yo).call(this))}async _createChatCompletion(e,r,s){this._listenForAbort(s?.signal),d(this,te,"m",pa).call(this,r);let n=await e.chat.completions.create({...r,stream:!1},{...s,signal:this.controller.signal});return this._connected(),this._addChatCompletion(As(n,r))}async _runChatCompletion(e,r,s){for(let n of r.messages)this._addMessage(n,!1);return await this._createChatCompletion(e,r,s)}async _runTools(e,r,s,n){let o="tool",{tool_choice:i="auto",stream:a,...c}=r,u=typeof i!="string"&&i.type==="function"&&i?.function?.name,{maxChatCompletions:f=zl,afterCompletion:h}=n||{},g=r.tools.map(_=>{if(at(_)){if(!_.$callback)throw new P("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:_.$callback,name:_.function.name,description:_.function.description||"",parameters:_.function.parameters,parse:_.$parseRaw,strict:!0}}}return _}),A={};for(let _ of g)_.type==="function"&&(A[_.function.name||_.function.function.name]=_.function);let I="tools"in r?g.map(_=>_.type==="function"?{type:"function",function:{name:_.function.name||_.function.function.name,parameters:_.function.parameters,description:_.function.description,strict:_.function.strict}}:_):void 0;for(let _ of r.messages)this._addMessage(_,!1);let b=async _=>{if(_.type!=="function")return{message:void 0,functionCalled:!1};let m=_.id,{name:y,arguments:O}=_.function,R=A[y];if(!R){let j=`Invalid tool_call: ${JSON.stringify(y)}. Available options are: ${Object.keys(A).map(L=>JSON.stringify(L)).join(", ")}. Please try again`;return{message:{role:o,tool_call_id:m,content:j},functionCalled:!1}}if(u&&u!==y){let j=`Invalid tool_call: ${JSON.stringify(y)}. ${JSON.stringify(u)} requested. Please try again`;return{message:{role:o,tool_call_id:m,content:j},functionCalled:!1}}let N;if(ca(R)){let j;try{j=await R.parse(O)}catch(L){let X=L instanceof Error?L.message:String(L);return{message:{role:o,tool_call_id:m,content:X},functionCalled:!1}}N=await R.function(j,s)}else N=await R.function(O,s);let z=d(this,te,"m",ma).call(this,N);return{message:{role:o,tool_call_id:m,content:z},functionCalled:!0}};for(let _=0;_<f;++_){let m=await this._createChatCompletion(e,{...c,tool_choice:i,tools:I,messages:[...this.messages]},n),y=m.choices[0]?.message;if(!y)throw new P("missing message in ChatCompletion response");if(!y.tool_calls?.length){await h?.(m,s);return}if(u||r.parallel_tool_calls===!1)for(let O of y.tool_calls){let R=await b(O);if(R.message&&this._addMessage(R.message),u&&R.functionCalled){await h?.(m,s);return}}else{let O=await Promise.allSettled(y.tool_calls.map(b));for(let R of O)if(R.status==="rejected")throw R.reason;for(let R of O)R.status==="fulfilled"&&R.value.message&&this._addMessage(R.value.message)}await h?.(m,s)}}};te=new WeakSet,ho=function(){return d(this,te,"m",cn).call(this).content??null},cn=function(){let e=this.messages.length;for(;e-- >0;){let r=this.messages[e];if(Qt(r))return{...r,content:r.content??null,refusal:r.refusal??null}}throw new P("stream ended without producing a ChatCompletionMessage with role=assistant")},_o=function(){for(let e=this.messages.length-1;e>=0;e--){let r=this.messages[e];if(Qt(r)&&r?.tool_calls?.length)for(let s=r.tool_calls.length-1;s>=0;s--){let n=r.tool_calls[s];if(n?.type==="function")return n.function}}},go=function(){for(let e=this.messages.length-1;e>=0;e--){let r=this.messages[e];if(fo(r)&&r.content!=null&&typeof r.content=="string"&&this.messages.some(s=>s.role==="assistant"&&s.tool_calls?.some(n=>n.type==="function"&&n.id===r.tool_call_id)))return r.content}},yo=function(){let e={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(let{usage:r}of this._chatCompletions)r&&(e.completion_tokens+=r.completion_tokens,e.prompt_tokens+=r.prompt_tokens,e.total_tokens+=r.total_tokens);return e},pa=function(e){if(e.n!=null&&e.n>1)throw new P("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},ma=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};var Ps=class t extends tr{static runTools(e,r,s){let n=new t,o={...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"runTools"}};return n._run(()=>n._runTools(e,r,n,o)),n}_addMessage(e,r=!0){super._addMessage(e,r),Qt(e)&&e.content&&this._emit("content",e.content)}};var Z={STR:1,NUM:2,ARR:4,OBJ:8,NULL:16,BOOL:32,NAN:64,INFINITY:128,MINUS_INFINITY:256,INF:384,SPECIAL:496,ATOM:499,COLLECTION:12,ALL:511},Ao=class extends Error{},Io=class extends Error{};function jl(t,e=Z.ALL){if(typeof t!="string")throw new TypeError(`expecting str, got ${typeof t}`);if(!t.trim())throw new Error(`${t} is empty`);return Ul(t.trim(),e)}var Ul=(t,e)=>{let r=t.length,s=0,n=g=>{throw new Ao(`${g} at position ${s}`)},o=g=>{throw new Io(`${g} at position ${s}`)},i=()=>(h(),s>=r&&n("Unexpected end of input"),t[s]==='"'?a():t[s]==="{"?c():t[s]==="["?u():t.substring(s,s+4)==="null"||Z.NULL&e&&r-s<4&&"null".startsWith(t.substring(s))?(s+=4,null):t.substring(s,s+4)==="true"||Z.BOOL&e&&r-s<4&&"true".startsWith(t.substring(s))?(s+=4,!0):t.substring(s,s+5)==="false"||Z.BOOL&e&&r-s<5&&"false".startsWith(t.substring(s))?(s+=5,!1):t.substring(s,s+8)==="Infinity"||Z.INFINITY&e&&r-s<8&&"Infinity".startsWith(t.substring(s))?(s+=8,1/0):t.substring(s,s+9)==="-Infinity"||Z.MINUS_INFINITY&e&&1<r-s&&r-s<9&&"-Infinity".startsWith(t.substring(s))?(s+=9,-1/0):t.substring(s,s+3)==="NaN"||Z.NAN&e&&r-s<3&&"NaN".startsWith(t.substring(s))?(s+=3,NaN):f()),a=()=>{let g=s,A=!1;for(s++;s<r&&(t[s]!=='"'||A&&t[s-1]==="\\");)A=t[s]==="\\"?!A:!1,s++;if(t.charAt(s)=='"')try{return JSON.parse(t.substring(g,++s-Number(A)))}catch(I){o(String(I))}else if(Z.STR&e)try{return JSON.parse(t.substring(g,s-Number(A))+'"')}catch{return JSON.parse(t.substring(g,t.lastIndexOf("\\"))+'"')}n("Unterminated string literal")},c=()=>{s++,h();let g={};try{for(;t[s]!=="}";){if(h(),s>=r&&Z.OBJ&e)return g;let A=a();h(),s++;try{let I=i();Object.defineProperty(g,A,{value:I,writable:!0,enumerable:!0,configurable:!0})}catch(I){if(Z.OBJ&e)return g;throw I}h(),t[s]===","&&s++}}catch{if(Z.OBJ&e)return g;n("Expected '}' at end of object")}return s++,g},u=()=>{s++;let g=[];try{for(;t[s]!=="]";)g.push(i()),h(),t[s]===","&&s++}catch{if(Z.ARR&e)return g;n("Expected ']' at end of array")}return s++,g},f=()=>{if(s===0){t==="-"&&Z.NUM&e&&n("Not sure what '-' is");try{return JSON.parse(t)}catch(A){if(Z.NUM&e)try{return t[t.length-1]==="."?JSON.parse(t.substring(0,t.lastIndexOf("."))):JSON.parse(t.substring(0,t.lastIndexOf("e")))}catch{}o(String(A))}}let g=s;for(t[s]==="-"&&s++;t[s]&&!",]}".includes(t[s]);)s++;s==r&&!(Z.NUM&e)&&n("Unterminated number literal");try{return JSON.parse(t.substring(g,s))}catch{t.substring(g,s)==="-"&&Z.NUM&e&&n("Not sure what '-' is");try{return JSON.parse(t.substring(g,t.lastIndexOf("e")))}catch(I){o(String(I))}}},h=()=>{for(;s<r&&`
14
+ \r `.includes(t[s]);)s++};return i()},bo=t=>jl(t,Z.ALL^Z.NUM);var H,Ce,rr,qe,xo,pn,wo,Po,Oo,mn,ko,da,ut=class t extends tr{constructor(e){super(),H.add(this),Ce.set(this,void 0),rr.set(this,void 0),qe.set(this,void 0),k(this,Ce,e,"f"),k(this,rr,[],"f")}get currentChatCompletionSnapshot(){return d(this,qe,"f")}static fromReadableStream(e){let r=new t(null);return r._run(()=>r._fromReadableStream(e)),r}static createChatCompletion(e,r,s){let n=new t(r);return n._run(()=>n._runChatCompletion(e,{...r,stream:!0},{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),n}async _createChatCompletion(e,r,s){super._createChatCompletion,this._listenForAbort(s?.signal),d(this,H,"m",xo).call(this);let n=await e.chat.completions.create({...r,stream:!0},{...s,signal:this.controller.signal});this._connected();for await(let o of n)d(this,H,"m",wo).call(this,o);if(n.controller.signal?.aborted)throw new D;return this._addChatCompletion(d(this,H,"m",mn).call(this))}async _fromReadableStream(e,r){this._listenForAbort(r?.signal),d(this,H,"m",xo).call(this),this._connected();let s=xe.fromReadableStream(e,this.controller),n;for await(let o of s)n&&n!==o.id&&this._addChatCompletion(d(this,H,"m",mn).call(this)),d(this,H,"m",wo).call(this,o),n=o.id;if(s.controller.signal?.aborted)throw new D;return this._addChatCompletion(d(this,H,"m",mn).call(this))}[(Ce=new WeakMap,rr=new WeakMap,qe=new WeakMap,H=new WeakSet,xo=function(){this.ended||k(this,qe,void 0,"f")},pn=function(r){let s=d(this,rr,"f")[r.index];return s||(s={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},d(this,rr,"f")[r.index]=s,s)},wo=function(r){if(this.ended)return;let s=d(this,H,"m",da).call(this,r);this._emit("chunk",r,s);for(let n of r.choices){let o=s.choices[n.index];n.delta.content!=null&&o.message?.role==="assistant"&&o.message?.content&&(this._emit("content",n.delta.content,o.message.content),this._emit("content.delta",{delta:n.delta.content,snapshot:o.message.content,parsed:o.message.parsed})),n.delta.refusal!=null&&o.message?.role==="assistant"&&o.message?.refusal&&this._emit("refusal.delta",{delta:n.delta.refusal,snapshot:o.message.refusal}),n.logprobs?.content!=null&&o.message?.role==="assistant"&&this._emit("logprobs.content.delta",{content:n.logprobs?.content,snapshot:o.logprobs?.content??[]}),n.logprobs?.refusal!=null&&o.message?.role==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:n.logprobs?.refusal,snapshot:o.logprobs?.refusal??[]});let i=d(this,H,"m",pn).call(this,o);o.finish_reason&&(d(this,H,"m",Oo).call(this,o),i.current_tool_call_index!=null&&d(this,H,"m",Po).call(this,o,i.current_tool_call_index));for(let a of n.delta.tool_calls??[])i.current_tool_call_index!==a.index&&(d(this,H,"m",Oo).call(this,o),i.current_tool_call_index!=null&&d(this,H,"m",Po).call(this,o,i.current_tool_call_index)),i.current_tool_call_index=a.index;for(let a of n.delta.tool_calls??[]){let c=o.message.tool_calls?.[a.index];c?.type&&(c?.type==="function"?this._emit("tool_calls.function.arguments.delta",{name:c.function?.name,index:a.index,arguments:c.function.arguments,parsed_arguments:c.function.parsed_arguments,arguments_delta:a.function?.arguments??""}):(c?.type,void 0))}}},Po=function(r,s){if(d(this,H,"m",pn).call(this,r).done_tool_calls.has(s))return;let o=r.message.tool_calls?.[s];if(!o)throw new Error("no tool call snapshot");if(!o.type)throw new Error("tool call snapshot missing `type`");if(o.type==="function"){let i=d(this,Ce,"f")?.tools?.find(a=>gs(a)&&a.function.name===o.function.name);this._emit("tool_calls.function.arguments.done",{name:o.function.name,index:s,arguments:o.function.arguments,parsed_arguments:at(i)?i.$parseRaw(o.function.arguments):i?.function.strict?JSON.parse(o.function.arguments):null})}else o.type},Oo=function(r){let s=d(this,H,"m",pn).call(this,r);if(r.message.content&&!s.content_done){s.content_done=!0;let n=d(this,H,"m",ko).call(this);this._emit("content.done",{content:r.message.content,parsed:n?n.$parseRaw(r.message.content):null})}r.message.refusal&&!s.refusal_done&&(s.refusal_done=!0,this._emit("refusal.done",{refusal:r.message.refusal})),r.logprobs?.content&&!s.logprobs_content_done&&(s.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:r.logprobs.content})),r.logprobs?.refusal&&!s.logprobs_refusal_done&&(s.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:r.logprobs.refusal}))},mn=function(){if(this.ended)throw new P("stream has ended, this shouldn't happen");let r=d(this,qe,"f");if(!r)throw new P("request ended without sending any chunks");return k(this,qe,void 0,"f"),k(this,rr,[],"f"),Dl(r,d(this,Ce,"f"))},ko=function(){let r=d(this,Ce,"f")?.response_format;return ys(r)?r:null},da=function(r){var s,n,o,i;let a=d(this,qe,"f"),{choices:c,...u}=r;a?Object.assign(a,u):a=k(this,qe,{...u,choices:[]},"f");for(let{delta:f,finish_reason:h,index:g,logprobs:A=null,...I}of r.choices){let b=a.choices[g];if(b||(b=a.choices[g]={finish_reason:h,index:g,message:{},logprobs:A,...I}),A)if(!b.logprobs)b.logprobs=Object.assign({},A);else{let{content:z,refusal:j,...L}=A;Object.assign(b.logprobs,L),z&&((s=b.logprobs).content??(s.content=[]),b.logprobs.content.push(...z)),j&&((n=b.logprobs).refusal??(n.refusal=[]),b.logprobs.refusal.push(...j))}if(h&&(b.finish_reason=h,d(this,Ce,"f")&&mo(d(this,Ce,"f")))){if(h==="length")throw new Vt;if(h==="content_filter")throw new Jt}if(Object.assign(b,I),!f)continue;let{content:_,refusal:m,function_call:y,role:O,tool_calls:R,...N}=f;if(Object.assign(b.message,N),m&&(b.message.refusal=(b.message.refusal||"")+m),O&&(b.message.role=O),y&&(b.message.function_call?(y.name&&(b.message.function_call.name=y.name),y.arguments&&((o=b.message.function_call).arguments??(o.arguments=""),b.message.function_call.arguments+=y.arguments)):b.message.function_call=y),_&&(b.message.content=(b.message.content||"")+_,!b.message.refusal&&d(this,H,"m",ko).call(this)&&(b.message.parsed=b.message.content.trim()?bo(b.message.content):null)),R){b.message.tool_calls||(b.message.tool_calls=[]);for(let{index:z,id:j,type:L,function:X,...F}of R){let q=(i=b.message.tool_calls)[z]??(i[z]={});Object.assign(q,F),j&&(q.id=j),L&&(q.type=L),X&&(q.function??(q.function={name:X.name??"",arguments:""})),X?.name&&(q.function.name=X.name),X?.arguments&&(q.function.arguments+=X.arguments,oa(d(this,Ce,"f"),q)&&(q.function.parsed_arguments=bo(q.function.arguments)))}}}return a},Symbol.asyncIterator)](){let e=[],r=[],s=!1;return this.on("chunk",n=>{let o=r.shift();o?o.resolve(n):e.push(n)}),this.on("end",()=>{s=!0;for(let n of r)n.resolve(void 0);r.length=0}),this.on("abort",n=>{s=!0;for(let o of r)o.reject(n);r.length=0}),this.on("error",n=>{s=!0;for(let o of r)o.reject(n);r.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:s?{value:void 0,done:!0}:new Promise((o,i)=>r.push({resolve:o,reject:i})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new xe(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};function Dl(t,e){let{id:r,choices:s,created:n,model:o,system_fingerprint:i,...a}=t,c={...a,id:r,choices:s.map(({message:u,finish_reason:f,index:h,logprobs:g,...A})=>{if(!f)throw new P(`missing finish_reason for choice ${h}`);let{content:I=null,function_call:b,tool_calls:_,...m}=u,y=u.role;if(!y)throw new P(`missing role for choice ${h}`);if(b){let{arguments:O,name:R}=b;if(O==null)throw new P(`missing function_call.arguments for choice ${h}`);if(!R)throw new P(`missing function_call.name for choice ${h}`);return{...A,message:{content:I,function_call:{arguments:O,name:R},role:y,refusal:u.refusal??null},finish_reason:f,index:h,logprobs:g}}return _?{...A,index:h,finish_reason:f,logprobs:g,message:{...m,role:y,content:I,refusal:u.refusal??null,tool_calls:_.map((O,R)=>{let{function:N,type:z,id:j,...L}=O,{arguments:X,name:F,...q}=N||{};if(j==null)throw new P(`missing choices[${h}].tool_calls[${R}].id
15
15
  ${dn(t)}`);if(z==null)throw new P(`missing choices[${h}].tool_calls[${R}].type
16
16
  ${dn(t)}`);if(F==null)throw new P(`missing choices[${h}].tool_calls[${R}].function.name
17
17
  ${dn(t)}`);if(X==null)throw new P(`missing choices[${h}].tool_calls[${R}].function.arguments
18
- ${dn(t)}`);return{...D,id:j,type:z,function:{...q,name:F,arguments:X}}})}}:{...A,message:{...m,content:I,role:y,refusal:u.refusal??null},finish_reason:f,index:h,logprobs:g}}),created:n,model:o,object:"chat.completion",...i?{system_fingerprint:i}:{}};return ta(c,e)}function dn(t){return JSON.stringify(t)}var Os=class t extends ut{static fromReadableStream(e){let r=new t(null);return r._run(()=>r._fromReadableStream(e)),r}static runTools(e,r,s){let n=new t(r),o={...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"runTools"}};return n._run(()=>n._runTools(e,r,n,o)),n}};var Re=class extends p{constructor(){super(...arguments),this.messages=new it(this._client)}create(e,r){return this._client.post("/chat/completions",{body:e,...r,stream:e.stream??!1,__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(l`/chat/completions/${e}`,{...r,__security:{bearerAuth:!0}})}update(e,r,s){return this._client.post(l`/chat/completions/${e}`,{body:r,...s,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/chat/completions",C,{query:e,...r,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(l`/chat/completions/${e}`,{...r,__security:{bearerAuth:!0}})}parse(e,r){return na(e.tools),this._client.chat.completions.create(e,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(s=>As(s,e))}runTools(e,r){return e.stream?Os.runTools(this._client,e,r):Ps.runTools(this._client,e,r)}stream(e,r){return ut.createChatCompletion(this._client,e,r)}};Re.Messages=it;var We=class extends p{constructor(){super(...arguments),this.completions=new Re(this._client)}};We.Completions=Re;var nr=class extends p{create(e,r){return this._client.post("/organization/admin_api_keys",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r){return this._client.get(l`/organization/admin_api_keys/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/admin_api_keys",C,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(l`/organization/admin_api_keys/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var or=class extends p{list(e={},r){return this._client.getAPIList("/organization/audit_logs",$,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}};var ir=class extends p{create(e,r){return this._client.post("/organization/certificates",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r={},s){return this._client.get(l`/organization/certificates/${e}`,{query:r,...s,__security:{adminAPIKeyAuth:!0}})}update(e,r,s){return this._client.post(l`/organization/certificates/${e}`,{body:r,...s,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/certificates",$,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(l`/organization/certificates/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}activate(e,r){return this._client.getAPIList("/organization/certificates/activate",Q,{body:e,method:"post",...r,__security:{adminAPIKeyAuth:!0}})}deactivate(e,r){return this._client.getAPIList("/organization/certificates/deactivate",Q,{body:e,method:"post",...r,__security:{adminAPIKeyAuth:!0}})}};var ar=class extends p{retrieve(e){return this._client.get("/organization/data_retention",{...e,__security:{adminAPIKeyAuth:!0}})}update(e,r){return this._client.post("/organization/data_retention",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}};var ur=class extends p{create(e,r){return this._client.post("/organization/invites",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r){return this._client.get(l`/organization/invites/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/invites",$,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(l`/organization/invites/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var lr=class extends p{create(e,r){return this._client.post("/organization/roles",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r){return this._client.get(l`/organization/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,s){return this._client.post(l`/organization/roles/${e}`,{body:r,...s,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/roles",B,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(l`/organization/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var cr=class extends p{create(e,r){return this._client.post("/organization/spend_alerts",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r){return this._client.get(l`/organization/spend_alerts/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,s){return this._client.post(l`/organization/spend_alerts/${e}`,{body:r,...s,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/spend_alerts",$,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(l`/organization/spend_alerts/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var pr=class extends p{audioSpeeches(e,r){return this._client.get("/organization/usage/audio_speeches",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}audioTranscriptions(e,r){return this._client.get("/organization/usage/audio_transcriptions",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}codeInterpreterSessions(e,r){return this._client.get("/organization/usage/code_interpreter_sessions",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}completions(e,r){return this._client.get("/organization/usage/completions",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}costs(e,r){return this._client.get("/organization/costs",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}embeddings(e,r){return this._client.get("/organization/usage/embeddings",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}fileSearchCalls(e,r){return this._client.get("/organization/usage/file_search_calls",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}images(e,r){return this._client.get("/organization/usage/images",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}moderations(e,r){return this._client.get("/organization/usage/moderations",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}vectorStores(e,r){return this._client.get("/organization/usage/vector_stores",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}webSearchCalls(e,r){return this._client.get("/organization/usage/web_search_calls",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}};var mr=class extends p{create(e,r,s){return this._client.post(l`/organization/groups/${e}/roles`,{body:r,...s,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,s){let{group_id:n}=r;return this._client.get(l`/organization/groups/${n}/roles/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}list(e,r={},s){return this._client.getAPIList(l`/organization/groups/${e}/roles`,B,{query:r,...s,__security:{adminAPIKeyAuth:!0}})}delete(e,r,s){let{group_id:n}=r;return this._client.delete(l`/organization/groups/${n}/roles/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}};var dr=class extends p{create(e,r,s){return this._client.post(l`/organization/groups/${e}/users`,{body:r,...s,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,s){let{group_id:n}=r;return this._client.get(l`/organization/groups/${n}/users/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}list(e,r={},s){return this._client.getAPIList(l`/organization/groups/${e}/users`,B,{query:r,...s,__security:{adminAPIKeyAuth:!0}})}delete(e,r,s){let{group_id:n}=r;return this._client.delete(l`/organization/groups/${n}/users/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}};var He=class extends p{constructor(){super(...arguments),this.users=new dr(this._client),this.roles=new mr(this._client)}create(e,r){return this._client.post("/organization/groups",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r){return this._client.get(l`/organization/groups/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,s){return this._client.post(l`/organization/groups/${e}`,{body:r,...s,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/groups",B,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(l`/organization/groups/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};He.Users=dr;He.Roles=mr;var fr=class extends p{retrieve(e,r,s){let{project_id:n}=r;return this._client.get(l`/organization/projects/${n}/api_keys/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}list(e,r={},s){return this._client.getAPIList(l`/organization/projects/${e}/api_keys`,$,{query:r,...s,__security:{adminAPIKeyAuth:!0}})}delete(e,r,s){let{project_id:n}=r;return this._client.delete(l`/organization/projects/${n}/api_keys/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}};var hr=class extends p{list(e,r={},s){return this._client.getAPIList(l`/organization/projects/${e}/certificates`,$,{query:r,...s,__security:{adminAPIKeyAuth:!0}})}activate(e,r,s){return this._client.getAPIList(l`/organization/projects/${e}/certificates/activate`,Q,{body:r,method:"post",...s,__security:{adminAPIKeyAuth:!0}})}deactivate(e,r,s){return this._client.getAPIList(l`/organization/projects/${e}/certificates/deactivate`,Q,{body:r,method:"post",...s,__security:{adminAPIKeyAuth:!0}})}};var _r=class extends p{retrieve(e,r){return this._client.get(l`/organization/projects/${e}/data_retention`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,s){return this._client.post(l`/organization/projects/${e}/data_retention`,{body:r,...s,__security:{adminAPIKeyAuth:!0}})}};var gr=class extends p{retrieve(e,r){return this._client.get(l`/organization/projects/${e}/hosted_tool_permissions`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,s){return this._client.post(l`/organization/projects/${e}/hosted_tool_permissions`,{body:r,...s,__security:{adminAPIKeyAuth:!0}})}};var yr=class extends p{retrieve(e,r){return this._client.get(l`/organization/projects/${e}/model_permissions`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,s){return this._client.post(l`/organization/projects/${e}/model_permissions`,{body:r,...s,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(l`/organization/projects/${e}/model_permissions`,{...r,__security:{adminAPIKeyAuth:!0}})}};var Ar=class extends p{listRateLimits(e,r={},s){return this._client.getAPIList(l`/organization/projects/${e}/rate_limits`,$,{query:r,...s,__security:{adminAPIKeyAuth:!0}})}updateRateLimit(e,r,s){let{project_id:n,...o}=r;return this._client.post(l`/organization/projects/${n}/rate_limits/${e}`,{body:o,...s,__security:{adminAPIKeyAuth:!0}})}};var Ir=class extends p{create(e,r,s){return this._client.post(l`/projects/${e}/roles`,{body:r,...s,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,s){let{project_id:n}=r;return this._client.get(l`/projects/${n}/roles/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}update(e,r,s){let{project_id:n,...o}=r;return this._client.post(l`/projects/${n}/roles/${e}`,{body:o,...s,__security:{adminAPIKeyAuth:!0}})}list(e,r={},s){return this._client.getAPIList(l`/projects/${e}/roles`,B,{query:r,...s,__security:{adminAPIKeyAuth:!0}})}delete(e,r,s){let{project_id:n}=r;return this._client.delete(l`/projects/${n}/roles/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}};var br=class extends p{create(e,r,s){return this._client.post(l`/organization/projects/${e}/service_accounts`,{body:r,...s,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,s){let{project_id:n}=r;return this._client.get(l`/organization/projects/${n}/service_accounts/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}update(e,r,s){let{project_id:n,...o}=r;return this._client.post(l`/organization/projects/${n}/service_accounts/${e}`,{body:o,...s,__security:{adminAPIKeyAuth:!0}})}list(e,r={},s){return this._client.getAPIList(l`/organization/projects/${e}/service_accounts`,$,{query:r,...s,__security:{adminAPIKeyAuth:!0}})}delete(e,r,s){let{project_id:n}=r;return this._client.delete(l`/organization/projects/${n}/service_accounts/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}};var xr=class extends p{create(e,r,s){return this._client.post(l`/organization/projects/${e}/spend_alerts`,{body:r,...s,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,s){let{project_id:n}=r;return this._client.get(l`/organization/projects/${n}/spend_alerts/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}update(e,r,s){let{project_id:n,...o}=r;return this._client.post(l`/organization/projects/${n}/spend_alerts/${e}`,{body:o,...s,__security:{adminAPIKeyAuth:!0}})}list(e,r={},s){return this._client.getAPIList(l`/organization/projects/${e}/spend_alerts`,$,{query:r,...s,__security:{adminAPIKeyAuth:!0}})}delete(e,r,s){let{project_id:n}=r;return this._client.delete(l`/organization/projects/${n}/spend_alerts/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}};var wr=class extends p{create(e,r,s){let{project_id:n,...o}=r;return this._client.post(l`/projects/${n}/groups/${e}/roles`,{body:o,...s,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,s){let{project_id:n,group_id:o}=r;return this._client.get(l`/projects/${n}/groups/${o}/roles/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}list(e,r,s){let{project_id:n,...o}=r;return this._client.getAPIList(l`/projects/${n}/groups/${e}/roles`,B,{query:o,...s,__security:{adminAPIKeyAuth:!0}})}delete(e,r,s){let{project_id:n,group_id:o}=r;return this._client.delete(l`/projects/${n}/groups/${o}/roles/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}};var lt=class extends p{constructor(){super(...arguments),this.roles=new wr(this._client)}create(e,r,s){return this._client.post(l`/organization/projects/${e}/groups`,{body:r,...s,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,s){let{project_id:n,...o}=r;return this._client.get(l`/organization/projects/${n}/groups/${e}`,{query:o,...s,__security:{adminAPIKeyAuth:!0}})}list(e,r={},s){return this._client.getAPIList(l`/organization/projects/${e}/groups`,B,{query:r,...s,__security:{adminAPIKeyAuth:!0}})}delete(e,r,s){let{project_id:n}=r;return this._client.delete(l`/organization/projects/${n}/groups/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}};lt.Roles=wr;var Pr=class extends p{create(e,r,s){let{project_id:n,...o}=r;return this._client.post(l`/projects/${n}/users/${e}/roles`,{body:o,...s,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,s){let{project_id:n,user_id:o}=r;return this._client.get(l`/projects/${n}/users/${o}/roles/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}list(e,r,s){let{project_id:n,...o}=r;return this._client.getAPIList(l`/projects/${n}/users/${e}/roles`,B,{query:o,...s,__security:{adminAPIKeyAuth:!0}})}delete(e,r,s){let{project_id:n,user_id:o}=r;return this._client.delete(l`/projects/${n}/users/${o}/roles/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}};var ct=class extends p{constructor(){super(...arguments),this.roles=new Pr(this._client)}create(e,r,s){return this._client.post(l`/organization/projects/${e}/users`,{body:r,...s,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,s){let{project_id:n}=r;return this._client.get(l`/organization/projects/${n}/users/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}update(e,r,s){let{project_id:n,...o}=r;return this._client.post(l`/organization/projects/${n}/users/${e}`,{body:o,...s,__security:{adminAPIKeyAuth:!0}})}list(e,r={},s){return this._client.getAPIList(l`/organization/projects/${e}/users`,$,{query:r,...s,__security:{adminAPIKeyAuth:!0}})}delete(e,r,s){let{project_id:n}=r;return this._client.delete(l`/organization/projects/${n}/users/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}};ct.Roles=Pr;var V=class extends p{constructor(){super(...arguments),this.users=new ct(this._client),this.serviceAccounts=new br(this._client),this.apiKeys=new fr(this._client),this.rateLimits=new Ar(this._client),this.modelPermissions=new yr(this._client),this.hostedToolPermissions=new gr(this._client),this.groups=new lt(this._client),this.roles=new Ir(this._client),this.dataRetention=new _r(this._client),this.spendAlerts=new xr(this._client),this.certificates=new hr(this._client)}create(e,r){return this._client.post("/organization/projects",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r){return this._client.get(l`/organization/projects/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,s){return this._client.post(l`/organization/projects/${e}`,{body:r,...s,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/projects",$,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}archive(e,r){return this._client.post(l`/organization/projects/${e}/archive`,{...r,__security:{adminAPIKeyAuth:!0}})}};V.Users=ct;V.ServiceAccounts=br;V.APIKeys=fr;V.RateLimits=Ar;V.ModelPermissions=yr;V.HostedToolPermissions=gr;V.Groups=lt;V.Roles=Ir;V.DataRetention=_r;V.SpendAlerts=xr;V.Certificates=hr;var Or=class extends p{create(e,r,s){return this._client.post(l`/organization/users/${e}/roles`,{body:r,...s,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,s){let{user_id:n}=r;return this._client.get(l`/organization/users/${n}/roles/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}list(e,r={},s){return this._client.getAPIList(l`/organization/users/${e}/roles`,B,{query:r,...s,__security:{adminAPIKeyAuth:!0}})}delete(e,r,s){let{user_id:n}=r;return this._client.delete(l`/organization/users/${n}/roles/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}};var pt=class extends p{constructor(){super(...arguments),this.roles=new Or(this._client)}retrieve(e,r){return this._client.get(l`/organization/users/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,s){return this._client.post(l`/organization/users/${e}`,{body:r,...s,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/users",$,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(l`/organization/users/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};pt.Roles=Or;var J=class extends p{constructor(){super(...arguments),this.auditLogs=new or(this._client),this.adminAPIKeys=new nr(this._client),this.usage=new pr(this._client),this.invites=new ur(this._client),this.users=new pt(this._client),this.groups=new He(this._client),this.roles=new lr(this._client),this.dataRetention=new ar(this._client),this.spendAlerts=new cr(this._client),this.certificates=new ir(this._client),this.projects=new V(this._client)}};J.AuditLogs=or;J.AdminAPIKeys=nr;J.Usage=pr;J.Invites=ur;J.Users=pt;J.Groups=He;J.Roles=lr;J.DataRetention=ar;J.SpendAlerts=cr;J.Certificates=ir;J.Projects=V;var Ze=class extends p{constructor(){super(...arguments),this.organization=new J(this._client)}};Ze.Organization=J;var pa=Symbol("brand.privateNullableHeaders");function*hc(t){if(!t)return;if(pa in t){let{values:s,nulls:n}=t;yield*s.entries();for(let o of n)yield[o,null];return}let e=!1,r;t instanceof Headers?r=t.entries():Zn(t)?r=t:(e=!0,r=Object.entries(t??{}));for(let s of r){let n=s[0];if(typeof n!="string")throw new TypeError("expected header name to be a string");let o=Zn(s[1])?s[1]:[s[1]],i=!1;for(let a of o)a!==void 0&&(e&&!i&&(i=!0,yield[n,null]),yield[n,a])}}var w=t=>{let e=new Headers,r=new Set;for(let s of t){let n=new Set;for(let[o,i]of hc(s)){let a=o.toLowerCase();n.has(a)||(e.delete(o),n.add(a)),i===null?(e.delete(o),r.add(a)):(e.append(o,i),r.delete(a))}}return{[pa]:!0,values:e,nulls:r}};var kr=class extends p{create(e,r){return this._client.post("/audio/speech",{body:e,...r,headers:w([{Accept:"application/octet-stream"},r?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var vr=class extends p{create(e,r){return this._client.post("/audio/transcriptions",ee({body:e,...r,stream:e.stream??!1,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}};var Tr=class extends p{create(e,r){return this._client.post("/audio/translations",ee({body:e,...r,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}};var Pe=class extends p{constructor(){super(...arguments),this.transcriptions=new vr(this._client),this.translations=new Tr(this._client),this.speech=new kr(this._client)}};Pe.Transcriptions=vr;Pe.Translations=Tr;Pe.Speech=kr;var mt=class extends p{create(e,r){return this._client.post("/batches",{body:e,...r,__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(l`/batches/${e}`,{...r,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/batches",C,{query:e,...r,__security:{bearerAuth:!0}})}cancel(e,r){return this._client.post(l`/batches/${e}/cancel`,{...r,__security:{bearerAuth:!0}})}};var Cr=class extends p{create(e,r){return this._client.post("/assistants",{body:e,...r,headers:w([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(l`/assistants/${e}`,{...r,headers:w([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}update(e,r,s){return this._client.post(l`/assistants/${e}`,{body:r,...s,headers:w([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/assistants",C,{query:e,...r,headers:w([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(l`/assistants/${e}`,{...r,headers:w([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}};var Rr=class extends p{create(e,r){return this._client.post("/realtime/sessions",{body:e,...r,headers:w([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}};var Er=class extends p{create(e,r){return this._client.post("/realtime/transcription_sessions",{body:e,...r,headers:w([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}};var Ve=class extends p{constructor(){super(...arguments),this.sessions=new Rr(this._client),this.transcriptionSessions=new Er(this._client)}};Ve.Sessions=Rr;Ve.TranscriptionSessions=Er;var Sr=class extends p{create(e,r){return this._client.post("/chatkit/sessions",{body:e,...r,headers:w([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers]),__security:{bearerAuth:!0}})}cancel(e,r){return this._client.post(l`/chatkit/sessions/${e}/cancel`,{...r,headers:w([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers]),__security:{bearerAuth:!0}})}};var $r=class extends p{retrieve(e,r){return this._client.get(l`/chatkit/threads/${e}`,{...r,headers:w([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers]),__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/chatkit/threads",$,{query:e,...r,headers:w([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers]),__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(l`/chatkit/threads/${e}`,{...r,headers:w([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers]),__security:{bearerAuth:!0}})}listItems(e,r={},s){return this._client.getAPIList(l`/chatkit/threads/${e}/items`,$,{query:r,...s,headers:w([{"OpenAI-Beta":"chatkit_beta=v1"},s?.headers]),__security:{bearerAuth:!0}})}};var Je=class extends p{constructor(){super(...arguments),this.sessions=new Sr(this._client),this.threads=new $r(this._client)}};Je.Sessions=Sr;Je.Threads=$r;var Mr=class extends p{create(e,r,s){return this._client.post(l`/threads/${e}/messages`,{body:r,...s,headers:w([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}retrieve(e,r,s){let{thread_id:n}=r;return this._client.get(l`/threads/${n}/messages/${e}`,{...s,headers:w([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}update(e,r,s){let{thread_id:n,...o}=r;return this._client.post(l`/threads/${n}/messages/${e}`,{body:o,...s,headers:w([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}list(e,r={},s){return this._client.getAPIList(l`/threads/${e}/messages`,C,{query:r,...s,headers:w([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}delete(e,r,s){let{thread_id:n}=r;return this._client.delete(l`/threads/${n}/messages/${e}`,{...s,headers:w([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}};var Nr=class extends p{retrieve(e,r,s){let{thread_id:n,run_id:o,...i}=r;return this._client.get(l`/threads/${n}/runs/${o}/steps/${e}`,{query:i,...s,headers:w([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}list(e,r,s){let{thread_id:n,...o}=r;return this._client.getAPIList(l`/threads/${n}/runs/${e}/steps`,C,{query:o,...s,headers:w([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}};var ma=t=>{if(typeof Buffer<"u"){let e=Buffer.from(t,"base64");return Array.from(new Float32Array(e.buffer,e.byteOffset,e.length/Float32Array.BYTES_PER_ELEMENT))}else{let e=atob(t),r=e.length,s=new Uint8Array(r);for(let n=0;n<r;n++)s[n]=e.charCodeAt(n);return Array.from(new Float32Array(s.buffer))}};var me=t=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[t]?.trim()||void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(t)?.trim()||void 0};var G,ft,vo,Oe,fn,de,ht,zr,dt,gn,oe,hn,_n,Ts,ks,vs,da,fa,ha,_a,ga,ya,Aa,Ee=class extends Be{constructor(){super(...arguments),G.add(this),vo.set(this,[]),Oe.set(this,{}),fn.set(this,{}),de.set(this,void 0),ht.set(this,void 0),zr.set(this,void 0),dt.set(this,void 0),gn.set(this,void 0),oe.set(this,void 0),hn.set(this,void 0),_n.set(this,void 0),Ts.set(this,void 0)}[(vo=new WeakMap,Oe=new WeakMap,fn=new WeakMap,de=new WeakMap,ht=new WeakMap,zr=new WeakMap,dt=new WeakMap,gn=new WeakMap,oe=new WeakMap,hn=new WeakMap,_n=new WeakMap,Ts=new WeakMap,G=new WeakSet,Symbol.asyncIterator)](){let e=[],r=[],s=!1;return this.on("event",n=>{let o=r.shift();o?o.resolve(n):e.push(n)}),this.on("end",()=>{s=!0;for(let n of r)n.resolve(void 0);r.length=0}),this.on("abort",n=>{s=!0;for(let o of r)o.reject(n);r.length=0}),this.on("error",n=>{s=!0;for(let o of r)o.reject(n);r.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:s?{value:void 0,done:!0}:new Promise((o,i)=>r.push({resolve:o,reject:i})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){let r=new ft;return r._run(()=>r._fromReadableStream(e)),r}async _fromReadableStream(e,r){this._listenForAbort(r?.signal),this._connected();let s=we.fromReadableStream(e,this.controller);for await(let n of s)d(this,G,"m",ks).call(this,n);if(s.controller.signal?.aborted)throw new L;return this._addRun(d(this,G,"m",vs).call(this))}toReadableStream(){return new we(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,r,s,n){let o=new ft;return o._run(()=>o._runToolAssistantStream(e,r,s,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),o}async _createToolAssistantStream(e,r,s,n){this._listenForAbort(n?.signal);let o={...s,stream:!0},i=await e.submitToolOutputs(r,o,{...n,signal:this.controller.signal});this._connected();for await(let a of i)d(this,G,"m",ks).call(this,a);if(i.controller.signal?.aborted)throw new L;return this._addRun(d(this,G,"m",vs).call(this))}static createThreadAssistantStream(e,r,s){let n=new ft;return n._run(()=>n._threadAssistantStream(e,r,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),n}static createAssistantStream(e,r,s,n){let o=new ft;return o._run(()=>o._runAssistantStream(e,r,s,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),o}currentEvent(){return d(this,hn,"f")}currentRun(){return d(this,_n,"f")}currentMessageSnapshot(){return d(this,de,"f")}currentRunStepSnapshot(){return d(this,Ts,"f")}async finalRunSteps(){return await this.done(),Object.values(d(this,Oe,"f"))}async finalMessages(){return await this.done(),Object.values(d(this,fn,"f"))}async finalRun(){if(await this.done(),!d(this,ht,"f"))throw Error("Final run was not received.");return d(this,ht,"f")}async _createThreadAssistantStream(e,r,s){this._listenForAbort(s?.signal);let n={...r,stream:!0},o=await e.createAndRun(n,{...s,signal:this.controller.signal});this._connected();for await(let i of o)d(this,G,"m",ks).call(this,i);if(o.controller.signal?.aborted)throw new L;return this._addRun(d(this,G,"m",vs).call(this))}async _createAssistantStream(e,r,s,n){this._listenForAbort(n?.signal);let o={...s,stream:!0},i=await e.create(r,o,{...n,signal:this.controller.signal});this._connected();for await(let a of i)d(this,G,"m",ks).call(this,a);if(i.controller.signal?.aborted)throw new L;return this._addRun(d(this,G,"m",vs).call(this))}static accumulateDelta(e,r){for(let[s,n]of Object.entries(r)){if(!e.hasOwnProperty(s)){e[s]=n;continue}let o=e[s];if(o==null){e[s]=n;continue}if(s==="index"||s==="type"){e[s]=n;continue}if(typeof o=="string"&&typeof n=="string")o+=n;else if(typeof o=="number"&&typeof n=="number")o+=n;else if(cs(o)&&cs(n))o=this.accumulateDelta(o,n);else if(Array.isArray(o)&&Array.isArray(n)){if(o.every(i=>typeof i=="string"||typeof i=="number")){o.push(...n);continue}for(let i of n){if(!cs(i))throw new Error(`Expected array delta entry to be an object but got: ${i}`);let a=i.index;if(a==null)throw console.error(i),new Error("Expected array delta entry to have an `index` property");if(typeof a!="number")throw new Error(`Expected array delta entry \`index\` property to be a number but got ${a}`);let c=o[a];c==null?o.push(i):o[a]=this.accumulateDelta(c,i)}continue}else throw Error(`Unhandled record type: ${s}, deltaValue: ${n}, accValue: ${o}`);e[s]=o}return e}_addRun(e){return e}async _threadAssistantStream(e,r,s){return await this._createThreadAssistantStream(r,e,s)}async _runAssistantStream(e,r,s,n){return await this._createAssistantStream(r,e,s,n)}async _runToolAssistantStream(e,r,s,n){return await this._createToolAssistantStream(r,e,s,n)}};ft=Ee,ks=function(e){if(!this.ended)switch(k(this,hn,e,"f"),d(this,G,"m",ha).call(this,e),e.event){case"thread.created":break;case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":case"thread.run.requires_action":case"thread.run.completed":case"thread.run.incomplete":case"thread.run.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":d(this,G,"m",Aa).call(this,e);break;case"thread.run.step.created":case"thread.run.step.in_progress":case"thread.run.step.delta":case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":d(this,G,"m",fa).call(this,e);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":d(this,G,"m",da).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier");default:}},vs=function(){if(this.ended)throw new P("stream has ended, this shouldn't happen");if(!d(this,ht,"f"))throw Error("Final run has not been received");return d(this,ht,"f")},da=function(e){let[r,s]=d(this,G,"m",ga).call(this,e,d(this,de,"f"));k(this,de,r,"f"),d(this,fn,"f")[r.id]=r;for(let n of s){let o=r.content[n.index];o?.type=="text"&&this._emit("textCreated",o.text)}switch(e.event){case"thread.message.created":this._emit("messageCreated",e.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",e.data.delta,r),e.data.delta.content)for(let n of e.data.delta.content){if(n.type=="text"&&n.text){let o=n.text,i=r.content[n.index];if(i&&i.type=="text")this._emit("textDelta",o,i.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(n.index!=d(this,zr,"f")){if(d(this,dt,"f"))switch(d(this,dt,"f").type){case"text":this._emit("textDone",d(this,dt,"f").text,d(this,de,"f"));break;case"image_file":this._emit("imageFileDone",d(this,dt,"f").image_file,d(this,de,"f"));break}k(this,zr,n.index,"f")}k(this,dt,r.content[n.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(d(this,zr,"f")!==void 0){let n=e.data.content[d(this,zr,"f")];if(n)switch(n.type){case"image_file":this._emit("imageFileDone",n.image_file,d(this,de,"f"));break;case"text":this._emit("textDone",n.text,d(this,de,"f"));break}}d(this,de,"f")&&this._emit("messageDone",e.data),k(this,de,void 0,"f")}},fa=function(e){let r=d(this,G,"m",_a).call(this,e);switch(k(this,Ts,r,"f"),e.event){case"thread.run.step.created":this._emit("runStepCreated",e.data);break;case"thread.run.step.delta":let s=e.data.delta;if(s.step_details&&s.step_details.type=="tool_calls"&&s.step_details.tool_calls&&r.step_details.type=="tool_calls")for(let o of s.step_details.tool_calls)o.index==d(this,gn,"f")?this._emit("toolCallDelta",o,r.step_details.tool_calls[o.index]):(d(this,oe,"f")&&this._emit("toolCallDone",d(this,oe,"f")),k(this,gn,o.index,"f"),k(this,oe,r.step_details.tool_calls[o.index],"f"),d(this,oe,"f")&&this._emit("toolCallCreated",d(this,oe,"f")));this._emit("runStepDelta",e.data.delta,r);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":k(this,Ts,void 0,"f"),e.data.step_details.type=="tool_calls"&&d(this,oe,"f")&&(this._emit("toolCallDone",d(this,oe,"f")),k(this,oe,void 0,"f")),this._emit("runStepDone",e.data,r);break;case"thread.run.step.in_progress":break}},ha=function(e){d(this,vo,"f").push(e),this._emit("event",e)},_a=function(e){switch(e.event){case"thread.run.step.created":return d(this,Oe,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let r=d(this,Oe,"f")[e.data.id];if(!r)throw Error("Received a RunStepDelta before creation of a snapshot");let s=e.data;if(s.delta){let n=ft.accumulateDelta(r,s.delta);d(this,Oe,"f")[e.data.id]=n}return d(this,Oe,"f")[e.data.id];case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":case"thread.run.step.in_progress":d(this,Oe,"f")[e.data.id]=e.data;break}if(d(this,Oe,"f")[e.data.id])return d(this,Oe,"f")[e.data.id];throw new Error("No snapshot available")},ga=function(e,r){let s=[];switch(e.event){case"thread.message.created":return[e.data,s];case"thread.message.delta":if(!r)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let n=e.data;if(n.delta.content)for(let o of n.delta.content)if(o.index in r.content){let i=r.content[o.index];r.content[o.index]=d(this,G,"m",ya).call(this,o,i)}else r.content[o.index]=o,s.push(o);return[r,s];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(r)return[r,s];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},ya=function(e,r){return ft.accumulateDelta(r,e)},Aa=function(e){switch(k(this,_n,e.data,"f"),e.event){case"thread.run.created":break;case"thread.run.queued":break;case"thread.run.in_progress":break;case"thread.run.requires_action":case"thread.run.cancelled":case"thread.run.failed":case"thread.run.completed":case"thread.run.expired":case"thread.run.incomplete":k(this,ht,e.data,"f"),d(this,oe,"f")&&(this._emit("toolCallDone",d(this,oe,"f")),k(this,oe,void 0,"f"));break;case"thread.run.cancelling":break}};var _t=class extends p{constructor(){super(...arguments),this.steps=new Nr(this._client)}create(e,r,s){let{include:n,...o}=r;return this._client.post(l`/threads/${e}/runs`,{query:{include:n},body:o,...s,headers:w([{"OpenAI-Beta":"assistants=v2"},s?.headers]),stream:r.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}retrieve(e,r,s){let{thread_id:n}=r;return this._client.get(l`/threads/${n}/runs/${e}`,{...s,headers:w([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}update(e,r,s){let{thread_id:n,...o}=r;return this._client.post(l`/threads/${n}/runs/${e}`,{body:o,...s,headers:w([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}list(e,r={},s){return this._client.getAPIList(l`/threads/${e}/runs`,C,{query:r,...s,headers:w([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}cancel(e,r,s){let{thread_id:n}=r;return this._client.post(l`/threads/${n}/runs/${e}/cancel`,{...s,headers:w([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,r,s){let n=await this.create(e,r,s);return await this.poll(n.id,{thread_id:e},s)}createAndStream(e,r,s){return Ee.createAssistantStream(e,this._client.beta.threads.runs,r,s)}async poll(e,r,s){let n=w([s?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":s?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:o,response:i}=await this.retrieve(e,r,{...s,headers:{...s?.headers,...n}}).withResponse();switch(o.status){case"queued":case"in_progress":case"cancelling":let a=5e3;if(s?.pollIntervalMs)a=s.pollIntervalMs;else{let c=i.headers.get("openai-poll-after-ms");if(c){let u=parseInt(c);isNaN(u)||(a=u)}}await be(a);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return o}}}stream(e,r,s){return Ee.createAssistantStream(e,this._client.beta.threads.runs,r,s)}submitToolOutputs(e,r,s){let{thread_id:n,...o}=r;return this._client.post(l`/threads/${n}/runs/${e}/submit_tool_outputs`,{body:o,...s,headers:w([{"OpenAI-Beta":"assistants=v2"},s?.headers]),stream:r.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}async submitToolOutputsAndPoll(e,r,s){let n=await this.submitToolOutputs(e,r,s);return await this.poll(n.id,r,s)}submitToolOutputsStream(e,r,s){return Ee.createToolAssistantStream(e,this._client.beta.threads.runs,r,s)}};_t.Steps=Nr;var Ge=class extends p{constructor(){super(...arguments),this.runs=new _t(this._client),this.messages=new Mr(this._client)}create(e={},r){return this._client.post("/threads",{body:e,...r,headers:w([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(l`/threads/${e}`,{...r,headers:w([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}update(e,r,s){return this._client.post(l`/threads/${e}`,{body:r,...s,headers:w([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(l`/threads/${e}`,{...r,headers:w([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}createAndRun(e,r){return this._client.post("/threads/runs",{body:e,...r,headers:w([{"OpenAI-Beta":"assistants=v2"},r?.headers]),stream:e.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}async createAndRunPoll(e,r){let s=await this.createAndRun(e,r);return await this.runs.poll(s.id,{thread_id:s.thread_id},r)}createAndRunStream(e,r){return Ee.createThreadAssistantStream(e,this._client.beta.threads,r)}};Ge.Runs=_t;Ge.Messages=Mr;var fe=class extends p{constructor(){super(...arguments),this.realtime=new Ve(this._client),this.chatkit=new Je(this._client),this.assistants=new Cr(this._client),this.threads=new Ge(this._client)}};fe.Realtime=Ve;fe.ChatKit=Je;fe.Assistants=Cr;fe.Threads=Ge;var gt=class extends p{create(e,r){return this._client.post("/completions",{body:e,...r,stream:e.stream??!1,__security:{bearerAuth:!0}})}};var jr=class extends p{retrieve(e,r,s){let{container_id:n}=r;return this._client.get(l`/containers/${n}/files/${e}/content`,{...s,headers:w([{Accept:"application/binary"},s?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var yt=class extends p{constructor(){super(...arguments),this.content=new jr(this._client)}create(e,r,s){return this._client.post(l`/containers/${e}/files`,Fe({body:r,...s,__security:{bearerAuth:!0}},this._client))}retrieve(e,r,s){let{container_id:n}=r;return this._client.get(l`/containers/${n}/files/${e}`,{...s,__security:{bearerAuth:!0}})}list(e,r={},s){return this._client.getAPIList(l`/containers/${e}/files`,C,{query:r,...s,__security:{bearerAuth:!0}})}delete(e,r,s){let{container_id:n}=r;return this._client.delete(l`/containers/${n}/files/${e}`,{...s,headers:w([{Accept:"*/*"},s?.headers]),__security:{bearerAuth:!0}})}};yt.Content=jr;var Xe=class extends p{constructor(){super(...arguments),this.files=new yt(this._client)}create(e,r){return this._client.post("/containers",{body:e,...r,__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(l`/containers/${e}`,{...r,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/containers",C,{query:e,...r,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(l`/containers/${e}`,{...r,headers:w([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}};Xe.Files=yt;var Ur=class extends p{create(e,r,s){let{include:n,...o}=r;return this._client.post(l`/conversations/${e}/items`,{query:{include:n},body:o,...s,__security:{bearerAuth:!0}})}retrieve(e,r,s){let{conversation_id:n,...o}=r;return this._client.get(l`/conversations/${n}/items/${e}`,{query:o,...s,__security:{bearerAuth:!0}})}list(e,r={},s){return this._client.getAPIList(l`/conversations/${e}/items`,$,{query:r,...s,__security:{bearerAuth:!0}})}delete(e,r,s){let{conversation_id:n}=r;return this._client.delete(l`/conversations/${n}/items/${e}`,{...s,__security:{bearerAuth:!0}})}};var Ye=class extends p{constructor(){super(...arguments),this.items=new Ur(this._client)}create(e={},r){return this._client.post("/conversations",{body:e,...r,__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(l`/conversations/${e}`,{...r,__security:{bearerAuth:!0}})}update(e,r,s){return this._client.post(l`/conversations/${e}`,{body:r,...s,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(l`/conversations/${e}`,{...r,__security:{bearerAuth:!0}})}};Ye.Items=Ur;var At=class extends p{create(e,r){let s=!!e.encoding_format,n=s?e.encoding_format:"base64";s&&K(this._client).debug("embeddings/user defined encoding_format:",e.encoding_format);let o=this._client.post("/embeddings",{body:{...e,encoding_format:n},...r,__security:{bearerAuth:!0}});return s?o:(K(this._client).debug("embeddings/decoding base64 embeddings from base64"),o._thenUnwrap(i=>(i&&i.data&&i.data.forEach(a=>{let c=a.embedding;a.embedding=ma(c)}),i)))}};var Lr=class extends p{retrieve(e,r,s){let{eval_id:n,run_id:o}=r;return this._client.get(l`/evals/${n}/runs/${o}/output_items/${e}`,{...s,__security:{bearerAuth:!0}})}list(e,r,s){let{eval_id:n,...o}=r;return this._client.getAPIList(l`/evals/${n}/runs/${e}/output_items`,C,{query:o,...s,__security:{bearerAuth:!0}})}};var It=class extends p{constructor(){super(...arguments),this.outputItems=new Lr(this._client)}create(e,r,s){return this._client.post(l`/evals/${e}/runs`,{body:r,...s,__security:{bearerAuth:!0}})}retrieve(e,r,s){let{eval_id:n}=r;return this._client.get(l`/evals/${n}/runs/${e}`,{...s,__security:{bearerAuth:!0}})}list(e,r={},s){return this._client.getAPIList(l`/evals/${e}/runs`,C,{query:r,...s,__security:{bearerAuth:!0}})}delete(e,r,s){let{eval_id:n}=r;return this._client.delete(l`/evals/${n}/runs/${e}`,{...s,__security:{bearerAuth:!0}})}cancel(e,r,s){let{eval_id:n}=r;return this._client.post(l`/evals/${n}/runs/${e}`,{...s,__security:{bearerAuth:!0}})}};It.OutputItems=Lr;var Qe=class extends p{constructor(){super(...arguments),this.runs=new It(this._client)}create(e,r){return this._client.post("/evals",{body:e,...r,__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(l`/evals/${e}`,{...r,__security:{bearerAuth:!0}})}update(e,r,s){return this._client.post(l`/evals/${e}`,{body:r,...s,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/evals",C,{query:e,...r,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(l`/evals/${e}`,{...r,__security:{bearerAuth:!0}})}};Qe.Runs=It;var bt=class extends p{create(e,r){return this._client.post("/files",ee({body:e,...r,__security:{bearerAuth:!0}},this._client))}retrieve(e,r){return this._client.get(l`/files/${e}`,{...r,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/files",C,{query:e,...r,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(l`/files/${e}`,{...r,__security:{bearerAuth:!0}})}content(e,r){return this._client.get(l`/files/${e}/content`,{...r,headers:w([{Accept:"application/binary"},r?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:r=5e3,maxWait:s=1800*1e3}={}){let n=new Set(["processed","error","deleted"]),o=Date.now(),i=await this.retrieve(e);for(;!i.status||!n.has(i.status);)if(await be(r),i=await this.retrieve(e),Date.now()-o>s)throw new Ae({message:`Giving up on waiting for file ${e} to finish processing after ${s} milliseconds.`});return i}};var Dr=class extends p{};var Kr=class extends p{run(e,r){return this._client.post("/fine_tuning/alpha/graders/run",{body:e,...r,__security:{bearerAuth:!0}})}validate(e,r){return this._client.post("/fine_tuning/alpha/graders/validate",{body:e,...r,__security:{bearerAuth:!0}})}};var xt=class extends p{constructor(){super(...arguments),this.graders=new Kr(this._client)}};xt.Graders=Kr;var Fr=class extends p{create(e,r,s){return this._client.getAPIList(l`/fine_tuning/checkpoints/${e}/permissions`,Q,{body:r,method:"post",...s,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r={},s){return this._client.get(l`/fine_tuning/checkpoints/${e}/permissions`,{query:r,...s,__security:{adminAPIKeyAuth:!0}})}list(e,r={},s){return this._client.getAPIList(l`/fine_tuning/checkpoints/${e}/permissions`,$,{query:r,...s,__security:{adminAPIKeyAuth:!0}})}delete(e,r,s){let{fine_tuned_model_checkpoint:n}=r;return this._client.delete(l`/fine_tuning/checkpoints/${n}/permissions/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}};var wt=class extends p{constructor(){super(...arguments),this.permissions=new Fr(this._client)}};wt.Permissions=Fr;var Br=class extends p{list(e,r={},s){return this._client.getAPIList(l`/fine_tuning/jobs/${e}/checkpoints`,C,{query:r,...s,__security:{bearerAuth:!0}})}};var Pt=class extends p{constructor(){super(...arguments),this.checkpoints=new Br(this._client)}create(e,r){return this._client.post("/fine_tuning/jobs",{body:e,...r,__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(l`/fine_tuning/jobs/${e}`,{...r,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/fine_tuning/jobs",C,{query:e,...r,__security:{bearerAuth:!0}})}cancel(e,r){return this._client.post(l`/fine_tuning/jobs/${e}/cancel`,{...r,__security:{bearerAuth:!0}})}listEvents(e,r={},s){return this._client.getAPIList(l`/fine_tuning/jobs/${e}/events`,C,{query:r,...s,__security:{bearerAuth:!0}})}pause(e,r){return this._client.post(l`/fine_tuning/jobs/${e}/pause`,{...r,__security:{bearerAuth:!0}})}resume(e,r){return this._client.post(l`/fine_tuning/jobs/${e}/resume`,{...r,__security:{bearerAuth:!0}})}};Pt.Checkpoints=Br;var he=class extends p{constructor(){super(...arguments),this.methods=new Dr(this._client),this.jobs=new Pt(this._client),this.checkpoints=new wt(this._client),this.alpha=new xt(this._client)}};he.Methods=Dr;he.Jobs=Pt;he.Checkpoints=wt;he.Alpha=xt;var qr=class extends p{};var et=class extends p{constructor(){super(...arguments),this.graderModels=new qr(this._client)}};et.GraderModels=qr;var Ot=class extends p{createVariation(e,r){return this._client.post("/images/variations",ee({body:e,...r,__security:{bearerAuth:!0}},this._client))}edit(e,r){return this._client.post("/images/edits",ee({body:e,...r,stream:e.stream??!1,__security:{bearerAuth:!0}},this._client))}generate(e,r){return this._client.post("/images/generations",{body:e,...r,stream:e.stream??!1,__security:{bearerAuth:!0}})}};var kt=class extends p{retrieve(e,r){return this._client.get(l`/models/${e}`,{...r,__security:{bearerAuth:!0}})}list(e){return this._client.getAPIList("/models",Q,{...e,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(l`/models/${e}`,{...r,__security:{bearerAuth:!0}})}};var vt=class extends p{create(e,r){return this._client.post("/moderations",{body:e,...r,__security:{bearerAuth:!0}})}};var Wr=class extends p{accept(e,r,s){return this._client.post(l`/realtime/calls/${e}/accept`,{body:r,...s,headers:w([{Accept:"*/*"},s?.headers]),__security:{bearerAuth:!0}})}hangup(e,r){return this._client.post(l`/realtime/calls/${e}/hangup`,{...r,headers:w([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}refer(e,r,s){return this._client.post(l`/realtime/calls/${e}/refer`,{body:r,...s,headers:w([{Accept:"*/*"},s?.headers]),__security:{bearerAuth:!0}})}reject(e,r={},s){return this._client.post(l`/realtime/calls/${e}/reject`,{body:r,...s,headers:w([{Accept:"*/*"},s?.headers]),__security:{bearerAuth:!0}})}};var Hr=class extends p{create(e,r){return this._client.post("/realtime/client_secrets",{body:e,...r,__security:{bearerAuth:!0}})}};var Se=class extends p{constructor(){super(...arguments),this.clientSecrets=new Hr(this._client),this.calls=new Wr(this._client)}};Se.ClientSecrets=Hr;Se.Calls=Wr;function Ia(t,e){if(!e||!Hc(e)){let r={...t,output_parsed:null,output:t.output.map(s=>s.type==="function_call"?{...s,parsed_arguments:null}:s.type==="message"?{...s,content:s.content.map(n=>({...n,parsed:null}))}:s)};return ba(t,r)&&ie(r),r}return To(t,e)}function To(t,e){let r=!t.status||t.status==="completed",s=t.output.map(o=>{if(o.type==="function_call")return{...o,parsed_arguments:r?Jc(e,o):null};if(o.type==="message"){let i=o.content.map(a=>a.type==="output_text"?{...a,parsed:r?Wc(e,a.text):null}:a);return{...o,content:i}}return o}),n=Object.assign({},t,{output:s});return ba(t,n)&&ie(n),Object.defineProperty(n,"output_parsed",{enumerable:!0,get(){for(let o of n.output)if(o.type==="message"){for(let i of o.content)if(i.type==="output_text"&&i.parsed!==null)return i.parsed}return null}}),n}function Wc(t,e){return t.text?.format?.type!=="json_schema"?null:"$parseRaw"in t.text?.format?(t.text?.format).$parseRaw(e):JSON.parse(e)}function Hc(t){return!!ys(t.text?.format)}function Zc(t){return t?.$brand==="auto-parseable-tool"}function Vc(t,e){return t.find(r=>r.type==="function"&&r.name===e)}function Jc(t,e){let r=Vc(t.tools??[],e.name);return{...e,...e,parsed_arguments:Zc(r)?r.$parseRaw(e.arguments):r?.strict?JSON.parse(e.arguments):null}}function ba(t,e){return!Object.getOwnPropertyDescriptor(t,"output_text")||e.output_text==null}function ie(t){let e=[];for(let r of t.output)if(r.type==="message")for(let s of r.content)s.type==="output_text"&&e.push(s.text);t.output_text=e.join("")}function wa(t,e){if(!e){if(t.type!=="response.created")throw new P(`When snapshot hasn't been set yet, expected 'response.created' event, got ${t.type}`);return xa(t.response)}switch(t.type){case"response.output_item.added":{e.output.push(structuredClone(t.item)),t.item.type==="message"&&ie(e);break}case"response.output_item.done":{S(e,t.output_index),e.output[t.output_index]=structuredClone(t.item),t.item.type==="message"&&ie(e);break}case"response.content_part.added":{let r=S(e,t.output_index),s=r.type,n=t.part;s==="message"&&n.type!=="reasoning_text"?(r.content.push(structuredClone(n)),n.type==="output_text"&&ie(e)):s==="reasoning"&&n.type==="reasoning_text"&&(r.content||(r.content=[]),r.content.push(structuredClone(n)));break}case"response.content_part.done":{let r=S(e,t.output_index),s=t.part;if(r.type==="message"&&s.type!=="reasoning_text")le(r.content,t.content_index),r.content[t.content_index]=structuredClone(s),s.type==="output_text"&&ie(e);else if(r.type==="reasoning"&&s.type==="reasoning_text"){let n=r.content;if(!n)throw new P(`missing content at index ${t.content_index}`);le(n,t.content_index),n[t.content_index]=structuredClone(s)}break}case"response.output_text.delta":{let r=S(e,t.output_index);if(r.type==="message"){let s=le(r.content,t.content_index);if(s.type!=="output_text")throw new P(`expected content to be 'output_text', got ${s.type}`);s.text+=t.delta,e.output_text+=t.delta}break}case"response.output_text.done":{let r=S(e,t.output_index);if(r.type==="message"){let s=le(r.content,t.content_index);if(s.type!=="output_text")throw new P(`expected content to be 'output_text', got ${s.type}`);s.text=t.text,ie(e)}break}case"response.output_text.annotation.added":{let r=S(e,t.output_index);if(r.type==="message"){let s=le(r.content,t.content_index);if(s.type!=="output_text")throw new P(`expected content to be 'output_text', got ${s.type}`);s.annotations[t.annotation_index]=structuredClone(t.annotation)}break}case"response.refusal.delta":{let r=S(e,t.output_index);if(r.type==="message"){let s=le(r.content,t.content_index);if(s.type!=="refusal")throw new P(`expected content to be 'refusal', got ${s.type}`);s.refusal+=t.delta}break}case"response.refusal.done":{let r=S(e,t.output_index);if(r.type==="message"){let s=le(r.content,t.content_index);if(s.type!=="refusal")throw new P(`expected content to be 'refusal', got ${s.type}`);s.refusal=t.refusal}break}case"response.function_call_arguments.delta":{let r=S(e,t.output_index);r.type==="function_call"&&(r.arguments+=t.delta);break}case"response.function_call_arguments.done":{let r=S(e,t.output_index);r.type==="function_call"&&(r.arguments=t.arguments);break}case"response.reasoning_text.delta":{let r=S(e,t.output_index);if(r.type==="reasoning"){if(!r.content)throw new P(`missing content at index ${t.content_index}`);let s=le(r.content,t.content_index);if(s.type!=="reasoning_text")throw new P(`expected content to be 'reasoning_text', got ${s.type}`);s.text+=t.delta}break}case"response.reasoning_text.done":{let r=S(e,t.output_index);if(r.type==="reasoning"){if(!r.content)throw new P(`missing content at index ${t.content_index}`);let s=le(r.content,t.content_index);if(s.type!=="reasoning_text")throw new P(`expected content to be 'reasoning_text', got ${s.type}`);s.text=t.text}break}case"response.reasoning_summary_part.added":{let r=S(e,t.output_index);r.type==="reasoning"&&r.summary.push(structuredClone(t.part));break}case"response.reasoning_summary_part.done":{let r=S(e,t.output_index);r.type==="reasoning"&&(le(r.summary,t.summary_index),r.summary[t.summary_index]=structuredClone(t.part));break}case"response.reasoning_summary_text.delta":{let r=S(e,t.output_index);if(r.type==="reasoning"){let s=le(r.summary,t.summary_index);s.text+=t.delta}break}case"response.reasoning_summary_text.done":{let r=S(e,t.output_index);if(r.type==="reasoning"){let s=le(r.summary,t.summary_index);s.text=t.text}break}case"response.custom_tool_call_input.delta":{let r=S(e,t.output_index);r.type==="custom_tool_call"&&(r.input+=t.delta);break}case"response.custom_tool_call_input.done":{let r=S(e,t.output_index);r.type==="custom_tool_call"&&(r.input=t.input);break}case"response.mcp_call_arguments.delta":{let r=S(e,t.output_index);r.type==="mcp_call"&&(r.arguments+=t.delta);break}case"response.mcp_call_arguments.done":{let r=S(e,t.output_index);r.type==="mcp_call"&&(r.arguments=t.arguments);break}case"response.code_interpreter_call_code.delta":{let r=S(e,t.output_index);r.type==="code_interpreter_call"&&(r.code=(r.code??"")+t.delta);break}case"response.code_interpreter_call_code.done":{let r=S(e,t.output_index);r.type==="code_interpreter_call"&&(r.code=t.code);break}case"response.code_interpreter_call.in_progress":{let r=S(e,t.output_index);r.type==="code_interpreter_call"&&(r.status="in_progress");break}case"response.code_interpreter_call.interpreting":{let r=S(e,t.output_index);r.type==="code_interpreter_call"&&(r.status="interpreting");break}case"response.code_interpreter_call.completed":{let r=S(e,t.output_index);r.type==="code_interpreter_call"&&(r.status="completed");break}case"response.file_search_call.in_progress":{let r=S(e,t.output_index);r.type==="file_search_call"&&(r.status="in_progress");break}case"response.file_search_call.searching":{let r=S(e,t.output_index);r.type==="file_search_call"&&(r.status="searching");break}case"response.file_search_call.completed":{let r=S(e,t.output_index);r.type==="file_search_call"&&(r.status="completed");break}case"response.web_search_call.in_progress":{let r=S(e,t.output_index);r.type==="web_search_call"&&(r.status="in_progress");break}case"response.web_search_call.searching":{let r=S(e,t.output_index);r.type==="web_search_call"&&(r.status="searching");break}case"response.web_search_call.completed":{let r=S(e,t.output_index);r.type==="web_search_call"&&(r.status="completed");break}case"response.image_generation_call.in_progress":{let r=S(e,t.output_index);r.type==="image_generation_call"&&(r.status="in_progress");break}case"response.image_generation_call.generating":{let r=S(e,t.output_index);r.type==="image_generation_call"&&(r.status="generating");break}case"response.image_generation_call.completed":{let r=S(e,t.output_index);r.type==="image_generation_call"&&(r.status="completed");break}case"response.mcp_call.in_progress":{let r=S(e,t.output_index);r.type==="mcp_call"&&(r.status="in_progress");break}case"response.mcp_call.completed":{let r=S(e,t.output_index);r.type==="mcp_call"&&(r.status="completed");break}case"response.mcp_call.failed":{let r=S(e,t.output_index);r.type==="mcp_call"&&(r.status="failed");break}case"response.created":case"response.queued":case"response.in_progress":case"response.completed":case"response.failed":case"response.incomplete":{e=xa(t.response);break}case"response.audio.delta":case"response.audio.done":case"response.audio.transcript.delta":case"response.audio.transcript.done":case"response.image_generation_call.partial_image":case"response.mcp_list_tools.in_progress":case"response.mcp_list_tools.completed":case"response.mcp_list_tools.failed":case"error":break;default:Gc(t)}return e}function xa(t){let e=structuredClone(t);return(!Object.getOwnPropertyDescriptor(e,"output_text")||e.output_text==null)&&ie(e),e}function S(t,e){let r=t.output[e];if(!r)throw new P(`missing output at index ${e}`);return r}function le(t,e){let r=t[e];if(!r)throw new P(`missing content at index ${e}`);return r}function Gc(t){throw new P(`Unhandled response stream event: ${JSON.stringify(t)}`)}var Cs,yn,Tt,An,Pa,Oa,ka,In=class t extends Be{constructor(e){super(),Cs.add(this),yn.set(this,void 0),Tt.set(this,void 0),An.set(this,void 0),k(this,yn,e,"f")}static createResponse(e,r,s){let n=new t(r);return n._run(()=>n._createOrRetrieveResponse(e,r,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),n}async _createOrRetrieveResponse(e,r,s){this._listenForAbort(s?.signal),d(this,Cs,"m",Pa).call(this);let n,o=null;"response_id"in r?(n=await e.responses.retrieve(r.response_id,{stream:!0},{...s,signal:this.controller.signal,stream:!0}),o=r.starting_after??null):n=await e.responses.create({...r,stream:!0},{...s,signal:this.controller.signal}),this._connected();for await(let i of n)d(this,Cs,"m",Oa).call(this,i,o);if(n.controller.signal?.aborted)throw new L;return d(this,Cs,"m",ka).call(this)}[(yn=new WeakMap,Tt=new WeakMap,An=new WeakMap,Cs=new WeakSet,Pa=function(){this.ended||k(this,Tt,void 0,"f")},Oa=function(r,s){if(this.ended)return;let n=(i,a)=>{(s==null||a.sequence_number>s)&&this._emit(i,a)},o=wa(r,d(this,Tt,"f"));switch(k(this,Tt,o,"f"),n("event",r),r.type){case"response.output_text.delta":{let i=o.output[r.output_index];if(!i)throw new P(`missing output at index ${r.output_index}`);if(i.type==="message"){let a=i.content[r.content_index];if(!a)throw new P(`missing content at index ${r.content_index}`);if(a.type!=="output_text")throw new P(`expected content to be 'output_text', got ${a.type}`);n("response.output_text.delta",{...r,snapshot:a.text})}break}case"response.function_call_arguments.delta":{let i=o.output[r.output_index];if(!i)throw new P(`missing output at index ${r.output_index}`);i.type==="function_call"&&n("response.function_call_arguments.delta",{...r,snapshot:i.arguments});break}default:n(r.type,r);break}},ka=function(){if(this.ended)throw new P("stream has ended, this shouldn't happen");let r=d(this,Tt,"f");if(!r)throw new P("request ended without sending any events");k(this,Tt,void 0,"f");let s=Xc(r,d(this,yn,"f"));return k(this,An,s,"f"),s},Symbol.asyncIterator)](){let e=[],r=[],s=!1;return this.on("event",n=>{let o=r.shift();o?o.resolve(n):e.push(n)}),this.on("end",()=>{s=!0;for(let n of r)n.resolve(void 0);r.length=0}),this.on("abort",n=>{s=!0;for(let o of r)o.reject(n);r.length=0}),this.on("error",n=>{s=!0;for(let o of r)o.reject(n);r.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:s?{value:void 0,done:!0}:new Promise((o,i)=>r.push({resolve:o,reject:i})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();let e=d(this,An,"f");if(!e)throw new P("stream ended without producing a ChatCompletion");return e}};function Xc(t,e){return Ia(t,e)}var Zr=class extends p{list(e,r={},s){return this._client.getAPIList(l`/responses/${e}/input_items`,C,{query:r,...s,__security:{bearerAuth:!0}})}};var Vr=class extends p{count(e={},r){return this._client.post("/responses/input_tokens",{body:e,...r,__security:{bearerAuth:!0}})}};var ke=class extends p{constructor(){super(...arguments),this.inputItems=new Zr(this._client),this.inputTokens=new Vr(this._client)}create(e,r){return this._client.post("/responses",{body:e,...r,stream:e.stream??!1,__security:{bearerAuth:!0}})._thenUnwrap(s=>("object"in s&&s.object==="response"&&ie(s),s))}retrieve(e,r={},s){return this._client.get(l`/responses/${e}`,{query:r,...s,stream:r?.stream??!1,__security:{bearerAuth:!0}})._thenUnwrap(n=>("object"in n&&n.object==="response"&&ie(n),n))}delete(e,r){return this._client.delete(l`/responses/${e}`,{...r,headers:w([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}parse(e,r){return this._client.responses.create(e,r)._thenUnwrap(s=>To(s,e))}stream(e,r){return In.createResponse(this._client,e,r)}cancel(e,r){return this._client.post(l`/responses/${e}/cancel`,{...r,__security:{bearerAuth:!0}})}compact(e,r){return this._client.post("/responses/compact",{body:e,...r,__security:{bearerAuth:!0}})}};ke.InputItems=Zr;ke.InputTokens=Vr;var Jr=class extends p{retrieve(e,r){return this._client.get(l`/skills/${e}/content`,{...r,headers:w([{Accept:"application/binary"},r?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var Gr=class extends p{retrieve(e,r,s){let{skill_id:n}=r;return this._client.get(l`/skills/${n}/versions/${e}/content`,{...s,headers:w([{Accept:"application/binary"},s?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var Ct=class extends p{constructor(){super(...arguments),this.content=new Gr(this._client)}create(e,r={},s){return this._client.post(l`/skills/${e}/versions`,Fe({body:r,...s,__security:{bearerAuth:!0}},this._client))}retrieve(e,r,s){let{skill_id:n}=r;return this._client.get(l`/skills/${n}/versions/${e}`,{...s,__security:{bearerAuth:!0}})}list(e,r={},s){return this._client.getAPIList(l`/skills/${e}/versions`,C,{query:r,...s,__security:{bearerAuth:!0}})}delete(e,r,s){let{skill_id:n}=r;return this._client.delete(l`/skills/${n}/versions/${e}`,{...s,__security:{bearerAuth:!0}})}};Ct.Content=Gr;var $e=class extends p{constructor(){super(...arguments),this.content=new Jr(this._client),this.versions=new Ct(this._client)}create(e={},r){return this._client.post("/skills",Fe({body:e,...r,__security:{bearerAuth:!0}},this._client))}retrieve(e,r){return this._client.get(l`/skills/${e}`,{...r,__security:{bearerAuth:!0}})}update(e,r,s){return this._client.post(l`/skills/${e}`,{body:r,...s,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/skills",C,{query:e,...r,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(l`/skills/${e}`,{...r,__security:{bearerAuth:!0}})}};$e.Content=Jr;$e.Versions=Ct;var Xr=class extends p{create(e,r,s){return this._client.post(l`/uploads/${e}/parts`,ee({body:r,...s,__security:{bearerAuth:!0}},this._client))}};var tt=class extends p{constructor(){super(...arguments),this.parts=new Xr(this._client)}create(e,r){return this._client.post("/uploads",{body:e,...r,__security:{bearerAuth:!0}})}cancel(e,r){return this._client.post(l`/uploads/${e}/cancel`,{...r,__security:{bearerAuth:!0}})}complete(e,r,s){return this._client.post(l`/uploads/${e}/complete`,{body:r,...s,__security:{bearerAuth:!0}})}};tt.Parts=Xr;var va=async t=>{let e=await Promise.allSettled(t),r=e.filter(n=>n.status==="rejected");if(r.length){for(let n of r)console.error(n.reason);throw new Error(`${r.length} promise(s) failed - see the above errors`)}let s=[];for(let n of e)n.status==="fulfilled"&&s.push(n.value);return s};var Yr=class extends p{create(e,r,s){return this._client.post(l`/vector_stores/${e}/file_batches`,{body:r,...s,headers:w([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}retrieve(e,r,s){let{vector_store_id:n}=r;return this._client.get(l`/vector_stores/${n}/file_batches/${e}`,{...s,headers:w([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}cancel(e,r,s){let{vector_store_id:n}=r;return this._client.post(l`/vector_stores/${n}/file_batches/${e}/cancel`,{...s,headers:w([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,r,s){let n=await this.create(e,r);return await this.poll(e,n.id,s)}listFiles(e,r,s){let{vector_store_id:n,...o}=r;return this._client.getAPIList(l`/vector_stores/${n}/file_batches/${e}/files`,C,{query:o,...s,headers:w([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}async poll(e,r,s){let n=w([s?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":s?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:o,response:i}=await this.retrieve(r,{vector_store_id:e},{...s,headers:n}).withResponse();switch(o.status){case"in_progress":let a=5e3;if(s?.pollIntervalMs)a=s.pollIntervalMs;else{let c=i.headers.get("openai-poll-after-ms");if(c){let u=parseInt(c);isNaN(u)||(a=u)}}await be(a);break;case"failed":case"cancelled":case"completed":return o}}}async uploadAndPoll(e,{files:r,fileIds:s=[]},n){if(r==null||r.length==0)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");let o=n?.maxConcurrency??5,i=Math.min(o,r.length),a=this._client,c=r.values(),u=[...s];async function f(g){for(let A of g){let I=await a.files.create({file:A,purpose:"assistants"},n);u.push(I.id)}}let h=Array(i).fill(c).map(f);return await va(h),await this.createAndPoll(e,{file_ids:u})}};var Qr=class extends p{create(e,r,s){return this._client.post(l`/vector_stores/${e}/files`,{body:r,...s,headers:w([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}retrieve(e,r,s){let{vector_store_id:n}=r;return this._client.get(l`/vector_stores/${n}/files/${e}`,{...s,headers:w([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}update(e,r,s){let{vector_store_id:n,...o}=r;return this._client.post(l`/vector_stores/${n}/files/${e}`,{body:o,...s,headers:w([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}list(e,r={},s){return this._client.getAPIList(l`/vector_stores/${e}/files`,C,{query:r,...s,headers:w([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}delete(e,r,s){let{vector_store_id:n}=r;return this._client.delete(l`/vector_stores/${n}/files/${e}`,{...s,headers:w([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,r,s){let n=await this.create(e,r,s);return await this.poll(e,n.id,s)}async poll(e,r,s){let n=w([s?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":s?.pollIntervalMs?.toString()??void 0}]);for(;;){let o=await this.retrieve(r,{vector_store_id:e},{...s,headers:n}).withResponse(),i=o.data;switch(i.status){case"in_progress":let a=5e3;if(s?.pollIntervalMs)a=s.pollIntervalMs;else{let c=o.response.headers.get("openai-poll-after-ms");if(c){let u=parseInt(c);isNaN(u)||(a=u)}}await be(a);break;case"failed":case"completed":return i}}}async upload(e,r,s){let n=await this._client.files.create({file:r,purpose:"assistants"},s);return this.create(e,{file_id:n.id},s)}async uploadAndPoll(e,r,s){let n=await this.upload(e,r,s);return await this.poll(e,n.id,s)}content(e,r,s){let{vector_store_id:n}=r;return this._client.getAPIList(l`/vector_stores/${n}/files/${e}/content`,Q,{...s,headers:w([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}};var Me=class extends p{constructor(){super(...arguments),this.files=new Qr(this._client),this.fileBatches=new Yr(this._client)}create(e,r){return this._client.post("/vector_stores",{body:e,...r,headers:w([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(l`/vector_stores/${e}`,{...r,headers:w([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}update(e,r,s){return this._client.post(l`/vector_stores/${e}`,{body:r,...s,headers:w([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/vector_stores",C,{query:e,...r,headers:w([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(l`/vector_stores/${e}`,{...r,headers:w([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}search(e,r,s){return this._client.getAPIList(l`/vector_stores/${e}/search`,Q,{body:r,method:"post",...s,headers:w([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}};Me.Files=Qr;Me.FileBatches=Yr;var Rt=class extends p{create(e,r){return this._client.post("/videos",ee({body:e,...r,__security:{bearerAuth:!0}},this._client))}retrieve(e,r){return this._client.get(l`/videos/${e}`,{...r,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/videos",$,{query:e,...r,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(l`/videos/${e}`,{...r,__security:{bearerAuth:!0}})}createCharacter(e,r){return this._client.post("/videos/characters",ee({body:e,...r,__security:{bearerAuth:!0}},this._client))}downloadContent(e,r={},s){return this._client.get(l`/videos/${e}/content`,{query:r,...s,headers:w([{Accept:"application/binary"},s?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}edit(e,r){return this._client.post("/videos/edits",ee({body:e,...r,__security:{bearerAuth:!0}},this._client))}extend(e,r){return this._client.post("/videos/extensions",ee({body:e,...r,__security:{bearerAuth:!0}},this._client))}getCharacter(e,r){return this._client.get(l`/videos/characters/${e}`,{...r,__security:{bearerAuth:!0}})}remix(e,r,s){return this._client.post(l`/videos/${e}/remix`,Fe({body:r,...s,__security:{bearerAuth:!0}},this._client))}};var es,Ta,bn,Et=class extends p{constructor(){super(...arguments),es.add(this)}async unwrap(e,r,s=this._client.webhookSecret,n=300){return await this.verifySignature(e,r,s,n),JSON.parse(e)}async verifySignature(e,r,s=this._client.webhookSecret,n=300){if(typeof crypto>"u"||typeof crypto.subtle.importKey!="function"||typeof crypto.subtle.verify!="function")throw new Error("Webhook signature verification is only supported when the `crypto` global is defined");d(this,es,"m",Ta).call(this,s);let o=w([r]).values,i=d(this,es,"m",bn).call(this,o,"webhook-signature"),a=d(this,es,"m",bn).call(this,o,"webhook-timestamp"),c=d(this,es,"m",bn).call(this,o,"webhook-id"),u=parseInt(a,10);if(isNaN(u))throw new Ie("Invalid webhook timestamp format");let f=Math.floor(Date.now()/1e3);if(f-u>n)throw new Ie("Webhook timestamp is too old");if(u>f+n)throw new Ie("Webhook timestamp is too new");let h=i.split(" ").map(b=>b.startsWith("v1,")?b.substring(3):b),g=s.startsWith("whsec_")?Buffer.from(s.replace("whsec_",""),"base64"):Buffer.from(s,"utf-8"),A=c?`${c}.${a}.${e}`:`${a}.${e}`,I=await crypto.subtle.importKey("raw",g,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(let b of h)try{let _=Buffer.from(b,"base64");if(await crypto.subtle.verify("HMAC",I,_,new TextEncoder().encode(A)))return}catch{continue}throw new Ie("The given webhook signature does not match the expected signature")}};es=new WeakSet,Ta=function(e){if(typeof e!="string"||e.length===0)throw new Error("The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET, on the client class, OpenAI({ webhookSecret: '123' }), or passed to this function")},bn=function(e,r){if(!e)throw new Error("Headers are required");let s=e.get(r);if(s==null)throw new Error(`Missing required header: ${r}`);return s};var Ra=Symbol.for("openai.node.providerDefinitions.v1"),Ea=globalThis,Sa=Ea[Ra],$a=Sa??new WeakMap;Sa||Object.defineProperty(Ea,Ra,{value:$a});function Ma(t){let e=$a.get(t);if(!e)throw new Error("Invalid provider. Providers must be created with createProvider().");return e.configure()}var Co,Ro,Rs,Na,ip="workload-identity-auth",v=class{constructor(e={}){Co.add(this),Rs.set(this,void 0),this.completions=new gt(this),this.chat=new We(this),this.embeddings=new At(this),this.files=new bt(this),this.images=new Ot(this),this.audio=new Pe(this),this.moderations=new vt(this),this.models=new kt(this),this.fineTuning=new he(this),this.graders=new et(this),this.vectorStores=new Me(this),this.webhooks=new Et(this),this.beta=new fe(this),this.batches=new mt(this),this.uploads=new tt(this),this.admin=new Ze(this),this.responses=new ke(this),this.realtime=new Se(this),this.conversations=new Ye(this),this.evals=new Qe(this),this.containers=new Xe(this),this.skills=new $e(this),this.videos=new Rt(this);let r=e.provider;if(r){let b=["apiKey","adminAPIKey","workloadIdentity","baseURL"].filter(_=>e[_]!=null);if(b.length)throw new P(`The \`provider\` option cannot be used with ${b.map(_=>`\`${_}\``).join(", ")}. Configure authentication and the base URL through the provider instead.`)}let{baseURL:s=r?null:me("OPENAI_BASE_URL"),apiKey:n=r?null:me("OPENAI_API_KEY")??null,adminAPIKey:o=r?null:me("OPENAI_ADMIN_KEY")??null,organization:i=r?null:me("OPENAI_ORG_ID")??null,project:a=r?null:me("OPENAI_PROJECT_ID")??null,webhookSecret:c=me("OPENAI_WEBHOOK_SECRET")??null,workloadIdentity:u,...f}=e,h=r?Ma(r):void 0,g={apiKey:n,adminAPIKey:o,organization:i,project:a,webhookSecret:c,workloadIdentity:u,provider:r,...f,baseURL:h?.baseURL??(s||"https://api.openai.com/v1")};if(n&&u)throw new P("The `apiKey` and `workloadIdentity` options are mutually exclusive");if(!h&&!n&&!o&&!u)throw new P("Missing credentials. Please pass an `apiKey`, `workloadIdentity`, `adminAPIKey`, or set the `OPENAI_API_KEY` or `OPENAI_ADMIN_KEY` environment variable.");if(!g.dangerouslyAllowBrowser&&Ci())throw new P(`It looks like you're running in a browser-like environment.
18
+ ${dn(t)}`);return{...L,id:j,type:z,function:{...q,name:F,arguments:X}}})}}:{...A,message:{...m,content:I,role:y,refusal:u.refusal??null},finish_reason:f,index:h,logprobs:g}}),created:n,model:o,object:"chat.completion",...i?{system_fingerprint:i}:{}};return na(c,e)}function dn(t){return JSON.stringify(t)}var Os=class t extends ut{static fromReadableStream(e){let r=new t(null);return r._run(()=>r._fromReadableStream(e)),r}static runTools(e,r,s){let n=new t(r),o={...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"runTools"}};return n._run(()=>n._runTools(e,r,n,o)),n}};var Re=class extends p{constructor(){super(...arguments),this.messages=new it(this._client)}create(e,r){return this._client.post("/chat/completions",{body:e,...r,stream:e.stream??!1,__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(l`/chat/completions/${e}`,{...r,__security:{bearerAuth:!0}})}update(e,r,s){return this._client.post(l`/chat/completions/${e}`,{body:r,...s,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/chat/completions",C,{query:e,...r,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(l`/chat/completions/${e}`,{...r,__security:{bearerAuth:!0}})}parse(e,r){return aa(e.tools),this._client.chat.completions.create(e,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(s=>As(s,e))}runTools(e,r){return e.stream?Os.runTools(this._client,e,r):Ps.runTools(this._client,e,r)}stream(e,r){return ut.createChatCompletion(this._client,e,r)}};Re.Messages=it;var We=class extends p{constructor(){super(...arguments),this.completions=new Re(this._client)}};We.Completions=Re;var sr=class extends p{create(e,r){return this._client.post("/organization/admin_api_keys",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r){return this._client.get(l`/organization/admin_api_keys/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/admin_api_keys",C,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(l`/organization/admin_api_keys/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var nr=class extends p{list(e={},r){return this._client.getAPIList("/organization/audit_logs",$,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}};var or=class extends p{create(e,r){return this._client.post("/organization/certificates",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r={},s){return this._client.get(l`/organization/certificates/${e}`,{query:r,...s,__security:{adminAPIKeyAuth:!0}})}update(e,r,s){return this._client.post(l`/organization/certificates/${e}`,{body:r,...s,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/certificates",$,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(l`/organization/certificates/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}activate(e,r){return this._client.getAPIList("/organization/certificates/activate",Q,{body:e,method:"post",...r,__security:{adminAPIKeyAuth:!0}})}deactivate(e,r){return this._client.getAPIList("/organization/certificates/deactivate",Q,{body:e,method:"post",...r,__security:{adminAPIKeyAuth:!0}})}};var ir=class extends p{retrieve(e){return this._client.get("/organization/data_retention",{...e,__security:{adminAPIKeyAuth:!0}})}update(e,r){return this._client.post("/organization/data_retention",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}};var ar=class extends p{create(e,r){return this._client.post("/organization/invites",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r){return this._client.get(l`/organization/invites/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/invites",$,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(l`/organization/invites/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var ur=class extends p{create(e,r){return this._client.post("/organization/roles",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r){return this._client.get(l`/organization/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,s){return this._client.post(l`/organization/roles/${e}`,{body:r,...s,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/roles",B,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(l`/organization/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var lr=class extends p{create(e,r){return this._client.post("/organization/spend_alerts",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r){return this._client.get(l`/organization/spend_alerts/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,s){return this._client.post(l`/organization/spend_alerts/${e}`,{body:r,...s,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/spend_alerts",$,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(l`/organization/spend_alerts/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var cr=class extends p{audioSpeeches(e,r){return this._client.get("/organization/usage/audio_speeches",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}audioTranscriptions(e,r){return this._client.get("/organization/usage/audio_transcriptions",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}codeInterpreterSessions(e,r){return this._client.get("/organization/usage/code_interpreter_sessions",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}completions(e,r){return this._client.get("/organization/usage/completions",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}costs(e,r){return this._client.get("/organization/costs",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}embeddings(e,r){return this._client.get("/organization/usage/embeddings",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}fileSearchCalls(e,r){return this._client.get("/organization/usage/file_search_calls",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}images(e,r){return this._client.get("/organization/usage/images",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}moderations(e,r){return this._client.get("/organization/usage/moderations",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}vectorStores(e,r){return this._client.get("/organization/usage/vector_stores",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}webSearchCalls(e,r){return this._client.get("/organization/usage/web_search_calls",{query:e,...r,__security:{adminAPIKeyAuth:!0}})}};var pr=class extends p{create(e,r,s){return this._client.post(l`/organization/groups/${e}/roles`,{body:r,...s,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,s){let{group_id:n}=r;return this._client.get(l`/organization/groups/${n}/roles/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}list(e,r={},s){return this._client.getAPIList(l`/organization/groups/${e}/roles`,B,{query:r,...s,__security:{adminAPIKeyAuth:!0}})}delete(e,r,s){let{group_id:n}=r;return this._client.delete(l`/organization/groups/${n}/roles/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}};var mr=class extends p{create(e,r,s){return this._client.post(l`/organization/groups/${e}/users`,{body:r,...s,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,s){let{group_id:n}=r;return this._client.get(l`/organization/groups/${n}/users/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}list(e,r={},s){return this._client.getAPIList(l`/organization/groups/${e}/users`,B,{query:r,...s,__security:{adminAPIKeyAuth:!0}})}delete(e,r,s){let{group_id:n}=r;return this._client.delete(l`/organization/groups/${n}/users/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}};var He=class extends p{constructor(){super(...arguments),this.users=new mr(this._client),this.roles=new pr(this._client)}create(e,r){return this._client.post("/organization/groups",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r){return this._client.get(l`/organization/groups/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,s){return this._client.post(l`/organization/groups/${e}`,{body:r,...s,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/groups",B,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(l`/organization/groups/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};He.Users=mr;He.Roles=pr;var dr=class extends p{retrieve(e,r,s){let{project_id:n}=r;return this._client.get(l`/organization/projects/${n}/api_keys/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}list(e,r={},s){return this._client.getAPIList(l`/organization/projects/${e}/api_keys`,$,{query:r,...s,__security:{adminAPIKeyAuth:!0}})}delete(e,r,s){let{project_id:n}=r;return this._client.delete(l`/organization/projects/${n}/api_keys/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}};var fr=class extends p{list(e,r={},s){return this._client.getAPIList(l`/organization/projects/${e}/certificates`,$,{query:r,...s,__security:{adminAPIKeyAuth:!0}})}activate(e,r,s){return this._client.getAPIList(l`/organization/projects/${e}/certificates/activate`,Q,{body:r,method:"post",...s,__security:{adminAPIKeyAuth:!0}})}deactivate(e,r,s){return this._client.getAPIList(l`/organization/projects/${e}/certificates/deactivate`,Q,{body:r,method:"post",...s,__security:{adminAPIKeyAuth:!0}})}};var hr=class extends p{retrieve(e,r){return this._client.get(l`/organization/projects/${e}/data_retention`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,s){return this._client.post(l`/organization/projects/${e}/data_retention`,{body:r,...s,__security:{adminAPIKeyAuth:!0}})}};var _r=class extends p{retrieve(e,r){return this._client.get(l`/organization/projects/${e}/hosted_tool_permissions`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,s){return this._client.post(l`/organization/projects/${e}/hosted_tool_permissions`,{body:r,...s,__security:{adminAPIKeyAuth:!0}})}};var gr=class extends p{retrieve(e,r){return this._client.get(l`/organization/projects/${e}/model_permissions`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,s){return this._client.post(l`/organization/projects/${e}/model_permissions`,{body:r,...s,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(l`/organization/projects/${e}/model_permissions`,{...r,__security:{adminAPIKeyAuth:!0}})}};var yr=class extends p{listRateLimits(e,r={},s){return this._client.getAPIList(l`/organization/projects/${e}/rate_limits`,$,{query:r,...s,__security:{adminAPIKeyAuth:!0}})}updateRateLimit(e,r,s){let{project_id:n,...o}=r;return this._client.post(l`/organization/projects/${n}/rate_limits/${e}`,{body:o,...s,__security:{adminAPIKeyAuth:!0}})}};var Ar=class extends p{create(e,r,s){return this._client.post(l`/projects/${e}/roles`,{body:r,...s,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,s){let{project_id:n}=r;return this._client.get(l`/projects/${n}/roles/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}update(e,r,s){let{project_id:n,...o}=r;return this._client.post(l`/projects/${n}/roles/${e}`,{body:o,...s,__security:{adminAPIKeyAuth:!0}})}list(e,r={},s){return this._client.getAPIList(l`/projects/${e}/roles`,B,{query:r,...s,__security:{adminAPIKeyAuth:!0}})}delete(e,r,s){let{project_id:n}=r;return this._client.delete(l`/projects/${n}/roles/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}};var Ir=class extends p{create(e,r,s){return this._client.post(l`/organization/projects/${e}/service_accounts`,{body:r,...s,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,s){let{project_id:n}=r;return this._client.get(l`/organization/projects/${n}/service_accounts/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}update(e,r,s){let{project_id:n,...o}=r;return this._client.post(l`/organization/projects/${n}/service_accounts/${e}`,{body:o,...s,__security:{adminAPIKeyAuth:!0}})}list(e,r={},s){return this._client.getAPIList(l`/organization/projects/${e}/service_accounts`,$,{query:r,...s,__security:{adminAPIKeyAuth:!0}})}delete(e,r,s){let{project_id:n}=r;return this._client.delete(l`/organization/projects/${n}/service_accounts/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}};var br=class extends p{create(e,r,s){return this._client.post(l`/organization/projects/${e}/spend_alerts`,{body:r,...s,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,s){let{project_id:n}=r;return this._client.get(l`/organization/projects/${n}/spend_alerts/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}update(e,r,s){let{project_id:n,...o}=r;return this._client.post(l`/organization/projects/${n}/spend_alerts/${e}`,{body:o,...s,__security:{adminAPIKeyAuth:!0}})}list(e,r={},s){return this._client.getAPIList(l`/organization/projects/${e}/spend_alerts`,$,{query:r,...s,__security:{adminAPIKeyAuth:!0}})}delete(e,r,s){let{project_id:n}=r;return this._client.delete(l`/organization/projects/${n}/spend_alerts/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}};var xr=class extends p{create(e,r,s){let{project_id:n,...o}=r;return this._client.post(l`/projects/${n}/groups/${e}/roles`,{body:o,...s,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,s){let{project_id:n,group_id:o}=r;return this._client.get(l`/projects/${n}/groups/${o}/roles/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}list(e,r,s){let{project_id:n,...o}=r;return this._client.getAPIList(l`/projects/${n}/groups/${e}/roles`,B,{query:o,...s,__security:{adminAPIKeyAuth:!0}})}delete(e,r,s){let{project_id:n,group_id:o}=r;return this._client.delete(l`/projects/${n}/groups/${o}/roles/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}};var lt=class extends p{constructor(){super(...arguments),this.roles=new xr(this._client)}create(e,r,s){return this._client.post(l`/organization/projects/${e}/groups`,{body:r,...s,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,s){let{project_id:n,...o}=r;return this._client.get(l`/organization/projects/${n}/groups/${e}`,{query:o,...s,__security:{adminAPIKeyAuth:!0}})}list(e,r={},s){return this._client.getAPIList(l`/organization/projects/${e}/groups`,B,{query:r,...s,__security:{adminAPIKeyAuth:!0}})}delete(e,r,s){let{project_id:n}=r;return this._client.delete(l`/organization/projects/${n}/groups/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}};lt.Roles=xr;var wr=class extends p{create(e,r,s){let{project_id:n,...o}=r;return this._client.post(l`/projects/${n}/users/${e}/roles`,{body:o,...s,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,s){let{project_id:n,user_id:o}=r;return this._client.get(l`/projects/${n}/users/${o}/roles/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}list(e,r,s){let{project_id:n,...o}=r;return this._client.getAPIList(l`/projects/${n}/users/${e}/roles`,B,{query:o,...s,__security:{adminAPIKeyAuth:!0}})}delete(e,r,s){let{project_id:n,user_id:o}=r;return this._client.delete(l`/projects/${n}/users/${o}/roles/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}};var ct=class extends p{constructor(){super(...arguments),this.roles=new wr(this._client)}create(e,r,s){return this._client.post(l`/organization/projects/${e}/users`,{body:r,...s,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,s){let{project_id:n}=r;return this._client.get(l`/organization/projects/${n}/users/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}update(e,r,s){let{project_id:n,...o}=r;return this._client.post(l`/organization/projects/${n}/users/${e}`,{body:o,...s,__security:{adminAPIKeyAuth:!0}})}list(e,r={},s){return this._client.getAPIList(l`/organization/projects/${e}/users`,$,{query:r,...s,__security:{adminAPIKeyAuth:!0}})}delete(e,r,s){let{project_id:n}=r;return this._client.delete(l`/organization/projects/${n}/users/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}};ct.Roles=wr;var V=class extends p{constructor(){super(...arguments),this.users=new ct(this._client),this.serviceAccounts=new Ir(this._client),this.apiKeys=new dr(this._client),this.rateLimits=new yr(this._client),this.modelPermissions=new gr(this._client),this.hostedToolPermissions=new _r(this._client),this.groups=new lt(this._client),this.roles=new Ar(this._client),this.dataRetention=new hr(this._client),this.spendAlerts=new br(this._client),this.certificates=new fr(this._client)}create(e,r){return this._client.post("/organization/projects",{body:e,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r){return this._client.get(l`/organization/projects/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,s){return this._client.post(l`/organization/projects/${e}`,{body:r,...s,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/projects",$,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}archive(e,r){return this._client.post(l`/organization/projects/${e}/archive`,{...r,__security:{adminAPIKeyAuth:!0}})}};V.Users=ct;V.ServiceAccounts=Ir;V.APIKeys=dr;V.RateLimits=yr;V.ModelPermissions=gr;V.HostedToolPermissions=_r;V.Groups=lt;V.Roles=Ar;V.DataRetention=hr;V.SpendAlerts=br;V.Certificates=fr;var Pr=class extends p{create(e,r,s){return this._client.post(l`/organization/users/${e}/roles`,{body:r,...s,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r,s){let{user_id:n}=r;return this._client.get(l`/organization/users/${n}/roles/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}list(e,r={},s){return this._client.getAPIList(l`/organization/users/${e}/roles`,B,{query:r,...s,__security:{adminAPIKeyAuth:!0}})}delete(e,r,s){let{user_id:n}=r;return this._client.delete(l`/organization/users/${n}/roles/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}};var pt=class extends p{constructor(){super(...arguments),this.roles=new Pr(this._client)}retrieve(e,r){return this._client.get(l`/organization/users/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,r,s){return this._client.post(l`/organization/users/${e}`,{body:r,...s,__security:{adminAPIKeyAuth:!0}})}list(e={},r){return this._client.getAPIList("/organization/users",$,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(l`/organization/users/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};pt.Roles=Pr;var J=class extends p{constructor(){super(...arguments),this.auditLogs=new nr(this._client),this.adminAPIKeys=new sr(this._client),this.usage=new cr(this._client),this.invites=new ar(this._client),this.users=new pt(this._client),this.groups=new He(this._client),this.roles=new ur(this._client),this.dataRetention=new ir(this._client),this.spendAlerts=new lr(this._client),this.certificates=new or(this._client),this.projects=new V(this._client)}};J.AuditLogs=nr;J.AdminAPIKeys=sr;J.Usage=cr;J.Invites=ar;J.Users=pt;J.Groups=He;J.Roles=ur;J.DataRetention=ir;J.SpendAlerts=lr;J.Certificates=or;J.Projects=V;var Ze=class extends p{constructor(){super(...arguments),this.organization=new J(this._client)}};Ze.Organization=J;var fa=Symbol("brand.privateNullableHeaders");function*hc(t){if(!t)return;if(fa in t){let{values:s,nulls:n}=t;yield*s.entries();for(let o of n)yield[o,null];return}let e=!1,r;t instanceof Headers?r=t.entries():Zn(t)?r=t:(e=!0,r=Object.entries(t??{}));for(let s of r){let n=s[0];if(typeof n!="string")throw new TypeError("expected header name to be a string");let o=Zn(s[1])?s[1]:[s[1]],i=!1;for(let a of o)a!==void 0&&(e&&!i&&(i=!0,yield[n,null]),yield[n,a])}}var w=t=>{let e=new Headers,r=new Set;for(let s of t){let n=new Set;for(let[o,i]of hc(s)){let a=o.toLowerCase();n.has(a)||(e.delete(o),n.add(a)),i===null?(e.delete(o),r.add(a)):(e.append(o,i),r.delete(a))}}return{[fa]:!0,values:e,nulls:r}};var Or=class extends p{create(e,r){return this._client.post("/audio/speech",{body:e,...r,headers:w([{Accept:"application/octet-stream"},r?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var kr=class extends p{create(e,r){return this._client.post("/audio/transcriptions",ee({body:e,...r,stream:e.stream??!1,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}};var vr=class extends p{create(e,r){return this._client.post("/audio/translations",ee({body:e,...r,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}};var we=class extends p{constructor(){super(...arguments),this.transcriptions=new kr(this._client),this.translations=new vr(this._client),this.speech=new Or(this._client)}};we.Transcriptions=kr;we.Translations=vr;we.Speech=Or;var mt=class extends p{create(e,r){return this._client.post("/batches",{body:e,...r,__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(l`/batches/${e}`,{...r,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/batches",C,{query:e,...r,__security:{bearerAuth:!0}})}cancel(e,r){return this._client.post(l`/batches/${e}/cancel`,{...r,__security:{bearerAuth:!0}})}};var Tr=class extends p{create(e,r){return this._client.post("/assistants",{body:e,...r,headers:w([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(l`/assistants/${e}`,{...r,headers:w([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}update(e,r,s){return this._client.post(l`/assistants/${e}`,{body:r,...s,headers:w([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/assistants",C,{query:e,...r,headers:w([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(l`/assistants/${e}`,{...r,headers:w([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}};var Cr=class extends p{create(e,r){return this._client.post("/realtime/sessions",{body:e,...r,headers:w([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}};var Rr=class extends p{create(e,r){return this._client.post("/realtime/transcription_sessions",{body:e,...r,headers:w([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}};var Ve=class extends p{constructor(){super(...arguments),this.sessions=new Cr(this._client),this.transcriptionSessions=new Rr(this._client)}};Ve.Sessions=Cr;Ve.TranscriptionSessions=Rr;var Er=class extends p{create(e,r){return this._client.post("/chatkit/sessions",{body:e,...r,headers:w([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers]),__security:{bearerAuth:!0}})}cancel(e,r){return this._client.post(l`/chatkit/sessions/${e}/cancel`,{...r,headers:w([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers]),__security:{bearerAuth:!0}})}};var Sr=class extends p{retrieve(e,r){return this._client.get(l`/chatkit/threads/${e}`,{...r,headers:w([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers]),__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/chatkit/threads",$,{query:e,...r,headers:w([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers]),__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(l`/chatkit/threads/${e}`,{...r,headers:w([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers]),__security:{bearerAuth:!0}})}listItems(e,r={},s){return this._client.getAPIList(l`/chatkit/threads/${e}/items`,$,{query:r,...s,headers:w([{"OpenAI-Beta":"chatkit_beta=v1"},s?.headers]),__security:{bearerAuth:!0}})}};var Je=class extends p{constructor(){super(...arguments),this.sessions=new Er(this._client),this.threads=new Sr(this._client)}};Je.Sessions=Er;Je.Threads=Sr;var $r=class extends p{create(e,r,s){return this._client.post(l`/threads/${e}/messages`,{body:r,...s,headers:w([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}retrieve(e,r,s){let{thread_id:n}=r;return this._client.get(l`/threads/${n}/messages/${e}`,{...s,headers:w([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}update(e,r,s){let{thread_id:n,...o}=r;return this._client.post(l`/threads/${n}/messages/${e}`,{body:o,...s,headers:w([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}list(e,r={},s){return this._client.getAPIList(l`/threads/${e}/messages`,C,{query:r,...s,headers:w([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}delete(e,r,s){let{thread_id:n}=r;return this._client.delete(l`/threads/${n}/messages/${e}`,{...s,headers:w([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}};var Mr=class extends p{retrieve(e,r,s){let{thread_id:n,run_id:o,...i}=r;return this._client.get(l`/threads/${n}/runs/${o}/steps/${e}`,{query:i,...s,headers:w([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}list(e,r,s){let{thread_id:n,...o}=r;return this._client.getAPIList(l`/threads/${n}/runs/${e}/steps`,C,{query:o,...s,headers:w([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}};var ha=t=>{if(typeof Buffer<"u"){let e=Buffer.from(t,"base64");return Array.from(new Float32Array(e.buffer,e.byteOffset,e.length/Float32Array.BYTES_PER_ELEMENT))}else{let e=atob(t),r=e.length,s=new Uint8Array(r);for(let n=0;n<r;n++)s[n]=e.charCodeAt(n);return Array.from(new Float32Array(s.buffer))}};var pe=t=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[t]?.trim()||void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(t)?.trim()||void 0};var G,ft,vo,Pe,fn,me,ht,Nr,dt,gn,ne,hn,_n,Ts,ks,vs,_a,ga,ya,Aa,Ia,ba,xa,Ee=class extends Be{constructor(){super(...arguments),G.add(this),vo.set(this,[]),Pe.set(this,{}),fn.set(this,{}),me.set(this,void 0),ht.set(this,void 0),Nr.set(this,void 0),dt.set(this,void 0),gn.set(this,void 0),ne.set(this,void 0),hn.set(this,void 0),_n.set(this,void 0),Ts.set(this,void 0)}[(vo=new WeakMap,Pe=new WeakMap,fn=new WeakMap,me=new WeakMap,ht=new WeakMap,Nr=new WeakMap,dt=new WeakMap,gn=new WeakMap,ne=new WeakMap,hn=new WeakMap,_n=new WeakMap,Ts=new WeakMap,G=new WeakSet,Symbol.asyncIterator)](){let e=[],r=[],s=!1;return this.on("event",n=>{let o=r.shift();o?o.resolve(n):e.push(n)}),this.on("end",()=>{s=!0;for(let n of r)n.resolve(void 0);r.length=0}),this.on("abort",n=>{s=!0;for(let o of r)o.reject(n);r.length=0}),this.on("error",n=>{s=!0;for(let o of r)o.reject(n);r.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:s?{value:void 0,done:!0}:new Promise((o,i)=>r.push({resolve:o,reject:i})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){let r=new ft;return r._run(()=>r._fromReadableStream(e)),r}async _fromReadableStream(e,r){this._listenForAbort(r?.signal),this._connected();let s=xe.fromReadableStream(e,this.controller);for await(let n of s)d(this,G,"m",ks).call(this,n);if(s.controller.signal?.aborted)throw new D;return this._addRun(d(this,G,"m",vs).call(this))}toReadableStream(){return new xe(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,r,s,n){let o=new ft;return o._run(()=>o._runToolAssistantStream(e,r,s,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),o}async _createToolAssistantStream(e,r,s,n){this._listenForAbort(n?.signal);let o={...s,stream:!0},i=await e.submitToolOutputs(r,o,{...n,signal:this.controller.signal});this._connected();for await(let a of i)d(this,G,"m",ks).call(this,a);if(i.controller.signal?.aborted)throw new D;return this._addRun(d(this,G,"m",vs).call(this))}static createThreadAssistantStream(e,r,s){let n=new ft;return n._run(()=>n._threadAssistantStream(e,r,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),n}static createAssistantStream(e,r,s,n){let o=new ft;return o._run(()=>o._runAssistantStream(e,r,s,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),o}currentEvent(){return d(this,hn,"f")}currentRun(){return d(this,_n,"f")}currentMessageSnapshot(){return d(this,me,"f")}currentRunStepSnapshot(){return d(this,Ts,"f")}async finalRunSteps(){return await this.done(),Object.values(d(this,Pe,"f"))}async finalMessages(){return await this.done(),Object.values(d(this,fn,"f"))}async finalRun(){if(await this.done(),!d(this,ht,"f"))throw Error("Final run was not received.");return d(this,ht,"f")}async _createThreadAssistantStream(e,r,s){this._listenForAbort(s?.signal);let n={...r,stream:!0},o=await e.createAndRun(n,{...s,signal:this.controller.signal});this._connected();for await(let i of o)d(this,G,"m",ks).call(this,i);if(o.controller.signal?.aborted)throw new D;return this._addRun(d(this,G,"m",vs).call(this))}async _createAssistantStream(e,r,s,n){this._listenForAbort(n?.signal);let o={...s,stream:!0},i=await e.create(r,o,{...n,signal:this.controller.signal});this._connected();for await(let a of i)d(this,G,"m",ks).call(this,a);if(i.controller.signal?.aborted)throw new D;return this._addRun(d(this,G,"m",vs).call(this))}static accumulateDelta(e,r){for(let[s,n]of Object.entries(r)){if(!e.hasOwnProperty(s)){e[s]=n;continue}let o=e[s];if(o==null){e[s]=n;continue}if(s==="index"||s==="type"){e[s]=n;continue}if(typeof o=="string"&&typeof n=="string")o+=n;else if(typeof o=="number"&&typeof n=="number")o+=n;else if(cs(o)&&cs(n))o=this.accumulateDelta(o,n);else if(Array.isArray(o)&&Array.isArray(n)){if(o.every(i=>typeof i=="string"||typeof i=="number")){o.push(...n);continue}for(let i of n){if(!cs(i))throw new Error(`Expected array delta entry to be an object but got: ${i}`);let a=i.index;if(a==null)throw console.error(i),new Error("Expected array delta entry to have an `index` property");if(typeof a!="number")throw new Error(`Expected array delta entry \`index\` property to be a number but got ${a}`);let c=o[a];c==null?o.push(i):o[a]=this.accumulateDelta(c,i)}continue}else throw Error(`Unhandled record type: ${s}, deltaValue: ${n}, accValue: ${o}`);e[s]=o}return e}_addRun(e){return e}async _threadAssistantStream(e,r,s){return await this._createThreadAssistantStream(r,e,s)}async _runAssistantStream(e,r,s,n){return await this._createAssistantStream(r,e,s,n)}async _runToolAssistantStream(e,r,s,n){return await this._createToolAssistantStream(r,e,s,n)}};ft=Ee,ks=function(e){if(!this.ended)switch(k(this,hn,e,"f"),d(this,G,"m",ya).call(this,e),e.event){case"thread.created":break;case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":case"thread.run.requires_action":case"thread.run.completed":case"thread.run.incomplete":case"thread.run.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":d(this,G,"m",xa).call(this,e);break;case"thread.run.step.created":case"thread.run.step.in_progress":case"thread.run.step.delta":case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":d(this,G,"m",ga).call(this,e);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":d(this,G,"m",_a).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier");default:}},vs=function(){if(this.ended)throw new P("stream has ended, this shouldn't happen");if(!d(this,ht,"f"))throw Error("Final run has not been received");return d(this,ht,"f")},_a=function(e){let[r,s]=d(this,G,"m",Ia).call(this,e,d(this,me,"f"));k(this,me,r,"f"),d(this,fn,"f")[r.id]=r;for(let n of s){let o=r.content[n.index];o?.type=="text"&&this._emit("textCreated",o.text)}switch(e.event){case"thread.message.created":this._emit("messageCreated",e.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",e.data.delta,r),e.data.delta.content)for(let n of e.data.delta.content){if(n.type=="text"&&n.text){let o=n.text,i=r.content[n.index];if(i&&i.type=="text")this._emit("textDelta",o,i.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(n.index!=d(this,Nr,"f")){if(d(this,dt,"f"))switch(d(this,dt,"f").type){case"text":this._emit("textDone",d(this,dt,"f").text,d(this,me,"f"));break;case"image_file":this._emit("imageFileDone",d(this,dt,"f").image_file,d(this,me,"f"));break}k(this,Nr,n.index,"f")}k(this,dt,r.content[n.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(d(this,Nr,"f")!==void 0){let n=e.data.content[d(this,Nr,"f")];if(n)switch(n.type){case"image_file":this._emit("imageFileDone",n.image_file,d(this,me,"f"));break;case"text":this._emit("textDone",n.text,d(this,me,"f"));break}}d(this,me,"f")&&this._emit("messageDone",e.data),k(this,me,void 0,"f")}},ga=function(e){let r=d(this,G,"m",Aa).call(this,e);switch(k(this,Ts,r,"f"),e.event){case"thread.run.step.created":this._emit("runStepCreated",e.data);break;case"thread.run.step.delta":let s=e.data.delta;if(s.step_details&&s.step_details.type=="tool_calls"&&s.step_details.tool_calls&&r.step_details.type=="tool_calls")for(let o of s.step_details.tool_calls)o.index==d(this,gn,"f")?this._emit("toolCallDelta",o,r.step_details.tool_calls[o.index]):(d(this,ne,"f")&&this._emit("toolCallDone",d(this,ne,"f")),k(this,gn,o.index,"f"),k(this,ne,r.step_details.tool_calls[o.index],"f"),d(this,ne,"f")&&this._emit("toolCallCreated",d(this,ne,"f")));this._emit("runStepDelta",e.data.delta,r);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":k(this,Ts,void 0,"f"),e.data.step_details.type=="tool_calls"&&d(this,ne,"f")&&(this._emit("toolCallDone",d(this,ne,"f")),k(this,ne,void 0,"f")),this._emit("runStepDone",e.data,r);break;case"thread.run.step.in_progress":break}},ya=function(e){d(this,vo,"f").push(e),this._emit("event",e)},Aa=function(e){switch(e.event){case"thread.run.step.created":return d(this,Pe,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let r=d(this,Pe,"f")[e.data.id];if(!r)throw Error("Received a RunStepDelta before creation of a snapshot");let s=e.data;if(s.delta){let n=ft.accumulateDelta(r,s.delta);d(this,Pe,"f")[e.data.id]=n}return d(this,Pe,"f")[e.data.id];case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":case"thread.run.step.in_progress":d(this,Pe,"f")[e.data.id]=e.data;break}if(d(this,Pe,"f")[e.data.id])return d(this,Pe,"f")[e.data.id];throw new Error("No snapshot available")},Ia=function(e,r){let s=[];switch(e.event){case"thread.message.created":return[e.data,s];case"thread.message.delta":if(!r)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let n=e.data;if(n.delta.content)for(let o of n.delta.content)if(o.index in r.content){let i=r.content[o.index];r.content[o.index]=d(this,G,"m",ba).call(this,o,i)}else r.content[o.index]=o,s.push(o);return[r,s];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(r)return[r,s];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},ba=function(e,r){return ft.accumulateDelta(r,e)},xa=function(e){switch(k(this,_n,e.data,"f"),e.event){case"thread.run.created":break;case"thread.run.queued":break;case"thread.run.in_progress":break;case"thread.run.requires_action":case"thread.run.cancelled":case"thread.run.failed":case"thread.run.completed":case"thread.run.expired":case"thread.run.incomplete":k(this,ht,e.data,"f"),d(this,ne,"f")&&(this._emit("toolCallDone",d(this,ne,"f")),k(this,ne,void 0,"f"));break;case"thread.run.cancelling":break}};var _t=class extends p{constructor(){super(...arguments),this.steps=new Mr(this._client)}create(e,r,s){let{include:n,...o}=r;return this._client.post(l`/threads/${e}/runs`,{query:{include:n},body:o,...s,headers:w([{"OpenAI-Beta":"assistants=v2"},s?.headers]),stream:r.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}retrieve(e,r,s){let{thread_id:n}=r;return this._client.get(l`/threads/${n}/runs/${e}`,{...s,headers:w([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}update(e,r,s){let{thread_id:n,...o}=r;return this._client.post(l`/threads/${n}/runs/${e}`,{body:o,...s,headers:w([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}list(e,r={},s){return this._client.getAPIList(l`/threads/${e}/runs`,C,{query:r,...s,headers:w([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}cancel(e,r,s){let{thread_id:n}=r;return this._client.post(l`/threads/${n}/runs/${e}/cancel`,{...s,headers:w([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,r,s){let n=await this.create(e,r,s);return await this.poll(n.id,{thread_id:e},s)}createAndStream(e,r,s){return Ee.createAssistantStream(e,this._client.beta.threads.runs,r,s)}async poll(e,r,s){let n=w([s?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":s?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:o,response:i}=await this.retrieve(e,r,{...s,headers:{...s?.headers,...n}}).withResponse();switch(o.status){case"queued":case"in_progress":case"cancelling":let a=5e3;if(s?.pollIntervalMs)a=s.pollIntervalMs;else{let c=i.headers.get("openai-poll-after-ms");if(c){let u=parseInt(c);isNaN(u)||(a=u)}}await Ie(a);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return o}}}stream(e,r,s){return Ee.createAssistantStream(e,this._client.beta.threads.runs,r,s)}submitToolOutputs(e,r,s){let{thread_id:n,...o}=r;return this._client.post(l`/threads/${n}/runs/${e}/submit_tool_outputs`,{body:o,...s,headers:w([{"OpenAI-Beta":"assistants=v2"},s?.headers]),stream:r.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}async submitToolOutputsAndPoll(e,r,s){let n=await this.submitToolOutputs(e,r,s);return await this.poll(n.id,r,s)}submitToolOutputsStream(e,r,s){return Ee.createToolAssistantStream(e,this._client.beta.threads.runs,r,s)}};_t.Steps=Mr;var Ge=class extends p{constructor(){super(...arguments),this.runs=new _t(this._client),this.messages=new $r(this._client)}create(e={},r){return this._client.post("/threads",{body:e,...r,headers:w([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(l`/threads/${e}`,{...r,headers:w([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}update(e,r,s){return this._client.post(l`/threads/${e}`,{body:r,...s,headers:w([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(l`/threads/${e}`,{...r,headers:w([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}createAndRun(e,r){return this._client.post("/threads/runs",{body:e,...r,headers:w([{"OpenAI-Beta":"assistants=v2"},r?.headers]),stream:e.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}async createAndRunPoll(e,r){let s=await this.createAndRun(e,r);return await this.runs.poll(s.id,{thread_id:s.thread_id},r)}createAndRunStream(e,r){return Ee.createThreadAssistantStream(e,this._client.beta.threads,r)}};Ge.Runs=_t;Ge.Messages=$r;var de=class extends p{constructor(){super(...arguments),this.realtime=new Ve(this._client),this.chatkit=new Je(this._client),this.assistants=new Tr(this._client),this.threads=new Ge(this._client)}};de.Realtime=Ve;de.ChatKit=Je;de.Assistants=Tr;de.Threads=Ge;var gt=class extends p{create(e,r){return this._client.post("/completions",{body:e,...r,stream:e.stream??!1,__security:{bearerAuth:!0}})}};var zr=class extends p{retrieve(e,r,s){let{container_id:n}=r;return this._client.get(l`/containers/${n}/files/${e}/content`,{...s,headers:w([{Accept:"application/binary"},s?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var yt=class extends p{constructor(){super(...arguments),this.content=new zr(this._client)}create(e,r,s){return this._client.post(l`/containers/${e}/files`,Fe({body:r,...s,__security:{bearerAuth:!0}},this._client))}retrieve(e,r,s){let{container_id:n}=r;return this._client.get(l`/containers/${n}/files/${e}`,{...s,__security:{bearerAuth:!0}})}list(e,r={},s){return this._client.getAPIList(l`/containers/${e}/files`,C,{query:r,...s,__security:{bearerAuth:!0}})}delete(e,r,s){let{container_id:n}=r;return this._client.delete(l`/containers/${n}/files/${e}`,{...s,headers:w([{Accept:"*/*"},s?.headers]),__security:{bearerAuth:!0}})}};yt.Content=zr;var Xe=class extends p{constructor(){super(...arguments),this.files=new yt(this._client)}create(e,r){return this._client.post("/containers",{body:e,...r,__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(l`/containers/${e}`,{...r,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/containers",C,{query:e,...r,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(l`/containers/${e}`,{...r,headers:w([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}};Xe.Files=yt;var jr=class extends p{create(e,r,s){let{include:n,...o}=r;return this._client.post(l`/conversations/${e}/items`,{query:{include:n},body:o,...s,__security:{bearerAuth:!0}})}retrieve(e,r,s){let{conversation_id:n,...o}=r;return this._client.get(l`/conversations/${n}/items/${e}`,{query:o,...s,__security:{bearerAuth:!0}})}list(e,r={},s){return this._client.getAPIList(l`/conversations/${e}/items`,$,{query:r,...s,__security:{bearerAuth:!0}})}delete(e,r,s){let{conversation_id:n}=r;return this._client.delete(l`/conversations/${n}/items/${e}`,{...s,__security:{bearerAuth:!0}})}};var Ye=class extends p{constructor(){super(...arguments),this.items=new jr(this._client)}create(e={},r){return this._client.post("/conversations",{body:e,...r,__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(l`/conversations/${e}`,{...r,__security:{bearerAuth:!0}})}update(e,r,s){return this._client.post(l`/conversations/${e}`,{body:r,...s,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(l`/conversations/${e}`,{...r,__security:{bearerAuth:!0}})}};Ye.Items=jr;var At=class extends p{create(e,r){let s=!!e.encoding_format,n=s?e.encoding_format:"base64";s&&K(this._client).debug("embeddings/user defined encoding_format:",e.encoding_format);let o=this._client.post("/embeddings",{body:{...e,encoding_format:n},...r,__security:{bearerAuth:!0}});return s?o:(K(this._client).debug("embeddings/decoding base64 embeddings from base64"),o._thenUnwrap(i=>(i&&i.data&&i.data.forEach(a=>{let c=a.embedding;a.embedding=ha(c)}),i)))}};var Ur=class extends p{retrieve(e,r,s){let{eval_id:n,run_id:o}=r;return this._client.get(l`/evals/${n}/runs/${o}/output_items/${e}`,{...s,__security:{bearerAuth:!0}})}list(e,r,s){let{eval_id:n,...o}=r;return this._client.getAPIList(l`/evals/${n}/runs/${e}/output_items`,C,{query:o,...s,__security:{bearerAuth:!0}})}};var It=class extends p{constructor(){super(...arguments),this.outputItems=new Ur(this._client)}create(e,r,s){return this._client.post(l`/evals/${e}/runs`,{body:r,...s,__security:{bearerAuth:!0}})}retrieve(e,r,s){let{eval_id:n}=r;return this._client.get(l`/evals/${n}/runs/${e}`,{...s,__security:{bearerAuth:!0}})}list(e,r={},s){return this._client.getAPIList(l`/evals/${e}/runs`,C,{query:r,...s,__security:{bearerAuth:!0}})}delete(e,r,s){let{eval_id:n}=r;return this._client.delete(l`/evals/${n}/runs/${e}`,{...s,__security:{bearerAuth:!0}})}cancel(e,r,s){let{eval_id:n}=r;return this._client.post(l`/evals/${n}/runs/${e}`,{...s,__security:{bearerAuth:!0}})}};It.OutputItems=Ur;var Qe=class extends p{constructor(){super(...arguments),this.runs=new It(this._client)}create(e,r){return this._client.post("/evals",{body:e,...r,__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(l`/evals/${e}`,{...r,__security:{bearerAuth:!0}})}update(e,r,s){return this._client.post(l`/evals/${e}`,{body:r,...s,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/evals",C,{query:e,...r,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(l`/evals/${e}`,{...r,__security:{bearerAuth:!0}})}};Qe.Runs=It;var bt=class extends p{create(e,r){return this._client.post("/files",ee({body:e,...r,__security:{bearerAuth:!0}},this._client))}retrieve(e,r){return this._client.get(l`/files/${e}`,{...r,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/files",C,{query:e,...r,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(l`/files/${e}`,{...r,__security:{bearerAuth:!0}})}content(e,r){return this._client.get(l`/files/${e}/content`,{...r,headers:w([{Accept:"application/binary"},r?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:r=5e3,maxWait:s=1800*1e3}={}){let n=new Set(["processed","error","deleted"]),o=Date.now(),i=await this.retrieve(e);for(;!i.status||!n.has(i.status);)if(await Ie(r),i=await this.retrieve(e),Date.now()-o>s)throw new ye({message:`Giving up on waiting for file ${e} to finish processing after ${s} milliseconds.`});return i}};var Dr=class extends p{};var Lr=class extends p{run(e,r){return this._client.post("/fine_tuning/alpha/graders/run",{body:e,...r,__security:{bearerAuth:!0}})}validate(e,r){return this._client.post("/fine_tuning/alpha/graders/validate",{body:e,...r,__security:{bearerAuth:!0}})}};var xt=class extends p{constructor(){super(...arguments),this.graders=new Lr(this._client)}};xt.Graders=Lr;var Kr=class extends p{create(e,r,s){return this._client.getAPIList(l`/fine_tuning/checkpoints/${e}/permissions`,Q,{body:r,method:"post",...s,__security:{adminAPIKeyAuth:!0}})}retrieve(e,r={},s){return this._client.get(l`/fine_tuning/checkpoints/${e}/permissions`,{query:r,...s,__security:{adminAPIKeyAuth:!0}})}list(e,r={},s){return this._client.getAPIList(l`/fine_tuning/checkpoints/${e}/permissions`,$,{query:r,...s,__security:{adminAPIKeyAuth:!0}})}delete(e,r,s){let{fine_tuned_model_checkpoint:n}=r;return this._client.delete(l`/fine_tuning/checkpoints/${n}/permissions/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}};var wt=class extends p{constructor(){super(...arguments),this.permissions=new Kr(this._client)}};wt.Permissions=Kr;var Fr=class extends p{list(e,r={},s){return this._client.getAPIList(l`/fine_tuning/jobs/${e}/checkpoints`,C,{query:r,...s,__security:{bearerAuth:!0}})}};var Pt=class extends p{constructor(){super(...arguments),this.checkpoints=new Fr(this._client)}create(e,r){return this._client.post("/fine_tuning/jobs",{body:e,...r,__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(l`/fine_tuning/jobs/${e}`,{...r,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/fine_tuning/jobs",C,{query:e,...r,__security:{bearerAuth:!0}})}cancel(e,r){return this._client.post(l`/fine_tuning/jobs/${e}/cancel`,{...r,__security:{bearerAuth:!0}})}listEvents(e,r={},s){return this._client.getAPIList(l`/fine_tuning/jobs/${e}/events`,C,{query:r,...s,__security:{bearerAuth:!0}})}pause(e,r){return this._client.post(l`/fine_tuning/jobs/${e}/pause`,{...r,__security:{bearerAuth:!0}})}resume(e,r){return this._client.post(l`/fine_tuning/jobs/${e}/resume`,{...r,__security:{bearerAuth:!0}})}};Pt.Checkpoints=Fr;var fe=class extends p{constructor(){super(...arguments),this.methods=new Dr(this._client),this.jobs=new Pt(this._client),this.checkpoints=new wt(this._client),this.alpha=new xt(this._client)}};fe.Methods=Dr;fe.Jobs=Pt;fe.Checkpoints=wt;fe.Alpha=xt;var Br=class extends p{};var et=class extends p{constructor(){super(...arguments),this.graderModels=new Br(this._client)}};et.GraderModels=Br;var Ot=class extends p{createVariation(e,r){return this._client.post("/images/variations",ee({body:e,...r,__security:{bearerAuth:!0}},this._client))}edit(e,r){return this._client.post("/images/edits",ee({body:e,...r,stream:e.stream??!1,__security:{bearerAuth:!0}},this._client))}generate(e,r){return this._client.post("/images/generations",{body:e,...r,stream:e.stream??!1,__security:{bearerAuth:!0}})}};var kt=class extends p{retrieve(e,r){return this._client.get(l`/models/${e}`,{...r,__security:{bearerAuth:!0}})}list(e){return this._client.getAPIList("/models",Q,{...e,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(l`/models/${e}`,{...r,__security:{bearerAuth:!0}})}};var vt=class extends p{create(e,r){return this._client.post("/moderations",{body:e,...r,__security:{bearerAuth:!0}})}};var qr=class extends p{accept(e,r,s){return this._client.post(l`/realtime/calls/${e}/accept`,{body:r,...s,headers:w([{Accept:"*/*"},s?.headers]),__security:{bearerAuth:!0}})}hangup(e,r){return this._client.post(l`/realtime/calls/${e}/hangup`,{...r,headers:w([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}refer(e,r,s){return this._client.post(l`/realtime/calls/${e}/refer`,{body:r,...s,headers:w([{Accept:"*/*"},s?.headers]),__security:{bearerAuth:!0}})}reject(e,r={},s){return this._client.post(l`/realtime/calls/${e}/reject`,{body:r,...s,headers:w([{Accept:"*/*"},s?.headers]),__security:{bearerAuth:!0}})}};var Wr=class extends p{create(e,r){return this._client.post("/realtime/client_secrets",{body:e,...r,__security:{bearerAuth:!0}})}};var Se=class extends p{constructor(){super(...arguments),this.clientSecrets=new Wr(this._client),this.calls=new qr(this._client)}};Se.ClientSecrets=Wr;Se.Calls=qr;function wa(t,e){if(!e||!Hc(e)){let r={...t,output_parsed:null,output:t.output.map(s=>s.type==="function_call"?{...s,parsed_arguments:null}:s.type==="message"?{...s,content:s.content.map(n=>({...n,parsed:null}))}:s)};return Pa(t,r)&&oe(r),r}return To(t,e)}function To(t,e){let r=!t.status||t.status==="completed",s=t.output.map(o=>{if(o.type==="function_call")return{...o,parsed_arguments:r?Jc(e,o):null};if(o.type==="message"){let i=o.content.map(a=>a.type==="output_text"?{...a,parsed:r?Wc(e,a.text):null}:a);return{...o,content:i}}return o}),n=Object.assign({},t,{output:s});return Pa(t,n)&&oe(n),Object.defineProperty(n,"output_parsed",{enumerable:!0,get(){for(let o of n.output)if(o.type==="message"){for(let i of o.content)if(i.type==="output_text"&&i.parsed!==null)return i.parsed}return null}}),n}function Wc(t,e){return t.text?.format?.type!=="json_schema"?null:"$parseRaw"in t.text?.format?(t.text?.format).$parseRaw(e):JSON.parse(e)}function Hc(t){return!!ys(t.text?.format)}function Zc(t){return t?.$brand==="auto-parseable-tool"}function Vc(t,e){return t.find(r=>r.type==="function"&&r.name===e)}function Jc(t,e){let r=Vc(t.tools??[],e.name);return{...e,...e,parsed_arguments:Zc(r)?r.$parseRaw(e.arguments):r?.strict?JSON.parse(e.arguments):null}}function Pa(t,e){return!Object.getOwnPropertyDescriptor(t,"output_text")||e.output_text==null}function oe(t){let e=[];for(let r of t.output)if(r.type==="message")for(let s of r.content)s.type==="output_text"&&e.push(s.text);t.output_text=e.join("")}function ka(t,e){if(!e){if(t.type!=="response.created")throw new P(`When snapshot hasn't been set yet, expected 'response.created' event, got ${t.type}`);return Oa(t.response)}switch(t.type){case"response.output_item.added":{e.output.push(structuredClone(t.item)),t.item.type==="message"&&oe(e);break}case"response.output_item.done":{S(e,t.output_index),e.output[t.output_index]=structuredClone(t.item),t.item.type==="message"&&oe(e);break}case"response.content_part.added":{let r=S(e,t.output_index),s=r.type,n=t.part;s==="message"&&n.type!=="reasoning_text"?(r.content.push(structuredClone(n)),n.type==="output_text"&&oe(e)):s==="reasoning"&&n.type==="reasoning_text"&&(r.content||(r.content=[]),r.content.push(structuredClone(n)));break}case"response.content_part.done":{let r=S(e,t.output_index),s=t.part;if(r.type==="message"&&s.type!=="reasoning_text")ue(r.content,t.content_index),r.content[t.content_index]=structuredClone(s),s.type==="output_text"&&oe(e);else if(r.type==="reasoning"&&s.type==="reasoning_text"){let n=r.content;if(!n)throw new P(`missing content at index ${t.content_index}`);ue(n,t.content_index),n[t.content_index]=structuredClone(s)}break}case"response.output_text.delta":{let r=S(e,t.output_index);if(r.type==="message"){let s=ue(r.content,t.content_index);if(s.type!=="output_text")throw new P(`expected content to be 'output_text', got ${s.type}`);s.text+=t.delta,e.output_text+=t.delta}break}case"response.output_text.done":{let r=S(e,t.output_index);if(r.type==="message"){let s=ue(r.content,t.content_index);if(s.type!=="output_text")throw new P(`expected content to be 'output_text', got ${s.type}`);s.text=t.text,oe(e)}break}case"response.output_text.annotation.added":{let r=S(e,t.output_index);if(r.type==="message"){let s=ue(r.content,t.content_index);if(s.type!=="output_text")throw new P(`expected content to be 'output_text', got ${s.type}`);s.annotations[t.annotation_index]=structuredClone(t.annotation)}break}case"response.refusal.delta":{let r=S(e,t.output_index);if(r.type==="message"){let s=ue(r.content,t.content_index);if(s.type!=="refusal")throw new P(`expected content to be 'refusal', got ${s.type}`);s.refusal+=t.delta}break}case"response.refusal.done":{let r=S(e,t.output_index);if(r.type==="message"){let s=ue(r.content,t.content_index);if(s.type!=="refusal")throw new P(`expected content to be 'refusal', got ${s.type}`);s.refusal=t.refusal}break}case"response.function_call_arguments.delta":{let r=S(e,t.output_index);r.type==="function_call"&&(r.arguments+=t.delta);break}case"response.function_call_arguments.done":{let r=S(e,t.output_index);r.type==="function_call"&&(r.arguments=t.arguments);break}case"response.reasoning_text.delta":{let r=S(e,t.output_index);if(r.type==="reasoning"){if(!r.content)throw new P(`missing content at index ${t.content_index}`);let s=ue(r.content,t.content_index);if(s.type!=="reasoning_text")throw new P(`expected content to be 'reasoning_text', got ${s.type}`);s.text+=t.delta}break}case"response.reasoning_text.done":{let r=S(e,t.output_index);if(r.type==="reasoning"){if(!r.content)throw new P(`missing content at index ${t.content_index}`);let s=ue(r.content,t.content_index);if(s.type!=="reasoning_text")throw new P(`expected content to be 'reasoning_text', got ${s.type}`);s.text=t.text}break}case"response.reasoning_summary_part.added":{let r=S(e,t.output_index);r.type==="reasoning"&&r.summary.push(structuredClone(t.part));break}case"response.reasoning_summary_part.done":{let r=S(e,t.output_index);r.type==="reasoning"&&(ue(r.summary,t.summary_index),r.summary[t.summary_index]=structuredClone(t.part));break}case"response.reasoning_summary_text.delta":{let r=S(e,t.output_index);if(r.type==="reasoning"){let s=ue(r.summary,t.summary_index);s.text+=t.delta}break}case"response.reasoning_summary_text.done":{let r=S(e,t.output_index);if(r.type==="reasoning"){let s=ue(r.summary,t.summary_index);s.text=t.text}break}case"response.custom_tool_call_input.delta":{let r=S(e,t.output_index);r.type==="custom_tool_call"&&(r.input+=t.delta);break}case"response.custom_tool_call_input.done":{let r=S(e,t.output_index);r.type==="custom_tool_call"&&(r.input=t.input);break}case"response.mcp_call_arguments.delta":{let r=S(e,t.output_index);r.type==="mcp_call"&&(r.arguments+=t.delta);break}case"response.mcp_call_arguments.done":{let r=S(e,t.output_index);r.type==="mcp_call"&&(r.arguments=t.arguments);break}case"response.code_interpreter_call_code.delta":{let r=S(e,t.output_index);r.type==="code_interpreter_call"&&(r.code=(r.code??"")+t.delta);break}case"response.code_interpreter_call_code.done":{let r=S(e,t.output_index);r.type==="code_interpreter_call"&&(r.code=t.code);break}case"response.code_interpreter_call.in_progress":{let r=S(e,t.output_index);r.type==="code_interpreter_call"&&(r.status="in_progress");break}case"response.code_interpreter_call.interpreting":{let r=S(e,t.output_index);r.type==="code_interpreter_call"&&(r.status="interpreting");break}case"response.code_interpreter_call.completed":{let r=S(e,t.output_index);r.type==="code_interpreter_call"&&(r.status="completed");break}case"response.file_search_call.in_progress":{let r=S(e,t.output_index);r.type==="file_search_call"&&(r.status="in_progress");break}case"response.file_search_call.searching":{let r=S(e,t.output_index);r.type==="file_search_call"&&(r.status="searching");break}case"response.file_search_call.completed":{let r=S(e,t.output_index);r.type==="file_search_call"&&(r.status="completed");break}case"response.web_search_call.in_progress":{let r=S(e,t.output_index);r.type==="web_search_call"&&(r.status="in_progress");break}case"response.web_search_call.searching":{let r=S(e,t.output_index);r.type==="web_search_call"&&(r.status="searching");break}case"response.web_search_call.completed":{let r=S(e,t.output_index);r.type==="web_search_call"&&(r.status="completed");break}case"response.image_generation_call.in_progress":{let r=S(e,t.output_index);r.type==="image_generation_call"&&(r.status="in_progress");break}case"response.image_generation_call.generating":{let r=S(e,t.output_index);r.type==="image_generation_call"&&(r.status="generating");break}case"response.image_generation_call.completed":{let r=S(e,t.output_index);r.type==="image_generation_call"&&(r.status="completed");break}case"response.mcp_call.in_progress":{let r=S(e,t.output_index);r.type==="mcp_call"&&(r.status="in_progress");break}case"response.mcp_call.completed":{let r=S(e,t.output_index);r.type==="mcp_call"&&(r.status="completed");break}case"response.mcp_call.failed":{let r=S(e,t.output_index);r.type==="mcp_call"&&(r.status="failed");break}case"response.created":case"response.queued":case"response.in_progress":case"response.completed":case"response.failed":case"response.incomplete":{e=Oa(t.response);break}case"response.audio.delta":case"response.audio.done":case"response.audio.transcript.delta":case"response.audio.transcript.done":case"response.image_generation_call.partial_image":case"response.mcp_list_tools.in_progress":case"response.mcp_list_tools.completed":case"response.mcp_list_tools.failed":case"error":break;default:Gc(t)}return e}function Oa(t){let e=structuredClone(t);return(!Object.getOwnPropertyDescriptor(e,"output_text")||e.output_text==null)&&oe(e),e}function S(t,e){let r=t.output[e];if(!r)throw new P(`missing output at index ${e}`);return r}function ue(t,e){let r=t[e];if(!r)throw new P(`missing content at index ${e}`);return r}function Gc(t){throw new P(`Unhandled response stream event: ${JSON.stringify(t)}`)}var Cs,yn,Tt,An,va,Ta,Ca,In=class t extends Be{constructor(e){super(),Cs.add(this),yn.set(this,void 0),Tt.set(this,void 0),An.set(this,void 0),k(this,yn,e,"f")}static createResponse(e,r,s){let n=new t(r);return n._run(()=>n._createOrRetrieveResponse(e,r,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),n}async _createOrRetrieveResponse(e,r,s){this._listenForAbort(s?.signal),d(this,Cs,"m",va).call(this);let n,o=null;"response_id"in r?(n=await e.responses.retrieve(r.response_id,{stream:!0},{...s,signal:this.controller.signal,stream:!0}),o=r.starting_after??null):n=await e.responses.create({...r,stream:!0},{...s,signal:this.controller.signal}),this._connected();for await(let i of n)d(this,Cs,"m",Ta).call(this,i,o);if(n.controller.signal?.aborted)throw new D;return d(this,Cs,"m",Ca).call(this)}[(yn=new WeakMap,Tt=new WeakMap,An=new WeakMap,Cs=new WeakSet,va=function(){this.ended||k(this,Tt,void 0,"f")},Ta=function(r,s){if(this.ended)return;let n=(i,a)=>{(s==null||a.sequence_number>s)&&this._emit(i,a)},o=ka(r,d(this,Tt,"f"));switch(k(this,Tt,o,"f"),n("event",r),r.type){case"response.output_text.delta":{let i=o.output[r.output_index];if(!i)throw new P(`missing output at index ${r.output_index}`);if(i.type==="message"){let a=i.content[r.content_index];if(!a)throw new P(`missing content at index ${r.content_index}`);if(a.type!=="output_text")throw new P(`expected content to be 'output_text', got ${a.type}`);n("response.output_text.delta",{...r,snapshot:a.text})}break}case"response.function_call_arguments.delta":{let i=o.output[r.output_index];if(!i)throw new P(`missing output at index ${r.output_index}`);i.type==="function_call"&&n("response.function_call_arguments.delta",{...r,snapshot:i.arguments});break}default:n(r.type,r);break}},Ca=function(){if(this.ended)throw new P("stream has ended, this shouldn't happen");let r=d(this,Tt,"f");if(!r)throw new P("request ended without sending any events");k(this,Tt,void 0,"f");let s=Xc(r,d(this,yn,"f"));return k(this,An,s,"f"),s},Symbol.asyncIterator)](){let e=[],r=[],s=!1;return this.on("event",n=>{let o=r.shift();o?o.resolve(n):e.push(n)}),this.on("end",()=>{s=!0;for(let n of r)n.resolve(void 0);r.length=0}),this.on("abort",n=>{s=!0;for(let o of r)o.reject(n);r.length=0}),this.on("error",n=>{s=!0;for(let o of r)o.reject(n);r.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:s?{value:void 0,done:!0}:new Promise((o,i)=>r.push({resolve:o,reject:i})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();let e=d(this,An,"f");if(!e)throw new P("stream ended without producing a ChatCompletion");return e}};function Xc(t,e){return wa(t,e)}var Hr=class extends p{list(e,r={},s){return this._client.getAPIList(l`/responses/${e}/input_items`,C,{query:r,...s,__security:{bearerAuth:!0}})}};var Zr=class extends p{count(e={},r){return this._client.post("/responses/input_tokens",{body:e,...r,__security:{bearerAuth:!0}})}};var Oe=class extends p{constructor(){super(...arguments),this.inputItems=new Hr(this._client),this.inputTokens=new Zr(this._client)}create(e,r){return this._client.post("/responses",{body:e,...r,stream:e.stream??!1,__security:{bearerAuth:!0}})._thenUnwrap(s=>("object"in s&&s.object==="response"&&oe(s),s))}retrieve(e,r={},s){return this._client.get(l`/responses/${e}`,{query:r,...s,stream:r?.stream??!1,__security:{bearerAuth:!0}})._thenUnwrap(n=>("object"in n&&n.object==="response"&&oe(n),n))}delete(e,r){return this._client.delete(l`/responses/${e}`,{...r,headers:w([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}parse(e,r){return this._client.responses.create(e,r)._thenUnwrap(s=>To(s,e))}stream(e,r){return In.createResponse(this._client,e,r)}cancel(e,r){return this._client.post(l`/responses/${e}/cancel`,{...r,__security:{bearerAuth:!0}})}compact(e,r){return this._client.post("/responses/compact",{body:e,...r,__security:{bearerAuth:!0}})}};Oe.InputItems=Hr;Oe.InputTokens=Zr;var Vr=class extends p{retrieve(e,r){return this._client.get(l`/skills/${e}/content`,{...r,headers:w([{Accept:"application/binary"},r?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var Jr=class extends p{retrieve(e,r,s){let{skill_id:n}=r;return this._client.get(l`/skills/${n}/versions/${e}/content`,{...s,headers:w([{Accept:"application/binary"},s?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var Ct=class extends p{constructor(){super(...arguments),this.content=new Jr(this._client)}create(e,r={},s){return this._client.post(l`/skills/${e}/versions`,Fe({body:r,...s,__security:{bearerAuth:!0}},this._client))}retrieve(e,r,s){let{skill_id:n}=r;return this._client.get(l`/skills/${n}/versions/${e}`,{...s,__security:{bearerAuth:!0}})}list(e,r={},s){return this._client.getAPIList(l`/skills/${e}/versions`,C,{query:r,...s,__security:{bearerAuth:!0}})}delete(e,r,s){let{skill_id:n}=r;return this._client.delete(l`/skills/${n}/versions/${e}`,{...s,__security:{bearerAuth:!0}})}};Ct.Content=Jr;var $e=class extends p{constructor(){super(...arguments),this.content=new Vr(this._client),this.versions=new Ct(this._client)}create(e={},r){return this._client.post("/skills",Fe({body:e,...r,__security:{bearerAuth:!0}},this._client))}retrieve(e,r){return this._client.get(l`/skills/${e}`,{...r,__security:{bearerAuth:!0}})}update(e,r,s){return this._client.post(l`/skills/${e}`,{body:r,...s,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/skills",C,{query:e,...r,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(l`/skills/${e}`,{...r,__security:{bearerAuth:!0}})}};$e.Content=Vr;$e.Versions=Ct;var Gr=class extends p{create(e,r,s){return this._client.post(l`/uploads/${e}/parts`,ee({body:r,...s,__security:{bearerAuth:!0}},this._client))}};var tt=class extends p{constructor(){super(...arguments),this.parts=new Gr(this._client)}create(e,r){return this._client.post("/uploads",{body:e,...r,__security:{bearerAuth:!0}})}cancel(e,r){return this._client.post(l`/uploads/${e}/cancel`,{...r,__security:{bearerAuth:!0}})}complete(e,r,s){return this._client.post(l`/uploads/${e}/complete`,{body:r,...s,__security:{bearerAuth:!0}})}};tt.Parts=Gr;var Ra=async t=>{let e=await Promise.allSettled(t),r=e.filter(n=>n.status==="rejected");if(r.length){for(let n of r)console.error(n.reason);throw new Error(`${r.length} promise(s) failed - see the above errors`)}let s=[];for(let n of e)n.status==="fulfilled"&&s.push(n.value);return s};var Xr=class extends p{create(e,r,s){return this._client.post(l`/vector_stores/${e}/file_batches`,{body:r,...s,headers:w([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}retrieve(e,r,s){let{vector_store_id:n}=r;return this._client.get(l`/vector_stores/${n}/file_batches/${e}`,{...s,headers:w([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}cancel(e,r,s){let{vector_store_id:n}=r;return this._client.post(l`/vector_stores/${n}/file_batches/${e}/cancel`,{...s,headers:w([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,r,s){let n=await this.create(e,r);return await this.poll(e,n.id,s)}listFiles(e,r,s){let{vector_store_id:n,...o}=r;return this._client.getAPIList(l`/vector_stores/${n}/file_batches/${e}/files`,C,{query:o,...s,headers:w([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}async poll(e,r,s){let n=w([s?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":s?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:o,response:i}=await this.retrieve(r,{vector_store_id:e},{...s,headers:n}).withResponse();switch(o.status){case"in_progress":let a=5e3;if(s?.pollIntervalMs)a=s.pollIntervalMs;else{let c=i.headers.get("openai-poll-after-ms");if(c){let u=parseInt(c);isNaN(u)||(a=u)}}await Ie(a);break;case"failed":case"cancelled":case"completed":return o}}}async uploadAndPoll(e,{files:r,fileIds:s=[]},n){if(r==null||r.length==0)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");let o=n?.maxConcurrency??5,i=Math.min(o,r.length),a=this._client,c=r.values(),u=[...s];async function f(g){for(let A of g){let I=await a.files.create({file:A,purpose:"assistants"},n);u.push(I.id)}}let h=Array(i).fill(c).map(f);return await Ra(h),await this.createAndPoll(e,{file_ids:u})}};var Yr=class extends p{create(e,r,s){return this._client.post(l`/vector_stores/${e}/files`,{body:r,...s,headers:w([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}retrieve(e,r,s){let{vector_store_id:n}=r;return this._client.get(l`/vector_stores/${n}/files/${e}`,{...s,headers:w([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}update(e,r,s){let{vector_store_id:n,...o}=r;return this._client.post(l`/vector_stores/${n}/files/${e}`,{body:o,...s,headers:w([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}list(e,r={},s){return this._client.getAPIList(l`/vector_stores/${e}/files`,C,{query:r,...s,headers:w([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}delete(e,r,s){let{vector_store_id:n}=r;return this._client.delete(l`/vector_stores/${n}/files/${e}`,{...s,headers:w([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,r,s){let n=await this.create(e,r,s);return await this.poll(e,n.id,s)}async poll(e,r,s){let n=w([s?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":s?.pollIntervalMs?.toString()??void 0}]);for(;;){let o=await this.retrieve(r,{vector_store_id:e},{...s,headers:n}).withResponse(),i=o.data;switch(i.status){case"in_progress":let a=5e3;if(s?.pollIntervalMs)a=s.pollIntervalMs;else{let c=o.response.headers.get("openai-poll-after-ms");if(c){let u=parseInt(c);isNaN(u)||(a=u)}}await Ie(a);break;case"failed":case"completed":return i}}}async upload(e,r,s){let n=await this._client.files.create({file:r,purpose:"assistants"},s);return this.create(e,{file_id:n.id},s)}async uploadAndPoll(e,r,s){let n=await this.upload(e,r,s);return await this.poll(e,n.id,s)}content(e,r,s){let{vector_store_id:n}=r;return this._client.getAPIList(l`/vector_stores/${n}/files/${e}/content`,Q,{...s,headers:w([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}};var Me=class extends p{constructor(){super(...arguments),this.files=new Yr(this._client),this.fileBatches=new Xr(this._client)}create(e,r){return this._client.post("/vector_stores",{body:e,...r,headers:w([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}retrieve(e,r){return this._client.get(l`/vector_stores/${e}`,{...r,headers:w([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}update(e,r,s){return this._client.post(l`/vector_stores/${e}`,{body:r,...s,headers:w([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/vector_stores",C,{query:e,...r,headers:w([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(l`/vector_stores/${e}`,{...r,headers:w([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}search(e,r,s){return this._client.getAPIList(l`/vector_stores/${e}/search`,Q,{body:r,method:"post",...s,headers:w([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}};Me.Files=Yr;Me.FileBatches=Xr;var Rt=class extends p{create(e,r){return this._client.post("/videos",ee({body:e,...r,__security:{bearerAuth:!0}},this._client))}retrieve(e,r){return this._client.get(l`/videos/${e}`,{...r,__security:{bearerAuth:!0}})}list(e={},r){return this._client.getAPIList("/videos",$,{query:e,...r,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(l`/videos/${e}`,{...r,__security:{bearerAuth:!0}})}createCharacter(e,r){return this._client.post("/videos/characters",ee({body:e,...r,__security:{bearerAuth:!0}},this._client))}downloadContent(e,r={},s){return this._client.get(l`/videos/${e}/content`,{query:r,...s,headers:w([{Accept:"application/binary"},s?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}edit(e,r){return this._client.post("/videos/edits",ee({body:e,...r,__security:{bearerAuth:!0}},this._client))}extend(e,r){return this._client.post("/videos/extensions",ee({body:e,...r,__security:{bearerAuth:!0}},this._client))}getCharacter(e,r){return this._client.get(l`/videos/characters/${e}`,{...r,__security:{bearerAuth:!0}})}remix(e,r,s){return this._client.post(l`/videos/${e}/remix`,Fe({body:r,...s,__security:{bearerAuth:!0}},this._client))}};var Qr,Ea,bn,Et=class extends p{constructor(){super(...arguments),Qr.add(this)}async unwrap(e,r,s=this._client.webhookSecret,n=300){return await this.verifySignature(e,r,s,n),JSON.parse(e)}async verifySignature(e,r,s=this._client.webhookSecret,n=300){if(typeof crypto>"u"||typeof crypto.subtle.importKey!="function"||typeof crypto.subtle.verify!="function")throw new Error("Webhook signature verification is only supported when the `crypto` global is defined");d(this,Qr,"m",Ea).call(this,s);let o=w([r]).values,i=d(this,Qr,"m",bn).call(this,o,"webhook-signature"),a=d(this,Qr,"m",bn).call(this,o,"webhook-timestamp"),c=d(this,Qr,"m",bn).call(this,o,"webhook-id"),u=parseInt(a,10);if(isNaN(u))throw new Ae("Invalid webhook timestamp format");let f=Math.floor(Date.now()/1e3);if(f-u>n)throw new Ae("Webhook timestamp is too old");if(u>f+n)throw new Ae("Webhook timestamp is too new");let h=i.split(" ").map(b=>b.startsWith("v1,")?b.substring(3):b),g=s.startsWith("whsec_")?Buffer.from(s.replace("whsec_",""),"base64"):Buffer.from(s,"utf-8"),A=c?`${c}.${a}.${e}`:`${a}.${e}`,I=await crypto.subtle.importKey("raw",g,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(let b of h)try{let _=Buffer.from(b,"base64");if(await crypto.subtle.verify("HMAC",I,_,new TextEncoder().encode(A)))return}catch{continue}throw new Ae("The given webhook signature does not match the expected signature")}};Qr=new WeakSet,Ea=function(e){if(typeof e!="string"||e.length===0)throw new Error("The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET, on the client class, OpenAI({ webhookSecret: '123' }), or passed to this function")},bn=function(e,r){if(!e)throw new Error("Headers are required");let s=e.get(r);if(s==null)throw new Error(`Missing required header: ${r}`);return s};var $a=Symbol.for("openai.node.providerDefinitions.v1"),Ma=globalThis,Na=Ma[$a],za=Na??new WeakMap;Na||Object.defineProperty(Ma,$a,{value:za});function ja(t){let e=za.get(t);if(!e)throw new Error("Invalid provider. Providers must be created with createProvider().");return e.configure()}var Co,Ro,Rs,Ua,ip="workload-identity-auth",v=class{constructor(e={}){Co.add(this),Rs.set(this,void 0),this.completions=new gt(this),this.chat=new We(this),this.embeddings=new At(this),this.files=new bt(this),this.images=new Ot(this),this.audio=new we(this),this.moderations=new vt(this),this.models=new kt(this),this.fineTuning=new fe(this),this.graders=new et(this),this.vectorStores=new Me(this),this.webhooks=new Et(this),this.beta=new de(this),this.batches=new mt(this),this.uploads=new tt(this),this.admin=new Ze(this),this.responses=new Oe(this),this.realtime=new Se(this),this.conversations=new Ye(this),this.evals=new Qe(this),this.containers=new Xe(this),this.skills=new $e(this),this.videos=new Rt(this);let r=e.provider;if(r){let b=["apiKey","adminAPIKey","workloadIdentity","baseURL"].filter(_=>e[_]!=null);if(b.length)throw new P(`The \`provider\` option cannot be used with ${b.map(_=>`\`${_}\``).join(", ")}. Configure authentication and the base URL through the provider instead.`)}let{baseURL:s=r?null:pe("OPENAI_BASE_URL"),apiKey:n=r?null:pe("OPENAI_API_KEY")??null,adminAPIKey:o=r?null:pe("OPENAI_ADMIN_KEY")??null,organization:i=r?null:pe("OPENAI_ORG_ID")??null,project:a=r?null:pe("OPENAI_PROJECT_ID")??null,webhookSecret:c=pe("OPENAI_WEBHOOK_SECRET")??null,workloadIdentity:u,...f}=e,h=r?ja(r):void 0,g={apiKey:n,adminAPIKey:o,organization:i,project:a,webhookSecret:c,workloadIdentity:u,provider:r,...f,baseURL:h?.baseURL??(s||"https://api.openai.com/v1")};if(n&&u)throw new P("The `apiKey` and `workloadIdentity` options are mutually exclusive");if(!h&&!n&&!o&&!u)throw new P("Missing credentials. Please pass an `apiKey`, `workloadIdentity`, `adminAPIKey`, or set the `OPENAI_API_KEY` or `OPENAI_ADMIN_KEY` environment variable.");if(!g.dangerouslyAllowBrowser&&Si())throw new P(`It looks like you're running in a browser-like environment.
19
19
 
20
20
  This is disabled by default, as it risks exposing your secret API credentials to attackers.
21
21
  If you understand the risks and have appropriate mitigations in place,
@@ -24,25 +24,21 @@ you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
24
24
  new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
25
25
 
26
26
  https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
27
- `);this.baseURL=g.baseURL,this.timeout=g.timeout??Ro.DEFAULT_TIMEOUT,this.logger=g.logger??console;let A="warn";this.logLevel=A,this.logLevel=oo(g.logLevel,"ClientOptions.logLevel",this)??oo(me("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??A,this.fetchOptions=g.fetchOptions,this.maxRetries=g.maxRetries??2,this.fetch=g.fetch??Zs(),k(this,Rs,Si,"f");let I=r?void 0:me("OPENAI_CUSTOM_HEADERS");if(I){let b={};for(let _ of I.split(`
28
- `)){let m=_.indexOf(":");m>=0&&(b[_.substring(0,m).trim()]=_.substring(m+1).trim())}g.defaultHeaders=w([b,g.defaultHeaders])}this._options=g,this._provider=h,u&&(this._workloadIdentityAuth=new en(u,this.fetch)),this.apiKey=typeof n=="string"?n:null,this.adminAPIKey=o,this.organization=i,this.project=a,this.webhookSecret=c}withOptions(e){let r=this._options.provider,s=e.provider??r,n={...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._options.apiKey,adminAPIKey:this.adminAPIKey,workloadIdentity:this._options.workloadIdentity,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret};return s&&(delete n.apiKey,delete n.adminAPIKey,delete n.workloadIdentity,delete n.baseURL,s!==r&&(delete n.organization,delete n.project,delete n.defaultHeaders)),new this.constructor({...n,...e,provider:s})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:r},s={bearerAuth:!0,adminAPIKeyAuth:!0}){if(!(e.get("authorization")||e.get("api-key"))&&!(r.has("authorization")||r.has("api-key"))&&!(this._workloadIdentityAuth&&s.bearerAuth))throw new Error('Could not resolve authentication method. Expected either apiKey or adminAPIKey to be set. Or for one of the "Authorization" or "api-key" headers to be explicitly omitted')}async authHeaders(e,r={bearerAuth:!0,adminAPIKeyAuth:!0}){return w([r.bearerAuth?await this.bearerAuth(e):null,r.adminAPIKeyAuth?await this.adminAPIKeyAuth(e):null])}async bearerAuth(e){if(this._workloadIdentityAuth)return w([{Authorization:`Bearer ${await this._workloadIdentityAuth.getToken()}`}]);if(this.apiKey!=null)return w([{Authorization:`Bearer ${this.apiKey}`}])}async adminAPIKeyAuth(e){if(this.adminAPIKey!=null)return w([{Authorization:`Bearer ${this.adminAPIKey}`}])}stringifyQuery(e){return Ki(e)}getUserAgent(){return`${this.constructor.name}/JS ${Ke}`}defaultIdempotencyKey(){return`stainless-node-retry-${Hn()}`}makeStatusError(e,r,s,n){return U.generate(e,r,s,n)}async _callApiKey(){if(this._provider)return!1;let e=this._options.apiKey;if(typeof e!="function")return!1;let r;try{r=await e()}catch(s){throw s instanceof P?s:new P(`Failed to get token from 'apiKey' function: ${s.message}`,{cause:s})}if(typeof r!="string"||!r)throw new P(`Expected 'apiKey' function argument to return a string but it returned ${r}`);return this.apiKey=r,!0}buildURL(e,r,s){let n=!d(this,Co,"m",Na).call(this)&&s||this.baseURL,o=xi(e)?new URL(e):new URL(n+(n.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),i=this.defaultQuery(),a=Object.fromEntries(o.searchParams);return(!Vn(i)||!Vn(a))&&(r={...a,...i,...r}),typeof r=="object"&&r&&!Array.isArray(r)&&(o.search=this.stringifyQuery(r)),o.toString()}async prepareOptions(e){if(this._provider)return;(e.__security??{bearerAuth:!0}).bearerAuth&&await this._callApiKey()}async prepareRequest(e,{url:r,options:s}){}get(e,r){return this.methodRequest("get",e,r)}post(e,r){return this.methodRequest("post",e,r)}patch(e,r){return this.methodRequest("patch",e,r)}put(e,r){return this.methodRequest("put",e,r)}delete(e,r){return this.methodRequest("delete",e,r)}methodRequest(e,r,s){return this.request(Promise.resolve(s).then(n=>({method:e,path:r,...n})))}request(e,r=null){return new ot(this,this.makeRequest(e,r,void 0))}async makeRequest(e,r,s){let n=await e,o=n.maxRetries??this.maxRetries;r==null&&(r=o),await this.prepareOptions(n);let{req:i,url:a,timeout:c}=await this.buildRequest(n,{retryCount:o-r});await this.prepareRequest(i,{url:a,options:n}),await this._provider?.prepareRequest?.(i,{url:a,options:n});let u="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),f=s===void 0?"":`, retryOf: ${s}`,h=Date.now();if(K(this).debug(`[${u}] sending request`,ve({retryOfRequestLogID:s,method:n.method,url:a,options:n,headers:i.headers})),n.signal?.aborted)throw new L;let g=n.__security??{bearerAuth:!0},A=new AbortController,I=await this.fetchWithAuth(a,i,c,A,g).catch(us),b=Date.now();if(I instanceof globalThis.Error){let y=`retrying, ${r} attempts remaining`;if(n.signal?.aborted)throw new L;let O=as(I)||/timed? ?out/i.test(String(I)+("cause"in I?String(I.cause):""));if(r)return K(this).info(`[${u}] connection ${O?"timed out":"failed"} - ${y}`),K(this).debug(`[${u}] connection ${O?"timed out":"failed"} (${y})`,ve({retryOfRequestLogID:s,url:a,durationMs:b-h,message:I.message})),this.retryRequest(n,r,s??u);throw K(this).info(`[${u}] connection ${O?"timed out":"failed"} - error; no more retries left`),K(this).debug(`[${u}] connection ${O?"timed out":"failed"} (error; no more retries left)`,ve({retryOfRequestLogID:s,url:a,durationMs:b-h,message:I.message})),I instanceof st||I instanceof ls?I:O?new Ae:new De({message:ap(I),cause:I})}let _=[...I.headers.entries()].filter(([y])=>y==="x-request-id").map(([y,O])=>", "+y+": "+JSON.stringify(O)).join(""),m=`[${u}${f}${_}] ${i.method} ${a} ${I.ok?"succeeded":"failed"} with status ${I.status} in ${b-h}ms`;if(!I.ok){if(I.status===401&&this._workloadIdentityAuth&&g.bearerAuth&&!n.__metadata?.hasStreamingBody&&!n.__metadata?.workloadIdentityTokenRefreshed)return await Xn(I.body),this._workloadIdentityAuth.invalidateToken(),this.makeRequest({...n,__metadata:{...n.__metadata,workloadIdentityTokenRefreshed:!0}},r,s??u);let y=await this.shouldRetry(I);if(r&&y){let D=`retrying, ${r} attempts remaining`;return await Xn(I.body),K(this).info(`${m} - ${D}`),K(this).debug(`[${u}] response error (${D})`,ve({retryOfRequestLogID:s,url:I.url,status:I.status,headers:I.headers,durationMs:b-h})),this.retryRequest(n,r,s??u,I.headers)}let O=y?"error; no more retries left":"error; not retryable";K(this).info(`${m} - ${O}`);let R=await I.text().catch(D=>us(D).message),N=Oi(R),z=N?void 0:R;throw K(this).debug(`[${u}] response error (${O})`,ve({retryOfRequestLogID:s,url:I.url,status:I.status,headers:I.headers,message:z,durationMs:Date.now()-h})),this.makeStatusError(I.status,N,z,I.headers)}return K(this).info(m),K(this).debug(`[${u}] response start`,ve({retryOfRequestLogID:s,url:I.url,status:I.status,headers:I.headers,durationMs:b-h})),{response:I,options:n,controller:A,requestLogID:u,retryOfRequestLogID:s,startTime:h}}getAPIList(e,r,s){return this.requestAPIList(r,s&&"then"in s?s.then(n=>({method:"get",path:e,...n})):{method:"get",path:e,...s})}requestAPIList(e,r){let s=this.makeRequest(r,null,void 0);return new fs(this,s,e)}async fetchWithAuth(e,r,s,n,o={bearerAuth:!0,adminAPIKeyAuth:!0}){if(this._workloadIdentityAuth&&o.bearerAuth){let a=r.headers,c=a.get("Authorization");if(!c||c===`Bearer ${ip}`){let u=await this._workloadIdentityAuth.getToken();a.set("Authorization",`Bearer ${u}`)}}return await this.fetchWithTimeout(e,r,s,n)}async fetchWithTimeout(e,r,s,n){let{signal:o,method:i,...a}=r||{},c=this._makeAbort(n);o&&o.addEventListener("abort",c,{once:!0});let u=setTimeout(c,s),f=globalThis.ReadableStream&&a.body instanceof globalThis.ReadableStream||typeof a.body=="object"&&a.body!==null&&Symbol.asyncIterator in a.body,h={signal:n.signal,...f?{duplex:"half"}:{},method:"GET",...a};i&&(h.method=i.toUpperCase());try{return await this.fetch.call(void 0,e,h)}finally{clearTimeout(u)}}async shouldRetry(e){let r=e.headers.get("x-should-retry");return r==="true"?!0:r==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,r,s,n){let o,i=n?.get("retry-after-ms");if(i){let c=parseFloat(i);Number.isNaN(c)||(o=c)}let a=n?.get("retry-after");if(a&&!o){let c=parseFloat(a);Number.isNaN(c)?o=Date.parse(a)-Date.now():o=c*1e3}if(o===void 0){let c=e.maxRetries??this.maxRetries;o=this.calculateDefaultRetryTimeoutMillis(r,c)}return await be(o),this.makeRequest(e,r-1,s)}calculateDefaultRetryTimeoutMillis(e,r){let o=r-e,i=Math.min(.5*Math.pow(2,o),8),a=1-Math.random()*.25;return i*a*1e3}async buildRequest(e,{retryCount:r=0}={}){let s={...e},{method:n,path:o,query:i,defaultBaseURL:a}=s,c=this.buildURL(o,i,a);"timeout"in s&&Pi("timeout",s.timeout),s.timeout=s.timeout??this.timeout;let{bodyHeaders:u,body:f,isStreamingBody:h}=this.buildBody({options:s});h&&(e.__metadata={...e.__metadata,hasStreamingBody:!0});let g=await this.buildHeaders({options:e,method:n,bodyHeaders:u,retryCount:r});return{req:{method:n,headers:g,...s.signal&&{signal:s.signal},...globalThis.ReadableStream&&f instanceof globalThis.ReadableStream&&{duplex:"half"},...f&&{body:f},...this.fetchOptions??{},...s.fetchOptions??{}},url:c,timeout:s.timeout}}async buildHeaders({options:e,method:r,bodyHeaders:s,retryCount:n}){let o={};this.idempotencyHeader&&r!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),o[this.idempotencyHeader]=e.idempotencyKey);let i=w([o,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(n),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...Ri(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},this._provider?void 0:await this.authHeaders(e,e.__security??{bearerAuth:!0}),this._options.defaultHeaders,s,e.headers]);return this._provider||this.validateHeaders(i,e.__security??{bearerAuth:!0}),i.values}_makeAbort(e){return()=>e.abort()}buildBody({options:e}){let{body:r,headers:s}=e;if(!r)return r===void 0&&"body"in e?{...d(this,Rs,"f").call(this,{body:r,headers:w([s])}),isStreamingBody:!1}:{bodyHeaders:void 0,body:void 0,isStreamingBody:!1};let n=w([s]),o=typeof globalThis.ReadableStream<"u"&&r instanceof globalThis.ReadableStream,i=!o&&(typeof r=="string"||r instanceof ArrayBuffer||ArrayBuffer.isView(r)||typeof globalThis.Blob<"u"&&r instanceof globalThis.Blob||r instanceof URLSearchParams||r instanceof FormData);return ArrayBuffer.isView(r)||r instanceof ArrayBuffer||r instanceof DataView||typeof r=="string"&&n.values.has("content-type")||globalThis.Blob&&r instanceof globalThis.Blob||r instanceof FormData||r instanceof URLSearchParams||o?{bodyHeaders:void 0,body:r,isStreamingBody:!i}:typeof r=="object"&&(Symbol.asyncIterator in r||Symbol.iterator in r&&"next"in r&&typeof r.next=="function")?{bodyHeaders:void 0,body:Vs(r),isStreamingBody:!0}:typeof r=="object"&&n.values.get("content-type")==="application/x-www-form-urlencoded"?{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(r),isStreamingBody:!1}:{...d(this,Rs,"f").call(this,{body:r,headers:n}),isStreamingBody:!1}}};Ro=v,Rs=new WeakMap,Co=new WeakSet,Na=function(){return this._provider!==void 0||this.baseURL!=="https://api.openai.com/v1"};v.OpenAI=Ro;v.DEFAULT_TIMEOUT=6e5;v.OpenAIError=P;v.APIError=U;v.APIConnectionError=De;v.APIConnectionTimeoutError=Ae;v.APIUserAbortError=L;v.NotFoundError=qt;v.ConflictError=Wt;v.RateLimitError=Zt;v.BadRequestError=Kt;v.AuthenticationError=Ft;v.InternalServerError=Vt;v.PermissionDeniedError=Bt;v.UnprocessableEntityError=Ht;v.InvalidWebhookSignatureError=Ie;v.toFile=_s;v.Completions=gt;v.Chat=We;v.Embeddings=At;v.Files=bt;v.Images=Ot;v.Audio=Pe;v.Moderations=vt;v.Models=kt;v.FineTuning=he;v.Graders=et;v.VectorStores=Me;v.Webhooks=Et;v.Beta=fe;v.Batches=mt;v.Uploads=tt;v.Admin=Ze;v.Responses=ke;v.Realtime=Se;v.Conversations=Ye;v.Evals=Qe;v.Containers=Xe;v.Skills=$e;v.Videos=Rt;function ap(t){if(up(t))return"Connection error. This may be caused by passing an undici dispatcher, such as ProxyAgent, that is incompatible with the fetch implementation. If you are using undici's ProxyAgent, pass the fetch implementation from the same undici package: import { fetch, ProxyAgent } from 'undici'; new OpenAI({ fetch, fetchOptions: { dispatcher: new ProxyAgent(...) } });"}function up(t){let e=t;for(let r=0;r<8&&e&&typeof e=="object";r++){let s=e;if(s.code==="UND_ERR_INVALID_ARG"&&typeof s.message=="string"&&s.message.includes("invalid onRequestStart method"))return!0;e=s.cause}return!1}function lp(t){return!!(String(t).includes("context_length_exceeded")||"message"in t&&typeof t.message=="string"&&(t.message.includes("Input tokens exceed the configured limit")||t.message.includes("exceeds the context window")||t.message.includes("maximum context length")))}function ce(t){if(!t||typeof t!="object")return t;let e;return t.constructor.name===Ae.name&&"message"in t&&typeof t.message=="string"?(e=new Error(t.message),e.name="TimeoutError"):t.constructor.name===L.name&&"message"in t&&typeof t.message=="string"?(e=new Error(t.message),e.name="AbortError"):lp(t)?e=Yo.fromError(t):"status"in t&&t.status===400&&"message"in t&&typeof t.message=="string"&&t.message.includes("tool_calls")?e=is(t,"INVALID_TOOL_RESULTS"):"status"in t&&t.status===401?e=is(t,"MODEL_AUTHENTICATION"):"status"in t&&t.status===429?e=is(t,"MODEL_RATE_LIMIT"):"status"in t&&t.status===404?e=is(t,"MODEL_NOT_FOUND"):e=t,e}var _e=t=>t();function Ne(t){return t?!!(/^o\d/.test(t??"")||t.startsWith("gpt-5")&&!t.startsWith("gpt-5-chat")):!1}function cp(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 xn(t){return t.metadata?.filename??t.metadata?.name??t.metadata?.title}var pp="LC_AUTOGENERATED";function St(t){let e=t.metadata?.filename??t.metadata?.name??t.metadata?.title;return e||(console.warn("OpenAI may require a filename for file uploads. Specify a filename in the content block metadata, e.g.: { type: 'file', mimeType: '...', data: '...', metadata: { filename: 'my-file.pdf' } }. Using placeholder filename 'LC_AUTOGENERATED'."),pp)}function ze(t){let 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(!Ks.isInstance(t))throw new Error("Invalid generic chat message");return cp(t);default:throw new Error(`Unknown message type: ${e}`)}}function za(t){return!!(t.includes("gpt-5.2-pro")||t.includes("gpt-5.4-pro")||t.includes("gpt-5.5-pro")||t.includes("codex"))}function je(t){let{azureOpenAIApiDeploymentName:e,azureOpenAIApiInstanceName:r,azureOpenAIApiKey:s,azureOpenAIBasePath:n,baseURL:o,azureADTokenProvider:i,azureOpenAIEndpoint:a}=t;if((s||i)&&n&&e)return`${n}/${e}`;if((s||i)&&a&&e)return`${a}/openai/deployments/${e}`;if(s||i){if(!r)throw new Error("azureOpenAIApiInstanceName is required when using azureOpenAIApiKey");if(!e)throw new Error("azureOpenAIApiDeploymentName is a required parameter when using azureOpenAIApiKey");return`https://${r}.openai.azure.com/openai/deployments/${e}`}return o}function So(t){return typeof Headers<"u"&&t!==null&&typeof t=="object"&&Object.prototype.toString.call(t)==="[object Headers]"}function ja(t){let e=_e(()=>{if(So(t))return t;if(Array.isArray(t))return new Headers(t);if(typeof t=="object"&&t!==null&&"values"in t&&So(t.values))return t.values;if(typeof t=="object"&&t!==null){let r=Object.entries(t).filter(([,s])=>typeof s=="string").map(([s,n])=>[s,n]);return new Headers(r)}return new Headers});return Object.fromEntries(e.entries())}function Ua(){let t=Xo();return(t==="node"||t==="deno")&&(t=`(${t}/${process.version}; ${process.platform}; ${process.arch})`),t}function Ue(t,e=!1,r="1.0.0"){let s=ja(t),n=Ua(),o=`langchainjs${e?"-azure":""}-openai`;return{...s,"User-Agent":s["User-Agent"]?`${o}/${r} (${n})${s["User-Agent"]}`:`${o}/${r} (${n})`}}function La(t,e){let r;return Ws(t)?r=yi(t):r=t,e?.strict!==void 0&&(r.function.strict=e.strict),r}function mp(t){return t.anyOf!==void 0&&Array.isArray(t.anyOf)}function Da(t){let e=["namespace functions {",""];for(let r of t)r.description&&e.push(`// ${r.description}`),Object.keys(r.parameters.properties??{}).length>0?(e.push(`type ${r.name} = (_: {`),e.push(Ka(r.parameters,0)),e.push("}) => any;")):e.push(`type ${r.name} = () => any;`),e.push("");return e.push("} // namespace functions"),e.join(`
29
- `)}function Ka(t,e){let r=[];for(let[s,n]of Object.entries(t.properties??{}))n.description&&e<2&&r.push(`// ${n.description}`),t.required?.includes(s)?r.push(`${s}: ${wn(n,e)},`):r.push(`${s}?: ${wn(n,e)},`);return r.map(s=>" ".repeat(e)+s).join(`
30
- `)}function wn(t,e){if(mp(t))return t.anyOf.map(r=>wn(r,e)).join(" | ");switch(t.type){case"string":return t.enum?t.enum.map(r=>`"${r}"`).join(" | "):"string";case"number":return t.enum?t.enum.map(r=>`${r}`).join(" | "):"number";case"integer":return t.enum?t.enum.map(r=>`${r}`).join(" | "):"number";case"boolean":return"boolean";case"null":return"null";case"object":return["{",Ka(t,e+2),"}"].join(`
31
- `);case"array":return t.items?`${wn(t.items,e)}[]`:"any[]";default:return""}}function Pn(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 ts(t){return"type"in t&&t.type!=="function"}function Fa(t){return typeof t=="object"&&t!==null&&"extras"in t&&typeof t.extras=="object"&&t.extras!==null&&"providerToolDefinition"in t.extras&&typeof t.extras.providerToolDefinition=="object"&&t.extras.providerToolDefinition!==null}function Ba(t){return t!=null&&typeof t=="object"&&"type"in t&&t.type!=="function"}function $t(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 On(t){return"type"in t&&t.type==="custom"&&"custom"in t&&typeof t.custom=="object"&&t.custom!==null}function qa(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 Wa(t){if(t.type==="computer_call")return{...t,type:"tool_call",call_id:t.id,id:t.call_id,name:"computer_use",isComputerTool:!0,args:{action:t.action}}}function Ha(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="tool_call"&&"isComputerTool"in t&&t.isComputerTool===!0}function Za(t,e){return typeof t!="object"||t===null||!("type"in t)||t.type!=="tool_call"?!1:!!("isCustomTool"in t&&t.isCustomTool===!0||e&&"id"in t&&typeof t.id=="string"&&t.id in e)}function Va(t){let 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 Ja(t){let 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()}}}var Xa=Symbol("Let zodToJsonSchema decide on which parser to use"),Ga={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"},Ya=t=>typeof t=="string"?{...Ga,basePath:["#"],definitions:{},name:t}:{...Ga,basePath:["#"],definitions:{},...t};var Es=t=>"_def"in t?t._def:t;function Qa(t){if(!t)return!0;for(let e in t)return!1;return!0}var eu=t=>{let e=Ya(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,currentPath:r,propertyPath:void 0,seenRefs:new Set,seen:new Map(Object.entries(e.definitions).map(([s,n])=>[Es(n),{def:Es(n),path:[...e.basePath,e.definitionPath,s],jsonSchema:void 0}]))}};function $o(t,e,r,s){s?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function M(t,e,r,s,n){t[e]=r,$o(t,e,s,n)}function tu(){return{}}function ru(t,e){let r={type:"array"};return t.type?._def?.typeName!==E.ZodAny&&(r.items=T(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&M(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&M(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(M(r,"minItems",t.exactLength.value,t.exactLength.message,e),M(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}function su(t,e){let r={type:"integer",format:"int64"};if(!t.checks)return r;for(let s of t.checks)switch(s.kind){case"min":e.target==="jsonSchema7"?s.inclusive?M(r,"minimum",s.value,s.message,e):M(r,"exclusiveMinimum",s.value,s.message,e):(s.inclusive||(r.exclusiveMinimum=!0),M(r,"minimum",s.value,s.message,e));break;case"max":e.target==="jsonSchema7"?s.inclusive?M(r,"maximum",s.value,s.message,e):M(r,"exclusiveMaximum",s.value,s.message,e):(s.inclusive||(r.exclusiveMaximum=!0),M(r,"maximum",s.value,s.message,e));break;case"multipleOf":M(r,"multipleOf",s.value,s.message,e);break}return r}function nu(){return{type:"boolean"}}function ou(t,e,r){return T(t.type._def,e,r)}var iu=(t,e,r)=>T(t.innerType._def,e,r);function Mo(t,e,r){let s=r??e.dateStrategy;if(Array.isArray(s))return{anyOf:s.map((n,o)=>Mo(t,e,n))};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 dp(t,e)}}var dp=(t,e)=>{let r={type:"integer",format:"unix-time"};if(e.target==="openApi3")return r;for(let s of t.checks)switch(s.kind){case"min":M(r,"minimum",s.value,s.message,e);break;case"max":M(r,"maximum",s.value,s.message,e);break}return r};function au(t,e,r){return{...T(t.innerType._def,e,r),default:t.defaultValue()}}function uu(t,e,r){return e.effectStrategy==="input"?T(t.schema._def,e,r):{}}function lu(t){return{type:"string",enum:[...t.values]}}var fp=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function cu(t,e){let r=[T(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),T(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(o=>!!o),s=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,n=[];return r.forEach(o=>{if(fp(o))n.push(...o.allOf),o.unevaluatedProperties===void 0&&(s=void 0);else{let i=o;if("additionalProperties"in o&&o.additionalProperties===!1){let{additionalProperties:a,...c}=o;i=c}else s=void 0;n.push(i)}}),n.length?{allOf:n,...s}:void 0}function pu(t,e){let r=typeof t.value;return r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:r==="bigint"?"integer":r,enum:[t.value]}:{type:r==="bigint"?"integer":r,const:t.value}}var No,Mt={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:()=>(No===void 0&&(No=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),No),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/};function kn(t,e){let r={type:"string"};function s(n){return e.patternStrategy==="escape"?hp(n):n}if(t.checks)for(let n of t.checks)switch(n.kind){case"min":M(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":M(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"email":switch(e.emailStrategy){case"format:email":ge(r,"email",n.message,e);break;case"format:idn-email":ge(r,"idn-email",n.message,e);break;case"pattern:zod":ye(r,Mt.email,n.message,e);break}break;case"url":ge(r,"uri",n.message,e);break;case"uuid":ge(r,"uuid",n.message,e);break;case"regex":ye(r,n.regex,n.message,e);break;case"cuid":ye(r,Mt.cuid,n.message,e);break;case"cuid2":ye(r,Mt.cuid2,n.message,e);break;case"startsWith":ye(r,RegExp(`^${s(n.value)}`),n.message,e);break;case"endsWith":ye(r,RegExp(`${s(n.value)}$`),n.message,e);break;case"datetime":ge(r,"date-time",n.message,e);break;case"date":ge(r,"date",n.message,e);break;case"time":ge(r,"time",n.message,e);break;case"duration":ge(r,"duration",n.message,e);break;case"length":M(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),M(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{ye(r,RegExp(s(n.value)),n.message,e);break}case"ip":{n.version!=="v6"&&ge(r,"ipv4",n.message,e),n.version!=="v4"&&ge(r,"ipv6",n.message,e);break}case"emoji":ye(r,Mt.emoji,n.message,e);break;case"ulid":{ye(r,Mt.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{ge(r,"binary",n.message,e);break}case"contentEncoding:base64":{M(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{ye(r,Mt.base64,n.message,e);break}}break}case"nanoid":ye(r,Mt.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}var hp=t=>Array.from(t).map(e=>/[a-zA-Z0-9]/.test(e)?e:`\\${e}`).join(""),ge=(t,e,r,s)=>{t.format||t.anyOf?.some(n=>n.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,...r&&s.errorMessages&&{errorMessage:{format:r}}})):M(t,"format",e,r,s)},ye=(t,e,r,s)=>{t.pattern||t.allOf?.some(n=>n.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:mu(e,s),...r&&s.errorMessages&&{errorMessage:{pattern:r}}})):M(t,"pattern",mu(e,s),r,s)},mu=(t,e)=>{let r=typeof t=="function"?t():t;if(!e.applyRegexFlags||!r.flags)return r.source;let s={i:r.flags.includes("i"),m:r.flags.includes("m"),s:r.flags.includes("s")},n=s.i?r.source.toLowerCase():r.source,o="",i=!1,a=!1,c=!1;for(let u=0;u<n.length;u++){if(i){o+=n[u],i=!1;continue}if(s.i){if(a){if(n[u].match(/[a-z]/)){c?(o+=n[u],o+=`${n[u-2]}-${n[u]}`.toUpperCase(),c=!1):n[u+1]==="-"&&n[u+2]?.match(/[a-z]/)?(o+=n[u],c=!0):o+=`${n[u]}${n[u].toUpperCase()}`;continue}}else if(n[u].match(/[a-z]/)){o+=`[${n[u]}${n[u].toUpperCase()}]`;continue}}if(s.m){if(n[u]==="^"){o+=`(^|(?<=[\r
27
+ `);this.baseURL=g.baseURL,this.timeout=g.timeout??Ro.DEFAULT_TIMEOUT,this.logger=g.logger??console;let A="warn";this.logLevel=A,this.logLevel=oo(g.logLevel,"ClientOptions.logLevel",this)??oo(pe("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??A,this.fetchOptions=g.fetchOptions,this.maxRetries=g.maxRetries??2,this.fetch=g.fetch??Zs(),k(this,Rs,Ni,"f");let I=r?void 0:pe("OPENAI_CUSTOM_HEADERS");if(I){let b={};for(let _ of I.split(`
28
+ `)){let m=_.indexOf(":");m>=0&&(b[_.substring(0,m).trim()]=_.substring(m+1).trim())}g.defaultHeaders=w([b,g.defaultHeaders])}this._options=g,this._provider=h,u&&(this._workloadIdentityAuth=new en(u,this.fetch)),this.apiKey=typeof n=="string"?n:null,this.adminAPIKey=o,this.organization=i,this.project=a,this.webhookSecret=c}withOptions(e){let r=this._options.provider,s=e.provider??r,n={...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._options.apiKey,adminAPIKey:this.adminAPIKey,workloadIdentity:this._options.workloadIdentity,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret};return s&&(delete n.apiKey,delete n.adminAPIKey,delete n.workloadIdentity,delete n.baseURL,s!==r&&(delete n.organization,delete n.project,delete n.defaultHeaders)),new this.constructor({...n,...e,provider:s})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:r},s={bearerAuth:!0,adminAPIKeyAuth:!0}){if(!(e.get("authorization")||e.get("api-key"))&&!(r.has("authorization")||r.has("api-key"))&&!(this._workloadIdentityAuth&&s.bearerAuth))throw new Error('Could not resolve authentication method. Expected either apiKey or adminAPIKey to be set. Or for one of the "Authorization" or "api-key" headers to be explicitly omitted')}async authHeaders(e,r={bearerAuth:!0,adminAPIKeyAuth:!0}){return w([r.bearerAuth?await this.bearerAuth(e):null,r.adminAPIKeyAuth?await this.adminAPIKeyAuth(e):null])}async bearerAuth(e){if(this._workloadIdentityAuth)return w([{Authorization:`Bearer ${await this._workloadIdentityAuth.getToken()}`}]);if(this.apiKey!=null)return w([{Authorization:`Bearer ${this.apiKey}`}])}async adminAPIKeyAuth(e){if(this.adminAPIKey!=null)return w([{Authorization:`Bearer ${this.adminAPIKey}`}])}stringifyQuery(e){return qi(e)}getUserAgent(){return`${this.constructor.name}/JS ${Ke}`}defaultIdempotencyKey(){return`stainless-node-retry-${Hn()}`}makeStatusError(e,r,s,n){return U.generate(e,r,s,n)}async _callApiKey(){if(this._provider)return!1;let e=this._options.apiKey;if(typeof e!="function")return!1;let r;try{r=await e()}catch(s){throw s instanceof P?s:new P(`Failed to get token from 'apiKey' function: ${s.message}`,{cause:s})}if(typeof r!="string"||!r)throw new P(`Expected 'apiKey' function argument to return a string but it returned ${r}`);return this.apiKey=r,!0}buildURL(e,r,s){let n=!d(this,Co,"m",Ua).call(this)&&s||this.baseURL,o=Oi(e)?new URL(e):new URL(n+(n.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),i=this.defaultQuery(),a=Object.fromEntries(o.searchParams);return(!Vn(i)||!Vn(a))&&(r={...a,...i,...r}),typeof r=="object"&&r&&!Array.isArray(r)&&(o.search=this.stringifyQuery(r)),o.toString()}async prepareOptions(e){if(this._provider)return;(e.__security??{bearerAuth:!0}).bearerAuth&&await this._callApiKey()}async prepareRequest(e,{url:r,options:s}){}get(e,r){return this.methodRequest("get",e,r)}post(e,r){return this.methodRequest("post",e,r)}patch(e,r){return this.methodRequest("patch",e,r)}put(e,r){return this.methodRequest("put",e,r)}delete(e,r){return this.methodRequest("delete",e,r)}methodRequest(e,r,s){return this.request(Promise.resolve(s).then(n=>({method:e,path:r,...n})))}request(e,r=null){return new ot(this,this.makeRequest(e,r,void 0))}async makeRequest(e,r,s){let n=await e,o=n.maxRetries??this.maxRetries;r==null&&(r=o),await this.prepareOptions(n);let{req:i,url:a,timeout:c}=await this.buildRequest(n,{retryCount:o-r});await this.prepareRequest(i,{url:a,options:n}),await this._provider?.prepareRequest?.(i,{url:a,options:n});let u="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),f=s===void 0?"":`, retryOf: ${s}`,h=Date.now();if(K(this).debug(`[${u}] sending request`,ve({retryOfRequestLogID:s,method:n.method,url:a,options:n,headers:i.headers})),n.signal?.aborted)throw new D;let g=n.__security??{bearerAuth:!0},A=new AbortController,I=await this.fetchWithAuth(a,i,c,A,g).catch(us),b=Date.now();if(I instanceof globalThis.Error){let y=`retrying, ${r} attempts remaining`;if(n.signal?.aborted)throw new D;let O=as(I)||/timed? ?out/i.test(String(I)+("cause"in I?String(I.cause):""));if(r)return K(this).info(`[${u}] connection ${O?"timed out":"failed"} - ${y}`),K(this).debug(`[${u}] connection ${O?"timed out":"failed"} (${y})`,ve({retryOfRequestLogID:s,url:a,durationMs:b-h,message:I.message})),this.retryRequest(n,r,s??u);throw K(this).info(`[${u}] connection ${O?"timed out":"failed"} - error; no more retries left`),K(this).debug(`[${u}] connection ${O?"timed out":"failed"} (error; no more retries left)`,ve({retryOfRequestLogID:s,url:a,durationMs:b-h,message:I.message})),I instanceof st||I instanceof ls?I:O?new ye:new Le({message:ap(I),cause:I})}let _=[...I.headers.entries()].filter(([y])=>y==="x-request-id").map(([y,O])=>", "+y+": "+JSON.stringify(O)).join(""),m=`[${u}${f}${_}] ${i.method} ${a} ${I.ok?"succeeded":"failed"} with status ${I.status} in ${b-h}ms`;if(!I.ok){if(I.status===401&&this._workloadIdentityAuth&&g.bearerAuth&&!n.__metadata?.hasStreamingBody&&!n.__metadata?.workloadIdentityTokenRefreshed)return await Xn(I.body),this._workloadIdentityAuth.invalidateToken(),this.makeRequest({...n,__metadata:{...n.__metadata,workloadIdentityTokenRefreshed:!0}},r,s??u);let y=await this.shouldRetry(I);if(r&&y){let L=`retrying, ${r} attempts remaining`;return await Xn(I.body),K(this).info(`${m} - ${L}`),K(this).debug(`[${u}] response error (${L})`,ve({retryOfRequestLogID:s,url:I.url,status:I.status,headers:I.headers,durationMs:b-h})),this.retryRequest(n,r,s??u,I.headers)}let O=y?"error; no more retries left":"error; not retryable";K(this).info(`${m} - ${O}`);let R=await I.text().catch(L=>us(L).message),N=Ti(R),z=N?void 0:R;throw K(this).debug(`[${u}] response error (${O})`,ve({retryOfRequestLogID:s,url:I.url,status:I.status,headers:I.headers,message:z,durationMs:Date.now()-h})),this.makeStatusError(I.status,N,z,I.headers)}return K(this).info(m),K(this).debug(`[${u}] response start`,ve({retryOfRequestLogID:s,url:I.url,status:I.status,headers:I.headers,durationMs:b-h})),{response:I,options:n,controller:A,requestLogID:u,retryOfRequestLogID:s,startTime:h}}getAPIList(e,r,s){return this.requestAPIList(r,s&&"then"in s?s.then(n=>({method:"get",path:e,...n})):{method:"get",path:e,...s})}requestAPIList(e,r){let s=this.makeRequest(r,null,void 0);return new fs(this,s,e)}async fetchWithAuth(e,r,s,n,o={bearerAuth:!0,adminAPIKeyAuth:!0}){if(this._workloadIdentityAuth&&o.bearerAuth){let a=r.headers,c=a.get("Authorization");if(!c||c===`Bearer ${ip}`){let u=await this._workloadIdentityAuth.getToken();a.set("Authorization",`Bearer ${u}`)}}return await this.fetchWithTimeout(e,r,s,n)}async fetchWithTimeout(e,r,s,n){let{signal:o,method:i,...a}=r||{},c=this._makeAbort(n);o&&o.addEventListener("abort",c,{once:!0});let u=setTimeout(c,s),f=globalThis.ReadableStream&&a.body instanceof globalThis.ReadableStream||typeof a.body=="object"&&a.body!==null&&Symbol.asyncIterator in a.body,h={signal:n.signal,...f?{duplex:"half"}:{},method:"GET",...a};i&&(h.method=i.toUpperCase());try{return await this.fetch.call(void 0,e,h)}finally{clearTimeout(u)}}async shouldRetry(e){let r=e.headers.get("x-should-retry");return r==="true"?!0:r==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,r,s,n){let o,i=n?.get("retry-after-ms");if(i){let c=parseFloat(i);Number.isNaN(c)||(o=c)}let a=n?.get("retry-after");if(a&&!o){let c=parseFloat(a);Number.isNaN(c)?o=Date.parse(a)-Date.now():o=c*1e3}if(o===void 0){let c=e.maxRetries??this.maxRetries;o=this.calculateDefaultRetryTimeoutMillis(r,c)}return await Ie(o),this.makeRequest(e,r-1,s)}calculateDefaultRetryTimeoutMillis(e,r){let o=r-e,i=Math.min(.5*Math.pow(2,o),8),a=1-Math.random()*.25;return i*a*1e3}async buildRequest(e,{retryCount:r=0}={}){let s={...e},{method:n,path:o,query:i,defaultBaseURL:a}=s,c=this.buildURL(o,i,a);"timeout"in s&&vi("timeout",s.timeout),s.timeout=s.timeout??this.timeout;let{bodyHeaders:u,body:f,isStreamingBody:h}=this.buildBody({options:s});h&&(e.__metadata={...e.__metadata,hasStreamingBody:!0});let g=await this.buildHeaders({options:e,method:n,bodyHeaders:u,retryCount:r});return{req:{method:n,headers:g,...s.signal&&{signal:s.signal},...globalThis.ReadableStream&&f instanceof globalThis.ReadableStream&&{duplex:"half"},...f&&{body:f},...this.fetchOptions??{},...s.fetchOptions??{}},url:c,timeout:s.timeout}}async buildHeaders({options:e,method:r,bodyHeaders:s,retryCount:n}){let o={};this.idempotencyHeader&&r!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),o[this.idempotencyHeader]=e.idempotencyKey);let i=w([o,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(n),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...$i(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},this._provider?void 0:await this.authHeaders(e,e.__security??{bearerAuth:!0}),this._options.defaultHeaders,s,e.headers]);return this._provider||this.validateHeaders(i,e.__security??{bearerAuth:!0}),i.values}_makeAbort(e){return()=>e.abort()}buildBody({options:e}){let{body:r,headers:s}=e;if(!r)return r===void 0&&"body"in e?{...d(this,Rs,"f").call(this,{body:r,headers:w([s])}),isStreamingBody:!1}:{bodyHeaders:void 0,body:void 0,isStreamingBody:!1};let n=w([s]),o=typeof globalThis.ReadableStream<"u"&&r instanceof globalThis.ReadableStream,i=!o&&(typeof r=="string"||r instanceof ArrayBuffer||ArrayBuffer.isView(r)||typeof globalThis.Blob<"u"&&r instanceof globalThis.Blob||r instanceof URLSearchParams||r instanceof FormData);return ArrayBuffer.isView(r)||r instanceof ArrayBuffer||r instanceof DataView||typeof r=="string"&&n.values.has("content-type")||globalThis.Blob&&r instanceof globalThis.Blob||r instanceof FormData||r instanceof URLSearchParams||o?{bodyHeaders:void 0,body:r,isStreamingBody:!i}:typeof r=="object"&&(Symbol.asyncIterator in r||Symbol.iterator in r&&"next"in r&&typeof r.next=="function")?{bodyHeaders:void 0,body:Vs(r),isStreamingBody:!0}:typeof r=="object"&&n.values.get("content-type")==="application/x-www-form-urlencoded"?{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(r),isStreamingBody:!1}:{...d(this,Rs,"f").call(this,{body:r,headers:n}),isStreamingBody:!1}}};Ro=v,Rs=new WeakMap,Co=new WeakSet,Ua=function(){return this._provider!==void 0||this.baseURL!=="https://api.openai.com/v1"};v.OpenAI=Ro;v.DEFAULT_TIMEOUT=6e5;v.OpenAIError=P;v.APIError=U;v.APIConnectionError=Le;v.APIConnectionTimeoutError=ye;v.APIUserAbortError=D;v.NotFoundError=Bt;v.ConflictError=qt;v.RateLimitError=Ht;v.BadRequestError=Lt;v.AuthenticationError=Kt;v.InternalServerError=Zt;v.PermissionDeniedError=Ft;v.UnprocessableEntityError=Wt;v.InvalidWebhookSignatureError=Ae;v.toFile=_s;v.Completions=gt;v.Chat=We;v.Embeddings=At;v.Files=bt;v.Images=Ot;v.Audio=we;v.Moderations=vt;v.Models=kt;v.FineTuning=fe;v.Graders=et;v.VectorStores=Me;v.Webhooks=Et;v.Beta=de;v.Batches=mt;v.Uploads=tt;v.Admin=Ze;v.Responses=Oe;v.Realtime=Se;v.Conversations=Ye;v.Evals=Qe;v.Containers=Xe;v.Skills=$e;v.Videos=Rt;function ap(t){if(up(t))return"Connection error. This may be caused by passing an undici dispatcher, such as ProxyAgent, that is incompatible with the fetch implementation. If you are using undici's ProxyAgent, pass the fetch implementation from the same undici package: import { fetch, ProxyAgent } from 'undici'; new OpenAI({ fetch, fetchOptions: { dispatcher: new ProxyAgent(...) } });"}function up(t){let e=t;for(let r=0;r<8&&e&&typeof e=="object";r++){let s=e;if(s.code==="UND_ERR_INVALID_ARG"&&typeof s.message=="string"&&s.message.includes("invalid onRequestStart method"))return!0;e=s.cause}return!1}function lp(t){return!!(String(t).includes("context_length_exceeded")||"message"in t&&typeof t.message=="string"&&(t.message.includes("Input tokens exceed the configured limit")||t.message.includes("exceeds the context window")||t.message.includes("maximum context length")))}function le(t){if(!t||typeof t!="object")return t;let e;return t.constructor.name===ye.name&&"message"in t&&typeof t.message=="string"?(e=new Error(t.message),e.name="TimeoutError"):t.constructor.name===D.name&&"message"in t&&typeof t.message=="string"?(e=new Error(t.message),e.name="AbortError"):lp(t)?e=Yo.fromError(t):"status"in t&&t.status===400&&"message"in t&&typeof t.message=="string"&&t.message.includes("tool_calls")?e=is(t,"INVALID_TOOL_RESULTS"):"status"in t&&t.status===401?e=is(t,"MODEL_AUTHENTICATION"):"status"in t&&t.status===429?e=is(t,"MODEL_RATE_LIMIT"):"status"in t&&t.status===404?e=is(t,"MODEL_NOT_FOUND"):e=t,e}var he=t=>t();function Ne(t){return t?!!(/^o\d/.test(t??"")||t.startsWith("gpt-5")&&!t.startsWith("gpt-5-chat")):!1}function cp(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 xn(t){return t.metadata?.filename??t.metadata?.name??t.metadata?.title}var pp="LC_AUTOGENERATED";function St(t){let e=t.metadata?.filename??t.metadata?.name??t.metadata?.title;return e||(console.warn("OpenAI may require a filename for file uploads. Specify a filename in the content block metadata, e.g.: { type: 'file', mimeType: '...', data: '...', metadata: { filename: 'my-file.pdf' } }. Using placeholder filename 'LC_AUTOGENERATED'."),pp)}function ze(t){let 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(!Ks.isInstance(t))throw new Error("Invalid generic chat message");return cp(t);default:throw new Error(`Unknown message type: ${e}`)}}function Da(t){return!!(t.includes("gpt-5.2-pro")||t.includes("gpt-5.4-pro")||t.includes("gpt-5.5-pro")||t.includes("codex"))}function je(t){let{azureOpenAIApiDeploymentName:e,azureOpenAIApiInstanceName:r,azureOpenAIApiKey:s,azureOpenAIBasePath:n,baseURL:o,azureADTokenProvider:i,azureOpenAIEndpoint:a}=t;if((s||i)&&n&&e)return`${n}/${e}`;if((s||i)&&a&&e)return`${a}/openai/deployments/${e}`;if(s||i){if(!r)throw new Error("azureOpenAIApiInstanceName is required when using azureOpenAIApiKey");if(!e)throw new Error("azureOpenAIApiDeploymentName is a required parameter when using azureOpenAIApiKey");return`https://${r}.openai.azure.com/openai/deployments/${e}`}return o}function So(t){return typeof Headers<"u"&&t!==null&&typeof t=="object"&&Object.prototype.toString.call(t)==="[object Headers]"}function La(t){let e=he(()=>{if(So(t))return t;if(Array.isArray(t))return new Headers(t);if(typeof t=="object"&&t!==null&&"values"in t&&So(t.values))return t.values;if(typeof t=="object"&&t!==null){let r=Object.entries(t).filter(([,s])=>typeof s=="string").map(([s,n])=>[s,n]);return new Headers(r)}return new Headers});return Object.fromEntries(e.entries())}function Ka(){let t=Xo();return(t==="node"||t==="deno")&&(t=`(${t}/${process.version}; ${process.platform}; ${process.arch})`),t}function Ue(t,e=!1,r="1.0.0"){let s=La(t),n=Ka(),o=`langchainjs${e?"-azure":""}-openai`;return{...s,"User-Agent":s["User-Agent"]?`${o}/${r} (${n})${s["User-Agent"]}`:`${o}/${r} (${n})`}}function Fa(t,e){let r;return Ws(t)?r=yi(t):r=t,e?.strict!==void 0&&(r.function.strict=e.strict),r}function mp(t){return t.anyOf!==void 0&&Array.isArray(t.anyOf)}function Ba(t){let e=["namespace functions {",""];for(let r of t)r.description&&e.push(`// ${r.description}`),Object.keys(r.parameters.properties??{}).length>0?(e.push(`type ${r.name} = (_: {`),e.push(qa(r.parameters,0)),e.push("}) => any;")):e.push(`type ${r.name} = () => any;`),e.push("");return e.push("} // namespace functions"),e.join(`
29
+ `)}function qa(t,e){let r=[];for(let[s,n]of Object.entries(t.properties??{}))n.description&&e<2&&r.push(`// ${n.description}`),t.required?.includes(s)?r.push(`${s}: ${wn(n,e)},`):r.push(`${s}?: ${wn(n,e)},`);return r.map(s=>" ".repeat(e)+s).join(`
30
+ `)}function wn(t,e){if(mp(t))return t.anyOf.map(r=>wn(r,e)).join(" | ");switch(t.type){case"string":return t.enum?t.enum.map(r=>`"${r}"`).join(" | "):"string";case"number":return t.enum?t.enum.map(r=>`${r}`).join(" | "):"number";case"integer":return t.enum?t.enum.map(r=>`${r}`).join(" | "):"number";case"boolean":return"boolean";case"null":return"null";case"object":return["{",qa(t,e+2),"}"].join(`
31
+ `);case"array":return t.items?`${wn(t.items,e)}[]`:"any[]";default:return""}}function Pn(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 es(t){return"type"in t&&t.type!=="function"}function Wa(t){return typeof t=="object"&&t!==null&&"extras"in t&&typeof t.extras=="object"&&t.extras!==null&&"providerToolDefinition"in t.extras&&typeof t.extras.providerToolDefinition=="object"&&t.extras.providerToolDefinition!==null}function Ha(t){return t!=null&&typeof t=="object"&&"type"in t&&t.type!=="function"}function $t(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 On(t){return"type"in t&&t.type==="custom"&&"custom"in t&&typeof t.custom=="object"&&t.custom!==null}function Za(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 Va(t){if(t.type==="computer_call")return{...t,type:"tool_call",call_id:t.id,id:t.call_id,name:"computer_use",isComputerTool:!0,args:{action:t.action}}}function Ja(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="tool_call"&&"isComputerTool"in t&&t.isComputerTool===!0}function Ga(t,e){return typeof t!="object"||t===null||!("type"in t)||t.type!=="tool_call"?!1:!!("isCustomTool"in t&&t.isCustomTool===!0||e&&"id"in t&&typeof t.id=="string"&&t.id in e)}function Xa(t){let 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 Ya(t){let 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()}}}var eu=Symbol("Let zodToJsonSchema decide on which parser to use"),Qa={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"},tu=t=>typeof t=="string"?{...Qa,basePath:["#"],definitions:{},name:t}:{...Qa,basePath:["#"],definitions:{},...t};var Es=t=>"_def"in t?t._def:t;function ru(t){if(!t)return!0;for(let e in t)return!1;return!0}var su=t=>{let e=tu(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,currentPath:r,propertyPath:void 0,seenRefs:new Set,seen:new Map(Object.entries(e.definitions).map(([s,n])=>[Es(n),{def:Es(n),path:[...e.basePath,e.definitionPath,s],jsonSchema:void 0}]))}};function $o(t,e,r,s){s?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function M(t,e,r,s,n){t[e]=r,$o(t,e,s,n)}function nu(){return{}}function ou(t,e){let r={type:"array"};return t.type?._def?.typeName!==E.ZodAny&&(r.items=T(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&M(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&M(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(M(r,"minItems",t.exactLength.value,t.exactLength.message,e),M(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}function iu(t,e){let r={type:"integer",format:"int64"};if(!t.checks)return r;for(let s of t.checks)switch(s.kind){case"min":e.target==="jsonSchema7"?s.inclusive?M(r,"minimum",s.value,s.message,e):M(r,"exclusiveMinimum",s.value,s.message,e):(s.inclusive||(r.exclusiveMinimum=!0),M(r,"minimum",s.value,s.message,e));break;case"max":e.target==="jsonSchema7"?s.inclusive?M(r,"maximum",s.value,s.message,e):M(r,"exclusiveMaximum",s.value,s.message,e):(s.inclusive||(r.exclusiveMaximum=!0),M(r,"maximum",s.value,s.message,e));break;case"multipleOf":M(r,"multipleOf",s.value,s.message,e);break}return r}function au(){return{type:"boolean"}}function uu(t,e,r){return T(t.type._def,e,r)}var lu=(t,e,r)=>T(t.innerType._def,e,r);function Mo(t,e,r){let s=r??e.dateStrategy;if(Array.isArray(s))return{anyOf:s.map((n,o)=>Mo(t,e,n))};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 dp(t,e)}}var dp=(t,e)=>{let r={type:"integer",format:"unix-time"};if(e.target==="openApi3")return r;for(let s of t.checks)switch(s.kind){case"min":M(r,"minimum",s.value,s.message,e);break;case"max":M(r,"maximum",s.value,s.message,e);break}return r};function cu(t,e,r){return{...T(t.innerType._def,e,r),default:t.defaultValue()}}function pu(t,e,r){return e.effectStrategy==="input"?T(t.schema._def,e,r):{}}function mu(t){return{type:"string",enum:[...t.values]}}var fp=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function du(t,e){let r=[T(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),T(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(o=>!!o),s=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,n=[];return r.forEach(o=>{if(fp(o))n.push(...o.allOf),o.unevaluatedProperties===void 0&&(s=void 0);else{let i=o;if("additionalProperties"in o&&o.additionalProperties===!1){let{additionalProperties:a,...c}=o;i=c}else s=void 0;n.push(i)}}),n.length?{allOf:n,...s}:void 0}function fu(t,e){let r=typeof t.value;return r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:r==="bigint"?"integer":r,enum:[t.value]}:{type:r==="bigint"?"integer":r,const:t.value}}var No,Mt={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:()=>(No===void 0&&(No=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),No),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/};function kn(t,e){let r={type:"string"};function s(n){return e.patternStrategy==="escape"?hp(n):n}if(t.checks)for(let n of t.checks)switch(n.kind){case"min":M(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":M(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"email":switch(e.emailStrategy){case"format:email":_e(r,"email",n.message,e);break;case"format:idn-email":_e(r,"idn-email",n.message,e);break;case"pattern:zod":ge(r,Mt.email,n.message,e);break}break;case"url":_e(r,"uri",n.message,e);break;case"uuid":_e(r,"uuid",n.message,e);break;case"regex":ge(r,n.regex,n.message,e);break;case"cuid":ge(r,Mt.cuid,n.message,e);break;case"cuid2":ge(r,Mt.cuid2,n.message,e);break;case"startsWith":ge(r,RegExp(`^${s(n.value)}`),n.message,e);break;case"endsWith":ge(r,RegExp(`${s(n.value)}$`),n.message,e);break;case"datetime":_e(r,"date-time",n.message,e);break;case"date":_e(r,"date",n.message,e);break;case"time":_e(r,"time",n.message,e);break;case"duration":_e(r,"duration",n.message,e);break;case"length":M(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),M(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{ge(r,RegExp(s(n.value)),n.message,e);break}case"ip":{n.version!=="v6"&&_e(r,"ipv4",n.message,e),n.version!=="v4"&&_e(r,"ipv6",n.message,e);break}case"emoji":ge(r,Mt.emoji,n.message,e);break;case"ulid":{ge(r,Mt.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{_e(r,"binary",n.message,e);break}case"contentEncoding:base64":{M(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{ge(r,Mt.base64,n.message,e);break}}break}case"nanoid":ge(r,Mt.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}var hp=t=>Array.from(t).map(e=>/[a-zA-Z0-9]/.test(e)?e:`\\${e}`).join(""),_e=(t,e,r,s)=>{t.format||t.anyOf?.some(n=>n.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,...r&&s.errorMessages&&{errorMessage:{format:r}}})):M(t,"format",e,r,s)},ge=(t,e,r,s)=>{t.pattern||t.allOf?.some(n=>n.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:hu(e,s),...r&&s.errorMessages&&{errorMessage:{pattern:r}}})):M(t,"pattern",hu(e,s),r,s)},hu=(t,e)=>{let r=typeof t=="function"?t():t;if(!e.applyRegexFlags||!r.flags)return r.source;let s={i:r.flags.includes("i"),m:r.flags.includes("m"),s:r.flags.includes("s")},n=s.i?r.source.toLowerCase():r.source,o="",i=!1,a=!1,c=!1;for(let u=0;u<n.length;u++){if(i){o+=n[u],i=!1;continue}if(s.i){if(a){if(n[u].match(/[a-z]/)){c?(o+=n[u],o+=`${n[u-2]}-${n[u]}`.toUpperCase(),c=!1):n[u+1]==="-"&&n[u+2]?.match(/[a-z]/)?(o+=n[u],c=!0):o+=`${n[u]}${n[u].toUpperCase()}`;continue}}else if(n[u].match(/[a-z]/)){o+=`[${n[u]}${n[u].toUpperCase()}]`;continue}}if(s.m){if(n[u]==="^"){o+=`(^|(?<=[\r
32
32
  ]))`;continue}else if(n[u]==="$"){o+=`($|(?=[\r
33
33
  ]))`;continue}}if(s.s&&n[u]==="."){o+=a?`${n[u]}\r
34
34
  `:`[${n[u]}\r
35
- ]`;continue}o+=n[u],n[u]==="\\"?i=!0:a&&n[u]==="]"?a=!1:!a&&n[u]==="["&&(a=!0)}try{let u=new RegExp(o)}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`),r.source}return o};function vn(t,e){if(e.target==="openApi3"&&t.keyType?._def.typeName===E.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((s,n)=>({...s,[n]:T(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",n]})??{}}),{}),additionalProperties:!1};let r={type:"object",additionalProperties:T(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??{}};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===E.ZodString&&t.keyType._def.checks?.length){let s=Object.entries(kn(t.keyType._def,e)).reduce((n,[o,i])=>o==="type"?n:{...n,[o]:i},{});return{...r,propertyNames:s}}else if(t.keyType?._def.typeName===E.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};return r}function du(t,e){if(e.mapStrategy==="record")return vn(t,e);let r=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:[r,s],minItems:2,maxItems:2}}}function fu(t){let e=t.values,s=Object.keys(t.values).filter(o=>typeof e[e[o]]!="number").map(o=>e[o]),n=Array.from(new Set(s.map(o=>typeof o)));return{type:n.length===1?n[0]==="string"?"string":"number":["string","number"],enum:s}}function hu(){return{not:{}}}function _u(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Ss={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function yu(t,e){if(e.target==="openApi3")return gu(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(s=>s._def.typeName in Ss&&(!s._def.checks||!s._def.checks.length))){let s=r.reduce((n,o)=>{let i=Ss[o._def.typeName];return i&&!n.includes(i)?[...n,i]:n},[]);return{type:s.length>1?s:s[0]}}else if(r.every(s=>s._def.typeName==="ZodLiteral"&&!s.description)){let s=r.reduce((n,o)=>{let i=typeof o._def.value;switch(i){case"string":case"number":case"boolean":return[...n,i];case"bigint":return[...n,"integer"];case"object":if(o._def.value===null)return[...n,"null"];default:return n}},[]);if(s.length===r.length){let n=s.filter((o,i,a)=>a.indexOf(o)===i);return{type:n.length>1?n:n[0],enum:r.reduce((o,i)=>o.includes(i._def.value)?o:[...o,i._def.value],[])}}}else if(r.every(s=>s._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((s,n)=>[...s,...n._def.values.filter(o=>!s.includes(o))],[])};return gu(t,e)}var gu=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((s,n)=>T(s._def,{...e,currentPath:[...e.currentPath,"anyOf",`${n}`]})).filter(s=>!!s&&(!e.strictUnions||typeof s=="object"&&Object.keys(s).length>0));return r.length?{anyOf:r}:void 0};function Au(t,e,r){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:Ss[t.innerType._def.typeName],nullable:!0}:{type:[Ss[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=T(t.innerType._def,{...e,currentPath:[...e.currentPath]},r);return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let s=T(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return s&&{anyOf:[s,{type:"null"}]}}function Iu(t,e){let r={type:"number"};if(!t.checks)return r;for(let s of t.checks)switch(s.kind){case"int":r.type="integer",$o(r,"type",s.message,e);break;case"min":e.target==="jsonSchema7"?s.inclusive?M(r,"minimum",s.value,s.message,e):M(r,"exclusiveMinimum",s.value,s.message,e):(s.inclusive||(r.exclusiveMinimum=!0),M(r,"minimum",s.value,s.message,e));break;case"max":e.target==="jsonSchema7"?s.inclusive?M(r,"maximum",s.value,s.message,e):M(r,"exclusiveMaximum",s.value,s.message,e):(s.inclusive||(r.exclusiveMaximum=!0),M(r,"maximum",s.value,s.message,e));break;case"multipleOf":M(r,"multipleOf",s.value,s.message,e);break}return r}function _p(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 bu(t,e){let r={type:"object",...Object.entries(t.shape()).reduce((s,[n,o])=>{if(o===void 0||o._def===void 0)return s;let i=[...e.currentPath,"properties",n],a=T(o._def,{...e,currentPath:i,propertyPath:i});if(a===void 0)return s;if(e.openaiStrictMode&&o.isOptional()&&!o.isNullable()&&typeof o._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,[n]:a},required:o.isOptional()&&!e.openaiStrictMode?s.required:[...s.required,n]}},{properties:{},required:[]}),additionalProperties:_p(t,e)};return r.required.length||delete r.required,r}var xu=(t,e,r)=>{if(e.propertyPath&&e.currentPath.slice(0,e.propertyPath.length).toString()===e.propertyPath.toString())return T(t.innerType._def,{...e,currentPath:e.currentPath},r);let s=T(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]},r);return s?{anyOf:[{not:{}},s]}:{}};var wu=(t,e,r)=>{if(e.pipeStrategy==="input")return T(t.in._def,e,r);if(e.pipeStrategy==="output")return T(t.out._def,e,r);let s=T(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=T(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",s?"1":"0"]});return{allOf:[s,n].filter(o=>o!==void 0)}};function Pu(t,e,r){return T(t.type._def,e,r)}function Ou(t,e){let s={type:"array",uniqueItems:!0,items:T(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&M(s,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&M(s,"maxItems",t.maxSize.value,t.maxSize.message,e),s}function ku(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,s)=>T(r._def,{...e,currentPath:[...e.currentPath,"items",`${s}`]})).reduce((r,s)=>s===void 0?r:[...r,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((r,s)=>T(r._def,{...e,currentPath:[...e.currentPath,"items",`${s}`]})).reduce((r,s)=>s===void 0?r:[...r,s],[])}}function vu(){return{not:{}}}function Tu(){return{}}var Cu=(t,e,r)=>T(t.innerType._def,e,r);function T(t,e,r=!1){let s=e.seen.get(t);if(e.override){let o=e.override?.(t,e,s,r);if(o!==Xa)return o}if(s&&!r){let o=gp(s,e);if(o!==void 0)return"$ref"in o&&e.seenRefs.add(o.$ref),o}let n={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,n);try{let o=Ip(t,t.typeName,e,r);return o&&bp(t,e,o),n.jsonSchema=o,o}finally{r&&s&&e.seen.set(t,s)}}var gp=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"extract-to-root":let r=t.path.slice(e.basePath.length+1).map((s,n)=>n===0?s:yp(s)).join("_");return r!==e.name&&e.nameStrategy==="duplicate-ref"&&(e.definitions[r]=t.def),{$ref:[...e.basePath,e.definitionPath,r].join("/")};case"relative":return{$ref:Ap(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((s,n)=>e.currentPath[n]===s)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),{}):e.$refStrategy==="seen"?{}:void 0}},Ru="_x_",yp=t=>{if(/^[A-Za-z0-9_-]*$/.test(t)&&!t.startsWith(Ru))return t;let e=Ru;for(let r=0;r<t.length;r++)e+=t.charCodeAt(r).toString(16).padStart(4,"0");return e},Ap=(t,e)=>{let r=0;for(;r<t.length&&r<e.length&&t[r]===e[r];r++);return[(t.length-r).toString(),...e.slice(r)].join("/")},Ip=(t,e,r,s)=>{switch(e){case E.ZodString:return kn(t,r);case E.ZodNumber:return Iu(t,r);case E.ZodObject:return bu(t,r);case E.ZodBigInt:return su(t,r);case E.ZodBoolean:return nu();case E.ZodDate:return Mo(t,r);case E.ZodUndefined:return vu();case E.ZodNull:return _u(r);case E.ZodArray:return ru(t,r);case E.ZodUnion:case E.ZodDiscriminatedUnion:return yu(t,r);case E.ZodIntersection:return cu(t,r);case E.ZodTuple:return ku(t,r);case E.ZodRecord:return vn(t,r);case E.ZodLiteral:return pu(t,r);case E.ZodEnum:return lu(t);case E.ZodNativeEnum:return fu(t);case E.ZodNullable:return Au(t,r,s);case E.ZodOptional:return xu(t,r,s);case E.ZodMap:return du(t,r);case E.ZodSet:return Ou(t,r);case E.ZodLazy:return T(t.getter()._def,r,s);case E.ZodPromise:return Pu(t,r,s);case E.ZodNaN:case E.ZodNever:return hu();case E.ZodEffects:return uu(t,r,s);case E.ZodAny:return tu();case E.ZodUnknown:return Tu();case E.ZodDefault:return au(t,r,s);case E.ZodBranded:return ou(t,r,s);case E.ZodReadonly:return Cu(t,r,s);case E.ZodCatch:return iu(t,r,s);case E.ZodPipeline:return wu(t,r,s);case E.ZodFunction:case E.ZodVoid:case E.ZodSymbol:return;default:return(n=>{})(e)}},bp=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r);var zo=(t,e)=>{let r=eu(e),s=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,n=T(t._def,s===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,s]},!1)??{},o=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;o!==void 0&&(n.title=o);let i=(()=>{if(Qa(r.definitions))return;let c={},u=new Set;for(let f=0;f<500;f++){let h=Object.entries(r.definitions).filter(([g])=>!u.has(g));if(h.length===0)break;for(let[g,A]of h)c[g]=T(Es(A),{...r,currentPath:[...r.basePath,r.definitionPath,g]},!0)??{},u.add(g)}return c})(),a=s===void 0?i?{...n,[r.definitionPath]:i}:n:r.nameStrategy==="duplicate-ref"?{...n,...i||r.seenRefs.size?{[r.definitionPath]:{...i,...r.seenRefs.size?{[s]:n}:void 0}}:void 0}:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,s].join("/"),[r.definitionPath]:{...i,[s]:n}};return r.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":r.target==="jsonSchema2019-09"&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),a};function Eu(t){if(t.type!=="object")throw new Error(`Root schema must have type: 'object' but got type: ${t.type?`'${t.type}'`:"undefined"}`);let e=structuredClone(t);return Le(e,[],e)}function jo(t){if(typeof t=="boolean")return!1;if(t.type==="null")return!0;for(let e of t.oneOf??[])if(jo(e))return!0;for(let e of t.anyOf??[])if(jo(e))return!0;return!1}function Le(t,e,r){if(typeof t=="boolean")throw new TypeError(`Expected object schema but got boolean; path=${e.join("/")}`);if(!Nt(t))throw new TypeError(`Expected ${JSON.stringify(t)} to be an object; path=${e.join("/")}`);let s=t.$defs;if(Nt(s))for(let[g,A]of Object.entries(s))Le(A,[...e,"$defs",g],r);let n=t.definitions;if(Nt(n))for(let[g,A]of Object.entries(n))Le(A,[...e,"definitions",g],r);t.type==="object"&&!("additionalProperties"in t)&&(t.additionalProperties=!1);let i=t.required??[],a=t.properties;if(Nt(a)){for(let[g,A]of Object.entries(a))if(!jo(A)&&!i.includes(g))throw new Error(`Zod field at \`${[...e,"properties",g].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(a),t.properties=Object.fromEntries(Object.entries(a).map(([g,A])=>[g,Le(A,[...e,"properties",g],r)]))}let c=t.items;Nt(c)&&(t.items=Le(c,[...e,"items"],r));let u=t.anyOf;Array.isArray(u)&&(t.anyOf=u.map((g,A)=>Le(g,[...e,"anyOf",String(A)],r)));let f=t.allOf;if(Array.isArray(f))if(f.length===1){let g=Le(f[0],[...e,"allOf","0"],r);Object.assign(t,g),delete t.allOf}else t.allOf=f.map((g,A)=>Le(g,[...e,"allOf",String(A)],r));t.default===null&&delete t.default;let h=t.$ref;if(h&&wp(t,1)){if(typeof h!="string")throw new TypeError(`Received non-string $ref - ${h}; path=${e.join("/")}`);let g=xp(r,h);if(typeof g=="boolean")throw new Error(`Expected \`$ref: ${h}\` to resolve to an object schema but got boolean`);if(!Nt(g))throw new Error(`Expected \`$ref: ${h}\` to resolve to an object but got ${JSON.stringify(g)}`);return Object.assign(t,{...g,...t}),delete t.$ref,Le(t,e,r)}return t}function xp(t,e){if(!e.startsWith("#/"))throw new Error(`Unexpected $ref format ${JSON.stringify(e)}; Does not start with #/`);let r=e.slice(2).split("/"),s=t;for(let n of r){if(!Nt(s))throw new Error(`encountered non-object entry while resolving ${e} - ${JSON.stringify(s)}`);let o=s[n];if(o===void 0)throw new Error(`Key ${n} not found while resolving ${e}`);s=o}return s}function Nt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function wp(t,e){let r=0;for(let s in t)if(r++,r>e)return!0;return!1}function Pp(t,e){return zo(t,{openaiStrictMode:!0,name:e.name,nameStrategy:"duplicate-ref",$refStrategy:"extract-to-root",nullableStrategy:"property"})}function Op(t){return Eu(ii(t,{target:"draft-7",override:({zodSchema:e,jsonSchema:r})=>{let s=e._zod.def;if(s.type==="union"&&"discriminator"in s&&Array.isArray(r.oneOf)){if(r.anyOf!==void 0)throw new Error("Zod discriminated union generated both `anyOf` and `oneOf`, which cannot be represented in an OpenAI strict schema");r.anyOf=r.oneOf,delete r.oneOf}}}))}function kp(t){return"_zod"in t}function Su(t,e,r){return ea({type:"json_schema",json_schema:{...r,name:e,strict:!0,schema:kp(t)?Op(t):Pp(t,{name:e})}},s=>t.parse(JSON.parse(s)))}var $u=["jsonSchema","functionCalling","jsonMode"];function Mu(t,e){if(typeof e<"u"&&!$u.includes(e))throw new Error(`Invalid method: ${e}. Supported methods are: ${$u.join(", ")}`);let r=!t.startsWith("gpt-3")&&!t.startsWith("gpt-4-")&&t!=="gpt-4";if(r&&!e)return"jsonSchema";if(!r&&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 vp(t,e){let r={...t};return Object.defineProperties(r,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:e,enumerable:!1}}),r}function Nu(t,e,r){if(ui(t))return Su(t,e,r);if(ai(t))return vp({type:"json_schema",json_schema:{...r,name:e,strict:!0,schema:Lt(t,{cycles:"ref",reused:"ref",override(s){s.jsonSchema.title=e}})}},s=>oi(t,JSON.parse(s)));throw new Error("Unsupported schema response format")}function zu(t,e){if(e&&typeof e=="object"&&"images"in e&&Array.isArray(e.images)){let r=e.images.filter(s=>typeof s?.image_url?.url=="string").map(s=>({type:"image",url:s.image_url.url}));return[{type:"text",text:t},...r]}return t}var ju={"gpt-4o-2024-11-20":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.3-codex":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-codex":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-pro":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:272e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o-mini":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"text-embedding-ada-002":{maxInputTokens:8192,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1536,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-chat-latest":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"codex-mini-latest":{maxInputTokens:2e5,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.1-codex-max":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o-2024-05-13":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:4096,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.2-chat-latest":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.2-codex":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o3-deep-research":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},o1:{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.1":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o4-mini-deep-research":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.3-codex-spark":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},o3:{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"text-embedding-3-small":{maxInputTokens:8191,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1536,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4.1-nano":{maxInputTokens:1047576,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"text-embedding-3-large":{maxInputTokens:8191,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:3072,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-3.5-turbo":{maxInputTokens:16385,imageInputs:!1,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:4096,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!1,imageUrlInputs:!1,pdfToolMessage:!1,imageToolMessage:!1,toolChoice:!0},"gpt-5.1-codex-mini":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.2":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4.1":{maxInputTokens:1047576,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o3-pro":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4-turbo":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:4096,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o4-mini":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4.1-mini":{maxInputTokens:1047576,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.4":{maxInputTokens:105e4,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o1-preview":{maxInputTokens:128e3,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.4-pro":{maxInputTokens:105e4,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.5":{maxInputTokens:105e4,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:13e4,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.5-pro":{maxInputTokens:105e4,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o1-pro":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.1-codex":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.2-pro":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o3-mini":{maxInputTokens:2e5,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o-2024-08-06":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-mini":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.1-chat-latest":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4":{maxInputTokens:8192,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-nano":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o1-mini":{maxInputTokens:128e3,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0}};function rs(t,e){return typeof t=="string"?{model:t,...e??{}}:t??e}var zt=class extends _i{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;promptCacheRetention;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","reasoning_effort","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","promptCacheRetention","verbosity"]}getLsParams(t){let 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??{});let e=typeof t?.configuration?.apiKey=="string"||typeof t?.configuration?.apiKey=="function"?t?.configuration?.apiKey:void 0;this.apiKey=t?.apiKey??e??pe("OPENAI_API_KEY"),this.organization=t?.configuration?.organization??pe("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.promptCacheRetention=t?.promptCacheRetention??this.promptCacheRetention,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,this._addVersion("@langchain/openai","1.5.3")}_getReasoningParams(t){if(!Ne(this.model))return;let e;return this.reasoning!==void 0&&(e={...e,...this.reasoning}),t?.reasoning!==void 0&&(e={...e,...t.reasoning}),t?.reasoningEffort!==void 0&&e?.effort===void 0&&(e={...e,effort:t.reasoningEffort}),e}_getResponseFormat(t){return t&&t.type==="json_schema"&&t.json_schema.schema&&os(t.json_schema.schema)?Nu(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){let e=je({baseURL:this.clientConfig.baseURL}),r={...this.clientConfig,baseURL:e,timeout:this.timeout,maxRetries:0};r.baseURL||delete r.baseURL,r.defaultHeaders=Ue(r.defaultHeaders),this.client=new v(r)}return{...this.clientConfig,...t}}_convertChatOpenAIToolToCompletionsTool(t,e){return $t(t)?Ja(t.metadata.customTool):Fs(t)?e?.strict!==void 0?{...t,function:{...t.function,strict:e.strict}}:t:La(t,e)}bindTools(t,e){let r;return e?.strict!==void 0?r=e.strict:this.supportsStrictToolCalling!==void 0&&(r=this.supportsStrictToolCalling),this.withConfig({tools:t.map(s=>{if(ts(s)||$t(s))return s;if(Fa(s))return s.extras.providerToolDefinition;let n=this._convertChatOpenAIToolToCompletionsTool(s,{strict:r});return Ws(s)&&s.extras?.defer_loading===!0?{...n,defer_loading:!0}: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,r)=>(r&&r.tokenUsage&&(e.tokenUsage.completionTokens+=r.tokenUsage.completionTokens??0,e.tokenUsage.promptTokens+=r.tokenUsage.promptTokens??0,e.tokenUsage.totalTokens+=r.tokenUsage.totalTokens??0),e),{tokenUsage:{completionTokens:0,promptTokens:0,totalTokens:0}})}async getNumTokensFromMessages(t){let e=0,r=0,s=0;this.model==="gpt-3.5-turbo-0301"?(r=4,s=-1):(r=3,s=1);let n=await Promise.all(t.map(async o=>{let[i,a]=await Promise.all([this.getNumTokens(o.content),this.getNumTokens(ze(o))]),c=o.name!==void 0?s+await this.getNumTokens(o.name):0,u=i+r+a+c,f=o;if(f._getType()==="function"&&(u-=2),f.additional_kwargs?.function_call&&(u+=3),f?.additional_kwargs.function_call?.name&&(u+=await this.getNumTokens(f.additional_kwargs.function_call?.name)),f.additional_kwargs.function_call?.arguments)try{u+=await this.getNumTokens(JSON.stringify(JSON.parse(f.additional_kwargs.function_call?.arguments)))}catch(h){console.error("Error parsing function arguments",h,JSON.stringify(f.additional_kwargs.function_call)),u+=await this.getNumTokens(f.additional_kwargs.function_call?.arguments)}return e+=u,u}));return e+=3,{totalCount:e,countPerMessage:n}}async _getNumTokensFromGenerations(t){return(await Promise.all(t.map(async e=>e.message.additional_kwargs?.function_call?(await this.getNumTokensFromMessages([e.message])).countPerMessage[0]:await this.getNumTokens(e.message.content)))).reduce((e,r)=>e+r,0)}async _getEstimatedTokenCountFromPrompt(t,e,r){let s=(await this.getNumTokensFromMessages(t)).totalCount;if(e&&r!=="auto"){let n=Da(e);s+=await this.getNumTokens(n),s+=9}return e&&t.find(n=>n._getType()==="system")&&(s-=4),r==="none"?s+=1:typeof r=="object"&&(s+=await this.getNumTokens(r.name)+4),s}async moderateContent(t,e){let r=this._getClientOptions(e?.options),s={input:t,model:e?.model??"omni-moderation-latest"};return this.caller.call(async()=>{try{return await this.client.moderations.create(s,r)}catch(n){throw ce(n)}})}get profile(){return ju[this.model]??{}}_getStructuredOutputMethod(t){let 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 r,s,{schema:n,name:o,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'");let a=Mu(this.model,e?.method);if(a==="jsonMode"){s=Bn(n);let c=Lt(n);r=this.withConfig({outputVersion:"v0",response_format:{type:"json_object"},ls_structured_output_format:{kwargs:{method:"json_mode"},schema:{title:o??"extract",...c}}})}else if(a==="jsonSchema"){let c=Lt(n),u={name:o??"extract",description:li(c),schema:os(n)?n:c,strict:e?.strict};if(r=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,...c}}}),os(n)||Kn(n)){let f=Bn(n);s=ci.from(async h=>"parsed"in h.additional_kwargs?h.additional_kwargs.parsed:f.invoke(h.content))}else s=new mi}else{let c=o??"extract",u=Lt(n),f;os(n)||Kn(n)?f={name:c,description:u.description,parameters:u}:typeof n.name=="string"&&typeof n.parameters=="object"&&n.parameters!=null?(f=n,c=n.name):(c=n.title??c,f={name:c,description:n.description??"",parameters:n}),r=this.withConfig({outputVersion:"v0",tools:[{type:"function",function:f}],tool_choice:{type:"function",function:{name:c}},ls_structured_output_format:{kwargs:{method:"function_calling"},schema:{title:c,...u}},...e?.strict!==void 0?{strict:e.strict}:{}}),s=di(n,c)}return fi(r,s,i)}};var Tn={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"){let e=Ln({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`);let r=e.mime_type||t.mime_type||"",s;try{s=Un(r)}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=Un(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"){let e=Ln({dataUrl:t.url}),r=St(t);if(!e)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,filename:r}}}if(t.source_type==="base64"){let e=St(t);return{type:"file",file:{file_data:`data:${t.mime_type??""};base64,${t.data}`,filename:e}}}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`)}},Uo=({message:t,rawResponse:e,includeRawResponse:r})=>{let s=t.tool_calls,n=t.reasoning_content;switch(t.role){case"assistant":{let o=[],i=[];for(let u of s??[])try{o.push(Bs(u,{returnId:!0}))}catch(f){i.push(Dt(u,f.message))}let a={function_call:t.function_call,tool_calls:s};r!==void 0&&(a.__raw_response=e),n!==void 0&&(a.reasoning_content=n);let c={model_provider:"openai",model_name:e.model,...e.system_fingerprint?{usage:{...e.usage},system_fingerprint:e.system_fingerprint}:{}};return t.audio&&(a.audio=t.audio),new ae({content:zu(t.content||"",e.choices?.[0]?.message),tool_calls:o,invalid_tool_calls:i,additional_kwargs:a,response_metadata:c,id:e.id})}default:return new Ks(t.content||"",t.role??"unknown")}},Lo=({delta:t,rawResponse:e,includeRawResponse:r,defaultRole:s})=>{let n=t.role??s,o=t.content??"",i;t.function_call?i={function_call:t.function_call}:t.tool_calls?i={tool_calls:t.tool_calls}:i={},r&&(i.__raw_response=e),t.reasoning_content!==void 0&&(i.reasoning_content=t.reasoning_content),t.audio&&(i.audio={...t.audio,index:e.choices[0].index});let a={model_provider:"openai",usage:{...e.usage}};if(n==="user")return new si({content:o,response_metadata:a});if(n==="assistant"){let c=[];if(Array.isArray(t.tool_calls))for(let u of t.tool_calls)c.push({name:u.function?.name,args:u.function?.arguments,id:u.id,index:u.index,type:"tool_call_chunk"});return new Ut({content:o,tool_call_chunks:c,additional_kwargs:i,id:e.id,response_metadata:a})}else return n==="system"?new Dn({content:o,response_metadata:a}):n==="developer"?new Dn({content:o,response_metadata:a,additional_kwargs:{__openai_role__:"developer"}}):n==="function"?new ri({content:o,additional_kwargs:i,name:t.name,response_metadata:a}):n==="tool"?new Qo({content:o,additional_kwargs:i,tool_call_id:t.tool_call_id,response_metadata:a}):new ti({content:o,role:n,response_metadata:a})},Uu=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){let e=ni(()=>{let[,r]=t.mimeType.split("/");return r==="wav"||r==="mp3"?r:"wav"});return{type:"input_audio",input_audio:{data:t.data.toString(),format:e}}}if(t.type==="file"){if(t.data){let e=St(t);return{type:"file",file:{file_data:`data:${t.mimeType};base64,${t.data}`,filename:e}}}if(t.fileId)return{type:"file",file:{file_id:t.fileId}}}},Lu=({message:t,model:e})=>{let r=ze(t);if(r==="system"&&Ne(e)&&(r="developer"),r==="developer")return{role:"developer",content:t.contentBlocks.filter(n=>n.type==="text")};if(r==="system")return{role:"system",content:t.contentBlocks.filter(n=>n.type==="text")};if(r==="assistant"){let n={role:"assistant",content:t.contentBlocks.filter(o=>o.type==="text")};return ae.isInstance(t)&&t.tool_calls?.length?n.tool_calls=t.tool_calls.map(Fn):t.additional_kwargs.tool_calls!=null&&(n.tool_calls=t.additional_kwargs.tool_calls),n}else{if(r==="tool"&&Ls.isInstance(t))return{role:"tool",tool_call_id:t.tool_call_id,content:t.contentBlocks.filter(n=>n.type==="text")};if(r==="function")return{role:"function",name:t.name??"",content:t.contentBlocks.filter(n=>n.type==="text").join("")}}function*s(n){for(let o of n){o.type==="text"&&(yield{type:"text",text:o.text});let i=Uu(o);i&&(yield i)}}return{role:"user",content:Array.from(s(t.contentBlocks))}},ss=({messages:t,model:e})=>t.flatMap(r=>{if("output_version"in r.response_metadata&&r.response_metadata?.output_version==="v1")return Lu({message:r});let s=ze(r);s==="system"&&Ne(e)&&(s="developer");let n=typeof r.content=="string"?r.content:r.content.flatMap(i=>js(i)?Us(i,Tn):typeof i=="object"&&i!==null&&"type"in i&&i.type==="tool_use"?[]:i),o={role:s,content:n};return r.name!=null&&(o.name=r.name),r.additional_kwargs.function_call!=null&&(o.function_call=r.additional_kwargs.function_call),ae.isInstance(r)&&r.tool_calls?.length?o.tool_calls=r.tool_calls.map(Fn):(r.additional_kwargs.tool_calls!=null&&(o.tool_calls=r.additional_kwargs.tool_calls),Ls.isInstance(r)&&r.tool_call_id!=null&&(o.tool_call_id=r.tool_call_id)),r.additional_kwargs.audio&&typeof r.additional_kwargs.audio=="object"&&"id"in r.additional_kwargs.audio?[o,{role:"assistant",audio:{id:r.additional_kwargs.audio.id}}]:o});var Cn=class extends zt{constructor(t,e){super(rs(t,e))}invocationParams(t,e){let r;t?.strict!==void 0?r=t.strict:this.supportsStrictToolCalling!==void 0&&(r=this.supportsStrictToolCalling),!(this.streaming||e?.streaming)&&t?.response_format?.type==="json_schema"&&r!==!1&&(r=!0);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}});let n={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:r})):void 0,tool_choice:Pn(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,prompt_cache_retention:t?.promptCacheRetention??this.promptCacheRetention,verbosity:t?.verbosity??this.verbosity};t?.prediction!==void 0&&(n.prediction=t.prediction),this.service_tier!==void 0&&(n.service_tier=this.service_tier),t?.service_tier!==void 0&&(n.service_tier=t.service_tier);let o=this._getReasoningParams(t);return o!==void 0&&o.effort!==void 0&&(n.reasoning_effort=o.effort),Ne(n.model)?n.max_completion_tokens=this.maxTokens===-1?void 0:this.maxTokens:n.max_tokens=this.maxTokens===-1?void 0:this.maxTokens,n}async _generate(t,e,r){e.signal?.throwIfAborted();let s={},n=this.invocationParams(e),o=ss({messages:t,model:this.model});if(n.stream){let i=this._streamResponseChunks(t,e,r),a={};for await(let A of i){A.message.response_metadata={...A.generationInfo,...A.message.response_metadata};let I=A.generationInfo?.completion??0;a[I]===void 0?a[I]=A:a[I]=a[I].concat(A)}let c=Object.entries(a).sort(([A],[I])=>parseInt(A,10)-parseInt(I,10)).map(([A,I])=>I),{functions:u,function_call:f}=this.invocationParams(e),h=await this._getEstimatedTokenCountFromPrompt(t,u,f),g=await this._getNumTokensFromGenerations(c);return s.input_tokens=h,s.output_tokens=g,s.total_tokens=h+g,{generations:c,llmOutput:{estimatedTokenUsage:{promptTokens:s.input_tokens,completionTokens:s.output_tokens,totalTokens:s.total_tokens}}}}else{let i=await this.completionWithRetry({...n,stream:!1,messages:o},{signal:e?.signal,...e?.options}),{completion_tokens:a,prompt_tokens:c,total_tokens:u,prompt_tokens_details:f,completion_tokens_details:h}=i?.usage??{};a&&(s.output_tokens=(s.output_tokens??0)+a),c&&(s.input_tokens=(s.input_tokens??0)+c),u&&(s.total_tokens=(s.total_tokens??0)+u),(f?.audio_tokens!==null||f?.cached_tokens!==null)&&(s.input_token_details={...f?.audio_tokens!==null&&{audio:f?.audio_tokens},...f?.cached_tokens!==null&&{cache_read:f?.cached_tokens}}),(h?.audio_tokens!==null||h?.reasoning_tokens!==null)&&(s.output_token_details={...h?.audio_tokens!==null&&{audio:h?.audio_tokens},...h?.reasoning_tokens!==null&&{reasoning:h?.reasoning_tokens}});let g=[];for(let A of i?.choices??[]){let I={text:A.message?.content??"",message:this._convertCompletionsMessageToBaseMessage(A.message??{role:"assistant"},i)};I.generationInfo={...A.finish_reason?{finish_reason:A.finish_reason}:{},...A.logprobs?{logprobs:A.logprobs}:{}},Ds(I.message)&&(I.message.usage_metadata=s),I.message=new ae(Object.fromEntries(Object.entries(I.message).filter(([b])=>!b.startsWith("lc_")))),g.push(I)}return{generations:g,llmOutput:{tokenUsage:{promptTokens:s.input_tokens,completionTokens:s.output_tokens,totalTokens:s.total_tokens}}}}}async*_streamChatModelEvents(t,e,r){let s=ss({messages:t,model:this.model}),n={...this.invocationParams(e,{streaming:!0}),messages:s,stream:!0},o=await this.completionWithRetry(n,e),i=this.streamUsage??e.streamUsage;yield*qs(async function*(c,u){for await(let f of c){if(u?.aborted)return;yield f}}(o,e.signal),{streamUsage:i??!0,provider:this.streamEventProvider})}get streamEventProvider(){return"openai"}async*_streamResponseChunks(t,e,r){let s=ss({messages:t,model:this.model}),n={...this.invocationParams(e,{streaming:!0}),messages:s,stream:!0},o,i=await this.completionWithRetry(n,e),a;for await(let c of i){if(e.signal?.aborted)return;let u=c?.choices?.[0];if(c.usage&&(a=c.usage),!u)continue;let{delta:f}=u;if(!f)continue;let h=this._convertCompletionsDeltaToBaseMessageChunk(f,c,o);o=f.role??o;let g={prompt:e.promptIndex??0,completion:u.index??0};if(typeof h.content!="string"){console.log("[WARNING]: Received non-string content from OpenAI. This is currently not supported.");continue}let A={...g};u.finish_reason!=null&&(A.finish_reason=u.finish_reason,A.system_fingerprint=c.system_fingerprint,A.model_name=c.model,A.service_tier=c.service_tier),this.logprobs&&(A.logprobs=u.logprobs);let I=new ns({message:h,text:h.content,generationInfo:A});yield I,await r?.handleLLMNewToken(I.text??"",g,void 0,void 0,void 0,{chunk:I})}if(a){let c={...a.prompt_tokens_details?.audio_tokens!==null&&{audio:a.prompt_tokens_details?.audio_tokens},...a.prompt_tokens_details?.cached_tokens!==null&&{cache_read:a.prompt_tokens_details?.cached_tokens}},u={...a.completion_tokens_details?.audio_tokens!==null&&{audio:a.completion_tokens_details?.audio_tokens},...a.completion_tokens_details?.reasoning_tokens!==null&&{reasoning:a.completion_tokens_details?.reasoning_tokens}},f=new ns({message:new Ut({content:"",response_metadata:{usage:{...a}},usage_metadata:{input_tokens:a.prompt_tokens,output_tokens:a.completion_tokens,total_tokens:a.total_tokens,...Object.keys(c).length>0&&{input_token_details:c},...Object.keys(u).length>0&&{output_token_details:u}}}),text:""});yield f,await r?.handleLLMNewToken(f.text??"",{prompt:0,completion:0},void 0,void 0,void 0,{chunk:f})}if(e.signal?.aborted)throw new Error("AbortError")}async completionWithRetry(t,e){let r=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,r):await this.client.chat.completions.create(t,r)}catch(n){throw ce(n)}})}_convertCompletionsDeltaToBaseMessageChunk(t,e,r){return Lo({delta:t,rawResponse:e,includeRawResponse:this.__includeRawResponse,defaultRole:r})}_convertCompletionsMessageToBaseMessage(t,e){return Uo({message:t,rawResponse:e,includeRawResponse:this.__includeRawResponse})}};var Rn="__openai_function_call_ids__",En="__openai_custom_tool_call_ids__";function Hu(t){return t.type==="url_citation"?{type:"citation",source:"url_citation",url:t.url,title:t.title,startIndex:t.start_index,endIndex:t.end_index}:t.type==="file_citation"?{type:"citation",source:"file_citation",title:t.filename,startIndex:t.index,file_id:t.file_id}:t.type==="container_file_citation"?{type:"citation",source:"container_file_citation",title:t.filename,startIndex:t.start_index,endIndex:t.end_index,file_id:t.file_id,container_id:t.container_id}:t.type==="file_path"?{type:"citation",source:"file_path",startIndex:t.index,file_id:t.file_id}:{type:"non_standard",value:t}}function Cp(t){if(t.type==="url_citation"||t.type==="file_citation"||t.type==="container_file_citation"||t.type==="file_path")return t;if(t.type==="citation"){let e=t;if(e.source==="url_citation")return{type:"url_citation",url:e.url??"",title:e.title??"",start_index:e.startIndex??0,end_index:e.endIndex??0};if(e.source==="file_citation")return{type:"file_citation",file_id:e.file_id??"",filename:e.title??"",index:e.startIndex??0};if(e.source==="container_file_citation")return{type:"container_file_citation",file_id:e.file_id??"",filename:e.title??"",container_id:e.container_id??"",start_index:e.startIndex??0,end_index:e.endIndex??0};if(e.source==="file_path")return{type:"file_path",file_id:e.file_id??"",index:e.startIndex??0}}return t.type==="non_standard"?t.value:t}var $s=t=>{let e={...t?.input_tokens_details?.cached_tokens!=null&&{cache_read:t?.input_tokens_details?.cached_tokens}},r={...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:r}},Sn=t=>{if(t.error){let a=new Error(t.error.message);throw a.name=t.error.code,a}let e=[],r=[],s=[],n=t.output.map(a=>{if(a.type==="function_call"&&"parsed_arguments"in a){let c={...a};return delete c.parsed_arguments,c}return a}),o={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,output:n,status:t.status,user:t.user,service_tier:t.service_tier,model_name:t.model},i={};for(let a of t.output)if(a.type==="message")e.push(...a.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.map(Hu),...a.phase!==null?{phase:a.phase}:{}}):c.type==="refusal"?(i.refusal=c.refusal,[]):c));else if(a.type==="function_call"){let c={function:{name:a.name,arguments:a.arguments},id:a.call_id};try{r.push(Bs(c,{returnId:!0}))}catch(u){let f;typeof u=="object"&&u!=null&&"message"in u&&typeof u.message=="string"&&(f=u.message),s.push(Dt(c,f))}i[Rn]??={},a.id&&(i[Rn][a.call_id]=a.id)}else if(a.type==="reasoning"){i.reasoning=a;let c=a.summary?.map(u=>u.text).filter(Boolean).join("");c&&e.push({type:"reasoning",reasoning:c})}else if(a.type==="custom_tool_call"){let c=qa(a);c?(r.push(c),i[En]??={},a.id&&a.call_id&&(i[En][a.call_id]=a.id)):s.push(Dt(a,"Malformed custom tool call"))}else if(a.type==="computer_call"){let c=Wa(a);c?r.push(c):s.push(Dt(a,"Malformed computer call"))}else a.type==="image_generation_call"?(a.result&&e.push({type:"image",mimeType:"image/png",data:a.result,id:a.id,metadata:{status:a.status}}),i.tool_outputs??=[],i.tool_outputs.push(a)):(i.tool_outputs??=[],i.tool_outputs.push(a));return new ae({id:t.id,content:e,tool_calls:r,invalid_tool_calls:s,usage_metadata:$s(t.usage),additional_kwargs:i,response_metadata:o})},Zu=t=>{let e=(t.summary.length>1?t.summary.reduce((r,s)=>{let n=r[r.length-1];return n.index===s.index?n.text+=s.text:r.push(s),r},[{...t.summary[0]}]):t.summary).map(r=>Object.fromEntries(Object.entries(r).filter(([s])=>s!=="index")));return{...t,summary:e}},Do=t=>{let e=[],r={},s,n=[],o={model_provider:"openai"},i={},a;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:[Hu(t.annotation)],index:t.content_index});else if(t.type==="response.output_item.added"&&t.item.type==="message"){let c="phase"in t.item?t.item.phase:void 0;c&&e.push({type:"text",text:"",phase:c,index:0})}else if(t.type==="response.output_item.added"&&t.item.type==="function_call")n.push({type:"tool_call_chunk",name:t.item.name,args:t.item.arguments,id:t.item.call_id,index:t.output_index}),i[Rn]={[t.item.call_id]:t.item.id};else if(t.type==="response.output_item.added"&&t.item.type==="custom_tool_call")n.push({type:"tool_call_chunk",isCustomTool:!0,name:t.item.name,args:t.item.input,id:t.item.call_id,index:t.output_index}),i[En]={[t.item.call_id]:t.item.id};else if(t.type==="response.output_item.done"&&t.item.type==="computer_call")n.push({type:"tool_call_chunk",name:"computer_use",args:JSON.stringify({action:t.item.action}),id:t.item.call_id,index:t.output_index}),i.tool_outputs=[t.item];else if(t.type==="response.output_item.done"&&t.item.type==="image_generation_call")t.item.result&&e.push({type:"image",mimeType:"image/png",data:t.item.result,id:t.item.id,metadata:{status:t.item.status}}),i.tool_outputs=[t.item];else if(t.type==="response.output_item.done"&&["web_search_call","file_search_call","code_interpreter_call","shell_call","local_shell_call","mcp_call","mcp_list_tools","mcp_approval_request","custom_tool_call","tool_search_call","tool_search_output"].includes(t.item.type))i.tool_outputs=[t.item];else if(t.type==="response.created")a=t.response.id,o.id=t.response.id,o.model_name=t.response.model,o.model=t.response.model;else if(t.type==="response.completed"||t.type==="response.incomplete"){a=t.response.id;let c=Sn(t.response);if(s=$s(t.response.usage),t.response.text?.format?.type==="json_schema"&&c.text)try{i.parsed??=JSON.parse(c.text)}catch{}for(let[u,f]of Object.entries(t.response))u!=="id"&&(u==="output"?o[u]=c.response_metadata.output:o[u]=f)}else if(t.type==="response.function_call_arguments.delta"||t.type==="response.custom_tool_call_input.delta")n.push({type:"tool_call_chunk",args:t.delta,index:t.output_index,...t.type==="response.custom_tool_call_input.delta"?{isCustomTool:!0}:{}});else if(t.type==="response.web_search_call.in_progress"||t.type==="response.web_search_call.searching"||t.type==="response.web_search_call.completed"||t.type==="response.file_search_call.in_progress"||t.type==="response.file_search_call.searching"||t.type==="response.file_search_call.completed"||t.type==="response.image_generation_call.in_progress"||t.type==="response.image_generation_call.generating"||t.type==="response.image_generation_call.completed"){let[,c,u]=t.type.match(/^response\.(.*)\.([^.]+)$/)??["","",""];r={tool_outputs:{id:t.item_id,type:c,status:u}}}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"){let c=t.item.summary?t.item.summary.map((f,h)=>({...f,index:h})):void 0;i.reasoning={id:t.item.id,type:t.item.type,...c?{summary:c}:{}};let u=t.item.summary?.map(f=>f.text).filter(Boolean).join("");u&&e.push({type:"reasoning",reasoning:u})}else if(t.type==="response.reasoning_summary_part.added")i.reasoning={type:"reasoning",summary:[{...t.part,index:t.summary_index}]},t.part.text&&e.push({type:"reasoning",reasoning:t.part.text,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}]},t.delta&&e.push({type:"reasoning",reasoning:t.delta,index:t.summary_index});else return t.type==="response.image_generation_call.partial_image",null;return new ns({text:e.map(c=>c.text).join(""),message:new Ut({id:a,content:e,tool_call_chunks:n,usage_metadata:s,additional_kwargs:i,response_metadata:o}),generationInfo:r})},Vu=t=>{let e=ae.isInstance(t)&&t.response_metadata?.model_provider==="openai";function*r(){let s=_e(()=>{try{let m=ze(t);return m==="system"||m==="developer"||m==="assistant"||m==="user"?m:"assistant"}catch{return"assistant"}}),n,o=new Set,i=new Set,a=new Map,c=new Map;function*u(){if(!n)return;let m=n.content;(typeof m=="string"&&m.length>0||Array.isArray(m)&&m.length>0)&&(yield n),n=void 0}let f=(m,y)=>{n||(n={type:"message",role:s,content:[],...y?{phase:y}:{}}),typeof n.content=="string"?n.content=n.content.length>0?[{type:"input_text",text:n.content},...m]:[...m]:n.content.push(...m)},h=m=>{if(typeof m=="string")return m;try{return JSON.stringify(m??{})}catch{return"{}"}},g=m=>{let y=_e(()=>{let O=m.metadata?.detail;return O==="low"||O==="high"||O==="auto"?O:"auto"});if(m.fileId)return{type:"input_image",detail:y,file_id:m.fileId};if(m.url)return{type:"input_image",detail:y,image_url:m.url};if(m.data){let O=typeof m.data=="string"?m.data:Buffer.from(m.data).toString("base64");return{type:"input_image",detail:y,image_url:`data:${m.mimeType??"image/png"};base64,${O}`}}},A=m=>{if(m.fileId){let y=xn(m);return{type:"input_file",file_id:m.fileId,...y?{filename:y}:{}}}if(m.url){let y=xn(m);return{...y?{filename:y}:{},type:"input_file",file_url:m.url}}if(m.data){let y=St(m),O=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,${O}`,filename:y}}},I=m=>{let y=_e(()=>{if(Array.isArray(m.summary)){let R=m.summary?.map(N=>N?.text).filter(N=>typeof N=="string")??[];if(R.length>0)return R}return m.reasoning?[m.reasoning]:[]}),O=y.length>0?y.map(R=>({type:"summary_text",text:R})):[{type:"summary_text",text:""}];return{type:"reasoning",...m.id?{id:m.id}:{},summary:O}},b=m=>({type:"function_call",name:m.name??"",call_id:m.id??"",arguments:h(m.args)}),_=m=>{let y=h(m.output),O=m.status==="success"?"completed":m.status==="error"?"incomplete":void 0;return{type:"function_call_output",call_id:m.toolCallId??"",output:y,...O?{status:O}:{}}};for(let m of t.contentBlocks)if(m.type==="text"){let y=_e(()=>{if("extras"in m&&typeof m.extras=="object"&&m.extras!==null&&"phase"in m.extras)return m.extras.phase});f([{type:"input_text",text:m.text}],y)}else if(m.type!=="invalid_tool_call"){if(m.type==="reasoning")yield*u(),yield I(m);else if(m.type==="tool_call"){yield*u();let y=m.id??"";y&&(o.add(y),a.delete(y)),yield b(m)}else if(m.type==="tool_call_chunk"){if(m.id){let y=a.get(m.id)??{name:m.name,args:[]};m.name&&(y.name=m.name),m.args&&y.args.push(m.args),a.set(m.id,y)}}else if(m.type==="server_tool_call"){yield*u();let y=m.id??"";y&&(i.add(y),c.delete(y)),yield b(m)}else if(m.type==="server_tool_call_chunk"){if(m.id){let y=c.get(m.id)??{name:m.name,args:[]};m.name&&(y.name=m.name),m.args&&y.args.push(m.args),c.set(m.id,y)}}else if(m.type==="server_tool_call_result")yield*u(),yield _(m);else if(m.type!=="audio")if(m.type==="file"){let y=A(m);y&&f([y])}else if(m.type==="image"){let y=g(m);y&&f([y])}else if(m.type==="video"){let y=A(m);y&&f([y])}else m.type==="text-plain"?m.text&&f([{type:"input_text",text:m.text}]):m.type==="non_standard"&&e&&(yield*u(),yield m.value)}yield*u();for(let[m,y]of a){if(!m||o.has(m))continue;let O=y.args.join("");!y.name&&!O||(yield{type:"function_call",call_id:m,name:y.name??"",arguments:O})}for(let[m,y]of c){if(!m||i.has(m))continue;let O=y.args.join("");!y.name&&!O||(yield{type:"function_call",call_id:m,name:y.name??"",arguments:O})}}return Array.from(r())},Ms=({messages:t,zdrEnabled:e,model:r})=>t.flatMap(s=>{let n=s.response_metadata;if(n?.output_version==="v1")return Vu(s);let o=s.additional_kwargs,i=ze(s);if(i==="system"&&Ne(r)&&(i="developer"),i==="function")throw new Error("Function messages are not supported in Responses API");if(i==="tool"){let a=s;if(o?.type==="computer_call_output")return{type:"computer_call_output",output:(()=>{if(typeof a.content=="string")return{type:"input_image",image_url:a.content};if(Array.isArray(a.content)){let u=a.content.find(g=>g.type==="input_image");if(u)return u;let f=a.content.find(g=>g.type==="computer_screenshot");if(f)return f;let h=a.content.find(g=>g.type==="image_url");if(h)return{type:"input_image",image_url:typeof h.image_url=="string"?h.image_url:h.image_url.url}}throw new Error("Invalid computer call output")})(),call_id:a.tool_call_id};if(a.additional_kwargs?.customTool)return{type:"custom_tool_call_output",call_id:a.tool_call_id,output:a.content};let c=Array.isArray(a.content)&&a.content.every(u=>typeof u=="object"&&u!==null&&"type"in u&&(u.type==="input_file"||u.type==="input_image"||u.type==="input_text"));return{type:"function_call_output",call_id:a.tool_call_id,id:a.id?.startsWith("fc_")?a.id:void 0,output:c?a.content:typeof a.content!="string"?JSON.stringify(a.content):a.content}}if(i==="assistant"){if(!e&&n?.output!=null&&Array.isArray(n?.output)&&n?.output.length>0&&n?.output.every(b=>"type"in b))return n?.output;let a=[],c=o?.reasoning,u=!!c?.encrypted_content;if(c&&(!e||u)){let b=Zu(c);a.push(b)}let{content:f}=s;if(o?.refusal&&(typeof f=="string"&&(f=[{type:"output_text",text:f,annotations:[]}]),f=[...f,{type:"refusal",refusal:o.refusal}]),typeof f=="string"||f.length>0){let b={type:"message",role:"assistant",...s.id&&!e&&s.id.startsWith("msg_")?{id:s.id}:{},content:_e(()=>typeof f=="string"?f:f.flatMap(_=>{if(_.type==="text"){let m=_;return{type:"output_text",text:m.text,annotations:(m.annotations??[]).map(Cp)}}return _.type==="output_text"||_.type==="refusal"?_:[]})),phase:_e(()=>{if(Array.isArray(f))return f.find(_=>"phase"in _&&typeof _.phase=="string")?.phase})};a.push(b)}let h=o?.[Rn],g=o?.[En];ae.isInstance(s)&&s.tool_calls?.length?a.push(...s.tool_calls.map(b=>Za(b,g)?{type:"custom_tool_call",id:"call_id"in b&&typeof b.call_id=="string"?b.call_id:g?.[b.id??""]??"",call_id:b.id??"",input:b.args.input,name:b.name}:Ha(b)?{type:"computer_call",id:b.call_id,call_id:b.id??"",action:b.args.action}:{type:"function_call",name:b.name,arguments:JSON.stringify(b.args),call_id:b.id,...e?{}:{id:h?.[b.id]}})):o?.tool_calls&&a.push(...o.tool_calls.map(b=>({type:"function_call",name:b.function.name,call_id:b.id,arguments:b.function.arguments,...e?{}:{id:h?.[b.id]}})));let A=n?.output?.length?n?.output:o.tool_outputs,I=["computer_call","mcp_call","code_interpreter_call","image_generation_call","shell_call","local_shell_call"];if(A!=null){let b=A?.filter(_=>I.includes(_.type));b.length>0&&a.push(...b)}return a}if(i==="user"||i==="system"||i==="developer"){if(typeof s.content=="string")return{type:"message",role:i,content:s.content};let a=[],c=s.content.flatMap(u=>{if(u.type==="mcp_approval_response"&&a.push({type:"mcp_approval_response",approval_request_id:u.approval_request_id,approve:u.approve}),js(u)){if(u.type==="file"){let f=xn(u);if(u.source_type==="url")return{type:"input_file",file_url:u.url,...f?{filename:f}:{}};if(u.source_type==="id")return{type:"input_file",file_id:u.id,...f?{filename:f}:{}};if(u.source_type==="base64")return{type:"input_file",file_data:`data:${u.mime_type??""};base64,${u.data}`,filename:St(u)}}return Us(u,Tn)}return u.type==="text"?{type:"input_text",text:u.text}:u.type==="image_url"?{type:"input_image",image_url:_e(()=>{if(typeof u.image_url=="string")return u.image_url;if(typeof u.image_url=="object"&&u.image_url!==null&&"url"in u.image_url)return u.image_url.url}),detail:_e(()=>{if(typeof u.image_url=="string")return"auto";if(typeof u.image_url=="object"&&u.image_url!==null&&"detail"in u.image_url)return u.image_url.detail})}:u.type==="input_text"||u.type==="input_image"||u.type==="input_file"?u:[]});return c.length>0&&a.push({type:"message",role:i,content:c}),a}return console.warn(`Unsupported role found when converting to OpenAI Responses API: ${i}`),[]});async function*Ko(t,e={}){let r=e.streamUsage??!0,s=e.provider??"openai",n=new Map,o=new Map,i=0,a=!1,c,u,f,h,g=new Set,A=(_,m)=>{let y=o.get(_);if(y!==void 0)return{index:y,isNew:!1};let O=i++;return o.set(_,O),n.set(O,{...m}),{index:O,isNew:!0}},I=function*(){a||(a=!0,yield{event:"message-start",id:c})},b=function*(_){if(g.has(_))return;let m=n.get(_);m&&(g.add(_),yield{event:"content-block-finish",index:_,content:hi(m)})};for await(let _ of t){if(_.type==="response.created"){c=_.response.id,yield*I(),yield{event:"provider",provider:s,name:"response.created",payload:{model:_.response.model,id:_.response.id}};continue}if(_.type==="response.output_text.delta"){yield*I();let{index:m,isNew:y}=A(`text:${_.output_index}:${_.content_index}`,{type:"text",text:""});y&&(yield{event:"content-block-start",index:m,content:{type:"text",text:""}});let O=n.get(m);O.text=(O.text??"")+_.delta,yield{event:"content-block-delta",index:m,delta:{type:"text-delta",text:_.delta}};continue}if(_.type==="response.reasoning_summary_text.delta"){yield*I();let{index:m,isNew:y}=A(`reasoning:${_.output_index}:${_.summary_index}`,{type:"reasoning",reasoning:""});y&&(yield{event:"content-block-start",index:m,content:{type:"reasoning",reasoning:""}});let O=n.get(m);O.reasoning=(O.reasoning??"")+_.delta,yield{event:"content-block-delta",index:m,delta:{type:"reasoning-delta",reasoning:_.delta}};continue}if(_.type==="response.output_item.added"&&(_.item.type==="function_call"||_.item.type==="custom_tool_call")){yield*I();let m=`tool:${_.output_index}`,y=_.item.type==="custom_tool_call",O=_.item.type==="function_call"?_.item.arguments??"":_.item.input??"",{index:R,isNew:N}=A(m,{type:"tool_call_chunk",id:_.item.call_id,name:_.item.name,args:O,index:_.output_index,...y?{isCustomTool:!0}:{}});if(N&&(yield{event:"content-block-start",index:R,content:{type:"tool_call_chunk",id:_.item.call_id,name:_.item.name,args:O,index:_.output_index}}),O){let z=n.get(R);yield{event:"content-block-delta",index:R,delta:{type:"block-delta",fields:{type:"tool_call_chunk",...z.id!=null?{id:z.id}:{},...z.name!=null?{name:z.name}:{},args:z.args}}}}continue}if(_.type==="response.function_call_arguments.delta"||_.type==="response.custom_tool_call_input.delta"){yield*I();let{index:m,isNew:y}=A(`tool:${_.output_index}`,{type:"tool_call_chunk",args:"",index:_.output_index,..._.type==="response.custom_tool_call_input.delta"?{isCustomTool:!0}:{}});y&&(yield{event:"content-block-start",index:m,content:{type:"tool_call_chunk",args:"",index:_.output_index}});let O=n.get(m);O.args=(O.args??"")+_.delta,yield{event:"content-block-delta",index:m,delta:{type:"block-delta",fields:{type:"tool_call_chunk",...O.id!=null?{id:O.id}:{},...O.name!=null?{name:O.name}:{},args:O.args}}};continue}if(_.type==="response.output_item.done"&&(_.item.type==="function_call"||_.item.type==="custom_tool_call")){yield*I();let m=`tool:${_.output_index}`,y=_.item.type==="function_call"?_.item.arguments??"":_.item.input??"",{index:O,isNew:R}=A(m,{type:"tool_call_chunk",id:_.item.call_id,name:_.item.name,args:y,index:_.output_index});if(R)yield{event:"content-block-start",index:O,content:{type:"tool_call_chunk",id:_.item.call_id,name:_.item.name,args:y,index:_.output_index}};else{let N=n.get(O);N.args=y,N.id=_.item.call_id,N.name=_.item.name}yield*b(O);continue}if(_.type==="response.completed"||_.type==="response.incomplete"){yield*I(),c=_.response.id,f=Rp(_.response.status,_.type),h={model_provider:s,id:_.response.id,model:_.response.model,status:_.response.status},r&&_.response.usage&&(u=$s(_.response.usage),yield{event:"usage",usage:u});continue}_.type!=="response.image_generation_call.partial_image"&&(yield*I(),yield{event:"provider",provider:s,name:_.type,payload:_})}a||(yield{event:"message-start"});for(let[_]of n)g.has(_)||(yield*b(_));yield{event:"message-finish",reason:f,...u?{usage:u}:{},...h?{responseMetadata:h}:{}}}function Rp(t,e){return e==="response.incomplete"?"length":t==="completed"?"stop":t==="incomplete"?"length":"stop"}var $n=class extends zt{constructor(t,e){super(rs(t,e))}invocationParams(t){let e;t?.strict!==void 0&&(e=t.strict),e===void 0&&this.supportsStrictToolCalling!==void 0&&(e=this.supportsStrictToolCalling);let r={model:this.model,temperature:this.temperature,top_p:this.topP,user:this.user,service_tier:this.service_tier,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:Ba(t?.tool_choice)?t?.tool_choice:(()=>{let n=Pn(t?.tool_choice);if(typeof n=="object"&&"type"in n){if(n.type==="function")return{type:"function",name:n.function.name};if(n.type==="allowed_tools")return{type:"allowed_tools",mode:n.allowed_tools.mode,tools:n.allowed_tools.tools};if(n.type==="custom")return{type:"custom",name:n.custom.name}}})(),text:(()=>{if(t?.text)return t.text;let n=this._getResponseFormat(t?.response_format);return n?.type==="json_schema"?n.json_schema.schema!=null?{format:{type:"json_schema",schema:n.json_schema.schema,description:n.json_schema.description,name:n.json_schema.name,strict:n.json_schema.strict},verbosity:t?.verbosity}:void 0:{format:n,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,prompt_cache_retention:t?.promptCacheRetention??this.promptCacheRetention,...this.zdrEnabled?{store:!1}:{},...this.modelKwargs},s=this._getReasoningParams(t);return s!==void 0&&(r.reasoning=s),r}async _generate(t,e,r){e.signal?.throwIfAborted();let s=this.invocationParams(e);if(s.stream){let n=this._streamResponseChunks(t,e,r),o;for await(let i of n)i.message.response_metadata={...i.generationInfo,...i.message.response_metadata},o=o?.concat(i)??i;return{generations:o?[o]:[],llmOutput:{estimatedTokenUsage:o?.message?.usage_metadata}}}else{let n=await this.completionWithRetry({input:Ms({messages:t,zdrEnabled:this.zdrEnabled??!1,model:this.model}),...s,stream:!1},{signal:e?.signal,...e?.options});return{generations:[{text:n.output_text,message:Sn(n)}],llmOutput:{id:n.id,estimatedTokenUsage:n.usage?{promptTokens:n.usage.input_tokens,completionTokens:n.usage.output_tokens,totalTokens:n.usage.total_tokens}:void 0}}}}async*_streamChatModelEvents(t,e,r){let s=await this.completionWithRetry({...this.invocationParams(e),input:Ms({messages:t,zdrEnabled:this.zdrEnabled??!1,model:this.model}),stream:!0},e),n=this.streamUsage??e.streamUsage;yield*Ko(async function*(i,a){for await(let c of i){if(a?.aborted)return;yield c}}(s,e.signal),{streamUsage:n??!0,provider:this.streamEventProvider})}get streamEventProvider(){return"openai"}async*_streamResponseChunks(t,e,r){let s=await this.completionWithRetry({...this.invocationParams(e),input:Ms({messages:t,zdrEnabled:this.zdrEnabled??!1,model:this.model}),stream:!0},e);try{for await(let n of s){if(e.signal?.aborted)return;let o=Do(n);o!=null&&(yield o,await r?.handleLLMNewToken(o.text||"",{prompt:e.promptIndex??0,completion:0},void 0,void 0,void 0,{chunk:o}))}}catch(n){throw ce(n)}}async completionWithRetry(t,e){return this.caller.call(async()=>{let r=this._getClientOptions(e);try{return t.text?.format?.type==="json_schema"&&!t.stream?await this.client.responses.parse(t,r):await this.client.responses.create(t,r)}catch(s){throw ce(s)}})}_reduceChatOpenAITools(t,e){let r=[];for(let s of t)if(ts(s))s.type==="image_generation"&&e?.stream&&(s.partial_images=1),r.push(s);else if($t(s)){let n=s.metadata.customTool;r.push({type:"custom",name:n.name,description:n.description,format:n.format})}else if(Fs(s)){let n={};for(let[o,i]of Object.entries(s))o!=="type"&&o!=="function"&&(n[o]=i);r.push({type:"function",name:s.function.name,parameters:s.function.parameters,description:s.function.description,strict:e?.strict??null,...n})}else On(s)&&r.push(Va(s));return r}};var Mn=class Ju extends zt{useResponsesApi=!1;responses;completions;get lc_serializable_keys(){return[...super.lc_serializable_keys,"useResponsesApi"]}get callKeys(){return[...super.callKeys,"useResponsesApi"]}fields;constructor(e,r){let s=rs(e,r);super(s),this.fields=s,this.useResponsesApi=s?.useResponsesApi??!1,this.responses=s?.responses??new $n(s),this.completions=s?.completions??new Cn(s)}_useResponsesApi(e){let r=e?.tools?.some(ts),s=e?.previous_response_id!=null||e?.text!=null||e?.truncation!=null||e?.include!=null||e?.reasoning?.summary!=null||this.reasoning?.summary!=null,n=e?.tools?.some(On)||e?.tools?.some($t);return this.useResponsesApi||r||s||n||za(this.model)}getLsParams(e){let r=this._combineCallOptions(e);return this._useResponsesApi(e)?this.responses.getLsParams(r):this.completions.getLsParams(r)}invocationParams(e){let r=this._combineCallOptions(e);return this._useResponsesApi(e)?this.responses.invocationParams(r):this.completions.invocationParams(r)}async _generate(e,r,s){return this._useResponsesApi(r)?this.responses._generate(e,r,s):this.completions._generate(e,r,s)}async*_streamChatModelEvents(e,r,s){if(this._useResponsesApi(r)){yield*this.responses._streamChatModelEvents(e,this._combineCallOptions(r),s);return}yield*this.completions._streamChatModelEvents(e,this._combineCallOptions(r),s)}async*_streamResponseChunks(e,r,s){if(this._useResponsesApi(r)){yield*this.responses._streamResponseChunks(e,this._combineCallOptions(r),s);return}yield*this.completions._streamResponseChunks(e,this._combineCallOptions(r),s)}withConfig(e){let r=new Ju(this.fields);return r.defaultOptions={...this.defaultOptions,...e},r}};var Nn=class extends pi{model="text-embedding-ada-002";modelName;batchSize=512;stripNewLines=!0;dimensions;timeout;organization;encodingFormat;client;clientConfig;apiKey;constructor(t){let e={maxConcurrency:2,...t};super(e);let r=e?.apiKey??e?.openAIApiKey??pe("OPENAI_API_KEY");this.organization=e?.configuration?.organization??pe("OPENAI_ORGANIZATION"),this.model=e?.model??e?.modelName??this.model,this.modelName=this.model,this.batchSize=e?.batchSize??this.batchSize,this.stripNewLines=e?.stripNewLines??this.stripNewLines,this.timeout=e?.timeout,this.dimensions=e?.dimensions,this.encodingFormat=e?.encodingFormat,this.clientConfig={apiKey:r,organization:this.organization,dangerouslyAllowBrowser:!0,...t?.configuration}}async embedDocuments(t){let e=Wn(this.stripNewLines?t.map(o=>o.replace(/\n/g," ")):t,this.batchSize),r=e.map(o=>{let i={model:this.model,input:o};return this.dimensions&&(i.dimensions=this.dimensions),this.encodingFormat&&(i.encoding_format=this.encodingFormat),this.embeddingWithRetry(i)}),s=await Promise.all(r),n=[];for(let o=0;o<s.length;o+=1){let i=e[o],{data:a}=s[o];for(let c=0;c<i.length;c+=1)n.push(a[c].embedding)}return n}async embedQuery(t){let e={model:this.model,input:this.stripNewLines?t.replace(/\n/g," "):t};this.dimensions&&(e.dimensions=this.dimensions),this.encodingFormat&&(e.encoding_format=this.encodingFormat);let{data:r}=await this.embeddingWithRetry(e);return r[0].embedding}async embeddingWithRetry(t){if(!this.client){let r=je({baseURL:this.clientConfig.baseURL}),s={...this.clientConfig,baseURL:r,timeout:this.timeout,maxRetries:0};s.baseURL||delete s.baseURL,s.defaultHeaders=Ue(s.defaultHeaders),this.client=new v(s)}let e={};return this.caller.call(async()=>{try{return await this.client.embeddings.create(t,e)}catch(r){throw ce(r)}})}};var Mp=x.object({type:x.literal("screenshot")}),Np=x.object({type:x.literal("click"),x:x.number(),y:x.number(),button:x.enum(["left","right","wheel","back","forward"]).default("left")}),zp=x.object({type:x.literal("double_click"),x:x.number(),y:x.number(),button:x.enum(["left","right","wheel","back","forward"]).default("left")}),jp=x.object({type:x.literal("drag"),path:x.array(x.object({x:x.number(),y:x.number()}))}),Up=x.object({type:x.literal("keypress"),keys:x.array(x.string())}),Lp=x.object({type:x.literal("move"),x:x.number(),y:x.number()}),Dp=x.object({type:x.literal("scroll"),x:x.number(),y:x.number(),scroll_x:x.number(),scroll_y:x.number()}),Kp=x.object({type:x.literal("type"),text:x.string()}),Fp=x.object({type:x.literal("wait"),duration:x.number().optional()}),Bp=x.union([Mp,Np,zp,jp,Up,Lp,Dp,Kp,Fp]),sT=x.object({action:Bp});var qp=x.object({type:x.literal("exec"),command:x.array(x.string()),env:x.record(x.string(),x.string()).optional(),working_directory:x.string().optional(),timeout_ms:x.number().optional(),user:x.string().optional()}),aT=x.union([qp]);var pT=x.object({commands:x.array(x.string()).describe("Array of shell commands to execute"),timeout_ms:x.number().optional().describe("Optional timeout in milliseconds for the commands"),max_output_length:x.number().optional().describe("Optional maximum number of characters to return from each command")});var Wp=x.object({type:x.literal("create_file"),path:x.string(),diff:x.string()}),Hp=x.object({type:x.literal("update_file"),path:x.string(),diff:x.string()}),Zp=x.object({type:x.literal("delete_file"),path:x.string()}),hT=x.union([Wp,Hp,Zp]);var el={advanced:"gpt-5.2",default:"gpt-5-mini",fast:"gpt-5.4-nano"},Wo={default:"text-embedding-ada-002"},Bo=new Map,zn=null,Gp=()=>{let t=Yu.getDefault().helperServices;if(!t?.aiModels?.url)throw new Error("AI Models Service URL is not defined in the portal's helper services.");return t.aiModels.url},tl=async t=>{let e=Gp();Bo.size===0&&(zn||(zn=(async()=>{try{(await Qu(`${e}/models`)).data.models.forEach(s=>Bo.set(s.name,s))}catch(s){throw zn=null,s}})()),await zn);let r=Bo.get(t);if(!r)throw new Error(`Model '${t}' is not available in the discovery service.`);return r.endpoint},Xp=async(t="default")=>await tl(el[t]),Yp=async(t="default")=>await tl(Wo[t]),jt=(t,e)=>e,rl=(t,e)=>({...t,...e}),sl=(t="",e)=>{let r=typeof e=="string"?e.trim():"";if(!r)return t;let s=t.trim();if(!s)return r;if(s===r)return t;let n=s.split(`
35
+ ]`;continue}o+=n[u],n[u]==="\\"?i=!0:a&&n[u]==="]"?a=!1:!a&&n[u]==="["&&(a=!0)}try{let u=new RegExp(o)}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`),r.source}return o};function vn(t,e){if(e.target==="openApi3"&&t.keyType?._def.typeName===E.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((s,n)=>({...s,[n]:T(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",n]})??{}}),{}),additionalProperties:!1};let r={type:"object",additionalProperties:T(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??{}};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===E.ZodString&&t.keyType._def.checks?.length){let s=Object.entries(kn(t.keyType._def,e)).reduce((n,[o,i])=>o==="type"?n:{...n,[o]:i},{});return{...r,propertyNames:s}}else if(t.keyType?._def.typeName===E.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};return r}function _u(t,e){if(e.mapStrategy==="record")return vn(t,e);let r=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:[r,s],minItems:2,maxItems:2}}}function gu(t){let e=t.values,s=Object.keys(t.values).filter(o=>typeof e[e[o]]!="number").map(o=>e[o]),n=Array.from(new Set(s.map(o=>typeof o)));return{type:n.length===1?n[0]==="string"?"string":"number":["string","number"],enum:s}}function yu(){return{not:{}}}function Au(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Ss={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function bu(t,e){if(e.target==="openApi3")return Iu(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(s=>s._def.typeName in Ss&&(!s._def.checks||!s._def.checks.length))){let s=r.reduce((n,o)=>{let i=Ss[o._def.typeName];return i&&!n.includes(i)?[...n,i]:n},[]);return{type:s.length>1?s:s[0]}}else if(r.every(s=>s._def.typeName==="ZodLiteral"&&!s.description)){let s=r.reduce((n,o)=>{let i=typeof o._def.value;switch(i){case"string":case"number":case"boolean":return[...n,i];case"bigint":return[...n,"integer"];case"object":if(o._def.value===null)return[...n,"null"];default:return n}},[]);if(s.length===r.length){let n=s.filter((o,i,a)=>a.indexOf(o)===i);return{type:n.length>1?n:n[0],enum:r.reduce((o,i)=>o.includes(i._def.value)?o:[...o,i._def.value],[])}}}else if(r.every(s=>s._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((s,n)=>[...s,...n._def.values.filter(o=>!s.includes(o))],[])};return Iu(t,e)}var Iu=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((s,n)=>T(s._def,{...e,currentPath:[...e.currentPath,"anyOf",`${n}`]})).filter(s=>!!s&&(!e.strictUnions||typeof s=="object"&&Object.keys(s).length>0));return r.length?{anyOf:r}:void 0};function xu(t,e,r){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:Ss[t.innerType._def.typeName],nullable:!0}:{type:[Ss[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=T(t.innerType._def,{...e,currentPath:[...e.currentPath]},r);return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let s=T(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return s&&{anyOf:[s,{type:"null"}]}}function wu(t,e){let r={type:"number"};if(!t.checks)return r;for(let s of t.checks)switch(s.kind){case"int":r.type="integer",$o(r,"type",s.message,e);break;case"min":e.target==="jsonSchema7"?s.inclusive?M(r,"minimum",s.value,s.message,e):M(r,"exclusiveMinimum",s.value,s.message,e):(s.inclusive||(r.exclusiveMinimum=!0),M(r,"minimum",s.value,s.message,e));break;case"max":e.target==="jsonSchema7"?s.inclusive?M(r,"maximum",s.value,s.message,e):M(r,"exclusiveMaximum",s.value,s.message,e):(s.inclusive||(r.exclusiveMaximum=!0),M(r,"maximum",s.value,s.message,e));break;case"multipleOf":M(r,"multipleOf",s.value,s.message,e);break}return r}function _p(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 Pu(t,e){let r={type:"object",...Object.entries(t.shape()).reduce((s,[n,o])=>{if(o===void 0||o._def===void 0)return s;let i=[...e.currentPath,"properties",n],a=T(o._def,{...e,currentPath:i,propertyPath:i});if(a===void 0)return s;if(e.openaiStrictMode&&o.isOptional()&&!o.isNullable()&&typeof o._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,[n]:a},required:o.isOptional()&&!e.openaiStrictMode?s.required:[...s.required,n]}},{properties:{},required:[]}),additionalProperties:_p(t,e)};return r.required.length||delete r.required,r}var Ou=(t,e,r)=>{if(e.propertyPath&&e.currentPath.slice(0,e.propertyPath.length).toString()===e.propertyPath.toString())return T(t.innerType._def,{...e,currentPath:e.currentPath},r);let s=T(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]},r);return s?{anyOf:[{not:{}},s]}:{}};var ku=(t,e,r)=>{if(e.pipeStrategy==="input")return T(t.in._def,e,r);if(e.pipeStrategy==="output")return T(t.out._def,e,r);let s=T(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=T(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",s?"1":"0"]});return{allOf:[s,n].filter(o=>o!==void 0)}};function vu(t,e,r){return T(t.type._def,e,r)}function Tu(t,e){let s={type:"array",uniqueItems:!0,items:T(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&M(s,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&M(s,"maxItems",t.maxSize.value,t.maxSize.message,e),s}function Cu(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,s)=>T(r._def,{...e,currentPath:[...e.currentPath,"items",`${s}`]})).reduce((r,s)=>s===void 0?r:[...r,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((r,s)=>T(r._def,{...e,currentPath:[...e.currentPath,"items",`${s}`]})).reduce((r,s)=>s===void 0?r:[...r,s],[])}}function Ru(){return{not:{}}}function Eu(){return{}}var Su=(t,e,r)=>T(t.innerType._def,e,r);function T(t,e,r=!1){let s=e.seen.get(t);if(e.override){let o=e.override?.(t,e,s,r);if(o!==eu)return o}if(s&&!r){let o=gp(s,e);if(o!==void 0)return"$ref"in o&&e.seenRefs.add(o.$ref),o}let n={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,n);try{let o=Ip(t,t.typeName,e,r);return o&&bp(t,e,o),n.jsonSchema=o,o}finally{r&&s&&e.seen.set(t,s)}}var gp=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"extract-to-root":let r=t.path.slice(e.basePath.length+1).map((s,n)=>n===0?s:yp(s)).join("_");return r!==e.name&&e.nameStrategy==="duplicate-ref"&&(e.definitions[r]=t.def),{$ref:[...e.basePath,e.definitionPath,r].join("/")};case"relative":return{$ref:Ap(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((s,n)=>e.currentPath[n]===s)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),{}):e.$refStrategy==="seen"?{}:void 0}},$u="_x_",yp=t=>{if(/^[A-Za-z0-9_-]*$/.test(t)&&!t.startsWith($u))return t;let e=$u;for(let r=0;r<t.length;r++)e+=t.charCodeAt(r).toString(16).padStart(4,"0");return e},Ap=(t,e)=>{let r=0;for(;r<t.length&&r<e.length&&t[r]===e[r];r++);return[(t.length-r).toString(),...e.slice(r)].join("/")},Ip=(t,e,r,s)=>{switch(e){case E.ZodString:return kn(t,r);case E.ZodNumber:return wu(t,r);case E.ZodObject:return Pu(t,r);case E.ZodBigInt:return iu(t,r);case E.ZodBoolean:return au();case E.ZodDate:return Mo(t,r);case E.ZodUndefined:return Ru();case E.ZodNull:return Au(r);case E.ZodArray:return ou(t,r);case E.ZodUnion:case E.ZodDiscriminatedUnion:return bu(t,r);case E.ZodIntersection:return du(t,r);case E.ZodTuple:return Cu(t,r);case E.ZodRecord:return vn(t,r);case E.ZodLiteral:return fu(t,r);case E.ZodEnum:return mu(t);case E.ZodNativeEnum:return gu(t);case E.ZodNullable:return xu(t,r,s);case E.ZodOptional:return Ou(t,r,s);case E.ZodMap:return _u(t,r);case E.ZodSet:return Tu(t,r);case E.ZodLazy:return T(t.getter()._def,r,s);case E.ZodPromise:return vu(t,r,s);case E.ZodNaN:case E.ZodNever:return yu();case E.ZodEffects:return pu(t,r,s);case E.ZodAny:return nu();case E.ZodUnknown:return Eu();case E.ZodDefault:return cu(t,r,s);case E.ZodBranded:return uu(t,r,s);case E.ZodReadonly:return Su(t,r,s);case E.ZodCatch:return lu(t,r,s);case E.ZodPipeline:return ku(t,r,s);case E.ZodFunction:case E.ZodVoid:case E.ZodSymbol:return;default:return(n=>{})(e)}},bp=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r);var zo=(t,e)=>{let r=su(e),s=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,n=T(t._def,s===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,s]},!1)??{},o=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;o!==void 0&&(n.title=o);let i=(()=>{if(ru(r.definitions))return;let c={},u=new Set;for(let f=0;f<500;f++){let h=Object.entries(r.definitions).filter(([g])=>!u.has(g));if(h.length===0)break;for(let[g,A]of h)c[g]=T(Es(A),{...r,currentPath:[...r.basePath,r.definitionPath,g]},!0)??{},u.add(g)}return c})(),a=s===void 0?i?{...n,[r.definitionPath]:i}:n:r.nameStrategy==="duplicate-ref"?{...n,...i||r.seenRefs.size?{[r.definitionPath]:{...i,...r.seenRefs.size?{[s]:n}:void 0}}:void 0}:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,s].join("/"),[r.definitionPath]:{...i,[s]:n}};return r.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":r.target==="jsonSchema2019-09"&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),a};function Mu(t){if(t.type!=="object")throw new Error(`Root schema must have type: 'object' but got type: ${t.type?`'${t.type}'`:"undefined"}`);let e=structuredClone(t);return De(e,[],e)}function jo(t){if(typeof t=="boolean")return!1;if(t.type==="null")return!0;for(let e of t.oneOf??[])if(jo(e))return!0;for(let e of t.anyOf??[])if(jo(e))return!0;return!1}function De(t,e,r){if(typeof t=="boolean")throw new TypeError(`Expected object schema but got boolean; path=${e.join("/")}`);if(!Nt(t))throw new TypeError(`Expected ${JSON.stringify(t)} to be an object; path=${e.join("/")}`);let s=t.$defs;if(Nt(s))for(let[g,A]of Object.entries(s))De(A,[...e,"$defs",g],r);let n=t.definitions;if(Nt(n))for(let[g,A]of Object.entries(n))De(A,[...e,"definitions",g],r);t.type==="object"&&!("additionalProperties"in t)&&(t.additionalProperties=!1);let i=t.required??[],a=t.properties;if(Nt(a)){for(let[g,A]of Object.entries(a))if(!jo(A)&&!i.includes(g))throw new Error(`Zod field at \`${[...e,"properties",g].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(a),t.properties=Object.fromEntries(Object.entries(a).map(([g,A])=>[g,De(A,[...e,"properties",g],r)]))}let c=t.items;Nt(c)&&(t.items=De(c,[...e,"items"],r));let u=t.anyOf;Array.isArray(u)&&(t.anyOf=u.map((g,A)=>De(g,[...e,"anyOf",String(A)],r)));let f=t.allOf;if(Array.isArray(f))if(f.length===1){let g=De(f[0],[...e,"allOf","0"],r);Object.assign(t,g),delete t.allOf}else t.allOf=f.map((g,A)=>De(g,[...e,"allOf",String(A)],r));t.default===null&&delete t.default;let h=t.$ref;if(h&&wp(t,1)){if(typeof h!="string")throw new TypeError(`Received non-string $ref - ${h}; path=${e.join("/")}`);let g=xp(r,h);if(typeof g=="boolean")throw new Error(`Expected \`$ref: ${h}\` to resolve to an object schema but got boolean`);if(!Nt(g))throw new Error(`Expected \`$ref: ${h}\` to resolve to an object but got ${JSON.stringify(g)}`);return Object.assign(t,{...g,...t}),delete t.$ref,De(t,e,r)}return t}function xp(t,e){if(!e.startsWith("#/"))throw new Error(`Unexpected $ref format ${JSON.stringify(e)}; Does not start with #/`);let r=e.slice(2).split("/"),s=t;for(let n of r){if(!Nt(s))throw new Error(`encountered non-object entry while resolving ${e} - ${JSON.stringify(s)}`);let o=s[n];if(o===void 0)throw new Error(`Key ${n} not found while resolving ${e}`);s=o}return s}function Nt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function wp(t,e){let r=0;for(let s in t)if(r++,r>e)return!0;return!1}function Pp(t,e){return zo(t,{openaiStrictMode:!0,name:e.name,nameStrategy:"duplicate-ref",$refStrategy:"extract-to-root",nullableStrategy:"property"})}function Op(t){return Mu(ii(t,{target:"draft-7",override:({zodSchema:e,jsonSchema:r})=>{let s=e._zod.def;if(s.type==="union"&&"discriminator"in s&&Array.isArray(r.oneOf)){if(r.anyOf!==void 0)throw new Error("Zod discriminated union generated both `anyOf` and `oneOf`, which cannot be represented in an OpenAI strict schema");r.anyOf=r.oneOf,delete r.oneOf}}}))}function kp(t){return"_zod"in t}function Nu(t,e,r){return sa({type:"json_schema",json_schema:{...r,name:e,strict:!0,schema:kp(t)?Op(t):Pp(t,{name:e})}},s=>t.parse(JSON.parse(s)))}var zu=["jsonSchema","functionCalling","jsonMode"];function ju(t,e){if(typeof e<"u"&&!zu.includes(e))throw new Error(`Invalid method: ${e}. Supported methods are: ${zu.join(", ")}`);let r=!t.startsWith("gpt-3")&&!t.startsWith("gpt-4-")&&t!=="gpt-4";if(r&&!e)return"jsonSchema";if(!r&&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 vp(t,e){let r={...t};return Object.defineProperties(r,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:e,enumerable:!1}}),r}function Uu(t,e,r){if(ui(t))return Nu(t,e,r);if(ai(t))return vp({type:"json_schema",json_schema:{...r,name:e,strict:!0,schema:Ut(t,{cycles:"ref",reused:"ref",override(s){s.jsonSchema.title=e}})}},s=>oi(t,JSON.parse(s)));throw new Error("Unsupported schema response format")}function Du(t,e){if(e&&typeof e=="object"&&"images"in e&&Array.isArray(e.images)){let r=e.images.filter(s=>typeof s?.image_url?.url=="string").map(s=>({type:"image",url:s.image_url.url}));return[{type:"text",text:t},...r]}return t}var Lu={"gpt-4o-2024-11-20":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.3-codex":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-codex":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-pro":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:272e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o-mini":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"text-embedding-ada-002":{maxInputTokens:8192,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1536,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-chat-latest":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"codex-mini-latest":{maxInputTokens:2e5,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.1-codex-max":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o-2024-05-13":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:4096,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.2-chat-latest":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.2-codex":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o3-deep-research":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},o1:{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.1":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o4-mini-deep-research":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.3-codex-spark":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},o3:{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"text-embedding-3-small":{maxInputTokens:8191,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1536,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4.1-nano":{maxInputTokens:1047576,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"text-embedding-3-large":{maxInputTokens:8191,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:3072,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-3.5-turbo":{maxInputTokens:16385,imageInputs:!1,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:4096,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!1,imageUrlInputs:!1,pdfToolMessage:!1,imageToolMessage:!1,toolChoice:!0},"gpt-5.1-codex-mini":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.2":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4.1":{maxInputTokens:1047576,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o3-pro":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4-turbo":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:4096,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o4-mini":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4.1-mini":{maxInputTokens:1047576,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.4":{maxInputTokens:105e4,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o1-preview":{maxInputTokens:128e3,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.4-pro":{maxInputTokens:105e4,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.5":{maxInputTokens:105e4,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:13e4,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.5-pro":{maxInputTokens:105e4,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o1-pro":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.1-codex":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.2-pro":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o3-mini":{maxInputTokens:2e5,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o-2024-08-06":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-mini":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.1-chat-latest":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4":{maxInputTokens:8192,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-nano":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o1-mini":{maxInputTokens:128e3,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0}};function ts(t,e){return typeof t=="string"?{model:t,...e??{}}:t??e}var zt=class extends _i{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;promptCacheRetention;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","reasoning_effort","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","promptCacheRetention","verbosity"]}getLsParams(t){let 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??{});let e=typeof t?.configuration?.apiKey=="string"||typeof t?.configuration?.apiKey=="function"?t?.configuration?.apiKey:void 0;this.apiKey=t?.apiKey??e??ce("OPENAI_API_KEY"),this.organization=t?.configuration?.organization??ce("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.promptCacheRetention=t?.promptCacheRetention??this.promptCacheRetention,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,this._addVersion("@langchain/openai","1.5.3")}_getReasoningParams(t){if(!Ne(this.model))return;let e;return this.reasoning!==void 0&&(e={...e,...this.reasoning}),t?.reasoning!==void 0&&(e={...e,...t.reasoning}),t?.reasoningEffort!==void 0&&e?.effort===void 0&&(e={...e,effort:t.reasoningEffort}),e}_getResponseFormat(t){return t&&t.type==="json_schema"&&t.json_schema.schema&&ns(t.json_schema.schema)?Uu(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){let e=je({baseURL:this.clientConfig.baseURL}),r={...this.clientConfig,baseURL:e,timeout:this.timeout,maxRetries:0};r.baseURL||delete r.baseURL,r.defaultHeaders=Ue(r.defaultHeaders),this.client=new v(r)}return{...this.clientConfig,...t}}_convertChatOpenAIToolToCompletionsTool(t,e){return $t(t)?Ya(t.metadata.customTool):Fs(t)?e?.strict!==void 0?{...t,function:{...t.function,strict:e.strict}}:t:Fa(t,e)}bindTools(t,e){let r;return e?.strict!==void 0?r=e.strict:this.supportsStrictToolCalling!==void 0&&(r=this.supportsStrictToolCalling),this.withConfig({tools:t.map(s=>{if(es(s)||$t(s))return s;if(Wa(s))return s.extras.providerToolDefinition;let n=this._convertChatOpenAIToolToCompletionsTool(s,{strict:r});return Ws(s)&&s.extras?.defer_loading===!0?{...n,defer_loading:!0}: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,r)=>(r&&r.tokenUsage&&(e.tokenUsage.completionTokens+=r.tokenUsage.completionTokens??0,e.tokenUsage.promptTokens+=r.tokenUsage.promptTokens??0,e.tokenUsage.totalTokens+=r.tokenUsage.totalTokens??0),e),{tokenUsage:{completionTokens:0,promptTokens:0,totalTokens:0}})}async getNumTokensFromMessages(t){let e=0,r=0,s=0;this.model==="gpt-3.5-turbo-0301"?(r=4,s=-1):(r=3,s=1);let n=await Promise.all(t.map(async o=>{let[i,a]=await Promise.all([this.getNumTokens(o.content),this.getNumTokens(ze(o))]),c=o.name!==void 0?s+await this.getNumTokens(o.name):0,u=i+r+a+c,f=o;if(f._getType()==="function"&&(u-=2),f.additional_kwargs?.function_call&&(u+=3),f?.additional_kwargs.function_call?.name&&(u+=await this.getNumTokens(f.additional_kwargs.function_call?.name)),f.additional_kwargs.function_call?.arguments)try{u+=await this.getNumTokens(JSON.stringify(JSON.parse(f.additional_kwargs.function_call?.arguments)))}catch(h){console.error("Error parsing function arguments",h,JSON.stringify(f.additional_kwargs.function_call)),u+=await this.getNumTokens(f.additional_kwargs.function_call?.arguments)}return e+=u,u}));return e+=3,{totalCount:e,countPerMessage:n}}async _getNumTokensFromGenerations(t){return(await Promise.all(t.map(async e=>e.message.additional_kwargs?.function_call?(await this.getNumTokensFromMessages([e.message])).countPerMessage[0]:await this.getNumTokens(e.message.content)))).reduce((e,r)=>e+r,0)}async _getEstimatedTokenCountFromPrompt(t,e,r){let s=(await this.getNumTokensFromMessages(t)).totalCount;if(e&&r!=="auto"){let n=Ba(e);s+=await this.getNumTokens(n),s+=9}return e&&t.find(n=>n._getType()==="system")&&(s-=4),r==="none"?s+=1:typeof r=="object"&&(s+=await this.getNumTokens(r.name)+4),s}async moderateContent(t,e){let r=this._getClientOptions(e?.options),s={input:t,model:e?.model??"omni-moderation-latest"};return this.caller.call(async()=>{try{return await this.client.moderations.create(s,r)}catch(n){throw le(n)}})}get profile(){return Lu[this.model]??{}}_getStructuredOutputMethod(t){let 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 r,s,{schema:n,name:o,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'");let a=ju(this.model,e?.method);if(a==="jsonMode"){s=Bn(n);let c=Ut(n);r=this.withConfig({outputVersion:"v0",response_format:{type:"json_object"},ls_structured_output_format:{kwargs:{method:"json_mode"},schema:{title:o??"extract",...c}}})}else if(a==="jsonSchema"){let c=Ut(n),u={name:o??"extract",description:li(c),schema:ns(n)?n:c,strict:e?.strict};if(r=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,...c}}}),ns(n)||Kn(n)){let f=Bn(n);s=ci.from(async h=>"parsed"in h.additional_kwargs?h.additional_kwargs.parsed:f.invoke(h.content))}else s=new mi}else{let c=o??"extract",u=Ut(n),f;ns(n)||Kn(n)?f={name:c,description:u.description,parameters:u}:typeof n.name=="string"&&typeof n.parameters=="object"&&n.parameters!=null?(f=n,c=n.name):(c=n.title??c,f={name:c,description:n.description??"",parameters:n}),r=this.withConfig({outputVersion:"v0",tools:[{type:"function",function:f}],tool_choice:{type:"function",function:{name:c}},ls_structured_output_format:{kwargs:{method:"function_calling"},schema:{title:c,...u}},...e?.strict!==void 0?{strict:e.strict}:{}}),s=di(n,c)}return fi(r,s,i)}};var Tn={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"){let e=Dn({dataUrl:t.url});if(!e)throw new Error(`URL audio blocks with source_type ${t.source_type} must be formatted as a data URL for ChatOpenAI`);let r=e.mime_type||t.mime_type||"",s;try{s=Un(r)}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=Un(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"){let e=Dn({dataUrl:t.url}),r=St(t);if(!e)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,filename:r}}}if(t.source_type==="base64"){let e=St(t);return{type:"file",file:{file_data:`data:${t.mime_type??""};base64,${t.data}`,filename:e}}}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`)}},Uo=({message:t,rawResponse:e,includeRawResponse:r})=>{let s=t.tool_calls,n=t.reasoning_content;switch(t.role){case"assistant":{let o=[],i=[];for(let u of s??[])try{o.push(Bs(u,{returnId:!0}))}catch(f){i.push(Dt(u,f.message))}let a={function_call:t.function_call,tool_calls:s};r!==void 0&&(a.__raw_response=e),n!==void 0&&(a.reasoning_content=n);let c={model_provider:"openai",model_name:e.model,...e.system_fingerprint?{usage:{...e.usage},system_fingerprint:e.system_fingerprint}:{}};return t.audio&&(a.audio=t.audio),new ie({content:Du(t.content||"",e.choices?.[0]?.message),tool_calls:o,invalid_tool_calls:i,additional_kwargs:a,response_metadata:c,id:e.id})}default:return new Ks(t.content||"",t.role??"unknown")}},Do=({delta:t,rawResponse:e,includeRawResponse:r,defaultRole:s})=>{let n=t.role??s,o=t.content??"",i;t.function_call?i={function_call:t.function_call}:t.tool_calls?i={tool_calls:t.tool_calls}:i={},r&&(i.__raw_response=e),t.reasoning_content!==void 0&&(i.reasoning_content=t.reasoning_content),t.audio&&(i.audio={...t.audio,index:e.choices[0].index});let a={model_provider:"openai",usage:{...e.usage}};if(n==="user")return new si({content:o,response_metadata:a});if(n==="assistant"){let c=[];if(Array.isArray(t.tool_calls))for(let u of t.tool_calls)c.push({name:u.function?.name,args:u.function?.arguments,id:u.id,index:u.index,type:"tool_call_chunk"});return new jt({content:o,tool_call_chunks:c,additional_kwargs:i,id:e.id,response_metadata:a})}else return n==="system"?new Ln({content:o,response_metadata:a}):n==="developer"?new Ln({content:o,response_metadata:a,additional_kwargs:{__openai_role__:"developer"}}):n==="function"?new ri({content:o,additional_kwargs:i,name:t.name,response_metadata:a}):n==="tool"?new Qo({content:o,additional_kwargs:i,tool_call_id:t.tool_call_id,response_metadata:a}):new ti({content:o,role:n,response_metadata:a})},Ku=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){let e=ni(()=>{let[,r]=t.mimeType.split("/");return r==="wav"||r==="mp3"?r:"wav"});return{type:"input_audio",input_audio:{data:t.data.toString(),format:e}}}if(t.type==="file"){if(t.data){let e=St(t);return{type:"file",file:{file_data:`data:${t.mimeType};base64,${t.data}`,filename:e}}}if(t.fileId)return{type:"file",file:{file_id:t.fileId}}}},Fu=({message:t,model:e})=>{let r=ze(t);if(r==="system"&&Ne(e)&&(r="developer"),r==="developer")return{role:"developer",content:t.contentBlocks.filter(n=>n.type==="text")};if(r==="system")return{role:"system",content:t.contentBlocks.filter(n=>n.type==="text")};if(r==="assistant"){let n={role:"assistant",content:t.contentBlocks.filter(o=>o.type==="text")};return ie.isInstance(t)&&t.tool_calls?.length?n.tool_calls=t.tool_calls.map(Fn):t.additional_kwargs.tool_calls!=null&&(n.tool_calls=t.additional_kwargs.tool_calls),n}else{if(r==="tool"&&Ds.isInstance(t))return{role:"tool",tool_call_id:t.tool_call_id,content:t.contentBlocks.filter(n=>n.type==="text")};if(r==="function")return{role:"function",name:t.name??"",content:t.contentBlocks.filter(n=>n.type==="text").join("")}}function*s(n){for(let o of n){o.type==="text"&&(yield{type:"text",text:o.text});let i=Ku(o);i&&(yield i)}}return{role:"user",content:Array.from(s(t.contentBlocks))}},rs=({messages:t,model:e})=>t.flatMap(r=>{if("output_version"in r.response_metadata&&r.response_metadata?.output_version==="v1")return Fu({message:r});let s=ze(r);s==="system"&&Ne(e)&&(s="developer");let n=typeof r.content=="string"?r.content:r.content.flatMap(i=>js(i)?Us(i,Tn):typeof i=="object"&&i!==null&&"type"in i&&i.type==="tool_use"?[]:i),o={role:s,content:n};return r.name!=null&&(o.name=r.name),r.additional_kwargs.function_call!=null&&(o.function_call=r.additional_kwargs.function_call),ie.isInstance(r)&&r.tool_calls?.length?o.tool_calls=r.tool_calls.map(Fn):(r.additional_kwargs.tool_calls!=null&&(o.tool_calls=r.additional_kwargs.tool_calls),Ds.isInstance(r)&&r.tool_call_id!=null&&(o.tool_call_id=r.tool_call_id)),r.additional_kwargs.audio&&typeof r.additional_kwargs.audio=="object"&&"id"in r.additional_kwargs.audio?[o,{role:"assistant",audio:{id:r.additional_kwargs.audio.id}}]:o});var Cn=class extends zt{constructor(t,e){super(ts(t,e))}invocationParams(t,e){let r;t?.strict!==void 0?r=t.strict:this.supportsStrictToolCalling!==void 0&&(r=this.supportsStrictToolCalling),!(this.streaming||e?.streaming)&&t?.response_format?.type==="json_schema"&&r!==!1&&(r=!0);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}});let n={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:r})):void 0,tool_choice:Pn(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,prompt_cache_retention:t?.promptCacheRetention??this.promptCacheRetention,verbosity:t?.verbosity??this.verbosity};t?.prediction!==void 0&&(n.prediction=t.prediction),this.service_tier!==void 0&&(n.service_tier=this.service_tier),t?.service_tier!==void 0&&(n.service_tier=t.service_tier);let o=this._getReasoningParams(t);return o!==void 0&&o.effort!==void 0&&(n.reasoning_effort=o.effort),Ne(n.model)?n.max_completion_tokens=this.maxTokens===-1?void 0:this.maxTokens:n.max_tokens=this.maxTokens===-1?void 0:this.maxTokens,n}async _generate(t,e,r){e.signal?.throwIfAborted();let s={},n=this.invocationParams(e),o=rs({messages:t,model:this.model});if(n.stream){let i=this._streamResponseChunks(t,e,r),a={};for await(let A of i){A.message.response_metadata={...A.generationInfo,...A.message.response_metadata};let I=A.generationInfo?.completion??0;a[I]===void 0?a[I]=A:a[I]=a[I].concat(A)}let c=Object.entries(a).sort(([A],[I])=>parseInt(A,10)-parseInt(I,10)).map(([A,I])=>I),{functions:u,function_call:f}=this.invocationParams(e),h=await this._getEstimatedTokenCountFromPrompt(t,u,f),g=await this._getNumTokensFromGenerations(c);return s.input_tokens=h,s.output_tokens=g,s.total_tokens=h+g,{generations:c,llmOutput:{estimatedTokenUsage:{promptTokens:s.input_tokens,completionTokens:s.output_tokens,totalTokens:s.total_tokens}}}}else{let i=await this.completionWithRetry({...n,stream:!1,messages:o},{signal:e?.signal,...e?.options}),{completion_tokens:a,prompt_tokens:c,total_tokens:u,prompt_tokens_details:f,completion_tokens_details:h}=i?.usage??{};a&&(s.output_tokens=(s.output_tokens??0)+a),c&&(s.input_tokens=(s.input_tokens??0)+c),u&&(s.total_tokens=(s.total_tokens??0)+u),(f?.audio_tokens!==null||f?.cached_tokens!==null)&&(s.input_token_details={...f?.audio_tokens!==null&&{audio:f?.audio_tokens},...f?.cached_tokens!==null&&{cache_read:f?.cached_tokens}}),(h?.audio_tokens!==null||h?.reasoning_tokens!==null)&&(s.output_token_details={...h?.audio_tokens!==null&&{audio:h?.audio_tokens},...h?.reasoning_tokens!==null&&{reasoning:h?.reasoning_tokens}});let g=[];for(let A of i?.choices??[]){let I={text:A.message?.content??"",message:this._convertCompletionsMessageToBaseMessage(A.message??{role:"assistant"},i)};I.generationInfo={...A.finish_reason?{finish_reason:A.finish_reason}:{},...A.logprobs?{logprobs:A.logprobs}:{}},Ls(I.message)&&(I.message.usage_metadata=s),I.message=new ie(Object.fromEntries(Object.entries(I.message).filter(([b])=>!b.startsWith("lc_")))),g.push(I)}return{generations:g,llmOutput:{tokenUsage:{promptTokens:s.input_tokens,completionTokens:s.output_tokens,totalTokens:s.total_tokens}}}}}async*_streamChatModelEvents(t,e,r){let s=rs({messages:t,model:this.model}),n={...this.invocationParams(e,{streaming:!0}),messages:s,stream:!0},o=await this.completionWithRetry(n,e),i=this.streamUsage??e.streamUsage;yield*qs(async function*(c,u){for await(let f of c){if(u?.aborted)return;yield f}}(o,e.signal),{streamUsage:i??!0,provider:this.streamEventProvider})}get streamEventProvider(){return"openai"}async*_streamResponseChunks(t,e,r){let s=rs({messages:t,model:this.model}),n={...this.invocationParams(e,{streaming:!0}),messages:s,stream:!0},o,i=await this.completionWithRetry(n,e),a;for await(let c of i){if(e.signal?.aborted)return;let u=c?.choices?.[0];if(c.usage&&(a=c.usage),!u)continue;let{delta:f}=u;if(!f)continue;let h=this._convertCompletionsDeltaToBaseMessageChunk(f,c,o);o=f.role??o;let g={prompt:e.promptIndex??0,completion:u.index??0};if(typeof h.content!="string"){console.log("[WARNING]: Received non-string content from OpenAI. This is currently not supported.");continue}let A={...g};u.finish_reason!=null&&(A.finish_reason=u.finish_reason,A.system_fingerprint=c.system_fingerprint,A.model_name=c.model,A.service_tier=c.service_tier),this.logprobs&&(A.logprobs=u.logprobs);let I=new ss({message:h,text:h.content,generationInfo:A});yield I,await r?.handleLLMNewToken(I.text??"",g,void 0,void 0,void 0,{chunk:I})}if(a){let c={...a.prompt_tokens_details?.audio_tokens!==null&&{audio:a.prompt_tokens_details?.audio_tokens},...a.prompt_tokens_details?.cached_tokens!==null&&{cache_read:a.prompt_tokens_details?.cached_tokens}},u={...a.completion_tokens_details?.audio_tokens!==null&&{audio:a.completion_tokens_details?.audio_tokens},...a.completion_tokens_details?.reasoning_tokens!==null&&{reasoning:a.completion_tokens_details?.reasoning_tokens}},f=new ss({message:new jt({content:"",response_metadata:{usage:{...a}},usage_metadata:{input_tokens:a.prompt_tokens,output_tokens:a.completion_tokens,total_tokens:a.total_tokens,...Object.keys(c).length>0&&{input_token_details:c},...Object.keys(u).length>0&&{output_token_details:u}}}),text:""});yield f,await r?.handleLLMNewToken(f.text??"",{prompt:0,completion:0},void 0,void 0,void 0,{chunk:f})}if(e.signal?.aborted)throw new Error("AbortError")}async completionWithRetry(t,e){let r=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,r):await this.client.chat.completions.create(t,r)}catch(n){throw le(n)}})}_convertCompletionsDeltaToBaseMessageChunk(t,e,r){return Do({delta:t,rawResponse:e,includeRawResponse:this.__includeRawResponse,defaultRole:r})}_convertCompletionsMessageToBaseMessage(t,e){return Uo({message:t,rawResponse:e,includeRawResponse:this.__includeRawResponse})}};var Rn="__openai_function_call_ids__",En="__openai_custom_tool_call_ids__";function Ju(t){return t.type==="url_citation"?{type:"citation",source:"url_citation",url:t.url,title:t.title,startIndex:t.start_index,endIndex:t.end_index}:t.type==="file_citation"?{type:"citation",source:"file_citation",title:t.filename,startIndex:t.index,file_id:t.file_id}:t.type==="container_file_citation"?{type:"citation",source:"container_file_citation",title:t.filename,startIndex:t.start_index,endIndex:t.end_index,file_id:t.file_id,container_id:t.container_id}:t.type==="file_path"?{type:"citation",source:"file_path",startIndex:t.index,file_id:t.file_id}:{type:"non_standard",value:t}}function Cp(t){if(t.type==="url_citation"||t.type==="file_citation"||t.type==="container_file_citation"||t.type==="file_path")return t;if(t.type==="citation"){let e=t;if(e.source==="url_citation")return{type:"url_citation",url:e.url??"",title:e.title??"",start_index:e.startIndex??0,end_index:e.endIndex??0};if(e.source==="file_citation")return{type:"file_citation",file_id:e.file_id??"",filename:e.title??"",index:e.startIndex??0};if(e.source==="container_file_citation")return{type:"container_file_citation",file_id:e.file_id??"",filename:e.title??"",container_id:e.container_id??"",start_index:e.startIndex??0,end_index:e.endIndex??0};if(e.source==="file_path")return{type:"file_path",file_id:e.file_id??"",index:e.startIndex??0}}return t.type==="non_standard"?t.value:t}var $s=t=>{let e={...t?.input_tokens_details?.cached_tokens!=null&&{cache_read:t?.input_tokens_details?.cached_tokens}},r={...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:r}},Sn=t=>{if(t.error){let a=new Error(t.error.message);throw a.name=t.error.code,a}let e=[],r=[],s=[],n=t.output.map(a=>{if(a.type==="function_call"&&"parsed_arguments"in a){let c={...a};return delete c.parsed_arguments,c}return a}),o={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,output:n,status:t.status,user:t.user,service_tier:t.service_tier,model_name:t.model},i={};for(let a of t.output)if(a.type==="message")e.push(...a.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.map(Ju),...a.phase!==null?{phase:a.phase}:{}}):c.type==="refusal"?(i.refusal=c.refusal,[]):c));else if(a.type==="function_call"){let c={function:{name:a.name,arguments:a.arguments},id:a.call_id};try{r.push(Bs(c,{returnId:!0}))}catch(u){let f;typeof u=="object"&&u!=null&&"message"in u&&typeof u.message=="string"&&(f=u.message),s.push(Dt(c,f))}i[Rn]??={},a.id&&(i[Rn][a.call_id]=a.id)}else if(a.type==="reasoning"){i.reasoning=a;let c=a.summary?.map(u=>u.text).filter(Boolean).join("");c&&e.push({type:"reasoning",reasoning:c})}else if(a.type==="custom_tool_call"){let c=Za(a);c?(r.push(c),i[En]??={},a.id&&a.call_id&&(i[En][a.call_id]=a.id)):s.push(Dt(a,"Malformed custom tool call"))}else if(a.type==="computer_call"){let c=Va(a);c?r.push(c):s.push(Dt(a,"Malformed computer call"))}else a.type==="image_generation_call"?(a.result&&e.push({type:"image",mimeType:"image/png",data:a.result,id:a.id,metadata:{status:a.status}}),i.tool_outputs??=[],i.tool_outputs.push(a)):(i.tool_outputs??=[],i.tool_outputs.push(a));return new ie({id:t.id,content:e,tool_calls:r,invalid_tool_calls:s,usage_metadata:$s(t.usage),additional_kwargs:i,response_metadata:o})},Gu=t=>{let e=(t.summary.length>1?t.summary.reduce((r,s)=>{let n=r[r.length-1];return n.index===s.index?n.text+=s.text:r.push(s),r},[{...t.summary[0]}]):t.summary).map(r=>Object.fromEntries(Object.entries(r).filter(([s])=>s!=="index")));return{...t,summary:e}},Lo=t=>{let e=[],r={},s,n=[],o={model_provider:"openai"},i={},a;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:[Ju(t.annotation)],index:t.content_index});else if(t.type==="response.output_item.added"&&t.item.type==="message"){let c="phase"in t.item?t.item.phase:void 0;c&&e.push({type:"text",text:"",phase:c,index:0})}else if(t.type==="response.output_item.added"&&t.item.type==="function_call")n.push({type:"tool_call_chunk",name:t.item.name,args:t.item.arguments,id:t.item.call_id,index:t.output_index}),i[Rn]={[t.item.call_id]:t.item.id};else if(t.type==="response.output_item.added"&&t.item.type==="custom_tool_call")n.push({type:"tool_call_chunk",isCustomTool:!0,name:t.item.name,args:t.item.input,id:t.item.call_id,index:t.output_index}),i[En]={[t.item.call_id]:t.item.id};else if(t.type==="response.output_item.done"&&t.item.type==="computer_call")n.push({type:"tool_call_chunk",name:"computer_use",args:JSON.stringify({action:t.item.action}),id:t.item.call_id,index:t.output_index}),i.tool_outputs=[t.item];else if(t.type==="response.output_item.done"&&t.item.type==="image_generation_call")t.item.result&&e.push({type:"image",mimeType:"image/png",data:t.item.result,id:t.item.id,metadata:{status:t.item.status}}),i.tool_outputs=[t.item];else if(t.type==="response.output_item.done"&&["web_search_call","file_search_call","code_interpreter_call","shell_call","local_shell_call","mcp_call","mcp_list_tools","mcp_approval_request","custom_tool_call","tool_search_call","tool_search_output"].includes(t.item.type))i.tool_outputs=[t.item];else if(t.type==="response.created")a=t.response.id,o.id=t.response.id,o.model_name=t.response.model,o.model=t.response.model;else if(t.type==="response.completed"||t.type==="response.incomplete"){a=t.response.id;let c=Sn(t.response);if(s=$s(t.response.usage),t.response.text?.format?.type==="json_schema"&&c.text)try{i.parsed??=JSON.parse(c.text)}catch{}for(let[u,f]of Object.entries(t.response))u!=="id"&&(u==="output"?o[u]=c.response_metadata.output:o[u]=f)}else if(t.type==="response.function_call_arguments.delta"||t.type==="response.custom_tool_call_input.delta")n.push({type:"tool_call_chunk",args:t.delta,index:t.output_index,...t.type==="response.custom_tool_call_input.delta"?{isCustomTool:!0}:{}});else if(t.type==="response.web_search_call.in_progress"||t.type==="response.web_search_call.searching"||t.type==="response.web_search_call.completed"||t.type==="response.file_search_call.in_progress"||t.type==="response.file_search_call.searching"||t.type==="response.file_search_call.completed"||t.type==="response.image_generation_call.in_progress"||t.type==="response.image_generation_call.generating"||t.type==="response.image_generation_call.completed"){let[,c,u]=t.type.match(/^response\.(.*)\.([^.]+)$/)??["","",""];r={tool_outputs:{id:t.item_id,type:c,status:u}}}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"){let c=t.item.summary?t.item.summary.map((f,h)=>({...f,index:h})):void 0;i.reasoning={id:t.item.id,type:t.item.type,...c?{summary:c}:{}};let u=t.item.summary?.map(f=>f.text).filter(Boolean).join("");u&&e.push({type:"reasoning",reasoning:u})}else if(t.type==="response.reasoning_summary_part.added")i.reasoning={type:"reasoning",summary:[{...t.part,index:t.summary_index}]},t.part.text&&e.push({type:"reasoning",reasoning:t.part.text,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}]},t.delta&&e.push({type:"reasoning",reasoning:t.delta,index:t.summary_index});else return t.type==="response.image_generation_call.partial_image",null;return new ss({text:e.map(c=>c.text).join(""),message:new jt({id:a,content:e,tool_call_chunks:n,usage_metadata:s,additional_kwargs:i,response_metadata:o}),generationInfo:r})},Xu=t=>{let e=ie.isInstance(t)&&t.response_metadata?.model_provider==="openai";function*r(){let s=he(()=>{try{let m=ze(t);return m==="system"||m==="developer"||m==="assistant"||m==="user"?m:"assistant"}catch{return"assistant"}}),n,o=new Set,i=new Set,a=new Map,c=new Map;function*u(){if(!n)return;let m=n.content;(typeof m=="string"&&m.length>0||Array.isArray(m)&&m.length>0)&&(yield n),n=void 0}let f=(m,y)=>{n||(n={type:"message",role:s,content:[],...y?{phase:y}:{}}),typeof n.content=="string"?n.content=n.content.length>0?[{type:"input_text",text:n.content},...m]:[...m]:n.content.push(...m)},h=m=>{if(typeof m=="string")return m;try{return JSON.stringify(m??{})}catch{return"{}"}},g=m=>{let y=he(()=>{let O=m.metadata?.detail;return O==="low"||O==="high"||O==="auto"?O:"auto"});if(m.fileId)return{type:"input_image",detail:y,file_id:m.fileId};if(m.url)return{type:"input_image",detail:y,image_url:m.url};if(m.data){let O=typeof m.data=="string"?m.data:Buffer.from(m.data).toString("base64");return{type:"input_image",detail:y,image_url:`data:${m.mimeType??"image/png"};base64,${O}`}}},A=m=>{if(m.fileId){let y=xn(m);return{type:"input_file",file_id:m.fileId,...y?{filename:y}:{}}}if(m.url){let y=xn(m);return{...y?{filename:y}:{},type:"input_file",file_url:m.url}}if(m.data){let y=St(m),O=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,${O}`,filename:y}}},I=m=>{let y=he(()=>{if(Array.isArray(m.summary)){let R=m.summary?.map(N=>N?.text).filter(N=>typeof N=="string")??[];if(R.length>0)return R}return m.reasoning?[m.reasoning]:[]}),O=y.length>0?y.map(R=>({type:"summary_text",text:R})):[{type:"summary_text",text:""}];return{type:"reasoning",...m.id?{id:m.id}:{},summary:O}},b=m=>({type:"function_call",name:m.name??"",call_id:m.id??"",arguments:h(m.args)}),_=m=>{let y=h(m.output),O=m.status==="success"?"completed":m.status==="error"?"incomplete":void 0;return{type:"function_call_output",call_id:m.toolCallId??"",output:y,...O?{status:O}:{}}};for(let m of t.contentBlocks)if(m.type==="text"){let y=he(()=>{if("extras"in m&&typeof m.extras=="object"&&m.extras!==null&&"phase"in m.extras)return m.extras.phase});f([{type:"input_text",text:m.text}],y)}else if(m.type!=="invalid_tool_call"){if(m.type==="reasoning")yield*u(),yield I(m);else if(m.type==="tool_call"){yield*u();let y=m.id??"";y&&(o.add(y),a.delete(y)),yield b(m)}else if(m.type==="tool_call_chunk"){if(m.id){let y=a.get(m.id)??{name:m.name,args:[]};m.name&&(y.name=m.name),m.args&&y.args.push(m.args),a.set(m.id,y)}}else if(m.type==="server_tool_call"){yield*u();let y=m.id??"";y&&(i.add(y),c.delete(y)),yield b(m)}else if(m.type==="server_tool_call_chunk"){if(m.id){let y=c.get(m.id)??{name:m.name,args:[]};m.name&&(y.name=m.name),m.args&&y.args.push(m.args),c.set(m.id,y)}}else if(m.type==="server_tool_call_result")yield*u(),yield _(m);else if(m.type!=="audio")if(m.type==="file"){let y=A(m);y&&f([y])}else if(m.type==="image"){let y=g(m);y&&f([y])}else if(m.type==="video"){let y=A(m);y&&f([y])}else m.type==="text-plain"?m.text&&f([{type:"input_text",text:m.text}]):m.type==="non_standard"&&e&&(yield*u(),yield m.value)}yield*u();for(let[m,y]of a){if(!m||o.has(m))continue;let O=y.args.join("");!y.name&&!O||(yield{type:"function_call",call_id:m,name:y.name??"",arguments:O})}for(let[m,y]of c){if(!m||i.has(m))continue;let O=y.args.join("");!y.name&&!O||(yield{type:"function_call",call_id:m,name:y.name??"",arguments:O})}}return Array.from(r())},Ms=({messages:t,zdrEnabled:e,model:r})=>t.flatMap(s=>{let n=s.response_metadata;if(n?.output_version==="v1")return Xu(s);let o=s.additional_kwargs,i=ze(s);if(i==="system"&&Ne(r)&&(i="developer"),i==="function")throw new Error("Function messages are not supported in Responses API");if(i==="tool"){let a=s;if(o?.type==="computer_call_output")return{type:"computer_call_output",output:(()=>{if(typeof a.content=="string")return{type:"input_image",image_url:a.content};if(Array.isArray(a.content)){let u=a.content.find(g=>g.type==="input_image");if(u)return u;let f=a.content.find(g=>g.type==="computer_screenshot");if(f)return f;let h=a.content.find(g=>g.type==="image_url");if(h)return{type:"input_image",image_url:typeof h.image_url=="string"?h.image_url:h.image_url.url}}throw new Error("Invalid computer call output")})(),call_id:a.tool_call_id};if(a.additional_kwargs?.customTool)return{type:"custom_tool_call_output",call_id:a.tool_call_id,output:a.content};let c=Array.isArray(a.content)&&a.content.every(u=>typeof u=="object"&&u!==null&&"type"in u&&(u.type==="input_file"||u.type==="input_image"||u.type==="input_text"));return{type:"function_call_output",call_id:a.tool_call_id,id:a.id?.startsWith("fc_")?a.id:void 0,output:c?a.content:typeof a.content!="string"?JSON.stringify(a.content):a.content}}if(i==="assistant"){if(!e&&n?.output!=null&&Array.isArray(n?.output)&&n?.output.length>0&&n?.output.every(b=>"type"in b))return n?.output;let a=[],c=o?.reasoning,u=!!c?.encrypted_content;if(c&&(!e||u)){let b=Gu(c);a.push(b)}let{content:f}=s;if(o?.refusal&&(typeof f=="string"&&(f=[{type:"output_text",text:f,annotations:[]}]),f=[...f,{type:"refusal",refusal:o.refusal}]),typeof f=="string"||f.length>0){let b={type:"message",role:"assistant",...s.id&&!e&&s.id.startsWith("msg_")?{id:s.id}:{},content:he(()=>typeof f=="string"?f:f.flatMap(_=>{if(_.type==="text"){let m=_;return{type:"output_text",text:m.text,annotations:(m.annotations??[]).map(Cp)}}return _.type==="output_text"||_.type==="refusal"?_:[]})),phase:he(()=>{if(Array.isArray(f))return f.find(_=>"phase"in _&&typeof _.phase=="string")?.phase})};a.push(b)}let h=o?.[Rn],g=o?.[En];ie.isInstance(s)&&s.tool_calls?.length?a.push(...s.tool_calls.map(b=>Ga(b,g)?{type:"custom_tool_call",id:"call_id"in b&&typeof b.call_id=="string"?b.call_id:g?.[b.id??""]??"",call_id:b.id??"",input:b.args.input,name:b.name}:Ja(b)?{type:"computer_call",id:b.call_id,call_id:b.id??"",action:b.args.action}:{type:"function_call",name:b.name,arguments:JSON.stringify(b.args),call_id:b.id,...e?{}:{id:h?.[b.id]}})):o?.tool_calls&&a.push(...o.tool_calls.map(b=>({type:"function_call",name:b.function.name,call_id:b.id,arguments:b.function.arguments,...e?{}:{id:h?.[b.id]}})));let A=n?.output?.length?n?.output:o.tool_outputs,I=["computer_call","mcp_call","code_interpreter_call","image_generation_call","shell_call","local_shell_call"];if(A!=null){let b=A?.filter(_=>I.includes(_.type));b.length>0&&a.push(...b)}return a}if(i==="user"||i==="system"||i==="developer"){if(typeof s.content=="string")return{type:"message",role:i,content:s.content};let a=[],c=s.content.flatMap(u=>{if(u.type==="mcp_approval_response"&&a.push({type:"mcp_approval_response",approval_request_id:u.approval_request_id,approve:u.approve}),js(u)){if(u.type==="file"){let f=xn(u);if(u.source_type==="url")return{type:"input_file",file_url:u.url,...f?{filename:f}:{}};if(u.source_type==="id")return{type:"input_file",file_id:u.id,...f?{filename:f}:{}};if(u.source_type==="base64")return{type:"input_file",file_data:`data:${u.mime_type??""};base64,${u.data}`,filename:St(u)}}return Us(u,Tn)}return u.type==="text"?{type:"input_text",text:u.text}:u.type==="image_url"?{type:"input_image",image_url:he(()=>{if(typeof u.image_url=="string")return u.image_url;if(typeof u.image_url=="object"&&u.image_url!==null&&"url"in u.image_url)return u.image_url.url}),detail:he(()=>{if(typeof u.image_url=="string")return"auto";if(typeof u.image_url=="object"&&u.image_url!==null&&"detail"in u.image_url)return u.image_url.detail})}:u.type==="input_text"||u.type==="input_image"||u.type==="input_file"?u:[]});return c.length>0&&a.push({type:"message",role:i,content:c}),a}return console.warn(`Unsupported role found when converting to OpenAI Responses API: ${i}`),[]});async function*Ko(t,e={}){let r=e.streamUsage??!0,s=e.provider??"openai",n=new Map,o=new Map,i=0,a=!1,c,u,f,h,g=new Set,A=(_,m)=>{let y=o.get(_);if(y!==void 0)return{index:y,isNew:!1};let O=i++;return o.set(_,O),n.set(O,{...m}),{index:O,isNew:!0}},I=function*(){a||(a=!0,yield{event:"message-start",id:c})},b=function*(_){if(g.has(_))return;let m=n.get(_);m&&(g.add(_),yield{event:"content-block-finish",index:_,content:hi(m)})};for await(let _ of t){if(_.type==="response.created"){c=_.response.id,yield*I(),yield{event:"provider",provider:s,name:"response.created",payload:{model:_.response.model,id:_.response.id}};continue}if(_.type==="response.output_text.delta"){yield*I();let{index:m,isNew:y}=A(`text:${_.output_index}:${_.content_index}`,{type:"text",text:""});y&&(yield{event:"content-block-start",index:m,content:{type:"text",text:""}});let O=n.get(m);O.text=(O.text??"")+_.delta,yield{event:"content-block-delta",index:m,delta:{type:"text-delta",text:_.delta}};continue}if(_.type==="response.reasoning_summary_text.delta"){yield*I();let{index:m,isNew:y}=A(`reasoning:${_.output_index}:${_.summary_index}`,{type:"reasoning",reasoning:""});y&&(yield{event:"content-block-start",index:m,content:{type:"reasoning",reasoning:""}});let O=n.get(m);O.reasoning=(O.reasoning??"")+_.delta,yield{event:"content-block-delta",index:m,delta:{type:"reasoning-delta",reasoning:_.delta}};continue}if(_.type==="response.output_item.added"&&(_.item.type==="function_call"||_.item.type==="custom_tool_call")){yield*I();let m=`tool:${_.output_index}`,y=_.item.type==="custom_tool_call",O=_.item.type==="function_call"?_.item.arguments??"":_.item.input??"",{index:R,isNew:N}=A(m,{type:"tool_call_chunk",id:_.item.call_id,name:_.item.name,args:O,index:_.output_index,...y?{isCustomTool:!0}:{}});if(N&&(yield{event:"content-block-start",index:R,content:{type:"tool_call_chunk",id:_.item.call_id,name:_.item.name,args:O,index:_.output_index}}),O){let z=n.get(R);yield{event:"content-block-delta",index:R,delta:{type:"block-delta",fields:{type:"tool_call_chunk",...z.id!=null?{id:z.id}:{},...z.name!=null?{name:z.name}:{},args:z.args}}}}continue}if(_.type==="response.function_call_arguments.delta"||_.type==="response.custom_tool_call_input.delta"){yield*I();let{index:m,isNew:y}=A(`tool:${_.output_index}`,{type:"tool_call_chunk",args:"",index:_.output_index,..._.type==="response.custom_tool_call_input.delta"?{isCustomTool:!0}:{}});y&&(yield{event:"content-block-start",index:m,content:{type:"tool_call_chunk",args:"",index:_.output_index}});let O=n.get(m);O.args=(O.args??"")+_.delta,yield{event:"content-block-delta",index:m,delta:{type:"block-delta",fields:{type:"tool_call_chunk",...O.id!=null?{id:O.id}:{},...O.name!=null?{name:O.name}:{},args:O.args}}};continue}if(_.type==="response.output_item.done"&&(_.item.type==="function_call"||_.item.type==="custom_tool_call")){yield*I();let m=`tool:${_.output_index}`,y=_.item.type==="function_call"?_.item.arguments??"":_.item.input??"",{index:O,isNew:R}=A(m,{type:"tool_call_chunk",id:_.item.call_id,name:_.item.name,args:y,index:_.output_index});if(R)yield{event:"content-block-start",index:O,content:{type:"tool_call_chunk",id:_.item.call_id,name:_.item.name,args:y,index:_.output_index}};else{let N=n.get(O);N.args=y,N.id=_.item.call_id,N.name=_.item.name}yield*b(O);continue}if(_.type==="response.completed"||_.type==="response.incomplete"){yield*I(),c=_.response.id,f=Rp(_.response.status,_.type),h={model_provider:s,id:_.response.id,model:_.response.model,status:_.response.status},r&&_.response.usage&&(u=$s(_.response.usage),yield{event:"usage",usage:u});continue}_.type!=="response.image_generation_call.partial_image"&&(yield*I(),yield{event:"provider",provider:s,name:_.type,payload:_})}a||(yield{event:"message-start"});for(let[_]of n)g.has(_)||(yield*b(_));yield{event:"message-finish",reason:f,...u?{usage:u}:{},...h?{responseMetadata:h}:{}}}function Rp(t,e){return e==="response.incomplete"?"length":t==="completed"?"stop":t==="incomplete"?"length":"stop"}var $n=class extends zt{constructor(t,e){super(ts(t,e))}invocationParams(t){let e;t?.strict!==void 0&&(e=t.strict),e===void 0&&this.supportsStrictToolCalling!==void 0&&(e=this.supportsStrictToolCalling);let r={model:this.model,temperature:this.temperature,top_p:this.topP,user:this.user,service_tier:this.service_tier,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:Ha(t?.tool_choice)?t?.tool_choice:(()=>{let n=Pn(t?.tool_choice);if(typeof n=="object"&&"type"in n){if(n.type==="function")return{type:"function",name:n.function.name};if(n.type==="allowed_tools")return{type:"allowed_tools",mode:n.allowed_tools.mode,tools:n.allowed_tools.tools};if(n.type==="custom")return{type:"custom",name:n.custom.name}}})(),text:(()=>{if(t?.text)return t.text;let n=this._getResponseFormat(t?.response_format);return n?.type==="json_schema"?n.json_schema.schema!=null?{format:{type:"json_schema",schema:n.json_schema.schema,description:n.json_schema.description,name:n.json_schema.name,strict:n.json_schema.strict},verbosity:t?.verbosity}:void 0:{format:n,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,prompt_cache_retention:t?.promptCacheRetention??this.promptCacheRetention,...this.zdrEnabled?{store:!1}:{},...this.modelKwargs},s=this._getReasoningParams(t);return s!==void 0&&(r.reasoning=s),r}async _generate(t,e,r){e.signal?.throwIfAborted();let s=this.invocationParams(e);if(s.stream){let n=this._streamResponseChunks(t,e,r),o;for await(let i of n)i.message.response_metadata={...i.generationInfo,...i.message.response_metadata},o=o?.concat(i)??i;return{generations:o?[o]:[],llmOutput:{estimatedTokenUsage:o?.message?.usage_metadata}}}else{let n=await this.completionWithRetry({input:Ms({messages:t,zdrEnabled:this.zdrEnabled??!1,model:this.model}),...s,stream:!1},{signal:e?.signal,...e?.options});return{generations:[{text:n.output_text,message:Sn(n)}],llmOutput:{id:n.id,estimatedTokenUsage:n.usage?{promptTokens:n.usage.input_tokens,completionTokens:n.usage.output_tokens,totalTokens:n.usage.total_tokens}:void 0}}}}async*_streamChatModelEvents(t,e,r){let s=await this.completionWithRetry({...this.invocationParams(e),input:Ms({messages:t,zdrEnabled:this.zdrEnabled??!1,model:this.model}),stream:!0},e),n=this.streamUsage??e.streamUsage;yield*Ko(async function*(i,a){for await(let c of i){if(a?.aborted)return;yield c}}(s,e.signal),{streamUsage:n??!0,provider:this.streamEventProvider})}get streamEventProvider(){return"openai"}async*_streamResponseChunks(t,e,r){let s=await this.completionWithRetry({...this.invocationParams(e),input:Ms({messages:t,zdrEnabled:this.zdrEnabled??!1,model:this.model}),stream:!0},e);try{for await(let n of s){if(e.signal?.aborted)return;let o=Lo(n);o!=null&&(yield o,await r?.handleLLMNewToken(o.text||"",{prompt:e.promptIndex??0,completion:0},void 0,void 0,void 0,{chunk:o}))}}catch(n){throw le(n)}}async completionWithRetry(t,e){return this.caller.call(async()=>{let r=this._getClientOptions(e);try{return t.text?.format?.type==="json_schema"&&!t.stream?await this.client.responses.parse(t,r):await this.client.responses.create(t,r)}catch(s){throw le(s)}})}_reduceChatOpenAITools(t,e){let r=[];for(let s of t)if(es(s))s.type==="image_generation"&&e?.stream&&(s.partial_images=1),r.push(s);else if($t(s)){let n=s.metadata.customTool;r.push({type:"custom",name:n.name,description:n.description,format:n.format})}else if(Fs(s)){let n={};for(let[o,i]of Object.entries(s))o!=="type"&&o!=="function"&&(n[o]=i);r.push({type:"function",name:s.function.name,parameters:s.function.parameters,description:s.function.description,strict:e?.strict??null,...n})}else On(s)&&r.push(Xa(s));return r}};var Mn=class Yu extends zt{useResponsesApi=!1;responses;completions;get lc_serializable_keys(){return[...super.lc_serializable_keys,"useResponsesApi"]}get callKeys(){return[...super.callKeys,"useResponsesApi"]}fields;constructor(e,r){let s=ts(e,r);super(s),this.fields=s,this.useResponsesApi=s?.useResponsesApi??!1,this.responses=s?.responses??new $n(s),this.completions=s?.completions??new Cn(s)}_useResponsesApi(e){let r=e?.tools?.some(es),s=e?.previous_response_id!=null||e?.text!=null||e?.truncation!=null||e?.include!=null||e?.reasoning?.summary!=null||this.reasoning?.summary!=null,n=e?.tools?.some(On)||e?.tools?.some($t);return this.useResponsesApi||r||s||n||Da(this.model)}getLsParams(e){let r=this._combineCallOptions(e);return this._useResponsesApi(e)?this.responses.getLsParams(r):this.completions.getLsParams(r)}invocationParams(e){let r=this._combineCallOptions(e);return this._useResponsesApi(e)?this.responses.invocationParams(r):this.completions.invocationParams(r)}async _generate(e,r,s){return this._useResponsesApi(r)?this.responses._generate(e,r,s):this.completions._generate(e,r,s)}async*_streamChatModelEvents(e,r,s){if(this._useResponsesApi(r)){yield*this.responses._streamChatModelEvents(e,this._combineCallOptions(r),s);return}yield*this.completions._streamChatModelEvents(e,this._combineCallOptions(r),s)}async*_streamResponseChunks(e,r,s){if(this._useResponsesApi(r)){yield*this.responses._streamResponseChunks(e,this._combineCallOptions(r),s);return}yield*this.completions._streamResponseChunks(e,this._combineCallOptions(r),s)}withConfig(e){let r=new Yu(this.fields);return r.defaultOptions={...this.defaultOptions,...e},r}};var Nn=class extends pi{model="text-embedding-ada-002";modelName;batchSize=512;stripNewLines=!0;dimensions;timeout;organization;encodingFormat;client;clientConfig;apiKey;constructor(t){let e={maxConcurrency:2,...t};super(e);let r=e?.apiKey??e?.openAIApiKey??ce("OPENAI_API_KEY");this.organization=e?.configuration?.organization??ce("OPENAI_ORGANIZATION"),this.model=e?.model??e?.modelName??this.model,this.modelName=this.model,this.batchSize=e?.batchSize??this.batchSize,this.stripNewLines=e?.stripNewLines??this.stripNewLines,this.timeout=e?.timeout,this.dimensions=e?.dimensions,this.encodingFormat=e?.encodingFormat,this.clientConfig={apiKey:r,organization:this.organization,dangerouslyAllowBrowser:!0,...t?.configuration}}async embedDocuments(t){let e=Wn(this.stripNewLines?t.map(o=>o.replace(/\n/g," ")):t,this.batchSize),r=e.map(o=>{let i={model:this.model,input:o};return this.dimensions&&(i.dimensions=this.dimensions),this.encodingFormat&&(i.encoding_format=this.encodingFormat),this.embeddingWithRetry(i)}),s=await Promise.all(r),n=[];for(let o=0;o<s.length;o+=1){let i=e[o],{data:a}=s[o];for(let c=0;c<i.length;c+=1)n.push(a[c].embedding)}return n}async embedQuery(t){let e={model:this.model,input:this.stripNewLines?t.replace(/\n/g," "):t};this.dimensions&&(e.dimensions=this.dimensions),this.encodingFormat&&(e.encoding_format=this.encodingFormat);let{data:r}=await this.embeddingWithRetry(e);return r[0].embedding}async embeddingWithRetry(t){if(!this.client){let r=je({baseURL:this.clientConfig.baseURL}),s={...this.clientConfig,baseURL:r,timeout:this.timeout,maxRetries:0};s.baseURL||delete s.baseURL,s.defaultHeaders=Ue(s.defaultHeaders),this.client=new v(s)}let e={};return this.caller.call(async()=>{try{return await this.client.embeddings.create(t,e)}catch(r){throw le(r)}})}};var Mp=x.object({type:x.literal("screenshot")}),Np=x.object({type:x.literal("click"),x:x.number(),y:x.number(),button:x.enum(["left","right","wheel","back","forward"]).default("left")}),zp=x.object({type:x.literal("double_click"),x:x.number(),y:x.number(),button:x.enum(["left","right","wheel","back","forward"]).default("left")}),jp=x.object({type:x.literal("drag"),path:x.array(x.object({x:x.number(),y:x.number()}))}),Up=x.object({type:x.literal("keypress"),keys:x.array(x.string())}),Dp=x.object({type:x.literal("move"),x:x.number(),y:x.number()}),Lp=x.object({type:x.literal("scroll"),x:x.number(),y:x.number(),scroll_x:x.number(),scroll_y:x.number()}),Kp=x.object({type:x.literal("type"),text:x.string()}),Fp=x.object({type:x.literal("wait"),duration:x.number().optional()}),Bp=x.union([Mp,Np,zp,jp,Up,Dp,Lp,Kp,Fp]),rT=x.object({action:Bp});var qp=x.object({type:x.literal("exec"),command:x.array(x.string()),env:x.record(x.string(),x.string()).optional(),working_directory:x.string().optional(),timeout_ms:x.number().optional(),user:x.string().optional()}),iT=x.union([qp]);var cT=x.object({commands:x.array(x.string()).describe("Array of shell commands to execute"),timeout_ms:x.number().optional().describe("Optional timeout in milliseconds for the commands"),max_output_length:x.number().optional().describe("Optional maximum number of characters to return from each command")});var Wp=x.object({type:x.literal("create_file"),path:x.string(),diff:x.string()}),Hp=x.object({type:x.literal("update_file"),path:x.string(),diff:x.string()}),Zp=x.object({type:x.literal("delete_file"),path:x.string()}),fT=x.union([Wp,Hp,Zp]);var sl={advanced:"gpt-5.2",default:"gpt-5-mini",fast:"gpt-5.4-nano"},Wo={default:"text-embedding-ada-002"},Bo=new Map,zn=null,Gp=()=>{let t=tl.getDefault().helperServices;if(!t?.aiModels?.url)throw new Error("AI Models Service URL is not defined in the portal's helper services.");return t.aiModels.url},nl=async t=>{let e=Gp();Bo.size===0&&(zn||(zn=(async()=>{try{(await rl(`${e}/models`)).data.models.forEach(s=>Bo.set(s.name,s))}catch(s){throw zn=null,s}})()),await zn);let r=Bo.get(t);if(!r)throw new Error(`Model '${t}' is not available in the discovery service.`);return r.endpoint},Xp=async(t="default")=>await nl(sl[t]),Yp=async(t="default")=>await nl(Wo[t]),FC=ke.Root({agentExecutionContext:ke({default:bi,reducer:Ai}),currentIntent:ke({default:()=>"none",reducer:os}),routing:ke({default:()=>({mode:"auto"}),reducer:os}),lastExecutedAgent:ke({default:()=>"",reducer:os}),requiresFollowUp:ke({default:()=>!0,reducer:os}),stepCount:ke({default:()=>0,reducer:(t,e)=>e??t+1}),finalOutputMessage:ke({default:()=>"",reducer:Ii})}),Qp=t=>{if(!t||typeof t!="object"||!("services"in t))return!1;let e=t.services;return!!e&&typeof e=="object"&&"agentRegistry"in e},em=t=>{let e=t?.configurable;return Qp(e)?e:void 0},tm=(t,e,r)=>{let s=t[e];return s?typeof s=="function"?s():Promise.resolve(s):new Promise((n,o)=>{(typeof queueMicrotask=="function"?queueMicrotask:setTimeout)(o.bind(null,new Error("Unknown variable dynamic import: "+e+(e.split("/").length!==r?". Note that variables only represent file names one level deep.":""))))})},Ho=async t=>(await tm(Object.assign({"./field_descriptions_prompt.md":()=>import("./ZU2FHVNK.js"),"./intent_prompt.md":()=>import("./BL273EGZ.js"),"./layer_descriptions_prompt.md":()=>import("./LK7ZIQW6.js")}),`./${t}.md`,2)).default,rm=async t=>{let{agent:e,messages:r,config:s}=t;return{structuredResponse:(await e.invoke({messages:r},s)).structuredResponse}},sm=t=>typeof t=="string"&&t.length>0?t:void 0,nm=()=>Go(),om=t=>typeof t!="string"||t.trim().length===0?"MapsSDK":`MapsSDK - ${t.trim()}`,im=t=>{let e=t?.configurable;return{conversationId:sm(e?.thread_id),abortSignal:t?.signal,requestId:nm(),requestSource:om(Jp.applicationName)}},am=t=>{if(t==null||typeof t=="string"||t instanceof FormData||t instanceof HTMLFormElement)return t;if(t instanceof URLSearchParams)return t.toString();throw new TypeError(`Unsupported request body type: ${Object.prototype.toString.call(t)}`)},ol=async({config:t})=>{let e=tl.getDefault(),r=(await Vp.getCredential(`${e.url}/sharing`))?.token;return async(s,n)=>{let{conversationId:o,abortSignal:i,requestId:a,requestSource:c}=im(t),u=new Headers(n?.headers);for(let h of[...u.keys()]){let g=h.toLowerCase();(g==="authorization"||g==="api-key"||g.startsWith("x-stainless-"))&&u.delete(h)}r&&r.length>0&&u.set("X-Esri-Authorization",`Bearer ${r}`),e.isPortal||(c&&c.length>0&&u.set("X-Esri-Request-Source",c),o&&o.length>0&&u.set("X-Esri-Conversation-Id",o),a.length>0&&u.set("X-Esri-Request-Id",a));let f=i&&n?.signal?AbortSignal.any([i,n.signal]):n?.signal??i;return(await rl(s instanceof Request?s.url:s.toString(),{body:am(n?.body),headers:Object.fromEntries(u),responseType:"native",signal:f})).data}},zs=async(t={})=>{let{modelTier:e="default",temperature:r=0,config:s}=t,n=sl[e],o=await Xp(e);return new Mn({modelName:n,apiKey:"dummy-key",...e!=="default"&&{temperature:r},configuration:{baseURL:o,fetch:await ol({config:s})}})},BC=async(t={})=>{let{tier:e="default",config:r}=t,s=Wo[e],n=await Yp(e);return new Nn({modelName:s,apiKey:"dummy-key",configuration:{baseURL:n,fetch:await ol({config:r})},batchSize:2048,maxConcurrency:10})},um=x.object({id:x.string().min(1),name:x.string().min(1),description:x.string().min(1)});x.array(um);var Qu=t=>JSON.stringify(t,null,2),lm=t=>{let e=t.map(s=>s.id),r=x.enum(e);return x.object({intent:r.nullable(),assignedTask:x.string().nullable(),requiresFollowUp:x.boolean()})},qC=async(t,e)=>{let r=em(e);if(e?.signal?.aborted)return await rt({text:"Run cancelled; skipping intent routing"},e),{...t,currentIntent:"none",finalOutputMessage:"Operation cancelled.",requiresFollowUp:!1};try{await rt({text:"Asking LLM to route to an agent"},e);let s=r.services.agentRegistry?.list()??[],n=s.map(({agent:b})=>({id:b.id,name:b.name,description:b.description}));if(!n.length)return await rt({text:"No agents registered; skipping intent detection"},e),{...t,currentIntent:"none",finalOutputMessage:"No agents registered; skipping intent detection."};let o=await Ho("intent_prompt"),i=Qu(n),a=lm(n),c={registeredAgents:i,priorSteps:Qu(t.agentExecutionContext.priorSteps),userRequest:t.agentExecutionContext.userRequest},u=await qn.fromTemplate(o).format(c),f=xi({model:await zs({modelTier:"fast",config:e}),tools:[],systemPrompt:u,responseFormat:a,middleware:[wi({model:await zs({modelTier:"fast",config:e}),trigger:{tokens:4e3},keep:{messages:6}}),Pi({runLimit:2})]}),{structuredResponse:h}=await rm({agent:f,messages:t.agentExecutionContext.messages,config:e}),g=a.parse(h??{intent:null,assignedTask:null,requiresFollowUp:!1}),A=g.intent??"none",I={...t,currentIntent:A,requiresFollowUp:g.requiresFollowUp,agentExecutionContext:{...t.agentExecutionContext,assignedTask:g.assignedTask??""}};if(A==="none"){let b=`I could not find an agent that can handle that request. I have access to the following agents: ${s.map(({agent:_})=>_.name).join(", ")}.
36
36
 
37
- `);return n[n.length-1]?.trim()===r?t:`${t}
38
-
39
- ${r}`},nl=()=>({userRequest:"",assignedTask:"",messages:[],priorSteps:[],sharedState:{}}),Qp=()=>({agentExecutionContext:re({reducer:rl,default:nl}),outputMessage:re({reducer:sl,default:()=>""}),summary:re({reducer:jt,default:()=>""}),status:re({reducer:jt})}),FC=()=>({...Qp(),sharedStatePatch:re({reducer:jt})}),BC=re.Root({agentExecutionContext:re({default:nl,reducer:rl}),currentIntent:re({default:()=>"none",reducer:jt}),routing:re({default:()=>({mode:"auto"}),reducer:jt}),lastExecutedAgent:re({default:()=>"",reducer:jt}),requiresFollowUp:re({default:()=>!0,reducer:jt}),stepCount:re({default:()=>0,reducer:(t,e)=>e??t+1}),finalOutputMessage:re({default:()=>"",reducer:sl})}),em=t=>{if(!t||typeof t!="object"||!("services"in t))return!1;let e=t.services;return!!e&&typeof e=="object"&&"agentRegistry"in e},tm=t=>{let e=t?.configurable;return em(e)?e:void 0},rm=(t,e,r)=>{let s=t[e];return s?typeof s=="function"?s():Promise.resolve(s):new Promise((n,o)=>{(typeof queueMicrotask=="function"?queueMicrotask:setTimeout)(o.bind(null,new Error("Unknown variable dynamic import: "+e+(e.split("/").length!==r?". Note that variables only represent file names one level deep.":""))))})},Ho=async t=>(await rm(Object.assign({"./field_descriptions_prompt.md":()=>import("./ZU2FHVNK.js"),"./intent_prompt.md":()=>import("./BL273EGZ.js"),"./layer_descriptions_prompt.md":()=>import("./LK7ZIQW6.js")}),`./${t}.md`,2)).default,sm=async t=>{let{agent:e,messages:r,config:s}=t;return{structuredResponse:(await e.invoke({messages:r},s)).structuredResponse}},nm=t=>typeof t=="string"&&t.length>0?t:void 0,om=()=>Go(),im=t=>typeof t!="string"||t.trim().length===0?"MapsSDK":`MapsSDK - ${t.trim()}`,am=t=>{let e=t?.configurable;return{conversationId:nm(e?.thread_id),abortSignal:t?.signal,requestId:om(),requestSource:im(Jp.applicationName)}},um=t=>{if(t==null||typeof t=="string"||t instanceof FormData||t instanceof HTMLFormElement)return t;if(t instanceof URLSearchParams)return t.toString();throw new TypeError(`Unsupported request body type: ${Object.prototype.toString.call(t)}`)},ol=async({config:t})=>{let e=Yu.getDefault(),r=(await Vp.getCredential(`${e.url}/sharing`))?.token;return async(s,n)=>{let{conversationId:o,abortSignal:i,requestId:a,requestSource:c}=am(t),u=new Headers(n?.headers);for(let h of[...u.keys()]){let g=h.toLowerCase();(g==="authorization"||g==="api-key"||g.startsWith("x-stainless-"))&&u.delete(h)}r&&r.length>0&&u.set("X-Esri-Authorization",`Bearer ${r}`),e.isPortal||(c&&c.length>0&&u.set("X-Esri-Request-Source",c),o&&o.length>0&&u.set("X-Esri-Conversation-Id",o),a.length>0&&u.set("X-Esri-Request-Id",a));let f=i&&n?.signal?AbortSignal.any([i,n.signal]):n?.signal??i;return(await Qu(s instanceof Request?s.url:s.toString(),{body:um(n?.body),headers:Object.fromEntries(u),responseType:"native",signal:f})).data}},zs=async(t={})=>{let{modelTier:e="default",temperature:r=0,config:s}=t,n=el[e],o=await Xp(e);return new Mn({modelName:n,apiKey:"dummy-key",...e!=="default"&&{temperature:r},configuration:{baseURL:o,fetch:await ol({config:s})}})},qC=async(t={})=>{let{tier:e="default",config:r}=t,s=Wo[e],n=await Yp(e);return new Nn({modelName:s,apiKey:"dummy-key",configuration:{baseURL:n,fetch:await ol({config:r})},batchSize:2048,maxConcurrency:10})},lm=x.object({id:x.string().min(1),name:x.string().min(1),description:x.string().min(1)});x.array(lm);var Gu=t=>JSON.stringify(t,null,2),cm=t=>{let e=t.map(s=>s.id),r=x.enum(e);return x.object({intent:r.nullable(),assignedTask:x.string().nullable(),requiresFollowUp:x.boolean()})},WC=async(t,e)=>{let r=tm(e);if(e?.signal?.aborted)return await rt({text:"Run cancelled; skipping intent routing"},e),{...t,currentIntent:"none",finalOutputMessage:"Operation cancelled.",requiresFollowUp:!1};try{await rt({text:"Asking LLM to route to an agent"},e);let s=r.services.agentRegistry?.list()??[],n=s.map(({agent:b})=>({id:b.id,name:b.name,description:b.description}));if(!n.length)return await rt({text:"No agents registered; skipping intent detection"},e),{...t,currentIntent:"none",finalOutputMessage:"No agents registered; skipping intent detection."};let o=await Ho("intent_prompt"),i=Gu(n),a=cm(n),c={registeredAgents:i,priorSteps:Gu(t.agentExecutionContext.priorSteps),userRequest:t.agentExecutionContext.userRequest},u=await qn.fromTemplate(o).format(c),f=Ai({model:await zs({modelTier:"fast",config:e}),tools:[],systemPrompt:u,responseFormat:a,middleware:[Ii({model:await zs({modelTier:"fast",config:e}),trigger:{tokens:4e3},keep:{messages:6}}),bi({runLimit:2})]}),{structuredResponse:h}=await sm({agent:f,messages:t.agentExecutionContext.messages,config:e}),g=a.parse(h??{intent:null,assignedTask:null,requiresFollowUp:!1}),A=g.intent??"none",I={...t,currentIntent:A,requiresFollowUp:g.requiresFollowUp,agentExecutionContext:{...t.agentExecutionContext,assignedTask:g.assignedTask??""}};if(A==="none"){let b=`I could not find an agent that can handle that request. I have access to the following agents: ${s.map(({agent:_})=>_.name).join(", ")}.
40
-
41
- Please ask a question that can be answered by one of these agents.`;return await rt({text:"LLM did not identify a clear intent."},e),{...t,currentIntent:A,requiresFollowUp:!1,finalOutputMessage:b,agentExecutionContext:{...t.agentExecutionContext,assignedTask:"",messages:[...t.agentExecutionContext.messages,new ae(b)],priorSteps:[...t.agentExecutionContext.priorSteps??[],{agentId:"no-intent-router",assignedTask:t.agentExecutionContext.userRequest,summary:"No matching agent found; asked user to rephrase.",status:"failed"}]}}}return await rt({text:`Agent picked: ${A}
37
+ Please ask a question that can be answered by one of these agents.`;return await rt({text:"LLM did not identify a clear intent."},e),{...t,currentIntent:A,requiresFollowUp:!1,finalOutputMessage:b,agentExecutionContext:{...t.agentExecutionContext,assignedTask:"",messages:[...t.agentExecutionContext.messages,new ie(b)],priorSteps:[...t.agentExecutionContext.priorSteps??[],{agentId:"no-intent-router",assignedTask:t.agentExecutionContext.userRequest,summary:"No matching agent found; asked user to rephrase.",status:"failed"}]}}}return await rt({text:`Agent picked: ${A}
42
38
  Task Assigned: ${g.assignedTask??""}
43
- Requires Follow-Up: ${g.requiresFollowUp}`},e),I}catch(s){throw await rt({text:"Error during intent detection"},e),new Error(`Error during intent detection: ${s instanceof Error?s.message:String(s)}`)}},pm="0.1",Ns=1536,mm="openai",dm=Wo.default,fm=`Name: {name}
39
+ Requires Follow-Up: ${g.requiresFollowUp}`},e),I}catch(s){throw await rt({text:"Error during intent detection"},e),new Error(`Error during intent detection: ${s instanceof Error?s.message:String(s)}`)}},cm="0.1",Ns=1536,pm="openai",mm=Wo.default,dm=`Name: {name}
44
40
  Title: {title}
45
- Description: {description}`,hm=`Name: {name}
41
+ Description: {description}`,fm=`Name: {name}
46
42
  Alias: {alias}
47
- Description: {description}`,HC=x.object({schemaVersion:x.literal(pm),modified:x.number().int().nonnegative(),embeddings:x.object({modelProvider:x.literal(mm),model:x.literal(dm),dimensions:x.literal(Ns),templates:x.object({layer:x.string().default(fm),field:x.string().default(hm)})}),layers:x.array(x.object({id:x.string().min(1),name:x.string().min(1),title:x.string().catch(""),description:x.string().catch(""),vector:x.array(x.number()).length(Ns,{message:`Layer vector must be exactly ${Ns} dimensions`}),fields:x.array(x.object({name:x.string().min(1),alias:x.string().catch(""),description:x.string().catch(""),vector:x.array(x.number()).length(Ns,{message:`Field vector must be exactly ${Ns} dimensions`})}))})).default([])}),_m=t=>{let e=new Set;for(let r of t)if(Ds(r)){let s=r;s.tool_calls&&s.tool_calls.length>0&&s.tool_calls.forEach(n=>{n.id&&e.add(n.id)})}return t.filter(r=>{if(ei(r)){let s=r;return e.has(s.tool_call_id)}return!0})},Zo=(t,e)=>{let r=gi.fromTemplate(t);return qn.fromMessages([r,...e])},gm=async t=>{let{promptText:e,modelTier:r,temperature:s,messages:n,config:o}=t,i=Zo(e,n??[]),a=await zs({modelTier:r,temperature:s,config:o});return i.pipe(a)},ZC=async t=>{let{promptText:e,modelTier:r="default",temperature:s=0,messages:n,inputVariables:o,config:i}=t,a=await(await gm({promptText:e,modelTier:r,temperature:s,messages:n,config:i})).invoke(o??{},i);if(typeof a=="string")return a;let c=a.content;return typeof c=="string"?c:JSON.stringify(c)},il=async t=>{let{promptText:e,modelTier:r="default",temperature:s=0,messages:n,inputVariables:o,schema:i,config:a}=t,c=Zo(e,n??[]),u=(await zs({modelTier:r,temperature:s,config:a})).withStructuredOutput(i);return await c.pipe(u).invoke(o??{},a)},VC=async t=>{let{promptText:e,modelTier:r="default",temperature:s=0,messages:n,inputVariables:o,tools:i,config:a}=t,c=i.length>0?_m(n??[]):n??[],u=Zo(e,c),f=await zs({modelTier:r,temperature:s,config:a});return await u.pipe(f.bindTools(i)).invoke(o??{},a)},ym=ue.object({name:ue.string(),description:ue.string(),valueType:ue.string(),alias:ue.string()}),Am=ue.object({fields:ue.array(ym)}),al=(t,e)=>t.getFieldAlias(e)??void 0,qo=(t,e)=>al(t,e.name)??e.alias??"",Im=(t,e)=>{let r=al(t,e.name);return!!(r&&r!==(e.alias??""))};function Xu(t,e){let r=new Map;for(let s of t.fields){let n=e.fields.find(c=>c.name===s.name),o=qo(t,s),i=Im(t,s),a={name:s.name,type:s.type,alias:i?o:n?.alias??o,description:n?.description??s.description??"",valueType:n?.valueType??s.valueType??"",domain:t.getFieldDomain(s.name)??void 0};r.set(s.name,a)}return r}var JC=async t=>{let e=await Ho("field_descriptions_prompt"),r=t.fields.filter(o=>!(qo(t,o)&&o.description)).map(o=>{let{name:i,type:a,description:c}=o,u=qo(t,o);return[`Name: ${i}`,`Type: ${a}`,`Alias: ${u}`,`Description: ${c??"N/A"}`].join(", ")}).join(`
48
- `);if(r.length===0)return Xu(t,{fields:[]});let s={existingItemTitle:t.portalItem?.title,existingItemDescription:t.portalItem?.description,existingLayerTitle:t.title,existingLayerDescription:t.portalItem?.description,fieldInformation:r},n=await il({promptText:e,schema:Am,inputVariables:s});return Xu(t,n)},bm=ue.object({title:ue.string(),description:ue.string(),name:ue.string().nullable()}),GC=async(t,e)=>{let r=await Ho("layer_descriptions_prompt"),s=Array.from(e.values()),n={fieldInformation:JSON.stringify(s,null,2),existingLayerTitle:t.title,existingLayerDescription:t.portalItem?.description,existingLayerSnippet:t.portalItem?.snippet,layerGeometryType:t.geometryType};return{...await il({promptText:r,schema:bm,inputVariables:n}),name:t.title??null}};return{a:Yp,b:Qp,c:FC,d:BC,e:tm,f:zs,g:qC,h:WC,i:pm,j:Ns,k:mm,l:dm,m:fm,n:hm,o:HC,p:ZC,q:il,r:VC,s:JC,t:GC}},"portal/Portal","request","identity/IdentityManager","config")
43
+ Description: {description}`,WC=x.object({schemaVersion:x.literal(cm),modified:x.number().int().nonnegative(),embeddings:x.object({modelProvider:x.literal(pm),model:x.literal(mm),dimensions:x.literal(Ns),templates:x.object({layer:x.string().default(dm),field:x.string().default(fm)})}),layers:x.array(x.object({id:x.string().min(1),name:x.string().min(1),title:x.string().catch(""),description:x.string().catch(""),vector:x.array(x.number()).length(Ns,{message:`Layer vector must be exactly ${Ns} dimensions`}),fields:x.array(x.object({name:x.string().min(1),alias:x.string().catch(""),description:x.string().catch(""),vector:x.array(x.number()).length(Ns,{message:`Field vector must be exactly ${Ns} dimensions`})}))})).default([])}),hm=t=>{let e=new Set;for(let r of t)if(Ls(r)){let s=r;s.tool_calls&&s.tool_calls.length>0&&s.tool_calls.forEach(n=>{n.id&&e.add(n.id)})}return t.filter(r=>{if(ei(r)){let s=r;return e.has(s.tool_call_id)}return!0})},Zo=(t,e)=>{let r=gi.fromTemplate(t);return qn.fromMessages([r,...e])},_m=async t=>{let{promptText:e,modelTier:r,temperature:s,messages:n,config:o}=t,i=Zo(e,n??[]),a=await zs({modelTier:r,temperature:s,config:o});return i.pipe(a)},HC=async t=>{let{promptText:e,modelTier:r="default",temperature:s=0,messages:n,inputVariables:o,config:i}=t,a=await(await _m({promptText:e,modelTier:r,temperature:s,messages:n,config:i})).invoke(o??{},i);if(typeof a=="string")return a;let c=a.content;return typeof c=="string"?c:JSON.stringify(c)},il=async t=>{let{promptText:e,modelTier:r="default",temperature:s=0,messages:n,inputVariables:o,schema:i,config:a}=t,c=Zo(e,n??[]),u=(await zs({modelTier:r,temperature:s,config:a})).withStructuredOutput(i);return await c.pipe(u).invoke(o??{},a)},ZC=async t=>{let{promptText:e,modelTier:r="default",temperature:s=0,messages:n,inputVariables:o,tools:i,config:a}=t,c=i.length>0?hm(n??[]):n??[],u=Zo(e,c),f=await zs({modelTier:r,temperature:s,config:a});return await u.pipe(f.bindTools(i)).invoke(o??{},a)},gm=ae.object({name:ae.string(),description:ae.string(),valueType:ae.string(),alias:ae.string()}),ym=ae.object({fields:ae.array(gm)}),al=(t,e)=>t.getFieldAlias(e)??void 0,qo=(t,e)=>al(t,e.name)??e.alias??"",Am=(t,e)=>{let r=al(t,e.name);return!!(r&&r!==(e.alias??""))};function el(t,e){let r=new Map;for(let s of t.fields){let n=e.fields.find(c=>c.name===s.name),o=qo(t,s),i=Am(t,s),a={name:s.name,type:s.type,alias:i?o:n?.alias??o,description:n?.description??s.description??"",valueType:n?.valueType??s.valueType??"",domain:t.getFieldDomain(s.name)??void 0};r.set(s.name,a)}return r}var VC=async t=>{let e=await Ho("field_descriptions_prompt"),r=t.fields.filter(o=>!(qo(t,o)&&o.description)).map(o=>{let{name:i,type:a,description:c}=o,u=qo(t,o);return[`Name: ${i}`,`Type: ${a}`,`Alias: ${u}`,`Description: ${c??"N/A"}`].join(", ")}).join(`
44
+ `);if(r.length===0)return el(t,{fields:[]});let s={existingItemTitle:t.portalItem?.title,existingItemDescription:t.portalItem?.description,existingLayerTitle:t.title,existingLayerDescription:t.portalItem?.description,fieldInformation:r},n=await il({promptText:e,schema:ym,inputVariables:s});return el(t,n)},Im=ae.object({title:ae.string(),description:ae.string(),name:ae.string().nullable()}),JC=async(t,e)=>{let r=await Ho("layer_descriptions_prompt"),s=Array.from(e.values()),n={fieldInformation:JSON.stringify(s,null,2),existingLayerTitle:t.title,existingLayerDescription:t.portalItem?.description,existingLayerSnippet:t.portalItem?.snippet,layerGeometryType:t.geometryType};return{...await il({promptText:r,schema:Im,inputVariables:n}),name:t.title??null}};return{a:Yp,b:FC,c:em,d:zs,e:BC,f:qC,g:cm,h:Ns,i:pm,j:mm,k:dm,l:fm,m:WC,n:HC,o:il,p:ZC,q:VC,r:JC}},"portal/Portal","request","identity/IdentityManager","config")