@arcgis/ai-components 5.2.0-next.72 → 5.2.0-next.74
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent-utils/LLMAgent.d.ts +5 -2
- package/dist/agent-utils/LLMAgent.js +1 -1
- package/dist/agentic-workflow/jsonTypes.d.ts +8 -1
- package/dist/agentic-workflow/nodes/AgentNode.d.ts +2 -0
- package/dist/agentic-workflow/nodes/tools/ArcgisTool.d.ts +21 -0
- package/dist/cdn/253R5CBD.js +2 -0
- package/dist/cdn/2VBPA27M.js +18 -0
- package/dist/cdn/{DWYODVWW.js → 323DHVYA.js} +5 -5
- package/dist/cdn/34O57OGV.js +2 -0
- package/dist/cdn/{FSMHR7GK.js → 4HDDRBIY.js} +1 -1
- package/dist/cdn/4MFEKBKL.js +11 -0
- package/dist/cdn/{Y5UFOH54.js → 4NJ2FF7H.js} +1 -1
- package/dist/cdn/4YXYLX4H.js +2 -0
- package/dist/cdn/5DVRVY4L.js +2 -0
- package/dist/cdn/5PJXNTLZ.js +2 -0
- package/dist/cdn/5R6QUF5B.js +2 -0
- package/dist/cdn/5RVELJU4.js +36 -0
- package/dist/cdn/5WLNL4HZ.js +2 -0
- package/dist/cdn/66SKMECC.js +2 -0
- package/dist/cdn/6CLF7KIK.js +2 -0
- package/dist/cdn/{S6ZAQRC6.js → 6KFMRBAA.js} +1 -1
- package/dist/cdn/77QFSIWW.js +5 -0
- package/dist/cdn/7E2QMWK6.js +2 -0
- package/dist/cdn/{HO2YDJI2.js → 7M6VKBTK.js} +1 -1
- package/dist/cdn/{HJG7QM2R.js → 7VAQUCBU.js} +1 -1
- package/dist/cdn/ACJTJLZN.js +2 -0
- package/dist/cdn/AI6DYOKR.js +181 -0
- package/dist/cdn/AT4XVTJR.js +44 -0
- package/dist/cdn/BS2PFNU4.js +2 -0
- package/dist/cdn/CCC6LBMY.js +2 -0
- package/dist/cdn/CGXQAB3A.js +2 -0
- package/dist/cdn/{M3MRIGDZ.js → CP5BVGJU.js} +1 -1
- package/dist/cdn/CWD37QFT.js +2 -0
- package/dist/cdn/DY36ATOA.js +2 -0
- package/dist/cdn/DYASSC7Z.js +2 -0
- package/dist/cdn/EAEQONP7.js +2 -0
- package/dist/cdn/EMLOVMD4.js +2 -0
- package/dist/cdn/EWLXNGKH.js +208 -0
- package/dist/cdn/FAR3DFFK.js +2 -0
- package/dist/cdn/FDOMMK2M.js +2 -0
- package/dist/cdn/GRHIFCQX.js +2 -0
- package/dist/cdn/{S3XUYAUX.js → HHFNQR6Z.js} +1 -1
- package/dist/cdn/{WQKNV6KK.js → HMUWQCXU.js} +1 -1
- package/dist/cdn/HZ5ARNAM.js +2 -0
- package/dist/cdn/I6PD2HSL.js +2 -0
- package/dist/cdn/IDUC4CPV.js +2 -0
- package/dist/cdn/IRNSIUBT.js +2 -0
- package/dist/cdn/{OYNIFMCJ.js → J6SZIQJA.js} +1 -1
- package/dist/cdn/K335IAIE.js +2 -0
- package/dist/cdn/K33MZ726.js +2 -0
- package/dist/cdn/KA3FF3ZO.js +2 -0
- package/dist/cdn/{DBHLKLKM.js → KPO4XX6J.js} +1 -1
- package/dist/cdn/{I4L45WQS.js → L7XTRDFM.js} +1 -1
- package/dist/cdn/LCFIADOZ.js +2 -0
- package/dist/cdn/MDM2K3U7.js +2 -0
- package/dist/cdn/MM33KJPF.js +2 -0
- package/dist/cdn/NIY32GK2.js +2 -0
- package/dist/cdn/{3ZPPYCNL.js → ONMNQBPO.js} +1 -1
- package/dist/cdn/ONQ6JSBJ.js +2 -0
- package/dist/cdn/{6QJFOL6M.js → OWTGH34K.js} +1 -1
- package/dist/cdn/{XPTCV6YV.js → PSYRZMX2.js} +1 -1
- package/dist/cdn/Q4IQUEZN.js +14 -0
- package/dist/cdn/QNNGPA3Q.js +2 -0
- package/dist/cdn/QRHZXLZN.js +2 -0
- package/dist/cdn/QVOMX3R6.js +2 -0
- package/dist/cdn/QZ3NQTNQ.js +2 -0
- package/dist/cdn/RADWN4ZP.js +2 -0
- package/dist/cdn/RU2T7GUX.js +2 -0
- package/dist/cdn/S6OYR4VI.js +156 -0
- package/dist/cdn/T2GJLEYV.js +2 -0
- package/dist/cdn/TKYI5QRL.js +2 -0
- package/dist/cdn/{5SFZS2RD.js → TQXLSW4A.js} +2 -2
- package/dist/cdn/{NJJYZP3R.js → U6FBRUM4.js} +1 -1
- package/dist/cdn/UIXX3XEN.js +2 -0
- package/dist/cdn/UPWAOZXQ.js +2 -0
- package/dist/cdn/{5SF6DEMO.js → VNJMTA6O.js} +1 -1
- package/dist/cdn/VOKXKU7M.js +56 -0
- package/dist/cdn/{33BF35AO.js → VYTYVWR6.js} +4 -4
- package/dist/cdn/WMZ24LWS.js +2 -0
- package/dist/cdn/{JYVBCHR6.js → WP7ORLSB.js} +1 -1
- package/dist/cdn/WS3T73IY.js +2 -0
- package/dist/cdn/{UZL6UVE4.js → ZLWWWTH4.js} +1 -1
- package/dist/cdn/{PAUIFUMO.js → ZQMBJ6MI.js} +1 -1
- package/dist/cdn/agent-utils/index.js +1 -1
- package/dist/cdn/agent-utils/middlewares/humanInTheLoop.js +1 -1
- package/dist/cdn/agent-utils/middlewares/middleware.js +1 -1
- package/dist/cdn/agent-utils/middlewares/trace.js +1 -1
- package/dist/cdn/index.js +1 -1
- package/dist/chunks/adapter.js +938 -1938
- package/dist/chunks/adapter10.js +21 -0
- package/dist/chunks/adapter11.js +30 -0
- package/dist/chunks/adapter12.js +22 -0
- package/dist/chunks/adapter13.js +22 -0
- package/dist/chunks/adapter14.js +109 -0
- package/dist/chunks/adapter15.js +40 -0
- package/dist/chunks/adapter16.js +154 -0
- package/dist/chunks/adapter17.js +141 -0
- package/dist/chunks/adapter18.js +127 -0
- package/dist/chunks/adapter2.js +52 -0
- package/dist/chunks/adapter3.js +30 -0
- package/dist/chunks/adapter4.js +50 -0
- package/dist/chunks/adapter5.js +27 -0
- package/dist/chunks/adapter6.js +24 -0
- package/dist/chunks/adapter7.js +26 -0
- package/dist/chunks/adapter8.js +21 -0
- package/dist/chunks/adapter9.js +42 -0
- package/dist/chunks/arcgisKnowledgeGraph.js +5 -5
- package/dist/chunks/dataExplorationGraph.js +30 -27
- package/dist/chunks/fetchAgentContext.js +13 -0
- package/dist/chunks/fetchService.js +10 -0
- package/dist/chunks/formatFeatureAttributes.js +132 -0
- package/dist/chunks/generateLayerDescriptions.js +145 -148
- package/dist/chunks/helpGraph.js +11 -9
- package/dist/chunks/layerStylingGraph.js +22 -21
- package/dist/chunks/mergeWhereClauses.js +15 -0
- package/dist/chunks/navigationGraph.js +68 -57
- package/dist/chunks/types.js +59 -0
- package/dist/components/arcgis-assistant-agent/customElement.js +404 -279
- package/dist/components/arcgis-assistant-data-exploration-agent/customElement.js +15 -5
- package/dist/components/arcgis-assistant-help-agent/customElement.js +21 -5
- package/dist/components/arcgis-assistant-knowledge-agent/customElement.js +39 -22
- package/dist/components/arcgis-assistant-layer-styling-agent/customElement.js +22 -5
- package/dist/components/arcgis-assistant-navigation-agent/customElement.js +13 -5
- package/dist/docs/api.json +1 -1
- package/dist/docs/docs.json +1 -1
- package/dist/docs/web-types.json +1 -1
- package/dist/types/stencil.d.ts +2 -2
- package/dist/utils/index.d.ts +4 -5
- package/dist/utils/index.js +19 -20
- package/package.json +8 -8
- package/dist/cdn/55M2HE4U.js +0 -2
- package/dist/cdn/5RZGG4F2.js +0 -2
- package/dist/cdn/BAB3MK4Y.js +0 -2
- package/dist/cdn/BMBV6Y2A.js +0 -2
- package/dist/cdn/D3RKQSWS.js +0 -2
- package/dist/cdn/E7KEOJZG.js +0 -208
- package/dist/cdn/IGQFAL3H.js +0 -2
- package/dist/cdn/LUY6V4TP.js +0 -181
- package/dist/cdn/NSXX2KYS.js +0 -2
- package/dist/cdn/OFRFP4BX.js +0 -2
- package/dist/cdn/OUFGJV3R.js +0 -2
- package/dist/cdn/RWM5T4XB.js +0 -180
- package/dist/cdn/SRFLL6ET.js +0 -2
- package/dist/cdn/WDOM6Z5O.js +0 -18
- package/dist/cdn/WZFC5HUX.js +0 -56
- package/dist/cdn/Z4XUJQ2I.js +0 -36
- package/dist/cdn/ZJEWP2ND.js +0 -44
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
|
|
2
|
+
import{a as us,b as ki,c as vi,d as Ti}from"./7M6VKBTK.js";import{b as ri}from"./R74ZHFA6.js";import{a as st}from"./7VAQUCBU.js";import{b as Ci,c as Ri,d as Ei}from"./VOKXKU7M.js";import{K as gi,L as yi,M as Hs,N as Zn,O as Kt,P as Vn,Q as Ai,R as Ii,T as bi,U as xi,V as Zs,X as wi,Y as Jn,Z as Gn,_ as Pi,aa as Oi,ka as ke}from"./EWLXNGKH.js";import{Ac as Vs,Cb as hi,E as Bn,F as qn,G as Ks,Ub as E,W as Fs,X as oi,Z as ii,Zb as Lt,ea as ae,fa as Bs,ha as Dt,hc as _i,ia as qs,ja as ai,mb as is,na as ui,o as si,p as re,qb as Hn,ra as li,rb as di,sb as fi,u as rt,ub as as,vc as Ws,wa as Wn,x as ni,y as Ls,za as ci}from"./AI6DYOKR.js";import{a as ue}from"./VXFQANGJ.js";import{$ as mi,Dd as b,j as pi}from"./MWYBF3F3.js";export default $arcgis.t(([nl,ol,Yp,Qp])=>{function ls(t,e){return t.lc_error_code=e,t.message=`${t.message}
|
|
3
|
+
|
|
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 Xn=function(){let{crypto:t}=globalThis;if(t?.randomUUID)return Xn=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 cs(t){return typeof t=="object"&&t!==null&&("name"in t&&t.name==="AbortError"||"message"in t&&String(t.message).includes("FetchRequestCanceledException"))}var ps=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{},j=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:ps(r)});let o=r?.error;return e===400?new Ft(e,o,s,n):e===401?new Bt(e,o,s,n):e===403?new qt(e,o,s,n):e===404?new Wt(e,o,s,n):e===409?new Ht(e,o,s,n):e===422?new Zt(e,o,s,n):e===429?new Vt(e,o,s,n):e>=500?new Jt(e,o,s,n):new t(e,o,s,n)}},D=class extends j{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},Le=class extends j{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."})}},Ft=class extends j{},Bt=class extends j{},qt=class extends j{},Wt=class extends j{},Ht=class extends j{},Zt=class extends j{},Vt=class extends j{},Jt=class extends j{},Gt=class extends P{constructor(){super("Could not parse response content as the length limit was reached")}},Xt=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)}},nt=class extends j{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}},ms=class extends P{constructor(e,r,s){super(e),this.provider=r,this.cause=s}};var dl=/^[a-z][a-z0-9+.-]*:/i,Si=t=>dl.test(t),Y=t=>(Y=Array.isArray,Y(t)),Yn=Y;function Js(t){return typeof t!="object"?{}:t??{}}function Qn(t){if(!t)return!0;for(let e in t)return!1;return!0}function $i(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function ds(t){return t!=null&&typeof t=="object"&&!Array.isArray(t)}var Mi=(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 Ni=t=>{try{return JSON.parse(t)}catch{return}};var Ie=t=>new Promise(e=>setTimeout(e,t));var Ke="6.45.0";var Di=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function fl(){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 hl=()=>{let t=fl();if(t==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ke,"X-Stainless-OS":Ui(Deno.build.os),"X-Stainless-Arch":zi(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":Ui(globalThis.process.platform??"unknown"),"X-Stainless-Arch":zi(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=_l();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 _l(){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 zi=t=>t==="x32"?"x32":t==="x86_64"||t==="x64"?"x64":t==="arm"?"arm":t==="aarch64"||t==="arm64"?"arm64":t?`other:${t}`:"unknown",Ui=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"),ji,Li=()=>ji??(ji=hl());function Gs(){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 eo(...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 Xs(t){let e=Symbol.asyncIterator in t?t[Symbol.asyncIterator]():t[Symbol.iterator]();return eo({start(){},async pull(r){let{done:s,value:n}=await e.next();s?r.close():r.enqueue(n)},async cancel(){await e.return?.()}})}function to(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 ro(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 Fi=({headers:t,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});var so="RFC3986",no=t=>String(t),oo={RFC1738:t=>String(t).replace(/%20/g,"+"),RFC3986:no},Bi="RFC1738";var Ys=(t,e)=>(Ys=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),Ys(t,e)),be=(()=>{let t=[];for(let e=0;e<256;++e)t.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return t})();var io=1024,qi=(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+=io){let c=o.length>=io?o.slice(a,a+io):o,u=[];for(let h=0;h<c.length;++h){let f=c.charCodeAt(h);if(f===45||f===46||f===95||f===126||f>=48&&f<=57||f>=65&&f<=90||f>=97&&f<=122||n===Bi&&(f===40||f===41)){u[u.length]=c.charAt(h);continue}if(f<128){u[u.length]=be[f];continue}if(f<2048){u[u.length]=be[192|f>>6]+be[128|f&63];continue}if(f<55296||f>=57344){u[u.length]=be[224|f>>12]+be[128|f>>6&63]+be[128|f&63];continue}h+=1,f=65536+((f&1023)<<10|c.charCodeAt(h)&1023),u[u.length]=be[240|f>>18]+be[128|f>>12&63]+be[128|f>>6&63]+be[128|f&63]}i+=u.join("")}return i};function Wi(t){return!t||typeof t!="object"?!1:!!(t.constructor&&t.constructor.isBuffer&&t.constructor.isBuffer(t))}function ao(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 Zi={brackets(t){return String(t)+"[]"},comma:"comma",indices(t,e){return String(t)+"["+e+"]"},repeat(t){return String(t)}},Vi=function(t,e){Array.prototype.push.apply(t,Y(e)?e:[e])},Hi,W={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:qi,encodeValuesOnly:!1,format:so,formatter:no,indices:!1,serializeDate(t){return(Hi??(Hi=Function.prototype.call.bind(Date.prototype.toISOString)))(t)},skipNulls:!1,strictNullHandling:!1};function yl(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"||typeof t=="symbol"||typeof t=="bigint"}var uo={};function Ji(t,e,r,s,n,o,i,a,c,u,h,f,g,y,I,x,_,v){let p=t,A=v,O=0,z=!1;for(;(A=A.get(uo))!==void 0&&!z;){let F=A.get(t);if(O+=1,typeof F<"u"){if(F===O)throw new RangeError("Cyclic object value");z=!0}typeof A.get(uo)>"u"&&(O=0)}if(typeof u=="function"?p=u(e,p):p instanceof Date?p=g?.(p):r==="comma"&&Y(p)&&(p=ao(p,function(F){return F instanceof Date?g?.(F):F})),p===null){if(o)return c&&!x?c(e,W.encoder,_,"key",y):e;p=""}if(yl(p)||Wi(p)){if(c){let F=x?e:c(e,W.encoder,_,"key",y);return[I?.(F)+"="+I?.(c(p,W.encoder,_,"value",y))]}return[I?.(e)+"="+I?.(String(p))]}let N=[];if(typeof p>"u")return N;let U;if(r==="comma"&&Y(p))x&&c&&(p=ao(p,c)),U=[{value:p.length>0?p.join(",")||null:void 0}];else if(Y(u))U=u;else{let F=Object.keys(p);U=h?F.sort(h):F}let L=a?String(e).replace(/\./g,"%2E"):String(e),X=s&&Y(p)&&p.length===1?L+"[]":L;if(n&&Y(p)&&p.length===0)return X+"[]";for(let F=0;F<U.length;++F){let q=U[F],ei=typeof q=="object"&&typeof q.value<"u"?q.value:p[q];if(i&&ei===null)continue;let Fn=f&&a?q.replace(/\./g,"%2E"):q,pl=Y(p)?typeof r=="function"?r(X,Fn):X:X+(f?"."+Fn:"["+Fn+"]");v.set(t,O);let ti=new WeakMap;ti.set(uo,v),Vi(N,Ji(ei,pl,r,s,n,o,i,a,r==="comma"&&x&&Y(p)?null:c,u,h,f,g,y,I,x,_,ti))}return N}function Al(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=so;if(typeof t.format<"u"){if(!Ys(oo,t.format))throw new TypeError("Unknown format option provided.");r=t.format}let s=oo[r],n=W.filter;(typeof t.filter=="function"||Y(t.filter))&&(n=t.filter);let o;if(t.arrayFormat&&t.arrayFormat in Zi?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 Gi(t,e={}){let r=t,s=Al(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=Zi[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 y=n[g];s.skipNulls&&r[y]===null||Vi(i,Ji(r[y],y,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 h=i.join(s.delimiter),f=s.addQueryPrefix===!0?"?":"";return s.charsetSentinel&&(s.charset==="iso-8859-1"?f+="utf8=%26%2310003%3B&":f+="utf8=%E2%9C%93&"),h.length>0?f+h:""}function Xi(t){return Gi(t,{arrayFormat:"brackets"})}function ea(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 Yi;function Yt(t){let e;return(Yi??(e=new globalThis.TextEncoder,Yi=e.encode.bind(e)))(t)}var Qi;function lo(t){let e;return(Qi??(e=new globalThis.TextDecoder,Qi=e.decode.bind(e)))(t)}var se,ne,ot=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"?Yt(e):e;k(this,se,ea([d(this,se,"f"),r]),"f");let s=[],n;for(;(n=bl(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(lo(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=lo(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;ot.NEWLINE_CHARS=new Set([`
|
|
7
|
+
`,"\r"]);ot.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function bl(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 ta(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 en={off:0,error:200,warn:300,info:400,debug:500},co=(t,e,r)=>{if(t){if($i(en,t))return t;K(r).warn(`${e} was set to ${JSON.stringify(t)}, expected one of ${JSON.stringify(Object.keys(en))}`)}};function fs(){}function Qs(t,e,r){return!e||en[t]>en[r]?fs:e[t].bind(e)}var xl={error:fs,warn:fs,info:fs,debug:fs},ra=new WeakMap;function K(t){let e=t.logger,r=t.logLevel??"off";if(!e)return xl;let s=ra.get(e);if(s&&s[0]===r)return s[1];let n={error:Qs("error",e,r),warn:Qs("warn",e,r),info:Qs("info",e,r),debug:Qs("debug",e,r)};return ra.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 hs,xe=class t{constructor(e,r,s){this.iterator=e,hs.set(this,void 0),this.controller=r,k(this,hs,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 wl(e,r))if(!c){if(u.data.startsWith("[DONE]")){c=!0;continue}if(u.event===null||!u.event.startsWith("thread.")){let h;try{h=JSON.parse(u.data)}catch(f){throw i.error("Could not parse message into JSON:",u.data),i.error("From chunk:",u.raw),f}if(h&&h.error)throw new j(void 0,h.error,void 0,e.headers);yield n?{event:u.event,data:h}:h}else{let h;try{h=JSON.parse(u.data)}catch(f){throw console.error("Could not parse message into JSON:",u.data),console.error("From chunk:",u.raw),f}if(u.event=="error")throw new j(void 0,h.error,h.message,void 0);yield{event:u.event,data:h}}}c=!0}catch(u){if(cs(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 ot,c=to(e);for await(let u of c)for(let h of a.decode(u))yield h;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(cs(c))return;throw c}finally{a||r.abort()}}return new t(i,r,s)}[(hs=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,hs,"f")),new t(()=>n(r),this.controller,d(this,hs,"f"))]}toReadableStream(){let e=this,r;return eo({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=Yt(JSON.stringify(n)+`
|
|
8
|
+
`);s.enqueue(i)}catch(n){s.error(n)}},async cancel(){await r.return?.()}})}};async function*wl(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 po,s=new ot,n=to(t.body);for await(let o of Pl(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*Pl(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"?Yt(r):r,n=new Uint8Array(e.length+s.length);n.set(e),n.set(s,e.length),e=n;let o;for(;(o=ta(e))!==-1;)yield e.slice(0,o),e=e.slice(o)}e.length>0&&(yield e)}var po=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]=Ol(e,":");return n.startsWith(" ")&&(n=n.substring(1)),r==="event"?this.event=n:r==="data"&&this.data.push(n),null}};function Ol(t,e){let r=t.indexOf(e);return r!==-1?[t.substring(0,r),e,t.substring(r+e.length)]:[t,"",""]}async function tn(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 mo(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 mo(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 _s,it=class t extends Promise{constructor(e,r,s=tn){super(n=>{n(null)}),this.responsePromise=r,this.parseResponse=s,_s.set(this,void 0),k(this,_s,e,"f")}_thenUnwrap(e){return new t(d(this,_s,"f"),this.responsePromise,async(r,s)=>mo(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,_s,"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)}};_s=new WeakMap;var rn,Qt=class{constructor(e,r,s,n){rn.set(this,void 0),k(this,rn,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,rn,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(rn=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let r of e.getPaginatedItems())yield r}},gs=class extends it{constructor(e,r,s){super(e,r,async(n,o)=>new s(n,o.response,await tn(n,o),o.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let r of e)yield r}},Q=class extends Qt{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}},R=class extends Qt{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:{...Js(this.options.query),after:r}}:null}},$=class extends Qt{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:{...Js(this.options.query),after:e}}:null}},B=class extends Qt{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:{...Js(this.options.query),after:e}}:null}};var vl={jwt:"urn:ietf:params:oauth:token-type:jwt",id:"urn:ietf:params:oauth:token-type:id_token"},Tl="urn:ietf:params:oauth:grant-type:token-exchange",sn=class{constructor(e,r){this.cachedToken=null,this.refreshPromise=null,this.tokenExchangeUrl="https://auth.openai.com/oauth/token",this.config=e,this.fetch=r??Gs()}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:Tl,subject_token:e,subject_token_type:vl[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 nt(s.status,u,s.headers):j.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 _o=()=>{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 er(t,e,r){return _o(),new File(t,e??"unknown_file",r)}function ys(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 nn=t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function",Fe=async(t,e)=>fo(t.body)?{...t,body:await na(t.body,e)}:t,ee=async(t,e)=>({...t,body:await na(t.body,e)}),sa=new WeakMap;function Cl(t){let e=typeof t=="function"?t:t.fetch,r=sa.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 sa.set(e,s),s}var na=async(t,e)=>{if(!await Cl(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])=>ho(r,s,n))),r},oa=t=>t instanceof Blob&&"name"in t,Rl=t=>typeof t=="object"&&t!==null&&(t instanceof Response||nn(t)||oa(t)),fo=t=>{if(Rl(t))return!0;if(Array.isArray(t))return t.some(fo);if(t&&typeof t=="object"){for(let e in t)if(fo(t[e]))return!0}return!1},ho=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,er([await r.blob()],ys(r)));else if(nn(r))t.append(e,er([await new Response(Xs(r)).blob()],ys(r)));else if(oa(r))t.append(e,r,ys(r));else if(Array.isArray(r))await Promise.all(r.map(s=>ho(t,e+"[]",s)));else if(typeof r=="object")await Promise.all(Object.entries(r).map(([s,n])=>ho(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 ia=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",El=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&ia(t),Sl=t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function";async function As(t,e,r){if(_o(),t=await t,El(t))return t instanceof File?t:er([await t.arrayBuffer()],t.name);if(Sl(t)){let n=await t.blob();return e||(e=new URL(t.url).pathname.split(/[\\/]/).pop()),er(await go(n),e,r)}let s=await go(t);if(e||(e=ys(t)),!r?.type){let n=s.find(o=>typeof o=="object"&&"type"in o&&o.type);typeof n=="string"&&(r={...r,type:n})}return er(s,e,r)}async function go(t){let e=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)e.push(t);else if(ia(t))e.push(t instanceof Blob?t:await t.arrayBuffer());else if(nn(t))for await(let r of t)e.push(...await go(r));else{let r=t?.constructor?.name;throw new Error(`Unexpected data type: ${typeof t}${r?`; constructor: ${r}`:""}${$l(t)}`)}return e}function $l(t){return typeof t!="object"||t===null?"":`; props: [${Object.getOwnPropertyNames(t).map(r=>`"${r}"`).join(", ")}]`}var m=class{constructor(e){this._client=e}};function ua(t){return t.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var aa=Object.freeze(Object.create(null)),Nl=(t=ua)=>function(r,...s){if(r.length===1)return r[0];let n=!1,o=[],i=r.reduce((h,f,g)=>{/[?#]/.test(f)&&(n=!0);let y=s[g],I=(n?encodeURIComponent:t)(""+y);return g!==s.length&&(y==null||typeof y=="object"&&y.toString===Object.getPrototypeOf(Object.getPrototypeOf(y.hasOwnProperty??aa)??aa)?.toString)&&(I=y+"",o.push({start:h.length+f.length,length:I.length,error:`Value of type ${Object.prototype.toString.call(y).slice(8,-1)} is not a valid path parameter`})),h+f+(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((h,f)=>h.start-f.start),o.length>0){let h=0,f=o.reduce((g,y)=>{let I=" ".repeat(y.start-h),x="^".repeat(y.length);return h=y.start+y.length,g+I+x},"");throw new P(`Path parameters result in path with invalid segments:
|
|
10
|
+
${o.map(g=>g.error).join(`
|
|
11
|
+
`)}
|
|
12
|
+
${i}
|
|
13
|
+
${f}`)}return i},l=Nl(ua);var at=class extends m{list(e,r={},s){return this._client.getAPIList(l`/chat/completions/${e}/messages`,R,{query:r,...s,__security:{bearerAuth:!0}})}};function Is(t){return t!==void 0&&"function"in t&&t.function!==void 0}function ca(t,e){let r={...t};return Object.defineProperties(r,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:e,enumerable:!1}}),r}function bs(t){return t?.$brand==="auto-parseable-response-format"}function ut(t){return t?.$brand==="auto-parseable-tool"}function pa(t,e){return!e||!yo(e)?{...t,choices:t.choices.map(r=>(da(r.message.tool_calls),{...r,message:{...r.message,parsed:null,...r.message.tool_calls?{tool_calls:r.message.tool_calls}:void 0}}))}:xs(t,e)}function xs(t,e){let r=t.choices.map(s=>{if(s.finish_reason==="length")throw new Gt;if(s.finish_reason==="content_filter")throw new Xt;return da(s.message.tool_calls),{...s,message:{...s.message,...s.message.tool_calls?{tool_calls:s.message.tool_calls?.map(n=>jl(e,n))??void 0}:void 0,parsed:s.message.content&&!s.message.refusal?Ul(e,s.message.content):null}}});return{...t,choices:r}}function Ul(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 jl(t,e){let r=t.tools?.find(s=>Is(s)&&s.function?.name===e.function.name);return{...e,function:{...e.function,parsed_arguments:ut(r)?r.$parseRaw(e.function.arguments):r?.function.strict?JSON.parse(e.function.arguments):null}}}function ma(t,e){if(!t||!("tools"in t)||!t.tools)return!1;let r=t.tools?.find(s=>Is(s)&&s.function?.name===e.function.name);return Is(r)&&(ut(r)||r?.function.strict||!1)}function yo(t){return bs(t.response_format)?!0:t.tools?.some(e=>ut(e)||e.type==="function"&&e.function.strict===!0)??!1}function da(t){for(let e of t||[])if(e.type!=="function")throw new P(`Currently only \`function\` tool calls are supported; Received \`${e.type}\``)}function fa(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 tr=t=>t?.role==="assistant",Ao=t=>t?.role==="tool";var on,an,un,ws,Ps,ln,Os,Te,cn,ks,pn,mn,rr,ha,_a,Be=class{constructor(){on.add(this),this.controller=new AbortController,an.set(this,void 0),un.set(this,()=>{}),ws.set(this,()=>{}),Ps.set(this,void 0),ln.set(this,()=>{}),Os.set(this,()=>{}),Te.set(this,{}),cn.set(this,[]),ks.set(this,!1),pn.set(this,!1),mn.set(this,!1),rr.set(this,!1),k(this,an,new Promise((e,r)=>{k(this,un,e,"f"),k(this,ws,r,"f")}),"f"),k(this,Ps,new Promise((e,r)=>{k(this,ln,e,"f"),k(this,Os,r,"f")}),"f"),d(this,an,"f").catch(()=>{}),d(this,Ps,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},d(this,on,"m",_a).bind(this))},0)}_connected(){this.ended||(d(this,un,"f").call(this),this._emit("connect"))}get ended(){return d(this,ks,"f")}get errored(){return d(this,pn,"f")}get aborted(){return d(this,mn,"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,cn,"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,rr,!0,"f"),e!=="error"&&this.once("error",s),this.once(e,r)})}async done(){k(this,rr,!0,"f"),await d(this,Ps,"f")}_emit(e,...r){if(d(this,ks,"f"))return;e==="end"&&(d(this,on,"m",ha).call(this),k(this,ks,!0,"f"),d(this,ln,"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,rr,"f")&&!s?.length&&Promise.reject(n),d(this,ws,"f").call(this,n),d(this,Os,"f").call(this,n),this._emit("end");return}if(e==="error"){let n=r[0];!d(this,rr,"f")&&!s?.length&&Promise.reject(n),d(this,ws,"f").call(this,n),d(this,Os,"f").call(this,n),this._emit("end")}}_emitFinal(){}};an=new WeakMap,un=new WeakMap,ws=new WeakMap,Ps=new WeakMap,ln=new WeakMap,Os=new WeakMap,Te=new WeakMap,cn=new WeakMap,ks=new WeakMap,pn=new WeakMap,mn=new WeakMap,rr=new WeakMap,on=new WeakSet,ha=function(){for(let{signal:e,listener:r}of d(this,cn,"f").splice(0))e.removeEventListener("abort",r)},_a=function(e){if(k(this,pn,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new D),e instanceof D)return k(this,mn,!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 ga(t){return typeof t.parse=="function"}var te,Io,dn,bo,xo,wo,ya,Aa,Dl=10,sr=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),Ao(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(tr(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",Io).call(this)}async finalMessage(){return await this.done(),d(this,te,"m",dn).call(this)}async finalFunctionToolCall(){return await this.done(),d(this,te,"m",bo).call(this)}async finalFunctionToolCallResult(){return await this.done(),d(this,te,"m",xo).call(this)}async totalUsage(){return await this.done(),d(this,te,"m",wo).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",dn).call(this);r&&this._emit("finalMessage",r);let s=d(this,te,"m",Io).call(this);s&&this._emit("finalContent",s);let n=d(this,te,"m",bo).call(this);n&&this._emit("finalFunctionToolCall",n);let o=d(this,te,"m",xo).call(this);o!=null&&this._emit("finalFunctionToolCallResult",o),this._chatCompletions.some(i=>i.usage)&&this._emit("totalUsage",d(this,te,"m",wo).call(this))}async _createChatCompletion(e,r,s){this._listenForAbort(s?.signal),d(this,te,"m",ya).call(this,r);let n=await e.chat.completions.create({...r,stream:!1},{...s,signal:this.controller.signal});return this._connected(),this._addChatCompletion(xs(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:h=Dl,afterCompletion:f}=n||{},g=r.tools.map(_=>{if(ut(_)){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 _}),y={};for(let _ of g)_.type==="function"&&(y[_.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 x=async _=>{if(_.type!=="function")return{message:void 0,functionCalled:!1};let v=_.id,{name:p,arguments:A}=_.function,O=y[p];if(!O){let U=`Invalid tool_call: ${JSON.stringify(p)}. Available options are: ${Object.keys(y).map(L=>JSON.stringify(L)).join(", ")}. Please try again`;return{message:{role:o,tool_call_id:v,content:U},functionCalled:!1}}if(u&&u!==p){let U=`Invalid tool_call: ${JSON.stringify(p)}. ${JSON.stringify(u)} requested. Please try again`;return{message:{role:o,tool_call_id:v,content:U},functionCalled:!1}}let z;if(ga(O)){let U;try{U=await O.parse(A)}catch(L){let X=L instanceof Error?L.message:String(L);return{message:{role:o,tool_call_id:v,content:X},functionCalled:!1}}z=await O.function(U,s)}else z=await O.function(A,s);let N=d(this,te,"m",Aa).call(this,z);return{message:{role:o,tool_call_id:v,content:N},functionCalled:!0}};for(let _=0;_<h;++_){let v=await this._createChatCompletion(e,{...c,tool_choice:i,tools:I,messages:[...this.messages]},n),p=v.choices[0]?.message;if(!p)throw new P("missing message in ChatCompletion response");if(!p.tool_calls?.length){await f?.(v,s);return}if(u||r.parallel_tool_calls===!1)for(let A of p.tool_calls){let O=await x(A);if(O.message&&this._addMessage(O.message),u&&O.functionCalled){await f?.(v,s);return}}else{let A=await Promise.allSettled(p.tool_calls.map(x));for(let O of A)if(O.status==="rejected")throw O.reason;for(let O of A)O.status==="fulfilled"&&O.value.message&&this._addMessage(O.value.message)}await f?.(v,s)}}};te=new WeakSet,Io=function(){return d(this,te,"m",dn).call(this).content??null},dn=function(){let e=this.messages.length;for(;e-- >0;){let r=this.messages[e];if(tr(r))return{...r,content:r.content??null,refusal:r.refusal??null}}throw new P("stream ended without producing a ChatCompletionMessage with role=assistant")},bo=function(){for(let e=this.messages.length-1;e>=0;e--){let r=this.messages[e];if(tr(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}}},xo=function(){for(let e=this.messages.length-1;e>=0;e--){let r=this.messages[e];if(Ao(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}},wo=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},ya=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.")},Aa=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};var vs=class t extends sr{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),tr(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},Po=class extends Error{},Oo=class extends Error{};function Ll(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 Kl(t.trim(),e)}var Kl=(t,e)=>{let r=t.length,s=0,n=g=>{throw new Po(`${g} at position ${s}`)},o=g=>{throw new Oo(`${g} at position ${s}`)},i=()=>(f(),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):h()),a=()=>{let g=s,y=!1;for(s++;s<r&&(t[s]!=='"'||y&&t[s-1]==="\\");)y=t[s]==="\\"?!y:!1,s++;if(t.charAt(s)=='"')try{return JSON.parse(t.substring(g,++s-Number(y)))}catch(I){o(String(I))}else if(Z.STR&e)try{return JSON.parse(t.substring(g,s-Number(y))+'"')}catch{return JSON.parse(t.substring(g,t.lastIndexOf("\\"))+'"')}n("Unterminated string literal")},c=()=>{s++,f();let g={};try{for(;t[s]!=="}";){if(f(),s>=r&&Z.OBJ&e)return g;let y=a();f(),s++;try{let I=i();Object.defineProperty(g,y,{value:I,writable:!0,enumerable:!0,configurable:!0})}catch(I){if(Z.OBJ&e)return g;throw I}f(),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()),f(),t[s]===","&&s++}catch{if(Z.ARR&e)return g;n("Expected ']' at end of array")}return s++,g},h=()=>{if(s===0){t==="-"&&Z.NUM&e&&n("Not sure what '-' is");try{return JSON.parse(t)}catch(y){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(y))}}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))}}},f=()=>{for(;s<r&&`
|
|
14
|
+
\r `.includes(t[s]);)s++};return i()},ko=t=>Ll(t,Z.ALL^Z.NUM);var H,Ce,nr,qe,vo,fn,To,Co,Ro,hn,Eo,Ia,lt=class t extends sr{constructor(e){super(),H.add(this),Ce.set(this,void 0),nr.set(this,void 0),qe.set(this,void 0),k(this,Ce,e,"f"),k(this,nr,[],"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",vo).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",To).call(this,o);if(n.controller.signal?.aborted)throw new D;return this._addChatCompletion(d(this,H,"m",hn).call(this))}async _fromReadableStream(e,r){this._listenForAbort(r?.signal),d(this,H,"m",vo).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",hn).call(this)),d(this,H,"m",To).call(this,o),n=o.id;if(s.controller.signal?.aborted)throw new D;return this._addChatCompletion(d(this,H,"m",hn).call(this))}[(Ce=new WeakMap,nr=new WeakMap,qe=new WeakMap,H=new WeakSet,vo=function(){this.ended||k(this,qe,void 0,"f")},fn=function(r){let s=d(this,nr,"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,nr,"f")[r.index]=s,s)},To=function(r){if(this.ended)return;let s=d(this,H,"m",Ia).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",fn).call(this,o);o.finish_reason&&(d(this,H,"m",Ro).call(this,o),i.current_tool_call_index!=null&&d(this,H,"m",Co).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",Ro).call(this,o),i.current_tool_call_index!=null&&d(this,H,"m",Co).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))}}},Co=function(r,s){if(d(this,H,"m",fn).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=>Is(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:ut(i)?i.$parseRaw(o.function.arguments):i?.function.strict?JSON.parse(o.function.arguments):null})}else o.type},Ro=function(r){let s=d(this,H,"m",fn).call(this,r);if(r.message.content&&!s.content_done){s.content_done=!0;let n=d(this,H,"m",Eo).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}))},hn=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,nr,[],"f"),Fl(r,d(this,Ce,"f"))},Eo=function(){let r=d(this,Ce,"f")?.response_format;return bs(r)?r:null},Ia=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:h,finish_reason:f,index:g,logprobs:y=null,...I}of r.choices){let x=a.choices[g];if(x||(x=a.choices[g]={finish_reason:f,index:g,message:{},logprobs:y,...I}),y)if(!x.logprobs)x.logprobs=Object.assign({},y);else{let{content:N,refusal:U,...L}=y;Object.assign(x.logprobs,L),N&&((s=x.logprobs).content??(s.content=[]),x.logprobs.content.push(...N)),U&&((n=x.logprobs).refusal??(n.refusal=[]),x.logprobs.refusal.push(...U))}if(f&&(x.finish_reason=f,d(this,Ce,"f")&&yo(d(this,Ce,"f")))){if(f==="length")throw new Gt;if(f==="content_filter")throw new Xt}if(Object.assign(x,I),!h)continue;let{content:_,refusal:v,function_call:p,role:A,tool_calls:O,...z}=h;if(Object.assign(x.message,z),v&&(x.message.refusal=(x.message.refusal||"")+v),A&&(x.message.role=A),p&&(x.message.function_call?(p.name&&(x.message.function_call.name=p.name),p.arguments&&((o=x.message.function_call).arguments??(o.arguments=""),x.message.function_call.arguments+=p.arguments)):x.message.function_call=p),_&&(x.message.content=(x.message.content||"")+_,!x.message.refusal&&d(this,H,"m",Eo).call(this)&&(x.message.parsed=x.message.content.trim()?ko(x.message.content):null)),O){x.message.tool_calls||(x.message.tool_calls=[]);for(let{index:N,id:U,type:L,function:X,...F}of O){let q=(i=x.message.tool_calls)[N]??(i[N]={});Object.assign(q,F),U&&(q.id=U),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,ma(d(this,Ce,"f"),q)&&(q.function.parsed_arguments=ko(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 Fl(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:h,index:f,logprobs:g,...y})=>{if(!h)throw new P(`missing finish_reason for choice ${f}`);let{content:I=null,function_call:x,tool_calls:_,...v}=u,p=u.role;if(!p)throw new P(`missing role for choice ${f}`);if(x){let{arguments:A,name:O}=x;if(A==null)throw new P(`missing function_call.arguments for choice ${f}`);if(!O)throw new P(`missing function_call.name for choice ${f}`);return{...y,message:{content:I,function_call:{arguments:A,name:O},role:p,refusal:u.refusal??null},finish_reason:h,index:f,logprobs:g}}return _?{...y,index:f,finish_reason:h,logprobs:g,message:{...v,role:p,content:I,refusal:u.refusal??null,tool_calls:_.map((A,O)=>{let{function:z,type:N,id:U,...L}=A,{arguments:X,name:F,...q}=z||{};if(U==null)throw new P(`missing choices[${f}].tool_calls[${O}].id
|
|
15
|
+
${_n(t)}`);if(N==null)throw new P(`missing choices[${f}].tool_calls[${O}].type
|
|
16
|
+
${_n(t)}`);if(F==null)throw new P(`missing choices[${f}].tool_calls[${O}].function.name
|
|
17
|
+
${_n(t)}`);if(X==null)throw new P(`missing choices[${f}].tool_calls[${O}].function.arguments
|
|
18
|
+
${_n(t)}`);return{...L,id:U,type:N,function:{...q,name:F,arguments:X}}})}}:{...y,message:{...v,content:I,role:p,refusal:u.refusal??null},finish_reason:h,index:f,logprobs:g}}),created:n,model:o,object:"chat.completion",...i?{system_fingerprint:i}:{}};return pa(c,e)}function _n(t){return JSON.stringify(t)}var Ts=class t extends lt{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 m{constructor(){super(...arguments),this.messages=new at(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",R,{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 fa(e.tools),this._client.chat.completions.create(e,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(s=>xs(s,e))}runTools(e,r){return e.stream?Ts.runTools(this._client,e,r):vs.runTools(this._client,e,r)}stream(e,r){return lt.createChatCompletion(this._client,e,r)}};Re.Messages=at;var We=class extends m{constructor(){super(...arguments),this.completions=new Re(this._client)}};We.Completions=Re;var or=class extends m{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",R,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,r){return this._client.delete(l`/organization/admin_api_keys/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var ir=class extends m{list(e={},r){return this._client.getAPIList("/organization/audit_logs",$,{query:e,...r,__security:{adminAPIKeyAuth:!0}})}};var ar=class extends m{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 ur=class extends m{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 lr=class extends m{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 cr=class extends m{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 pr=class extends m{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 mr=class extends m{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 dr=class extends m{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 fr=class extends m{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 m{constructor(){super(...arguments),this.users=new fr(this._client),this.roles=new dr(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=fr;He.Roles=dr;var hr=class extends m{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 _r=class extends m{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 gr=class extends m{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 yr=class extends m{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 Ar=class extends m{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 Ir=class extends m{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 br=class extends m{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 xr=class extends m{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 wr=class extends m{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 Pr=class extends m{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 ct=class extends m{constructor(){super(...arguments),this.roles=new Pr(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}})}};ct.Roles=Pr;var Or=class extends m{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 pt=class extends m{constructor(){super(...arguments),this.roles=new Or(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}})}};pt.Roles=Or;var V=class extends m{constructor(){super(...arguments),this.users=new pt(this._client),this.serviceAccounts=new xr(this._client),this.apiKeys=new hr(this._client),this.rateLimits=new Ir(this._client),this.modelPermissions=new Ar(this._client),this.hostedToolPermissions=new yr(this._client),this.groups=new ct(this._client),this.roles=new br(this._client),this.dataRetention=new gr(this._client),this.spendAlerts=new wr(this._client),this.certificates=new _r(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=pt;V.ServiceAccounts=xr;V.APIKeys=hr;V.RateLimits=Ir;V.ModelPermissions=Ar;V.HostedToolPermissions=yr;V.Groups=ct;V.Roles=br;V.DataRetention=gr;V.SpendAlerts=wr;V.Certificates=_r;var kr=class extends m{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 mt=class extends m{constructor(){super(...arguments),this.roles=new kr(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}})}};mt.Roles=kr;var J=class extends m{constructor(){super(...arguments),this.auditLogs=new ir(this._client),this.adminAPIKeys=new or(this._client),this.usage=new mr(this._client),this.invites=new lr(this._client),this.users=new mt(this._client),this.groups=new He(this._client),this.roles=new cr(this._client),this.dataRetention=new ur(this._client),this.spendAlerts=new pr(this._client),this.certificates=new ar(this._client),this.projects=new V(this._client)}};J.AuditLogs=ir;J.AdminAPIKeys=or;J.Usage=mr;J.Invites=lr;J.Users=mt;J.Groups=He;J.Roles=cr;J.DataRetention=ur;J.SpendAlerts=pr;J.Certificates=ar;J.Projects=V;var Ze=class extends m{constructor(){super(...arguments),this.organization=new J(this._client)}};Ze.Organization=J;var ba=Symbol("brand.privateNullableHeaders");function*yc(t){if(!t)return;if(ba 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():Yn(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=Yn(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 yc(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{[ba]:!0,values:e,nulls:r}};var vr=class extends m{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 Tr=class extends m{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 Cr=class extends m{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 m{constructor(){super(...arguments),this.transcriptions=new Tr(this._client),this.translations=new Cr(this._client),this.speech=new vr(this._client)}};we.Transcriptions=Tr;we.Translations=Cr;we.Speech=vr;var dt=class extends m{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",R,{query:e,...r,__security:{bearerAuth:!0}})}cancel(e,r){return this._client.post(l`/batches/${e}/cancel`,{...r,__security:{bearerAuth:!0}})}};var Rr=class extends m{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",R,{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 Er=class extends m{create(e,r){return this._client.post("/realtime/sessions",{body:e,...r,headers:w([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}};var Sr=class extends m{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 m{constructor(){super(...arguments),this.sessions=new Er(this._client),this.transcriptionSessions=new Sr(this._client)}};Ve.Sessions=Er;Ve.TranscriptionSessions=Sr;var $r=class extends m{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 Mr=class extends m{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 m{constructor(){super(...arguments),this.sessions=new $r(this._client),this.threads=new Mr(this._client)}};Je.Sessions=$r;Je.Threads=Mr;var Nr=class extends m{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`,R,{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 zr=class extends m{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`,R,{query:o,...s,headers:w([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}};var xa=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,ht,So,Pe,gn,me,_t,Ur,ft,In,oe,yn,An,Es,Cs,Rs,wa,Pa,Oa,ka,va,Ta,Ca,Ee=class extends Be{constructor(){super(...arguments),G.add(this),So.set(this,[]),Pe.set(this,{}),gn.set(this,{}),me.set(this,void 0),_t.set(this,void 0),Ur.set(this,void 0),ft.set(this,void 0),In.set(this,void 0),oe.set(this,void 0),yn.set(this,void 0),An.set(this,void 0),Es.set(this,void 0)}[(So=new WeakMap,Pe=new WeakMap,gn=new WeakMap,me=new WeakMap,_t=new WeakMap,Ur=new WeakMap,ft=new WeakMap,In=new WeakMap,oe=new WeakMap,yn=new WeakMap,An=new WeakMap,Es=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 ht;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",Cs).call(this,n);if(s.controller.signal?.aborted)throw new D;return this._addRun(d(this,G,"m",Rs).call(this))}toReadableStream(){return new xe(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,r,s,n){let o=new ht;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",Cs).call(this,a);if(i.controller.signal?.aborted)throw new D;return this._addRun(d(this,G,"m",Rs).call(this))}static createThreadAssistantStream(e,r,s){let n=new ht;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 ht;return o._run(()=>o._runAssistantStream(e,r,s,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),o}currentEvent(){return d(this,yn,"f")}currentRun(){return d(this,An,"f")}currentMessageSnapshot(){return d(this,me,"f")}currentRunStepSnapshot(){return d(this,Es,"f")}async finalRunSteps(){return await this.done(),Object.values(d(this,Pe,"f"))}async finalMessages(){return await this.done(),Object.values(d(this,gn,"f"))}async finalRun(){if(await this.done(),!d(this,_t,"f"))throw Error("Final run was not received.");return d(this,_t,"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",Cs).call(this,i);if(o.controller.signal?.aborted)throw new D;return this._addRun(d(this,G,"m",Rs).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",Cs).call(this,a);if(i.controller.signal?.aborted)throw new D;return this._addRun(d(this,G,"m",Rs).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(ds(o)&&ds(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(!ds(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)}};ht=Ee,Cs=function(e){if(!this.ended)switch(k(this,yn,e,"f"),d(this,G,"m",Oa).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",Ca).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",Pa).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",wa).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier");default:}},Rs=function(){if(this.ended)throw new P("stream has ended, this shouldn't happen");if(!d(this,_t,"f"))throw Error("Final run has not been received");return d(this,_t,"f")},wa=function(e){let[r,s]=d(this,G,"m",va).call(this,e,d(this,me,"f"));k(this,me,r,"f"),d(this,gn,"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,Ur,"f")){if(d(this,ft,"f"))switch(d(this,ft,"f").type){case"text":this._emit("textDone",d(this,ft,"f").text,d(this,me,"f"));break;case"image_file":this._emit("imageFileDone",d(this,ft,"f").image_file,d(this,me,"f"));break}k(this,Ur,n.index,"f")}k(this,ft,r.content[n.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(d(this,Ur,"f")!==void 0){let n=e.data.content[d(this,Ur,"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")}},Pa=function(e){let r=d(this,G,"m",ka).call(this,e);switch(k(this,Es,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,In,"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,In,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,Es,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}},Oa=function(e){d(this,So,"f").push(e),this._emit("event",e)},ka=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=ht.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")},va=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",Ta).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")},Ta=function(e,r){return ht.accumulateDelta(r,e)},Ca=function(e){switch(k(this,An,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,_t,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 gt=class extends m{constructor(){super(...arguments),this.steps=new zr(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`,R,{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)}};gt.Steps=zr;var Ge=class extends m{constructor(){super(...arguments),this.runs=new gt(this._client),this.messages=new Nr(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=gt;Ge.Messages=Nr;var de=class extends m{constructor(){super(...arguments),this.realtime=new Ve(this._client),this.chatkit=new Je(this._client),this.assistants=new Rr(this._client),this.threads=new Ge(this._client)}};de.Realtime=Ve;de.ChatKit=Je;de.Assistants=Rr;de.Threads=Ge;var yt=class extends m{create(e,r){return this._client.post("/completions",{body:e,...r,stream:e.stream??!1,__security:{bearerAuth:!0}})}};var jr=class extends m{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 At=class extends m{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`,R,{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}})}};At.Content=jr;var Xe=class extends m{constructor(){super(...arguments),this.files=new At(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",R,{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=At;var Dr=class extends m{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 m{constructor(){super(...arguments),this.items=new Dr(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=Dr;var It=class extends m{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=xa(c)}),i)))}};var Lr=class extends m{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`,R,{query:o,...s,__security:{bearerAuth:!0}})}};var bt=class extends m{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`,R,{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}})}};bt.OutputItems=Lr;var Qe=class extends m{constructor(){super(...arguments),this.runs=new bt(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",R,{query:e,...r,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(l`/evals/${e}`,{...r,__security:{bearerAuth:!0}})}};Qe.Runs=bt;var xt=class extends m{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",R,{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 Kr=class extends m{};var Fr=class extends m{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 wt=class extends m{constructor(){super(...arguments),this.graders=new Fr(this._client)}};wt.Graders=Fr;var Br=class extends m{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 Pt=class extends m{constructor(){super(...arguments),this.permissions=new Br(this._client)}};Pt.Permissions=Br;var qr=class extends m{list(e,r={},s){return this._client.getAPIList(l`/fine_tuning/jobs/${e}/checkpoints`,R,{query:r,...s,__security:{bearerAuth:!0}})}};var Ot=class extends m{constructor(){super(...arguments),this.checkpoints=new qr(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",R,{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`,R,{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}})}};Ot.Checkpoints=qr;var fe=class extends m{constructor(){super(...arguments),this.methods=new Kr(this._client),this.jobs=new Ot(this._client),this.checkpoints=new Pt(this._client),this.alpha=new wt(this._client)}};fe.Methods=Kr;fe.Jobs=Ot;fe.Checkpoints=Pt;fe.Alpha=wt;var Wr=class extends m{};var et=class extends m{constructor(){super(...arguments),this.graderModels=new Wr(this._client)}};et.GraderModels=Wr;var kt=class extends m{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 vt=class extends m{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 Tt=class extends m{create(e,r){return this._client.post("/moderations",{body:e,...r,__security:{bearerAuth:!0}})}};var Hr=class extends m{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 Zr=class extends m{create(e,r){return this._client.post("/realtime/client_secrets",{body:e,...r,__security:{bearerAuth:!0}})}};var Se=class extends m{constructor(){super(...arguments),this.clientSecrets=new Zr(this._client),this.calls=new Hr(this._client)}};Se.ClientSecrets=Zr;Se.Calls=Hr;function Ra(t,e){if(!e||!Jc(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 Ea(t,r)&&ie(r),r}return $o(t,e)}function $o(t,e){let r=!t.status||t.status==="completed",s=t.output.map(o=>{if(o.type==="function_call")return{...o,parsed_arguments:r?Yc(e,o):null};if(o.type==="message"){let i=o.content.map(a=>a.type==="output_text"?{...a,parsed:r?Vc(e,a.text):null}:a);return{...o,content:i}}return o}),n=Object.assign({},t,{output:s});return Ea(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 Vc(t,e){return t.text?.format?.type!=="json_schema"?null:"$parseRaw"in t.text?.format?(t.text?.format).$parseRaw(e):JSON.parse(e)}function Jc(t){return!!bs(t.text?.format)}function Gc(t){return t?.$brand==="auto-parseable-tool"}function Xc(t,e){return t.find(r=>r.type==="function"&&r.name===e)}function Yc(t,e){let r=Xc(t.tools??[],e.name);return{...e,...e,parsed_arguments:Gc(r)?r.$parseRaw(e.arguments):r?.strict?JSON.parse(e.arguments):null}}function Ea(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 $a(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 Sa(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=Sa(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:Qc(t)}return e}function Sa(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 Qc(t){throw new P(`Unhandled response stream event: ${JSON.stringify(t)}`)}var Ss,bn,Ct,xn,Ma,Na,za,wn=class t extends Be{constructor(e){super(),Ss.add(this),bn.set(this,void 0),Ct.set(this,void 0),xn.set(this,void 0),k(this,bn,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,Ss,"m",Ma).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,Ss,"m",Na).call(this,i,o);if(n.controller.signal?.aborted)throw new D;return d(this,Ss,"m",za).call(this)}[(bn=new WeakMap,Ct=new WeakMap,xn=new WeakMap,Ss=new WeakSet,Ma=function(){this.ended||k(this,Ct,void 0,"f")},Na=function(r,s){if(this.ended)return;let n=(i,a)=>{(s==null||a.sequence_number>s)&&this._emit(i,a)},o=$a(r,d(this,Ct,"f"));switch(k(this,Ct,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}},za=function(){if(this.ended)throw new P("stream has ended, this shouldn't happen");let r=d(this,Ct,"f");if(!r)throw new P("request ended without sending any events");k(this,Ct,void 0,"f");let s=ep(r,d(this,bn,"f"));return k(this,xn,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,xn,"f");if(!e)throw new P("stream ended without producing a ChatCompletion");return e}};function ep(t,e){return Ra(t,e)}var Vr=class extends m{list(e,r={},s){return this._client.getAPIList(l`/responses/${e}/input_items`,R,{query:r,...s,__security:{bearerAuth:!0}})}};var Jr=class extends m{count(e={},r){return this._client.post("/responses/input_tokens",{body:e,...r,__security:{bearerAuth:!0}})}};var Oe=class extends m{constructor(){super(...arguments),this.inputItems=new Vr(this._client),this.inputTokens=new Jr(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=>$o(s,e))}stream(e,r){return wn.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=Vr;Oe.InputTokens=Jr;var Gr=class extends m{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 Xr=class extends m{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 Rt=class extends m{constructor(){super(...arguments),this.content=new Xr(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`,R,{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}})}};Rt.Content=Xr;var $e=class extends m{constructor(){super(...arguments),this.content=new Gr(this._client),this.versions=new Rt(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",R,{query:e,...r,__security:{bearerAuth:!0}})}delete(e,r){return this._client.delete(l`/skills/${e}`,{...r,__security:{bearerAuth:!0}})}};$e.Content=Gr;$e.Versions=Rt;var Yr=class extends m{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 m{constructor(){super(...arguments),this.parts=new Yr(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=Yr;var Ua=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 Qr=class extends m{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`,R,{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 h(g){for(let y of g){let I=await a.files.create({file:y,purpose:"assistants"},n);u.push(I.id)}}let f=Array(i).fill(c).map(h);return await Ua(f),await this.createAndPoll(e,{file_ids:u})}};var es=class extends m{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`,R,{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 m{constructor(){super(...arguments),this.files=new es(this._client),this.fileBatches=new Qr(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",R,{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=es;Me.FileBatches=Qr;var Et=class extends m{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 ts,ja,Pn,St=class extends m{constructor(){super(...arguments),ts.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,ts,"m",ja).call(this,s);let o=w([r]).values,i=d(this,ts,"m",Pn).call(this,o,"webhook-signature"),a=d(this,ts,"m",Pn).call(this,o,"webhook-timestamp"),c=d(this,ts,"m",Pn).call(this,o,"webhook-id"),u=parseInt(a,10);if(isNaN(u))throw new Ae("Invalid webhook timestamp format");let h=Math.floor(Date.now()/1e3);if(h-u>n)throw new Ae("Webhook timestamp is too old");if(u>h+n)throw new Ae("Webhook timestamp is too new");let f=i.split(" ").map(x=>x.startsWith("v1,")?x.substring(3):x),g=s.startsWith("whsec_")?Buffer.from(s.replace("whsec_",""),"base64"):Buffer.from(s,"utf-8"),y=c?`${c}.${a}.${e}`:`${a}.${e}`,I=await crypto.subtle.importKey("raw",g,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(let x of f)try{let _=Buffer.from(x,"base64");if(await crypto.subtle.verify("HMAC",I,_,new TextEncoder().encode(y)))return}catch{continue}throw new Ae("The given webhook signature does not match the expected signature")}};ts=new WeakSet,ja=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")},Pn=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 La=Symbol.for("openai.node.providerDefinitions.v1"),Ka=globalThis,Fa=Ka[La],Ba=Fa??new WeakMap;Fa||Object.defineProperty(Ka,La,{value:Ba});function qa(t){let e=Ba.get(t);if(!e)throw new Error("Invalid provider. Providers must be created with createProvider().");return e.configure()}var Mo,No,$s,Wa,lp="workload-identity-auth",T=class{constructor(e={}){Mo.add(this),$s.set(this,void 0),this.completions=new yt(this),this.chat=new We(this),this.embeddings=new It(this),this.files=new xt(this),this.images=new kt(this),this.audio=new we(this),this.moderations=new Tt(this),this.models=new vt(this),this.fineTuning=new fe(this),this.graders=new et(this),this.vectorStores=new Me(this),this.webhooks=new St(this),this.beta=new de(this),this.batches=new dt(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 Et(this);let r=e.provider;if(r){let x=["apiKey","adminAPIKey","workloadIdentity","baseURL"].filter(_=>e[_]!=null);if(x.length)throw new P(`The \`provider\` option cannot be used with ${x.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,...h}=e,f=r?qa(r):void 0,g={apiKey:n,adminAPIKey:o,organization:i,project:a,webhookSecret:c,workloadIdentity:u,provider:r,...h,baseURL:f?.baseURL??(s||"https://api.openai.com/v1")};if(n&&u)throw new P("The `apiKey` and `workloadIdentity` options are mutually exclusive");if(!f&&!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&&Di())throw new P(`It looks like you're running in a browser-like environment.
|
|
19
|
+
|
|
20
|
+
This is disabled by default, as it risks exposing your secret API credentials to attackers.
|
|
21
|
+
If you understand the risks and have appropriate mitigations in place,
|
|
22
|
+
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
|
|
23
|
+
|
|
24
|
+
new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
|
|
25
|
+
|
|
26
|
+
https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
|
|
27
|
+
`);this.baseURL=g.baseURL,this.timeout=g.timeout??No.DEFAULT_TIMEOUT,this.logger=g.logger??console;let y="warn";this.logLevel=y,this.logLevel=co(g.logLevel,"ClientOptions.logLevel",this)??co(pe("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??y,this.fetchOptions=g.fetchOptions,this.maxRetries=g.maxRetries??2,this.fetch=g.fetch??Gs(),k(this,$s,Fi,"f");let I=r?void 0:pe("OPENAI_CUSTOM_HEADERS");if(I){let x={};for(let _ of I.split(`
|
|
28
|
+
`)){let v=_.indexOf(":");v>=0&&(x[_.substring(0,v).trim()]=_.substring(v+1).trim())}g.defaultHeaders=w([x,g.defaultHeaders])}this._options=g,this._provider=f,u&&(this._workloadIdentityAuth=new sn(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 Xi(e)}getUserAgent(){return`${this.constructor.name}/JS ${Ke}`}defaultIdempotencyKey(){return`stainless-node-retry-${Xn()}`}makeStatusError(e,r,s,n){return j.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,Mo,"m",Wa).call(this)&&s||this.baseURL,o=Si(e)?new URL(e):new URL(n+(n.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),i=this.defaultQuery(),a=Object.fromEntries(o.searchParams);return(!Qn(i)||!Qn(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 it(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"),h=s===void 0?"":`, retryOf: ${s}`,f=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},y=new AbortController,I=await this.fetchWithAuth(a,i,c,y,g).catch(ps),x=Date.now();if(I instanceof globalThis.Error){let p=`retrying, ${r} attempts remaining`;if(n.signal?.aborted)throw new D;let A=cs(I)||/timed? ?out/i.test(String(I)+("cause"in I?String(I.cause):""));if(r)return K(this).info(`[${u}] connection ${A?"timed out":"failed"} - ${p}`),K(this).debug(`[${u}] connection ${A?"timed out":"failed"} (${p})`,ve({retryOfRequestLogID:s,url:a,durationMs:x-f,message:I.message})),this.retryRequest(n,r,s??u);throw K(this).info(`[${u}] connection ${A?"timed out":"failed"} - error; no more retries left`),K(this).debug(`[${u}] connection ${A?"timed out":"failed"} (error; no more retries left)`,ve({retryOfRequestLogID:s,url:a,durationMs:x-f,message:I.message})),I instanceof nt||I instanceof ms?I:A?new ye:new Le({message:cp(I),cause:I})}let _=[...I.headers.entries()].filter(([p])=>p==="x-request-id").map(([p,A])=>", "+p+": "+JSON.stringify(A)).join(""),v=`[${u}${h}${_}] ${i.method} ${a} ${I.ok?"succeeded":"failed"} with status ${I.status} in ${x-f}ms`;if(!I.ok){if(I.status===401&&this._workloadIdentityAuth&&g.bearerAuth&&!n.__metadata?.hasStreamingBody&&!n.__metadata?.workloadIdentityTokenRefreshed)return await ro(I.body),this._workloadIdentityAuth.invalidateToken(),this.makeRequest({...n,__metadata:{...n.__metadata,workloadIdentityTokenRefreshed:!0}},r,s??u);let p=await this.shouldRetry(I);if(r&&p){let L=`retrying, ${r} attempts remaining`;return await ro(I.body),K(this).info(`${v} - ${L}`),K(this).debug(`[${u}] response error (${L})`,ve({retryOfRequestLogID:s,url:I.url,status:I.status,headers:I.headers,durationMs:x-f})),this.retryRequest(n,r,s??u,I.headers)}let A=p?"error; no more retries left":"error; not retryable";K(this).info(`${v} - ${A}`);let O=await I.text().catch(L=>ps(L).message),z=Ni(O),N=z?void 0:O;throw K(this).debug(`[${u}] response error (${A})`,ve({retryOfRequestLogID:s,url:I.url,status:I.status,headers:I.headers,message:N,durationMs:Date.now()-f})),this.makeStatusError(I.status,z,N,I.headers)}return K(this).info(v),K(this).debug(`[${u}] response start`,ve({retryOfRequestLogID:s,url:I.url,status:I.status,headers:I.headers,durationMs:x-f})),{response:I,options:n,controller:y,requestLogID:u,retryOfRequestLogID:s,startTime:f}}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 gs(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 ${lp}`){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),h=globalThis.ReadableStream&&a.body instanceof globalThis.ReadableStream||typeof a.body=="object"&&a.body!==null&&Symbol.asyncIterator in a.body,f={signal:n.signal,...h?{duplex:"half"}:{},method:"GET",...a};i&&(f.method=i.toUpperCase());try{return await this.fetch.call(void 0,e,f)}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&&Mi("timeout",s.timeout),s.timeout=s.timeout??this.timeout;let{bodyHeaders:u,body:h,isStreamingBody:f}=this.buildBody({options:s});f&&(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&&h instanceof globalThis.ReadableStream&&{duplex:"half"},...h&&{body:h},...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))}:{},...Li(),"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,$s,"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:Xs(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,$s,"f").call(this,{body:r,headers:n}),isStreamingBody:!1}}};No=T,$s=new WeakMap,Mo=new WeakSet,Wa=function(){return this._provider!==void 0||this.baseURL!=="https://api.openai.com/v1"};T.OpenAI=No;T.DEFAULT_TIMEOUT=6e5;T.OpenAIError=P;T.APIError=j;T.APIConnectionError=Le;T.APIConnectionTimeoutError=ye;T.APIUserAbortError=D;T.NotFoundError=Wt;T.ConflictError=Ht;T.RateLimitError=Vt;T.BadRequestError=Ft;T.AuthenticationError=Bt;T.InternalServerError=Jt;T.PermissionDeniedError=qt;T.UnprocessableEntityError=Zt;T.InvalidWebhookSignatureError=Ae;T.toFile=As;T.Completions=yt;T.Chat=We;T.Embeddings=It;T.Files=xt;T.Images=kt;T.Audio=we;T.Moderations=Tt;T.Models=vt;T.FineTuning=fe;T.Graders=et;T.VectorStores=Me;T.Webhooks=St;T.Beta=de;T.Batches=dt;T.Uploads=tt;T.Admin=Ze;T.Responses=Oe;T.Realtime=Se;T.Conversations=Ye;T.Evals=Qe;T.Containers=Xe;T.Skills=$e;T.Videos=Et;function cp(t){if(pp(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 pp(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 mp(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===ye.name&&"message"in t&&typeof t.message=="string"?(e=new Error(t.message),e.name="TimeoutError",rt(e,!0)):t.constructor.name===D.name&&"message"in t&&typeof t.message=="string"?(e=new Error(t.message),e.name="AbortError",rt(e,!1)):mp(t)?e=ni.fromError(t):"status"in t&&t.status===400&&"message"in t&&typeof t.message=="string"&&t.message.includes("tool_calls")?e=rt(ls(t,"INVALID_TOOL_RESULTS"),!1):"status"in t&&t.status===401?e=rt(ls(t,"MODEL_AUTHENTICATION"),!1):"status"in t&&t.status===429?e=rt(ls(t,"MODEL_RATE_LIMIT"),!0):"status"in t&&t.status===404?e=rt(ls(t,"MODEL_NOT_FOUND"),!1):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 dp(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 On(t){return t.metadata?.filename??t.metadata?.name??t.metadata?.title}var fp="LC_AUTOGENERATED";function $t(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'."),fp)}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(!qs.isInstance(t))throw new Error("Invalid generic chat message");return dp(t);default:throw new Error(`Unknown message type: ${e}`)}}function Ha(t){return!!(t.includes("gpt-5.2-pro")||t.includes("gpt-5.4-pro")||t.includes("gpt-5.5-pro")||t.includes("codex"))}function Ue(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 Uo(t){return typeof Headers<"u"&&t!==null&&typeof t=="object"&&Object.prototype.toString.call(t)==="[object Headers]"}function Za(t){let e=he(()=>{if(Uo(t))return t;if(Array.isArray(t))return new Headers(t);if(typeof t=="object"&&t!==null&&"values"in t&&Uo(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 Va(){let t=si();return(t==="node"||t==="deno")&&(t=`(${t}/${process.version}; ${process.platform}; ${process.arch})`),t}function je(t,e=!1,r="1.0.0"){let s=Za(t),n=Va(),o=`langchainjs${e?"-azure":""}-openai`;return{...s,"User-Agent":s["User-Agent"]?`${o}/${r} (${n})${s["User-Agent"]}`:`${o}/${r} (${n})`}}function Ja(t,e){let r;return Vs(t)?r=Pi(t):r=t,e?.strict!==void 0&&(r.function.strict=e.strict),r}function hp(t){return t.anyOf!==void 0&&Array.isArray(t.anyOf)}function Ga(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(Xa(r.parameters,0)),e.push("}) => any;")):e.push(`type ${r.name} = () => any;`),e.push("");return e.push("} // namespace functions"),e.join(`
|
|
29
|
+
`)}function Xa(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}: ${kn(n,e)},`):r.push(`${s}?: ${kn(n,e)},`);return r.map(s=>" ".repeat(e)+s).join(`
|
|
30
|
+
`)}function kn(t,e){if(hp(t))return t.anyOf.map(r=>kn(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["{",Xa(t,e+2),"}"].join(`
|
|
31
|
+
`);case"array":return t.items?`${kn(t.items,e)}[]`:"any[]";default:return""}}function vn(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 rs(t){return"type"in t&&t.type!=="function"}function Ya(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 Qa(t){return t!=null&&typeof t=="object"&&"type"in t&&t.type!=="function"}function Mt(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 Tn(t){return"type"in t&&t.type==="custom"&&"custom"in t&&typeof t.custom=="object"&&t.custom!==null}function eu(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 tu(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 ru(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="tool_call"&&"isComputerTool"in t&&t.isComputerTool===!0}function su(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 nu(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 ou(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 au=Symbol("Let zodToJsonSchema decide on which parser to use"),iu={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"},uu=t=>typeof t=="string"?{...iu,basePath:["#"],definitions:{},name:t}:{...iu,basePath:["#"],definitions:{},...t};var Ms=t=>"_def"in t?t._def:t;function lu(t){if(!t)return!0;for(let e in t)return!1;return!0}var cu=t=>{let e=uu(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])=>[Ms(n),{def:Ms(n),path:[...e.basePath,e.definitionPath,s],jsonSchema:void 0}]))}};function jo(t,e,r,s){s?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function M(t,e,r,s,n){t[e]=r,jo(t,e,s,n)}function pu(){return{}}function mu(t,e){let r={type:"array"};return t.type?._def?.typeName!==E.ZodAny&&(r.items=C(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 du(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 fu(){return{type:"boolean"}}function hu(t,e,r){return C(t.type._def,e,r)}var _u=(t,e,r)=>C(t.innerType._def,e,r);function Do(t,e,r){let s=r??e.dateStrategy;if(Array.isArray(s))return{anyOf:s.map((n,o)=>Do(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 _p(t,e)}}var _p=(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 gu(t,e,r){return{...C(t.innerType._def,e,r),default:t.defaultValue()}}function yu(t,e,r){return e.effectStrategy==="input"?C(t.schema._def,e,r):{}}function Au(t){return{type:"string",enum:[...t.values]}}var gp=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function Iu(t,e){let r=[C(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),C(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(gp(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 bu(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 Lo,Nt={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:()=>(Lo===void 0&&(Lo=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Lo),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 Cn(t,e){let r={type:"string"};function s(n){return e.patternStrategy==="escape"?yp(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,Nt.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,Nt.cuid,n.message,e);break;case"cuid2":ge(r,Nt.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,Nt.emoji,n.message,e);break;case"ulid":{ge(r,Nt.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,Nt.base64,n.message,e);break}}break}case"nanoid":ge(r,Nt.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}var yp=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:xu(e,s),...r&&s.errorMessages&&{errorMessage:{pattern:r}}})):M(t,"pattern",xu(e,s),r,s)},xu=(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
|
+
]))`;continue}else if(n[u]==="$"){o+=`($|(?=[\r
|
|
33
|
+
]))`;continue}}if(s.s&&n[u]==="."){o+=a?`${n[u]}\r
|
|
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 Rn(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]:C(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",n]})??{}}),{}),additionalProperties:!1};let r={type:"object",additionalProperties:C(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(Cn(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 wu(t,e){if(e.mapStrategy==="record")return Rn(t,e);let r=C(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},s=C(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 Pu(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 Ou(){return{not:{}}}function ku(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Ns={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Tu(t,e){if(e.target==="openApi3")return vu(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(s=>s._def.typeName in Ns&&(!s._def.checks||!s._def.checks.length))){let s=r.reduce((n,o)=>{let i=Ns[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 vu(t,e)}var vu=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((s,n)=>C(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 Cu(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:Ns[t.innerType._def.typeName],nullable:!0}:{type:[Ns[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=C(t.innerType._def,{...e,currentPath:[...e.currentPath]},r);return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let s=C(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return s&&{anyOf:[s,{type:"null"}]}}function Ru(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",jo(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 Ap(t,e){return e.removeAdditionalStrategy==="strict"?t.catchall._def.typeName==="ZodNever"?t.unknownKeys!=="strict":C(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0:t.catchall._def.typeName==="ZodNever"?t.unknownKeys==="passthrough":C(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0}function Eu(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=C(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:Ap(t,e)};return r.required.length||delete r.required,r}var Su=(t,e,r)=>{if(e.propertyPath&&e.currentPath.slice(0,e.propertyPath.length).toString()===e.propertyPath.toString())return C(t.innerType._def,{...e,currentPath:e.currentPath},r);let s=C(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]},r);return s?{anyOf:[{not:{}},s]}:{}};var $u=(t,e,r)=>{if(e.pipeStrategy==="input")return C(t.in._def,e,r);if(e.pipeStrategy==="output")return C(t.out._def,e,r);let s=C(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=C(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",s?"1":"0"]});return{allOf:[s,n].filter(o=>o!==void 0)}};function Mu(t,e,r){return C(t.type._def,e,r)}function Nu(t,e){let s={type:"array",uniqueItems:!0,items:C(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 zu(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,s)=>C(r._def,{...e,currentPath:[...e.currentPath,"items",`${s}`]})).reduce((r,s)=>s===void 0?r:[...r,s],[]),additionalItems:C(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,s)=>C(r._def,{...e,currentPath:[...e.currentPath,"items",`${s}`]})).reduce((r,s)=>s===void 0?r:[...r,s],[])}}function Uu(){return{not:{}}}function ju(){return{}}var Du=(t,e,r)=>C(t.innerType._def,e,r);function C(t,e,r=!1){let s=e.seen.get(t);if(e.override){let o=e.override?.(t,e,s,r);if(o!==au)return o}if(s&&!r){let o=Ip(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=wp(t,t.typeName,e,r);return o&&Pp(t,e,o),n.jsonSchema=o,o}finally{r&&s&&e.seen.set(t,s)}}var Ip=(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:bp(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:xp(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}},Lu="_x_",bp=t=>{if(/^[A-Za-z0-9_-]*$/.test(t)&&!t.startsWith(Lu))return t;let e=Lu;for(let r=0;r<t.length;r++)e+=t.charCodeAt(r).toString(16).padStart(4,"0");return e},xp=(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("/")},wp=(t,e,r,s)=>{switch(e){case E.ZodString:return Cn(t,r);case E.ZodNumber:return Ru(t,r);case E.ZodObject:return Eu(t,r);case E.ZodBigInt:return du(t,r);case E.ZodBoolean:return fu();case E.ZodDate:return Do(t,r);case E.ZodUndefined:return Uu();case E.ZodNull:return ku(r);case E.ZodArray:return mu(t,r);case E.ZodUnion:case E.ZodDiscriminatedUnion:return Tu(t,r);case E.ZodIntersection:return Iu(t,r);case E.ZodTuple:return zu(t,r);case E.ZodRecord:return Rn(t,r);case E.ZodLiteral:return bu(t,r);case E.ZodEnum:return Au(t);case E.ZodNativeEnum:return Pu(t);case E.ZodNullable:return Cu(t,r,s);case E.ZodOptional:return Su(t,r,s);case E.ZodMap:return wu(t,r);case E.ZodSet:return Nu(t,r);case E.ZodLazy:return C(t.getter()._def,r,s);case E.ZodPromise:return Mu(t,r,s);case E.ZodNaN:case E.ZodNever:return Ou();case E.ZodEffects:return yu(t,r,s);case E.ZodAny:return pu();case E.ZodUnknown:return ju();case E.ZodDefault:return gu(t,r,s);case E.ZodBranded:return hu(t,r,s);case E.ZodReadonly:return Du(t,r,s);case E.ZodCatch:return _u(t,r,s);case E.ZodPipeline:return $u(t,r,s);case E.ZodFunction:case E.ZodVoid:case E.ZodSymbol:return;default:return(n=>{})(e)}},Pp=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r);var Ko=(t,e)=>{let r=cu(e),s=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,n=C(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(lu(r.definitions))return;let c={},u=new Set;for(let h=0;h<500;h++){let f=Object.entries(r.definitions).filter(([g])=>!u.has(g));if(f.length===0)break;for(let[g,y]of f)c[g]=C(Ms(y),{...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 Ku(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 Fo(t){if(typeof t=="boolean")return!1;if(t.type==="null")return!0;for(let e of t.oneOf??[])if(Fo(e))return!0;for(let e of t.anyOf??[])if(Fo(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(!zt(t))throw new TypeError(`Expected ${JSON.stringify(t)} to be an object; path=${e.join("/")}`);let s=t.$defs;if(zt(s))for(let[g,y]of Object.entries(s))De(y,[...e,"$defs",g],r);let n=t.definitions;if(zt(n))for(let[g,y]of Object.entries(n))De(y,[...e,"definitions",g],r);t.type==="object"&&!("additionalProperties"in t)&&(t.additionalProperties=!1);let i=t.required??[],a=t.properties;if(zt(a)){for(let[g,y]of Object.entries(a))if(!Fo(y)&&!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,y])=>[g,De(y,[...e,"properties",g],r)]))}let c=t.items;zt(c)&&(t.items=De(c,[...e,"items"],r));let u=t.anyOf;Array.isArray(u)&&(t.anyOf=u.map((g,y)=>De(g,[...e,"anyOf",String(y)],r)));let h=t.allOf;if(Array.isArray(h))if(h.length===1){let g=De(h[0],[...e,"allOf","0"],r);Object.assign(t,g),delete t.allOf}else t.allOf=h.map((g,y)=>De(g,[...e,"allOf",String(y)],r));t.default===null&&delete t.default;let f=t.$ref;if(f&&kp(t,1)){if(typeof f!="string")throw new TypeError(`Received non-string $ref - ${f}; path=${e.join("/")}`);let g=Op(r,f);if(typeof g=="boolean")throw new Error(`Expected \`$ref: ${f}\` to resolve to an object schema but got boolean`);if(!zt(g))throw new Error(`Expected \`$ref: ${f}\` 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 Op(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(!zt(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 zt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function kp(t,e){let r=0;for(let s in t)if(r++,r>e)return!0;return!1}function vp(t,e){return Ko(t,{openaiStrictMode:!0,name:e.name,nameStrategy:"duplicate-ref",$refStrategy:"extract-to-root",nullableStrategy:"property"})}function Tp(t){return Ku(mi(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 Cp(t){return"_zod"in t}function Fu(t,e,r){return ca({type:"json_schema",json_schema:{...r,name:e,strict:!0,schema:Cp(t)?Tp(t):vp(t,{name:e})}},s=>t.parse(JSON.parse(s)))}var Bu=["jsonSchema","functionCalling","jsonMode"];function qu(t,e){if(typeof e<"u"&&!Bu.includes(e))throw new Error(`Invalid method: ${e}. Supported methods are: ${Bu.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 Rp(t,e){let r={...t};return Object.defineProperties(r,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:e,enumerable:!1}}),r}function Wu(t,e,r){if(fi(t))return Fu(t,e,r);if(di(t))return Rp({type:"json_schema",json_schema:{...r,name:e,strict:!0,schema:Lt(t,{cycles:"ref",reused:"ref",override(s){s.jsonSchema.title=e}})}},s=>pi(t,JSON.parse(s)));throw new Error("Unsupported schema response format")}function Hu(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 Zu={"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}};var En="**REDACTED**";function ss(t,e){return typeof t=="string"?{model:t,...e??{}}:t??e}var Ut=class extends xi{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}}_getInvocationParamsForTracing(t){let e=this.invocationParams(t);return Array.isArray(e.tools)?{...e,tools:e.tools.map(r=>{if(r?.type!=="mcp")return r;let s={...r};return"headers"in s&&(s.headers=En),"authorization"in s&&(s.authorization=En),s})}:e}_getCallOptionsForTracing(t,e){return Array.isArray(t.tools)?{...t,tools:t.tools.map(r=>{if(typeof r!="object"||r===null||!("type"in r)||r.type!=="mcp")return r;let s={...r};return"headers"in s&&(s.headers=En),"authorization"in s&&(s.authorization=En),s})}:t}_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,r=Oi({baseURL:t?.configuration?.baseURL??(re("OPENAI_API_BASE")||re("OPENAI_BASE_URL")||void 0),providerPath:"openai/v1"});this.apiKey=t?.apiKey??e??r.apiKey??re("OPENAI_API_KEY"),this.organization=t?.configuration?.organization??re("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,baseURL:r.baseURL},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.8")}_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&&as(t.json_schema.schema)?Wu(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=Ue({baseURL:this.clientConfig.baseURL}),r={...this.clientConfig,baseURL:e,timeout:this.timeout,maxRetries:0};r.baseURL||delete r.baseURL,r.defaultHeaders=je(r.defaultHeaders),this.client=new T(r)}return{...this.clientConfig,...t}}_convertChatOpenAIToolToCompletionsTool(t,e){return Mt(t)?ou(t.metadata.customTool):Ws(t)?e?.strict!==void 0?{...t,function:{...t.function,strict:e.strict}}:t:Ja(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(rs(s)||Mt(s))return s;if(Ya(s))return s.extras.providerToolDefinition;let n=this._convertChatOpenAIToolToCompletionsTool(s,{strict:r});return Vs(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,h=o;if(h._getType()==="function"&&(u-=2),h.additional_kwargs?.function_call&&(u+=3),h?.additional_kwargs.function_call?.name&&(u+=await this.getNumTokens(h.additional_kwargs.function_call?.name)),h.additional_kwargs.function_call?.arguments)try{u+=await this.getNumTokens(JSON.stringify(JSON.parse(h.additional_kwargs.function_call?.arguments)))}catch(f){console.error("Error parsing function arguments",f,JSON.stringify(h.additional_kwargs.function_call)),u+=await this.getNumTokens(h.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=Ga(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 Zu[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=qu(this.model,e?.method);if(a==="jsonMode"){s=Vn(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:hi(c),schema:as(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}}}),as(n)||Hn(n)){let h=Vn(n);s=_i.from(async f=>"parsed"in f.additional_kwargs?f.additional_kwargs.parsed:h.invoke(f.content))}else s=new yi}else{let c=o??"extract",u=Lt(n),h;as(n)||Hn(n)?h={name:c,description:u.description,parameters:u}:typeof n.name=="string"&&typeof n.parameters=="object"&&n.parameters!=null?(h=n,c=n.name):(c=n.title??c,h={name:c,description:n.description??"",parameters:n}),r=this.withConfig({outputVersion:"v0",tools:[{type:"function",function:h}],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=Ai(n,c)}return Ii(r,s,i)}};var zs={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=qn({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=Bn(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=Bn(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=qn({dataUrl:t.url}),r=$t(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=$t(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`)}},Sn=({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(Hs(u,{returnId:!0}))}catch(h){i.push(Kt(u,h.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,usage:{...e.usage},...e.system_fingerprint?{system_fingerprint:e.system_fingerprint}:{}};return t.audio&&(a.audio=t.audio),new ae({content:Hu(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 qs(t.content||"",t.role??"unknown")}},$n=({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 li({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 Dt({content:o,tool_call_chunks:c,additional_kwargs:i,id:e.id,response_metadata:a})}else return n==="system"?new Wn({content:o,response_metadata:a}):n==="developer"?new Wn({content:o,response_metadata:a,additional_kwargs:{__openai_role__:"developer"}}):n==="function"?new ui({content:o,additional_kwargs:i,name:t.name,response_metadata:a}):n==="tool"?new oi({content:o,additional_kwargs:i,tool_call_id:t.tool_call_id,response_metadata:a}):new ai({content:o,role:n,response_metadata:a})},Bo=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=ci(()=>{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=$t(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}}}},qo=({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(Zn):t.additional_kwargs.tool_calls!=null&&(n.tool_calls=t.additional_kwargs.tool_calls),n}else{if(r==="tool"&&Fs.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=Bo(o);i&&(yield i)}}return{role:"user",content:Array.from(s(t.contentBlocks))}},jt=({messages:t,model:e})=>t.flatMap(r=>{if("output_version"in r.response_metadata&&r.response_metadata?.output_version==="v1")return qo({message:r});let s=ze(r);s==="system"&&Ne(e)&&(s="developer");let n=typeof r.content=="string"?r.content:r.content.flatMap(i=>Ls(i)?Ks(i,zs):typeof i=="object"&&i!==null&&"type"in i&&(i.type==="tool_use"||i.type==="tool_call"||i.type==="reasoning"||i.type==="reasoning_content"||i.type==="thinking")?[]: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(Zn):(r.additional_kwargs.tool_calls!=null&&(o.tool_calls=r.additional_kwargs.tool_calls),Fs.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 Mn=class extends Ut{constructor(t,e){super(ss(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:vn(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=jt({messages:t,model:this.model});if(n.stream){let i=this._streamResponseChunks(t,e,r),a={};for await(let y of i){y.message.response_metadata={...y.generationInfo,...y.message.response_metadata};let I=y.generationInfo?.completion??0;a[I]===void 0?a[I]=y:a[I]=a[I].concat(y)}let c=Object.entries(a).sort(([y],[I])=>parseInt(y,10)-parseInt(I,10)).map(([y,I])=>I),{functions:u,function_call:h}=this.invocationParams(e),f=await this._getEstimatedTokenCountFromPrompt(t,u,h),g=await this._getNumTokensFromGenerations(c);return s.input_tokens=f,s.output_tokens=g,s.total_tokens=f+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,maxRetries:e?.maxRetries,...e?.options}),{completion_tokens:a,prompt_tokens:c,total_tokens:u,prompt_tokens_details:h,completion_tokens_details:f}=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),(h?.audio_tokens!==null||h?.cached_tokens!==null)&&(s.input_token_details={...h?.audio_tokens!==null&&{audio:h?.audio_tokens},...h?.cached_tokens!==null&&{cache_read:h?.cached_tokens}}),(f?.audio_tokens!==null||f?.reasoning_tokens!==null)&&(s.output_token_details={...f?.audio_tokens!==null&&{audio:f?.audio_tokens},...f?.reasoning_tokens!==null&&{reasoning:f?.reasoning_tokens}});let g=[];for(let y of i?.choices??[]){let I={text:y.message?.content??"",message:this._convertCompletionsMessageToBaseMessage(y.message??{role:"assistant"},i)};I.generationInfo={...y.finish_reason?{finish_reason:y.finish_reason}:{},...y.logprobs?{logprobs:y.logprobs}:{}},Bs(I.message)&&(I.message.usage_metadata=s),I.message=new ae(Object.fromEntries(Object.entries(I.message).filter(([x])=>!x.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=jt({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*Zs(async function*(c,u){for await(let h of c){if(u?.aborted)return;yield h}}(o,e.signal),{streamUsage:i??!0,provider:this.streamEventProvider})}get streamEventProvider(){return"openai"}async*_streamResponseChunks(t,e,r){let s=jt({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:h}=u;if(!h)continue;let f=this._convertCompletionsDeltaToBaseMessageChunk(h,c,o);o=h.role??o;let g={prompt:e.promptIndex??0,completion:u.index??0};if(typeof f.content!="string"){console.log("[WARNING]: Received non-string content from OpenAI. This is currently not supported.");continue}let y={...g};u.finish_reason!=null&&(y.finish_reason=u.finish_reason,y.system_fingerprint=c.system_fingerprint,y.model_name=c.model,y.service_tier=c.service_tier),this.logprobs&&(y.logprobs=u.logprobs);let I=new is({message:f,text:f.content,generationInfo:y});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}},h=new is({message:new Dt({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 h,await r?.handleLLMNewToken(h.text??"",{prompt:0,completion:0},void 0,void 0,void 0,{chunk:h})}if(e.signal?.aborted)throw new Error("AbortError")}async completionWithRetry(t,e){let{maxRetries:r,...s}=e??{},n=this._getClientOptions(s),o=t.response_format&&t.response_format.type==="json_schema";return this.caller.callWithOptions({maxRetries:r},async()=>{try{return o&&!t.stream?await this.client.chat.completions.parse(t,n):await this.client.chat.completions.create(t,n)}catch(i){throw ce(i)}})}_convertCompletionsDeltaToBaseMessageChunk(t,e,r){return $n({delta:t,rawResponse:e,includeRawResponse:this.__includeRawResponse,defaultRole:r})}_convertCompletionsMessageToBaseMessage(t,e){return Sn({message:t,rawResponse:e,includeRawResponse:this.__includeRawResponse})}};var Nn="__openai_function_call_ids__",zn="__openai_custom_tool_call_ids__";function el(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 Sp(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 ns=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}},Us=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(el),...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(Hs(c,{returnId:!0}))}catch(u){let h;typeof u=="object"&&u!=null&&"message"in u&&typeof u.message=="string"&&(h=u.message),s.push(Kt(c,h))}i[Nn]??={},a.id&&(i[Nn][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=eu(a);c?(r.push(c),i[zn]??={},a.id&&a.call_id&&(i[zn][a.call_id]=a.id)):s.push(Kt(a,"Malformed custom tool call"))}else if(a.type==="computer_call"){let c=tu(a);c?r.push(c):s.push(Kt(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:ns(t.usage),additional_kwargs:i,response_metadata:o})},Wo=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}},Un=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:[el(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[Nn]={[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[zn]={[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=Us(t.response);if(s=ns(t.response.usage),t.response.text?.format?.type==="json_schema"&&c.text)try{i.parsed??=JSON.parse(c.text)}catch{}for(let[u,h]of Object.entries(t.response))u!=="id"&&(u==="output"?o[u]=c.response_metadata.output:o[u]=h)}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((h,f)=>({...h,index:f})):void 0;i.reasoning={id:t.item.id,type:t.item.type,...c?{summary:c}:{}};let u=t.item.summary?.map(h=>h.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 is({text:e.map(c=>c.text).join(""),message:new Dt({id:a,content:e,tool_call_chunks:n,usage_metadata:s,additional_kwargs:i,response_metadata:o}),generationInfo:r})},Ho=t=>{let e=ae.isInstance(t)&&t.response_metadata?.model_provider==="openai";function*r(){let s=he(()=>{try{let p=ze(t);return p==="system"||p==="developer"||p==="assistant"||p==="user"?p:"assistant"}catch{return"assistant"}}),n=p=>s==="assistant"?{type:"output_text",text:p,annotations:[]}:{type:"input_text",text:p},o,i=new Set,a=new Set,c=new Map,u=new Map;function*h(){if(!o)return;let p=o.content;(typeof p=="string"&&p.length>0||Array.isArray(p)&&p.length>0)&&(yield o),o=void 0}let f=(p,A)=>{o||(o={type:"message",role:s,content:[],...A?{phase:A}:{}}),typeof o.content=="string"?o.content=o.content.length>0?[n(o.content),...p]:[...p]:o.content.push(...p)},g=p=>{if(typeof p=="string")return p;try{return JSON.stringify(p??{})}catch{return"{}"}},y=p=>{let A=he(()=>{let O=p.metadata?.detail;return O==="low"||O==="high"||O==="auto"?O:"auto"});if(p.fileId)return{type:"input_image",detail:A,file_id:p.fileId};if(p.url)return{type:"input_image",detail:A,image_url:p.url};if(p.data){let O=typeof p.data=="string"?p.data:Buffer.from(p.data).toString("base64");return{type:"input_image",detail:A,image_url:`data:${p.mimeType??"image/png"};base64,${O}`}}},I=p=>{if(p.fileId){let A=On(p);return{type:"input_file",file_id:p.fileId,...A?{filename:A}:{}}}if(p.url){let A=On(p);return{...A?{filename:A}:{},type:"input_file",file_url:p.url}}if(p.data){let A=$t(p),O=typeof p.data=="string"?p.data:Buffer.from(p.data).toString("base64");return{type:"input_file",file_data:`data:${p.mimeType??"application/octet-stream"};base64,${O}`,filename:A}}},x=p=>{let A=he(()=>{if(Array.isArray(p.summary)){let z=p.summary?.map(N=>N?.text).filter(N=>typeof N=="string")??[];if(z.length>0)return z}return p.reasoning?[p.reasoning]:[]}),O=A.length>0?A.map(z=>({type:"summary_text",text:z})):[{type:"summary_text",text:""}];return{type:"reasoning",...p.id?{id:p.id}:{},summary:O}},_=p=>({type:"function_call",name:p.name??"",call_id:p.id??"",arguments:g(p.args)}),v=p=>{let A=g(p.output),O=p.status==="success"?"completed":p.status==="error"?"incomplete":void 0;return{type:"function_call_output",call_id:p.toolCallId??"",output:A,...O?{status:O}:{}}};for(let p of t.contentBlocks)if(p.type==="text"){let A=he(()=>{if("extras"in p&&typeof p.extras=="object"&&p.extras!==null&&"phase"in p.extras)return p.extras.phase});f([n(p.text)],A)}else if(p.type!=="invalid_tool_call"){if(p.type==="reasoning")yield*h(),yield x(p);else if(p.type==="tool_call"){yield*h();let A=p.id??"";A&&(i.add(A),c.delete(A)),yield _(p)}else if(p.type==="tool_call_chunk"){if(p.id){let A=c.get(p.id)??{name:p.name,args:[]};p.name&&(A.name=p.name),p.args&&A.args.push(p.args),c.set(p.id,A)}}else if(p.type==="server_tool_call"){yield*h();let A=p.id??"";A&&(a.add(A),u.delete(A)),yield _(p)}else if(p.type==="server_tool_call_chunk"){if(p.id){let A=u.get(p.id)??{name:p.name,args:[]};p.name&&(A.name=p.name),p.args&&A.args.push(p.args),u.set(p.id,A)}}else if(p.type==="server_tool_call_result")yield*h(),yield v(p);else if(p.type!=="audio")if(p.type==="file"){let A=I(p);A&&f([A])}else if(p.type==="image"){let A=y(p);A&&f([A])}else if(p.type==="video"){let A=I(p);A&&f([A])}else p.type==="text-plain"?p.text&&f([n(p.text)]):p.type==="non_standard"&&e&&(yield*h(),yield p.value)}yield*h();for(let[p,A]of c){if(!p||i.has(p))continue;let O=A.args.join("");!A.name&&!O||(yield{type:"function_call",call_id:p,name:A.name??"",arguments:O})}for(let[p,A]of u){if(!p||a.has(p))continue;let O=A.args.join("");!A.name&&!O||(yield{type:"function_call",call_id:p,name:A.name??"",arguments:O})}}return Array.from(r())},os=({messages:t,zdrEnabled:e,model:r})=>t.flatMap(s=>{let n=s.response_metadata;if(n?.output_version==="v1")return Ho(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 h=a.content.find(g=>g.type==="computer_screenshot");if(h)return h;let f=a.content.find(g=>g.type==="image_url");if(f)return{type:"input_image",image_url:typeof f.image_url=="string"?f.image_url:f.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(x=>"type"in x))return n?.output;let a=[],c=o?.reasoning,u=!!c?.encrypted_content;if(c&&(!e||u)){let x=Wo(c);a.push(x)}let{content:h}=s;if(o?.refusal&&(typeof h=="string"&&(h=[{type:"output_text",text:h,annotations:[]}]),h=[...h,{type:"refusal",refusal:o.refusal}]),typeof h=="string"||h.length>0){let x={type:"message",role:"assistant",...s.id&&!e&&s.id.startsWith("msg_")?{id:s.id}:{},content:he(()=>typeof h=="string"?h:h.flatMap(_=>{if(_.type==="text"){let v=_;return{type:"output_text",text:v.text,annotations:(v.annotations??[]).map(Sp)}}return _.type==="output_text"||_.type==="refusal"?_:[]})),phase:he(()=>{if(Array.isArray(h))return h.find(_=>"phase"in _&&typeof _.phase=="string")?.phase})};a.push(x)}let f=o?.[Nn],g=o?.[zn];ae.isInstance(s)&&s.tool_calls?.length?a.push(...s.tool_calls.map(x=>su(x,g)?{type:"custom_tool_call",id:"call_id"in x&&typeof x.call_id=="string"?x.call_id:g?.[x.id??""]??"",call_id:x.id??"",input:x.args.input,name:x.name}:ru(x)?{type:"computer_call",id:x.call_id,call_id:x.id??"",action:x.args.action}:{type:"function_call",name:x.name,arguments:JSON.stringify(x.args),call_id:x.id,...e?{}:{id:f?.[x.id]}})):o?.tool_calls&&a.push(...o.tool_calls.map(x=>({type:"function_call",name:x.function.name,call_id:x.id,arguments:x.function.arguments,...e?{}:{id:f?.[x.id]}})));let y=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(y!=null){let x=y?.filter(_=>I.includes(_.type));x.length>0&&a.push(...x)}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}),Ls(u)){if(u.type==="file"){let h=On(u);if(u.source_type==="url")return{type:"input_file",file_url:u.url,...h?{filename:h}:{}};if(u.source_type==="id")return{type:"input_file",file_id:u.id,...h?{filename:h}:{}};if(u.source_type==="base64")return{type:"input_file",file_data:`data:${u.mime_type??""};base64,${u.data}`,filename:$t(u)}}return Ks(u,zs)}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*Zo(t,e={}){let r=e.streamUsage??!0,s=e.provider??"openai",n=new Map,o=new Map,i=0,a=!1,c,u,h,f,g=new Set,y=(_,v)=>{let p=o.get(_);if(p!==void 0)return{index:p,isNew:!1};let A=i++;return o.set(_,A),n.set(A,{...v}),{index:A,isNew:!0}},I=function*(){a||(a=!0,yield{event:"message-start",id:c})},x=function*(_){if(g.has(_))return;let v=n.get(_);v&&(g.add(_),yield{event:"content-block-finish",index:_,content:bi(v)})};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:v,isNew:p}=y(`text:${_.output_index}:${_.content_index}`,{type:"text",text:""});p&&(yield{event:"content-block-start",index:v,content:{type:"text",text:""}});let A=n.get(v);A.text=(A.text??"")+_.delta,yield{event:"content-block-delta",index:v,delta:{type:"text-delta",text:_.delta}};continue}if(_.type==="response.reasoning_summary_text.delta"){yield*I();let{index:v,isNew:p}=y(`reasoning:${_.output_index}:${_.summary_index}`,{type:"reasoning",reasoning:""});p&&(yield{event:"content-block-start",index:v,content:{type:"reasoning",reasoning:""}});let A=n.get(v);A.reasoning=(A.reasoning??"")+_.delta,yield{event:"content-block-delta",index:v,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 v=`tool:${_.output_index}`,p=_.item.type==="custom_tool_call",A=_.item.type==="function_call"?_.item.arguments??"":_.item.input??"",{index:O,isNew:z}=y(v,{type:"tool_call_chunk",id:_.item.call_id,name:_.item.name,args:A,index:_.output_index,...p?{isCustomTool:!0}:{}});if(z&&(yield{event:"content-block-start",index:O,content:{type:"tool_call_chunk",id:_.item.call_id,name:_.item.name,args:A,index:_.output_index}}),A){let N=n.get(O);yield{event:"content-block-delta",index:O,delta:{type:"block-delta",fields:{type:"tool_call_chunk",...N.id!=null?{id:N.id}:{},...N.name!=null?{name:N.name}:{},args:N.args}}}}continue}if(_.type==="response.function_call_arguments.delta"||_.type==="response.custom_tool_call_input.delta"){yield*I();let{index:v,isNew:p}=y(`tool:${_.output_index}`,{type:"tool_call_chunk",args:"",index:_.output_index,..._.type==="response.custom_tool_call_input.delta"?{isCustomTool:!0}:{}});p&&(yield{event:"content-block-start",index:v,content:{type:"tool_call_chunk",args:"",index:_.output_index}});let A=n.get(v);A.args=(A.args??"")+_.delta,yield{event:"content-block-delta",index:v,delta:{type:"block-delta",fields:{type:"tool_call_chunk",...A.id!=null?{id:A.id}:{},...A.name!=null?{name:A.name}:{},args:A.args}}};continue}if(_.type==="response.output_item.done"&&(_.item.type==="function_call"||_.item.type==="custom_tool_call")){yield*I();let v=`tool:${_.output_index}`,p=_.item.type==="function_call"?_.item.arguments??"":_.item.input??"",{index:A,isNew:O}=y(v,{type:"tool_call_chunk",id:_.item.call_id,name:_.item.name,args:p,index:_.output_index});if(O)yield{event:"content-block-start",index:A,content:{type:"tool_call_chunk",id:_.item.call_id,name:_.item.name,args:p,index:_.output_index}};else{let z=n.get(A);z.args=p,z.id=_.item.call_id,z.name=_.item.name}yield*x(A);continue}if(_.type==="response.completed"||_.type==="response.incomplete"){yield*I(),c=_.response.id,h=$p(_.response.status,_.type),f={model_provider:s,id:_.response.id,model:_.response.model,status:_.response.status},r&&_.response.usage&&(u=ns(_.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*x(_));yield{event:"message-finish",reason:h,...u?{usage:u}:{},...f?{responseMetadata:f}:{}}}function $p(t,e){return e==="response.incomplete"?"length":t==="completed"?"stop":t==="incomplete"?"length":"stop"}var jn=class extends Ut{constructor(t,e){super(ss(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:Qa(t?.tool_choice)?t?.tool_choice:(()=>{let n=vn(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:os({messages:t,zdrEnabled:this.zdrEnabled??!1,model:this.model}),...s,stream:!1},{signal:e?.signal,maxRetries:e?.maxRetries,...e?.options});return{generations:[{text:n.output_text,message:Us(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:os({messages:t,zdrEnabled:this.zdrEnabled??!1,model:this.model}),stream:!0},e),n=this.streamUsage??e.streamUsage;yield*Zo(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:os({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=Un(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){let{maxRetries:r,...s}=e??{},n=this._getClientOptions(s);return this.caller.callWithOptions({maxRetries:r},async()=>{try{return t.text?.format?.type==="json_schema"&&!t.stream?await this.client.responses.parse(t,n):await this.client.responses.create(t,n)}catch(o){throw ce(o)}})}_reduceChatOpenAITools(t,e){let r=[];for(let s of t)if(rs(s))s.type==="image_generation"&&e?.stream&&(s.partial_images=1),r.push(s);else if(Mt(s)){let n=s.metadata.customTool;r.push({type:"custom",name:n.name,description:n.description,format:n.format})}else if(Ws(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 Tn(s)&&r.push(nu(s));return r}};var Dn=class tl extends Ut{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=ss(e,r);super(s),this.fields=s,this.useResponsesApi=s?.useResponsesApi??!1,this.responses=s?.responses??new jn(s),this.completions=s?.completions??new Mn(s)}_useResponsesApi(e){let r=e?.tools?.some(rs),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(Tn)||e?.tools?.some(Mt);return this.useResponsesApi||r||s||n||Ha(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 tl(this.fields);return r.defaultOptions={...this.defaultOptions,...e},r}};var Ln=class extends gi{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??re("OPENAI_API_KEY");this.organization=e?.configuration?.organization??re("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=Gn(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=Ue({baseURL:this.clientConfig.baseURL}),s={...this.clientConfig,baseURL:r,timeout:this.timeout,maxRetries:0};s.baseURL||delete s.baseURL,s.defaultHeaders=je(s.defaultHeaders),this.client=new T(s)}let e={};return this.caller.call(async()=>{try{return await this.client.embeddings.create(t,e)}catch(r){throw ce(r)}})}};var Up=b.object({type:b.literal("screenshot")}),jp=b.object({type:b.literal("click"),x:b.number(),y:b.number(),button:b.enum(["left","right","wheel","back","forward"]).default("left")}),Dp=b.object({type:b.literal("double_click"),x:b.number(),y:b.number(),button:b.enum(["left","right","wheel","back","forward"]).default("left")}),Lp=b.object({type:b.literal("drag"),path:b.array(b.object({x:b.number(),y:b.number()}))}),Kp=b.object({type:b.literal("keypress"),keys:b.array(b.string())}),Fp=b.object({type:b.literal("move"),x:b.number(),y:b.number()}),Bp=b.object({type:b.literal("scroll"),x:b.number(),y:b.number(),scroll_x:b.number(),scroll_y:b.number()}),qp=b.object({type:b.literal("type"),text:b.string()}),Wp=b.object({type:b.literal("wait"),duration:b.number().optional()}),Hp=b.union([Up,jp,Dp,Lp,Kp,Fp,Bp,qp,Wp]),aT=b.object({action:Hp});var Zp=b.object({type:b.literal("exec"),command:b.array(b.string()),env:b.record(b.string(),b.string()).optional(),working_directory:b.string().optional(),timeout_ms:b.number().optional(),user:b.string().optional()}),pT=b.union([Zp]);var hT=b.object({commands:b.array(b.string()).describe("Array of shell commands to execute"),timeout_ms:b.number().optional().describe("Optional timeout in milliseconds for the commands"),max_output_length:b.number().optional().describe("Optional maximum number of characters to return from each command")});var Vp=b.object({type:b.literal("create_file"),path:b.string(),diff:b.string()}),Jp=b.object({type:b.literal("update_file"),path:b.string(),diff:b.string()}),Gp=b.object({type:b.literal("delete_file"),path:b.string()}),AT=b.union([Vp,Jp,Gp]);var il={advanced:"gpt-5.6-sol",default:"gpt-5.6-terra",fast:"gpt-5.6-luna"},Xo={default:"text-embedding-ada-002"},Jo=new Map,Kn=null,em=()=>{let t=nl.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},al=async t=>{let e=em();Jo.size===0&&(Kn||(Kn=(async()=>{try{(await ol(`${e}/models`)).data.models.forEach(s=>Jo.set(s.name,s))}catch(s){throw Kn=null,s}})()),await Kn);let r=Jo.get(t);if(!r)throw new Error(`Model '${t}' is not available in the discovery service.`);return r.endpoint},tm=async(t="default")=>await al(il[t]),rm=async(t="default")=>await al(Xo[t]),ZC=ke.Root({agentExecutionContext:ke({default:Ti,reducer:ki}),currentIntent:ke({default:()=>"none",reducer:us}),routing:ke({default:()=>({mode:"auto"}),reducer:us}),lastExecutedAgent:ke({default:()=>"",reducer:us}),requiresFollowUp:ke({default:()=>!0,reducer:us}),stepCount:ke({default:()=>0,reducer:(t,e)=>e??t+1}),finalOutputMessage:ke({default:()=>"",reducer:vi})}),sm=t=>{if(!t||typeof t!="object"||!("services"in t))return!1;let e=t.services;return!!e&&typeof e=="object"&&"agentRegistry"in e},nm=t=>{let e=t?.configurable;return sm(e)?e:void 0},om=(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.":""))))})},Yo=async t=>(await om(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,im=async t=>{let{agent:e,messages:r,config:s}=t;return{structuredResponse:(await e.invoke({messages:r},s)).structuredResponse}},am=t=>typeof t=="string"&&t.length>0?t:void 0,um=()=>ri(),lm=t=>typeof t!="string"||t.trim().length===0?"MapsSDK":`MapsSDK - ${t.trim()}`,cm=t=>{let e=t?.configurable;return{conversationId:am(e?.thread_id),abortSignal:t?.signal,requestId:um(),requestSource:lm(Qp.applicationName)}},pm=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)}`)},ul=async({config:t})=>{let e=nl.getDefault(),r=(await Yp.getCredential(`${e.url}/sharing`))?.token;return async(s,n)=>{let{conversationId:o,abortSignal:i,requestId:a,requestSource:c}=cm(t),u=new Headers(n?.headers);for(let f of[...u.keys()]){let g=f.toLowerCase();(g==="authorization"||g==="api-key"||g.startsWith("x-stainless-"))&&u.delete(f)}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 h=i&&n?.signal?AbortSignal.any([i,n.signal]):n?.signal??i;return(await ol(s instanceof Request?s.url:s.toString(),{body:pm(n?.body),headers:Object.fromEntries(u),responseType:"native",signal:h})).data}},Ds=async(t={})=>{let{modelTier:e="default",config:r}=t,s=il[e],n=await tm(e);return new Dn({modelName:s,apiKey:"dummy-key",configuration:{baseURL:n,fetch:await ul({config:r})}})},VC=async(t={})=>{let{tier:e="default",config:r}=t,s=Xo[e],n=await rm(e);return new Ln({modelName:s,apiKey:"dummy-key",configuration:{baseURL:n,fetch:await ul({config:r})},batchSize:2048,maxConcurrency:10})},mm=b.object({id:b.string().min(1),name:b.string().min(1),description:b.string().min(1)});b.array(mm);var rl=t=>JSON.stringify(t,null,2),dm=t=>{let e=t.map(s=>s.id),r=b.enum(e);return b.object({intent:r.nullable(),assignedTask:b.string().nullable(),requiresFollowUp:b.boolean()})},JC=async(t,e)=>{let r=nm(e);if(e?.signal?.aborted)return await st({text:"Run cancelled; skipping intent routing"},e),{...t,currentIntent:"none",finalOutputMessage:"Operation cancelled.",requiresFollowUp:!1};try{await st({text:"Asking LLM to route to an agent"},e);let s=r.services.agentRegistry?.list()??[],n=s.map(({agent:x})=>({id:x.id,name:x.name,description:x.description}));if(!n.length)return await st({text:"No agents registered; skipping intent detection"},e),{...t,currentIntent:"none",finalOutputMessage:"No agents registered; skipping intent detection."};let o=await Yo("intent_prompt"),i=rl(n),a=dm(n),c={registeredAgents:i,priorSteps:rl(t.agentExecutionContext.priorSteps),userRequest:t.agentExecutionContext.userRequest},u=await Jn.fromTemplate(o).format(c),h=Ci({model:await Ds({modelTier:"fast",config:e}),tools:[],systemPrompt:u,responseFormat:a,middleware:[Ri({model:await Ds({modelTier:"fast",config:e}),trigger:{tokens:4e3},keep:{messages:6}}),Ei({runLimit:2})]}),{structuredResponse:f}=await im({agent:h,messages:t.agentExecutionContext.messages,config:e}),g=a.parse(f??{intent:null,assignedTask:null,requiresFollowUp:!1}),y=g.intent??"none",I={...t,currentIntent:y,requiresFollowUp:g.requiresFollowUp,agentExecutionContext:{...t.agentExecutionContext,assignedTask:g.assignedTask??""}};if(y==="none"){let x=`I could not find an agent that can handle that request. I have access to the following agents: ${s.map(({agent:_})=>_.name).join(", ")}.
|
|
36
|
+
|
|
37
|
+
Please ask a question that can be answered by one of these agents.`;return await st({text:"LLM did not identify a clear intent."},e),{...t,currentIntent:y,requiresFollowUp:!1,finalOutputMessage:x,agentExecutionContext:{...t.agentExecutionContext,assignedTask:"",messages:[...t.agentExecutionContext.messages,new ae(x)],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 st({text:`Agent picked: ${y}
|
|
38
|
+
Task Assigned: ${g.assignedTask??""}
|
|
39
|
+
Requires Follow-Up: ${g.requiresFollowUp}`},e),I}catch(s){throw await st({text:"Error during intent detection"},e),new Error(`Error during intent detection: ${s instanceof Error?s.message:String(s)}`)}},fm="0.1",js=1536,hm="openai",_m=Xo.default,gm=`Name: {name}
|
|
40
|
+
Title: {title}
|
|
41
|
+
Description: {description}`,ym=`Name: {name}
|
|
42
|
+
Alias: {alias}
|
|
43
|
+
Description: {description}`,GC=b.object({schemaVersion:b.literal(fm),modified:b.number().int().nonnegative(),embeddings:b.object({modelProvider:b.literal(hm),model:b.literal(_m),dimensions:b.literal(js),templates:b.object({layer:b.string().default(gm),field:b.string().default(ym)})}),layers:b.array(b.object({id:b.string().min(1),name:b.string().min(1),title:b.string().catch(""),description:b.string().catch(""),vector:b.array(b.number()).length(js,{message:`Layer vector must be exactly ${js} dimensions`}),fields:b.array(b.object({name:b.string().min(1),alias:b.string().catch(""),description:b.string().catch(""),vector:b.array(b.number()).length(js,{message:`Field vector must be exactly ${js} dimensions`})}))})).default([])}),Am=t=>{let e=new Set;for(let r of t)if(Bs(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(ii(r)){let s=r;return e.has(s.tool_call_id)}return!0})},Qo=(t,e)=>{let r=wi.fromTemplate(t);return Jn.fromMessages([r,...e])},Im=async t=>{let{promptText:e,modelTier:r,messages:s,config:n}=t,o=Qo(e,s??[]),i=await Ds({modelTier:r,config:n});return o.pipe(i)},XC=async t=>{let{promptText:e,modelTier:r="default",messages:s,inputVariables:n,config:o}=t,i=await(await Im({promptText:e,modelTier:r,messages:s,config:o})).invoke(n??{},o);if(typeof i=="string")return i;let a=i.content;return typeof a=="string"?a:JSON.stringify(a)},ll=async t=>{let{promptText:e,modelTier:r="default",messages:s,inputVariables:n,schema:o,config:i}=t,a=Qo(e,s??[]),c=(await Ds({modelTier:r,config:i})).withStructuredOutput(o);return await a.pipe(c).invoke(n??{},i)},YC=async t=>{let{promptText:e,modelTier:r="default",messages:s,inputVariables:n,tools:o,config:i}=t,a=o.length>0?Am(s??[]):s??[],c=Qo(e,a),u=await Ds({modelTier:r,config:i});return await c.pipe(u.bindTools(o)).invoke(n??{},i)},bm=ue.object({name:ue.string(),description:ue.string(),valueType:ue.string(),alias:ue.string()}),xm=ue.object({fields:ue.array(bm)}),cl=(t,e)=>t.getFieldAlias(e)??void 0,Go=(t,e)=>cl(t,e.name)??e.alias??"",wm=(t,e)=>{let r=cl(t,e.name);return!!(r&&r!==(e.alias??""))};function sl(t,e){let r=new Map;for(let s of t.fields){let n=e.fields.find(c=>c.name===s.name),o=Go(t,s),i=wm(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 QC=async t=>{let e=await Yo("field_descriptions_prompt"),r=t.fields.filter(o=>!(Go(t,o)&&o.description)).map(o=>{let{name:i,type:a,description:c}=o,u=Go(t,o);return[`Name: ${i}`,`Type: ${a}`,`Alias: ${u}`,`Description: ${c??"N/A"}`].join(", ")}).join(`
|
|
44
|
+
`);if(r.length===0)return sl(t,{fields:[]});let s={existingItemTitle:t.portalItem?.title,existingItemDescription:t.portalItem?.description,existingLayerTitle:t.title,existingLayerDescription:t.portalItem?.description,fieldInformation:r},n=await ll({promptText:e,schema:xm,inputVariables:s});return sl(t,n)},Pm=ue.object({title:ue.string(),description:ue.string(),name:ue.string().nullable()}),eR=async(t,e)=>{let r=await Yo("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 ll({promptText:r,schema:Pm,inputVariables:n}),name:t.title??null}};return{a:rm,b:ZC,c:nm,d:Ds,e:VC,f:JC,g:fm,h:js,i:hm,j:_m,k:gm,l:ym,m:GC,n:XC,o:ll,p:YC,q:QC,r:eR}},"portal/Portal","request","identity/IdentityManager","config")
|