@mcp-use/inspector 0.14.0-canary.0 → 0.14.0-canary.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +10 -54
- package/dist/client/assets/browser-INsCMNyc.js +410 -0
- package/dist/client/assets/client-BLKbZjby.js +92 -0
- package/dist/client/assets/{display-A5IEINAP-D2Zkswj8.js → display-A5IEINAP-QwkwrW1D.js} +2 -2
- package/dist/client/assets/{embeddings-SLmbAVWP.js → embeddings-Dt8zD86W.js} +1 -1
- package/dist/client/assets/{index-CTUcNdQF.js → index-7zlfUUVg.js} +2 -2
- package/dist/client/assets/{index-DF_VhD4l.js → index-BIwswAy1.js} +2 -2
- package/dist/client/assets/{index-DDOzs1PG.js → index-BTYob6lV.js} +1 -1
- package/dist/client/assets/{index-pqhVKjyB.js → index-C9DK5WY4.js} +1 -1
- package/dist/client/assets/{index-ZoGs-72y.js → index-Cu6BBsRe.js} +1 -1
- package/dist/client/assets/{index-DvTyGyQK.js → index-HrVSgYfQ.js} +10 -10
- package/dist/client/assets/{index-DorqJhTq.js → index-Sz6vqd-H.js} +1 -1
- package/dist/client/assets/index-T9QtDRcf.css +1 -0
- package/dist/client/assets/index-c4KcZ9vr.js +1753 -0
- package/dist/client/assets/index-jYSn9Ie7.js +71 -0
- package/dist/client/assets/{llms-Og3hdOaD.js → llms-CJxJGKtJ.js} +1 -1
- package/dist/client/assets/util-QmrWvrtn.js +1 -0
- package/dist/client/index.html +3 -3
- package/dist/server/{chunk-JEKCWLHD.js → chunk-4OEEUHLZ.js} +2 -2
- package/dist/server/{chunk-YLX7JQDX.js → chunk-BC23UV5D.js} +3 -1
- package/dist/server/{chunk-XGILHZOF.js → chunk-E4Y73JSU.js} +5 -49
- package/dist/server/{chunk-JCLAFMDT.js → chunk-PUX4EJWH.js} +11 -0
- package/dist/server/{chunk-MCMZDGO6.js → chunk-Z5QIR3IS.js} +2 -2
- package/dist/server/cli.js +4 -4
- package/dist/server/index.js +5 -5
- package/dist/server/middleware.js +5 -5
- package/dist/server/server.d.ts +11 -0
- package/dist/server/server.d.ts.map +1 -1
- package/dist/server/server.js +16 -11
- package/dist/server/shared-routes.d.ts.map +1 -1
- package/dist/server/shared-routes.js +3 -3
- package/dist/server/shared-static.d.ts +5 -1
- package/dist/server/shared-static.d.ts.map +1 -1
- package/dist/server/shared-static.js +1 -1
- package/dist/server/shared-utils-browser.d.ts +9 -1
- package/dist/server/shared-utils-browser.d.ts.map +1 -1
- package/dist/server/shared-utils-browser.js +1 -1
- package/dist/server/utils.d.ts +14 -0
- package/dist/server/utils.d.ts.map +1 -1
- package/dist/server/utils.js +5 -3
- package/package.json +3 -3
- package/dist/client/assets/browser-2Ez00ml2.js +0 -501
- package/dist/client/assets/fs-u42MReIY.js +0 -1
- package/dist/client/assets/index-BFXh5irY.js +0 -1701
- package/dist/client/assets/index-DRz5BQNA.js +0 -1
- package/dist/client/assets/index-cMXsdFDY.css +0 -1
- package/dist/client/assets/index-jWGWxByD.js +0 -71
- package/dist/client/assets/path-BX1ROoWV.js +0 -1
- package/dist/client/assets/path-MNZaYwxc.js +0 -1
- package/dist/client/assets/posthog-node-CuYhrq1Q.js +0 -1
- package/dist/client/assets/transport-wrapper-browser-BI4dDu3b.js +0 -1
- package/dist/client/assets/util-t-trnxQI.js +0 -1
- package/dist/client/assets/winston-CYVymxcI.js +0 -37
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{F as Es,aK as Ra,aL as I,V as $a,U as Pa,y as $e,L as Jn,i as Xe,ad as Ea,ap as Ma,M as Na,I as Ms,J as Ns,B as Se,f as js,aM as ja,E as mn,aN as Kn,aO as Ua,aP as La,aQ as Da,K as Zn,aR as zn,aS as Fa,t as Ba,D as Gt}from"./index-
|
|
1
|
+
import{F as Es,aK as Ra,aL as I,V as $a,U as Pa,y as $e,L as Jn,i as Xe,ad as Ea,ap as Ma,M as Na,I as Ms,J as Ns,B as Se,f as js,aM as ja,E as mn,aN as Kn,aO as Ua,aP as La,aQ as Da,K as Zn,aR as zn,aS as Fa,t as Ba,D as Gt}from"./index-C9DK5WY4.js";import{c as Wa,j as qa,h as Ja,f as Us,S as Hn,J as Vn,R as Xn}from"./index-jYSn9Ie7.js";import{x as Ka,y as Za,o as K,m as ee,v as Ls,n as J,i as At,s as Q,q as gn,z as za}from"./index-c4KcZ9vr.js";import{J as Gn,c as Ha,p as Ds,m as at}from"./llms-CJxJGKtJ.js";import"./embeddings-Dt8zD86W.js";import"./index-Cu6BBsRe.js";function Ge(t,e){return t.lc_error_code=e,t.message=`${t.message}
|
|
2
2
|
|
|
3
3
|
Troubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${e}/
|
|
4
4
|
`,t}function O(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 c(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 Fs=function(){const{crypto:t}=globalThis;if(t?.randomUUID)return Fs=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 Qt(t){return typeof t=="object"&&t!==null&&("name"in t&&t.name==="AbortError"||"message"in t&&String(t.message).includes("FetchRequestCanceledException"))}const Yt=t=>{if(t instanceof Error)return t;if(typeof t=="object"&&t!==null){try{if(Object.prototype.toString.call(t)==="[object Error]"){const e=new Error(t.message,t.cause?{cause:t.cause}:{});return t.stack&&(e.stack=t.stack),t.cause&&!e.cause&&(e.cause=t.cause),t.name&&(e.name=t.name),e}}catch{}try{return new Error(JSON.stringify(t))}catch{}}return new Error(t)};class x extends Error{}class q extends x{constructor(e,n,s,r){super(`${q.makeMessage(e,n,s)}`),this.status=e,this.headers=r,this.requestID=r?.get("x-request-id"),this.error=n;const a=n;this.code=a?.code,this.param=a?.param,this.type=a?.type}static makeMessage(e,n,s){const r=n?.message?typeof n.message=="string"?n.message:JSON.stringify(n.message):n?JSON.stringify(n):s;return e&&r?`${e} ${r}`:e?`${e} status code (no body)`:r||"(no status code or body)"}static generate(e,n,s,r){if(!e||!r)return new Rt({message:s,cause:Yt(n)});const a=n?.error;return e===400?new Bs(e,a,s,r):e===401?new Ws(e,a,s,r):e===403?new qs(e,a,s,r):e===404?new Js(e,a,s,r):e===409?new Ks(e,a,s,r):e===422?new Zs(e,a,s,r):e===429?new zs(e,a,s,r):e>=500?new Hs(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 Bs extends q{}class Ws extends q{}class qs extends q{}class Js extends q{}class Ks extends q{}class Zs extends q{}class zs extends q{}class Hs extends q{}class Vs extends x{constructor(){super("Could not parse response content as the length limit was reached")}}class Xs extends x{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}class Pe extends Error{constructor(e){super(e)}}const Va=/^[a-z][a-z0-9+.-]*:/i,Xa=t=>Va.test(t);let H=t=>(H=Array.isArray,H(t)),Qn=H;function Gs(t){return typeof t!="object"?{}:t??{}}function Ga(t){if(!t)return!0;for(const e in t)return!1;return!0}function Qa(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function Wt(t){return t!=null&&typeof t=="object"&&!Array.isArray(t)}const Ya=(t,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new x(`${t} must be an integer`);if(e<0)throw new x(`${t} must be a positive integer`);return e},ei=t=>{try{return JSON.parse(t)}catch{return}},Ke=t=>new Promise(e=>setTimeout(e,t)),Oe="6.10.0",ti=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function ni(){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 si=()=>{const t=ni();if(t==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Oe,"X-Stainless-OS":es(Deno.build.os),"X-Stainless-Arch":Yn(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":Oe,"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":Oe,"X-Stainless-OS":es(globalThis.process.platform??"unknown"),"X-Stainless-Arch":Yn(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};const e=ri();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Oe,"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":Oe,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function ri(){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 Yn=t=>t==="x32"?"x32":t==="x86_64"||t==="x64"?"x64":t==="arm"?"arm":t==="aarch64"||t==="arm64"?"arm64":t?`other:${t}`:"unknown",es=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 ts;const ai=()=>ts??(ts=si());function ii(){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 Qs(...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 Ys(t){let e=Symbol.asyncIterator in t?t[Symbol.asyncIterator]():t[Symbol.iterator]();return Qs({start(){},async pull(n){const{done:s,value:r}=await e.next();s?n.close():n.enqueue(r)},async cancel(){await e.return?.()}})}function er(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 oi(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 ui=({headers:t,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)}),tr="RFC3986",nr=t=>String(t),ns={RFC1738:t=>String(t).replace(/%20/g,"+"),RFC3986:nr},li="RFC1738";let en=(t,e)=>(en=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),en(t,e));const re=(()=>{const t=[];for(let e=0;e<256;++e)t.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return t})(),qt=1024,ci=(t,e,n,s,r)=>{if(t.length===0)return t;let a=t;if(typeof t=="symbol"?a=Symbol.prototype.toString.call(t):typeof t!="string"&&(a=String(t)),n==="iso-8859-1")return escape(a).replace(/%u[0-9a-f]{4}/gi,function(o){return"%26%23"+parseInt(o.slice(2),16)+"%3B"});let i="";for(let o=0;o<a.length;o+=qt){const l=a.length>=qt?a.slice(o,o+qt):a,u=[];for(let m=0;m<l.length;++m){let p=l.charCodeAt(m);if(p===45||p===46||p===95||p===126||p>=48&&p<=57||p>=65&&p<=90||p>=97&&p<=122||r===li&&(p===40||p===41)){u[u.length]=l.charAt(m);continue}if(p<128){u[u.length]=re[p];continue}if(p<2048){u[u.length]=re[192|p>>6]+re[128|p&63];continue}if(p<55296||p>=57344){u[u.length]=re[224|p>>12]+re[128|p>>6&63]+re[128|p&63];continue}m+=1,p=65536+((p&1023)<<10|l.charCodeAt(m)&1023),u[u.length]=re[240|p>>18]+re[128|p>>12&63]+re[128|p>>6&63]+re[128|p&63]}i+=u.join("")}return i};function di(t){return!t||typeof t!="object"?!1:!!(t.constructor&&t.constructor.isBuffer&&t.constructor.isBuffer(t))}function ss(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 sr={brackets(t){return String(t)+"[]"},comma:"comma",indices(t,e){return String(t)+"["+e+"]"},repeat(t){return String(t)}},rr=function(t,e){Array.prototype.push.apply(t,H(e)?e:[e])};let rs;const j={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:ci,encodeValuesOnly:!1,format:tr,formatter:nr,indices:!1,serializeDate(t){return(rs??(rs=Function.prototype.call.bind(Date.prototype.toISOString)))(t)},skipNulls:!1,strictNullHandling:!1};function pi(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"||typeof t=="symbol"||typeof t=="bigint"}const Jt={};function ar(t,e,n,s,r,a,i,o,l,u,m,p,f,d,b,w,$,h){let g=t,T=h,C=0,Z=!1;for(;(T=T.get(Jt))!==void 0&&!Z;){const P=T.get(t);if(C+=1,typeof P<"u"){if(P===C)throw new RangeError("Cyclic object value");Z=!0}typeof T.get(Jt)>"u"&&(C=0)}if(typeof u=="function"?g=u(e,g):g instanceof Date?g=f?.(g):n==="comma"&&H(g)&&(g=ss(g,function(P){return P instanceof Date?f?.(P):P})),g===null){if(a)return l&&!w?l(e,j.encoder,$,"key",d):e;g=""}if(pi(g)||di(g)){if(l){const P=w?e:l(e,j.encoder,$,"key",d);return[b?.(P)+"="+b?.(l(g,j.encoder,$,"value",d))]}return[b?.(e)+"="+b?.(String(g))]}const U=[];if(typeof g>"u")return U;let R;if(n==="comma"&&H(g))w&&l&&(g=ss(g,l)),R=[{value:g.length>0?g.join(",")||null:void 0}];else if(H(u))R=u;else{const P=Object.keys(g);R=m?P.sort(m):P}const F=o?String(e).replace(/\./g,"%2E"):String(e),L=s&&H(g)&&g.length===1?F+"[]":F;if(r&&H(g)&&g.length===0)return L+"[]";for(let P=0;P<R.length;++P){const M=R[P],Wn=typeof M=="object"&&typeof M.value<"u"?M.value:g[M];if(i&&Wn===null)continue;const Bt=p&&o?M.replace(/\./g,"%2E"):M,Aa=H(g)?typeof n=="function"?n(L,Bt):L:L+(p?"."+Bt:"["+Bt+"]");h.set(t,C);const qn=new WeakMap;qn.set(Jt,h),rr(U,ar(Wn,Aa,n,s,r,a,i,o,n==="comma"&&w&&H(g)?null:l,u,m,p,f,d,b,w,$,qn))}return U}function fi(t=j){if(typeof t.allowEmptyArrays<"u"&&typeof t.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof t.encodeDotInKeys<"u"&&typeof t.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(t.encoder!==null&&typeof t.encoder<"u"&&typeof t.encoder!="function")throw new TypeError("Encoder has to be a function.");const e=t.charset||j.charset;if(typeof t.charset<"u"&&t.charset!=="utf-8"&&t.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let n=tr;if(typeof t.format<"u"){if(!en(ns,t.format))throw new TypeError("Unknown format option provided.");n=t.format}const s=ns[n];let r=j.filter;(typeof t.filter=="function"||H(t.filter))&&(r=t.filter);let a;if(t.arrayFormat&&t.arrayFormat in sr?a=t.arrayFormat:"indices"in t?a=t.indices?"indices":"repeat":a=j.arrayFormat,"commaRoundTrip"in t&&typeof t.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");const i=typeof t.allowDots>"u"?t.encodeDotInKeys?!0:j.allowDots:!!t.allowDots;return{addQueryPrefix:typeof t.addQueryPrefix=="boolean"?t.addQueryPrefix:j.addQueryPrefix,allowDots:i,allowEmptyArrays:typeof t.allowEmptyArrays=="boolean"?!!t.allowEmptyArrays:j.allowEmptyArrays,arrayFormat:a,charset:e,charsetSentinel:typeof t.charsetSentinel=="boolean"?t.charsetSentinel:j.charsetSentinel,commaRoundTrip:!!t.commaRoundTrip,delimiter:typeof t.delimiter>"u"?j.delimiter:t.delimiter,encode:typeof t.encode=="boolean"?t.encode:j.encode,encodeDotInKeys:typeof t.encodeDotInKeys=="boolean"?t.encodeDotInKeys:j.encodeDotInKeys,encoder:typeof t.encoder=="function"?t.encoder:j.encoder,encodeValuesOnly:typeof t.encodeValuesOnly=="boolean"?t.encodeValuesOnly:j.encodeValuesOnly,filter:r,format:n,formatter:s,serializeDate:typeof t.serializeDate=="function"?t.serializeDate:j.serializeDate,skipNulls:typeof t.skipNulls=="boolean"?t.skipNulls:j.skipNulls,sort:typeof t.sort=="function"?t.sort:null,strictNullHandling:typeof t.strictNullHandling=="boolean"?t.strictNullHandling:j.strictNullHandling}}function hi(t,e={}){let n=t;const s=fi(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=sr[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||rr(i,ar(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 m=i.join(s.delimiter);let p=s.addQueryPrefix===!0?"?":"";return s.charsetSentinel&&(s.charset==="iso-8859-1"?p+="utf8=%26%2310003%3B&":p+="utf8=%E2%9C%93&"),m.length>0?p+m:""}function mi(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 as;function _n(t){let e;return(as??(e=new globalThis.TextEncoder,as=e.encode.bind(e)))(t)}let is;function os(t){let e;return(is??(e=new globalThis.TextDecoder,is=e.decode.bind(e)))(t)}var V,X;class Pt{constructor(){V.set(this,void 0),X.set(this,void 0),O(this,V,new Uint8Array),O(this,X,null)}decode(e){if(e==null)return[];const n=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?_n(e):e;O(this,V,mi([c(this,V,"f"),n]));const s=[];let r;for(;(r=gi(c(this,V,"f"),c(this,X,"f")))!=null;){if(r.carriage&&c(this,X,"f")==null){O(this,X,r.index);continue}if(c(this,X,"f")!=null&&(r.index!==c(this,X,"f")+1||r.carriage)){s.push(os(c(this,V,"f").subarray(0,c(this,X,"f")-1))),O(this,V,c(this,V,"f").subarray(c(this,X,"f"))),O(this,X,null);continue}const a=c(this,X,"f")!==null?r.preceding-1:r.preceding,i=os(c(this,V,"f").subarray(0,a));s.push(i),O(this,V,c(this,V,"f").subarray(r.index)),O(this,X,null)}return s}flush(){return c(this,V,"f").length?this.decode(`
|
|
@@ -30,4 +30,4 @@ https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
|
|
|
30
30
|
]))`;continue}else if(r[u]==="$"){a+=`($|(?=[\r
|
|
31
31
|
]))`;continue}}if(s.s&&r[u]==="."){a+=o?`${r[u]}\r
|
|
32
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 Ia(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]:S(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",r]})??{}}),{}),additionalProperties:!1};const n={type:"object",additionalProperties:S(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(Oa(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 Lo(t,e){if(e.mapStrategy==="record")return Ia(t,e);const n=S(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},s=S(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 Do(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 Fo(){return{not:{}}}function Bo(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}const St={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Wo(t,e){if(e.target==="openApi3")return As(t,e);const n=t.options instanceof Map?Array.from(t.options.values()):t.options;if(n.every(s=>s._def.typeName in St&&(!s._def.checks||!s._def.checks.length))){const s=n.reduce((r,a)=>{const i=St[a._def.typeName];return i&&!r.includes(i)?[...r,i]:r},[]);return{type:s.length>1?s:s[0]}}else if(n.every(s=>s._def.typeName==="ZodLiteral"&&!s.description)){const s=n.reduce((r,a)=>{const i=typeof a._def.value;switch(i){case"string":case"number":case"boolean":return[...r,i];case"bigint":return[...r,"integer"];case"object":if(a._def.value===null)return[...r,"null"];case"symbol":case"undefined":case"function":default:return r}},[]);if(s.length===n.length){const r=s.filter((a,i,o)=>o.indexOf(a)===i);return{type:r.length>1?r:r[0],enum:n.reduce((a,i)=>a.includes(i._def.value)?a:[...a,i._def.value],[])}}}else if(n.every(s=>s._def.typeName==="ZodEnum"))return{type:"string",enum:n.reduce((s,r)=>[...s,...r._def.values.filter(a=>!s.includes(a))],[])};return As(t,e)}const As=(t,e)=>{const n=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((s,r)=>S(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 qo(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:St[t.innerType._def.typeName],nullable:!0}:{type:[St[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){const s=S(t.innerType._def,{...e,currentPath:[...e.currentPath]});return s&&"$ref"in s?{allOf:[s],nullable:!0}:s&&{...s,nullable:!0}}const n=S(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}function Jo(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",va(n,"type",s.message,e);break;case"min":e.target==="jsonSchema7"?s.inclusive?A(n,"minimum",s.value,s.message,e):A(n,"exclusiveMinimum",s.value,s.message,e):(s.inclusive||(n.exclusiveMinimum=!0),A(n,"minimum",s.value,s.message,e));break;case"max":e.target==="jsonSchema7"?s.inclusive?A(n,"maximum",s.value,s.message,e):A(n,"exclusiveMaximum",s.value,s.message,e):(s.inclusive||(n.exclusiveMaximum=!0),A(n,"maximum",s.value,s.message,e));break;case"multipleOf":A(n,"multipleOf",s.value,s.message,e);break}return n}function Ko(t,e){return e.removeAdditionalStrategy==="strict"?t.catchall._def.typeName==="ZodNever"?t.unknownKeys!=="strict":S(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0:t.catchall._def.typeName==="ZodNever"?t.unknownKeys==="passthrough":S(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0}function Zo(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=S(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:Ko(t,e)};return n.required.length||delete n.required,n}const zo=(t,e)=>{if(e.propertyPath&&e.currentPath.slice(0,e.propertyPath.length).toString()===e.propertyPath.toString())return S(t.innerType._def,{...e,currentPath:e.currentPath});const n=S(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return n?{anyOf:[{not:{}},n]}:{}},Ho=(t,e)=>{if(e.pipeStrategy==="input")return S(t.in._def,e);if(e.pipeStrategy==="output")return S(t.out._def,e);const n=S(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),s=S(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",n?"1":"0"]});return{allOf:[n,s].filter(r=>r!==void 0)}};function Vo(t,e){return S(t.type._def,e)}function Xo(t,e){const s={type:"array",uniqueItems:!0,items:S(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&A(s,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&A(s,"maxItems",t.maxSize.value,t.maxSize.message,e),s}function Go(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((n,s)=>S(n._def,{...e,currentPath:[...e.currentPath,"items",`${s}`]})).reduce((n,s)=>s===void 0?n:[...n,s],[]),additionalItems:S(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((n,s)=>S(n._def,{...e,currentPath:[...e.currentPath,"items",`${s}`]})).reduce((n,s)=>s===void 0?n:[...n,s],[])}}function Qo(){return{not:{}}}function Yo(){return{}}const eu=(t,e)=>S(t.innerType._def,e);function S(t,e,n=!1){const s=e.seen.get(t);if(e.override){const i=e.override?.(t,e,s,n);if(i!==bo)return i}if(s&&!n){const i=tu(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=su(t,t.typeName,e,n);return a&&ru(t,e,a),r.jsonSchema=a,a}const tu=(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:nu(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}},nu=(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("/")},su=(t,e,n,s)=>{switch(e){case I.ZodString:return Oa(t,n);case I.ZodNumber:return Jo(t,n);case I.ZodObject:return Zo(t,n);case I.ZodBigInt:return To(t,n);case I.ZodBoolean:return So();case I.ZodDate:return xa(t,n);case I.ZodUndefined:return Qo();case I.ZodNull:return Bo(n);case I.ZodArray:return ko(t,n);case I.ZodUnion:case I.ZodDiscriminatedUnion:return Wo(t,n);case I.ZodIntersection:return No(t,n);case I.ZodTuple:return Go(t,n);case I.ZodRecord:return Ia(t,n);case I.ZodLiteral:return jo(t,n);case I.ZodEnum:return Eo(t);case I.ZodNativeEnum:return Do(t);case I.ZodNullable:return qo(t,n);case I.ZodOptional:return zo(t,n);case I.ZodMap:return Lo(t,n);case I.ZodSet:return Xo(t,n);case I.ZodLazy:return S(t.getter()._def,n);case I.ZodPromise:return Vo(t,n);case I.ZodNaN:case I.ZodNever:return Fo();case I.ZodEffects:return Po(t,n,s);case I.ZodAny:return Io();case I.ZodUnknown:return Yo();case I.ZodDefault:return $o(t,n);case I.ZodBranded:return Co(t,n);case I.ZodReadonly:return eu(t,n);case I.ZodCatch:return Ao(t,n);case I.ZodPipeline:return Ho(t,n);case I.ZodFunction:case I.ZodVoid:case I.ZodSymbol:return;default:return(r=>{})()}},ru=(t,e,n)=>(t.description&&(n.description=t.description,e.markdownDescription&&(n.markdownDescription=t.description)),n),au=(t,e)=>{const n=Oo(e),s=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,r=S(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(xo(n.definitions))return;const l={},u=new Set;for(let m=0;m<500;m++){const p=Object.entries(n.definitions).filter(([f])=>!u.has(f));if(p.length===0)break;for(const[f,d]of p)l[f]=S(fn(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 iu(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 hn(t){if(typeof t=="boolean")return!1;if(t.type==="null")return!0;for(const e of t.oneOf??[])if(hn(e))return!0;for(const e of t.anyOf??[])if(hn(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(!hn(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 m=t.allOf;if(Array.isArray(m))if(m.length===1){const f=le(m[0],[...e,"allOf","0"],n);Object.assign(t,f),delete t.allOf}else t.allOf=m.map((f,d)=>le(f,[...e,"allOf",String(d)],n));t.default===null&&delete t.default;const p=t.$ref;if(p&&uu(t,1)){if(typeof p!="string")throw new TypeError(`Received non-string $ref - ${p}; path=${e.join("/")}`);const f=ou(n,p);if(typeof f=="boolean")throw new Error(`Expected \`$ref: ${p}\` to resolve to an object schema but got boolean`);if(!he(f))throw new Error(`Expected \`$ref: ${p}\` 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 ou(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 uu(t,e){let n=0;for(const s in t)if(n++,n>e)return!0;return!1}function lu(t,e){return au(t,{openaiStrictMode:!0,name:e.name,nameStrategy:"duplicate-ref",$refStrategy:"extract-to-root",nullableStrategy:"property"})}function cu(t){return iu(Ka(t,{target:"draft-7"}))}function du(t){return"_zod"in t}function pu(t,e,n){return $i({type:"json_schema",json_schema:{...n,name:e,strict:!0,schema:du(t)?cu(t):lu(t,{name:e})}},s=>t.parse(JSON.parse(s)))}const Rs=["jsonSchema","functionCalling","jsonMode"];function fu(t,e){if(typeof e<"u"&&!Rs.includes(e))throw new Error(`Invalid method: ${e}. Supported methods are: ${Rs.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 hu(t,e){const n={...t};return Object.defineProperties(n,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:e,enumerable:!1}}),n}function mu(t,e,n){if($a(t))return pu(t,e,n);if(Pa(t))return hu({type:"json_schema",json_schema:{...n,name:e,strict:!0,schema:$e(t,{cycles:"ref",reused:"ref",override(s){s.jsonSchema.title=e}})}},s=>Za(t,JSON.parse(s)));throw new Error("Unsupported schema response format")}function gu(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 _u={"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 yu=_u,Bn=class extends Ja{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??Jn("OPENAI_API_KEY"),this.organization=t?.configuration?.organization??Jn("OPENAI_ORGANIZATION"),this.model=t?.model??t?.modelName??this.model,this.modelKwargs=t?.modelKwargs??{},this.timeout=t?.timeout,this.temperature=t?.temperature??this.temperature,this.topP=t?.topP??this.topP,this.frequencyPenalty=t?.frequencyPenalty??this.frequencyPenalty,this.presencePenalty=t?.presencePenalty??this.presencePenalty,this.logprobs=t?.logprobs,this.topLogprobs=t?.topLogprobs,this.n=t?.n??this.n,this.logitBias=t?.logitBias,this.stop=t?.stopSequences??t?.stop,this.stopSequences=this.stop,this.user=t?.user,this.__includeRawResponse=t?.__includeRawResponse,this.audio=t?.audio,this.modalities=t?.modalities,this.reasoning=t?.reasoning,this.maxTokens=t?.maxCompletionTokens??t?.maxTokens,this.promptCacheKey=t?.promptCacheKey??this.promptCacheKey,this.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(!He(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&&Xe(t.json_schema.schema)?mu(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=ro(n),r={...this.clientConfig,baseURL:s,timeout:this.timeout,maxRetries:0};r.baseURL||delete r.baseURL,r.defaultHeaders=oo(r.defaultHeaders),this.client=new k(r)}return{...this.clientConfig,...t}}_convertChatOpenAIToolToCompletionsTool(t,e){return Tt(t)?wo(t.metadata.customTool):Us(t)?e?.strict!==void 0?{...t,function:{...t.function,strict:e.strict}}:t:uo(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=>Fn(s)||Tt(s)?s:po(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(Ve(a)),l=a.name!==void 0?s+await this.getNumTokens(a.name):0;let u=i+n+o+l;const m=a;if(m._getType()==="function"&&(u-=2),m.additional_kwargs?.function_call&&(u+=3),m?.additional_kwargs.function_call?.name&&(u+=await this.getNumTokens(m.additional_kwargs.function_call?.name)),m.additional_kwargs.function_call?.arguments)try{u+=await this.getNumTokens(JSON.stringify(JSON.parse(m.additional_kwargs.function_call?.arguments)))}catch(p){console.error("Error parsing function arguments",p,JSON.stringify(m.additional_kwargs.function_call)),u+=await this.getNumTokens(m.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=co(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 Dn(a)}})}get profile(){return yu[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=fu(this.model,e?.method);if(o==="jsonMode"){Xe(r)?s=Hn.fromZodSchema(r):s=new Vn;const p=$e(r);n=this.withConfig({outputVersion:"v0",response_format:{type:"json_object"},ls_structured_output_format:{kwargs:{method:"json_mode"},schema:{title:a??"extract",...p}}})}else if(o==="jsonSchema"){const p={name:a??"extract",description:Ea(r),schema:r,strict:e?.strict},f=$e(p.schema);if(n=this.withConfig({outputVersion:"v0",response_format:{type:"json_schema",json_schema:p},ls_structured_output_format:{kwargs:{method:"json_schema"},schema:{title:p.name,description:p.description,...f}}}),Xe(r)){const d=Hn.fromZodSchema(r);s=Ma.from(b=>"parsed"in b.additional_kwargs?b.additional_kwargs.parsed:d)}else s=new Vn}else{let p=a??"extract";if(Xe(r)){const f=$e(r);n=this.withConfig({outputVersion:"v0",tools:[{type:"function",function:{name:p,description:f.description,parameters:f}}],tool_choice:{type:"function",function:{name:p}},ls_structured_output_format:{kwargs:{method:"function_calling"},schema:{title:p,...f}},...e?.strict!==void 0?{strict:e.strict}:{}}),s=new Gn({returnSingle:!0,keyName:p,zodSchema:r})}else{let f;typeof r.name=="string"&&typeof r.parameters=="object"&&r.parameters!=null?(f=r,p=r.name):(p=r.title??p,f={name:p,description:r.description??"",parameters:r});const d=$e(r);n=this.withConfig({outputVersion:"v0",tools:[{type:"function",function:f}],tool_choice:{type:"function",function:{name:p}},ls_structured_output_format:{kwargs:{method:"function_calling"},schema:{title:p,...d}},...e?.strict!==void 0?{strict:e.strict}:{}}),s=new Gn({returnSingle:!0,keyName:p})}}if(!i)return n.pipe(s);const l=Xn.assign({parsed:(p,f)=>s.invoke(p.raw,f)}),u=Xn.assign({parsed:()=>null}),m=l.withFallbacks({fallbacks:[u]});return Na.from([{raw:n},m])}};const ka={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=Zn({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=zn(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=zn(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=Zn({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`)}},wu=({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(Ds(u,{returnId:!0}))}catch(m){a.push(at(u,m.message))}const i={function_call:t.function_call,tool_calls:s};n!==void 0&&(i.__raw_response=e);const o={model_provider:"openai",model_name:e.model,...e.system_fingerprint?{usage:{...e.usage},system_fingerprint:e.system_fingerprint}:{}};t.audio&&(i.audio=t.audio);const l=gu(t.content||"",e.choices?.[0]?.message);return new Se({content:l,tool_calls:r,invalid_tool_calls:a,additional_kwargs:i,response_metadata:o,id:e.id})}default:return new Es(t.content||"",t.role??"unknown")}},bu=({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 ja({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 mn({content:a,tool_call_chunks:l,additional_kwargs:i,id:e.id,response_metadata:o})}else return r==="system"?new Kn({content:a,response_metadata:o}):r==="developer"?new Kn({content:a,response_metadata:o,additional_kwargs:{__openai_role__:"developer"}}):r==="function"?new Ua({content:a,additional_kwargs:i,name:t.name,response_metadata:o}):r==="tool"?new La({content:a,additional_kwargs:i,tool_call_id:t.tool_call_id,response_metadata:o}):new Da({content:a,role:r,response_metadata:o})},vu=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=Fa(()=>{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}}}},xu=({message:t,model:e})=>{let n=Ve(t);if(n==="system"&&He(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"&&js.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=vu(a);i&&(yield i)}}return{role:"user",content:Array.from(s(t.contentBlocks))}},$s=({messages:t,model:e})=>t.flatMap(n=>{if("output_version"in n.response_metadata&&n.response_metadata?.output_version==="v1")return xu({message:n});let s=Ve(n);s==="system"&&He(e)&&(s="developer");const r=typeof n.content=="string"?n.content:n.content.map(i=>Ms(i)?Ns(i,ka):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),Se.isInstance(n)&&n.tool_calls?.length?a.tool_calls=n.tool_calls.map(Ha):(n.additional_kwargs.tool_calls!=null&&(a.tool_calls=n.additional_kwargs.tool_calls),js.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 Ou=class extends Bn{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:wa(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),He(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=$s({messages:t,model:this.model});if(r.stream){const i=this._streamResponseChunks(t,e,n),o={};for await(const d of i){d.message.response_metadata={...d.generationInfo,...d.message.response_metadata};const b=d.generationInfo?.completion??0;o[b]===void 0?o[b]=d:o[b]=o[b].concat(d)}const l=Object.entries(o).sort(([d],[b])=>parseInt(d,10)-parseInt(b,10)).map(([d,b])=>b),{functions:u,function_call:m}=this.invocationParams(e),p=await this._getEstimatedTokenCountFromPrompt(t,u,m),f=await this._getNumTokensFromGenerations(l);return s.input_tokens=p,s.output_tokens=f,s.total_tokens=p+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:m,completion_tokens_details:p}=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),(m?.audio_tokens!==null||m?.cached_tokens!==null)&&(s.input_token_details={...m?.audio_tokens!==null&&{audio:m?.audio_tokens},...m?.cached_tokens!==null&&{cache_read:m?.cached_tokens}}),(p?.audio_tokens!==null||p?.reasoning_tokens!==null)&&(s.output_token_details={...p?.audio_tokens!==null&&{audio:p?.audio_tokens},...p?.reasoning_tokens!==null&&{reasoning:p?.reasoning_tokens}});const f=[];for(const d of i?.choices??[]){const w={text:d.message?.content??"",message:this._convertCompletionsMessageToBaseMessage(d.message??{role:"assistant"},i)};w.generationInfo={...d.finish_reason?{finish_reason:d.finish_reason}:{},...d.logprobs?{logprobs:d.logprobs}:{}},Ba(w.message)&&(w.message.usage_metadata=s),w.message=new Se(Object.fromEntries(Object.entries(w.message).filter(([$])=>!$.startsWith("lc_")))),f.push(w)}return{generations:f,llmOutput:{tokenUsage:{promptTokens:s.input_tokens,completionTokens:s.output_tokens,totalTokens:s.total_tokens}}}}}async*_streamResponseChunks(t,e,n){const s=$s({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:m}=u;if(!m)continue;const p=this._convertCompletionsDeltaToBaseMessageChunk(m,l,a);a=m.role??a;const f={prompt:e.promptIndex??0,completion:u.index??0};if(typeof p.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 b=new Gt({message:p,text:p.content,generationInfo:d});yield b,await n?.handleLLMNewToken(b.text??"",f,void 0,void 0,void 0,{chunk:b})}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 Gt({message:new mn({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 Dn(r)}})}_convertCompletionsDeltaToBaseMessageChunk(t,e,n){return bu({delta:t,rawResponse:e,includeRawResponse:this.__includeRawResponse,defaultRole:n})}_convertCompletionsMessageToBaseMessage(t,e){return wu({message:t,rawResponse:e,includeRawResponse:this.__includeRawResponse})}};const Ct="__openai_function_call_ids__",Ta=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}},Sa=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(Ds(l,{returnId:!0}))}catch(u){let m;typeof u=="object"&&u!=null&&"message"in u&&typeof u.message=="string"&&(m=u.message),r.push(at(l,m))}i[Ct]??={},o.id&&(i[Ct][o.call_id]=o.id)}else if(o.type==="reasoning")i.reasoning=o;else if(o.type==="custom_tool_call"){const l=ho(o);l?s.push(l):r.push(at(o,"Malformed custom tool call"))}else if(o.type==="computer_call"){const l=mo(o);l?s.push(l):r.push(at(o,"Malformed computer call"))}else i.tool_outputs??=[],i.tool_outputs.push(o);return new Se({id:e,content:n,tool_calls:s,invalid_tool_calls:r,usage_metadata:Ta(t.usage),additional_kwargs:i,response_metadata:a})},Iu=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}},ku=t=>{const e=[];let n={},s;const r=[],a={model_provider:"openai"},i={};let o;if(t.type==="response.output_text.delta")e.push({type:"text",text:t.delta,index:t.content_index});else if(t.type==="response.output_text.annotation.added")e.push({type:"text",text:"",annotations:[t.annotation],index:t.content_index});else if(t.type==="response.output_item.added"&&t.item.type==="message")o=t.item.id;else if(t.type==="response.output_item.added"&&t.item.type==="function_call")r.push({type:"tool_call_chunk",name:t.item.name,args:t.item.arguments,id:t.item.call_id,index:t.output_index}),i[Ct]={[t.item.call_id]:t.item.id};else if(t.type==="response.output_item.done"&&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=Sa(t.response);s=Ta(t.response.usage),t.response.text?.format?.type==="json_schema"&&(i.parsed??=JSON.parse(l.text));for(const[u,m]of Object.entries(t.response))u!=="id"&&(a[u]=m)}else if(t.type==="response.function_call_arguments.delta"||t.type==="response.custom_tool_call_input.delta")r.push({type:"tool_call_chunk",args:t.delta,index:t.output_index});else if(t.type==="response.web_search_call.completed"||t.type==="response.file_search_call.completed")n={tool_outputs:{id:t.item_id,type:t.type.replace("response.","").replace(".completed",""),status:"completed"}};else if(t.type==="response.refusal.done")i.refusal=t.refusal;else if(t.type==="response.output_item.added"&&"item"in t&&t.item.type==="reasoning"){const l=t.item.summary?t.item.summary.map((u,m)=>({...u,index:m})):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 Gt({text:e.map(l=>l.text).join(""),message:new mn({id:o,content:e,tool_call_chunks:r,usage_metadata:s,additional_kwargs:i,response_metadata:a}),generationInfo:n})},Tu=t=>{const e=Se.isInstance(t)&&t.response_metadata?.model_provider==="openai";function*n(){const s=ye(()=>{try{const h=Ve(t);return h==="system"||h==="developer"||h==="assistant"||h==="user"?h:"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 h=r.content;(typeof h=="string"&&h.length>0||Array.isArray(h)&&h.length>0)&&(yield r),r=void 0}const m=h=>{r||(r={type:"message",role:s,content:[]}),typeof r.content=="string"?r.content=r.content.length>0?[{type:"input_text",text:r.content},...h]:[...h]:r.content.push(...h)},p=h=>{if(typeof h=="string")return h;try{return JSON.stringify(h??{})}catch{return"{}"}},f=h=>{const g=ye(()=>{const T=h.metadata?.detail;return T==="low"||T==="high"||T==="auto"?T:"auto"});if(h.fileId)return{type:"input_image",detail:g,file_id:h.fileId};if(h.url)return{type:"input_image",detail:g,image_url:h.url};if(h.data){const T=typeof h.data=="string"?h.data:Buffer.from(h.data).toString("base64"),C=h.mimeType??"image/png";return{type:"input_image",detail:g,image_url:`data:${C};base64,${T}`}}},d=h=>{const g=It(h);if(h.fileId&&typeof g=="string")return{type:"input_file",file_id:h.fileId,...g?{filename:g}:{}};if(h.url&&typeof g=="string")return{type:"input_file",file_url:h.url,...g?{filename:g}:{}};if(h.data&&typeof g=="string"){const T=typeof h.data=="string"?h.data:Buffer.from(h.data).toString("base64");return{type:"input_file",file_data:`data:${h.mimeType??"application/octet-stream"};base64,${T}`,...g?{filename:g}:{}}}},b=h=>{const g=ye(()=>{if(Array.isArray(h.summary)){const U=h.summary?.map(R=>R?.text).filter(R=>typeof R=="string")??[];if(U.length>0)return U}return h.reasoning?[h.reasoning]:[]}),T=g.length>0?g.map(Z=>({type:"summary_text",text:Z})):[{type:"summary_text",text:""}],C={type:"reasoning",id:h.id??"",summary:T};return h.reasoning&&(C.content=[{type:"reasoning_text",text:h.reasoning}]),C},w=h=>({type:"function_call",name:h.name??"",call_id:h.id??"",arguments:p(h.args)}),$=h=>{const g=p(h.output),T=h.status==="success"?"completed":h.status==="error"?"incomplete":void 0;return{type:"function_call_output",call_id:h.toolCallId??"",output:g,...T?{status:T}:{}}};for(const h of t.contentBlocks)if(h.type==="text")m([{type:"input_text",text:h.text}]);else if(h.type!=="invalid_tool_call"){if(h.type==="reasoning")yield*u(),yield b(h);else if(h.type==="tool_call"){yield*u();const g=h.id??"";g&&(a.add(g),o.delete(g)),yield w(h)}else if(h.type==="tool_call_chunk"){if(h.id){const g=o.get(h.id)??{name:h.name,args:[]};h.name&&(g.name=h.name),h.args&&g.args.push(h.args),o.set(h.id,g)}}else if(h.type==="server_tool_call"){yield*u();const g=h.id??"";g&&(i.add(g),l.delete(g)),yield w(h)}else if(h.type==="server_tool_call_chunk"){if(h.id){const g=l.get(h.id)??{name:h.name,args:[]};h.name&&(g.name=h.name),h.args&&g.args.push(h.args),l.set(h.id,g)}}else if(h.type==="server_tool_call_result")yield*u(),yield $(h);else if(h.type!=="audio")if(h.type==="file"){const g=d(h);g&&m([g])}else if(h.type==="image"){const g=f(h);g&&m([g])}else if(h.type==="video"){const g=d(h);g&&m([g])}else h.type==="text-plain"?h.text&&m([{type:"input_text",text:h.text}]):h.type==="non_standard"&&e&&(yield*u(),yield h.value)}yield*u();for(const[h,g]of o){if(!h||a.has(h))continue;const T=g.args.join("");!g.name&&!T||(yield{type:"function_call",call_id:h,name:g.name??"",arguments:T})}for(const[h,g]of l){if(!h||i.has(h))continue;const T=g.args.join("");!g.name&&!T||(yield{type:"function_call",call_id:h,name:g.name??"",arguments:T})}}return Array.from(n())},Ps=({messages:t,zdrEnabled:e,model:n})=>t.flatMap(s=>{const r=s.response_metadata;if(r?.output_version==="v1")return Tu(s);const a=s.additional_kwargs;let i=Ve(s);if(i==="system"&&He(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 m=o.content.find(f=>f.type==="computer_screenshot");if(m)return m;const p=o.content.find(f=>f.type==="image_url");if(p)return{type:"input_image",image_url:typeof p.image_url=="string"?p.image_url:p.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=Iu(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?.[Ct];Se.isInstance(s)&&s.tool_calls?.length?o.push(...s.tool_calls.map(f=>_o(f)?{type:"custom_tool_call",id:f.call_id,call_id:f.id??"",input:f.args.input,name:f.name}:go(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 m=r?.output?.length?r?.output:a.tool_outputs,p=["computer_call","mcp_call","code_interpreter_call","image_generation_call"];if(m!=null){const d=m?.filter(b=>p.includes(b.type));d.length>0&&o.push(...d)}return o}if(i==="user"||i==="system"||i==="developer"){if(typeof s.content=="string")return{type:"message",role:i,content:s.content};const o=[],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}),Ms(u))return Ns(u,ka);if(u.type==="text")return{type:"input_text",text:u.text};if(u.type==="image_url"){const m=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}),p=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:m,detail:p}}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 Su=class extends Bn{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:fo(t?.tool_choice)?t?.tool_choice:(()=>{const r=wa(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:Ps({messages:t,zdrEnabled:this.zdrEnabled??!1,model:this.model}),...n,stream:!1},{signal:e?.signal,...e?.options});return{generations:[{text:s.output_text,message:Sa(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:Ps({messages:t,zdrEnabled:this.zdrEnabled??!1,model:this.model}),stream:!0},e);for await(const r of s){const a=ku(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 Dn(s)}})}_reduceChatOpenAITools(t,e){const n=[];for(const s of t)if(Fn(s))s.type==="image_generation"&&e?.stream&&(s.partial_images=1),n.push(s);else if(Tt(s)){const r=s.metadata.customTool;n.push({type:"custom",name:r.name,description:r.description,format:r.format})}else Us(s)?n.push({type:"function",name:s.function.name,parameters:s.function.parameters,description:s.function.description,strict:e?.strict??null}):ba(s)&&n.push(yo(s));return n}},al=class Ca extends Bn{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 Su(e),this.completions=e?.completions??new Ou(e)}_useResponsesApi(e){const n=e?.tools?.some(Fn),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(ba)||e?.tools?.some(Tt);return this.useResponsesApi||n||s||r||so(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 Ca(this.fields);return n.defaultOptions={...this.defaultOptions,...e},n}};const Cu=K({type:ee("screenshot")}),Au=K({type:ee("click"),x:J(),y:J(),button:Ls(["left","right","wheel","back","forward"]).default("left")}),Ru=K({type:ee("double_click"),x:J(),y:J(),button:Ls(["left","right","wheel","back","forward"]).default("left")}),$u=K({type:ee("drag"),path:At(K({x:J(),y:J()}))}),Pu=K({type:ee("keypress"),keys:At(Q())}),Eu=K({type:ee("move"),x:J(),y:J()}),Mu=K({type:ee("scroll"),x:J(),y:J(),scroll_x:J(),scroll_y:J()}),Nu=K({type:ee("type"),text:Q()}),ju=K({type:ee("wait"),duration:J().optional()}),Uu=gn("type",[Cu,Au,Ru,$u,Pu,Eu,Mu,Nu,ju]);K({action:Uu});const Lu=K({type:ee("exec"),command:At(Q()),env:za(Q(),Q()).optional(),working_directory:Q().optional(),timeout_ms:J().optional(),user:Q().optional()});gn("type",[Lu]);K({commands:At(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 Du=K({type:ee("create_file"),path:Q(),diff:Q()}),Fu=K({type:ee("update_file"),path:Q(),diff:Q()}),Bu=K({type:ee("delete_file"),path:Q()});gn("type",[Du,Fu,Bu]);export{Bn as BaseChatOpenAI,al as ChatOpenAI,Ou as ChatOpenAICompletions,Su as ChatOpenAIResponses,k as OpenAIClient,ka as completionsApiContentBlockConverter,bu as convertCompletionsDeltaToBaseMessageChunk,wu as convertCompletionsMessageToBaseMessage,$s as convertMessagesToCompletionsMessageParams,Ps as convertMessagesToResponsesInput,Iu as convertReasoningSummaryToResponsesReasoningItem,ku as convertResponsesDeltaToChatGenerationChunk,Sa as convertResponsesMessageToAIMessage,Ta as convertResponsesUsageToUsageMetadata,vu as convertStandardContentBlockToCompletionsContentPart,xu as convertStandardContentMessageToCompletionsMessage,Tu as convertStandardContentMessageToResponsesInput,ro as getEndpoint,io as getFormattedEnv,oo as getHeadersWithUserAgent,Ts as isHeaders,Ve as messageToOpenAIRole,ao as normalizeHeaders,Ci as toFile,Dn as wrapOpenAIClientError};
|
|
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 Ia(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]:S(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",r]})??{}}),{}),additionalProperties:!1};const n={type:"object",additionalProperties:S(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(Oa(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 Lo(t,e){if(e.mapStrategy==="record")return Ia(t,e);const n=S(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},s=S(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 Do(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 Fo(){return{not:{}}}function Bo(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}const St={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Wo(t,e){if(e.target==="openApi3")return As(t,e);const n=t.options instanceof Map?Array.from(t.options.values()):t.options;if(n.every(s=>s._def.typeName in St&&(!s._def.checks||!s._def.checks.length))){const s=n.reduce((r,a)=>{const i=St[a._def.typeName];return i&&!r.includes(i)?[...r,i]:r},[]);return{type:s.length>1?s:s[0]}}else if(n.every(s=>s._def.typeName==="ZodLiteral"&&!s.description)){const s=n.reduce((r,a)=>{const i=typeof a._def.value;switch(i){case"string":case"number":case"boolean":return[...r,i];case"bigint":return[...r,"integer"];case"object":if(a._def.value===null)return[...r,"null"];case"symbol":case"undefined":case"function":default:return r}},[]);if(s.length===n.length){const r=s.filter((a,i,o)=>o.indexOf(a)===i);return{type:r.length>1?r:r[0],enum:n.reduce((a,i)=>a.includes(i._def.value)?a:[...a,i._def.value],[])}}}else if(n.every(s=>s._def.typeName==="ZodEnum"))return{type:"string",enum:n.reduce((s,r)=>[...s,...r._def.values.filter(a=>!s.includes(a))],[])};return As(t,e)}const As=(t,e)=>{const n=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((s,r)=>S(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 qo(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:St[t.innerType._def.typeName],nullable:!0}:{type:[St[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){const s=S(t.innerType._def,{...e,currentPath:[...e.currentPath]});return s&&"$ref"in s?{allOf:[s],nullable:!0}:s&&{...s,nullable:!0}}const n=S(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}function Jo(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",va(n,"type",s.message,e);break;case"min":e.target==="jsonSchema7"?s.inclusive?A(n,"minimum",s.value,s.message,e):A(n,"exclusiveMinimum",s.value,s.message,e):(s.inclusive||(n.exclusiveMinimum=!0),A(n,"minimum",s.value,s.message,e));break;case"max":e.target==="jsonSchema7"?s.inclusive?A(n,"maximum",s.value,s.message,e):A(n,"exclusiveMaximum",s.value,s.message,e):(s.inclusive||(n.exclusiveMaximum=!0),A(n,"maximum",s.value,s.message,e));break;case"multipleOf":A(n,"multipleOf",s.value,s.message,e);break}return n}function Ko(t,e){return e.removeAdditionalStrategy==="strict"?t.catchall._def.typeName==="ZodNever"?t.unknownKeys!=="strict":S(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0:t.catchall._def.typeName==="ZodNever"?t.unknownKeys==="passthrough":S(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0}function Zo(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=S(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:Ko(t,e)};return n.required.length||delete n.required,n}const zo=(t,e)=>{if(e.propertyPath&&e.currentPath.slice(0,e.propertyPath.length).toString()===e.propertyPath.toString())return S(t.innerType._def,{...e,currentPath:e.currentPath});const n=S(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return n?{anyOf:[{not:{}},n]}:{}},Ho=(t,e)=>{if(e.pipeStrategy==="input")return S(t.in._def,e);if(e.pipeStrategy==="output")return S(t.out._def,e);const n=S(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),s=S(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",n?"1":"0"]});return{allOf:[n,s].filter(r=>r!==void 0)}};function Vo(t,e){return S(t.type._def,e)}function Xo(t,e){const s={type:"array",uniqueItems:!0,items:S(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&A(s,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&A(s,"maxItems",t.maxSize.value,t.maxSize.message,e),s}function Go(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((n,s)=>S(n._def,{...e,currentPath:[...e.currentPath,"items",`${s}`]})).reduce((n,s)=>s===void 0?n:[...n,s],[]),additionalItems:S(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((n,s)=>S(n._def,{...e,currentPath:[...e.currentPath,"items",`${s}`]})).reduce((n,s)=>s===void 0?n:[...n,s],[])}}function Qo(){return{not:{}}}function Yo(){return{}}const eu=(t,e)=>S(t.innerType._def,e);function S(t,e,n=!1){const s=e.seen.get(t);if(e.override){const i=e.override?.(t,e,s,n);if(i!==bo)return i}if(s&&!n){const i=tu(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=su(t,t.typeName,e,n);return a&&ru(t,e,a),r.jsonSchema=a,a}const tu=(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:nu(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}},nu=(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("/")},su=(t,e,n,s)=>{switch(e){case I.ZodString:return Oa(t,n);case I.ZodNumber:return Jo(t,n);case I.ZodObject:return Zo(t,n);case I.ZodBigInt:return To(t,n);case I.ZodBoolean:return So();case I.ZodDate:return xa(t,n);case I.ZodUndefined:return Qo();case I.ZodNull:return Bo(n);case I.ZodArray:return ko(t,n);case I.ZodUnion:case I.ZodDiscriminatedUnion:return Wo(t,n);case I.ZodIntersection:return No(t,n);case I.ZodTuple:return Go(t,n);case I.ZodRecord:return Ia(t,n);case I.ZodLiteral:return jo(t,n);case I.ZodEnum:return Eo(t);case I.ZodNativeEnum:return Do(t);case I.ZodNullable:return qo(t,n);case I.ZodOptional:return zo(t,n);case I.ZodMap:return Lo(t,n);case I.ZodSet:return Xo(t,n);case I.ZodLazy:return S(t.getter()._def,n);case I.ZodPromise:return Vo(t,n);case I.ZodNaN:case I.ZodNever:return Fo();case I.ZodEffects:return Po(t,n,s);case I.ZodAny:return Io();case I.ZodUnknown:return Yo();case I.ZodDefault:return $o(t,n);case I.ZodBranded:return Co(t,n);case I.ZodReadonly:return eu(t,n);case I.ZodCatch:return Ao(t,n);case I.ZodPipeline:return Ho(t,n);case I.ZodFunction:case I.ZodVoid:case I.ZodSymbol:return;default:return(r=>{})()}},ru=(t,e,n)=>(t.description&&(n.description=t.description,e.markdownDescription&&(n.markdownDescription=t.description)),n),au=(t,e)=>{const n=Oo(e),s=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,r=S(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(xo(n.definitions))return;const l={},u=new Set;for(let m=0;m<500;m++){const p=Object.entries(n.definitions).filter(([f])=>!u.has(f));if(p.length===0)break;for(const[f,d]of p)l[f]=S(fn(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 iu(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 hn(t){if(typeof t=="boolean")return!1;if(t.type==="null")return!0;for(const e of t.oneOf??[])if(hn(e))return!0;for(const e of t.anyOf??[])if(hn(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(!hn(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 m=t.allOf;if(Array.isArray(m))if(m.length===1){const f=le(m[0],[...e,"allOf","0"],n);Object.assign(t,f),delete t.allOf}else t.allOf=m.map((f,d)=>le(f,[...e,"allOf",String(d)],n));t.default===null&&delete t.default;const p=t.$ref;if(p&&uu(t,1)){if(typeof p!="string")throw new TypeError(`Received non-string $ref - ${p}; path=${e.join("/")}`);const f=ou(n,p);if(typeof f=="boolean")throw new Error(`Expected \`$ref: ${p}\` to resolve to an object schema but got boolean`);if(!he(f))throw new Error(`Expected \`$ref: ${p}\` 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 ou(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 uu(t,e){let n=0;for(const s in t)if(n++,n>e)return!0;return!1}function lu(t,e){return au(t,{openaiStrictMode:!0,name:e.name,nameStrategy:"duplicate-ref",$refStrategy:"extract-to-root",nullableStrategy:"property"})}function cu(t){return iu(Ka(t,{target:"draft-7"}))}function du(t){return"_zod"in t}function pu(t,e,n){return $i({type:"json_schema",json_schema:{...n,name:e,strict:!0,schema:du(t)?cu(t):lu(t,{name:e})}},s=>t.parse(JSON.parse(s)))}const Rs=["jsonSchema","functionCalling","jsonMode"];function fu(t,e){if(typeof e<"u"&&!Rs.includes(e))throw new Error(`Invalid method: ${e}. Supported methods are: ${Rs.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 hu(t,e){const n={...t};return Object.defineProperties(n,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:e,enumerable:!1}}),n}function mu(t,e,n){if($a(t))return pu(t,e,n);if(Pa(t))return hu({type:"json_schema",json_schema:{...n,name:e,strict:!0,schema:$e(t,{cycles:"ref",reused:"ref",override(s){s.jsonSchema.title=e}})}},s=>Za(t,JSON.parse(s)));throw new Error("Unsupported schema response format")}function gu(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 _u={"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 yu=_u,Bn=class extends Ja{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??Jn("OPENAI_API_KEY"),this.organization=t?.configuration?.organization??Jn("OPENAI_ORGANIZATION"),this.model=t?.model??t?.modelName??this.model,this.modelKwargs=t?.modelKwargs??{},this.timeout=t?.timeout,this.temperature=t?.temperature??this.temperature,this.topP=t?.topP??this.topP,this.frequencyPenalty=t?.frequencyPenalty??this.frequencyPenalty,this.presencePenalty=t?.presencePenalty??this.presencePenalty,this.logprobs=t?.logprobs,this.topLogprobs=t?.topLogprobs,this.n=t?.n??this.n,this.logitBias=t?.logitBias,this.stop=t?.stopSequences??t?.stop,this.stopSequences=this.stop,this.user=t?.user,this.__includeRawResponse=t?.__includeRawResponse,this.audio=t?.audio,this.modalities=t?.modalities,this.reasoning=t?.reasoning,this.maxTokens=t?.maxCompletionTokens??t?.maxTokens,this.promptCacheKey=t?.promptCacheKey??this.promptCacheKey,this.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(!He(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&&Xe(t.json_schema.schema)?mu(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=ro(n),r={...this.clientConfig,baseURL:s,timeout:this.timeout,maxRetries:0};r.baseURL||delete r.baseURL,r.defaultHeaders=oo(r.defaultHeaders),this.client=new k(r)}return{...this.clientConfig,...t}}_convertChatOpenAIToolToCompletionsTool(t,e){return Tt(t)?wo(t.metadata.customTool):Us(t)?e?.strict!==void 0?{...t,function:{...t.function,strict:e.strict}}:t:uo(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=>Fn(s)||Tt(s)?s:po(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(Ve(a)),l=a.name!==void 0?s+await this.getNumTokens(a.name):0;let u=i+n+o+l;const m=a;if(m._getType()==="function"&&(u-=2),m.additional_kwargs?.function_call&&(u+=3),m?.additional_kwargs.function_call?.name&&(u+=await this.getNumTokens(m.additional_kwargs.function_call?.name)),m.additional_kwargs.function_call?.arguments)try{u+=await this.getNumTokens(JSON.stringify(JSON.parse(m.additional_kwargs.function_call?.arguments)))}catch(p){console.error("Error parsing function arguments",p,JSON.stringify(m.additional_kwargs.function_call)),u+=await this.getNumTokens(m.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=co(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 Dn(a)}})}get profile(){return yu[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=fu(this.model,e?.method);if(o==="jsonMode"){Xe(r)?s=Hn.fromZodSchema(r):s=new Vn;const p=$e(r);n=this.withConfig({outputVersion:"v0",response_format:{type:"json_object"},ls_structured_output_format:{kwargs:{method:"json_mode"},schema:{title:a??"extract",...p}}})}else if(o==="jsonSchema"){const p={name:a??"extract",description:Ea(r),schema:r,strict:e?.strict},f=$e(p.schema);if(n=this.withConfig({outputVersion:"v0",response_format:{type:"json_schema",json_schema:p},ls_structured_output_format:{kwargs:{method:"json_schema"},schema:{title:p.name,description:p.description,...f}}}),Xe(r)){const d=Hn.fromZodSchema(r);s=Ma.from(b=>"parsed"in b.additional_kwargs?b.additional_kwargs.parsed:d)}else s=new Vn}else{let p=a??"extract";if(Xe(r)){const f=$e(r);n=this.withConfig({outputVersion:"v0",tools:[{type:"function",function:{name:p,description:f.description,parameters:f}}],tool_choice:{type:"function",function:{name:p}},ls_structured_output_format:{kwargs:{method:"function_calling"},schema:{title:p,...f}},...e?.strict!==void 0?{strict:e.strict}:{}}),s=new Gn({returnSingle:!0,keyName:p,zodSchema:r})}else{let f;typeof r.name=="string"&&typeof r.parameters=="object"&&r.parameters!=null?(f=r,p=r.name):(p=r.title??p,f={name:p,description:r.description??"",parameters:r});const d=$e(r);n=this.withConfig({outputVersion:"v0",tools:[{type:"function",function:f}],tool_choice:{type:"function",function:{name:p}},ls_structured_output_format:{kwargs:{method:"function_calling"},schema:{title:p,...d}},...e?.strict!==void 0?{strict:e.strict}:{}}),s=new Gn({returnSingle:!0,keyName:p})}}if(!i)return n.pipe(s);const l=Xn.assign({parsed:(p,f)=>s.invoke(p.raw,f)}),u=Xn.assign({parsed:()=>null}),m=l.withFallbacks({fallbacks:[u]});return Na.from([{raw:n},m])}};const ka={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=Zn({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=zn(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=zn(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=Zn({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`)}},wu=({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(Ds(u,{returnId:!0}))}catch(m){a.push(at(u,m.message))}const i={function_call:t.function_call,tool_calls:s};n!==void 0&&(i.__raw_response=e);const o={model_provider:"openai",model_name:e.model,...e.system_fingerprint?{usage:{...e.usage},system_fingerprint:e.system_fingerprint}:{}};t.audio&&(i.audio=t.audio);const l=gu(t.content||"",e.choices?.[0]?.message);return new Se({content:l,tool_calls:r,invalid_tool_calls:a,additional_kwargs:i,response_metadata:o,id:e.id})}default:return new Es(t.content||"",t.role??"unknown")}},bu=({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 ja({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 mn({content:a,tool_call_chunks:l,additional_kwargs:i,id:e.id,response_metadata:o})}else return r==="system"?new Kn({content:a,response_metadata:o}):r==="developer"?new Kn({content:a,response_metadata:o,additional_kwargs:{__openai_role__:"developer"}}):r==="function"?new Ua({content:a,additional_kwargs:i,name:t.name,response_metadata:o}):r==="tool"?new La({content:a,additional_kwargs:i,tool_call_id:t.tool_call_id,response_metadata:o}):new Da({content:a,role:r,response_metadata:o})},vu=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=Fa(()=>{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}}}},xu=({message:t,model:e})=>{let n=Ve(t);if(n==="system"&&He(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"&&js.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=vu(a);i&&(yield i)}}return{role:"user",content:Array.from(s(t.contentBlocks))}},$s=({messages:t,model:e})=>t.flatMap(n=>{if("output_version"in n.response_metadata&&n.response_metadata?.output_version==="v1")return xu({message:n});let s=Ve(n);s==="system"&&He(e)&&(s="developer");const r=typeof n.content=="string"?n.content:n.content.map(i=>Ms(i)?Ns(i,ka):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),Se.isInstance(n)&&n.tool_calls?.length?a.tool_calls=n.tool_calls.map(Ha):(n.additional_kwargs.tool_calls!=null&&(a.tool_calls=n.additional_kwargs.tool_calls),js.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 Ou=class extends Bn{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:wa(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),He(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=$s({messages:t,model:this.model});if(r.stream){const i=this._streamResponseChunks(t,e,n),o={};for await(const d of i){d.message.response_metadata={...d.generationInfo,...d.message.response_metadata};const b=d.generationInfo?.completion??0;o[b]===void 0?o[b]=d:o[b]=o[b].concat(d)}const l=Object.entries(o).sort(([d],[b])=>parseInt(d,10)-parseInt(b,10)).map(([d,b])=>b),{functions:u,function_call:m}=this.invocationParams(e),p=await this._getEstimatedTokenCountFromPrompt(t,u,m),f=await this._getNumTokensFromGenerations(l);return s.input_tokens=p,s.output_tokens=f,s.total_tokens=p+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:m,completion_tokens_details:p}=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),(m?.audio_tokens!==null||m?.cached_tokens!==null)&&(s.input_token_details={...m?.audio_tokens!==null&&{audio:m?.audio_tokens},...m?.cached_tokens!==null&&{cache_read:m?.cached_tokens}}),(p?.audio_tokens!==null||p?.reasoning_tokens!==null)&&(s.output_token_details={...p?.audio_tokens!==null&&{audio:p?.audio_tokens},...p?.reasoning_tokens!==null&&{reasoning:p?.reasoning_tokens}});const f=[];for(const d of i?.choices??[]){const w={text:d.message?.content??"",message:this._convertCompletionsMessageToBaseMessage(d.message??{role:"assistant"},i)};w.generationInfo={...d.finish_reason?{finish_reason:d.finish_reason}:{},...d.logprobs?{logprobs:d.logprobs}:{}},Ba(w.message)&&(w.message.usage_metadata=s),w.message=new Se(Object.fromEntries(Object.entries(w.message).filter(([$])=>!$.startsWith("lc_")))),f.push(w)}return{generations:f,llmOutput:{tokenUsage:{promptTokens:s.input_tokens,completionTokens:s.output_tokens,totalTokens:s.total_tokens}}}}}async*_streamResponseChunks(t,e,n){const s=$s({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:m}=u;if(!m)continue;const p=this._convertCompletionsDeltaToBaseMessageChunk(m,l,a);a=m.role??a;const f={prompt:e.promptIndex??0,completion:u.index??0};if(typeof p.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 b=new Gt({message:p,text:p.content,generationInfo:d});yield b,await n?.handleLLMNewToken(b.text??"",f,void 0,void 0,void 0,{chunk:b})}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 Gt({message:new mn({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 Dn(r)}})}_convertCompletionsDeltaToBaseMessageChunk(t,e,n){return bu({delta:t,rawResponse:e,includeRawResponse:this.__includeRawResponse,defaultRole:n})}_convertCompletionsMessageToBaseMessage(t,e){return wu({message:t,rawResponse:e,includeRawResponse:this.__includeRawResponse})}};const Ct="__openai_function_call_ids__",Ta=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}},Sa=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(Ds(l,{returnId:!0}))}catch(u){let m;typeof u=="object"&&u!=null&&"message"in u&&typeof u.message=="string"&&(m=u.message),r.push(at(l,m))}i[Ct]??={},o.id&&(i[Ct][o.call_id]=o.id)}else if(o.type==="reasoning")i.reasoning=o;else if(o.type==="custom_tool_call"){const l=ho(o);l?s.push(l):r.push(at(o,"Malformed custom tool call"))}else if(o.type==="computer_call"){const l=mo(o);l?s.push(l):r.push(at(o,"Malformed computer call"))}else i.tool_outputs??=[],i.tool_outputs.push(o);return new Se({id:e,content:n,tool_calls:s,invalid_tool_calls:r,usage_metadata:Ta(t.usage),additional_kwargs:i,response_metadata:a})},Iu=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}},ku=t=>{const e=[];let n={},s;const r=[],a={model_provider:"openai"},i={};let o;if(t.type==="response.output_text.delta")e.push({type:"text",text:t.delta,index:t.content_index});else if(t.type==="response.output_text.annotation.added")e.push({type:"text",text:"",annotations:[t.annotation],index:t.content_index});else if(t.type==="response.output_item.added"&&t.item.type==="message")o=t.item.id;else if(t.type==="response.output_item.added"&&t.item.type==="function_call")r.push({type:"tool_call_chunk",name:t.item.name,args:t.item.arguments,id:t.item.call_id,index:t.output_index}),i[Ct]={[t.item.call_id]:t.item.id};else if(t.type==="response.output_item.done"&&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=Sa(t.response);s=Ta(t.response.usage),t.response.text?.format?.type==="json_schema"&&(i.parsed??=JSON.parse(l.text));for(const[u,m]of Object.entries(t.response))u!=="id"&&(a[u]=m)}else if(t.type==="response.function_call_arguments.delta"||t.type==="response.custom_tool_call_input.delta")r.push({type:"tool_call_chunk",args:t.delta,index:t.output_index});else if(t.type==="response.web_search_call.completed"||t.type==="response.file_search_call.completed")n={tool_outputs:{id:t.item_id,type:t.type.replace("response.","").replace(".completed",""),status:"completed"}};else if(t.type==="response.refusal.done")i.refusal=t.refusal;else if(t.type==="response.output_item.added"&&"item"in t&&t.item.type==="reasoning"){const l=t.item.summary?t.item.summary.map((u,m)=>({...u,index:m})):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 Gt({text:e.map(l=>l.text).join(""),message:new mn({id:o,content:e,tool_call_chunks:r,usage_metadata:s,additional_kwargs:i,response_metadata:a}),generationInfo:n})},Tu=t=>{const e=Se.isInstance(t)&&t.response_metadata?.model_provider==="openai";function*n(){const s=ye(()=>{try{const h=Ve(t);return h==="system"||h==="developer"||h==="assistant"||h==="user"?h:"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 h=r.content;(typeof h=="string"&&h.length>0||Array.isArray(h)&&h.length>0)&&(yield r),r=void 0}const m=h=>{r||(r={type:"message",role:s,content:[]}),typeof r.content=="string"?r.content=r.content.length>0?[{type:"input_text",text:r.content},...h]:[...h]:r.content.push(...h)},p=h=>{if(typeof h=="string")return h;try{return JSON.stringify(h??{})}catch{return"{}"}},f=h=>{const g=ye(()=>{const T=h.metadata?.detail;return T==="low"||T==="high"||T==="auto"?T:"auto"});if(h.fileId)return{type:"input_image",detail:g,file_id:h.fileId};if(h.url)return{type:"input_image",detail:g,image_url:h.url};if(h.data){const T=typeof h.data=="string"?h.data:Buffer.from(h.data).toString("base64"),C=h.mimeType??"image/png";return{type:"input_image",detail:g,image_url:`data:${C};base64,${T}`}}},d=h=>{const g=It(h);if(h.fileId&&typeof g=="string")return{type:"input_file",file_id:h.fileId,...g?{filename:g}:{}};if(h.url&&typeof g=="string")return{type:"input_file",file_url:h.url,...g?{filename:g}:{}};if(h.data&&typeof g=="string"){const T=typeof h.data=="string"?h.data:Buffer.from(h.data).toString("base64");return{type:"input_file",file_data:`data:${h.mimeType??"application/octet-stream"};base64,${T}`,...g?{filename:g}:{}}}},b=h=>{const g=ye(()=>{if(Array.isArray(h.summary)){const U=h.summary?.map(R=>R?.text).filter(R=>typeof R=="string")??[];if(U.length>0)return U}return h.reasoning?[h.reasoning]:[]}),T=g.length>0?g.map(Z=>({type:"summary_text",text:Z})):[{type:"summary_text",text:""}],C={type:"reasoning",id:h.id??"",summary:T};return h.reasoning&&(C.content=[{type:"reasoning_text",text:h.reasoning}]),C},w=h=>({type:"function_call",name:h.name??"",call_id:h.id??"",arguments:p(h.args)}),$=h=>{const g=p(h.output),T=h.status==="success"?"completed":h.status==="error"?"incomplete":void 0;return{type:"function_call_output",call_id:h.toolCallId??"",output:g,...T?{status:T}:{}}};for(const h of t.contentBlocks)if(h.type==="text")m([{type:"input_text",text:h.text}]);else if(h.type!=="invalid_tool_call"){if(h.type==="reasoning")yield*u(),yield b(h);else if(h.type==="tool_call"){yield*u();const g=h.id??"";g&&(a.add(g),o.delete(g)),yield w(h)}else if(h.type==="tool_call_chunk"){if(h.id){const g=o.get(h.id)??{name:h.name,args:[]};h.name&&(g.name=h.name),h.args&&g.args.push(h.args),o.set(h.id,g)}}else if(h.type==="server_tool_call"){yield*u();const g=h.id??"";g&&(i.add(g),l.delete(g)),yield w(h)}else if(h.type==="server_tool_call_chunk"){if(h.id){const g=l.get(h.id)??{name:h.name,args:[]};h.name&&(g.name=h.name),h.args&&g.args.push(h.args),l.set(h.id,g)}}else if(h.type==="server_tool_call_result")yield*u(),yield $(h);else if(h.type!=="audio")if(h.type==="file"){const g=d(h);g&&m([g])}else if(h.type==="image"){const g=f(h);g&&m([g])}else if(h.type==="video"){const g=d(h);g&&m([g])}else h.type==="text-plain"?h.text&&m([{type:"input_text",text:h.text}]):h.type==="non_standard"&&e&&(yield*u(),yield h.value)}yield*u();for(const[h,g]of o){if(!h||a.has(h))continue;const T=g.args.join("");!g.name&&!T||(yield{type:"function_call",call_id:h,name:g.name??"",arguments:T})}for(const[h,g]of l){if(!h||i.has(h))continue;const T=g.args.join("");!g.name&&!T||(yield{type:"function_call",call_id:h,name:g.name??"",arguments:T})}}return Array.from(n())},Ps=({messages:t,zdrEnabled:e,model:n})=>t.flatMap(s=>{const r=s.response_metadata;if(r?.output_version==="v1")return Tu(s);const a=s.additional_kwargs;let i=Ve(s);if(i==="system"&&He(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 m=o.content.find(f=>f.type==="computer_screenshot");if(m)return m;const p=o.content.find(f=>f.type==="image_url");if(p)return{type:"input_image",image_url:typeof p.image_url=="string"?p.image_url:p.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=Iu(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?.[Ct];Se.isInstance(s)&&s.tool_calls?.length?o.push(...s.tool_calls.map(f=>_o(f)?{type:"custom_tool_call",id:f.call_id,call_id:f.id??"",input:f.args.input,name:f.name}:go(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 m=r?.output?.length?r?.output:a.tool_outputs,p=["computer_call","mcp_call","code_interpreter_call","image_generation_call"];if(m!=null){const d=m?.filter(b=>p.includes(b.type));d.length>0&&o.push(...d)}return o}if(i==="user"||i==="system"||i==="developer"){if(typeof s.content=="string")return{type:"message",role:i,content:s.content};const o=[],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}),Ms(u))return Ns(u,ka);if(u.type==="text")return{type:"input_text",text:u.text};if(u.type==="image_url"){const m=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}),p=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:m,detail:p}}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 Su=class extends Bn{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:fo(t?.tool_choice)?t?.tool_choice:(()=>{const r=wa(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:Ps({messages:t,zdrEnabled:this.zdrEnabled??!1,model:this.model}),...n,stream:!1},{signal:e?.signal,...e?.options});return{generations:[{text:s.output_text,message:Sa(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:Ps({messages:t,zdrEnabled:this.zdrEnabled??!1,model:this.model}),stream:!0},e);for await(const r of s){const a=ku(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 Dn(s)}})}_reduceChatOpenAITools(t,e){const n=[];for(const s of t)if(Fn(s))s.type==="image_generation"&&e?.stream&&(s.partial_images=1),n.push(s);else if(Tt(s)){const r=s.metadata.customTool;n.push({type:"custom",name:r.name,description:r.description,format:r.format})}else Us(s)?n.push({type:"function",name:s.function.name,parameters:s.function.parameters,description:s.function.description,strict:e?.strict??null}):ba(s)&&n.push(yo(s));return n}},rl=class Ca extends Bn{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 Su(e),this.completions=e?.completions??new Ou(e)}_useResponsesApi(e){const n=e?.tools?.some(Fn),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(ba)||e?.tools?.some(Tt);return this.useResponsesApi||n||s||r||so(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 Ca(this.fields);return n.defaultOptions={...this.defaultOptions,...e},n}};const Cu=K({type:ee("screenshot")}),Au=K({type:ee("click"),x:J(),y:J(),button:Ls(["left","right","wheel","back","forward"]).default("left")}),Ru=K({type:ee("double_click"),x:J(),y:J(),button:Ls(["left","right","wheel","back","forward"]).default("left")}),$u=K({type:ee("drag"),path:At(K({x:J(),y:J()}))}),Pu=K({type:ee("keypress"),keys:At(Q())}),Eu=K({type:ee("move"),x:J(),y:J()}),Mu=K({type:ee("scroll"),x:J(),y:J(),scroll_x:J(),scroll_y:J()}),Nu=K({type:ee("type"),text:Q()}),ju=K({type:ee("wait"),duration:J().optional()}),Uu=gn("type",[Cu,Au,Ru,$u,Pu,Eu,Mu,Nu,ju]);K({action:Uu});const Lu=K({type:ee("exec"),command:At(Q()),env:za(Q(),Q()).optional(),working_directory:Q().optional(),timeout_ms:J().optional(),user:Q().optional()});gn("type",[Lu]);K({commands:At(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 Du=K({type:ee("create_file"),path:Q(),diff:Q()}),Fu=K({type:ee("update_file"),path:Q(),diff:Q()}),Bu=K({type:ee("delete_file"),path:Q()});gn("type",[Du,Fu,Bu]);export{Bn as BaseChatOpenAI,rl as ChatOpenAI,Ou as ChatOpenAICompletions,Su as ChatOpenAIResponses,k as OpenAIClient,ka as completionsApiContentBlockConverter,bu as convertCompletionsDeltaToBaseMessageChunk,wu as convertCompletionsMessageToBaseMessage,$s as convertMessagesToCompletionsMessageParams,Ps as convertMessagesToResponsesInput,Iu as convertReasoningSummaryToResponsesReasoningItem,ku as convertResponsesDeltaToChatGenerationChunk,Sa as convertResponsesMessageToAIMessage,Ta as convertResponsesUsageToUsageMetadata,vu as convertStandardContentBlockToCompletionsContentPart,xu as convertStandardContentMessageToCompletionsMessage,Tu as convertStandardContentMessageToResponsesInput,ro as getEndpoint,io as getFormattedEnv,oo as getHeadersWithUserAgent,Ts as isHeaders,Ve as messageToOpenAIRole,ao as normalizeHeaders,Ci as toFile,Dn as wrapOpenAIClientError};
|