@mcp-use/inspector 0.13.2 → 0.14.0-canary.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/dist/cli.js +7 -53
  2. package/dist/client/assets/base-Aouj1Yhj.js +2 -0
  3. package/dist/client/assets/{index-CR9w_74S.js → base-ZEkF4ver.js} +33 -36
  4. package/dist/client/assets/browser-BWolhM7l.js +12 -0
  5. package/dist/client/assets/embeddings-BTUgP3x_.js +1 -0
  6. package/dist/client/assets/{index-BYR-I2bf.js → index-BOIA9kd1.js} +2 -2
  7. package/dist/client/assets/{index-sQyTG4jp.js → index-BSuQO5pd.js} +3 -3
  8. package/dist/client/assets/index-Bfe1ynAS.js +4 -0
  9. package/dist/client/assets/{index-ClpBZU-N.js → index-C88Q8iJs.js} +1 -1
  10. package/dist/client/assets/index-CNfmoBX-.js +1701 -0
  11. package/dist/client/assets/index-CSZqqrHs.js +34 -0
  12. package/dist/client/assets/index-CtWrgdCi.js +7 -0
  13. package/dist/client/assets/index-DIlJ2WcE.js +70 -0
  14. package/dist/client/assets/index-cMXsdFDY.css +1 -0
  15. package/dist/client/index.html +3 -3
  16. package/dist/server/{chunk-XGILHZOF.js → chunk-F7YWZTWJ.js} +4 -48
  17. package/dist/server/{chunk-JEKCWLHD.js → chunk-Y4GX3FDV.js} +1 -1
  18. package/dist/server/{chunk-MCMZDGO6.js → chunk-Z5QIR3IS.js} +2 -2
  19. package/dist/server/cli.js +2 -2
  20. package/dist/server/index.js +3 -3
  21. package/dist/server/middleware.js +3 -3
  22. package/dist/server/server.d.ts.map +1 -1
  23. package/dist/server/server.js +28 -5
  24. package/dist/server/shared-routes.d.ts.map +1 -1
  25. package/dist/server/shared-routes.js +2 -2
  26. package/dist/server/shared-utils-browser.d.ts.map +1 -1
  27. package/dist/server/shared-utils-browser.js +1 -1
  28. package/package.json +2 -2
  29. package/dist/client/assets/browser-DZ15LLaB.js +0 -501
  30. package/dist/client/assets/display-A5IEINAP-HkQbiJ2E.js +0 -17
  31. package/dist/client/assets/embeddings-C0rUXJ5F.js +0 -1
  32. package/dist/client/assets/fs-u42MReIY.js +0 -1
  33. package/dist/client/assets/index-B5kLR_Rv.js +0 -33
  34. package/dist/client/assets/index-CkHH_UI9.js +0 -1676
  35. package/dist/client/assets/index-DQ7i0BFM.css +0 -1
  36. package/dist/client/assets/index-DRz5BQNA.js +0 -1
  37. package/dist/client/assets/index-DiwCBW8I.js +0 -7
  38. package/dist/client/assets/index-Dj6Mccu_.js +0 -20
  39. package/dist/client/assets/index-JiKw9JSs.js +0 -5
  40. package/dist/client/assets/index-Zctd0Z8B.js +0 -71
  41. package/dist/client/assets/llms-BDMth6TQ.js +0 -2
  42. package/dist/client/assets/path-BOQPmbms.js +0 -1
  43. package/dist/client/assets/path-MNZaYwxc.js +0 -1
  44. package/dist/client/assets/posthog-node-CuYhrq1Q.js +0 -1
  45. package/dist/client/assets/util-t-trnxQI.js +0 -1
  46. package/dist/client/assets/winston-CEUa9Wj-.js +0 -37
@@ -0,0 +1,34 @@
1
+ import"./index-Bfe1ynAS.js";import{x as js,bj as Da,bk as I,aC as Fa,aB as Ba,aq as Re,as as Wa,ab as Us,bi as qa,_ as Ds,at as Hn,i as Qe,aV as Ja,R as za,au as Ka,a5 as Fs,af as Bs,E as Ce,l as Ws,H as Za,D as wn,S as Vn,F as Ha,z as Va,w as Xa,J as Xn,I as Gn,ac as Ga,ar as en,C as Jt,be as Qa,b0 as Ya,a$ as ei,b1 as Qn}from"./base-ZEkF4ver.js";import{c as ti,O as qs,b as ni,a as si,S as Yn,J as es,R as ts}from"./index-DIlJ2WcE.js";import{c as ri,d as Js,e as ai}from"./base-Aouj1Yhj.js";import{h as ii,i as oi,o as z,l as ee,_ as zs,n as J,b as Pt,s as Q,e as bn,j as ui}from"./index-CNfmoBX-.js";import"./embeddings-BTUgP3x_.js";import"./index-CtWrgdCi.js";function Ye(t,e){return t.lc_error_code=e,t.message=`${t.message}
2
+
3
+ Troubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${e}/
4
+ `,t}function x(t,e,n,s,r){if(typeof e=="function"?t!==e||!0:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(t,n),n}function p(t,e,n,s){if(n==="a"&&!s)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!s:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return n==="m"?s:n==="a"?s.call(t):s?s.value:e.get(t)}let Ks=function(){const{crypto:t}=globalThis;if(t?.randomUUID)return Ks=t.randomUUID.bind(t),t.randomUUID();const e=new Uint8Array(1),n=t?()=>t.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,s=>(+s^n()&15>>+s/4).toString(16))};function tn(t){return typeof t=="object"&&t!==null&&("name"in t&&t.name==="AbortError"||"message"in t&&String(t.message).includes("FetchRequestCanceledException"))}const nn=t=>{if(t instanceof Error)return t;if(typeof t=="object"&&t!==null){try{if(Object.prototype.toString.call(t)==="[object Error]"){const e=new Error(t.message,t.cause?{cause:t.cause}:{});return t.stack&&(e.stack=t.stack),t.cause&&!e.cause&&(e.cause=t.cause),t.name&&(e.name=t.name),e}}catch{}try{return new Error(JSON.stringify(t))}catch{}}return new Error(t)};class O extends Error{}class q extends O{constructor(e,n,s,r){super(`${q.makeMessage(e,n,s)}`),this.status=e,this.headers=r,this.requestID=r?.get("x-request-id"),this.error=n;const a=n;this.code=a?.code,this.param=a?.param,this.type=a?.type}static makeMessage(e,n,s){const r=n?.message?typeof n.message=="string"?n.message:JSON.stringify(n.message):n?JSON.stringify(n):s;return e&&r?`${e} ${r}`:e?`${e} status code (no body)`:r||"(no status code or body)"}static generate(e,n,s,r){if(!e||!r)return new Rt({message:s,cause:nn(n)});const a=n?.error;return e===400?new Zs(e,a,s,r):e===401?new Hs(e,a,s,r):e===403?new Vs(e,a,s,r):e===404?new Xs(e,a,s,r):e===409?new Gs(e,a,s,r):e===422?new Qs(e,a,s,r):e===429?new Ys(e,a,s,r):e>=500?new er(e,a,s,r):new q(e,a,s,r)}}class Y extends q{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class Rt extends q{constructor({message:e,cause:n}){super(void 0,void 0,e||"Connection error.",void 0),n&&(this.cause=n)}}class $t extends Rt{constructor({message:e}={}){super({message:e??"Request timed out."})}}class Zs extends q{}class Hs extends q{}class Vs extends q{}class Xs extends q{}class Gs extends q{}class Qs extends q{}class Ys extends q{}class er extends q{}class tr extends O{constructor(){super("Could not parse response content as the length limit was reached")}}class nr extends O{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}class $e extends Error{constructor(e){super(e)}}const li=/^[a-z][a-z0-9+.-]*:/i,ci=t=>li.test(t);let H=t=>(H=Array.isArray,H(t)),ns=H;function sr(t){return typeof t!="object"?{}:t??{}}function di(t){if(!t)return!0;for(const e in t)return!1;return!0}function pi(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function zt(t){return t!=null&&typeof t=="object"&&!Array.isArray(t)}const fi=(t,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new O(`${t} must be an integer`);if(e<0)throw new O(`${t} must be a positive integer`);return e},hi=t=>{try{return JSON.parse(t)}catch{return}},Ze=t=>new Promise(e=>setTimeout(e,t)),xe="6.10.0",mi=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function gi(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}const _i=()=>{const t=gi();if(t==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":xe,"X-Stainless-OS":rs(Deno.build.os),"X-Stainless-Arch":ss(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":xe,"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":xe,"X-Stainless-OS":rs(globalThis.process.platform??"unknown"),"X-Stainless-Arch":ss(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};const e=yi();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":xe,"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":xe,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function yi(){if(typeof navigator>"u"||!navigator)return null;const t=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(const{key:e,pattern:n}of t){const s=n.exec(navigator.userAgent);if(s){const r=s[1]||0,a=s[2]||0,i=s[3]||0;return{browser:e,version:`${r}.${a}.${i}`}}}return null}const ss=t=>t==="x32"?"x32":t==="x86_64"||t==="x64"?"x64":t==="arm"?"arm":t==="aarch64"||t==="arm64"?"arm64":t?`other:${t}`:"unknown",rs=t=>(t=t.toLowerCase(),t.includes("ios")?"iOS":t==="android"?"Android":t==="darwin"?"MacOS":t==="win32"?"Windows":t==="freebsd"?"FreeBSD":t==="openbsd"?"OpenBSD":t==="linux"?"Linux":t?`Other:${t}`:"Unknown");let as;const wi=()=>as??(as=_i());function bi(){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 rr(...t){const e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...t)}function ar(t){let e=Symbol.asyncIterator in t?t[Symbol.asyncIterator]():t[Symbol.iterator]();return rr({start(){},async pull(n){const{done:s,value:r}=await e.next();s?n.close():n.enqueue(r)},async cancel(){await e.return?.()}})}function ir(t){if(t[Symbol.asyncIterator])return t;const e=t.getReader();return{async next(){try{const n=await e.read();return n?.done&&e.releaseLock(),n}catch(n){throw e.releaseLock(),n}},async return(){const n=e.cancel();return e.releaseLock(),await n,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function vi(t){if(t===null||typeof t!="object")return;if(t[Symbol.asyncIterator]){await t[Symbol.asyncIterator]().return?.();return}const e=t.getReader(),n=e.cancel();e.releaseLock(),await n}const Oi=({headers:t,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)}),or="RFC3986",ur=t=>String(t),is={RFC1738:t=>String(t).replace(/%20/g,"+"),RFC3986:ur},xi="RFC1738";let sn=(t,e)=>(sn=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),sn(t,e));const re=(()=>{const t=[];for(let e=0;e<256;++e)t.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return t})(),Kt=1024,ki=(t,e,n,s,r)=>{if(t.length===0)return t;let a=t;if(typeof t=="symbol"?a=Symbol.prototype.toString.call(t):typeof t!="string"&&(a=String(t)),n==="iso-8859-1")return escape(a).replace(/%u[0-9a-f]{4}/gi,function(o){return"%26%23"+parseInt(o.slice(2),16)+"%3B"});let i="";for(let o=0;o<a.length;o+=Kt){const l=a.length>=Kt?a.slice(o,o+Kt):a,u=[];for(let h=0;h<l.length;++h){let c=l.charCodeAt(h);if(c===45||c===46||c===95||c===126||c>=48&&c<=57||c>=65&&c<=90||c>=97&&c<=122||r===xi&&(c===40||c===41)){u[u.length]=l.charAt(h);continue}if(c<128){u[u.length]=re[c];continue}if(c<2048){u[u.length]=re[192|c>>6]+re[128|c&63];continue}if(c<55296||c>=57344){u[u.length]=re[224|c>>12]+re[128|c>>6&63]+re[128|c&63];continue}h+=1,c=65536+((c&1023)<<10|l.charCodeAt(h)&1023),u[u.length]=re[240|c>>18]+re[128|c>>12&63]+re[128|c>>6&63]+re[128|c&63]}i+=u.join("")}return i};function Ii(t){return!t||typeof t!="object"?!1:!!(t.constructor&&t.constructor.isBuffer&&t.constructor.isBuffer(t))}function os(t,e){if(H(t)){const n=[];for(let s=0;s<t.length;s+=1)n.push(e(t[s]));return n}return e(t)}const lr={brackets(t){return String(t)+"[]"},comma:"comma",indices(t,e){return String(t)+"["+e+"]"},repeat(t){return String(t)}},cr=function(t,e){Array.prototype.push.apply(t,H(e)?e:[e])};let us;const L={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:ki,encodeValuesOnly:!1,format:or,formatter:ur,indices:!1,serializeDate(t){return(us??(us=Function.prototype.call.bind(Date.prototype.toISOString)))(t)},skipNulls:!1,strictNullHandling:!1};function Si(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"||typeof t=="symbol"||typeof t=="bigint"}const Zt={};function dr(t,e,n,s,r,a,i,o,l,u,h,c,f,d,w,y,C,m){let g=t,k=m,A=0,K=!1;for(;(k=k.get(Zt))!==void 0&&!K;){const $=k.get(t);if(A+=1,typeof $<"u"){if($===A)throw new RangeError("Cyclic object value");K=!0}typeof k.get(Zt)>"u"&&(A=0)}if(typeof u=="function"?g=u(e,g):g instanceof Date?g=f?.(g):n==="comma"&&H(g)&&(g=os(g,function($){return $ instanceof Date?f?.($):$})),g===null){if(a)return l&&!y?l(e,L.encoder,C,"key",d):e;g=""}if(Si(g)||Ii(g)){if(l){const $=y?e:l(e,L.encoder,C,"key",d);return[w?.($)+"="+w?.(l(g,L.encoder,C,"value",d))]}return[w?.(e)+"="+w?.(String(g))]}const j=[];if(typeof g>"u")return j;let R;if(n==="comma"&&H(g))y&&l&&(g=os(g,l)),R=[{value:g.length>0?g.join(",")||null:void 0}];else if(H(u))R=u;else{const $=Object.keys(g);R=h?$.sort(h):$}const F=o?String(e).replace(/\./g,"%2E"):String(e),U=s&&H(g)&&g.length===1?F+"[]":F;if(r&&H(g)&&g.length===0)return U+"[]";for(let $=0;$<R.length;++$){const M=R[$],Kn=typeof M=="object"&&typeof M.value<"u"?M.value:g[M];if(i&&Kn===null)continue;const qt=c&&o?M.replace(/\./g,"%2E"):M,Ua=H(g)?typeof n=="function"?n(U,qt):U:U+(c?"."+qt:"["+qt+"]");m.set(t,A);const Zn=new WeakMap;Zn.set(Zt,m),cr(j,dr(Kn,Ua,n,s,r,a,i,o,n==="comma"&&y&&H(g)?null:l,u,h,c,f,d,w,y,C,Zn))}return j}function Ci(t=L){if(typeof t.allowEmptyArrays<"u"&&typeof t.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof t.encodeDotInKeys<"u"&&typeof t.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(t.encoder!==null&&typeof t.encoder<"u"&&typeof t.encoder!="function")throw new TypeError("Encoder has to be a function.");const e=t.charset||L.charset;if(typeof t.charset<"u"&&t.charset!=="utf-8"&&t.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let n=or;if(typeof t.format<"u"){if(!sn(is,t.format))throw new TypeError("Unknown format option provided.");n=t.format}const s=is[n];let r=L.filter;(typeof t.filter=="function"||H(t.filter))&&(r=t.filter);let a;if(t.arrayFormat&&t.arrayFormat in lr?a=t.arrayFormat:"indices"in t?a=t.indices?"indices":"repeat":a=L.arrayFormat,"commaRoundTrip"in t&&typeof t.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");const i=typeof t.allowDots>"u"?t.encodeDotInKeys?!0:L.allowDots:!!t.allowDots;return{addQueryPrefix:typeof t.addQueryPrefix=="boolean"?t.addQueryPrefix:L.addQueryPrefix,allowDots:i,allowEmptyArrays:typeof t.allowEmptyArrays=="boolean"?!!t.allowEmptyArrays:L.allowEmptyArrays,arrayFormat:a,charset:e,charsetSentinel:typeof t.charsetSentinel=="boolean"?t.charsetSentinel:L.charsetSentinel,commaRoundTrip:!!t.commaRoundTrip,delimiter:typeof t.delimiter>"u"?L.delimiter:t.delimiter,encode:typeof t.encode=="boolean"?t.encode:L.encode,encodeDotInKeys:typeof t.encodeDotInKeys=="boolean"?t.encodeDotInKeys:L.encodeDotInKeys,encoder:typeof t.encoder=="function"?t.encoder:L.encoder,encodeValuesOnly:typeof t.encodeValuesOnly=="boolean"?t.encodeValuesOnly:L.encodeValuesOnly,filter:r,format:n,formatter:s,serializeDate:typeof t.serializeDate=="function"?t.serializeDate:L.serializeDate,skipNulls:typeof t.skipNulls=="boolean"?t.skipNulls:L.skipNulls,sort:typeof t.sort=="function"?t.sort:null,strictNullHandling:typeof t.strictNullHandling=="boolean"?t.strictNullHandling:L.strictNullHandling}}function Ti(t,e={}){let n=t;const s=Ci(e);let r,a;typeof s.filter=="function"?(a=s.filter,n=a("",n)):H(s.filter)&&(a=s.filter,r=a);const i=[];if(typeof n!="object"||n===null)return"";const o=lr[s.arrayFormat],l=o==="comma"&&s.commaRoundTrip;r||(r=Object.keys(n)),s.sort&&r.sort(s.sort);const u=new WeakMap;for(let f=0;f<r.length;++f){const d=r[f];s.skipNulls&&n[d]===null||cr(i,dr(n[d],d,o,l,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))}const h=i.join(s.delimiter);let c=s.addQueryPrefix===!0?"?":"";return s.charsetSentinel&&(s.charset==="iso-8859-1"?c+="utf8=%26%2310003%3B&":c+="utf8=%E2%9C%93&"),h.length>0?c+h:""}function Ai(t){let e=0;for(const r of t)e+=r.length;const n=new Uint8Array(e);let s=0;for(const r of t)n.set(r,s),s+=r.length;return n}let ls;function vn(t){let e;return(ls??(e=new globalThis.TextEncoder,ls=e.encode.bind(e)))(t)}let cs;function ds(t){let e;return(cs??(e=new globalThis.TextDecoder,cs=e.decode.bind(e)))(t)}var V,X;class Et{constructor(){V.set(this,void 0),X.set(this,void 0),x(this,V,new Uint8Array),x(this,X,null)}decode(e){if(e==null)return[];const n=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?vn(e):e;x(this,V,Ai([p(this,V,"f"),n]));const s=[];let r;for(;(r=Pi(p(this,V,"f"),p(this,X,"f")))!=null;){if(r.carriage&&p(this,X,"f")==null){x(this,X,r.index);continue}if(p(this,X,"f")!=null&&(r.index!==p(this,X,"f")+1||r.carriage)){s.push(ds(p(this,V,"f").subarray(0,p(this,X,"f")-1))),x(this,V,p(this,V,"f").subarray(p(this,X,"f"))),x(this,X,null);continue}const a=p(this,X,"f")!==null?r.preceding-1:r.preceding,i=ds(p(this,V,"f").subarray(0,a));s.push(i),x(this,V,p(this,V,"f").subarray(r.index)),x(this,X,null)}return s}flush(){return p(this,V,"f").length?this.decode(`
5
+ `):[]}}V=new WeakMap,X=new WeakMap;Et.NEWLINE_CHARS=new Set([`
6
+ `,"\r"]);Et.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function Pi(t,e){for(let r=e??0;r<t.length;r++){if(t[r]===10)return{preceding:r,index:r+1,carriage:!1};if(t[r]===13)return{preceding:r,index:r+1,carriage:!0}}return null}function Ri(t){for(let s=0;s<t.length-1;s++){if(t[s]===10&&t[s+1]===10||t[s]===13&&t[s+1]===13)return s+2;if(t[s]===13&&t[s+1]===10&&s+3<t.length&&t[s+2]===13&&t[s+3]===10)return s+4}return-1}const gt={off:0,error:200,warn:300,info:400,debug:500},ps=(t,e,n)=>{if(t){if(pi(gt,t))return t;B(n).warn(`${e} was set to ${JSON.stringify(t)}, expected one of ${JSON.stringify(Object.keys(gt))}`)}};function Ee(){}function et(t,e,n){return!e||gt[t]>gt[n]?Ee:e[t].bind(e)}const $i={error:Ee,warn:Ee,info:Ee,debug:Ee};let fs=new WeakMap;function B(t){const e=t.logger,n=t.logLevel??"off";if(!e)return $i;const s=fs.get(e);if(s&&s[0]===n)return s[1];const r={error:et("error",e,n),warn:et("warn",e,n),info:et("info",e,n),debug:et("debug",e,n)};return fs.set(e,[n,r]),r}const fe=t=>(t.options&&(t.options={...t.options},delete t.options.headers),t.headers&&(t.headers=Object.fromEntries((t.headers instanceof Headers?[...t.headers]:Object.entries(t.headers)).map(([e,n])=>[e,e.toLowerCase()==="authorization"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":n]))),"retryOfRequestLogID"in t&&(t.retryOfRequestLogID&&(t.retryOf=t.retryOfRequestLogID),delete t.retryOfRequestLogID),t);var Pe;class ie{constructor(e,n,s){this.iterator=e,Pe.set(this,void 0),this.controller=n,x(this,Pe,s)}static fromSSEResponse(e,n,s){let r=!1;const a=s?B(s):console;async function*i(){if(r)throw new O("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");r=!0;let o=!1;try{for await(const l of Ei(e,n))if(!o){if(l.data.startsWith("[DONE]")){o=!0;continue}if(l.event===null||!l.event.startsWith("thread.")){let u;try{u=JSON.parse(l.data)}catch(h){throw a.error("Could not parse message into JSON:",l.data),a.error("From chunk:",l.raw),h}if(u&&u.error)throw new q(void 0,u.error,void 0,e.headers);yield u}else{let u;try{u=JSON.parse(l.data)}catch(h){throw console.error("Could not parse message into JSON:",l.data),console.error("From chunk:",l.raw),h}if(l.event=="error")throw new q(void 0,u.error,u.message,void 0);yield{event:l.event,data:u}}}o=!0}catch(l){if(tn(l))return;throw l}finally{o||n.abort()}}return new ie(i,n,s)}static fromReadableStream(e,n,s){let r=!1;async function*a(){const o=new Et,l=ir(e);for await(const u of l)for(const h of o.decode(u))yield h;for(const u of o.flush())yield u}async function*i(){if(r)throw new O("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");r=!0;let o=!1;try{for await(const l of a())o||l&&(yield JSON.parse(l));o=!0}catch(l){if(tn(l))return;throw l}finally{o||n.abort()}}return new ie(i,n,s)}[(Pe=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){const e=[],n=[],s=this.iterator(),r=a=>({next:()=>{if(a.length===0){const i=s.next();e.push(i),n.push(i)}return a.shift()}});return[new ie(()=>r(e),this.controller,p(this,Pe,"f")),new ie(()=>r(n),this.controller,p(this,Pe,"f"))]}toReadableStream(){const e=this;let n;return rr({async start(){n=e[Symbol.asyncIterator]()},async pull(s){try{const{value:r,done:a}=await n.next();if(a)return s.close();const i=vn(JSON.stringify(r)+`
7
+ `);s.enqueue(i)}catch(r){s.error(r)}},async cancel(){await n.return?.()}})}}async function*Ei(t,e){if(!t.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new O("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 O("Attempted to iterate over a response with no body");const n=new Ni,s=new Et,r=ir(t.body);for await(const a of Mi(r))for(const i of s.decode(a)){const o=n.decode(i);o&&(yield o)}for(const a of s.flush()){const i=n.decode(a);i&&(yield i)}}async function*Mi(t){let e=new Uint8Array;for await(const n of t){if(n==null)continue;const s=n instanceof ArrayBuffer?new Uint8Array(n):typeof n=="string"?vn(n):n;let r=new Uint8Array(e.length+s.length);r.set(e),r.set(s,e.length),e=r;let a;for(;(a=Ri(e))!==-1;)yield e.slice(0,a),e=e.slice(a)}e.length>0&&(yield e)}class Ni{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;const a={event:this.event,data:this.data.join(`
8
+ `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],a}if(this.chunks.push(e),e.startsWith(":"))return null;let[n,s,r]=Li(e,":");return r.startsWith(" ")&&(r=r.substring(1)),n==="event"?this.event=r:n==="data"&&this.data.push(r),null}}function Li(t,e){const n=t.indexOf(e);return n!==-1?[t.substring(0,n),e,t.substring(n+e.length)]:[t,"",""]}async function pr(t,e){const{response:n,requestLogID:s,retryOfRequestLogID:r,startTime:a}=e,i=await(async()=>{if(e.options.stream)return B(t).debug("response",n.status,n.url,n.headers,n.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(n,e.controller,t):ie.fromSSEResponse(n,e.controller,t);if(n.status===204)return null;if(e.options.__binaryResponse)return n;const l=n.headers.get("content-type")?.split(";")[0]?.trim();if(l?.includes("application/json")||l?.endsWith("+json")){const c=await n.json();return fr(c,n)}return await n.text()})();return B(t).debug(`[${s}] response parsed`,fe({retryOfRequestLogID:r,url:n.url,status:n.status,body:i,durationMs:Date.now()-a})),i}function fr(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 Me;class Mt extends Promise{constructor(e,n,s=pr){super(r=>{r(null)}),this.responsePromise=n,this.parseResponse=s,Me.set(this,void 0),x(this,Me,e)}_thenUnwrap(e){return new Mt(p(this,Me,"f"),this.responsePromise,async(n,s)=>fr(e(await this.parseResponse(n,s),s),s.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){const[e,n]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:n,request_id:n.headers.get("x-request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(p(this,Me,"f"),e))),this.parsedPromise}then(e,n){return this.parse().then(e,n)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}}Me=new WeakMap;var tt;class On{constructor(e,n,s,r){tt.set(this,void 0),x(this,tt,e),this.options=r,this.response=n,this.body=s}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){const e=this.nextPageRequestOptions();if(!e)throw new O("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await p(this,tt,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(tt=new WeakMap,Symbol.asyncIterator)](){for await(const e of this.iterPages())for(const n of e.getPaginatedItems())yield n}}class ji extends Mt{constructor(e,n,s){super(e,n,async(r,a)=>new s(r,a.response,await pr(r,a),a.options))}async*[Symbol.asyncIterator](){const e=await this;for await(const n of e)yield n}}class Nt extends On{constructor(e,n,s,r){super(e,n,s,r),this.data=s.data||[],this.object=s.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}}class E extends On{constructor(e,n,s,r){super(e,n,s,r),this.data=s.data||[],this.has_more=s.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){const e=this.getPaginatedItems(),n=e[e.length-1]?.id;return n?{...this.options,query:{...sr(this.options.query),after:n}}:null}}class _t extends On{constructor(e,n,s,r){super(e,n,s,r),this.data=s.data||[],this.has_more=s.has_more||!1,this.last_id=s.last_id||""}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){const e=this.last_id;return e?{...this.options,query:{...sr(this.options.query),after:e}}:null}}const hr=()=>{if(typeof File>"u"){const{process:t}=globalThis,e=typeof t?.versions?.node=="string"&&parseInt(t.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(e?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function We(t,e,n){return hr(),new File(t,e??"unknown_file",n)}function ot(t){return(typeof t=="object"&&t!==null&&("name"in t&&t.name&&String(t.name)||"url"in t&&t.url&&String(t.url)||"filename"in t&&t.filename&&String(t.filename)||"path"in t&&t.path&&String(t.path))||"").split(/[\\/]/).pop()||void 0}const xn=t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function",hs=async(t,e)=>rn(t.body)?{...t,body:await mr(t.body,e)}:t,we=async(t,e)=>({...t,body:await mr(t.body,e)}),ms=new WeakMap;function Ui(t){const e=typeof t=="function"?t:t.fetch,n=ms.get(e);if(n)return n;const s=(async()=>{try{const r="Response"in e?e.Response:(await e("data:,")).constructor,a=new FormData;return a.toString()!==await new r(a).text()}catch{return!0}})();return ms.set(e,s),s}const mr=async(t,e)=>{if(!await Ui(e))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");const n=new FormData;return await Promise.all(Object.entries(t||{}).map(([s,r])=>an(n,s,r))),n},gr=t=>t instanceof Blob&&"name"in t,Di=t=>typeof t=="object"&&t!==null&&(t instanceof Response||xn(t)||gr(t)),rn=t=>{if(Di(t))return!0;if(Array.isArray(t))return t.some(rn);if(t&&typeof t=="object"){for(const e in t)if(rn(t[e]))return!0}return!1},an=async(t,e,n)=>{if(n!==void 0){if(n==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")t.append(e,String(n));else if(n instanceof Response)t.append(e,We([await n.blob()],ot(n)));else if(xn(n))t.append(e,We([await new Response(ar(n)).blob()],ot(n)));else if(gr(n))t.append(e,n,ot(n));else if(Array.isArray(n))await Promise.all(n.map(s=>an(t,e+"[]",s)));else if(typeof n=="object")await Promise.all(Object.entries(n).map(([s,r])=>an(t,`${e}[${s}]`,r)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${n} instead`)}},_r=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",Fi=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&_r(t),Bi=t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function";async function Wi(t,e,n){if(hr(),t=await t,Fi(t))return t instanceof File?t:We([await t.arrayBuffer()],t.name);if(Bi(t)){const r=await t.blob();return e||(e=new URL(t.url).pathname.split(/[\\/]/).pop()),We(await on(r),e,n)}const s=await on(t);if(e||(e=ot(t)),!n?.type){const r=s.find(a=>typeof a=="object"&&"type"in a&&a.type);typeof r=="string"&&(n={...n,type:r})}return We(s,e,n)}async function on(t){let e=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)e.push(t);else if(_r(t))e.push(t instanceof Blob?t:await t.arrayBuffer());else if(xn(t))for await(const n of t)e.push(...await on(n));else{const n=t?.constructor?.name;throw new Error(`Unexpected data type: ${typeof t}${n?`; constructor: ${n}`:""}${qi(t)}`)}return e}function qi(t){return typeof t!="object"||t===null?"":`; props: [${Object.getOwnPropertyNames(t).map(n=>`"${n}"`).join(", ")}]`}class v{constructor(e){this._client=e}}function yr(t){return t.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}const gs=Object.freeze(Object.create(null)),Ji=(t=yr)=>function(n,...s){if(n.length===1)return n[0];let r=!1;const a=[],i=n.reduce((h,c,f)=>{/[?#]/.test(c)&&(r=!0);const d=s[f];let w=(r?encodeURIComponent:t)(""+d);return f!==s.length&&(d==null||typeof d=="object"&&d.toString===Object.getPrototypeOf(Object.getPrototypeOf(d.hasOwnProperty??gs)??gs)?.toString)&&(w=d+"",a.push({start:h.length+c.length,length:w.length,error:`Value of type ${Object.prototype.toString.call(d).slice(8,-1)} is not a valid path parameter`})),h+c+(f===s.length?"":w)},""),o=i.split(/[?#]/,1)[0],l=new RegExp("(?<=^|\\/)(?:\\.|%2e){1,2}(?=\\/|$)","gi");let u;for(;(u=l.exec(o))!==null;)a.push({start:u.index,length:u[0].length,error:`Value "${u[0]}" can't be safely passed as a path parameter`});if(a.sort((h,c)=>h.start-c.start),a.length>0){let h=0;const c=a.reduce((f,d)=>{const w=" ".repeat(d.start-h),y="^".repeat(d.length);return h=d.start+d.length,f+w+y},"");throw new O(`Path parameters result in path with invalid segments:
9
+ ${a.map(f=>f.error).join(`
10
+ `)}
11
+ ${i}
12
+ ${c}`)}return i},_=Ji(yr);let wr=class extends v{list(e,n={},s){return this._client.getAPIList(_`/chat/completions/${e}/messages`,E,{query:n,...s})}};function yt(t){return t!==void 0&&"function"in t&&t.function!==void 0}function zi(t,e){const n={...t};return Object.defineProperties(n,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:e,enumerable:!1}}),n}function kn(t){return t?.$brand==="auto-parseable-response-format"}function He(t){return t?.$brand==="auto-parseable-tool"}function Ki(t,e){return!e||!br(e)?{...t,choices:t.choices.map(n=>(vr(n.message.tool_calls),{...n,message:{...n.message,parsed:null,...n.message.tool_calls?{tool_calls:n.message.tool_calls}:void 0}}))}:In(t,e)}function In(t,e){const n=t.choices.map(s=>{if(s.finish_reason==="length")throw new tr;if(s.finish_reason==="content_filter")throw new nr;return vr(s.message.tool_calls),{...s,message:{...s.message,...s.message.tool_calls?{tool_calls:s.message.tool_calls?.map(r=>Hi(e,r))??void 0}:void 0,parsed:s.message.content&&!s.message.refusal?Zi(e,s.message.content):null}}});return{...t,choices:n}}function Zi(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 Hi(t,e){const n=t.tools?.find(s=>yt(s)&&s.function?.name===e.function.name);return{...e,function:{...e.function,parsed_arguments:He(n)?n.$parseRaw(e.function.arguments):n?.function.strict?JSON.parse(e.function.arguments):null}}}function Vi(t,e){if(!t||!("tools"in t)||!t.tools)return!1;const n=t.tools?.find(s=>yt(s)&&s.function?.name===e.function.name);return yt(n)&&(He(n)||n?.function.strict||!1)}function br(t){return kn(t.response_format)?!0:t.tools?.some(e=>He(e)||e.type==="function"&&e.function.strict===!0)??!1}function vr(t){for(const e of t||[])if(e.type!=="function")throw new O(`Currently only \`function\` tool calls are supported; Received \`${e.type}\``)}function Xi(t){for(const e of t??[]){if(e.type!=="function")throw new O(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)throw new O(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}const wt=t=>t?.role==="assistant",Or=t=>t?.role==="tool";var un,ut,lt,Ne,Le,ct,je,ue,Ue,bt,vt,ke,xr;class Sn{constructor(){un.add(this),this.controller=new AbortController,ut.set(this,void 0),lt.set(this,()=>{}),Ne.set(this,()=>{}),Le.set(this,void 0),ct.set(this,()=>{}),je.set(this,()=>{}),ue.set(this,{}),Ue.set(this,!1),bt.set(this,!1),vt.set(this,!1),ke.set(this,!1),x(this,ut,new Promise((e,n)=>{x(this,lt,e,"f"),x(this,Ne,n,"f")})),x(this,Le,new Promise((e,n)=>{x(this,ct,e,"f"),x(this,je,n,"f")})),p(this,ut,"f").catch(()=>{}),p(this,Le,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},p(this,un,"m",xr).bind(this))},0)}_connected(){this.ended||(p(this,lt,"f").call(this),this._emit("connect"))}get ended(){return p(this,Ue,"f")}get errored(){return p(this,bt,"f")}get aborted(){return p(this,vt,"f")}abort(){this.controller.abort()}on(e,n){return(p(this,ue,"f")[e]||(p(this,ue,"f")[e]=[])).push({listener:n}),this}off(e,n){const s=p(this,ue,"f")[e];if(!s)return this;const r=s.findIndex(a=>a.listener===n);return r>=0&&s.splice(r,1),this}once(e,n){return(p(this,ue,"f")[e]||(p(this,ue,"f")[e]=[])).push({listener:n,once:!0}),this}emitted(e){return new Promise((n,s)=>{x(this,ke,!0),e!=="error"&&this.once("error",s),this.once(e,n)})}async done(){x(this,ke,!0),await p(this,Le,"f")}_emit(e,...n){if(p(this,Ue,"f"))return;e==="end"&&(x(this,Ue,!0),p(this,ct,"f").call(this));const s=p(this,ue,"f")[e];if(s&&(p(this,ue,"f")[e]=s.filter(r=>!r.once),s.forEach(({listener:r})=>r(...n))),e==="abort"){const r=n[0];!p(this,ke,"f")&&!s?.length&&Promise.reject(r),p(this,Ne,"f").call(this,r),p(this,je,"f").call(this,r),this._emit("end");return}if(e==="error"){const r=n[0];!p(this,ke,"f")&&!s?.length&&Promise.reject(r),p(this,Ne,"f").call(this,r),p(this,je,"f").call(this,r),this._emit("end")}}_emitFinal(){}}ut=new WeakMap,lt=new WeakMap,Ne=new WeakMap,Le=new WeakMap,ct=new WeakMap,je=new WeakMap,ue=new WeakMap,Ue=new WeakMap,bt=new WeakMap,vt=new WeakMap,ke=new WeakMap,un=new WeakSet,xr=function(e){if(x(this,bt,!0),e instanceof Error&&e.name==="AbortError"&&(e=new Y),e instanceof Y)return x(this,vt,!0),this._emit("abort",e);if(e instanceof O)return this._emit("error",e);if(e instanceof Error){const n=new O(e.message);return n.cause=e,this._emit("error",n)}return this._emit("error",new O(String(e)))};function Gi(t){return typeof t.parse=="function"}var Z,ln,Ot,cn,dn,pn,kr,Ir;const Qi=10;class Sr extends Sn{constructor(){super(...arguments),Z.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){this._chatCompletions.push(e),this._emit("chatCompletion",e);const n=e.choices[0]?.message;return n&&this._addMessage(n),e}_addMessage(e,n=!0){if("content"in e||(e.content=null),this.messages.push(e),n){if(this._emit("message",e),Or(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(wt(e)&&e.tool_calls)for(const s of e.tool_calls)s.type==="function"&&this._emit("functionToolCall",s.function)}}async finalChatCompletion(){await this.done();const e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new O("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),p(this,Z,"m",ln).call(this)}async finalMessage(){return await this.done(),p(this,Z,"m",Ot).call(this)}async finalFunctionToolCall(){return await this.done(),p(this,Z,"m",cn).call(this)}async finalFunctionToolCallResult(){return await this.done(),p(this,Z,"m",dn).call(this)}async totalUsage(){return await this.done(),p(this,Z,"m",pn).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){const e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);const n=p(this,Z,"m",Ot).call(this);n&&this._emit("finalMessage",n);const s=p(this,Z,"m",ln).call(this);s&&this._emit("finalContent",s);const r=p(this,Z,"m",cn).call(this);r&&this._emit("finalFunctionToolCall",r);const a=p(this,Z,"m",dn).call(this);a!=null&&this._emit("finalFunctionToolCallResult",a),this._chatCompletions.some(i=>i.usage)&&this._emit("totalUsage",p(this,Z,"m",pn).call(this))}async _createChatCompletion(e,n,s){const r=s?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),p(this,Z,"m",kr).call(this,n);const a=await e.chat.completions.create({...n,stream:!1},{...s,signal:this.controller.signal});return this._connected(),this._addChatCompletion(In(a,n))}async _runChatCompletion(e,n,s){for(const r of n.messages)this._addMessage(r,!1);return await this._createChatCompletion(e,n,s)}async _runTools(e,n,s){const r="tool",{tool_choice:a="auto",stream:i,...o}=n,l=typeof a!="string"&&a.type==="function"&&a?.function?.name,{maxChatCompletions:u=Qi}=s||{},h=n.tools.map(d=>{if(He(d)){if(!d.$callback)throw new O("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:d.$callback,name:d.function.name,description:d.function.description||"",parameters:d.function.parameters,parse:d.$parseRaw,strict:!0}}}return d}),c={};for(const d of h)d.type==="function"&&(c[d.function.name||d.function.function.name]=d.function);const f="tools"in n?h.map(d=>d.type==="function"?{type:"function",function:{name:d.function.name||d.function.function.name,parameters:d.function.parameters,description:d.function.description,strict:d.function.strict}}:d):void 0;for(const d of n.messages)this._addMessage(d,!1);for(let d=0;d<u;++d){const y=(await this._createChatCompletion(e,{...o,tool_choice:a,tools:f,messages:[...this.messages]},s)).choices[0]?.message;if(!y)throw new O("missing message in ChatCompletion response");if(!y.tool_calls?.length)return;for(const C of y.tool_calls){if(C.type!=="function")continue;const m=C.id,{name:g,arguments:k}=C.function,A=c[g];if(A){if(l&&l!==g){const F=`Invalid tool_call: ${JSON.stringify(g)}. ${JSON.stringify(l)} requested. Please try again`;this._addMessage({role:r,tool_call_id:m,content:F});continue}}else{const F=`Invalid tool_call: ${JSON.stringify(g)}. Available options are: ${Object.keys(c).map(U=>JSON.stringify(U)).join(", ")}. Please try again`;this._addMessage({role:r,tool_call_id:m,content:F});continue}let K;try{K=Gi(A)?await A.parse(k):k}catch(F){const U=F instanceof Error?F.message:String(F);this._addMessage({role:r,tool_call_id:m,content:U});continue}const j=await A.function(K,this),R=p(this,Z,"m",Ir).call(this,j);if(this._addMessage({role:r,tool_call_id:m,content:R}),l)return}}}}Z=new WeakSet,ln=function(){return p(this,Z,"m",Ot).call(this).content??null},Ot=function(){let e=this.messages.length;for(;e-- >0;){const n=this.messages[e];if(wt(n))return{...n,content:n.content??null,refusal:n.refusal??null}}throw new O("stream ended without producing a ChatCompletionMessage with role=assistant")},cn=function(){for(let e=this.messages.length-1;e>=0;e--){const n=this.messages[e];if(wt(n)&&n?.tool_calls?.length)return n.tool_calls.filter(s=>s.type==="function").at(-1)?.function}},dn=function(){for(let e=this.messages.length-1;e>=0;e--){const n=this.messages[e];if(Or(n)&&n.content!=null&&typeof n.content=="string"&&this.messages.some(s=>s.role==="assistant"&&s.tool_calls?.some(r=>r.type==="function"&&r.id===n.tool_call_id)))return n.content}},pn=function(){const e={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(const{usage:n}of this._chatCompletions)n&&(e.completion_tokens+=n.completion_tokens,e.prompt_tokens+=n.prompt_tokens,e.total_tokens+=n.total_tokens);return e},kr=function(e){if(e.n!=null&&e.n>1)throw new O("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},Ir=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};class Cn extends Sr{static runTools(e,n,s){const r=new Cn,a={...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"runTools"}};return r._run(()=>r._runTools(e,n,a)),r}_addMessage(e,n=!0){super._addMessage(e,n),wt(e)&&e.content&&this._emit("content",e.content)}}const Cr=1,Tr=2,Ar=4,Pr=8,Rr=16,$r=32,Er=64,Mr=128,Nr=256,Lr=Mr|Nr,jr=Rr|$r|Lr|Er,Ur=Cr|Tr|jr,Dr=Ar|Pr,Yi=Ur|Dr,D={STR:Cr,NUM:Tr,ARR:Ar,OBJ:Pr,NULL:Rr,BOOL:$r,NAN:Er,INFINITY:Mr,MINUS_INFINITY:Nr,INF:Lr,SPECIAL:jr,ATOM:Ur,COLLECTION:Dr,ALL:Yi};class eo extends Error{}class to extends Error{}function no(t,e=D.ALL){if(typeof t!="string")throw new TypeError(`expecting str, got ${typeof t}`);if(!t.trim())throw new Error(`${t} is empty`);return so(t.trim(),e)}const so=(t,e)=>{const n=t.length;let s=0;const r=f=>{throw new eo(`${f} at position ${s}`)},a=f=>{throw new to(`${f} at position ${s}`)},i=()=>(c(),s>=n&&r("Unexpected end of input"),t[s]==='"'?o():t[s]==="{"?l():t[s]==="["?u():t.substring(s,s+4)==="null"||D.NULL&e&&n-s<4&&"null".startsWith(t.substring(s))?(s+=4,null):t.substring(s,s+4)==="true"||D.BOOL&e&&n-s<4&&"true".startsWith(t.substring(s))?(s+=4,!0):t.substring(s,s+5)==="false"||D.BOOL&e&&n-s<5&&"false".startsWith(t.substring(s))?(s+=5,!1):t.substring(s,s+8)==="Infinity"||D.INFINITY&e&&n-s<8&&"Infinity".startsWith(t.substring(s))?(s+=8,1/0):t.substring(s,s+9)==="-Infinity"||D.MINUS_INFINITY&e&&1<n-s&&n-s<9&&"-Infinity".startsWith(t.substring(s))?(s+=9,-1/0):t.substring(s,s+3)==="NaN"||D.NAN&e&&n-s<3&&"NaN".startsWith(t.substring(s))?(s+=3,NaN):h()),o=()=>{const f=s;let d=!1;for(s++;s<n&&(t[s]!=='"'||d&&t[s-1]==="\\");)d=t[s]==="\\"?!d:!1,s++;if(t.charAt(s)=='"')try{return JSON.parse(t.substring(f,++s-Number(d)))}catch(w){a(String(w))}else if(D.STR&e)try{return JSON.parse(t.substring(f,s-Number(d))+'"')}catch{return JSON.parse(t.substring(f,t.lastIndexOf("\\"))+'"')}r("Unterminated string literal")},l=()=>{s++,c();const f={};try{for(;t[s]!=="}";){if(c(),s>=n&&D.OBJ&e)return f;const d=o();c(),s++;try{const w=i();Object.defineProperty(f,d,{value:w,writable:!0,enumerable:!0,configurable:!0})}catch(w){if(D.OBJ&e)return f;throw w}c(),t[s]===","&&s++}}catch{if(D.OBJ&e)return f;r("Expected '}' at end of object")}return s++,f},u=()=>{s++;const f=[];try{for(;t[s]!=="]";)f.push(i()),c(),t[s]===","&&s++}catch{if(D.ARR&e)return f;r("Expected ']' at end of array")}return s++,f},h=()=>{if(s===0){t==="-"&&D.NUM&e&&r("Not sure what '-' is");try{return JSON.parse(t)}catch(d){if(D.NUM&e)try{return t[t.length-1]==="."?JSON.parse(t.substring(0,t.lastIndexOf("."))):JSON.parse(t.substring(0,t.lastIndexOf("e")))}catch{}a(String(d))}}const f=s;for(t[s]==="-"&&s++;t[s]&&!",]}".includes(t[s]);)s++;s==n&&!(D.NUM&e)&&r("Unterminated number literal");try{return JSON.parse(t.substring(f,s))}catch{t.substring(f,s)==="-"&&D.NUM&e&&r("Not sure what '-' is");try{return JSON.parse(t.substring(f,t.lastIndexOf("e")))}catch(w){a(String(w))}}},c=()=>{for(;s<n&&`
13
+ \r `.includes(t[s]);)s++};return i()},_s=t=>no(t,D.ALL^D.NUM);var N,oe,be,ce,Ht,nt,Vt,Xt,Gt,st,Qt,ys;class Ke extends Sr{constructor(e){super(),N.add(this),oe.set(this,void 0),be.set(this,void 0),ce.set(this,void 0),x(this,oe,e),x(this,be,[])}get currentChatCompletionSnapshot(){return p(this,ce,"f")}static fromReadableStream(e){const n=new Ke(null);return n._run(()=>n._fromReadableStream(e)),n}static createChatCompletion(e,n,s){const r=new Ke(n);return r._run(()=>r._runChatCompletion(e,{...n,stream:!0},{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),r}async _createChatCompletion(e,n,s){super._createChatCompletion;const r=s?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),p(this,N,"m",Ht).call(this);const a=await e.chat.completions.create({...n,stream:!0},{...s,signal:this.controller.signal});this._connected();for await(const i of a)p(this,N,"m",Vt).call(this,i);if(a.controller.signal?.aborted)throw new Y;return this._addChatCompletion(p(this,N,"m",st).call(this))}async _fromReadableStream(e,n){const s=n?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),p(this,N,"m",Ht).call(this),this._connected();const r=ie.fromReadableStream(e,this.controller);let a;for await(const i of r)a&&a!==i.id&&this._addChatCompletion(p(this,N,"m",st).call(this)),p(this,N,"m",Vt).call(this,i),a=i.id;if(r.controller.signal?.aborted)throw new Y;return this._addChatCompletion(p(this,N,"m",st).call(this))}[(oe=new WeakMap,be=new WeakMap,ce=new WeakMap,N=new WeakSet,Ht=function(){this.ended||x(this,ce,void 0)},nt=function(n){let s=p(this,be,"f")[n.index];return s||(s={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},p(this,be,"f")[n.index]=s,s)},Vt=function(n){if(this.ended)return;const s=p(this,N,"m",ys).call(this,n);this._emit("chunk",n,s);for(const r of n.choices){const a=s.choices[r.index];r.delta.content!=null&&a.message?.role==="assistant"&&a.message?.content&&(this._emit("content",r.delta.content,a.message.content),this._emit("content.delta",{delta:r.delta.content,snapshot:a.message.content,parsed:a.message.parsed})),r.delta.refusal!=null&&a.message?.role==="assistant"&&a.message?.refusal&&this._emit("refusal.delta",{delta:r.delta.refusal,snapshot:a.message.refusal}),r.logprobs?.content!=null&&a.message?.role==="assistant"&&this._emit("logprobs.content.delta",{content:r.logprobs?.content,snapshot:a.logprobs?.content??[]}),r.logprobs?.refusal!=null&&a.message?.role==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:r.logprobs?.refusal,snapshot:a.logprobs?.refusal??[]});const i=p(this,N,"m",nt).call(this,a);a.finish_reason&&(p(this,N,"m",Gt).call(this,a),i.current_tool_call_index!=null&&p(this,N,"m",Xt).call(this,a,i.current_tool_call_index));for(const o of r.delta.tool_calls??[])i.current_tool_call_index!==o.index&&(p(this,N,"m",Gt).call(this,a),i.current_tool_call_index!=null&&p(this,N,"m",Xt).call(this,a,i.current_tool_call_index)),i.current_tool_call_index=o.index;for(const o of r.delta.tool_calls??[]){const l=a.message.tool_calls?.[o.index];l?.type&&(l?.type==="function"?this._emit("tool_calls.function.arguments.delta",{name:l.function?.name,index:o.index,arguments:l.function.arguments,parsed_arguments:l.function.parsed_arguments,arguments_delta:o.function?.arguments??""}):(l?.type,void 0))}}},Xt=function(n,s){if(p(this,N,"m",nt).call(this,n).done_tool_calls.has(s))return;const a=n.message.tool_calls?.[s];if(!a)throw new Error("no tool call snapshot");if(!a.type)throw new Error("tool call snapshot missing `type`");if(a.type==="function"){const i=p(this,oe,"f")?.tools?.find(o=>yt(o)&&o.function.name===a.function.name);this._emit("tool_calls.function.arguments.done",{name:a.function.name,index:s,arguments:a.function.arguments,parsed_arguments:He(i)?i.$parseRaw(a.function.arguments):i?.function.strict?JSON.parse(a.function.arguments):null})}else a.type},Gt=function(n){const s=p(this,N,"m",nt).call(this,n);if(n.message.content&&!s.content_done){s.content_done=!0;const r=p(this,N,"m",Qt).call(this);this._emit("content.done",{content:n.message.content,parsed:r?r.$parseRaw(n.message.content):null})}n.message.refusal&&!s.refusal_done&&(s.refusal_done=!0,this._emit("refusal.done",{refusal:n.message.refusal})),n.logprobs?.content&&!s.logprobs_content_done&&(s.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:n.logprobs.content})),n.logprobs?.refusal&&!s.logprobs_refusal_done&&(s.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:n.logprobs.refusal}))},st=function(){if(this.ended)throw new O("stream has ended, this shouldn't happen");const n=p(this,ce,"f");if(!n)throw new O("request ended without sending any chunks");return x(this,ce,void 0),x(this,be,[]),ro(n,p(this,oe,"f"))},Qt=function(){const n=p(this,oe,"f")?.response_format;return kn(n)?n:null},ys=function(n){var s,r,a,i;let o=p(this,ce,"f");const{choices:l,...u}=n;o?Object.assign(o,u):o=x(this,ce,{...u,choices:[]});for(const{delta:h,finish_reason:c,index:f,logprobs:d=null,...w}of n.choices){let y=o.choices[f];if(y||(y=o.choices[f]={finish_reason:c,index:f,message:{},logprobs:d,...w}),d)if(!y.logprobs)y.logprobs=Object.assign({},d);else{const{content:j,refusal:R,...F}=d;Object.assign(y.logprobs,F),j&&((s=y.logprobs).content??(s.content=[]),y.logprobs.content.push(...j)),R&&((r=y.logprobs).refusal??(r.refusal=[]),y.logprobs.refusal.push(...R))}if(c&&(y.finish_reason=c,p(this,oe,"f")&&br(p(this,oe,"f")))){if(c==="length")throw new tr;if(c==="content_filter")throw new nr}if(Object.assign(y,w),!h)continue;const{content:C,refusal:m,function_call:g,role:k,tool_calls:A,...K}=h;if(Object.assign(y.message,K),m&&(y.message.refusal=(y.message.refusal||"")+m),k&&(y.message.role=k),g&&(y.message.function_call?(g.name&&(y.message.function_call.name=g.name),g.arguments&&((a=y.message.function_call).arguments??(a.arguments=""),y.message.function_call.arguments+=g.arguments)):y.message.function_call=g),C&&(y.message.content=(y.message.content||"")+C,!y.message.refusal&&p(this,N,"m",Qt).call(this)&&(y.message.parsed=_s(y.message.content))),A){y.message.tool_calls||(y.message.tool_calls=[]);for(const{index:j,id:R,type:F,function:U,...$}of A){const M=(i=y.message.tool_calls)[j]??(i[j]={});Object.assign(M,$),R&&(M.id=R),F&&(M.type=F),U&&(M.function??(M.function={name:U.name??"",arguments:""})),U?.name&&(M.function.name=U.name),U?.arguments&&(M.function.arguments+=U.arguments,Vi(p(this,oe,"f"),M)&&(M.function.parsed_arguments=_s(M.function.arguments)))}}}return o},Symbol.asyncIterator)](){const e=[],n=[];let s=!1;return this.on("chunk",r=>{const a=n.shift();a?a.resolve(r):e.push(r)}),this.on("end",()=>{s=!0;for(const r of n)r.resolve(void 0);n.length=0}),this.on("abort",r=>{s=!0;for(const a of n)a.reject(r);n.length=0}),this.on("error",r=>{s=!0;for(const a of n)a.reject(r);n.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:s?{value:void 0,done:!0}:new Promise((a,i)=>n.push({resolve:a,reject:i})).then(a=>a?{value:a,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new ie(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function ro(t,e){const{id:n,choices:s,created:r,model:a,system_fingerprint:i,...o}=t,l={...o,id:n,choices:s.map(({message:u,finish_reason:h,index:c,logprobs:f,...d})=>{if(!h)throw new O(`missing finish_reason for choice ${c}`);const{content:w=null,function_call:y,tool_calls:C,...m}=u,g=u.role;if(!g)throw new O(`missing role for choice ${c}`);if(y){const{arguments:k,name:A}=y;if(k==null)throw new O(`missing function_call.arguments for choice ${c}`);if(!A)throw new O(`missing function_call.name for choice ${c}`);return{...d,message:{content:w,function_call:{arguments:k,name:A},role:g,refusal:u.refusal??null},finish_reason:h,index:c,logprobs:f}}return C?{...d,index:c,finish_reason:h,logprobs:f,message:{...m,role:g,content:w,refusal:u.refusal??null,tool_calls:C.map((k,A)=>{const{function:K,type:j,id:R,...F}=k,{arguments:U,name:$,...M}=K||{};if(R==null)throw new O(`missing choices[${c}].tool_calls[${A}].id
14
+ ${rt(t)}`);if(j==null)throw new O(`missing choices[${c}].tool_calls[${A}].type
15
+ ${rt(t)}`);if($==null)throw new O(`missing choices[${c}].tool_calls[${A}].function.name
16
+ ${rt(t)}`);if(U==null)throw new O(`missing choices[${c}].tool_calls[${A}].function.arguments
17
+ ${rt(t)}`);return{...F,id:R,type:j,function:{...M,name:$,arguments:U}}})}}:{...d,message:{...m,content:w,role:g,refusal:u.refusal??null},finish_reason:h,index:c,logprobs:f}}),created:r,model:a,object:"chat.completion",...i?{system_fingerprint:i}:{}};return Ki(l,e)}function rt(t){return JSON.stringify(t)}class xt extends Ke{static fromReadableStream(e){const n=new xt(null);return n._run(()=>n._fromReadableStream(e)),n}static runTools(e,n,s){const r=new xt(n),a={...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"runTools"}};return r._run(()=>r._runTools(e,n,a)),r}}let Tn=class extends v{constructor(){super(...arguments),this.messages=new wr(this._client)}create(e,n){return this._client.post("/chat/completions",{body:e,...n,stream:e.stream??!1})}retrieve(e,n){return this._client.get(_`/chat/completions/${e}`,n)}update(e,n,s){return this._client.post(_`/chat/completions/${e}`,{body:n,...s})}list(e={},n){return this._client.getAPIList("/chat/completions",E,{query:e,...n})}delete(e,n){return this._client.delete(_`/chat/completions/${e}`,n)}parse(e,n){return Xi(e.tools),this._client.chat.completions.create(e,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(s=>In(s,e))}runTools(e,n){return e.stream?xt.runTools(this._client,e,n):Cn.runTools(this._client,e,n)}stream(e,n){return Ke.createChatCompletion(this._client,e,n)}};Tn.Messages=wr;class An extends v{constructor(){super(...arguments),this.completions=new Tn(this._client)}}An.Completions=Tn;const Fr=Symbol("brand.privateNullableHeaders");function*ao(t){if(!t)return;if(Fr in t){const{values:s,nulls:r}=t;yield*s.entries();for(const a of r)yield[a,null];return}let e=!1,n;t instanceof Headers?n=t.entries():ns(t)?n=t:(e=!0,n=Object.entries(t??{}));for(let s of n){const r=s[0];if(typeof r!="string")throw new TypeError("expected header name to be a string");const a=ns(s[1])?s[1]:[s[1]];let i=!1;for(const o of a)o!==void 0&&(e&&!i&&(i=!0,yield[r,null]),yield[r,o])}}const b=t=>{const e=new Headers,n=new Set;for(const s of t){const r=new Set;for(const[a,i]of ao(s)){const o=a.toLowerCase();r.has(o)||(e.delete(a),r.add(o)),i===null?(e.delete(a),n.add(o)):(e.append(a,i),n.delete(o))}}return{[Fr]:!0,values:e,nulls:n}};class Br extends v{create(e,n){return this._client.post("/audio/speech",{body:e,...n,headers:b([{Accept:"application/octet-stream"},n?.headers]),__binaryResponse:!0})}}class Wr extends v{create(e,n){return this._client.post("/audio/transcriptions",we({body:e,...n,stream:e.stream??!1,__metadata:{model:e.model}},this._client))}}class qr extends v{create(e,n){return this._client.post("/audio/translations",we({body:e,...n,__metadata:{model:e.model}},this._client))}}class Ve extends v{constructor(){super(...arguments),this.transcriptions=new Wr(this._client),this.translations=new qr(this._client),this.speech=new Br(this._client)}}Ve.Transcriptions=Wr;Ve.Translations=qr;Ve.Speech=Br;class Jr extends v{create(e,n){return this._client.post("/batches",{body:e,...n})}retrieve(e,n){return this._client.get(_`/batches/${e}`,n)}list(e={},n){return this._client.getAPIList("/batches",E,{query:e,...n})}cancel(e,n){return this._client.post(_`/batches/${e}/cancel`,n)}}class zr extends v{create(e,n){return this._client.post("/assistants",{body:e,...n,headers:b([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}retrieve(e,n){return this._client.get(_`/assistants/${e}`,{...n,headers:b([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}update(e,n,s){return this._client.post(_`/assistants/${e}`,{body:n,...s,headers:b([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}list(e={},n){return this._client.getAPIList("/assistants",E,{query:e,...n,headers:b([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}delete(e,n){return this._client.delete(_`/assistants/${e}`,{...n,headers:b([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}}let Kr=class extends v{create(e,n){return this._client.post("/realtime/sessions",{body:e,...n,headers:b([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}};class Zr extends v{create(e,n){return this._client.post("/realtime/transcription_sessions",{body:e,...n,headers:b([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}}let Lt=class extends v{constructor(){super(...arguments),this.sessions=new Kr(this._client),this.transcriptionSessions=new Zr(this._client)}};Lt.Sessions=Kr;Lt.TranscriptionSessions=Zr;class Hr extends v{create(e,n){return this._client.post("/chatkit/sessions",{body:e,...n,headers:b([{"OpenAI-Beta":"chatkit_beta=v1"},n?.headers])})}cancel(e,n){return this._client.post(_`/chatkit/sessions/${e}/cancel`,{...n,headers:b([{"OpenAI-Beta":"chatkit_beta=v1"},n?.headers])})}}let Vr=class extends v{retrieve(e,n){return this._client.get(_`/chatkit/threads/${e}`,{...n,headers:b([{"OpenAI-Beta":"chatkit_beta=v1"},n?.headers])})}list(e={},n){return this._client.getAPIList("/chatkit/threads",_t,{query:e,...n,headers:b([{"OpenAI-Beta":"chatkit_beta=v1"},n?.headers])})}delete(e,n){return this._client.delete(_`/chatkit/threads/${e}`,{...n,headers:b([{"OpenAI-Beta":"chatkit_beta=v1"},n?.headers])})}listItems(e,n={},s){return this._client.getAPIList(_`/chatkit/threads/${e}/items`,_t,{query:n,...s,headers:b([{"OpenAI-Beta":"chatkit_beta=v1"},s?.headers])})}};class jt extends v{constructor(){super(...arguments),this.sessions=new Hr(this._client),this.threads=new Vr(this._client)}}jt.Sessions=Hr;jt.Threads=Vr;class Xr extends v{create(e,n,s){return this._client.post(_`/threads/${e}/messages`,{body:n,...s,headers:b([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}retrieve(e,n,s){const{thread_id:r}=n;return this._client.get(_`/threads/${r}/messages/${e}`,{...s,headers:b([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}update(e,n,s){const{thread_id:r,...a}=n;return this._client.post(_`/threads/${r}/messages/${e}`,{body:a,...s,headers:b([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}list(e,n={},s){return this._client.getAPIList(_`/threads/${e}/messages`,E,{query:n,...s,headers:b([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}delete(e,n,s){const{thread_id:r}=n;return this._client.delete(_`/threads/${r}/messages/${e}`,{...s,headers:b([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}}class Gr extends v{retrieve(e,n,s){const{thread_id:r,run_id:a,...i}=n;return this._client.get(_`/threads/${r}/runs/${a}/steps/${e}`,{query:i,...s,headers:b([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}list(e,n,s){const{thread_id:r,...a}=n;return this._client.getAPIList(_`/threads/${r}/runs/${e}/steps`,E,{query:a,...s,headers:b([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}}const io=t=>{if(typeof Buffer<"u"){const e=Buffer.from(t,"base64");return Array.from(new Float32Array(e.buffer,e.byteOffset,e.length/Float32Array.BYTES_PER_ELEMENT))}else{const e=atob(t),n=e.length,s=new Uint8Array(n);for(let r=0;r<n;r++)s[r]=e.charCodeAt(r);return Array.from(new Float32Array(s.buffer))}};var oo={};const ve=t=>{if(typeof globalThis.process<"u")return oo?.[t]?.trim()??void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(t)?.trim()};var W,ge,fn,ae,dt,se,_e,Se,me,kt,G,pt,ft,qe,De,Fe,ws,bs,vs,Os,xs,ks,Is;class Je extends Sn{constructor(){super(...arguments),W.add(this),fn.set(this,[]),ae.set(this,{}),dt.set(this,{}),se.set(this,void 0),_e.set(this,void 0),Se.set(this,void 0),me.set(this,void 0),kt.set(this,void 0),G.set(this,void 0),pt.set(this,void 0),ft.set(this,void 0),qe.set(this,void 0)}[(fn=new WeakMap,ae=new WeakMap,dt=new WeakMap,se=new WeakMap,_e=new WeakMap,Se=new WeakMap,me=new WeakMap,kt=new WeakMap,G=new WeakMap,pt=new WeakMap,ft=new WeakMap,qe=new WeakMap,W=new WeakSet,Symbol.asyncIterator)](){const e=[],n=[];let s=!1;return this.on("event",r=>{const a=n.shift();a?a.resolve(r):e.push(r)}),this.on("end",()=>{s=!0;for(const r of n)r.resolve(void 0);n.length=0}),this.on("abort",r=>{s=!0;for(const a of n)a.reject(r);n.length=0}),this.on("error",r=>{s=!0;for(const a of n)a.reject(r);n.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:s?{value:void 0,done:!0}:new Promise((a,i)=>n.push({resolve:a,reject:i})).then(a=>a?{value:a,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){const n=new ge;return n._run(()=>n._fromReadableStream(e)),n}async _fromReadableStream(e,n){const s=n?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),this._connected();const r=ie.fromReadableStream(e,this.controller);for await(const a of r)p(this,W,"m",De).call(this,a);if(r.controller.signal?.aborted)throw new Y;return this._addRun(p(this,W,"m",Fe).call(this))}toReadableStream(){return new ie(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,n,s,r){const a=new ge;return a._run(()=>a._runToolAssistantStream(e,n,s,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),a}async _createToolAssistantStream(e,n,s,r){const a=r?.signal;a&&(a.aborted&&this.controller.abort(),a.addEventListener("abort",()=>this.controller.abort()));const i={...s,stream:!0},o=await e.submitToolOutputs(n,i,{...r,signal:this.controller.signal});this._connected();for await(const l of o)p(this,W,"m",De).call(this,l);if(o.controller.signal?.aborted)throw new Y;return this._addRun(p(this,W,"m",Fe).call(this))}static createThreadAssistantStream(e,n,s){const r=new ge;return r._run(()=>r._threadAssistantStream(e,n,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),r}static createAssistantStream(e,n,s,r){const a=new ge;return a._run(()=>a._runAssistantStream(e,n,s,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),a}currentEvent(){return p(this,pt,"f")}currentRun(){return p(this,ft,"f")}currentMessageSnapshot(){return p(this,se,"f")}currentRunStepSnapshot(){return p(this,qe,"f")}async finalRunSteps(){return await this.done(),Object.values(p(this,ae,"f"))}async finalMessages(){return await this.done(),Object.values(p(this,dt,"f"))}async finalRun(){if(await this.done(),!p(this,_e,"f"))throw Error("Final run was not received.");return p(this,_e,"f")}async _createThreadAssistantStream(e,n,s){const r=s?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort()));const a={...n,stream:!0},i=await e.createAndRun(a,{...s,signal:this.controller.signal});this._connected();for await(const o of i)p(this,W,"m",De).call(this,o);if(i.controller.signal?.aborted)throw new Y;return this._addRun(p(this,W,"m",Fe).call(this))}async _createAssistantStream(e,n,s,r){const a=r?.signal;a&&(a.aborted&&this.controller.abort(),a.addEventListener("abort",()=>this.controller.abort()));const i={...s,stream:!0},o=await e.create(n,i,{...r,signal:this.controller.signal});this._connected();for await(const l of o)p(this,W,"m",De).call(this,l);if(o.controller.signal?.aborted)throw new Y;return this._addRun(p(this,W,"m",Fe).call(this))}static accumulateDelta(e,n){for(const[s,r]of Object.entries(n)){if(!e.hasOwnProperty(s)){e[s]=r;continue}let a=e[s];if(a==null){e[s]=r;continue}if(s==="index"||s==="type"){e[s]=r;continue}if(typeof a=="string"&&typeof r=="string")a+=r;else if(typeof a=="number"&&typeof r=="number")a+=r;else if(zt(a)&&zt(r))a=this.accumulateDelta(a,r);else if(Array.isArray(a)&&Array.isArray(r)){if(a.every(i=>typeof i=="string"||typeof i=="number")){a.push(...r);continue}for(const i of r){if(!zt(i))throw new Error(`Expected array delta entry to be an object but got: ${i}`);const o=i.index;if(o==null)throw console.error(i),new Error("Expected array delta entry to have an `index` property");if(typeof o!="number")throw new Error(`Expected array delta entry \`index\` property to be a number but got ${o}`);const l=a[o];l==null?a.push(i):a[o]=this.accumulateDelta(l,i)}continue}else throw Error(`Unhandled record type: ${s}, deltaValue: ${r}, accValue: ${a}`);e[s]=a}return e}_addRun(e){return e}async _threadAssistantStream(e,n,s){return await this._createThreadAssistantStream(n,e,s)}async _runAssistantStream(e,n,s,r){return await this._createAssistantStream(n,e,s,r)}async _runToolAssistantStream(e,n,s,r){return await this._createToolAssistantStream(n,e,s,r)}}ge=Je,De=function(e){if(!this.ended)switch(x(this,pt,e),p(this,W,"m",vs).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":p(this,W,"m",Is).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":p(this,W,"m",bs).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":p(this,W,"m",ws).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier")}},Fe=function(){if(this.ended)throw new O("stream has ended, this shouldn't happen");if(!p(this,_e,"f"))throw Error("Final run has not been received");return p(this,_e,"f")},ws=function(e){const[n,s]=p(this,W,"m",xs).call(this,e,p(this,se,"f"));x(this,se,n),p(this,dt,"f")[n.id]=n;for(const r of s){const a=n.content[r.index];a?.type=="text"&&this._emit("textCreated",a.text)}switch(e.event){case"thread.message.created":this._emit("messageCreated",e.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",e.data.delta,n),e.data.delta.content)for(const r of e.data.delta.content){if(r.type=="text"&&r.text){let a=r.text,i=n.content[r.index];if(i&&i.type=="text")this._emit("textDelta",a,i.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(r.index!=p(this,Se,"f")){if(p(this,me,"f"))switch(p(this,me,"f").type){case"text":this._emit("textDone",p(this,me,"f").text,p(this,se,"f"));break;case"image_file":this._emit("imageFileDone",p(this,me,"f").image_file,p(this,se,"f"));break}x(this,Se,r.index)}x(this,me,n.content[r.index])}break;case"thread.message.completed":case"thread.message.incomplete":if(p(this,Se,"f")!==void 0){const r=e.data.content[p(this,Se,"f")];if(r)switch(r.type){case"image_file":this._emit("imageFileDone",r.image_file,p(this,se,"f"));break;case"text":this._emit("textDone",r.text,p(this,se,"f"));break}}p(this,se,"f")&&this._emit("messageDone",e.data),x(this,se,void 0)}},bs=function(e){const n=p(this,W,"m",Os).call(this,e);switch(x(this,qe,n),e.event){case"thread.run.step.created":this._emit("runStepCreated",e.data);break;case"thread.run.step.delta":const s=e.data.delta;if(s.step_details&&s.step_details.type=="tool_calls"&&s.step_details.tool_calls&&n.step_details.type=="tool_calls")for(const a of s.step_details.tool_calls)a.index==p(this,kt,"f")?this._emit("toolCallDelta",a,n.step_details.tool_calls[a.index]):(p(this,G,"f")&&this._emit("toolCallDone",p(this,G,"f")),x(this,kt,a.index),x(this,G,n.step_details.tool_calls[a.index]),p(this,G,"f")&&this._emit("toolCallCreated",p(this,G,"f")));this._emit("runStepDelta",e.data.delta,n);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":x(this,qe,void 0),e.data.step_details.type=="tool_calls"&&p(this,G,"f")&&(this._emit("toolCallDone",p(this,G,"f")),x(this,G,void 0)),this._emit("runStepDone",e.data,n);break}},vs=function(e){p(this,fn,"f").push(e),this._emit("event",e)},Os=function(e){switch(e.event){case"thread.run.step.created":return p(this,ae,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let n=p(this,ae,"f")[e.data.id];if(!n)throw Error("Received a RunStepDelta before creation of a snapshot");let s=e.data;if(s.delta){const r=ge.accumulateDelta(n,s.delta);p(this,ae,"f")[e.data.id]=r}return p(this,ae,"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":p(this,ae,"f")[e.data.id]=e.data;break}if(p(this,ae,"f")[e.data.id])return p(this,ae,"f")[e.data.id];throw new Error("No snapshot available")},xs=function(e,n){let s=[];switch(e.event){case"thread.message.created":return[e.data,s];case"thread.message.delta":if(!n)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let r=e.data;if(r.delta.content)for(const a of r.delta.content)if(a.index in n.content){let i=n.content[a.index];n.content[a.index]=p(this,W,"m",ks).call(this,a,i)}else n.content[a.index]=a,s.push(a);return[n,s];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(n)return[n,s];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},ks=function(e,n){return ge.accumulateDelta(n,e)},Is=function(e){switch(x(this,ft,e.data),e.event){case"thread.run.created":break;case"thread.run.queued":break;case"thread.run.in_progress":break;case"thread.run.requires_action":case"thread.run.cancelled":case"thread.run.failed":case"thread.run.completed":case"thread.run.expired":case"thread.run.incomplete":x(this,_e,e.data),p(this,G,"f")&&(this._emit("toolCallDone",p(this,G,"f")),x(this,G,void 0));break}};let Pn=class extends v{constructor(){super(...arguments),this.steps=new Gr(this._client)}create(e,n,s){const{include:r,...a}=n;return this._client.post(_`/threads/${e}/runs`,{query:{include:r},body:a,...s,headers:b([{"OpenAI-Beta":"assistants=v2"},s?.headers]),stream:n.stream??!1})}retrieve(e,n,s){const{thread_id:r}=n;return this._client.get(_`/threads/${r}/runs/${e}`,{...s,headers:b([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}update(e,n,s){const{thread_id:r,...a}=n;return this._client.post(_`/threads/${r}/runs/${e}`,{body:a,...s,headers:b([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}list(e,n={},s){return this._client.getAPIList(_`/threads/${e}/runs`,E,{query:n,...s,headers:b([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}cancel(e,n,s){const{thread_id:r}=n;return this._client.post(_`/threads/${r}/runs/${e}/cancel`,{...s,headers:b([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}async createAndPoll(e,n,s){const r=await this.create(e,n,s);return await this.poll(r.id,{thread_id:e},s)}createAndStream(e,n,s){return Je.createAssistantStream(e,this._client.beta.threads.runs,n,s)}async poll(e,n,s){const r=b([s?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":s?.pollIntervalMs?.toString()??void 0}]);for(;;){const{data:a,response:i}=await this.retrieve(e,n,{...s,headers:{...s?.headers,...r}}).withResponse();switch(a.status){case"queued":case"in_progress":case"cancelling":let o=5e3;if(s?.pollIntervalMs)o=s.pollIntervalMs;else{const l=i.headers.get("openai-poll-after-ms");if(l){const u=parseInt(l);isNaN(u)||(o=u)}}await Ze(o);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return a}}}stream(e,n,s){return Je.createAssistantStream(e,this._client.beta.threads.runs,n,s)}submitToolOutputs(e,n,s){const{thread_id:r,...a}=n;return this._client.post(_`/threads/${r}/runs/${e}/submit_tool_outputs`,{body:a,...s,headers:b([{"OpenAI-Beta":"assistants=v2"},s?.headers]),stream:n.stream??!1})}async submitToolOutputsAndPoll(e,n,s){const r=await this.submitToolOutputs(e,n,s);return await this.poll(r.id,n,s)}submitToolOutputsStream(e,n,s){return Je.createToolAssistantStream(e,this._client.beta.threads.runs,n,s)}};Pn.Steps=Gr;class Ut extends v{constructor(){super(...arguments),this.runs=new Pn(this._client),this.messages=new Xr(this._client)}create(e={},n){return this._client.post("/threads",{body:e,...n,headers:b([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}retrieve(e,n){return this._client.get(_`/threads/${e}`,{...n,headers:b([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}update(e,n,s){return this._client.post(_`/threads/${e}`,{body:n,...s,headers:b([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}delete(e,n){return this._client.delete(_`/threads/${e}`,{...n,headers:b([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}createAndRun(e,n){return this._client.post("/threads/runs",{body:e,...n,headers:b([{"OpenAI-Beta":"assistants=v2"},n?.headers]),stream:e.stream??!1})}async createAndRunPoll(e,n){const s=await this.createAndRun(e,n);return await this.runs.poll(s.id,{thread_id:s.thread_id},n)}createAndRunStream(e,n){return Je.createThreadAssistantStream(e,this._client.beta.threads,n)}}Ut.Runs=Pn;Ut.Messages=Xr;class Te extends v{constructor(){super(...arguments),this.realtime=new Lt(this._client),this.chatkit=new jt(this._client),this.assistants=new zr(this._client),this.threads=new Ut(this._client)}}Te.Realtime=Lt;Te.ChatKit=jt;Te.Assistants=zr;Te.Threads=Ut;class Qr extends v{create(e,n){return this._client.post("/completions",{body:e,...n,stream:e.stream??!1})}}class Yr extends v{retrieve(e,n,s){const{container_id:r}=n;return this._client.get(_`/containers/${r}/files/${e}/content`,{...s,headers:b([{Accept:"application/binary"},s?.headers]),__binaryResponse:!0})}}let Rn=class extends v{constructor(){super(...arguments),this.content=new Yr(this._client)}create(e,n,s){return this._client.post(_`/containers/${e}/files`,we({body:n,...s},this._client))}retrieve(e,n,s){const{container_id:r}=n;return this._client.get(_`/containers/${r}/files/${e}`,s)}list(e,n={},s){return this._client.getAPIList(_`/containers/${e}/files`,E,{query:n,...s})}delete(e,n,s){const{container_id:r}=n;return this._client.delete(_`/containers/${r}/files/${e}`,{...s,headers:b([{Accept:"*/*"},s?.headers])})}};Rn.Content=Yr;class $n extends v{constructor(){super(...arguments),this.files=new Rn(this._client)}create(e,n){return this._client.post("/containers",{body:e,...n})}retrieve(e,n){return this._client.get(_`/containers/${e}`,n)}list(e={},n){return this._client.getAPIList("/containers",E,{query:e,...n})}delete(e,n){return this._client.delete(_`/containers/${e}`,{...n,headers:b([{Accept:"*/*"},n?.headers])})}}$n.Files=Rn;class ea extends v{create(e,n,s){const{include:r,...a}=n;return this._client.post(_`/conversations/${e}/items`,{query:{include:r},body:a,...s})}retrieve(e,n,s){const{conversation_id:r,...a}=n;return this._client.get(_`/conversations/${r}/items/${e}`,{query:a,...s})}list(e,n={},s){return this._client.getAPIList(_`/conversations/${e}/items`,_t,{query:n,...s})}delete(e,n,s){const{conversation_id:r}=n;return this._client.delete(_`/conversations/${r}/items/${e}`,s)}}class En extends v{constructor(){super(...arguments),this.items=new ea(this._client)}create(e={},n){return this._client.post("/conversations",{body:e,...n})}retrieve(e,n){return this._client.get(_`/conversations/${e}`,n)}update(e,n,s){return this._client.post(_`/conversations/${e}`,{body:n,...s})}delete(e,n){return this._client.delete(_`/conversations/${e}`,n)}}En.Items=ea;class ta extends v{create(e,n){const s=!!e.encoding_format;let r=s?e.encoding_format:"base64";s&&B(this._client).debug("embeddings/user defined encoding_format:",e.encoding_format);const a=this._client.post("/embeddings",{body:{...e,encoding_format:r},...n});return s?a:(B(this._client).debug("embeddings/decoding base64 embeddings from base64"),a._thenUnwrap(i=>(i&&i.data&&i.data.forEach(o=>{const l=o.embedding;o.embedding=io(l)}),i)))}}class na extends v{retrieve(e,n,s){const{eval_id:r,run_id:a}=n;return this._client.get(_`/evals/${r}/runs/${a}/output_items/${e}`,s)}list(e,n,s){const{eval_id:r,...a}=n;return this._client.getAPIList(_`/evals/${r}/runs/${e}/output_items`,E,{query:a,...s})}}class Mn extends v{constructor(){super(...arguments),this.outputItems=new na(this._client)}create(e,n,s){return this._client.post(_`/evals/${e}/runs`,{body:n,...s})}retrieve(e,n,s){const{eval_id:r}=n;return this._client.get(_`/evals/${r}/runs/${e}`,s)}list(e,n={},s){return this._client.getAPIList(_`/evals/${e}/runs`,E,{query:n,...s})}delete(e,n,s){const{eval_id:r}=n;return this._client.delete(_`/evals/${r}/runs/${e}`,s)}cancel(e,n,s){const{eval_id:r}=n;return this._client.post(_`/evals/${r}/runs/${e}`,s)}}Mn.OutputItems=na;class Nn extends v{constructor(){super(...arguments),this.runs=new Mn(this._client)}create(e,n){return this._client.post("/evals",{body:e,...n})}retrieve(e,n){return this._client.get(_`/evals/${e}`,n)}update(e,n,s){return this._client.post(_`/evals/${e}`,{body:n,...s})}list(e={},n){return this._client.getAPIList("/evals",E,{query:e,...n})}delete(e,n){return this._client.delete(_`/evals/${e}`,n)}}Nn.Runs=Mn;let sa=class extends v{create(e,n){return this._client.post("/files",we({body:e,...n},this._client))}retrieve(e,n){return this._client.get(_`/files/${e}`,n)}list(e={},n){return this._client.getAPIList("/files",E,{query:e,...n})}delete(e,n){return this._client.delete(_`/files/${e}`,n)}content(e,n){return this._client.get(_`/files/${e}/content`,{...n,headers:b([{Accept:"application/binary"},n?.headers]),__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:n=5e3,maxWait:s=1800*1e3}={}){const r=new Set(["processed","error","deleted"]),a=Date.now();let i=await this.retrieve(e);for(;!i.status||!r.has(i.status);)if(await Ze(n),i=await this.retrieve(e),Date.now()-a>s)throw new $t({message:`Giving up on waiting for file ${e} to finish processing after ${s} milliseconds.`});return i}};class ra extends v{}let aa=class extends v{run(e,n){return this._client.post("/fine_tuning/alpha/graders/run",{body:e,...n})}validate(e,n){return this._client.post("/fine_tuning/alpha/graders/validate",{body:e,...n})}};class Ln extends v{constructor(){super(...arguments),this.graders=new aa(this._client)}}Ln.Graders=aa;class ia extends v{create(e,n,s){return this._client.getAPIList(_`/fine_tuning/checkpoints/${e}/permissions`,Nt,{body:n,method:"post",...s})}retrieve(e,n={},s){return this._client.get(_`/fine_tuning/checkpoints/${e}/permissions`,{query:n,...s})}delete(e,n,s){const{fine_tuned_model_checkpoint:r}=n;return this._client.delete(_`/fine_tuning/checkpoints/${r}/permissions/${e}`,s)}}let jn=class extends v{constructor(){super(...arguments),this.permissions=new ia(this._client)}};jn.Permissions=ia;class oa extends v{list(e,n={},s){return this._client.getAPIList(_`/fine_tuning/jobs/${e}/checkpoints`,E,{query:n,...s})}}class Un extends v{constructor(){super(...arguments),this.checkpoints=new oa(this._client)}create(e,n){return this._client.post("/fine_tuning/jobs",{body:e,...n})}retrieve(e,n){return this._client.get(_`/fine_tuning/jobs/${e}`,n)}list(e={},n){return this._client.getAPIList("/fine_tuning/jobs",E,{query:e,...n})}cancel(e,n){return this._client.post(_`/fine_tuning/jobs/${e}/cancel`,n)}listEvents(e,n={},s){return this._client.getAPIList(_`/fine_tuning/jobs/${e}/events`,E,{query:n,...s})}pause(e,n){return this._client.post(_`/fine_tuning/jobs/${e}/pause`,n)}resume(e,n){return this._client.post(_`/fine_tuning/jobs/${e}/resume`,n)}}Un.Checkpoints=oa;class Ae extends v{constructor(){super(...arguments),this.methods=new ra(this._client),this.jobs=new Un(this._client),this.checkpoints=new jn(this._client),this.alpha=new Ln(this._client)}}Ae.Methods=ra;Ae.Jobs=Un;Ae.Checkpoints=jn;Ae.Alpha=Ln;class ua extends v{}class Dn extends v{constructor(){super(...arguments),this.graderModels=new ua(this._client)}}Dn.GraderModels=ua;class la extends v{createVariation(e,n){return this._client.post("/images/variations",we({body:e,...n},this._client))}edit(e,n){return this._client.post("/images/edits",we({body:e,...n,stream:e.stream??!1},this._client))}generate(e,n){return this._client.post("/images/generations",{body:e,...n,stream:e.stream??!1})}}class ca extends v{retrieve(e,n){return this._client.get(_`/models/${e}`,n)}list(e){return this._client.getAPIList("/models",Nt,e)}delete(e,n){return this._client.delete(_`/models/${e}`,n)}}class da extends v{create(e,n){return this._client.post("/moderations",{body:e,...n})}}class pa extends v{accept(e,n,s){return this._client.post(_`/realtime/calls/${e}/accept`,{body:n,...s,headers:b([{Accept:"*/*"},s?.headers])})}hangup(e,n){return this._client.post(_`/realtime/calls/${e}/hangup`,{...n,headers:b([{Accept:"*/*"},n?.headers])})}refer(e,n,s){return this._client.post(_`/realtime/calls/${e}/refer`,{body:n,...s,headers:b([{Accept:"*/*"},s?.headers])})}reject(e,n={},s){return this._client.post(_`/realtime/calls/${e}/reject`,{body:n,...s,headers:b([{Accept:"*/*"},s?.headers])})}}class fa extends v{create(e,n){return this._client.post("/realtime/client_secrets",{body:e,...n})}}class Dt extends v{constructor(){super(...arguments),this.clientSecrets=new fa(this._client),this.calls=new pa(this._client)}}Dt.ClientSecrets=fa;Dt.Calls=pa;function uo(t,e){return!e||!co(e)?{...t,output_parsed:null,output:t.output.map(n=>n.type==="function_call"?{...n,parsed_arguments:null}:n.type==="message"?{...n,content:n.content.map(s=>({...s,parsed:null}))}:n)}:ha(t,e)}function ha(t,e){const n=t.output.map(r=>{if(r.type==="function_call")return{...r,parsed_arguments:ho(e,r)};if(r.type==="message"){const a=r.content.map(i=>i.type==="output_text"?{...i,parsed:lo(e,i.text)}:i);return{...r,content:a}}return r}),s=Object.assign({},t,{output:n});return Object.getOwnPropertyDescriptor(t,"output_text")||hn(s),Object.defineProperty(s,"output_parsed",{enumerable:!0,get(){for(const r of s.output)if(r.type==="message"){for(const a of r.content)if(a.type==="output_text"&&a.parsed!==null)return a.parsed}return null}}),s}function lo(t,e){return t.text?.format?.type!=="json_schema"?null:"$parseRaw"in t.text?.format?(t.text?.format).$parseRaw(e):JSON.parse(e)}function co(t){return!!kn(t.text?.format)}function po(t){return t?.$brand==="auto-parseable-tool"}function fo(t,e){return t.find(n=>n.type==="function"&&n.name===e)}function ho(t,e){const n=fo(t.tools??[],e.name);return{...e,...e,parsed_arguments:po(n)?n.$parseRaw(e.arguments):n?.strict?JSON.parse(e.arguments):null}}function hn(t){const e=[];for(const n of t.output)if(n.type==="message")for(const s of n.content)s.type==="output_text"&&e.push(s.text);t.output_text=e.join("")}var Oe,at,de,it,Ss,Cs,Ts,As;class Fn extends Sn{constructor(e){super(),Oe.add(this),at.set(this,void 0),de.set(this,void 0),it.set(this,void 0),x(this,at,e)}static createResponse(e,n,s){const r=new Fn(n);return r._run(()=>r._createOrRetrieveResponse(e,n,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),r}async _createOrRetrieveResponse(e,n,s){const r=s?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),p(this,Oe,"m",Ss).call(this);let a,i=null;"response_id"in n?(a=await e.responses.retrieve(n.response_id,{stream:!0},{...s,signal:this.controller.signal,stream:!0}),i=n.starting_after??null):a=await e.responses.create({...n,stream:!0},{...s,signal:this.controller.signal}),this._connected();for await(const o of a)p(this,Oe,"m",Cs).call(this,o,i);if(a.controller.signal?.aborted)throw new Y;return p(this,Oe,"m",Ts).call(this)}[(at=new WeakMap,de=new WeakMap,it=new WeakMap,Oe=new WeakSet,Ss=function(){this.ended||x(this,de,void 0)},Cs=function(n,s){if(this.ended)return;const r=(i,o)=>{(s==null||o.sequence_number>s)&&this._emit(i,o)},a=p(this,Oe,"m",As).call(this,n);switch(r("event",n),n.type){case"response.output_text.delta":{const i=a.output[n.output_index];if(!i)throw new O(`missing output at index ${n.output_index}`);if(i.type==="message"){const o=i.content[n.content_index];if(!o)throw new O(`missing content at index ${n.content_index}`);if(o.type!=="output_text")throw new O(`expected content to be 'output_text', got ${o.type}`);r("response.output_text.delta",{...n,snapshot:o.text})}break}case"response.function_call_arguments.delta":{const i=a.output[n.output_index];if(!i)throw new O(`missing output at index ${n.output_index}`);i.type==="function_call"&&r("response.function_call_arguments.delta",{...n,snapshot:i.arguments});break}default:r(n.type,n);break}},Ts=function(){if(this.ended)throw new O("stream has ended, this shouldn't happen");const n=p(this,de,"f");if(!n)throw new O("request ended without sending any events");x(this,de,void 0);const s=mo(n,p(this,at,"f"));return x(this,it,s),s},As=function(n){let s=p(this,de,"f");if(!s){if(n.type!=="response.created")throw new O(`When snapshot hasn't been set yet, expected 'response.created' event, got ${n.type}`);return s=x(this,de,n.response),s}switch(n.type){case"response.output_item.added":{s.output.push(n.item);break}case"response.content_part.added":{const r=s.output[n.output_index];if(!r)throw new O(`missing output at index ${n.output_index}`);const a=r.type,i=n.part;a==="message"&&i.type!=="reasoning_text"?r.content.push(i):a==="reasoning"&&i.type==="reasoning_text"&&(r.content||(r.content=[]),r.content.push(i));break}case"response.output_text.delta":{const r=s.output[n.output_index];if(!r)throw new O(`missing output at index ${n.output_index}`);if(r.type==="message"){const a=r.content[n.content_index];if(!a)throw new O(`missing content at index ${n.content_index}`);if(a.type!=="output_text")throw new O(`expected content to be 'output_text', got ${a.type}`);a.text+=n.delta}break}case"response.function_call_arguments.delta":{const r=s.output[n.output_index];if(!r)throw new O(`missing output at index ${n.output_index}`);r.type==="function_call"&&(r.arguments+=n.delta);break}case"response.reasoning_text.delta":{const r=s.output[n.output_index];if(!r)throw new O(`missing output at index ${n.output_index}`);if(r.type==="reasoning"){const a=r.content?.[n.content_index];if(!a)throw new O(`missing content at index ${n.content_index}`);if(a.type!=="reasoning_text")throw new O(`expected content to be 'reasoning_text', got ${a.type}`);a.text+=n.delta}break}case"response.completed":{x(this,de,n.response);break}}return s},Symbol.asyncIterator)](){const e=[],n=[];let s=!1;return this.on("event",r=>{const a=n.shift();a?a.resolve(r):e.push(r)}),this.on("end",()=>{s=!0;for(const r of n)r.resolve(void 0);n.length=0}),this.on("abort",r=>{s=!0;for(const a of n)a.reject(r);n.length=0}),this.on("error",r=>{s=!0;for(const a of n)a.reject(r);n.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:s?{value:void 0,done:!0}:new Promise((a,i)=>n.push({resolve:a,reject:i})).then(a=>a?{value:a,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();const e=p(this,it,"f");if(!e)throw new O("stream ended without producing a ChatCompletion");return e}}function mo(t,e){return uo(t,e)}class ma extends v{list(e,n={},s){return this._client.getAPIList(_`/responses/${e}/input_items`,E,{query:n,...s})}}class ga extends v{count(e={},n){return this._client.post("/responses/input_tokens",{body:e,...n})}}class Ft extends v{constructor(){super(...arguments),this.inputItems=new ma(this._client),this.inputTokens=new ga(this._client)}create(e,n){return this._client.post("/responses",{body:e,...n,stream:e.stream??!1})._thenUnwrap(s=>("object"in s&&s.object==="response"&&hn(s),s))}retrieve(e,n={},s){return this._client.get(_`/responses/${e}`,{query:n,...s,stream:n?.stream??!1})._thenUnwrap(r=>("object"in r&&r.object==="response"&&hn(r),r))}delete(e,n){return this._client.delete(_`/responses/${e}`,{...n,headers:b([{Accept:"*/*"},n?.headers])})}parse(e,n){return this._client.responses.create(e,n)._thenUnwrap(s=>ha(s,e))}stream(e,n){return Fn.createResponse(this._client,e,n)}cancel(e,n){return this._client.post(_`/responses/${e}/cancel`,n)}compact(e={},n){return this._client.post("/responses/compact",{body:e,...n})}}Ft.InputItems=ma;Ft.InputTokens=ga;class _a extends v{create(e,n,s){return this._client.post(_`/uploads/${e}/parts`,we({body:n,...s},this._client))}}class Bn extends v{constructor(){super(...arguments),this.parts=new _a(this._client)}create(e,n){return this._client.post("/uploads",{body:e,...n})}cancel(e,n){return this._client.post(_`/uploads/${e}/cancel`,n)}complete(e,n,s){return this._client.post(_`/uploads/${e}/complete`,{body:n,...s})}}Bn.Parts=_a;const go=async t=>{const e=await Promise.allSettled(t),n=e.filter(r=>r.status==="rejected");if(n.length){for(const r of n)console.error(r.reason);throw new Error(`${n.length} promise(s) failed - see the above errors`)}const s=[];for(const r of e)r.status==="fulfilled"&&s.push(r.value);return s};class ya extends v{create(e,n,s){return this._client.post(_`/vector_stores/${e}/file_batches`,{body:n,...s,headers:b([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}retrieve(e,n,s){const{vector_store_id:r}=n;return this._client.get(_`/vector_stores/${r}/file_batches/${e}`,{...s,headers:b([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}cancel(e,n,s){const{vector_store_id:r}=n;return this._client.post(_`/vector_stores/${r}/file_batches/${e}/cancel`,{...s,headers:b([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}async createAndPoll(e,n,s){const r=await this.create(e,n);return await this.poll(e,r.id,s)}listFiles(e,n,s){const{vector_store_id:r,...a}=n;return this._client.getAPIList(_`/vector_stores/${r}/file_batches/${e}/files`,E,{query:a,...s,headers:b([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}async poll(e,n,s){const r=b([s?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":s?.pollIntervalMs?.toString()??void 0}]);for(;;){const{data:a,response:i}=await this.retrieve(n,{vector_store_id:e},{...s,headers:r}).withResponse();switch(a.status){case"in_progress":let o=5e3;if(s?.pollIntervalMs)o=s.pollIntervalMs;else{const l=i.headers.get("openai-poll-after-ms");if(l){const u=parseInt(l);isNaN(u)||(o=u)}}await Ze(o);break;case"failed":case"cancelled":case"completed":return a}}}async uploadAndPoll(e,{files:n,fileIds:s=[]},r){if(n==null||n.length==0)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");const a=r?.maxConcurrency??5,i=Math.min(a,n.length),o=this._client,l=n.values(),u=[...s];async function h(f){for(let d of f){const w=await o.files.create({file:d,purpose:"assistants"},r);u.push(w.id)}}const c=Array(i).fill(l).map(h);return await go(c),await this.createAndPoll(e,{file_ids:u})}}class wa extends v{create(e,n,s){return this._client.post(_`/vector_stores/${e}/files`,{body:n,...s,headers:b([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}retrieve(e,n,s){const{vector_store_id:r}=n;return this._client.get(_`/vector_stores/${r}/files/${e}`,{...s,headers:b([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}update(e,n,s){const{vector_store_id:r,...a}=n;return this._client.post(_`/vector_stores/${r}/files/${e}`,{body:a,...s,headers:b([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}list(e,n={},s){return this._client.getAPIList(_`/vector_stores/${e}/files`,E,{query:n,...s,headers:b([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}delete(e,n,s){const{vector_store_id:r}=n;return this._client.delete(_`/vector_stores/${r}/files/${e}`,{...s,headers:b([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}async createAndPoll(e,n,s){const r=await this.create(e,n,s);return await this.poll(e,r.id,s)}async poll(e,n,s){const r=b([s?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":s?.pollIntervalMs?.toString()??void 0}]);for(;;){const a=await this.retrieve(n,{vector_store_id:e},{...s,headers:r}).withResponse(),i=a.data;switch(i.status){case"in_progress":let o=5e3;if(s?.pollIntervalMs)o=s.pollIntervalMs;else{const l=a.response.headers.get("openai-poll-after-ms");if(l){const u=parseInt(l);isNaN(u)||(o=u)}}await Ze(o);break;case"failed":case"completed":return i}}}async upload(e,n,s){const r=await this._client.files.create({file:n,purpose:"assistants"},s);return this.create(e,{file_id:r.id},s)}async uploadAndPoll(e,n,s){const r=await this.upload(e,n,s);return await this.poll(e,r.id,s)}content(e,n,s){const{vector_store_id:r}=n;return this._client.getAPIList(_`/vector_stores/${r}/files/${e}/content`,Nt,{...s,headers:b([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}}class Bt extends v{constructor(){super(...arguments),this.files=new wa(this._client),this.fileBatches=new ya(this._client)}create(e,n){return this._client.post("/vector_stores",{body:e,...n,headers:b([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}retrieve(e,n){return this._client.get(_`/vector_stores/${e}`,{...n,headers:b([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}update(e,n,s){return this._client.post(_`/vector_stores/${e}`,{body:n,...s,headers:b([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}list(e={},n){return this._client.getAPIList("/vector_stores",E,{query:e,...n,headers:b([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}delete(e,n){return this._client.delete(_`/vector_stores/${e}`,{...n,headers:b([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}search(e,n,s){return this._client.getAPIList(_`/vector_stores/${e}/search`,Nt,{body:n,method:"post",...s,headers:b([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}}Bt.Files=wa;Bt.FileBatches=ya;class ba extends v{create(e,n){return this._client.post("/videos",hs({body:e,...n},this._client))}retrieve(e,n){return this._client.get(_`/videos/${e}`,n)}list(e={},n){return this._client.getAPIList("/videos",_t,{query:e,...n})}delete(e,n){return this._client.delete(_`/videos/${e}`,n)}downloadContent(e,n={},s){return this._client.get(_`/videos/${e}/content`,{query:n,...s,headers:b([{Accept:"application/binary"},s?.headers]),__binaryResponse:!0})}remix(e,n,s){return this._client.post(_`/videos/${e}/remix`,hs({body:n,...s},this._client))}}var Ie,va,ht;class Oa extends v{constructor(){super(...arguments),Ie.add(this)}async unwrap(e,n,s=this._client.webhookSecret,r=300){return await this.verifySignature(e,n,s,r),JSON.parse(e)}async verifySignature(e,n,s=this._client.webhookSecret,r=300){if(typeof crypto>"u"||typeof crypto.subtle.importKey!="function"||typeof crypto.subtle.verify!="function")throw new Error("Webhook signature verification is only supported when the `crypto` global is defined");p(this,Ie,"m",va).call(this,s);const a=b([n]).values,i=p(this,Ie,"m",ht).call(this,a,"webhook-signature"),o=p(this,Ie,"m",ht).call(this,a,"webhook-timestamp"),l=p(this,Ie,"m",ht).call(this,a,"webhook-id"),u=parseInt(o,10);if(isNaN(u))throw new $e("Invalid webhook timestamp format");const h=Math.floor(Date.now()/1e3);if(h-u>r)throw new $e("Webhook timestamp is too old");if(u>h+r)throw new $e("Webhook timestamp is too new");const c=i.split(" ").map(y=>y.startsWith("v1,")?y.substring(3):y),f=s.startsWith("whsec_")?Buffer.from(s.replace("whsec_",""),"base64"):Buffer.from(s,"utf-8"),d=l?`${l}.${o}.${e}`:`${o}.${e}`,w=await crypto.subtle.importKey("raw",f,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(const y of c)try{const C=Buffer.from(y,"base64");if(await crypto.subtle.verify("HMAC",w,C,new TextEncoder().encode(d)))return}catch{continue}throw new $e("The given webhook signature does not match the expected signature")}}Ie=new WeakSet,va=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")},ht=function(e,n){if(!e)throw new Error("Headers are required");const s=e.get(n);if(s==null)throw new Error(`Missing required header: ${n}`);return s};var mn,Wn,mt,xa;class S{constructor({baseURL:e=ve("OPENAI_BASE_URL"),apiKey:n=ve("OPENAI_API_KEY"),organization:s=ve("OPENAI_ORG_ID")??null,project:r=ve("OPENAI_PROJECT_ID")??null,webhookSecret:a=ve("OPENAI_WEBHOOK_SECRET")??null,...i}={}){if(mn.add(this),mt.set(this,void 0),this.completions=new Qr(this),this.chat=new An(this),this.embeddings=new ta(this),this.files=new sa(this),this.images=new la(this),this.audio=new Ve(this),this.moderations=new da(this),this.models=new ca(this),this.fineTuning=new Ae(this),this.graders=new Dn(this),this.vectorStores=new Bt(this),this.webhooks=new Oa(this),this.beta=new Te(this),this.batches=new Jr(this),this.uploads=new Bn(this),this.responses=new Ft(this),this.realtime=new Dt(this),this.conversations=new En(this),this.evals=new Nn(this),this.containers=new $n(this),this.videos=new ba(this),n===void 0)throw new O("Missing credentials. Please pass an `apiKey`, or set the `OPENAI_API_KEY` environment variable.");const o={apiKey:n,organization:s,project:r,webhookSecret:a,...i,baseURL:e||"https://api.openai.com/v1"};if(!o.dangerouslyAllowBrowser&&mi())throw new O(`It looks like you're running in a browser-like environment.
18
+
19
+ This is disabled by default, as it risks exposing your secret API credentials to attackers.
20
+ If you understand the risks and have appropriate mitigations in place,
21
+ you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
22
+
23
+ new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
24
+
25
+ https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
26
+ `);this.baseURL=o.baseURL,this.timeout=o.timeout??Wn.DEFAULT_TIMEOUT,this.logger=o.logger??console;const l="warn";this.logLevel=l,this.logLevel=ps(o.logLevel,"ClientOptions.logLevel",this)??ps(ve("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??l,this.fetchOptions=o.fetchOptions,this.maxRetries=o.maxRetries??2,this.fetch=o.fetch??bi(),x(this,mt,Oi),this._options=o,this.apiKey=typeof n=="string"?n:"Missing Key",this.organization=s,this.project=r,this.webhookSecret=a}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:n}){}async authHeaders(e){return b([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return Ti(e,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${xe}`}defaultIdempotencyKey(){return`stainless-node-retry-${Ks()}`}makeStatusError(e,n,s,r){return q.generate(e,n,s,r)}async _callApiKey(){const e=this._options.apiKey;if(typeof e!="function")return!1;let n;try{n=await e()}catch(s){throw s instanceof O?s:new O(`Failed to get token from 'apiKey' function: ${s.message}`,{cause:s})}if(typeof n!="string"||!n)throw new O(`Expected 'apiKey' function argument to return a string but it returned ${n}`);return this.apiKey=n,!0}buildURL(e,n,s){const r=!p(this,mn,"m",xa).call(this)&&s||this.baseURL,a=ci(e)?new URL(e):new URL(r+(r.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),i=this.defaultQuery();return di(i)||(n={...i,...n}),typeof n=="object"&&n&&!Array.isArray(n)&&(a.search=this.stringifyQuery(n)),a.toString()}async prepareOptions(e){await this._callApiKey()}async prepareRequest(e,{url:n,options:s}){}get(e,n){return this.methodRequest("get",e,n)}post(e,n){return this.methodRequest("post",e,n)}patch(e,n){return this.methodRequest("patch",e,n)}put(e,n){return this.methodRequest("put",e,n)}delete(e,n){return this.methodRequest("delete",e,n)}methodRequest(e,n,s){return this.request(Promise.resolve(s).then(r=>({method:e,path:n,...r})))}request(e,n=null){return new Mt(this,this.makeRequest(e,n,void 0))}async makeRequest(e,n,s){const r=await e,a=r.maxRetries??this.maxRetries;n==null&&(n=a),await this.prepareOptions(r);const{req:i,url:o,timeout:l}=await this.buildRequest(r,{retryCount:a-n});await this.prepareRequest(i,{url:o,options:r});const u="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),h=s===void 0?"":`, retryOf: ${s}`,c=Date.now();if(B(this).debug(`[${u}] sending request`,fe({retryOfRequestLogID:s,method:r.method,url:o,options:r,headers:i.headers})),r.signal?.aborted)throw new Y;const f=new AbortController,d=await this.fetchWithTimeout(o,i,l,f).catch(nn),w=Date.now();if(d instanceof globalThis.Error){const m=`retrying, ${n} attempts remaining`;if(r.signal?.aborted)throw new Y;const g=tn(d)||/timed? ?out/i.test(String(d)+("cause"in d?String(d.cause):""));if(n)return B(this).info(`[${u}] connection ${g?"timed out":"failed"} - ${m}`),B(this).debug(`[${u}] connection ${g?"timed out":"failed"} (${m})`,fe({retryOfRequestLogID:s,url:o,durationMs:w-c,message:d.message})),this.retryRequest(r,n,s??u);throw B(this).info(`[${u}] connection ${g?"timed out":"failed"} - error; no more retries left`),B(this).debug(`[${u}] connection ${g?"timed out":"failed"} (error; no more retries left)`,fe({retryOfRequestLogID:s,url:o,durationMs:w-c,message:d.message})),g?new $t:new Rt({cause:d})}const y=[...d.headers.entries()].filter(([m])=>m==="x-request-id").map(([m,g])=>", "+m+": "+JSON.stringify(g)).join(""),C=`[${u}${h}${y}] ${i.method} ${o} ${d.ok?"succeeded":"failed"} with status ${d.status} in ${w-c}ms`;if(!d.ok){const m=await this.shouldRetry(d);if(n&&m){const R=`retrying, ${n} attempts remaining`;return await vi(d.body),B(this).info(`${C} - ${R}`),B(this).debug(`[${u}] response error (${R})`,fe({retryOfRequestLogID:s,url:d.url,status:d.status,headers:d.headers,durationMs:w-c})),this.retryRequest(r,n,s??u,d.headers)}const g=m?"error; no more retries left":"error; not retryable";B(this).info(`${C} - ${g}`);const k=await d.text().catch(R=>nn(R).message),A=hi(k),K=A?void 0:k;throw B(this).debug(`[${u}] response error (${g})`,fe({retryOfRequestLogID:s,url:d.url,status:d.status,headers:d.headers,message:K,durationMs:Date.now()-c})),this.makeStatusError(d.status,A,K,d.headers)}return B(this).info(C),B(this).debug(`[${u}] response start`,fe({retryOfRequestLogID:s,url:d.url,status:d.status,headers:d.headers,durationMs:w-c})),{response:d,options:r,controller:f,requestLogID:u,retryOfRequestLogID:s,startTime:c}}getAPIList(e,n,s){return this.requestAPIList(n,{method:"get",path:e,...s})}requestAPIList(e,n){const s=this.makeRequest(n,null,void 0);return new ji(this,s,e)}async fetchWithTimeout(e,n,s,r){const{signal:a,method:i,...o}=n||{};a&&a.addEventListener("abort",()=>r.abort());const l=setTimeout(()=>r.abort(),s),u=globalThis.ReadableStream&&o.body instanceof globalThis.ReadableStream||typeof o.body=="object"&&o.body!==null&&Symbol.asyncIterator in o.body,h={signal:r.signal,...u?{duplex:"half"}:{},method:"GET",...o};i&&(h.method=i.toUpperCase());try{return await this.fetch.call(void 0,e,h)}finally{clearTimeout(l)}}async shouldRetry(e){const n=e.headers.get("x-should-retry");return n==="true"?!0:n==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,n,s,r){let a;const i=r?.get("retry-after-ms");if(i){const l=parseFloat(i);Number.isNaN(l)||(a=l)}const o=r?.get("retry-after");if(o&&!a){const l=parseFloat(o);Number.isNaN(l)?a=Date.parse(o)-Date.now():a=l*1e3}if(!(a&&0<=a&&a<60*1e3)){const l=e.maxRetries??this.maxRetries;a=this.calculateDefaultRetryTimeoutMillis(n,l)}return await Ze(a),this.makeRequest(e,n-1,s)}calculateDefaultRetryTimeoutMillis(e,n){const a=n-e,i=Math.min(.5*Math.pow(2,a),8),o=1-Math.random()*.25;return i*o*1e3}async buildRequest(e,{retryCount:n=0}={}){const s={...e},{method:r,path:a,query:i,defaultBaseURL:o}=s,l=this.buildURL(a,i,o);"timeout"in s&&fi("timeout",s.timeout),s.timeout=s.timeout??this.timeout;const{bodyHeaders:u,body:h}=this.buildBody({options:s}),c=await this.buildHeaders({options:e,method:r,bodyHeaders:u,retryCount:n});return{req:{method:r,headers:c,...s.signal&&{signal:s.signal},...globalThis.ReadableStream&&h instanceof globalThis.ReadableStream&&{duplex:"half"},...h&&{body:h},...this.fetchOptions??{},...s.fetchOptions??{}},url:l,timeout:s.timeout}}async buildHeaders({options:e,method:n,bodyHeaders:s,retryCount:r}){let a={};this.idempotencyHeader&&n!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),a[this.idempotencyHeader]=e.idempotencyKey);const i=b([a,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(r),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...wi(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders(e),this._options.defaultHeaders,s,e.headers]);return this.validateHeaders(i),i.values}buildBody({options:{body:e,headers:n}}){if(!e)return{bodyHeaders:void 0,body:void 0};const s=b([n]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&s.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:ar(e)}:p(this,mt,"f").call(this,{body:e,headers:s})}}Wn=S,mt=new WeakMap,mn=new WeakSet,xa=function(){return this.baseURL!=="https://api.openai.com/v1"};S.OpenAI=Wn;S.DEFAULT_TIMEOUT=6e5;S.OpenAIError=O;S.APIError=q;S.APIConnectionError=Rt;S.APIConnectionTimeoutError=$t;S.APIUserAbortError=Y;S.NotFoundError=Xs;S.ConflictError=Gs;S.RateLimitError=Ys;S.BadRequestError=Zs;S.AuthenticationError=Hs;S.InternalServerError=er;S.PermissionDeniedError=Vs;S.UnprocessableEntityError=Qs;S.InvalidWebhookSignatureError=$e;S.toFile=Wi;S.Completions=Qr;S.Chat=An;S.Embeddings=ta;S.Files=sa;S.Images=la;S.Audio=Ve;S.Moderations=da;S.Models=ca;S.FineTuning=Ae;S.Graders=Dn;S.VectorStores=Bt;S.Webhooks=Oa;S.Beta=Te;S.Batches=Jr;S.Uploads=Bn;S.Responses=Ft;S.Realtime=Dt;S.Conversations=En;S.Evals=Nn;S.Containers=$n;S.Videos=ba;function qn(t){if(!t||typeof t!="object")return t;let e;return t.constructor.name===$t.name&&"message"in t&&typeof t.message=="string"?(e=new Error(t.message),e.name="TimeoutError"):t.constructor.name===Y.name&&"message"in t&&typeof t.message=="string"?(e=new Error(t.message),e.name="AbortError"):"status"in t&&t.status===400&&"message"in t&&typeof t.message=="string"&&t.message.includes("tool_calls")?e=Ye(t,"INVALID_TOOL_RESULTS"):"status"in t&&t.status===401?e=Ye(t,"MODEL_AUTHENTICATION"):"status"in t&&t.status===429?e=Ye(t,"MODEL_RATE_LIMIT"):"status"in t&&t.status===404?e=Ye(t,"MODEL_NOT_FOUND"):e=t,e}const ye=t=>t();function Xe(t){return t?!!(/^o\d/.test(t??"")||t.startsWith("gpt-5")&&!t.startsWith("gpt-5-chat")):!1}function _o(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 It(t){const e=t.metadata?.filename??t.metadata?.name??t.metadata?.title;if(!e)throw new Error("a filename or name or title is needed via meta-data for OpenAI when working with multimodal blocks");return e}function Ge(t){const e=t._getType();switch(e){case"system":return"system";case"ai":return"assistant";case"human":return"user";case"function":return"function";case"tool":return"tool";case"generic":if(!js.isInstance(t))throw new Error("Invalid generic chat message");return _o(t);default:throw new Error(`Unknown message type: ${e}`)}}function yo(t){return t.includes("gpt-5.2-pro")}function wo(t){const{azureOpenAIApiDeploymentName:e,azureOpenAIApiInstanceName:n,azureOpenAIApiKey:s,azureOpenAIBasePath:r,baseURL:a,azureADTokenProvider:i,azureOpenAIEndpoint:o}=t;if((s||i)&&r&&e)return`${r}/${e}`;if((s||i)&&o&&e)return`${o}/openai/deployments/${e}`;if(s||i){if(!n)throw new Error("azureOpenAIApiInstanceName is required when using azureOpenAIApiKey");if(!e)throw new Error("azureOpenAIApiDeploymentName is a required parameter when using azureOpenAIApiKey");return`https://${n}.openai.azure.com/openai/deployments/${e}`}return a}function Ps(t){return typeof Headers<"u"&&t!==null&&typeof t=="object"&&Object.prototype.toString.call(t)==="[object Headers]"}function bo(t){const e=ye(()=>{if(Ps(t))return t;if(Array.isArray(t))return new Headers(t);if(typeof t=="object"&&t!==null&&"values"in t&&Ps(t.values))return t.values;if(typeof t=="object"&&t!==null){const n=Object.entries(t).filter(([,s])=>typeof s=="string").map(([s,r])=>[s,r]);return new Headers(n)}return new Headers});return Object.fromEntries(e.entries())}function vo(){let t=Da();return(t==="node"||t==="deno")&&(t=`(${t}/${process.version}; browser; ${process.arch})`),t}function Oo(t,e=!1,n="1.0.0"){const s=bo(t),r=vo(),a=`langchainjs${e?"-azure":""}-openai`;return{...s,"User-Agent":s["User-Agent"]?`${a}/${n} (${r})${s["User-Agent"]}`:`${a}/${n} (${r})`}}function xo(t,e){let n;return ri(t)?n=ti(t):n=t,e?.strict!==void 0&&(n.function.strict=e.strict),n}function ko(t){return t.anyOf!==void 0&&Array.isArray(t.anyOf)}function Io(t){const e=["namespace functions {",""];for(const n of t)n.description&&e.push(`// ${n.description}`),Object.keys(n.parameters.properties??{}).length>0?(e.push(`type ${n.name} = (_: {`),e.push(ka(n.parameters,0)),e.push("}) => any;")):e.push(`type ${n.name} = () => any;`),e.push("");return e.push("} // namespace functions"),e.join(`
27
+ `)}function ka(t,e){const n=[];for(const[s,r]of Object.entries(t.properties??{}))r.description&&e<2&&n.push(`// ${r.description}`),t.required?.includes(s)?n.push(`${s}: ${St(r,e)},`):n.push(`${s}?: ${St(r,e)},`);return n.map(s=>" ".repeat(e)+s).join(`
28
+ `)}function St(t,e){if(ko(t))return t.anyOf.map(n=>St(n,e)).join(" | ");switch(t.type){case"string":return t.enum?t.enum.map(n=>`"${n}"`).join(" | "):"string";case"number":return t.enum?t.enum.map(n=>`${n}`).join(" | "):"number";case"integer":return t.enum?t.enum.map(n=>`${n}`).join(" | "):"number";case"boolean":return"boolean";case"null":return"null";case"object":return["{",ka(t,e+2),"}"].join(`
29
+ `);case"array":return t.items?`${St(t.items,e)}[]`:"any[]";default:return""}}function Ia(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 Jn(t){return"type"in t&&t.type!=="function"}function So(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 Co(t){return t!=null&&typeof t=="object"&&"type"in t&&t.type!=="function"}function Ct(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 Sa(t){return"type"in t&&t.type==="custom"&&"custom"in t&&typeof t.custom=="object"&&t.custom!==null}function To(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 Ao(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 Po(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="tool_call"&&"isComputerTool"in t&&t.isComputerTool===!0}function Ro(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="tool_call"&&"isCustomTool"in t&&t.isCustomTool===!0}function $o(t){const e=()=>{if(t.custom.format){if(t.custom.format.type==="grammar")return{type:"grammar",definition:t.custom.format.grammar.definition,syntax:t.custom.format.grammar.syntax};if(t.custom.format.type==="text")return{type:"text"}}};return{type:"custom",name:t.custom.name,description:t.custom.description,format:e()}}function Eo(t){const e=()=>{if(t.format){if(t.format.type==="grammar")return{type:"grammar",grammar:{definition:t.format.definition,syntax:t.format.syntax}};if(t.format.type==="text")return{type:"text"}}};return{type:"custom",custom:{name:t.name,description:t.description,format:e()}}}const Mo=Symbol("Let zodToJsonSchema decide on which parser to use"),Rs={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"},No=t=>typeof t=="string"?{...Rs,basePath:["#"],definitions:{},name:t}:{...Rs,basePath:["#"],definitions:{},...t},gn=t=>"_def"in t?t._def:t;function Lo(t){if(!t)return!0;for(const e in t)return!1;return!0}const jo=t=>{const e=No(t),n=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,currentPath:n,propertyPath:void 0,seenRefs:new Set,seen:new Map(Object.entries(e.definitions).map(([s,r])=>[gn(r),{def:gn(r),path:[...e.basePath,e.definitionPath,s],jsonSchema:void 0}]))}};function Ca(t,e,n,s){s?.errorMessages&&n&&(t.errorMessage={...t.errorMessage,[e]:n})}function P(t,e,n,s,r){t[e]=n,Ca(t,e,s,r)}function Uo(){return{}}function Do(t,e){const n={type:"array"};return t.type?._def?.typeName!==I.ZodAny&&(n.items=T(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&P(n,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&P(n,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(P(n,"minItems",t.exactLength.value,t.exactLength.message,e),P(n,"maxItems",t.exactLength.value,t.exactLength.message,e)),n}function Fo(t,e){const n={type:"integer",format:"int64"};if(!t.checks)return n;for(const s of t.checks)switch(s.kind){case"min":e.target==="jsonSchema7"?s.inclusive?P(n,"minimum",s.value,s.message,e):P(n,"exclusiveMinimum",s.value,s.message,e):(s.inclusive||(n.exclusiveMinimum=!0),P(n,"minimum",s.value,s.message,e));break;case"max":e.target==="jsonSchema7"?s.inclusive?P(n,"maximum",s.value,s.message,e):P(n,"exclusiveMaximum",s.value,s.message,e):(s.inclusive||(n.exclusiveMaximum=!0),P(n,"maximum",s.value,s.message,e));break;case"multipleOf":P(n,"multipleOf",s.value,s.message,e);break}return n}function Bo(){return{type:"boolean"}}function Wo(t,e){return T(t.type._def,e)}const qo=(t,e)=>T(t.innerType._def,e);function Ta(t,e,n){const s=n??e.dateStrategy;if(Array.isArray(s))return{anyOf:s.map((r,a)=>Ta(t,e,r))};switch(s){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return Jo(t,e)}}const Jo=(t,e)=>{const n={type:"integer",format:"unix-time"};if(e.target==="openApi3")return n;for(const s of t.checks)switch(s.kind){case"min":P(n,"minimum",s.value,s.message,e);break;case"max":P(n,"maximum",s.value,s.message,e);break}return n};function zo(t,e){return{...T(t.innerType._def,e),default:t.defaultValue()}}function Ko(t,e,n){return e.effectStrategy==="input"?T(t.schema._def,e,n):{}}function Zo(t){return{type:"string",enum:[...t.values]}}const Ho=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function Vo(t,e){const n=[T(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),T(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(a=>!!a);let s=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0;const r=[];return n.forEach(a=>{if(Ho(a))r.push(...a.allOf),a.unevaluatedProperties===void 0&&(s=void 0);else{let i=a;if("additionalProperties"in a&&a.additionalProperties===!1){const{additionalProperties:o,...l}=a;i=l}else s=void 0;r.push(i)}}),r.length?{allOf:r,...s}:void 0}function Xo(t,e){const n=typeof t.value;return n!=="bigint"&&n!=="number"&&n!=="boolean"&&n!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:n==="bigint"?"integer":n,enum:[t.value]}:{type:n==="bigint"?"integer":n,const:t.value}}let Yt;const pe={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:()=>(Yt===void 0&&(Yt=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Yt),base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/};function Aa(t,e){const n={type:"string"};function s(r){return e.patternStrategy==="escape"?Go(r):r}if(t.checks)for(const r of t.checks)switch(r.kind){case"min":P(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,r.message,e);break;case"max":P(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value,r.message,e);break;case"email":switch(e.emailStrategy){case"format:email":te(n,"email",r.message,e);break;case"format:idn-email":te(n,"idn-email",r.message,e);break;case"pattern:zod":ne(n,pe.email,r.message,e);break}break;case"url":te(n,"uri",r.message,e);break;case"uuid":te(n,"uuid",r.message,e);break;case"regex":ne(n,r.regex,r.message,e);break;case"cuid":ne(n,pe.cuid,r.message,e);break;case"cuid2":ne(n,pe.cuid2,r.message,e);break;case"startsWith":ne(n,RegExp(`^${s(r.value)}`),r.message,e);break;case"endsWith":ne(n,RegExp(`${s(r.value)}$`),r.message,e);break;case"datetime":te(n,"date-time",r.message,e);break;case"date":te(n,"date",r.message,e);break;case"time":te(n,"time",r.message,e);break;case"duration":te(n,"duration",r.message,e);break;case"length":P(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,r.message,e),P(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value,r.message,e);break;case"includes":{ne(n,RegExp(s(r.value)),r.message,e);break}case"ip":{r.version!=="v6"&&te(n,"ipv4",r.message,e),r.version!=="v4"&&te(n,"ipv6",r.message,e);break}case"emoji":ne(n,pe.emoji,r.message,e);break;case"ulid":{ne(n,pe.ulid,r.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{te(n,"binary",r.message,e);break}case"contentEncoding:base64":{P(n,"contentEncoding","base64",r.message,e);break}case"pattern:zod":{ne(n,pe.base64,r.message,e);break}}break}case"nanoid":ne(n,pe.nanoid,r.message,e)}return n}const Go=t=>Array.from(t).map(e=>/[a-zA-Z0-9]/.test(e)?e:`\\${e}`).join(""),te=(t,e,n,s)=>{t.format||t.anyOf?.some(r=>r.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&s.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...n&&s.errorMessages&&{errorMessage:{format:n}}})):P(t,"format",e,n,s)},ne=(t,e,n,s)=>{t.pattern||t.allOf?.some(r=>r.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&s.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:$s(e,s),...n&&s.errorMessages&&{errorMessage:{pattern:n}}})):P(t,"pattern",$s(e,s),n,s)},$s=(t,e)=>{const n=typeof t=="function"?t():t;if(!e.applyRegexFlags||!n.flags)return n.source;const s={i:n.flags.includes("i"),m:n.flags.includes("m"),s:n.flags.includes("s")},r=s.i?n.source.toLowerCase():n.source;let a="",i=!1,o=!1,l=!1;for(let u=0;u<r.length;u++){if(i){a+=r[u],i=!1;continue}if(s.i){if(o){if(r[u].match(/[a-z]/)){l?(a+=r[u],a+=`${r[u-2]}-${r[u]}`.toUpperCase(),l=!1):r[u+1]==="-"&&r[u+2]?.match(/[a-z]/)?(a+=r[u],l=!0):a+=`${r[u]}${r[u].toUpperCase()}`;continue}}else if(r[u].match(/[a-z]/)){a+=`[${r[u]}${r[u].toUpperCase()}]`;continue}}if(s.m){if(r[u]==="^"){a+=`(^|(?<=[\r
30
+ ]))`;continue}else if(r[u]==="$"){a+=`($|(?=[\r
31
+ ]))`;continue}}if(s.s&&r[u]==="."){a+=o?`${r[u]}\r
32
+ `:`[${r[u]}\r
33
+ ]`;continue}a+=r[u],r[u]==="\\"?i=!0:o&&r[u]==="]"?o=!1:!o&&r[u]==="["&&(o=!0)}try{const u=new RegExp(a)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),n.source}return a};function Pa(t,e){if(e.target==="openApi3"&&t.keyType?._def.typeName===I.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((s,r)=>({...s,[r]:T(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",r]})??{}}),{}),additionalProperties:!1};const n={type:"object",additionalProperties:T(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??{}};if(e.target==="openApi3")return n;if(t.keyType?._def.typeName===I.ZodString&&t.keyType._def.checks?.length){const s=Object.entries(Aa(t.keyType._def,e)).reduce((r,[a,i])=>a==="type"?r:{...r,[a]:i},{});return{...n,propertyNames:s}}else if(t.keyType?._def.typeName===I.ZodEnum)return{...n,propertyNames:{enum:t.keyType._def.values}};return n}function Qo(t,e){if(e.mapStrategy==="record")return Pa(t,e);const n=T(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},s=T(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||{};return{type:"array",maxItems:125,items:{type:"array",items:[n,s],minItems:2,maxItems:2}}}function Yo(t){const e=t.values,s=Object.keys(t.values).filter(a=>typeof e[e[a]]!="number").map(a=>e[a]),r=Array.from(new Set(s.map(a=>typeof a)));return{type:r.length===1?r[0]==="string"?"string":"number":["string","number"],enum:s}}function eu(){return{not:{}}}function tu(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}const Tt={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function nu(t,e){if(e.target==="openApi3")return Es(t,e);const n=t.options instanceof Map?Array.from(t.options.values()):t.options;if(n.every(s=>s._def.typeName in Tt&&(!s._def.checks||!s._def.checks.length))){const s=n.reduce((r,a)=>{const i=Tt[a._def.typeName];return i&&!r.includes(i)?[...r,i]:r},[]);return{type:s.length>1?s:s[0]}}else if(n.every(s=>s._def.typeName==="ZodLiteral"&&!s.description)){const s=n.reduce((r,a)=>{const i=typeof a._def.value;switch(i){case"string":case"number":case"boolean":return[...r,i];case"bigint":return[...r,"integer"];case"object":if(a._def.value===null)return[...r,"null"];case"symbol":case"undefined":case"function":default:return r}},[]);if(s.length===n.length){const r=s.filter((a,i,o)=>o.indexOf(a)===i);return{type:r.length>1?r:r[0],enum:n.reduce((a,i)=>a.includes(i._def.value)?a:[...a,i._def.value],[])}}}else if(n.every(s=>s._def.typeName==="ZodEnum"))return{type:"string",enum:n.reduce((s,r)=>[...s,...r._def.values.filter(a=>!s.includes(a))],[])};return Es(t,e)}const Es=(t,e)=>{const n=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((s,r)=>T(s._def,{...e,currentPath:[...e.currentPath,"anyOf",`${r}`]})).filter(s=>!!s&&(!e.strictUnions||typeof s=="object"&&Object.keys(s).length>0));return n.length?{anyOf:n}:void 0};function su(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"||e.nullableStrategy==="property"?{type:Tt[t.innerType._def.typeName],nullable:!0}:{type:[Tt[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){const s=T(t.innerType._def,{...e,currentPath:[...e.currentPath]});return s&&"$ref"in s?{allOf:[s],nullable:!0}:s&&{...s,nullable:!0}}const n=T(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}function ru(t,e){const n={type:"number"};if(!t.checks)return n;for(const s of t.checks)switch(s.kind){case"int":n.type="integer",Ca(n,"type",s.message,e);break;case"min":e.target==="jsonSchema7"?s.inclusive?P(n,"minimum",s.value,s.message,e):P(n,"exclusiveMinimum",s.value,s.message,e):(s.inclusive||(n.exclusiveMinimum=!0),P(n,"minimum",s.value,s.message,e));break;case"max":e.target==="jsonSchema7"?s.inclusive?P(n,"maximum",s.value,s.message,e):P(n,"exclusiveMaximum",s.value,s.message,e):(s.inclusive||(n.exclusiveMaximum=!0),P(n,"maximum",s.value,s.message,e));break;case"multipleOf":P(n,"multipleOf",s.value,s.message,e);break}return n}function au(t,e){return e.removeAdditionalStrategy==="strict"?t.catchall._def.typeName==="ZodNever"?t.unknownKeys!=="strict":T(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0:t.catchall._def.typeName==="ZodNever"?t.unknownKeys==="passthrough":T(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0}function iu(t,e){const n={type:"object",...Object.entries(t.shape()).reduce((s,[r,a])=>{if(a===void 0||a._def===void 0)return s;const i=[...e.currentPath,"properties",r],o=T(a._def,{...e,currentPath:i,propertyPath:i});if(o===void 0)return s;if(e.openaiStrictMode&&a.isOptional()&&!a.isNullable()&&typeof a._def?.defaultValue>"u")throw new Error(`Zod field at \`${i.join("/")}\` uses \`.optional()\` without \`.nullable()\` which is not supported by the API. See: https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses#all-fields-must-be-required`);return{properties:{...s.properties,[r]:o},required:a.isOptional()&&!e.openaiStrictMode?s.required:[...s.required,r]}},{properties:{},required:[]}),additionalProperties:au(t,e)};return n.required.length||delete n.required,n}const ou=(t,e)=>{if(e.propertyPath&&e.currentPath.slice(0,e.propertyPath.length).toString()===e.propertyPath.toString())return T(t.innerType._def,{...e,currentPath:e.currentPath});const n=T(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return n?{anyOf:[{not:{}},n]}:{}},uu=(t,e)=>{if(e.pipeStrategy==="input")return T(t.in._def,e);if(e.pipeStrategy==="output")return T(t.out._def,e);const n=T(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),s=T(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",n?"1":"0"]});return{allOf:[n,s].filter(r=>r!==void 0)}};function lu(t,e){return T(t.type._def,e)}function cu(t,e){const s={type:"array",uniqueItems:!0,items:T(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&P(s,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&P(s,"maxItems",t.maxSize.value,t.maxSize.message,e),s}function du(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((n,s)=>T(n._def,{...e,currentPath:[...e.currentPath,"items",`${s}`]})).reduce((n,s)=>s===void 0?n:[...n,s],[]),additionalItems:T(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((n,s)=>T(n._def,{...e,currentPath:[...e.currentPath,"items",`${s}`]})).reduce((n,s)=>s===void 0?n:[...n,s],[])}}function pu(){return{not:{}}}function fu(){return{}}const hu=(t,e)=>T(t.innerType._def,e);function T(t,e,n=!1){const s=e.seen.get(t);if(e.override){const i=e.override?.(t,e,s,n);if(i!==Mo)return i}if(s&&!n){const i=mu(s,e);if(i!==void 0)return"$ref"in i&&e.seenRefs.add(i.$ref),i}const r={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,r);const a=_u(t,t.typeName,e,n);return a&&yu(t,e,a),r.jsonSchema=a,a}const mu=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"extract-to-root":const n=t.path.slice(e.basePath.length+1).join("_");return n!==e.name&&e.nameStrategy==="duplicate-ref"&&(e.definitions[n]=t.def),{$ref:[...e.basePath,e.definitionPath,n].join("/")};case"relative":return{$ref:gu(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((s,r)=>e.currentPath[r]===s)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),{}):e.$refStrategy==="seen"?{}:void 0}},gu=(t,e)=>{let n=0;for(;n<t.length&&n<e.length&&t[n]===e[n];n++);return[(t.length-n).toString(),...e.slice(n)].join("/")},_u=(t,e,n,s)=>{switch(e){case I.ZodString:return Aa(t,n);case I.ZodNumber:return ru(t,n);case I.ZodObject:return iu(t,n);case I.ZodBigInt:return Fo(t,n);case I.ZodBoolean:return Bo();case I.ZodDate:return Ta(t,n);case I.ZodUndefined:return pu();case I.ZodNull:return tu(n);case I.ZodArray:return Do(t,n);case I.ZodUnion:case I.ZodDiscriminatedUnion:return nu(t,n);case I.ZodIntersection:return Vo(t,n);case I.ZodTuple:return du(t,n);case I.ZodRecord:return Pa(t,n);case I.ZodLiteral:return Xo(t,n);case I.ZodEnum:return Zo(t);case I.ZodNativeEnum:return Yo(t);case I.ZodNullable:return su(t,n);case I.ZodOptional:return ou(t,n);case I.ZodMap:return Qo(t,n);case I.ZodSet:return cu(t,n);case I.ZodLazy:return T(t.getter()._def,n);case I.ZodPromise:return lu(t,n);case I.ZodNaN:case I.ZodNever:return eu();case I.ZodEffects:return Ko(t,n,s);case I.ZodAny:return Uo();case I.ZodUnknown:return fu();case I.ZodDefault:return zo(t,n);case I.ZodBranded:return Wo(t,n);case I.ZodReadonly:return hu(t,n);case I.ZodCatch:return qo(t,n);case I.ZodPipeline:return uu(t,n);case I.ZodFunction:case I.ZodVoid:case I.ZodSymbol:return;default:return(r=>{})()}},yu=(t,e,n)=>(t.description&&(n.description=t.description,e.markdownDescription&&(n.markdownDescription=t.description)),n),wu=(t,e)=>{const n=jo(e),s=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,r=T(t._def,s===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,s]},!1)??{},a=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;a!==void 0&&(r.title=a);const i=(()=>{if(Lo(n.definitions))return;const l={},u=new Set;for(let h=0;h<500;h++){const c=Object.entries(n.definitions).filter(([f])=>!u.has(f));if(c.length===0)break;for(const[f,d]of c)l[f]=T(gn(d),{...n,currentPath:[...n.basePath,n.definitionPath,f]},!0)??{},u.add(f)}return l})(),o=s===void 0?i?{...r,[n.definitionPath]:i}:r:n.nameStrategy==="duplicate-ref"?{...r,...i||n.seenRefs.size?{[n.definitionPath]:{...i,...n.seenRefs.size?{[s]:r}:void 0}}:void 0}:{$ref:[...n.$refStrategy==="relative"?[]:n.basePath,n.definitionPath,s].join("/"),[n.definitionPath]:{...i,[s]:r}};return n.target==="jsonSchema7"?o.$schema="http://json-schema.org/draft-07/schema#":n.target==="jsonSchema2019-09"&&(o.$schema="https://json-schema.org/draft/2019-09/schema#"),o};function bu(t){if(t.type!=="object")throw new Error(`Root schema must have type: 'object' but got type: ${t.type?`'${t.type}'`:"undefined"}`);const e=structuredClone(t);return le(e,[],e)}function _n(t){if(typeof t=="boolean")return!1;if(t.type==="null")return!0;for(const e of t.oneOf??[])if(_n(e))return!0;for(const e of t.anyOf??[])if(_n(e))return!0;return!1}function le(t,e,n){if(typeof t=="boolean")throw new TypeError(`Expected object schema but got boolean; path=${e.join("/")}`);if(!he(t))throw new TypeError(`Expected ${JSON.stringify(t)} to be an object; path=${e.join("/")}`);const s=t.$defs;if(he(s))for(const[f,d]of Object.entries(s))le(d,[...e,"$defs",f],n);const r=t.definitions;if(he(r))for(const[f,d]of Object.entries(r))le(d,[...e,"definitions",f],n);t.type==="object"&&!("additionalProperties"in t)&&(t.additionalProperties=!1);const i=t.required??[],o=t.properties;if(he(o)){for(const[f,d]of Object.entries(o))if(!_n(d)&&!i.includes(f))throw new Error(`Zod field at \`${[...e,"properties",f].join("/")}\` uses \`.optional()\` without \`.nullable()\` which is not supported by the API. See: https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses#all-fields-must-be-required`);t.required=Object.keys(o),t.properties=Object.fromEntries(Object.entries(o).map(([f,d])=>[f,le(d,[...e,"properties",f],n)]))}const l=t.items;he(l)&&(t.items=le(l,[...e,"items"],n));const u=t.anyOf;Array.isArray(u)&&(t.anyOf=u.map((f,d)=>le(f,[...e,"anyOf",String(d)],n)));const h=t.allOf;if(Array.isArray(h))if(h.length===1){const f=le(h[0],[...e,"allOf","0"],n);Object.assign(t,f),delete t.allOf}else t.allOf=h.map((f,d)=>le(f,[...e,"allOf",String(d)],n));t.default===null&&delete t.default;const c=t.$ref;if(c&&Ou(t,1)){if(typeof c!="string")throw new TypeError(`Received non-string $ref - ${c}; path=${e.join("/")}`);const f=vu(n,c);if(typeof f=="boolean")throw new Error(`Expected \`$ref: ${c}\` to resolve to an object schema but got boolean`);if(!he(f))throw new Error(`Expected \`$ref: ${c}\` to resolve to an object but got ${JSON.stringify(f)}`);return Object.assign(t,{...f,...t}),delete t.$ref,le(t,e,n)}return t}function vu(t,e){if(!e.startsWith("#/"))throw new Error(`Unexpected $ref format ${JSON.stringify(e)}; Does not start with #/`);const n=e.slice(2).split("/");let s=t;for(const r of n){if(!he(s))throw new Error(`encountered non-object entry while resolving ${e} - ${JSON.stringify(s)}`);const a=s[r];if(a===void 0)throw new Error(`Key ${r} not found while resolving ${e}`);s=a}return s}function he(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Ou(t,e){let n=0;for(const s in t)if(n++,n>e)return!0;return!1}function xu(t,e){return wu(t,{openaiStrictMode:!0,name:e.name,nameStrategy:"duplicate-ref",$refStrategy:"extract-to-root",nullableStrategy:"property"})}function ku(t){return bu(ii(t,{target:"draft-7"}))}function Iu(t){return"_zod"in t}function Su(t,e,n){return zi({type:"json_schema",json_schema:{...n,name:e,strict:!0,schema:Iu(t)?ku(t):xu(t,{name:e})}},s=>t.parse(JSON.parse(s)))}const Ms=["jsonSchema","functionCalling","jsonMode"];function Cu(t,e){if(typeof e<"u"&&!Ms.includes(e))throw new Error(`Invalid method: ${e}. Supported methods are: ${Ms.join(", ")}`);const n=!t.startsWith("gpt-3")&&!t.startsWith("gpt-4-")&&t!=="gpt-4";if(n&&!e)return"jsonSchema";if(!n&&e==="jsonSchema")throw new Error(`JSON Schema is not supported for model "${t}". Please use a different method, e.g. "functionCalling" or "jsonMode".`);return e??"functionCalling"}function Tu(t,e){const n={...t};return Object.defineProperties(n,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:e,enumerable:!1}}),n}function Au(t,e,n){if(Fa(t))return Su(t,e,n);if(Ba(t))return Tu({type:"json_schema",json_schema:{...n,name:e,strict:!0,schema:Re(t,{cycles:"ref",reused:"ref",override(s){s.jsonSchema.title=e}})}},s=>oi(t,JSON.parse(s)));throw new Error("Unsupported schema response format")}function Pu(t,e){if(e&&typeof e=="object"&&"images"in e&&Array.isArray(e.images)){const n=e.images.filter(s=>typeof s?.image_url?.url=="string").map(s=>({type:"image",url:s.image_url.url}));return[{type:"text",text:t},...n]}return t}const Ru={"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-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":{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},"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-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-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-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},"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},"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},"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-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},"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},"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},"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-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},"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-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},"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},"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},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-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},"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},"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},"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-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},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},"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-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},"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},"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},"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}};var $u=Ru;function Wt(t,e){if(t.function===void 0)return;let n;if(e?.partial)try{n=qa(t.function.arguments??"{}")}catch{return}else try{n=JSON.parse(t.function.arguments)}catch(r){throw new qs([`Function "${t.function.name}" arguments:`,"",t.function.arguments,"","are not valid JSON.",`Error: ${r.message}`].join(`
34
+ `))}const s={name:t.function.name,args:n,type:"tool_call"};return e?.returnId&&(s.id=t.id),s}function Ra(t){if(t.id===void 0)throw new Error('All OpenAI tool calls must have an "id" field.');return{id:t.id,type:"function",function:{name:t.name,arguments:JSON.stringify(t.args)}}}function ze(t,e){return{name:t.function?.name,args:t.function?.arguments,id:t.id,error:e,type:"invalid_tool_call"}}var $a=class extends ni{static lc_name(){return"JsonOutputToolsParser"}returnId=!1;lc_namespace=["langchain","output_parsers","openai_tools"];lc_serializable=!0;constructor(t){super(t),this.returnId=t?.returnId??this.returnId}_diff(){throw new Error("Not supported.")}async parse(){throw new Error("Not implemented.")}async parseResult(t){return await this.parsePartialResult(t,!1)}async parsePartialResult(t,e=!0){const n=t[0].message;let s;if(Us(n)&&n.tool_calls?.length?s=n.tool_calls.map(a=>{const{id:i,...o}=a;return this.returnId?{id:i,...o}:o}):n.additional_kwargs.tool_calls!==void 0&&(s=JSON.parse(JSON.stringify(n.additional_kwargs.tool_calls)).map(i=>Wt(i,{returnId:this.returnId,partial:e}))),!s)return[];const r=[];for(const a of s)if(a!==void 0){const i={type:a.name,args:a.args,id:a.id};r.push(i)}return r}},yn=class extends $a{static lc_name(){return"JsonOutputKeyToolsParser"}lc_namespace=["langchain","output_parsers","openai_tools"];lc_serializable=!0;returnId=!1;keyName;returnSingle=!1;zodSchema;constructor(t){super(t),this.keyName=t.keyName,this.returnSingle=t.returnSingle??this.returnSingle,this.zodSchema=t.zodSchema}async _validateResult(t){if(this.zodSchema===void 0)return t;const e=await Wa(this.zodSchema,t);if(e.success)return e.data;throw new qs(`Failed to parse. Text: "${JSON.stringify(t,null,2)}". Error: ${JSON.stringify(e.error?.issues)}`,JSON.stringify(t,null,2))}async parsePartialResult(t){const n=(await super.parsePartialResult(t)).filter(r=>r.type===this.keyName);let s=n;if(n.length)return this.returnId||(s=n.map(r=>r.args)),this.returnSingle?s[0]:s}async parseResult(t){const n=(await super.parsePartialResult(t,!1)).filter(a=>a.type===this.keyName);let s=n;return n.length?(this.returnId||(s=n.map(a=>a.args)),this.returnSingle?this._validateResult(s[0]):await Promise.all(s.map(a=>this._validateResult(a)))):void 0}},Eu={};Ds(Eu,{JsonOutputKeyToolsParser:()=>yn,JsonOutputToolsParser:()=>$a,convertLangChainToolCallToOpenAI:()=>Ra,makeInvalidToolCall:()=>ze,parseToolCall:()=>Wt});var zn=class extends si{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","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){const e=this.invocationParams(t);return{ls_provider:"openai",ls_model_name:this.model,ls_model_type:"chat",ls_temperature:e.temperature??void 0,ls_max_tokens:e.max_tokens??void 0,ls_stop:t.stop}}_identifyingParams(){return{model_name:this.model,...this.invocationParams(),...this.clientConfig}}identifyingParams(){return this._identifyingParams()}constructor(t){super(t??{});const e=typeof t?.configuration?.apiKey=="string"||typeof t?.configuration?.apiKey=="function"?t?.configuration?.apiKey:void 0;this.apiKey=t?.apiKey??e??Hn("OPENAI_API_KEY"),this.organization=t?.configuration?.organization??Hn("OPENAI_ORGANIZATION"),this.model=t?.model??t?.modelName??this.model,this.modelKwargs=t?.modelKwargs??{},this.timeout=t?.timeout,this.temperature=t?.temperature??this.temperature,this.topP=t?.topP??this.topP,this.frequencyPenalty=t?.frequencyPenalty??this.frequencyPenalty,this.presencePenalty=t?.presencePenalty??this.presencePenalty,this.logprobs=t?.logprobs,this.topLogprobs=t?.topLogprobs,this.n=t?.n??this.n,this.logitBias=t?.logitBias,this.stop=t?.stopSequences??t?.stop,this.stopSequences=this.stop,this.user=t?.user,this.__includeRawResponse=t?.__includeRawResponse,this.audio=t?.audio,this.modalities=t?.modalities,this.reasoning=t?.reasoning,this.maxTokens=t?.maxCompletionTokens??t?.maxTokens,this.promptCacheKey=t?.promptCacheKey??this.promptCacheKey,this.promptCacheRetention=t?.promptCacheRetention??this.promptCacheRetention,this.verbosity=t?.verbosity??this.verbosity,this.disableStreaming=t?.disableStreaming===!0,this.streaming=t?.streaming===!0,this.disableStreaming&&(this.streaming=!1),t?.streaming===!1&&(this.disableStreaming=!0),this.streamUsage=t?.streamUsage??this.streamUsage,this.disableStreaming&&(this.streamUsage=!1),this.clientConfig={apiKey:this.apiKey,organization:this.organization,dangerouslyAllowBrowser:!0,...t?.configuration},t?.supportsStrictToolCalling!==void 0&&(this.supportsStrictToolCalling=t.supportsStrictToolCalling),t?.service_tier!==void 0&&(this.service_tier=t.service_tier),this.zdrEnabled=t?.zdrEnabled??!1}_getReasoningParams(t){if(!Xe(this.model))return;let e;return this.reasoning!==void 0&&(e={...e,...this.reasoning}),t?.reasoning!==void 0&&(e={...e,...t.reasoning}),e}_getResponseFormat(t){return t&&t.type==="json_schema"&&t.json_schema.schema&&Qe(t.json_schema.schema)?Au(t.json_schema.schema,t.json_schema.name,{description:t.json_schema.description}):t}_combineCallOptions(t){return{...this.defaultOptions,...t??{}}}_getClientOptions(t){if(!this.client){const n={baseURL:this.clientConfig.baseURL},s=wo(n),r={...this.clientConfig,baseURL:s,timeout:this.timeout,maxRetries:0};r.baseURL||delete r.baseURL,r.defaultHeaders=Oo(r.defaultHeaders),this.client=new S(r)}return{...this.clientConfig,...t}}_convertChatOpenAIToolToCompletionsTool(t,e){return Ct(t)?Eo(t.metadata.customTool):Js(t)?e?.strict!==void 0?{...t,function:{...t.function,strict:e.strict}}:t:xo(t,e)}bindTools(t,e){let n;return e?.strict!==void 0?n=e.strict:this.supportsStrictToolCalling!==void 0&&(n=this.supportsStrictToolCalling),this.withConfig({tools:t.map(s=>Jn(s)||Ct(s)?s:So(s)?s.extras.providerToolDefinition:this._convertChatOpenAIToolToCompletionsTool(s,{strict:n})),...e})}async stream(t,e){return super.stream(t,this._combineCallOptions(e))}async invoke(t,e){return super.invoke(t,this._combineCallOptions(e))}_combineLLMOutput(...t){return t.reduce((e,n)=>(n&&n.tokenUsage&&(e.tokenUsage.completionTokens+=n.tokenUsage.completionTokens??0,e.tokenUsage.promptTokens+=n.tokenUsage.promptTokens??0,e.tokenUsage.totalTokens+=n.tokenUsage.totalTokens??0),e),{tokenUsage:{completionTokens:0,promptTokens:0,totalTokens:0}})}async getNumTokensFromMessages(t){let e=0,n=0,s=0;this.model==="gpt-3.5-turbo-0301"?(n=4,s=-1):(n=3,s=1);const r=await Promise.all(t.map(async a=>{const i=await this.getNumTokens(a.content),o=await this.getNumTokens(Ge(a)),l=a.name!==void 0?s+await this.getNumTokens(a.name):0;let u=i+n+o+l;const h=a;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(c){console.error("Error parsing function arguments",c,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:r}}async _getNumTokensFromGenerations(t){return(await Promise.all(t.map(async n=>n.message.additional_kwargs?.function_call?(await this.getNumTokensFromMessages([n.message])).countPerMessage[0]:await this.getNumTokens(n.message.content)))).reduce((n,s)=>n+s,0)}async _getEstimatedTokenCountFromPrompt(t,e,n){let s=(await this.getNumTokensFromMessages(t)).totalCount;if(e&&n!=="auto"){const r=Io(e);s+=await this.getNumTokens(r),s+=9}return e&&t.find(r=>r._getType()==="system")&&(s-=4),n==="none"?s+=1:typeof n=="object"&&(s+=await this.getNumTokens(n.name)+4),s}async moderateContent(t,e){const n=this._getClientOptions(e?.options),s=e?.model??"omni-moderation-latest",r={input:t,model:s};return this.caller.call(async()=>{try{return await this.client.moderations.create(r,n)}catch(a){throw qn(a)}})}get profile(){return $u[this.model]??{}}_getStructuredOutputMethod(t){const e={...t};if(!this.model.startsWith("gpt-3")&&!this.model.startsWith("gpt-4-")&&this.model!=="gpt-4"){if(e?.method===void 0)return"jsonSchema"}else e.method==="jsonSchema"&&console.warn(`[WARNING]: JSON Schema is not supported for model "${this.model}". Falling back to tool calling.`);return e.method}withStructuredOutput(t,e){let n,s;const{schema:r,name:a,includeRaw:i}={...e,schema:t};if(e?.strict!==void 0&&e.method==="jsonMode")throw new Error("Argument `strict` is only supported for `method` = 'function_calling'");const o=Cu(this.model,e?.method);if(o==="jsonMode"){Qe(r)?s=Yn.fromZodSchema(r):s=new es;const c=Re(r);n=this.withConfig({outputVersion:"v0",response_format:{type:"json_object"},ls_structured_output_format:{kwargs:{method:"json_mode"},schema:{title:a??"extract",...c}}})}else if(o==="jsonSchema"){const c={name:a??"extract",description:Ja(r),schema:r,strict:e?.strict},f=Re(c.schema);if(n=this.withConfig({outputVersion:"v0",response_format:{type:"json_schema",json_schema:c},ls_structured_output_format:{kwargs:{method:"json_schema"},schema:{title:c.name,description:c.description,...f}}}),Qe(r)){const d=Yn.fromZodSchema(r);s=za.from(w=>"parsed"in w.additional_kwargs?w.additional_kwargs.parsed:d)}else s=new es}else{let c=a??"extract";if(Qe(r)){const f=Re(r);n=this.withConfig({outputVersion:"v0",tools:[{type:"function",function:{name:c,description:f.description,parameters:f}}],tool_choice:{type:"function",function:{name:c}},ls_structured_output_format:{kwargs:{method:"function_calling"},schema:{title:c,...f}},...e?.strict!==void 0?{strict:e.strict}:{}}),s=new yn({returnSingle:!0,keyName:c,zodSchema:r})}else{let f;typeof r.name=="string"&&typeof r.parameters=="object"&&r.parameters!=null?(f=r,c=r.name):(c=r.title??c,f={name:c,description:r.description??"",parameters:r});const d=Re(r);n=this.withConfig({outputVersion:"v0",tools:[{type:"function",function:f}],tool_choice:{type:"function",function:{name:c}},ls_structured_output_format:{kwargs:{method:"function_calling"},schema:{title:c,...d}},...e?.strict!==void 0?{strict:e.strict}:{}}),s=new yn({returnSingle:!0,keyName:c})}}if(!i)return n.pipe(s);const l=ts.assign({parsed:(c,f)=>s.invoke(c.raw,f)}),u=ts.assign({parsed:()=>null}),h=l.withFallbacks({fallbacks:[u]});return Ka.from([{raw:n},h])}};const Ea={providerName:"ChatOpenAI",fromStandardTextBlock(t){return{type:"text",text:t.text}},fromStandardImageBlock(t){if(t.source_type==="url")return{type:"image_url",image_url:{url:t.url,...t.metadata?.detail?{detail:t.metadata.detail}:{}}};if(t.source_type==="base64")return{type:"image_url",image_url:{url:`data:${t.mime_type??""};base64,${t.data}`,...t.metadata?.detail?{detail:t.metadata.detail}:{}}};throw new Error(`Image content blocks with source_type ${t.source_type} are not supported for ChatOpenAI`)},fromStandardAudioBlock(t){if(t.source_type==="url"){const e=Xn({dataUrl:t.url});if(!e)throw new Error(`URL audio blocks with source_type ${t.source_type} must be formatted as a data URL for ChatOpenAI`);const n=e.mime_type||t.mime_type||"";let s;try{s=Gn(n)}catch{throw new Error(`Audio blocks with source_type ${t.source_type} must have mime type of audio/wav or audio/mp3`)}if(s.type!=="audio"||s.subtype!=="wav"&&s.subtype!=="mp3")throw new Error(`Audio blocks with source_type ${t.source_type} must have mime type of audio/wav or audio/mp3`);return{type:"input_audio",input_audio:{format:s.subtype,data:e.data}}}if(t.source_type==="base64"){let e;try{e=Gn(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"){const e=Xn({dataUrl:t.url}),n=It(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,...t.metadata?.filename||t.metadata?.name?{filename:n}:{}}}}if(t.source_type==="base64"){const e=It(t);return{type:"file",file:{file_data:`data:${t.mime_type??""};base64,${t.data}`,...t.metadata?.filename||t.metadata?.name||t.metadata?.title?{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`)}},Mu=({message:t,rawResponse:e,includeRawResponse:n})=>{const s=t.tool_calls;switch(t.role){case"assistant":{const r=[],a=[];for(const u of s??[])try{r.push(Wt(u,{returnId:!0}))}catch(h){a.push(ze(u,h.message))}const i={function_call:t.function_call,tool_calls:s};n!==void 0&&(i.__raw_response=e);const o={model_provider:"openai",model_name:e.model,...e.system_fingerprint?{usage:{...e.usage},system_fingerprint:e.system_fingerprint}:{}};t.audio&&(i.audio=t.audio);const l=Pu(t.content||"",e.choices?.[0]?.message);return new Ce({content:l,tool_calls:r,invalid_tool_calls:a,additional_kwargs:i,response_metadata:o,id:e.id})}default:return new js(t.content||"",t.role??"unknown")}},Nu=({delta:t,rawResponse:e,includeRawResponse:n,defaultRole:s})=>{const r=t.role??s,a=t.content??"";let i;t.function_call?i={function_call:t.function_call}:t.tool_calls?i={tool_calls:t.tool_calls}:i={},n&&(i.__raw_response=e),t.audio&&(i.audio={...t.audio,index:e.choices[0].index});const o={model_provider:"openai",usage:{...e.usage}};if(r==="user")return new Za({content:a,response_metadata:o});if(r==="assistant"){const l=[];if(Array.isArray(t.tool_calls))for(const u of t.tool_calls)l.push({name:u.function?.name,args:u.function?.arguments,id:u.id,index:u.index,type:"tool_call_chunk"});return new wn({content:a,tool_call_chunks:l,additional_kwargs:i,id:e.id,response_metadata:o})}else return r==="system"?new Vn({content:a,response_metadata:o}):r==="developer"?new Vn({content:a,response_metadata:o,additional_kwargs:{__openai_role__:"developer"}}):r==="function"?new Ha({content:a,additional_kwargs:i,name:t.name,response_metadata:o}):r==="tool"?new Va({content:a,additional_kwargs:i,tool_call_id:t.tool_call_id,response_metadata:o}):new Xa({content:a,role:r,response_metadata:o})},Lu=t=>{if(t.type==="image"){if(t.url)return{type:"image_url",image_url:{url:t.url}};if(t.data)return{type:"image_url",image_url:{url:`data:${t.mimeType};base64,${t.data}`}}}if(t.type==="audio"&&t.data){const e=Ga(()=>{const[,n]=t.mimeType.split("/");return n==="wav"||n==="mp3"?n:"wav"});return{type:"input_audio",input_audio:{data:t.data.toString(),format:e}}}if(t.type==="file"){if(t.data){const e=It(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}}}},ju=({message:t,model:e})=>{let n=Ge(t);if(n==="system"&&Xe(e)&&(n="developer"),n==="developer")return{role:"developer",content:t.contentBlocks.filter(r=>r.type==="text")};if(n==="system")return{role:"system",content:t.contentBlocks.filter(r=>r.type==="text")};if(n==="assistant")return{role:"assistant",content:t.contentBlocks.filter(r=>r.type==="text")};if(n==="tool"&&Ws.isInstance(t))return{role:"tool",tool_call_id:t.tool_call_id,content:t.contentBlocks.filter(r=>r.type==="text")};if(n==="function")return{role:"function",name:t.name??"",content:t.contentBlocks.filter(r=>r.type==="text").join("")};function*s(r){for(const a of r){a.type==="text"&&(yield{type:"text",text:a.text});const i=Lu(a);i&&(yield i)}}return{role:"user",content:Array.from(s(t.contentBlocks))}},Ns=({messages:t,model:e})=>t.flatMap(n=>{if("output_version"in n.response_metadata&&n.response_metadata?.output_version==="v1")return ju({message:n});let s=Ge(n);s==="system"&&Xe(e)&&(s="developer");const r=typeof n.content=="string"?n.content:n.content.map(i=>Fs(i)?Bs(i,Ea):i),a={role:s,content:r};if(n.name!=null&&(a.name=n.name),n.additional_kwargs.function_call!=null&&(a.function_call=n.additional_kwargs.function_call),Ce.isInstance(n)&&n.tool_calls?.length?a.tool_calls=n.tool_calls.map(Ra):(n.additional_kwargs.tool_calls!=null&&(a.tool_calls=n.additional_kwargs.tool_calls),Ws.isInstance(n)&&n.tool_call_id!=null&&(a.tool_call_id=n.tool_call_id)),n.additional_kwargs.audio&&typeof n.additional_kwargs.audio=="object"&&"id"in n.additional_kwargs.audio){const i={role:"assistant",audio:{id:n.additional_kwargs.audio.id}};return[a,i]}return a});var Uu=class extends zn{invocationParams(t,e){let n;t?.strict!==void 0?n=t.strict:this.supportsStrictToolCalling!==void 0&&(n=this.supportsStrictToolCalling);let s={};t?.stream_options!==void 0?s={stream_options:t.stream_options}:this.streamUsage&&(this.streaming||e?.streaming)&&(s={stream_options:{include_usage:!0}});const r={model:this.model,temperature:this.temperature,top_p:this.topP,frequency_penalty:this.frequencyPenalty,presence_penalty:this.presencePenalty,logprobs:this.logprobs,top_logprobs:this.topLogprobs,n:this.n,logit_bias:this.logitBias,stop:t?.stop??this.stopSequences,user:this.user,stream:this.streaming,functions:t?.functions,function_call:t?.function_call,tools:t?.tools?.length?t.tools.map(i=>this._convertChatOpenAIToolToCompletionsTool(i,{strict:n})):void 0,tool_choice:Ia(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&&(r.prediction=t.prediction),this.service_tier!==void 0&&(r.service_tier=this.service_tier),t?.service_tier!==void 0&&(r.service_tier=t.service_tier);const a=this._getReasoningParams(t);return a!==void 0&&a.effort!==void 0&&(r.reasoning_effort=a.effort),Xe(r.model)?r.max_completion_tokens=this.maxTokens===-1?void 0:this.maxTokens:r.max_tokens=this.maxTokens===-1?void 0:this.maxTokens,r}async _generate(t,e,n){const s={},r=this.invocationParams(e),a=Ns({messages:t,model:this.model});if(r.stream){const i=this._streamResponseChunks(t,e,n),o={};for await(const d of i){d.message.response_metadata={...d.generationInfo,...d.message.response_metadata};const w=d.generationInfo?.completion??0;o[w]===void 0?o[w]=d:o[w]=o[w].concat(d)}const l=Object.entries(o).sort(([d],[w])=>parseInt(d,10)-parseInt(w,10)).map(([d,w])=>w),{functions:u,function_call:h}=this.invocationParams(e),c=await this._getEstimatedTokenCountFromPrompt(t,u,h),f=await this._getNumTokensFromGenerations(l);return s.input_tokens=c,s.output_tokens=f,s.total_tokens=c+f,{generations:l,llmOutput:{estimatedTokenUsage:{promptTokens:s.input_tokens,completionTokens:s.output_tokens,totalTokens:s.total_tokens}}}}else{const i=await this.completionWithRetry({...r,stream:!1,messages:a},{signal:e?.signal,...e?.options}),{completion_tokens:o,prompt_tokens:l,total_tokens:u,prompt_tokens_details:h,completion_tokens_details:c}=i?.usage??{};o&&(s.output_tokens=(s.output_tokens??0)+o),l&&(s.input_tokens=(s.input_tokens??0)+l),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}}),(c?.audio_tokens!==null||c?.reasoning_tokens!==null)&&(s.output_token_details={...c?.audio_tokens!==null&&{audio:c?.audio_tokens},...c?.reasoning_tokens!==null&&{reasoning:c?.reasoning_tokens}});const f=[];for(const d of i?.choices??[]){const y={text:d.message?.content??"",message:this._convertCompletionsMessageToBaseMessage(d.message??{role:"assistant"},i)};y.generationInfo={...d.finish_reason?{finish_reason:d.finish_reason}:{},...d.logprobs?{logprobs:d.logprobs}:{}},Us(y.message)&&(y.message.usage_metadata=s),y.message=new Ce(Object.fromEntries(Object.entries(y.message).filter(([C])=>!C.startsWith("lc_")))),f.push(y)}return{generations:f,llmOutput:{tokenUsage:{promptTokens:s.input_tokens,completionTokens:s.output_tokens,totalTokens:s.total_tokens}}}}}async*_streamResponseChunks(t,e,n){const s=Ns({messages:t,model:this.model}),r={...this.invocationParams(e,{streaming:!0}),messages:s,stream:!0};let a;const i=await this.completionWithRetry(r,e);let o;for await(const l of i){const u=l?.choices?.[0];if(l.usage&&(o=l.usage),!u)continue;const{delta:h}=u;if(!h)continue;const c=this._convertCompletionsDeltaToBaseMessageChunk(h,l,a);a=h.role??a;const f={prompt:e.promptIndex??0,completion:u.index??0};if(typeof c.content!="string"){console.log("[WARNING]: Received non-string content from OpenAI. This is currently not supported.");continue}const d={...f};u.finish_reason!=null&&(d.finish_reason=u.finish_reason,d.system_fingerprint=l.system_fingerprint,d.model_name=l.model,d.service_tier=l.service_tier),this.logprobs&&(d.logprobs=u.logprobs);const w=new en({message:c,text:c.content,generationInfo:d});yield w,await n?.handleLLMNewToken(w.text??"",f,void 0,void 0,void 0,{chunk:w})}if(o){const l={...o.prompt_tokens_details?.audio_tokens!==null&&{audio:o.prompt_tokens_details?.audio_tokens},...o.prompt_tokens_details?.cached_tokens!==null&&{cache_read:o.prompt_tokens_details?.cached_tokens}},u={...o.completion_tokens_details?.audio_tokens!==null&&{audio:o.completion_tokens_details?.audio_tokens},...o.completion_tokens_details?.reasoning_tokens!==null&&{reasoning:o.completion_tokens_details?.reasoning_tokens}};yield new en({message:new wn({content:"",response_metadata:{usage:{...o}},usage_metadata:{input_tokens:o.prompt_tokens,output_tokens:o.completion_tokens,total_tokens:o.total_tokens,...Object.keys(l).length>0&&{input_token_details:l},...Object.keys(u).length>0&&{output_token_details:u}}}),text:""})}if(e.signal?.aborted)throw new Error("AbortError")}async completionWithRetry(t,e){const n=this._getClientOptions(e),s=t.response_format&&t.response_format.type==="json_schema";return this.caller.call(async()=>{try{return s&&!t.stream?await this.client.chat.completions.parse(t,n):await this.client.chat.completions.create(t,n)}catch(r){throw qn(r)}})}_convertCompletionsDeltaToBaseMessageChunk(t,e,n){return Nu({delta:t,rawResponse:e,includeRawResponse:this.__includeRawResponse,defaultRole:n})}_convertCompletionsMessageToBaseMessage(t,e){return Mu({message:t,rawResponse:e,includeRawResponse:this.__includeRawResponse})}};const At="__openai_function_call_ids__",Ma=t=>{const e={...t?.input_tokens_details?.cached_tokens!=null&&{cache_read:t?.input_tokens_details?.cached_tokens}},n={...t?.output_tokens_details?.reasoning_tokens!=null&&{reasoning:t?.output_tokens_details?.reasoning_tokens}};return{input_tokens:t?.input_tokens??0,output_tokens:t?.output_tokens??0,total_tokens:t?.total_tokens??0,input_token_details:e,output_token_details:n}},Na=t=>{if(t.error){const o=new Error(t.error.message);throw o.name=t.error.code,o}let e;const n=[],s=[],r=[],a={model_provider:"openai",model:t.model,created_at:t.created_at,id:t.id,incomplete_details:t.incomplete_details,metadata:t.metadata,object:t.object,status:t.status,user:t.user,service_tier:t.service_tier,model_name:t.model},i={};for(const o of t.output)if(o.type==="message")e=o.id,n.push(...o.content.flatMap(l=>l.type==="output_text"?("parsed"in l&&l.parsed!=null&&(i.parsed=l.parsed),{type:"text",text:l.text,annotations:l.annotations}):l.type==="refusal"?(i.refusal=l.refusal,[]):l));else if(o.type==="function_call"){const l={function:{name:o.name,arguments:o.arguments},id:o.call_id};try{s.push(Wt(l,{returnId:!0}))}catch(u){let h;typeof u=="object"&&u!=null&&"message"in u&&typeof u.message=="string"&&(h=u.message),r.push(ze(l,h))}i[At]??={},o.id&&(i[At][o.call_id]=o.id)}else if(o.type==="reasoning")i.reasoning=o;else if(o.type==="custom_tool_call"){const l=To(o);l?s.push(l):r.push(ze(o,"Malformed custom tool call"))}else if(o.type==="computer_call"){const l=Ao(o);l?s.push(l):r.push(ze(o,"Malformed computer call"))}else i.tool_outputs??=[],i.tool_outputs.push(o);return new Ce({id:e,content:n,tool_calls:s,invalid_tool_calls:r,usage_metadata:Ma(t.usage),additional_kwargs:i,response_metadata:a})},Du=t=>{const e=(t.summary.length>1?t.summary.reduce((n,s)=>{const r=n[n.length-1];return r.index===s.index?r.text+=s.text:n.push(s),n},[{...t.summary[0]}]):t.summary).map(n=>Object.fromEntries(Object.entries(n).filter(([s])=>s!=="index")));return{...t,summary:e}},Fu=t=>{const e=[];let n={},s;const r=[],a={model_provider:"openai"},i={};let o;if(t.type==="response.output_text.delta")e.push({type:"text",text:t.delta,index:t.content_index});else if(t.type==="response.output_text.annotation.added")e.push({type:"text",text:"",annotations:[t.annotation],index:t.content_index});else if(t.type==="response.output_item.added"&&t.item.type==="message")o=t.item.id;else if(t.type==="response.output_item.added"&&t.item.type==="function_call")r.push({type:"tool_call_chunk",name:t.item.name,args:t.item.arguments,id:t.item.call_id,index:t.output_index}),i[At]={[t.item.call_id]:t.item.id};else if(t.type==="response.output_item.done"&&t.item.type==="computer_call")r.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"&&["web_search_call","file_search_call","code_interpreter_call","mcp_call","mcp_list_tools","mcp_approval_request","image_generation_call","custom_tool_call"].includes(t.item.type))i.tool_outputs=[t.item];else if(t.type==="response.created")a.id=t.response.id,a.model_name=t.response.model,a.model=t.response.model;else if(t.type==="response.completed"){const l=Na(t.response);s=Ma(t.response.usage),t.response.text?.format?.type==="json_schema"&&(i.parsed??=JSON.parse(l.text));for(const[u,h]of Object.entries(t.response))u!=="id"&&(a[u]=h)}else if(t.type==="response.function_call_arguments.delta"||t.type==="response.custom_tool_call_input.delta")r.push({type:"tool_call_chunk",args:t.delta,index:t.output_index});else if(t.type==="response.web_search_call.completed"||t.type==="response.file_search_call.completed")n={tool_outputs:{id:t.item_id,type:t.type.replace("response.","").replace(".completed",""),status:"completed"}};else if(t.type==="response.refusal.done")i.refusal=t.refusal;else if(t.type==="response.output_item.added"&&"item"in t&&t.item.type==="reasoning"){const l=t.item.summary?t.item.summary.map((u,h)=>({...u,index:h})):void 0;i.reasoning={id:t.item.id,type:t.item.type,...l?{summary:l}:{}}}else if(t.type==="response.reasoning_summary_part.added")i.reasoning={type:"reasoning",summary:[{...t.part,index:t.summary_index}]};else if(t.type==="response.reasoning_summary_text.delta")i.reasoning={type:"reasoning",summary:[{text:t.delta,type:"summary_text",index:t.summary_index}]};else return t.type==="response.image_generation_call.partial_image",null;return new en({text:e.map(l=>l.text).join(""),message:new wn({id:o,content:e,tool_call_chunks:r,usage_metadata:s,additional_kwargs:i,response_metadata:a}),generationInfo:n})},Bu=t=>{const e=Ce.isInstance(t)&&t.response_metadata?.model_provider==="openai";function*n(){const s=ye(()=>{try{const m=Ge(t);return m==="system"||m==="developer"||m==="assistant"||m==="user"?m:"assistant"}catch{return"assistant"}});let r;const a=new Set,i=new Set,o=new Map,l=new Map;function*u(){if(!r)return;const m=r.content;(typeof m=="string"&&m.length>0||Array.isArray(m)&&m.length>0)&&(yield r),r=void 0}const h=m=>{r||(r={type:"message",role:s,content:[]}),typeof r.content=="string"?r.content=r.content.length>0?[{type:"input_text",text:r.content},...m]:[...m]:r.content.push(...m)},c=m=>{if(typeof m=="string")return m;try{return JSON.stringify(m??{})}catch{return"{}"}},f=m=>{const g=ye(()=>{const k=m.metadata?.detail;return k==="low"||k==="high"||k==="auto"?k:"auto"});if(m.fileId)return{type:"input_image",detail:g,file_id:m.fileId};if(m.url)return{type:"input_image",detail:g,image_url:m.url};if(m.data){const k=typeof m.data=="string"?m.data:Buffer.from(m.data).toString("base64"),A=m.mimeType??"image/png";return{type:"input_image",detail:g,image_url:`data:${A};base64,${k}`}}},d=m=>{const g=It(m);if(m.fileId&&typeof g=="string")return{type:"input_file",file_id:m.fileId,...g?{filename:g}:{}};if(m.url&&typeof g=="string")return{type:"input_file",file_url:m.url,...g?{filename:g}:{}};if(m.data&&typeof g=="string"){const k=typeof m.data=="string"?m.data:Buffer.from(m.data).toString("base64");return{type:"input_file",file_data:`data:${m.mimeType??"application/octet-stream"};base64,${k}`,...g?{filename:g}:{}}}},w=m=>{const g=ye(()=>{if(Array.isArray(m.summary)){const j=m.summary?.map(R=>R?.text).filter(R=>typeof R=="string")??[];if(j.length>0)return j}return m.reasoning?[m.reasoning]:[]}),k=g.length>0?g.map(K=>({type:"summary_text",text:K})):[{type:"summary_text",text:""}],A={type:"reasoning",id:m.id??"",summary:k};return m.reasoning&&(A.content=[{type:"reasoning_text",text:m.reasoning}]),A},y=m=>({type:"function_call",name:m.name??"",call_id:m.id??"",arguments:c(m.args)}),C=m=>{const g=c(m.output),k=m.status==="success"?"completed":m.status==="error"?"incomplete":void 0;return{type:"function_call_output",call_id:m.toolCallId??"",output:g,...k?{status:k}:{}}};for(const m of t.contentBlocks)if(m.type==="text")h([{type:"input_text",text:m.text}]);else if(m.type!=="invalid_tool_call"){if(m.type==="reasoning")yield*u(),yield w(m);else if(m.type==="tool_call"){yield*u();const g=m.id??"";g&&(a.add(g),o.delete(g)),yield y(m)}else if(m.type==="tool_call_chunk"){if(m.id){const g=o.get(m.id)??{name:m.name,args:[]};m.name&&(g.name=m.name),m.args&&g.args.push(m.args),o.set(m.id,g)}}else if(m.type==="server_tool_call"){yield*u();const g=m.id??"";g&&(i.add(g),l.delete(g)),yield y(m)}else if(m.type==="server_tool_call_chunk"){if(m.id){const g=l.get(m.id)??{name:m.name,args:[]};m.name&&(g.name=m.name),m.args&&g.args.push(m.args),l.set(m.id,g)}}else if(m.type==="server_tool_call_result")yield*u(),yield C(m);else if(m.type!=="audio")if(m.type==="file"){const g=d(m);g&&h([g])}else if(m.type==="image"){const g=f(m);g&&h([g])}else if(m.type==="video"){const g=d(m);g&&h([g])}else m.type==="text-plain"?m.text&&h([{type:"input_text",text:m.text}]):m.type==="non_standard"&&e&&(yield*u(),yield m.value)}yield*u();for(const[m,g]of o){if(!m||a.has(m))continue;const k=g.args.join("");!g.name&&!k||(yield{type:"function_call",call_id:m,name:g.name??"",arguments:k})}for(const[m,g]of l){if(!m||i.has(m))continue;const k=g.args.join("");!g.name&&!k||(yield{type:"function_call",call_id:m,name:g.name??"",arguments:k})}}return Array.from(n())},Ls=({messages:t,zdrEnabled:e,model:n})=>t.flatMap(s=>{const r=s.response_metadata;if(r?.output_version==="v1")return Bu(s);const a=s.additional_kwargs;let i=Ge(s);if(i==="system"&&Xe(n)&&(i="developer"),i==="function")throw new Error("Function messages are not supported in Responses API");if(i==="tool"){const o=s;return a?.type==="computer_call_output"?{type:"computer_call_output",output:(()=>{if(typeof o.content=="string")return{type:"input_image",image_url:o.content};if(Array.isArray(o.content)){const u=o.content.find(f=>f.type==="input_image");if(u)return u;const h=o.content.find(f=>f.type==="computer_screenshot");if(h)return h;const c=o.content.find(f=>f.type==="image_url");if(c)return{type:"input_image",image_url:typeof c.image_url=="string"?c.image_url:c.image_url.url}}throw new Error("Invalid computer call output")})(),call_id:o.tool_call_id}:o.additional_kwargs?.customTool?{type:"custom_tool_call_output",call_id:o.tool_call_id,output:o.content}:{type:"function_call_output",call_id:o.tool_call_id,id:o.id?.startsWith("fc_")?o.id:void 0,output:typeof o.content!="string"?JSON.stringify(o.content):o.content}}if(i==="assistant"){if(!e&&r?.output!=null&&Array.isArray(r?.output)&&r?.output.length>0&&r?.output.every(f=>"type"in f))return r?.output;const o=[];if(a?.reasoning&&!e){const f=Du(a.reasoning);o.push(f)}let{content:l}=s;a?.refusal&&(typeof l=="string"&&(l=[{type:"output_text",text:l,annotations:[]}]),l=[...l,{type:"refusal",refusal:a.refusal}]),(typeof l=="string"||l.length>0)&&o.push({type:"message",role:"assistant",...s.id&&!e&&s.id.startsWith("msg_")?{id:s.id}:{},content:ye(()=>typeof l=="string"?l:l.flatMap(f=>f.type==="text"?{type:"output_text",text:f.text,annotations:f.annotations??[]}:f.type==="output_text"||f.type==="refusal"?f:[]))});const u=a?.[At];Ce.isInstance(s)&&s.tool_calls?.length?o.push(...s.tool_calls.map(f=>Ro(f)?{type:"custom_tool_call",id:f.call_id,call_id:f.id??"",input:f.args.input,name:f.name}:Po(f)?{type:"computer_call",id:f.call_id,call_id:f.id??"",action:f.args.action}:{type:"function_call",name:f.name,arguments:JSON.stringify(f.args),call_id:f.id,...e?{}:{id:u?.[f.id]}})):a?.tool_calls&&o.push(...a.tool_calls.map(f=>({type:"function_call",name:f.function.name,call_id:f.id,arguments:f.function.arguments,...e?{}:{id:u?.[f.id]}})));const h=r?.output?.length?r?.output:a.tool_outputs,c=["computer_call","mcp_call","code_interpreter_call","image_generation_call"];if(h!=null){const d=h?.filter(w=>c.includes(w.type));d.length>0&&o.push(...d)}return o}if(i==="user"||i==="system"||i==="developer"){if(typeof s.content=="string")return{type:"message",role:i,content:s.content};const o=[],l=s.content.flatMap(u=>{if(u.type==="mcp_approval_response"&&o.push({type:"mcp_approval_response",approval_request_id:u.approval_request_id,approve:u.approve}),Fs(u))return Bs(u,Ea);if(u.type==="text")return{type:"input_text",text:u.text};if(u.type==="image_url"){const h=ye(()=>{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}),c=ye(()=>{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});return{type:"input_image",image_url:h,detail:c}}return u.type==="input_text"||u.type==="input_image"||u.type==="input_file"?u:[]});return l.length>0&&o.push({type:"message",role:i,content:l}),o}return console.warn(`Unsupported role found when converting to OpenAI Responses API: ${i}`),[]});var Wu=class extends zn{invocationParams(t){let e;t?.strict!==void 0&&(e=t.strict),e===void 0&&this.supportsStrictToolCalling!==void 0&&(e=this.supportsStrictToolCalling);const n={model:this.model,temperature:this.temperature,top_p:this.topP,user:this.user,stream:this.streaming,previous_response_id:t?.previous_response_id,truncation:t?.truncation,include:t?.include,tools:t?.tools?.length?this._reduceChatOpenAITools(t.tools,{stream:this.streaming,strict:e}):void 0,tool_choice:Co(t?.tool_choice)?t?.tool_choice:(()=>{const r=Ia(t?.tool_choice);if(typeof r=="object"&&"type"in r){if(r.type==="function")return{type:"function",name:r.function.name};if(r.type==="allowed_tools")return{type:"allowed_tools",mode:r.allowed_tools.mode,tools:r.allowed_tools.tools};if(r.type==="custom")return{type:"custom",name:r.custom.name}}})(),text:(()=>{if(t?.text)return t.text;const r=this._getResponseFormat(t?.response_format);return r?.type==="json_schema"?r.json_schema.schema!=null?{format:{type:"json_schema",schema:r.json_schema.schema,description:r.json_schema.description,name:r.json_schema.name,strict:r.json_schema.strict},verbosity:t?.verbosity}:void 0:{format:r,verbosity:t?.verbosity}})(),parallel_tool_calls:t?.parallel_tool_calls,max_output_tokens:this.maxTokens===-1?void 0:this.maxTokens,prompt_cache_key:t?.promptCacheKey??this.promptCacheKey,prompt_cache_retention:t?.promptCacheRetention??this.promptCacheRetention,...this.zdrEnabled?{store:!1}:{},...this.modelKwargs},s=this._getReasoningParams(t);return s!==void 0&&(n.reasoning=s),n}async _generate(t,e){const n=this.invocationParams(e);if(n.stream){const s=this._streamResponseChunks(t,e);let r;for await(const a of s)a.message.response_metadata={...a.generationInfo,...a.message.response_metadata},r=r?.concat(a)??a;return{generations:r?[r]:[],llmOutput:{estimatedTokenUsage:r?.message?.usage_metadata}}}else{const s=await this.completionWithRetry({input:Ls({messages:t,zdrEnabled:this.zdrEnabled??!1,model:this.model}),...n,stream:!1},{signal:e?.signal,...e?.options});return{generations:[{text:s.output_text,message:Na(s)}],llmOutput:{id:s.id,estimatedTokenUsage:s.usage?{promptTokens:s.usage.input_tokens,completionTokens:s.usage.output_tokens,totalTokens:s.usage.total_tokens}:void 0}}}}async*_streamResponseChunks(t,e,n){const s=await this.completionWithRetry({...this.invocationParams(e),input:Ls({messages:t,zdrEnabled:this.zdrEnabled??!1,model:this.model}),stream:!0},e);for await(const r of s){const a=Fu(r);a!=null&&(yield a,await n?.handleLLMNewToken(a.text||"",{prompt:e.promptIndex??0,completion:0},void 0,void 0,void 0,{chunk:a}))}}async completionWithRetry(t,e){return this.caller.call(async()=>{const n=this._getClientOptions(e);try{return t.text?.format?.type==="json_schema"&&!t.stream?await this.client.responses.parse(t,n):await this.client.responses.create(t,n)}catch(s){throw qn(s)}})}_reduceChatOpenAITools(t,e){const n=[];for(const s of t)if(Jn(s))s.type==="image_generation"&&e?.stream&&(s.partial_images=1),n.push(s);else if(Ct(s)){const r=s.metadata.customTool;n.push({type:"custom",name:r.name,description:r.description,format:r.format})}else Js(s)?n.push({type:"function",name:s.function.name,parameters:s.function.parameters,description:s.function.description,strict:e?.strict??null}):Sa(s)&&n.push($o(s));return n}},Ol=class La extends zn{useResponsesApi=!1;responses;completions;get lc_serializable_keys(){return[...super.lc_serializable_keys,"useResponsesApi"]}get callKeys(){return[...super.callKeys,"useResponsesApi"]}constructor(e){super(e),this.fields=e,this.useResponsesApi=e?.useResponsesApi??!1,this.responses=e?.responses??new Wu(e),this.completions=e?.completions??new Uu(e)}_useResponsesApi(e){const n=e?.tools?.some(Jn),s=e?.previous_response_id!=null||e?.text!=null||e?.truncation!=null||e?.include!=null||e?.reasoning?.summary!=null||this.reasoning?.summary!=null,r=e?.tools?.some(Sa)||e?.tools?.some(Ct);return this.useResponsesApi||n||s||r||yo(this.model)}getLsParams(e){const n=this._combineCallOptions(e);return this._useResponsesApi(e)?this.responses.getLsParams(n):this.completions.getLsParams(n)}invocationParams(e){const n=this._combineCallOptions(e);return this._useResponsesApi(e)?this.responses.invocationParams(n):this.completions.invocationParams(n)}async _generate(e,n,s){return this._useResponsesApi(n)?this.responses._generate(e,n):this.completions._generate(e,n,s)}async*_streamResponseChunks(e,n,s){if(this._useResponsesApi(n)){yield*this.responses._streamResponseChunks(e,this._combineCallOptions(n),s);return}yield*this.completions._streamResponseChunks(e,this._combineCallOptions(n),s)}withConfig(e){const n=new La(this.fields);return n.defaultOptions={...this.defaultOptions,...e},n}},qu={};Ds(qu,{BaseLLM:()=>ja,LLM:()=>Ju});var ja=class Be extends ai{lc_namespace=["langchain","llms",this._llmType()];async invoke(e,n){const s=Be._convertInputToPromptValue(e);return(await this.generatePrompt([s],n,n?.callbacks)).generations[0][0].text}async*_streamResponseChunks(e,n,s){throw new Error("Not implemented.")}_separateRunnableConfigFromCallOptionsCompat(e){const[n,s]=super._separateRunnableConfigFromCallOptions(e);return s.signal=n.signal,[n,s]}async*_streamIterator(e,n){if(this._streamResponseChunks===Be.prototype._streamResponseChunks)yield this.invoke(e,n);else{const s=Be._convertInputToPromptValue(e),[r,a]=this._separateRunnableConfigFromCallOptionsCompat(n),i=await Jt.configure(r.callbacks,this.callbacks,r.tags,this.tags,r.metadata,this.metadata,{verbose:this.verbose}),o={options:a,invocation_params:this?.invocationParams(a),batch_size:1},l=await i?.handleLLMStart(this.toJSON(),[s.toString()],r.runId,void 0,o,void 0,void 0,r.runName);let u=new Qa({text:""});try{for await(const h of this._streamResponseChunks(s.toString(),a,l?.[0]))u?u=u.concat(h):u=h,typeof h.text=="string"&&(yield h.text)}catch(h){throw await Promise.all((l??[]).map(c=>c?.handleLLMError(h))),h}await Promise.all((l??[]).map(h=>h?.handleLLMEnd({generations:[[u]]})))}}async generatePrompt(e,n,s){const r=e.map(a=>a.toString());return this.generate(r,n,s)}invocationParams(e){return{}}_flattenLLMResult(e){const n=[];for(let s=0;s<e.generations.length;s+=1){const r=e.generations[s];if(s===0)n.push({generations:[r],llmOutput:e.llmOutput});else{const a=e.llmOutput?{...e.llmOutput,tokenUsage:{}}:void 0;n.push({generations:[r],llmOutput:a})}}return n}async _generateUncached(e,n,s,r){let a;if(r!==void 0&&r.length===e.length)a=r;else{const u=await Jt.configure(s.callbacks,this.callbacks,s.tags,this.tags,s.metadata,this.metadata,{verbose:this.verbose}),h={options:n,invocation_params:this?.invocationParams(n),batch_size:e.length};a=await u?.handleLLMStart(this.toJSON(),e,s.runId,void 0,h,void 0,void 0,s?.runName)}const i=!!a?.[0].handlers.find(Ya);let o;if(i&&e.length===1&&this._streamResponseChunks!==Be.prototype._streamResponseChunks)try{const u=await this._streamResponseChunks(e[0],n,a?.[0]);let h;for await(const c of u)h===void 0?h=c:h=ei(h,c);if(h===void 0)throw new Error("Received empty response from chat model call.");o={generations:[[h]],llmOutput:{}},await a?.[0].handleLLMEnd(o)}catch(u){throw await a?.[0].handleLLMError(u),u}else{try{o=await this._generate(e,n,a?.[0])}catch(h){throw await Promise.all((a??[]).map(c=>c?.handleLLMError(h))),h}const u=this._flattenLLMResult(o);await Promise.all((a??[]).map((h,c)=>h?.handleLLMEnd(u[c])))}const l=a?.map(u=>u.runId)||void 0;return Object.defineProperty(o,Qn,{value:l?{runIds:l}:void 0,configurable:!0}),o}async _generateCached({prompts:e,cache:n,llmStringKey:s,parsedOptions:r,handledOptions:a,runId:i}){const o=await Jt.configure(a.callbacks,this.callbacks,a.tags,this.tags,a.metadata,this.metadata,{verbose:this.verbose}),l={options:r,invocation_params:this?.invocationParams(r),batch_size:e.length},u=await o?.handleLLMStart(this.toJSON(),e,i,void 0,l,void 0,void 0,a?.runName),h=[],f=(await Promise.allSettled(e.map(async(y,C)=>{const m=await n.lookup(y,s);return m==null&&h.push(C),m}))).map((y,C)=>({result:y,runManager:u?.[C]})).filter(({result:y})=>y.status==="fulfilled"&&y.value!=null||y.status==="rejected"),d=[];await Promise.all(f.map(async({result:y,runManager:C},m)=>{if(y.status==="fulfilled"){const g=y.value;return d[m]=g.map(k=>(k.generationInfo={...k.generationInfo,tokenUsage:{}},k)),g.length&&await C?.handleLLMNewToken(g[0].text),C?.handleLLMEnd({generations:[g]},void 0,void 0,void 0,{cached:!0})}else return await C?.handleLLMError(y.reason,void 0,void 0,void 0,{cached:!0}),Promise.reject(y.reason)}));const w={generations:d,missingPromptIndices:h,startedRunManagers:u};return Object.defineProperty(w,Qn,{value:u?{runIds:u?.map(y=>y.runId)}:void 0,configurable:!0}),w}async generate(e,n,s){if(!Array.isArray(e))throw new Error("Argument 'prompts' is expected to be a string[]");let r;Array.isArray(n)?r={stop:n}:r=n;const[a,i]=this._separateRunnableConfigFromCallOptionsCompat(r);if(a.callbacks=a.callbacks??s,!this.cache)return this._generateUncached(e,i,a);const{cache:o}=this,l=this._getSerializedCacheKeyParametersForCall(i),{generations:u,missingPromptIndices:h,startedRunManagers:c}=await this._generateCached({prompts:e,cache:o,llmStringKey:l,parsedOptions:i,handledOptions:a,runId:a.runId});let f={};if(h.length>0){const d=await this._generateUncached(h.map(w=>e[w]),i,a,c!==void 0?h.map(w=>c?.[w]):void 0);await Promise.all(d.generations.map(async(w,y)=>{const C=h[y];return u[C]=w,o.update(e[C],l,w)})),f=d.llmOutput??{}}return{generations:u,llmOutput:f}}_identifyingParams(){return{}}_modelType(){return"base_llm"}},Ju=class extends ja{async _generate(t,e,n){return{generations:await Promise.all(t.map((r,a)=>this._call(r,{...e,promptIndex:a},n).then(i=>[{text:i}])))}}};const zu=z({type:ee("screenshot")}),Ku=z({type:ee("click"),x:J(),y:J(),button:zs(["left","right","wheel","back","forward"]).default("left")}),Zu=z({type:ee("double_click"),x:J(),y:J(),button:zs(["left","right","wheel","back","forward"]).default("left")}),Hu=z({type:ee("drag"),path:Pt(z({x:J(),y:J()}))}),Vu=z({type:ee("keypress"),keys:Pt(Q())}),Xu=z({type:ee("move"),x:J(),y:J()}),Gu=z({type:ee("scroll"),x:J(),y:J(),scroll_x:J(),scroll_y:J()}),Qu=z({type:ee("type"),text:Q()}),Yu=z({type:ee("wait"),duration:J().optional()}),el=bn("type",[zu,Ku,Zu,Hu,Vu,Xu,Gu,Qu,Yu]);z({action:el});const tl=z({type:ee("exec"),command:Pt(Q()),env:ui(Q(),Q()).optional(),working_directory:Q().optional(),timeout_ms:J().optional(),user:Q().optional()});bn("type",[tl]);z({commands:Pt(Q()).describe("Array of shell commands to execute"),timeout_ms:J().optional().describe("Optional timeout in milliseconds for the commands"),max_output_length:J().optional().describe("Optional maximum number of characters to return from each command")});const nl=z({type:ee("create_file"),path:Q(),diff:Q()}),sl=z({type:ee("update_file"),path:Q(),diff:Q()}),rl=z({type:ee("delete_file"),path:Q()});bn("type",[nl,sl,rl]);export{zn as BaseChatOpenAI,Ol as ChatOpenAI,Uu as ChatOpenAICompletions,Wu as ChatOpenAIResponses,S as OpenAIClient,Ea as completionsApiContentBlockConverter,Nu as convertCompletionsDeltaToBaseMessageChunk,Mu as convertCompletionsMessageToBaseMessage,Ns as convertMessagesToCompletionsMessageParams,Ls as convertMessagesToResponsesInput,Du as convertReasoningSummaryToResponsesReasoningItem,Fu as convertResponsesDeltaToChatGenerationChunk,Na as convertResponsesMessageToAIMessage,Ma as convertResponsesUsageToUsageMetadata,Lu as convertStandardContentBlockToCompletionsContentPart,ju as convertStandardContentMessageToCompletionsMessage,Bu as convertStandardContentMessageToResponsesInput,wo as getEndpoint,vo as getFormattedEnv,Oo as getHeadersWithUserAgent,Ps as isHeaders,Ge as messageToOpenAIRole,bo as normalizeHeaders,Wi as toFile,qn as wrapOpenAIClientError};
@@ -0,0 +1,7 @@
1
+ import{_ as E,T as f,e as x,m as P,a as g,i as $,b as N,c as O,v as A,C as I,p as y,d as L,o as J,s as F,f as R,g as M,h as S,A as C,j as b,k as B,l as _,n as j}from"./base-ZEkF4ver.js";import{i as Z,a as W,b as H,c as K,B as V}from"./base-Aouj1Yhj.js";import{p as q}from"./index-CNfmoBX-.js";var z={};E(z,{BaseToolkit:()=>G,DynamicStructuredTool:()=>k,DynamicTool:()=>D,StructuredTool:()=>T,Tool:()=>w,ToolInputParsingException:()=>f,isLangChainTool:()=>K,isRunnableToolLike:()=>H,isStructuredTool:()=>W,isStructuredToolParams:()=>Z,tool:()=>Q});var T=class extends V{extras;returnDirect=!1;verboseParsingErrors=!1;get lc_namespace(){return["langchain","tools"]}responseFormat="content";defaultConfig;constructor(t){super(t??{}),this.verboseParsingErrors=t?.verboseParsingErrors??this.verboseParsingErrors,this.responseFormat=t?.responseFormat??this.responseFormat,this.defaultConfig=t?.defaultConfig??this.defaultConfig,this.metadata=t?.metadata??this.metadata,this.extras=t?.extras??this.extras}async invoke(t,e){let a,r=x(P(this.defaultConfig,e));return g(t)?(a=t.args,r={...r,toolCall:t}):a=t,this.call(a,r)}async call(t,e,a){const r=g(t)?t.args:t;let u;if($(this.schema))try{u=await N(this.schema,r)}catch(c){let o="Received tool input did not match expected schema";throw this.verboseParsingErrors&&(o=`${o}
2
+ Details: ${c.message}`),O(c)&&(o=`${o}
3
+
4
+ ${q(c)}`),new f(o,JSON.stringify(t))}else{const c=A(r,this.schema);if(!c.valid){let o="Received tool input did not match expected schema";throw this.verboseParsingErrors&&(o=`${o}
5
+ Details: ${c.errors.map(v=>`${v.keywordLocation}: ${v.error}`).join(`
6
+ `)}`),new f(o,JSON.stringify(t))}u=r}const n=y(e),h=await I.configure(n.callbacks,this.callbacks,n.tags||a,this.tags,n.metadata,this.metadata,{verbose:this.verbose})?.handleToolStart(this.toJSON(),typeof t=="string"?t:JSON.stringify(t),n.runId,void 0,void 0,void 0,n.runName);delete n.runId;let s;try{s=await this._call(u,h,n)}catch(c){throw await h?.handleToolError(c),c}let m,p;if(this.responseFormat==="content_and_artifact")if(Array.isArray(s)&&s.length===2)[m,p]=s;else throw new Error(`Tool response format is "content_and_artifact" but the output was not a two-tuple.
7
+ Result: ${JSON.stringify(s)}`);else m=s;let i;g(t)&&(i=t.id),!i&&L(n)&&(i=n.toolCall.id);const l=U({content:m,artifact:p,toolCallId:i,name:this.name,metadata:this.metadata});return await h?.handleToolEnd(l),l}},w=class extends T{schema=J({input:F().optional()}).transform(t=>t.input);constructor(t){super(t)}call(t,e){const a=typeof t=="string"||t==null?{input:t}:t;return super.call(a,e)}},D=class extends w{static lc_name(){return"DynamicTool"}name;description;func;constructor(t){super(t),this.name=t.name,this.description=t.description,this.func=t.func,this.returnDirect=t.returnDirect??this.returnDirect}async call(t,e){const a=y(e);return a.runName===void 0&&(a.runName=this.name),super.call(t,a)}async _call(t,e,a){return this.func(t,e,a)}},k=class extends T{static lc_name(){return"DynamicStructuredTool"}name;description;func;schema;constructor(t){super(t),this.name=t.name,this.description=t.description,this.func=t.func,this.returnDirect=t.returnDirect??this.returnDirect,this.schema=t.schema}async call(t,e,a){const r=y(e);return r.runName===void 0&&(r.runName=this.name),super.call(t,r,a)}_call(t,e,a){return this.func(t,e,a)}},G=class{getTools(){return this.tools}};function Q(t,e){const a=R(e.schema),r=M(e.schema);if(!e.schema||a||r)return new D({...e,description:e.description??e.schema?.description??`${e.name} tool`,func:async(d,h,s)=>new Promise((m,p)=>{const i=S(s,{callbacks:h?.getChild()});C.runWithConfig(b(i),async()=>{try{m(t(d,i))}catch(l){p(l)}})})});const u=e.schema,n=e.description??e.schema.description??`${e.name} tool`;return new k({...e,description:n,schema:u,func:async(d,h,s)=>new Promise((m,p)=>{let i;const l=()=>{s?.signal&&i&&s.signal.removeEventListener("abort",i)};s?.signal&&(i=()=>{l(),p(j(s.signal))},s.signal.addEventListener("abort",i));const c=S(s,{callbacks:h?.getChild()});C.runWithConfig(b(c),async()=>{try{const o=await t(d,c);if(s?.signal?.aborted){l();return}l(),m(o)}catch(o){l(),p(o)}})})})}function U(t){const{content:e,artifact:a,toolCallId:r,metadata:u}=t;return r&&!B(e)?typeof e=="string"||Array.isArray(e)&&e.every(n=>typeof n=="object")?new _({status:"success",content:e,artifact:a,tool_call_id:r,name:t.name,metadata:u}):new _({status:"success",content:X(e),artifact:a,tool_call_id:r,name:t.name,metadata:u}):e}function X(t){try{return JSON.stringify(t,null,2)??""}catch{return`${t}`}}export{k as D};