scordi-extension 1.14.2 → 1.14.4
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/.vite/manifest.json +12 -12
- package/dist/assets/index-BAWpTgrx.js +4 -0
- package/dist/assets/index.ts-Yg98L0Rk.js +158 -0
- package/dist/assets/main.tsx-CiPjkJNz.js +2 -0
- package/dist/assets/main.tsx-loader-CRGmwXNh.js +13 -0
- package/dist/assets/types-oHwqLVs0.js +1 -0
- package/dist/blocks/EventClickBlock.d.ts +4 -4
- package/dist/blocks/GetElementDataBlock.d.ts +6 -6
- package/dist/blocks/GetTextBlock.d.ts +2 -2
- package/dist/blocks/index.d.ts +12 -12
- package/dist/manifest.json +7 -4
- package/dist/sdk/index.d.ts +1 -0
- package/dist/sdk/index.d.ts.map +1 -1
- package/dist/sdk/index.js +1223 -6438
- package/dist/sdk/types.d.ts +2 -2
- package/dist/sdk/types.d.ts.map +1 -1
- package/dist/service-worker-loader.js +1 -3
- package/dist/src/popup/index.html +6 -7
- package/package.json +12 -3
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
import{i as lh,b as dh,c as hh,d as fh}from"./internal-messages-Drf0Gb9U.js";import{g as Rr,Z as S,a as Ft,o as gr,s as mi,b as so,c as ph,l as mh,u as gh,n as _h,e as yh}from"./types-oHwqLVs0.js";class bh{activeTabs=new Map;async createTab(e,t=!1,r=2e3){const s=await chrome.tabs.create({url:e,active:t});if(!s.id)throw new Error("Failed to create new tab");return this.activeTabs.set(s.id,{url:e,createdAt:Date.now()}),await this.waitForTabLoad(s.id),await new Promise(a=>setTimeout(a,r)),s}async closeTab(e){await chrome.tabs.remove(e),this.activeTabs.delete(e)}async waitForTabLoad(e,t=3e4){return new Promise((r,s)=>{const a=setTimeout(()=>{chrome.tabs.onUpdated.removeListener(i),s(new Error("Tab load timeout"))},t),i=(o,u)=>{o===e&&u.status==="complete"&&(clearTimeout(a),chrome.tabs.onUpdated.removeListener(i),console.log("[8G TabManager] Tab loaded successfully:",e),r())};chrome.tabs.onUpdated.addListener(i)})}async executeBlock(e,t){return new Promise((r,s)=>{const a={isBlock:!0,type:"EXECUTE_BLOCK",data:e};chrome.tabs.sendMessage(t,a,i=>{chrome.runtime.lastError?(console.log("Error sending message:",chrome.runtime.lastError),s(new Error(chrome.runtime.lastError.message||"Communication error"))):lh(i)?(console.log("Content script error:",i.message),s(new Error(i.message))):(console.log("Received response from content script:",i),r(i||{data:null}))})})}}function M(n,e,t,r,s){if(typeof e=="function"?n!==e||!0:!e.has(n))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(n,t),t}function w(n,e,t,r){if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?n!==e||!r:!e.has(n))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?r:t==="a"?r.call(n):r?r.value:e.get(n)}let jc=function(){const{crypto:n}=globalThis;if(n?.randomUUID)return jc=n.randomUUID.bind(n),n.randomUUID();const e=new Uint8Array(1),t=n?()=>n.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,r=>(+r^t()&15>>+r/4).toString(16))};function Da(n){return typeof n=="object"&&n!==null&&("name"in n&&n.name==="AbortError"||"message"in n&&String(n.message).includes("FetchRequestCanceledException"))}const Fa=n=>{if(n instanceof Error)return n;if(typeof n=="object"&&n!==null){try{if(Object.prototype.toString.call(n)==="[object Error]"){const e=new Error(n.message,n.cause?{cause:n.cause}:{});return n.stack&&(e.stack=n.stack),n.cause&&!e.cause&&(e.cause=n.cause),n.name&&(e.name=n.name),e}}catch{}try{return new Error(JSON.stringify(n))}catch{}}return new Error(n)};class L extends Error{}class me extends L{constructor(e,t,r,s){super(`${me.makeMessage(e,t,r)}`),this.status=e,this.headers=s,this.requestID=s?.get("x-request-id"),this.error=t;const a=t;this.code=a?.code,this.param=a?.param,this.type=a?.type}static makeMessage(e,t,r){const s=t?.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):r;return e&&s?`${e} ${s}`:e?`${e} status code (no body)`:s||"(no status code or body)"}static generate(e,t,r,s){if(!e||!s)return new Bn({message:r,cause:Fa(t)});const a=t?.error;return e===400?new Lc(e,a,r,s):e===401?new Mc(e,a,r,s):e===403?new Uc(e,a,r,s):e===404?new Dc(e,a,r,s):e===409?new Fc(e,a,r,s):e===422?new Bc(e,a,r,s):e===429?new zc(e,a,r,s):e>=500?new qc(e,a,r,s):new me(e,a,r,s)}}class Ce extends me{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class Bn extends me{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}}class zn extends Bn{constructor({message:e}={}){super({message:e??"Request timed out."})}}class Lc extends me{}class Mc extends me{}class Uc extends me{}class Dc extends me{}class Fc extends me{}class Bc extends me{}class zc extends me{}class qc extends me{}class Hc extends L{constructor(){super("Could not parse response content as the length limit was reached")}}class Gc extends L{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}class ar extends Error{constructor(e){super(e)}}const wh=/^[a-z][a-z0-9+.-]*:/i,vh=n=>wh.test(n);let Te=n=>(Te=Array.isArray,Te(n)),ao=Te;function Eh(n){return typeof n!="object"?{}:n??{}}function Sh(n){if(!n)return!0;for(const e in n)return!1;return!0}function Oh(n,e){return Object.prototype.hasOwnProperty.call(n,e)}function ps(n){return n!=null&&typeof n=="object"&&!Array.isArray(n)}const Th=(n,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new L(`${n} must be an integer`);if(e<0)throw new L(`${n} must be a positive integer`);return e},Ah=n=>{try{return JSON.parse(n)}catch{return}},kr=n=>new Promise(e=>setTimeout(e,n)),Lt="5.12.2",Ph=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function Ih(){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 xh=()=>{const n=Ih();if(n==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Lt,"X-Stainless-OS":oo(Deno.build.os),"X-Stainless-Arch":io(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":Lt,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(n==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Lt,"X-Stainless-OS":oo(globalThis.process.platform??"unknown"),"X-Stainless-Arch":io(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};const e=Rh();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Lt,"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":Lt,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function Rh(){if(typeof navigator>"u"||!navigator)return null;const n=[{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:t}of n){const r=t.exec(navigator.userAgent);if(r){const s=r[1]||0,a=r[2]||0,i=r[3]||0;return{browser:e,version:`${s}.${a}.${i}`}}}return null}const io=n=>n==="x32"?"x32":n==="x86_64"||n==="x64"?"x64":n==="arm"?"arm":n==="aarch64"||n==="arm64"?"arm64":n?`other:${n}`:"unknown",oo=n=>(n=n.toLowerCase(),n.includes("ios")?"iOS":n==="android"?"Android":n==="darwin"?"MacOS":n==="win32"?"Windows":n==="freebsd"?"FreeBSD":n==="openbsd"?"OpenBSD":n==="linux"?"Linux":n?`Other:${n}`:"Unknown");let uo;const kh=()=>uo??(uo=xh());function Ch(){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 Jc(...n){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(...n)}function Wc(n){let e=Symbol.asyncIterator in n?n[Symbol.asyncIterator]():n[Symbol.iterator]();return Jc({start(){},async pull(t){const{done:r,value:s}=await e.next();r?t.close():t.enqueue(s)},async cancel(){await e.return?.()}})}function Zc(n){if(n[Symbol.asyncIterator])return n;const e=n.getReader();return{async next(){try{const t=await e.read();return t?.done&&e.releaseLock(),t}catch(t){throw e.releaseLock(),t}},async return(){const t=e.cancel();return e.releaseLock(),await t,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function $h(n){if(n===null||typeof n!="object")return;if(n[Symbol.asyncIterator]){await n[Symbol.asyncIterator]().return?.();return}const e=n.getReader(),t=e.cancel();e.releaseLock(),await t}const Nh=({headers:n,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)}),Kc="RFC3986",Vc=n=>String(n),co={RFC1738:n=>String(n).replace(/%20/g,"+"),RFC3986:Vc},jh="RFC1738";let Ba=(n,e)=>(Ba=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),Ba(n,e));const Ze=(()=>{const n=[];for(let e=0;e<256;++e)n.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return n})(),ms=1024,Lh=(n,e,t,r,s)=>{if(n.length===0)return n;let a=n;if(typeof n=="symbol"?a=Symbol.prototype.toString.call(n):typeof n!="string"&&(a=String(n)),t==="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+=ms){const u=a.length>=ms?a.slice(o,o+ms):a,c=[];for(let l=0;l<u.length;++l){let d=u.charCodeAt(l);if(d===45||d===46||d===95||d===126||d>=48&&d<=57||d>=65&&d<=90||d>=97&&d<=122||s===jh&&(d===40||d===41)){c[c.length]=u.charAt(l);continue}if(d<128){c[c.length]=Ze[d];continue}if(d<2048){c[c.length]=Ze[192|d>>6]+Ze[128|d&63];continue}if(d<55296||d>=57344){c[c.length]=Ze[224|d>>12]+Ze[128|d>>6&63]+Ze[128|d&63];continue}l+=1,d=65536+((d&1023)<<10|u.charCodeAt(l)&1023),c[c.length]=Ze[240|d>>18]+Ze[128|d>>12&63]+Ze[128|d>>6&63]+Ze[128|d&63]}i+=c.join("")}return i};function Mh(n){return!n||typeof n!="object"?!1:!!(n.constructor&&n.constructor.isBuffer&&n.constructor.isBuffer(n))}function lo(n,e){if(Te(n)){const t=[];for(let r=0;r<n.length;r+=1)t.push(e(n[r]));return t}return e(n)}const Xc={brackets(n){return String(n)+"[]"},comma:"comma",indices(n,e){return String(n)+"["+e+"]"},repeat(n){return String(n)}},Qc=function(n,e){Array.prototype.push.apply(n,Te(e)?e:[e])};let ho;const ae={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:Lh,encodeValuesOnly:!1,format:Kc,formatter:Vc,indices:!1,serializeDate(n){return(ho??(ho=Function.prototype.call.bind(Date.prototype.toISOString)))(n)},skipNulls:!1,strictNullHandling:!1};function Uh(n){return typeof n=="string"||typeof n=="number"||typeof n=="boolean"||typeof n=="symbol"||typeof n=="bigint"}const gs={};function Yc(n,e,t,r,s,a,i,o,u,c,l,d,h,f,p,m,g,_){let y=n,b=_,v=0,E=!1;for(;(b=b.get(gs))!==void 0&&!E;){const G=b.get(n);if(v+=1,typeof G<"u"){if(G===v)throw new RangeError("Cyclic object value");E=!0}typeof b.get(gs)>"u"&&(v=0)}if(typeof c=="function"?y=c(e,y):y instanceof Date?y=h?.(y):t==="comma"&&Te(y)&&(y=lo(y,function(G){return G instanceof Date?h?.(G):G})),y===null){if(a)return u&&!m?u(e,ae.encoder,g,"key",f):e;y=""}if(Uh(y)||Mh(y)){if(u){const G=m?e:u(e,ae.encoder,g,"key",f);return[p?.(G)+"="+p?.(u(y,ae.encoder,g,"value",f))]}return[p?.(e)+"="+p?.(String(y))]}const I=[];if(typeof y>"u")return I;let x;if(t==="comma"&&Te(y))m&&u&&(y=lo(y,u)),x=[{value:y.length>0?y.join(",")||null:void 0}];else if(Te(c))x=c;else{const G=Object.keys(y);x=l?G.sort(l):G}const O=o?String(e).replace(/\./g,"%2E"):String(e),q=r&&Te(y)&&y.length===1?O+"[]":O;if(s&&Te(y)&&y.length===0)return q+"[]";for(let G=0;G<x.length;++G){const V=x[G],Le=typeof V=="object"&&typeof V.value<"u"?V.value:y[V];if(i&&Le===null)continue;const yt=d&&o?V.replace(/\./g,"%2E"):V,P=Te(y)?typeof t=="function"?t(q,yt):q:q+(d?"."+yt:"["+yt+"]");_.set(n,v);const T=new WeakMap;T.set(gs,_),Qc(I,Yc(Le,P,t,r,s,a,i,o,t==="comma"&&m&&Te(y)?null:u,c,l,d,h,f,p,m,g,T))}return I}function Dh(n=ae){if(typeof n.allowEmptyArrays<"u"&&typeof n.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof n.encodeDotInKeys<"u"&&typeof n.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(n.encoder!==null&&typeof n.encoder<"u"&&typeof n.encoder!="function")throw new TypeError("Encoder has to be a function.");const e=n.charset||ae.charset;if(typeof n.charset<"u"&&n.charset!=="utf-8"&&n.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let t=Kc;if(typeof n.format<"u"){if(!Ba(co,n.format))throw new TypeError("Unknown format option provided.");t=n.format}const r=co[t];let s=ae.filter;(typeof n.filter=="function"||Te(n.filter))&&(s=n.filter);let a;if(n.arrayFormat&&n.arrayFormat in Xc?a=n.arrayFormat:"indices"in n?a=n.indices?"indices":"repeat":a=ae.arrayFormat,"commaRoundTrip"in n&&typeof n.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");const i=typeof n.allowDots>"u"?n.encodeDotInKeys?!0:ae.allowDots:!!n.allowDots;return{addQueryPrefix:typeof n.addQueryPrefix=="boolean"?n.addQueryPrefix:ae.addQueryPrefix,allowDots:i,allowEmptyArrays:typeof n.allowEmptyArrays=="boolean"?!!n.allowEmptyArrays:ae.allowEmptyArrays,arrayFormat:a,charset:e,charsetSentinel:typeof n.charsetSentinel=="boolean"?n.charsetSentinel:ae.charsetSentinel,commaRoundTrip:!!n.commaRoundTrip,delimiter:typeof n.delimiter>"u"?ae.delimiter:n.delimiter,encode:typeof n.encode=="boolean"?n.encode:ae.encode,encodeDotInKeys:typeof n.encodeDotInKeys=="boolean"?n.encodeDotInKeys:ae.encodeDotInKeys,encoder:typeof n.encoder=="function"?n.encoder:ae.encoder,encodeValuesOnly:typeof n.encodeValuesOnly=="boolean"?n.encodeValuesOnly:ae.encodeValuesOnly,filter:s,format:t,formatter:r,serializeDate:typeof n.serializeDate=="function"?n.serializeDate:ae.serializeDate,skipNulls:typeof n.skipNulls=="boolean"?n.skipNulls:ae.skipNulls,sort:typeof n.sort=="function"?n.sort:null,strictNullHandling:typeof n.strictNullHandling=="boolean"?n.strictNullHandling:ae.strictNullHandling}}function Fh(n,e={}){let t=n;const r=Dh(e);let s,a;typeof r.filter=="function"?(a=r.filter,t=a("",t)):Te(r.filter)&&(a=r.filter,s=a);const i=[];if(typeof t!="object"||t===null)return"";const o=Xc[r.arrayFormat],u=o==="comma"&&r.commaRoundTrip;s||(s=Object.keys(t)),r.sort&&s.sort(r.sort);const c=new WeakMap;for(let h=0;h<s.length;++h){const f=s[h];r.skipNulls&&t[f]===null||Qc(i,Yc(t[f],f,o,u,r.allowEmptyArrays,r.strictNullHandling,r.skipNulls,r.encodeDotInKeys,r.encode?r.encoder:null,r.filter,r.sort,r.allowDots,r.serializeDate,r.format,r.formatter,r.encodeValuesOnly,r.charset,c))}const l=i.join(r.delimiter);let d=r.addQueryPrefix===!0?"?":"";return r.charsetSentinel&&(r.charset==="iso-8859-1"?d+="utf8=%26%2310003%3B&":d+="utf8=%E2%9C%93&"),l.length>0?d+l:""}function Bh(n){let e=0;for(const s of n)e+=s.length;const t=new Uint8Array(e);let r=0;for(const s of n)t.set(s,r),r+=s.length;return t}let fo;function gi(n){let e;return(fo??(e=new globalThis.TextEncoder,fo=e.encode.bind(e)))(n)}let po;function mo(n){let e;return(po??(e=new globalThis.TextDecoder,po=e.decode.bind(e)))(n)}var Ie,xe;class qn{constructor(){Ie.set(this,void 0),xe.set(this,void 0),M(this,Ie,new Uint8Array),M(this,xe,null)}decode(e){if(e==null)return[];const t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?gi(e):e;M(this,Ie,Bh([w(this,Ie,"f"),t]));const r=[];let s;for(;(s=zh(w(this,Ie,"f"),w(this,xe,"f")))!=null;){if(s.carriage&&w(this,xe,"f")==null){M(this,xe,s.index);continue}if(w(this,xe,"f")!=null&&(s.index!==w(this,xe,"f")+1||s.carriage)){r.push(mo(w(this,Ie,"f").subarray(0,w(this,xe,"f")-1))),M(this,Ie,w(this,Ie,"f").subarray(w(this,xe,"f"))),M(this,xe,null);continue}const a=w(this,xe,"f")!==null?s.preceding-1:s.preceding,i=mo(w(this,Ie,"f").subarray(0,a));r.push(i),M(this,Ie,w(this,Ie,"f").subarray(s.index)),M(this,xe,null)}return r}flush(){return w(this,Ie,"f").length?this.decode(`
|
|
2
|
+
`):[]}}Ie=new WeakMap,xe=new WeakMap;qn.NEWLINE_CHARS=new Set([`
|
|
3
|
+
`,"\r"]);qn.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function zh(n,e){for(let s=e??0;s<n.length;s++){if(n[s]===10)return{preceding:s,index:s+1,carriage:!1};if(n[s]===13)return{preceding:s,index:s+1,carriage:!0}}return null}function qh(n){for(let r=0;r<n.length-1;r++){if(n[r]===10&&n[r+1]===10||n[r]===13&&n[r+1]===13)return r+2;if(n[r]===13&&n[r+1]===10&&r+3<n.length&&n[r+2]===13&&n[r+3]===10)return r+4}return-1}const wn={off:0,error:200,warn:300,info:400,debug:500},go=(n,e,t)=>{if(n){if(Oh(wn,n))return n;fe(t).warn(`${e} was set to ${JSON.stringify(n)}, expected one of ${JSON.stringify(Object.keys(wn))}`)}};function ir(){}function Fr(n,e,t){return!e||wn[n]>wn[t]?ir:e[n].bind(e)}const Hh={error:ir,warn:ir,info:ir,debug:ir};let _o=new WeakMap;function fe(n){const e=n.logger,t=n.logLevel??"off";if(!e)return Hh;const r=_o.get(e);if(r&&r[0]===t)return r[1];const s={error:Fr("error",e,t),warn:Fr("warn",e,t),info:Fr("info",e,t),debug:Fr("debug",e,t)};return _o.set(e,[t,s]),s}const wt=n=>(n.options&&(n.options={...n.options},delete n.options.headers),n.headers&&(n.headers=Object.fromEntries((n.headers instanceof Headers?[...n.headers]:Object.entries(n.headers)).map(([e,t])=>[e,e.toLowerCase()==="authorization"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":t]))),"retryOfRequestLogID"in n&&(n.retryOfRequestLogID&&(n.retryOf=n.retryOfRequestLogID),delete n.retryOfRequestLogID),n);var er;class Xe{constructor(e,t,r){this.iterator=e,er.set(this,void 0),this.controller=t,M(this,er,r)}static fromSSEResponse(e,t,r){let s=!1;const a=r?fe(r):console;async function*i(){if(s)throw new L("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let o=!1;try{for await(const u of Gh(e,t))if(!o){if(u.data.startsWith("[DONE]")){o=!0;continue}if(u.event===null||!u.event.startsWith("thread.")){let c;try{c=JSON.parse(u.data)}catch(l){throw a.error("Could not parse message into JSON:",u.data),a.error("From chunk:",u.raw),l}if(c&&c.error)throw new me(void 0,c.error,void 0,e.headers);yield c}else{let c;try{c=JSON.parse(u.data)}catch(l){throw console.error("Could not parse message into JSON:",u.data),console.error("From chunk:",u.raw),l}if(u.event=="error")throw new me(void 0,c.error,c.message,void 0);yield{event:u.event,data:c}}}o=!0}catch(u){if(Da(u))return;throw u}finally{o||t.abort()}}return new Xe(i,t,r)}static fromReadableStream(e,t,r){let s=!1;async function*a(){const o=new qn,u=Zc(e);for await(const c of u)for(const l of o.decode(c))yield l;for(const c of o.flush())yield c}async function*i(){if(s)throw new L("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let o=!1;try{for await(const u of a())o||u&&(yield JSON.parse(u));o=!0}catch(u){if(Da(u))return;throw u}finally{o||t.abort()}}return new Xe(i,t,r)}[(er=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){const e=[],t=[],r=this.iterator(),s=a=>({next:()=>{if(a.length===0){const i=r.next();e.push(i),t.push(i)}return a.shift()}});return[new Xe(()=>s(e),this.controller,w(this,er,"f")),new Xe(()=>s(t),this.controller,w(this,er,"f"))]}toReadableStream(){const e=this;let t;return Jc({async start(){t=e[Symbol.asyncIterator]()},async pull(r){try{const{value:s,done:a}=await t.next();if(a)return r.close();const i=gi(JSON.stringify(s)+`
|
|
4
|
+
`);r.enqueue(i)}catch(s){r.error(s)}},async cancel(){await t.return?.()}})}}async function*Gh(n,e){if(!n.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new L("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new L("Attempted to iterate over a response with no body");const t=new Wh,r=new qn,s=Zc(n.body);for await(const a of Jh(s))for(const i of r.decode(a)){const o=t.decode(i);o&&(yield o)}for(const a of r.flush()){const i=t.decode(a);i&&(yield i)}}async function*Jh(n){let e=new Uint8Array;for await(const t of n){if(t==null)continue;const r=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?gi(t):t;let s=new Uint8Array(e.length+r.length);s.set(e),s.set(r,e.length),e=s;let a;for(;(a=qh(e))!==-1;)yield e.slice(0,a),e=e.slice(a)}e.length>0&&(yield e)}class Wh{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;const a={event:this.event,data:this.data.join(`
|
|
5
|
+
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],a}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,r,s]=Zh(e,":");return s.startsWith(" ")&&(s=s.substring(1)),t==="event"?this.event=s:t==="data"&&this.data.push(s),null}}function Zh(n,e){const t=n.indexOf(e);return t!==-1?[n.substring(0,t),e,n.substring(t+e.length)]:[n,"",""]}async function el(n,e){const{response:t,requestLogID:r,retryOfRequestLogID:s,startTime:a}=e,i=await(async()=>{if(e.options.stream)return fe(n).debug("response",t.status,t.url,t.headers,t.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(t,e.controller,n):Xe.fromSSEResponse(t,e.controller,n);if(t.status===204)return null;if(e.options.__binaryResponse)return t;const u=t.headers.get("content-type")?.split(";")[0]?.trim();if(u?.includes("application/json")||u?.endsWith("+json")){const d=await t.json();return tl(d,t)}return await t.text()})();return fe(n).debug(`[${r}] response parsed`,wt({retryOfRequestLogID:s,url:t.url,status:t.status,body:i,durationMs:Date.now()-a})),i}function tl(n,e){return!n||typeof n!="object"||Array.isArray(n)?n:Object.defineProperty(n,"_request_id",{value:e.headers.get("x-request-id"),enumerable:!1})}var or;class Hn extends Promise{constructor(e,t,r=el){super(s=>{s(null)}),this.responsePromise=t,this.parseResponse=r,or.set(this,void 0),M(this,or,e)}_thenUnwrap(e){return new Hn(w(this,or,"f"),this.responsePromise,async(t,r)=>tl(e(await this.parseResponse(t,r),r),r.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){const[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get("x-request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(w(this,or,"f"),e))),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}}or=new WeakMap;var Br;class rl{constructor(e,t,r,s){Br.set(this,void 0),M(this,Br,e),this.options=s,this.response=t,this.body=r}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){const e=this.nextPageRequestOptions();if(!e)throw new L("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await w(this,Br,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(Br=new WeakMap,Symbol.asyncIterator)](){for await(const e of this.iterPages())for(const t of e.getPaginatedItems())yield t}}class Kh extends Hn{constructor(e,t,r){super(e,t,async(s,a)=>new r(s,a.response,await el(s,a),a.options))}async*[Symbol.asyncIterator](){const e=await this;for await(const t of e)yield t}}class Gn extends rl{constructor(e,t,r,s){super(e,t,r,s),this.data=r.data||[],this.object=r.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}}class re extends rl{constructor(e,t,r,s){super(e,t,r,s),this.data=r.data||[],this.has_more=r.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){const e=this.getPaginatedItems(),t=e[e.length-1]?.id;return t?{...this.options,query:{...Eh(this.options.query),after:t}}:null}}const nl=()=>{if(typeof File>"u"){const{process:n}=globalThis,e=typeof n?.versions?.node=="string"&&parseInt(n.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(e?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function _r(n,e,t){return nl(),new File(n,e??"unknown_file",t)}function un(n){return(typeof n=="object"&&n!==null&&("name"in n&&n.name&&String(n.name)||"url"in n&&n.url&&String(n.url)||"filename"in n&&n.filename&&String(n.filename)||"path"in n&&n.path&&String(n.path))||"").split(/[\\/]/).pop()||void 0}const sl=n=>n!=null&&typeof n=="object"&&typeof n[Symbol.asyncIterator]=="function",Pt=async(n,e)=>({...n,body:await Xh(n.body,e)}),yo=new WeakMap;function Vh(n){const e=typeof n=="function"?n:n.fetch,t=yo.get(e);if(t)return t;const r=(async()=>{try{const s="Response"in e?e.Response:(await e("data:,")).constructor,a=new FormData;return a.toString()!==await new s(a).text()}catch{return!0}})();return yo.set(e,r),r}const Xh=async(n,e)=>{if(!await Vh(e))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");const t=new FormData;return await Promise.all(Object.entries(n||{}).map(([r,s])=>za(t,r,s))),t},Qh=n=>n instanceof Blob&&"name"in n,za=async(n,e,t)=>{if(t!==void 0){if(t==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof t=="string"||typeof t=="number"||typeof t=="boolean")n.append(e,String(t));else if(t instanceof Response)n.append(e,_r([await t.blob()],un(t)));else if(sl(t))n.append(e,_r([await new Response(Wc(t)).blob()],un(t)));else if(Qh(t))n.append(e,t,un(t));else if(Array.isArray(t))await Promise.all(t.map(r=>za(n,e+"[]",r)));else if(typeof t=="object")await Promise.all(Object.entries(t).map(([r,s])=>za(n,`${e}[${r}]`,s)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${t} instead`)}},al=n=>n!=null&&typeof n=="object"&&typeof n.size=="number"&&typeof n.type=="string"&&typeof n.text=="function"&&typeof n.slice=="function"&&typeof n.arrayBuffer=="function",Yh=n=>n!=null&&typeof n=="object"&&typeof n.name=="string"&&typeof n.lastModified=="number"&&al(n),ef=n=>n!=null&&typeof n=="object"&&typeof n.url=="string"&&typeof n.blob=="function";async function tf(n,e,t){if(nl(),n=await n,Yh(n))return n instanceof File?n:_r([await n.arrayBuffer()],n.name);if(ef(n)){const s=await n.blob();return e||(e=new URL(n.url).pathname.split(/[\\/]/).pop()),_r(await qa(s),e,t)}const r=await qa(n);if(e||(e=un(n)),!t?.type){const s=r.find(a=>typeof a=="object"&&"type"in a&&a.type);typeof s=="string"&&(t={...t,type:s})}return _r(r,e,t)}async function qa(n){let e=[];if(typeof n=="string"||ArrayBuffer.isView(n)||n instanceof ArrayBuffer)e.push(n);else if(al(n))e.push(n instanceof Blob?n:await n.arrayBuffer());else if(sl(n))for await(const t of n)e.push(...await qa(t));else{const t=n?.constructor?.name;throw new Error(`Unexpected data type: ${typeof n}${t?`; constructor: ${t}`:""}${rf(n)}`)}return e}function rf(n){return typeof n!="object"||n===null?"":`; props: [${Object.getOwnPropertyNames(n).map(t=>`"${t}"`).join(", ")}]`}class U{constructor(e){this._client=e}}function il(n){return n.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}const bo=Object.freeze(Object.create(null)),nf=(n=il)=>function(t,...r){if(t.length===1)return t[0];let s=!1;const a=[],i=t.reduce((l,d,h)=>{/[?#]/.test(d)&&(s=!0);const f=r[h];let p=(s?encodeURIComponent:n)(""+f);return h!==r.length&&(f==null||typeof f=="object"&&f.toString===Object.getPrototypeOf(Object.getPrototypeOf(f.hasOwnProperty??bo)??bo)?.toString)&&(p=f+"",a.push({start:l.length+d.length,length:p.length,error:`Value of type ${Object.prototype.toString.call(f).slice(8,-1)} is not a valid path parameter`})),l+d+(h===r.length?"":p)},""),o=i.split(/[?#]/,1)[0],u=new RegExp("(?<=^|\\/)(?:\\.|%2e){1,2}(?=\\/|$)","gi");let c;for(;(c=u.exec(o))!==null;)a.push({start:c.index,length:c[0].length,error:`Value "${c[0]}" can't be safely passed as a path parameter`});if(a.sort((l,d)=>l.start-d.start),a.length>0){let l=0;const d=a.reduce((h,f)=>{const p=" ".repeat(f.start-l),m="^".repeat(f.length);return l=f.start+f.length,h+p+m},"");throw new L(`Path parameters result in path with invalid segments:
|
|
6
|
+
${a.map(h=>h.error).join(`
|
|
7
|
+
`)}
|
|
8
|
+
${i}
|
|
9
|
+
${d}`)}return i},A=nf(il);let ol=class extends U{list(e,t={},r){return this._client.getAPIList(A`/chat/completions/${e}/messages`,re,{query:t,...r})}};function vn(n){return n!==void 0&&"function"in n&&n.function!==void 0}function sf(n,e){const t={...n};return Object.defineProperties(t,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:e,enumerable:!1}}),t}function _i(n){return n?.$brand==="auto-parseable-response-format"}function Cr(n){return n?.$brand==="auto-parseable-tool"}function af(n,e){return!e||!ul(e)?{...n,choices:n.choices.map(t=>(cl(t.message.tool_calls),{...t,message:{...t.message,parsed:null,...t.message.tool_calls?{tool_calls:t.message.tool_calls}:void 0}}))}:yi(n,e)}function yi(n,e){const t=n.choices.map(r=>{if(r.finish_reason==="length")throw new Hc;if(r.finish_reason==="content_filter")throw new Gc;return cl(r.message.tool_calls),{...r,message:{...r.message,...r.message.tool_calls?{tool_calls:r.message.tool_calls?.map(s=>uf(e,s))??void 0}:void 0,parsed:r.message.content&&!r.message.refusal?of(e,r.message.content):null}}});return{...n,choices:t}}function of(n,e){return n.response_format?.type!=="json_schema"?null:n.response_format?.type==="json_schema"?"$parseRaw"in n.response_format?n.response_format.$parseRaw(e):JSON.parse(e):null}function uf(n,e){const t=n.tools?.find(r=>vn(r)&&r.function?.name===e.function.name);return{...e,function:{...e.function,parsed_arguments:Cr(t)?t.$parseRaw(e.function.arguments):t?.function.strict?JSON.parse(e.function.arguments):null}}}function cf(n,e){if(!n||!("tools"in n)||!n.tools)return!1;const t=n.tools?.find(r=>vn(r)&&r.function?.name===e.function.name);return vn(t)&&(Cr(t)||t?.function.strict||!1)}function ul(n){return _i(n.response_format)?!0:n.tools?.some(e=>Cr(e)||e.type==="function"&&e.function.strict===!0)??!1}function cl(n){for(const e of n||[])if(e.type!=="function")throw new L(`Currently only \`function\` tool calls are supported; Received \`${e.type}\``)}function lf(n){for(const e of n??[]){if(e.type!=="function")throw new L(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)throw new L(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}const En=n=>n?.role==="assistant",ll=n=>n?.role==="tool";var Ha,cn,ln,ur,cr,dn,lr,rt,dr,Sn,On,Mt,dl;class bi{constructor(){Ha.add(this),this.controller=new AbortController,cn.set(this,void 0),ln.set(this,()=>{}),ur.set(this,()=>{}),cr.set(this,void 0),dn.set(this,()=>{}),lr.set(this,()=>{}),rt.set(this,{}),dr.set(this,!1),Sn.set(this,!1),On.set(this,!1),Mt.set(this,!1),M(this,cn,new Promise((e,t)=>{M(this,ln,e,"f"),M(this,ur,t,"f")})),M(this,cr,new Promise((e,t)=>{M(this,dn,e,"f"),M(this,lr,t,"f")})),w(this,cn,"f").catch(()=>{}),w(this,cr,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},w(this,Ha,"m",dl).bind(this))},0)}_connected(){this.ended||(w(this,ln,"f").call(this),this._emit("connect"))}get ended(){return w(this,dr,"f")}get errored(){return w(this,Sn,"f")}get aborted(){return w(this,On,"f")}abort(){this.controller.abort()}on(e,t){return(w(this,rt,"f")[e]||(w(this,rt,"f")[e]=[])).push({listener:t}),this}off(e,t){const r=w(this,rt,"f")[e];if(!r)return this;const s=r.findIndex(a=>a.listener===t);return s>=0&&r.splice(s,1),this}once(e,t){return(w(this,rt,"f")[e]||(w(this,rt,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,r)=>{M(this,Mt,!0),e!=="error"&&this.once("error",r),this.once(e,t)})}async done(){M(this,Mt,!0),await w(this,cr,"f")}_emit(e,...t){if(w(this,dr,"f"))return;e==="end"&&(M(this,dr,!0),w(this,dn,"f").call(this));const r=w(this,rt,"f")[e];if(r&&(w(this,rt,"f")[e]=r.filter(s=>!s.once),r.forEach(({listener:s})=>s(...t))),e==="abort"){const s=t[0];!w(this,Mt,"f")&&!r?.length&&Promise.reject(s),w(this,ur,"f").call(this,s),w(this,lr,"f").call(this,s),this._emit("end");return}if(e==="error"){const s=t[0];!w(this,Mt,"f")&&!r?.length&&Promise.reject(s),w(this,ur,"f").call(this,s),w(this,lr,"f").call(this,s),this._emit("end")}}_emitFinal(){}}cn=new WeakMap,ln=new WeakMap,ur=new WeakMap,cr=new WeakMap,dn=new WeakMap,lr=new WeakMap,rt=new WeakMap,dr=new WeakMap,Sn=new WeakMap,On=new WeakMap,Mt=new WeakMap,Ha=new WeakSet,dl=function(e){if(M(this,Sn,!0),e instanceof Error&&e.name==="AbortError"&&(e=new Ce),e instanceof Ce)return M(this,On,!0),this._emit("abort",e);if(e instanceof L)return this._emit("error",e);if(e instanceof Error){const t=new L(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new L(String(e)))};function df(n){return typeof n.parse=="function"}var we,Ga,Tn,Ja,Wa,Za,hl,fl;const hf=10;class pl extends bi{constructor(){super(...arguments),we.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){this._chatCompletions.push(e),this._emit("chatCompletion",e);const t=e.choices[0]?.message;return t&&this._addMessage(t),e}_addMessage(e,t=!0){if("content"in e||(e.content=null),this.messages.push(e),t){if(this._emit("message",e),ll(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(En(e)&&e.tool_calls)for(const r of e.tool_calls)r.type==="function"&&this._emit("functionToolCall",r.function)}}async finalChatCompletion(){await this.done();const e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new L("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),w(this,we,"m",Ga).call(this)}async finalMessage(){return await this.done(),w(this,we,"m",Tn).call(this)}async finalFunctionToolCall(){return await this.done(),w(this,we,"m",Ja).call(this)}async finalFunctionToolCallResult(){return await this.done(),w(this,we,"m",Wa).call(this)}async totalUsage(){return await this.done(),w(this,we,"m",Za).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){const e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);const t=w(this,we,"m",Tn).call(this);t&&this._emit("finalMessage",t);const r=w(this,we,"m",Ga).call(this);r&&this._emit("finalContent",r);const s=w(this,we,"m",Ja).call(this);s&&this._emit("finalFunctionToolCall",s);const a=w(this,we,"m",Wa).call(this);a!=null&&this._emit("finalFunctionToolCallResult",a),this._chatCompletions.some(i=>i.usage)&&this._emit("totalUsage",w(this,we,"m",Za).call(this))}async _createChatCompletion(e,t,r){const s=r?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),w(this,we,"m",hl).call(this,t);const a=await e.chat.completions.create({...t,stream:!1},{...r,signal:this.controller.signal});return this._connected(),this._addChatCompletion(yi(a,t))}async _runChatCompletion(e,t,r){for(const s of t.messages)this._addMessage(s,!1);return await this._createChatCompletion(e,t,r)}async _runTools(e,t,r){const s="tool",{tool_choice:a="auto",stream:i,...o}=t,u=typeof a!="string"&&a.type==="function"&&a?.function?.name,{maxChatCompletions:c=hf}=r||{},l=t.tools.map(f=>{if(Cr(f)){if(!f.$callback)throw new L("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:f.$callback,name:f.function.name,description:f.function.description||"",parameters:f.function.parameters,parse:f.$parseRaw,strict:!0}}}return f}),d={};for(const f of l)f.type==="function"&&(d[f.function.name||f.function.function.name]=f.function);const h="tools"in t?l.map(f=>f.type==="function"?{type:"function",function:{name:f.function.name||f.function.function.name,parameters:f.function.parameters,description:f.function.description,strict:f.function.strict}}:f):void 0;for(const f of t.messages)this._addMessage(f,!1);for(let f=0;f<c;++f){const m=(await this._createChatCompletion(e,{...o,tool_choice:a,tools:h,messages:[...this.messages]},r)).choices[0]?.message;if(!m)throw new L("missing message in ChatCompletion response");if(!m.tool_calls?.length)return;for(const g of m.tool_calls){if(g.type!=="function")continue;const _=g.id,{name:y,arguments:b}=g.function,v=d[y];if(v){if(u&&u!==y){const O=`Invalid tool_call: ${JSON.stringify(y)}. ${JSON.stringify(u)} requested. Please try again`;this._addMessage({role:s,tool_call_id:_,content:O});continue}}else{const O=`Invalid tool_call: ${JSON.stringify(y)}. Available options are: ${Object.keys(d).map(q=>JSON.stringify(q)).join(", ")}. Please try again`;this._addMessage({role:s,tool_call_id:_,content:O});continue}let E;try{E=df(v)?await v.parse(b):b}catch(O){const q=O instanceof Error?O.message:String(O);this._addMessage({role:s,tool_call_id:_,content:q});continue}const I=await v.function(E,this),x=w(this,we,"m",fl).call(this,I);if(this._addMessage({role:s,tool_call_id:_,content:x}),u)return}}}}we=new WeakSet,Ga=function(){return w(this,we,"m",Tn).call(this).content??null},Tn=function(){let e=this.messages.length;for(;e-- >0;){const t=this.messages[e];if(En(t))return{...t,content:t.content??null,refusal:t.refusal??null}}throw new L("stream ended without producing a ChatCompletionMessage with role=assistant")},Ja=function(){for(let e=this.messages.length-1;e>=0;e--){const t=this.messages[e];if(En(t)&&t?.tool_calls?.length)return t.tool_calls.filter(r=>r.type==="function").at(-1)?.function}},Wa=function(){for(let e=this.messages.length-1;e>=0;e--){const t=this.messages[e];if(ll(t)&&t.content!=null&&typeof t.content=="string"&&this.messages.some(r=>r.role==="assistant"&&r.tool_calls?.some(s=>s.type==="function"&&s.id===t.tool_call_id)))return t.content}},Za=function(){const e={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(const{usage:t}of this._chatCompletions)t&&(e.completion_tokens+=t.completion_tokens,e.prompt_tokens+=t.prompt_tokens,e.total_tokens+=t.total_tokens);return e},hl=function(e){if(e.n!=null&&e.n>1)throw new L("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},fl=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};class wi extends pl{static runTools(e,t,r){const s=new wi,a={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runTools"}};return s._run(()=>s._runTools(e,t,a)),s}_addMessage(e,t=!0){super._addMessage(e,t),En(e)&&e.content&&this._emit("content",e.content)}}const ml=1,gl=2,_l=4,yl=8,bl=16,wl=32,vl=64,El=128,Sl=256,Ol=El|Sl,Tl=bl|wl|Ol|vl,Al=ml|gl|Tl,Pl=_l|yl,ff=Al|Pl,ue={STR:ml,NUM:gl,ARR:_l,OBJ:yl,NULL:bl,BOOL:wl,NAN:vl,INFINITY:El,MINUS_INFINITY:Sl,INF:Ol,SPECIAL:Tl,ATOM:Al,COLLECTION:Pl,ALL:ff};class pf extends Error{}class mf extends Error{}function gf(n,e=ue.ALL){if(typeof n!="string")throw new TypeError(`expecting str, got ${typeof n}`);if(!n.trim())throw new Error(`${n} is empty`);return _f(n.trim(),e)}const _f=(n,e)=>{const t=n.length;let r=0;const s=h=>{throw new pf(`${h} at position ${r}`)},a=h=>{throw new mf(`${h} at position ${r}`)},i=()=>(d(),r>=t&&s("Unexpected end of input"),n[r]==='"'?o():n[r]==="{"?u():n[r]==="["?c():n.substring(r,r+4)==="null"||ue.NULL&e&&t-r<4&&"null".startsWith(n.substring(r))?(r+=4,null):n.substring(r,r+4)==="true"||ue.BOOL&e&&t-r<4&&"true".startsWith(n.substring(r))?(r+=4,!0):n.substring(r,r+5)==="false"||ue.BOOL&e&&t-r<5&&"false".startsWith(n.substring(r))?(r+=5,!1):n.substring(r,r+8)==="Infinity"||ue.INFINITY&e&&t-r<8&&"Infinity".startsWith(n.substring(r))?(r+=8,1/0):n.substring(r,r+9)==="-Infinity"||ue.MINUS_INFINITY&e&&1<t-r&&t-r<9&&"-Infinity".startsWith(n.substring(r))?(r+=9,-1/0):n.substring(r,r+3)==="NaN"||ue.NAN&e&&t-r<3&&"NaN".startsWith(n.substring(r))?(r+=3,NaN):l()),o=()=>{const h=r;let f=!1;for(r++;r<t&&(n[r]!=='"'||f&&n[r-1]==="\\");)f=n[r]==="\\"?!f:!1,r++;if(n.charAt(r)=='"')try{return JSON.parse(n.substring(h,++r-Number(f)))}catch(p){a(String(p))}else if(ue.STR&e)try{return JSON.parse(n.substring(h,r-Number(f))+'"')}catch{return JSON.parse(n.substring(h,n.lastIndexOf("\\"))+'"')}s("Unterminated string literal")},u=()=>{r++,d();const h={};try{for(;n[r]!=="}";){if(d(),r>=t&&ue.OBJ&e)return h;const f=o();d(),r++;try{const p=i();Object.defineProperty(h,f,{value:p,writable:!0,enumerable:!0,configurable:!0})}catch(p){if(ue.OBJ&e)return h;throw p}d(),n[r]===","&&r++}}catch{if(ue.OBJ&e)return h;s("Expected '}' at end of object")}return r++,h},c=()=>{r++;const h=[];try{for(;n[r]!=="]";)h.push(i()),d(),n[r]===","&&r++}catch{if(ue.ARR&e)return h;s("Expected ']' at end of array")}return r++,h},l=()=>{if(r===0){n==="-"&&ue.NUM&e&&s("Not sure what '-' is");try{return JSON.parse(n)}catch(f){if(ue.NUM&e)try{return n[n.length-1]==="."?JSON.parse(n.substring(0,n.lastIndexOf("."))):JSON.parse(n.substring(0,n.lastIndexOf("e")))}catch{}a(String(f))}}const h=r;for(n[r]==="-"&&r++;n[r]&&!",]}".includes(n[r]);)r++;r==t&&!(ue.NUM&e)&&s("Unterminated number literal");try{return JSON.parse(n.substring(h,r))}catch{n.substring(h,r)==="-"&&ue.NUM&e&&s("Not sure what '-' is");try{return JSON.parse(n.substring(h,n.lastIndexOf("e")))}catch(p){a(String(p))}}},d=()=>{for(;r<t&&`
|
|
10
|
+
\r `.includes(n[r]);)r++};return i()},wo=n=>gf(n,ue.ALL^ue.NUM);var ne,tt,Ct,it,_s,zr,ys,bs,ws,qr,vs,vo;class Or extends pl{constructor(e){super(),ne.add(this),tt.set(this,void 0),Ct.set(this,void 0),it.set(this,void 0),M(this,tt,e),M(this,Ct,[])}get currentChatCompletionSnapshot(){return w(this,it,"f")}static fromReadableStream(e){const t=new Or(null);return t._run(()=>t._fromReadableStream(e)),t}static createChatCompletion(e,t,r){const s=new Or(t);return s._run(()=>s._runChatCompletion(e,{...t,stream:!0},{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),s}async _createChatCompletion(e,t,r){super._createChatCompletion;const s=r?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),w(this,ne,"m",_s).call(this);const a=await e.chat.completions.create({...t,stream:!0},{...r,signal:this.controller.signal});this._connected();for await(const i of a)w(this,ne,"m",ys).call(this,i);if(a.controller.signal?.aborted)throw new Ce;return this._addChatCompletion(w(this,ne,"m",qr).call(this))}async _fromReadableStream(e,t){const r=t?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),w(this,ne,"m",_s).call(this),this._connected();const s=Xe.fromReadableStream(e,this.controller);let a;for await(const i of s)a&&a!==i.id&&this._addChatCompletion(w(this,ne,"m",qr).call(this)),w(this,ne,"m",ys).call(this,i),a=i.id;if(s.controller.signal?.aborted)throw new Ce;return this._addChatCompletion(w(this,ne,"m",qr).call(this))}[(tt=new WeakMap,Ct=new WeakMap,it=new WeakMap,ne=new WeakSet,_s=function(){this.ended||M(this,it,void 0)},zr=function(t){let r=w(this,Ct,"f")[t.index];return r||(r={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},w(this,Ct,"f")[t.index]=r,r)},ys=function(t){if(this.ended)return;const r=w(this,ne,"m",vo).call(this,t);this._emit("chunk",t,r);for(const s of t.choices){const a=r.choices[s.index];s.delta.content!=null&&a.message?.role==="assistant"&&a.message?.content&&(this._emit("content",s.delta.content,a.message.content),this._emit("content.delta",{delta:s.delta.content,snapshot:a.message.content,parsed:a.message.parsed})),s.delta.refusal!=null&&a.message?.role==="assistant"&&a.message?.refusal&&this._emit("refusal.delta",{delta:s.delta.refusal,snapshot:a.message.refusal}),s.logprobs?.content!=null&&a.message?.role==="assistant"&&this._emit("logprobs.content.delta",{content:s.logprobs?.content,snapshot:a.logprobs?.content??[]}),s.logprobs?.refusal!=null&&a.message?.role==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:s.logprobs?.refusal,snapshot:a.logprobs?.refusal??[]});const i=w(this,ne,"m",zr).call(this,a);a.finish_reason&&(w(this,ne,"m",ws).call(this,a),i.current_tool_call_index!=null&&w(this,ne,"m",bs).call(this,a,i.current_tool_call_index));for(const o of s.delta.tool_calls??[])i.current_tool_call_index!==o.index&&(w(this,ne,"m",ws).call(this,a),i.current_tool_call_index!=null&&w(this,ne,"m",bs).call(this,a,i.current_tool_call_index)),i.current_tool_call_index=o.index;for(const o of s.delta.tool_calls??[]){const u=a.message.tool_calls?.[o.index];u?.type&&(u?.type==="function"?this._emit("tool_calls.function.arguments.delta",{name:u.function?.name,index:o.index,arguments:u.function.arguments,parsed_arguments:u.function.parsed_arguments,arguments_delta:o.function?.arguments??""}):(u?.type,void 0))}}},bs=function(t,r){if(w(this,ne,"m",zr).call(this,t).done_tool_calls.has(r))return;const a=t.message.tool_calls?.[r];if(!a)throw new Error("no tool call snapshot");if(!a.type)throw new Error("tool call snapshot missing `type`");if(a.type==="function"){const i=w(this,tt,"f")?.tools?.find(o=>vn(o)&&o.function.name===a.function.name);this._emit("tool_calls.function.arguments.done",{name:a.function.name,index:r,arguments:a.function.arguments,parsed_arguments:Cr(i)?i.$parseRaw(a.function.arguments):i?.function.strict?JSON.parse(a.function.arguments):null})}else a.type},ws=function(t){const r=w(this,ne,"m",zr).call(this,t);if(t.message.content&&!r.content_done){r.content_done=!0;const s=w(this,ne,"m",vs).call(this);this._emit("content.done",{content:t.message.content,parsed:s?s.$parseRaw(t.message.content):null})}t.message.refusal&&!r.refusal_done&&(r.refusal_done=!0,this._emit("refusal.done",{refusal:t.message.refusal})),t.logprobs?.content&&!r.logprobs_content_done&&(r.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:t.logprobs.content})),t.logprobs?.refusal&&!r.logprobs_refusal_done&&(r.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:t.logprobs.refusal}))},qr=function(){if(this.ended)throw new L("stream has ended, this shouldn't happen");const t=w(this,it,"f");if(!t)throw new L("request ended without sending any chunks");return M(this,it,void 0),M(this,Ct,[]),yf(t,w(this,tt,"f"))},vs=function(){const t=w(this,tt,"f")?.response_format;return _i(t)?t:null},vo=function(t){var r,s,a,i;let o=w(this,it,"f");const{choices:u,...c}=t;o?Object.assign(o,c):o=M(this,it,{...c,choices:[]});for(const{delta:l,finish_reason:d,index:h,logprobs:f=null,...p}of t.choices){let m=o.choices[h];if(m||(m=o.choices[h]={finish_reason:d,index:h,message:{},logprobs:f,...p}),f)if(!m.logprobs)m.logprobs=Object.assign({},f);else{const{content:I,refusal:x,...O}=f;Object.assign(m.logprobs,O),I&&((r=m.logprobs).content??(r.content=[]),m.logprobs.content.push(...I)),x&&((s=m.logprobs).refusal??(s.refusal=[]),m.logprobs.refusal.push(...x))}if(d&&(m.finish_reason=d,w(this,tt,"f")&&ul(w(this,tt,"f")))){if(d==="length")throw new Hc;if(d==="content_filter")throw new Gc}if(Object.assign(m,p),!l)continue;const{content:g,refusal:_,function_call:y,role:b,tool_calls:v,...E}=l;if(Object.assign(m.message,E),_&&(m.message.refusal=(m.message.refusal||"")+_),b&&(m.message.role=b),y&&(m.message.function_call?(y.name&&(m.message.function_call.name=y.name),y.arguments&&((a=m.message.function_call).arguments??(a.arguments=""),m.message.function_call.arguments+=y.arguments)):m.message.function_call=y),g&&(m.message.content=(m.message.content||"")+g,!m.message.refusal&&w(this,ne,"m",vs).call(this)&&(m.message.parsed=wo(m.message.content))),v){m.message.tool_calls||(m.message.tool_calls=[]);for(const{index:I,id:x,type:O,function:q,...G}of v){const V=(i=m.message.tool_calls)[I]??(i[I]={});Object.assign(V,G),x&&(V.id=x),O&&(V.type=O),q&&(V.function??(V.function={name:q.name??"",arguments:""})),q?.name&&(V.function.name=q.name),q?.arguments&&(V.function.arguments+=q.arguments,cf(w(this,tt,"f"),V)&&(V.function.parsed_arguments=wo(V.function.arguments)))}}}return o},Symbol.asyncIterator)](){const e=[],t=[];let r=!1;return this.on("chunk",s=>{const a=t.shift();a?a.resolve(s):e.push(s)}),this.on("end",()=>{r=!0;for(const s of t)s.resolve(void 0);t.length=0}),this.on("abort",s=>{r=!0;for(const a of t)a.reject(s);t.length=0}),this.on("error",s=>{r=!0;for(const a of t)a.reject(s);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((a,i)=>t.push({resolve:a,reject:i})).then(a=>a?{value:a,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new Xe(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function yf(n,e){const{id:t,choices:r,created:s,model:a,system_fingerprint:i,...o}=n,u={...o,id:t,choices:r.map(({message:c,finish_reason:l,index:d,logprobs:h,...f})=>{if(!l)throw new L(`missing finish_reason for choice ${d}`);const{content:p=null,function_call:m,tool_calls:g,..._}=c,y=c.role;if(!y)throw new L(`missing role for choice ${d}`);if(m){const{arguments:b,name:v}=m;if(b==null)throw new L(`missing function_call.arguments for choice ${d}`);if(!v)throw new L(`missing function_call.name for choice ${d}`);return{...f,message:{content:p,function_call:{arguments:b,name:v},role:y,refusal:c.refusal??null},finish_reason:l,index:d,logprobs:h}}return g?{...f,index:d,finish_reason:l,logprobs:h,message:{..._,role:y,content:p,refusal:c.refusal??null,tool_calls:g.map((b,v)=>{const{function:E,type:I,id:x,...O}=b,{arguments:q,name:G,...V}=E||{};if(x==null)throw new L(`missing choices[${d}].tool_calls[${v}].id
|
|
11
|
+
${Hr(n)}`);if(I==null)throw new L(`missing choices[${d}].tool_calls[${v}].type
|
|
12
|
+
${Hr(n)}`);if(G==null)throw new L(`missing choices[${d}].tool_calls[${v}].function.name
|
|
13
|
+
${Hr(n)}`);if(q==null)throw new L(`missing choices[${d}].tool_calls[${v}].function.arguments
|
|
14
|
+
${Hr(n)}`);return{...O,id:x,type:I,function:{...V,name:G,arguments:q}}})}}:{...f,message:{..._,content:p,role:y,refusal:c.refusal??null},finish_reason:l,index:d,logprobs:h}}),created:s,model:a,object:"chat.completion",...i?{system_fingerprint:i}:{}};return af(u,e)}function Hr(n){return JSON.stringify(n)}class An extends Or{static fromReadableStream(e){const t=new An(null);return t._run(()=>t._fromReadableStream(e)),t}static runTools(e,t,r){const s=new An(t),a={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runTools"}};return s._run(()=>s._runTools(e,t,a)),s}}let vi=class extends U{constructor(){super(...arguments),this.messages=new ol(this._client)}create(e,t){return this._client.post("/chat/completions",{body:e,...t,stream:e.stream??!1})}retrieve(e,t){return this._client.get(A`/chat/completions/${e}`,t)}update(e,t,r){return this._client.post(A`/chat/completions/${e}`,{body:t,...r})}list(e={},t){return this._client.getAPIList("/chat/completions",re,{query:e,...t})}delete(e,t){return this._client.delete(A`/chat/completions/${e}`,t)}parse(e,t){return lf(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(r=>yi(r,e))}runTools(e,t){return e.stream?An.runTools(this._client,e,t):wi.runTools(this._client,e,t)}stream(e,t){return Or.createChatCompletion(this._client,e,t)}};vi.Messages=ol;class Ei extends U{constructor(){super(...arguments),this.completions=new vi(this._client)}}Ei.Completions=vi;const Il=Symbol("brand.privateNullableHeaders");function*bf(n){if(!n)return;if(Il in n){const{values:r,nulls:s}=n;yield*r.entries();for(const a of s)yield[a,null];return}let e=!1,t;n instanceof Headers?t=n.entries():ao(n)?t=n:(e=!0,t=Object.entries(n??{}));for(let r of t){const s=r[0];if(typeof s!="string")throw new TypeError("expected header name to be a string");const a=ao(r[1])?r[1]:[r[1]];let i=!1;for(const o of a)o!==void 0&&(e&&!i&&(i=!0,yield[s,null]),yield[s,o])}}const $=n=>{const e=new Headers,t=new Set;for(const r of n){const s=new Set;for(const[a,i]of bf(r)){const o=a.toLowerCase();s.has(o)||(e.delete(a),s.add(o)),i===null?(e.delete(a),t.add(o)):(e.append(a,i),t.delete(o))}}return{[Il]:!0,values:e,nulls:t}};class xl extends U{create(e,t){return this._client.post("/audio/speech",{body:e,...t,headers:$([{Accept:"application/octet-stream"},t?.headers]),__binaryResponse:!0})}}class Rl extends U{create(e,t){return this._client.post("/audio/transcriptions",Pt({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model}},this._client))}}class kl extends U{create(e,t){return this._client.post("/audio/translations",Pt({body:e,...t,__metadata:{model:e.model}},this._client))}}class $r extends U{constructor(){super(...arguments),this.transcriptions=new Rl(this._client),this.translations=new kl(this._client),this.speech=new xl(this._client)}}$r.Transcriptions=Rl;$r.Translations=kl;$r.Speech=xl;class Cl extends U{create(e,t){return this._client.post("/batches",{body:e,...t})}retrieve(e,t){return this._client.get(A`/batches/${e}`,t)}list(e={},t){return this._client.getAPIList("/batches",re,{query:e,...t})}cancel(e,t){return this._client.post(A`/batches/${e}/cancel`,t)}}class $l extends U{create(e,t){return this._client.post("/assistants",{body:e,...t,headers:$([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(A`/assistants/${e}`,{...t,headers:$([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,r){return this._client.post(A`/assistants/${e}`,{body:t,...r,headers:$([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e={},t){return this._client.getAPIList("/assistants",re,{query:e,...t,headers:$([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}delete(e,t){return this._client.delete(A`/assistants/${e}`,{...t,headers:$([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}}class Nl extends U{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:$([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}}class jl extends U{create(e,t){return this._client.post("/realtime/transcription_sessions",{body:e,...t,headers:$([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}}class Jn extends U{constructor(){super(...arguments),this.sessions=new Nl(this._client),this.transcriptionSessions=new jl(this._client)}}Jn.Sessions=Nl;Jn.TranscriptionSessions=jl;class Ll extends U{create(e,t,r){return this._client.post(A`/threads/${e}/messages`,{body:t,...r,headers:$([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(e,t,r){const{thread_id:s}=t;return this._client.get(A`/threads/${s}/messages/${e}`,{...r,headers:$([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(e,t,r){const{thread_id:s,...a}=t;return this._client.post(A`/threads/${s}/messages/${e}`,{body:a,...r,headers:$([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t={},r){return this._client.getAPIList(A`/threads/${e}/messages`,re,{query:t,...r,headers:$([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}delete(e,t,r){const{thread_id:s}=t;return this._client.delete(A`/threads/${s}/messages/${e}`,{...r,headers:$([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}}class Ml extends U{retrieve(e,t,r){const{thread_id:s,run_id:a,...i}=t;return this._client.get(A`/threads/${s}/runs/${a}/steps/${e}`,{query:i,...r,headers:$([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t,r){const{thread_id:s,...a}=t;return this._client.getAPIList(A`/threads/${s}/runs/${e}/steps`,re,{query:a,...r,headers:$([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}}const wf=n=>{if(typeof Buffer<"u"){const e=Buffer.from(n,"base64");return Array.from(new Float32Array(e.buffer,e.byteOffset,e.length/Float32Array.BYTES_PER_ELEMENT))}else{const e=atob(n),t=e.length,r=new Uint8Array(t);for(let s=0;s<t;s++)r[s]=e.charCodeAt(s);return Array.from(new Float32Array(r.buffer))}};var vf={};const $t=n=>{if(typeof globalThis.process<"u")return vf?.[n]?.trim()??void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(n)?.trim()};var pe,Et,Ka,Ve,hn,ze,St,Bt,vt,Pn,ke,fn,pn,yr,hr,fr,Eo,So,Oo,To,Ao,Po,Io;class br extends bi{constructor(){super(...arguments),pe.add(this),Ka.set(this,[]),Ve.set(this,{}),hn.set(this,{}),ze.set(this,void 0),St.set(this,void 0),Bt.set(this,void 0),vt.set(this,void 0),Pn.set(this,void 0),ke.set(this,void 0),fn.set(this,void 0),pn.set(this,void 0),yr.set(this,void 0)}[(Ka=new WeakMap,Ve=new WeakMap,hn=new WeakMap,ze=new WeakMap,St=new WeakMap,Bt=new WeakMap,vt=new WeakMap,Pn=new WeakMap,ke=new WeakMap,fn=new WeakMap,pn=new WeakMap,yr=new WeakMap,pe=new WeakSet,Symbol.asyncIterator)](){const e=[],t=[];let r=!1;return this.on("event",s=>{const a=t.shift();a?a.resolve(s):e.push(s)}),this.on("end",()=>{r=!0;for(const s of t)s.resolve(void 0);t.length=0}),this.on("abort",s=>{r=!0;for(const a of t)a.reject(s);t.length=0}),this.on("error",s=>{r=!0;for(const a of t)a.reject(s);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((a,i)=>t.push({resolve:a,reject:i})).then(a=>a?{value:a,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){const t=new Et;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,t){const r=t?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),this._connected();const s=Xe.fromReadableStream(e,this.controller);for await(const a of s)w(this,pe,"m",hr).call(this,a);if(s.controller.signal?.aborted)throw new Ce;return this._addRun(w(this,pe,"m",fr).call(this))}toReadableStream(){return new Xe(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,r,s){const a=new Et;return a._run(()=>a._runToolAssistantStream(e,t,r,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),a}async _createToolAssistantStream(e,t,r,s){const a=s?.signal;a&&(a.aborted&&this.controller.abort(),a.addEventListener("abort",()=>this.controller.abort()));const i={...r,stream:!0},o=await e.submitToolOutputs(t,i,{...s,signal:this.controller.signal});this._connected();for await(const u of o)w(this,pe,"m",hr).call(this,u);if(o.controller.signal?.aborted)throw new Ce;return this._addRun(w(this,pe,"m",fr).call(this))}static createThreadAssistantStream(e,t,r){const s=new Et;return s._run(()=>s._threadAssistantStream(e,t,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),s}static createAssistantStream(e,t,r,s){const a=new Et;return a._run(()=>a._runAssistantStream(e,t,r,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),a}currentEvent(){return w(this,fn,"f")}currentRun(){return w(this,pn,"f")}currentMessageSnapshot(){return w(this,ze,"f")}currentRunStepSnapshot(){return w(this,yr,"f")}async finalRunSteps(){return await this.done(),Object.values(w(this,Ve,"f"))}async finalMessages(){return await this.done(),Object.values(w(this,hn,"f"))}async finalRun(){if(await this.done(),!w(this,St,"f"))throw Error("Final run was not received.");return w(this,St,"f")}async _createThreadAssistantStream(e,t,r){const s=r?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort()));const a={...t,stream:!0},i=await e.createAndRun(a,{...r,signal:this.controller.signal});this._connected();for await(const o of i)w(this,pe,"m",hr).call(this,o);if(i.controller.signal?.aborted)throw new Ce;return this._addRun(w(this,pe,"m",fr).call(this))}async _createAssistantStream(e,t,r,s){const a=s?.signal;a&&(a.aborted&&this.controller.abort(),a.addEventListener("abort",()=>this.controller.abort()));const i={...r,stream:!0},o=await e.create(t,i,{...s,signal:this.controller.signal});this._connected();for await(const u of o)w(this,pe,"m",hr).call(this,u);if(o.controller.signal?.aborted)throw new Ce;return this._addRun(w(this,pe,"m",fr).call(this))}static accumulateDelta(e,t){for(const[r,s]of Object.entries(t)){if(!e.hasOwnProperty(r)){e[r]=s;continue}let a=e[r];if(a==null){e[r]=s;continue}if(r==="index"||r==="type"){e[r]=s;continue}if(typeof a=="string"&&typeof s=="string")a+=s;else if(typeof a=="number"&&typeof s=="number")a+=s;else if(ps(a)&&ps(s))a=this.accumulateDelta(a,s);else if(Array.isArray(a)&&Array.isArray(s)){if(a.every(i=>typeof i=="string"||typeof i=="number")){a.push(...s);continue}for(const i of s){if(!ps(i))throw new Error(`Expected array delta entry to be an object but got: ${i}`);const o=i.index;if(o==null)throw console.error(i),new Error("Expected array delta entry to have an `index` property");if(typeof o!="number")throw new Error(`Expected array delta entry \`index\` property to be a number but got ${o}`);const u=a[o];u==null?a.push(i):a[o]=this.accumulateDelta(u,i)}continue}else throw Error(`Unhandled record type: ${r}, deltaValue: ${s}, accValue: ${a}`);e[r]=a}return e}_addRun(e){return e}async _threadAssistantStream(e,t,r){return await this._createThreadAssistantStream(t,e,r)}async _runAssistantStream(e,t,r,s){return await this._createAssistantStream(t,e,r,s)}async _runToolAssistantStream(e,t,r,s){return await this._createToolAssistantStream(t,e,r,s)}}Et=br,hr=function(e){if(!this.ended)switch(M(this,fn,e),w(this,pe,"m",Oo).call(this,e),e.event){case"thread.created":break;case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":case"thread.run.requires_action":case"thread.run.completed":case"thread.run.incomplete":case"thread.run.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":w(this,pe,"m",Io).call(this,e);break;case"thread.run.step.created":case"thread.run.step.in_progress":case"thread.run.step.delta":case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":w(this,pe,"m",So).call(this,e);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":w(this,pe,"m",Eo).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier")}},fr=function(){if(this.ended)throw new L("stream has ended, this shouldn't happen");if(!w(this,St,"f"))throw Error("Final run has not been received");return w(this,St,"f")},Eo=function(e){const[t,r]=w(this,pe,"m",Ao).call(this,e,w(this,ze,"f"));M(this,ze,t),w(this,hn,"f")[t.id]=t;for(const s of r){const a=t.content[s.index];a?.type=="text"&&this._emit("textCreated",a.text)}switch(e.event){case"thread.message.created":this._emit("messageCreated",e.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",e.data.delta,t),e.data.delta.content)for(const s of e.data.delta.content){if(s.type=="text"&&s.text){let a=s.text,i=t.content[s.index];if(i&&i.type=="text")this._emit("textDelta",a,i.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(s.index!=w(this,Bt,"f")){if(w(this,vt,"f"))switch(w(this,vt,"f").type){case"text":this._emit("textDone",w(this,vt,"f").text,w(this,ze,"f"));break;case"image_file":this._emit("imageFileDone",w(this,vt,"f").image_file,w(this,ze,"f"));break}M(this,Bt,s.index)}M(this,vt,t.content[s.index])}break;case"thread.message.completed":case"thread.message.incomplete":if(w(this,Bt,"f")!==void 0){const s=e.data.content[w(this,Bt,"f")];if(s)switch(s.type){case"image_file":this._emit("imageFileDone",s.image_file,w(this,ze,"f"));break;case"text":this._emit("textDone",s.text,w(this,ze,"f"));break}}w(this,ze,"f")&&this._emit("messageDone",e.data),M(this,ze,void 0)}},So=function(e){const t=w(this,pe,"m",To).call(this,e);switch(M(this,yr,t),e.event){case"thread.run.step.created":this._emit("runStepCreated",e.data);break;case"thread.run.step.delta":const r=e.data.delta;if(r.step_details&&r.step_details.type=="tool_calls"&&r.step_details.tool_calls&&t.step_details.type=="tool_calls")for(const a of r.step_details.tool_calls)a.index==w(this,Pn,"f")?this._emit("toolCallDelta",a,t.step_details.tool_calls[a.index]):(w(this,ke,"f")&&this._emit("toolCallDone",w(this,ke,"f")),M(this,Pn,a.index),M(this,ke,t.step_details.tool_calls[a.index]),w(this,ke,"f")&&this._emit("toolCallCreated",w(this,ke,"f")));this._emit("runStepDelta",e.data.delta,t);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":M(this,yr,void 0),e.data.step_details.type=="tool_calls"&&w(this,ke,"f")&&(this._emit("toolCallDone",w(this,ke,"f")),M(this,ke,void 0)),this._emit("runStepDone",e.data,t);break}},Oo=function(e){w(this,Ka,"f").push(e),this._emit("event",e)},To=function(e){switch(e.event){case"thread.run.step.created":return w(this,Ve,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let t=w(this,Ve,"f")[e.data.id];if(!t)throw Error("Received a RunStepDelta before creation of a snapshot");let r=e.data;if(r.delta){const s=Et.accumulateDelta(t,r.delta);w(this,Ve,"f")[e.data.id]=s}return w(this,Ve,"f")[e.data.id];case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":case"thread.run.step.in_progress":w(this,Ve,"f")[e.data.id]=e.data;break}if(w(this,Ve,"f")[e.data.id])return w(this,Ve,"f")[e.data.id];throw new Error("No snapshot available")},Ao=function(e,t){let r=[];switch(e.event){case"thread.message.created":return[e.data,r];case"thread.message.delta":if(!t)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let s=e.data;if(s.delta.content)for(const a of s.delta.content)if(a.index in t.content){let i=t.content[a.index];t.content[a.index]=w(this,pe,"m",Po).call(this,a,i)}else t.content[a.index]=a,r.push(a);return[t,r];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(t)return[t,r];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},Po=function(e,t){return Et.accumulateDelta(t,e)},Io=function(e){switch(M(this,pn,e.data),e.event){case"thread.run.created":break;case"thread.run.queued":break;case"thread.run.in_progress":break;case"thread.run.requires_action":case"thread.run.cancelled":case"thread.run.failed":case"thread.run.completed":case"thread.run.expired":case"thread.run.incomplete":M(this,St,e.data),w(this,ke,"f")&&(this._emit("toolCallDone",w(this,ke,"f")),M(this,ke,void 0));break}};let Si=class extends U{constructor(){super(...arguments),this.steps=new Ml(this._client)}create(e,t,r){const{include:s,...a}=t;return this._client.post(A`/threads/${e}/runs`,{query:{include:s},body:a,...r,headers:$([{"OpenAI-Beta":"assistants=v2"},r?.headers]),stream:t.stream??!1})}retrieve(e,t,r){const{thread_id:s}=t;return this._client.get(A`/threads/${s}/runs/${e}`,{...r,headers:$([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(e,t,r){const{thread_id:s,...a}=t;return this._client.post(A`/threads/${s}/runs/${e}`,{body:a,...r,headers:$([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t={},r){return this._client.getAPIList(A`/threads/${e}/runs`,re,{query:t,...r,headers:$([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}cancel(e,t,r){const{thread_id:s}=t;return this._client.post(A`/threads/${s}/runs/${e}/cancel`,{...r,headers:$([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async createAndPoll(e,t,r){const s=await this.create(e,t,r);return await this.poll(s.id,{thread_id:e},r)}createAndStream(e,t,r){return br.createAssistantStream(e,this._client.beta.threads.runs,t,r)}async poll(e,t,r){const s=$([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);for(;;){const{data:a,response:i}=await this.retrieve(e,t,{...r,headers:{...r?.headers,...s}}).withResponse();switch(a.status){case"queued":case"in_progress":case"cancelling":let o=5e3;if(r?.pollIntervalMs)o=r.pollIntervalMs;else{const u=i.headers.get("openai-poll-after-ms");if(u){const c=parseInt(u);isNaN(c)||(o=c)}}await kr(o);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return a}}}stream(e,t,r){return br.createAssistantStream(e,this._client.beta.threads.runs,t,r)}submitToolOutputs(e,t,r){const{thread_id:s,...a}=t;return this._client.post(A`/threads/${s}/runs/${e}/submit_tool_outputs`,{body:a,...r,headers:$([{"OpenAI-Beta":"assistants=v2"},r?.headers]),stream:t.stream??!1})}async submitToolOutputsAndPoll(e,t,r){const s=await this.submitToolOutputs(e,t,r);return await this.poll(s.id,t,r)}submitToolOutputsStream(e,t,r){return br.createToolAssistantStream(e,this._client.beta.threads.runs,t,r)}};Si.Steps=Ml;class Wn extends U{constructor(){super(...arguments),this.runs=new Si(this._client),this.messages=new Ll(this._client)}create(e={},t){return this._client.post("/threads",{body:e,...t,headers:$([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(A`/threads/${e}`,{...t,headers:$([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,r){return this._client.post(A`/threads/${e}`,{body:t,...r,headers:$([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}delete(e,t){return this._client.delete(A`/threads/${e}`,{...t,headers:$([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}createAndRun(e,t){return this._client.post("/threads/runs",{body:e,...t,headers:$([{"OpenAI-Beta":"assistants=v2"},t?.headers]),stream:e.stream??!1})}async createAndRunPoll(e,t){const r=await this.createAndRun(e,t);return await this.runs.poll(r.id,{thread_id:r.thread_id},t)}createAndRunStream(e,t){return br.createThreadAssistantStream(e,this._client.beta.threads,t)}}Wn.Runs=Si;Wn.Messages=Ll;class Nr extends U{constructor(){super(...arguments),this.realtime=new Jn(this._client),this.assistants=new $l(this._client),this.threads=new Wn(this._client)}}Nr.Realtime=Jn;Nr.Assistants=$l;Nr.Threads=Wn;class Ul extends U{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1})}}class Dl extends U{retrieve(e,t,r){const{container_id:s}=t;return this._client.get(A`/containers/${s}/files/${e}/content`,{...r,headers:$([{Accept:"application/binary"},r?.headers]),__binaryResponse:!0})}}let Oi=class extends U{constructor(){super(...arguments),this.content=new Dl(this._client)}create(e,t,r){return this._client.post(A`/containers/${e}/files`,Pt({body:t,...r},this._client))}retrieve(e,t,r){const{container_id:s}=t;return this._client.get(A`/containers/${s}/files/${e}`,r)}list(e,t={},r){return this._client.getAPIList(A`/containers/${e}/files`,re,{query:t,...r})}delete(e,t,r){const{container_id:s}=t;return this._client.delete(A`/containers/${s}/files/${e}`,{...r,headers:$([{Accept:"*/*"},r?.headers])})}};Oi.Content=Dl;class Ti extends U{constructor(){super(...arguments),this.files=new Oi(this._client)}create(e,t){return this._client.post("/containers",{body:e,...t})}retrieve(e,t){return this._client.get(A`/containers/${e}`,t)}list(e={},t){return this._client.getAPIList("/containers",re,{query:e,...t})}delete(e,t){return this._client.delete(A`/containers/${e}`,{...t,headers:$([{Accept:"*/*"},t?.headers])})}}Ti.Files=Oi;class Fl extends U{create(e,t){const r=!!e.encoding_format;let s=r?e.encoding_format:"base64";r&&fe(this._client).debug("embeddings/user defined encoding_format:",e.encoding_format);const a=this._client.post("/embeddings",{body:{...e,encoding_format:s},...t});return r?a:(fe(this._client).debug("embeddings/decoding base64 embeddings from base64"),a._thenUnwrap(i=>(i&&i.data&&i.data.forEach(o=>{const u=o.embedding;o.embedding=wf(u)}),i)))}}class Bl extends U{retrieve(e,t,r){const{eval_id:s,run_id:a}=t;return this._client.get(A`/evals/${s}/runs/${a}/output_items/${e}`,r)}list(e,t,r){const{eval_id:s,...a}=t;return this._client.getAPIList(A`/evals/${s}/runs/${e}/output_items`,re,{query:a,...r})}}class Ai extends U{constructor(){super(...arguments),this.outputItems=new Bl(this._client)}create(e,t,r){return this._client.post(A`/evals/${e}/runs`,{body:t,...r})}retrieve(e,t,r){const{eval_id:s}=t;return this._client.get(A`/evals/${s}/runs/${e}`,r)}list(e,t={},r){return this._client.getAPIList(A`/evals/${e}/runs`,re,{query:t,...r})}delete(e,t,r){const{eval_id:s}=t;return this._client.delete(A`/evals/${s}/runs/${e}`,r)}cancel(e,t,r){const{eval_id:s}=t;return this._client.post(A`/evals/${s}/runs/${e}`,r)}}Ai.OutputItems=Bl;class Pi extends U{constructor(){super(...arguments),this.runs=new Ai(this._client)}create(e,t){return this._client.post("/evals",{body:e,...t})}retrieve(e,t){return this._client.get(A`/evals/${e}`,t)}update(e,t,r){return this._client.post(A`/evals/${e}`,{body:t,...r})}list(e={},t){return this._client.getAPIList("/evals",re,{query:e,...t})}delete(e,t){return this._client.delete(A`/evals/${e}`,t)}}Pi.Runs=Ai;let zl=class extends U{create(e,t){return this._client.post("/files",Pt({body:e,...t},this._client))}retrieve(e,t){return this._client.get(A`/files/${e}`,t)}list(e={},t){return this._client.getAPIList("/files",re,{query:e,...t})}delete(e,t){return this._client.delete(A`/files/${e}`,t)}content(e,t){return this._client.get(A`/files/${e}/content`,{...t,headers:$([{Accept:"application/binary"},t?.headers]),__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:t=5e3,maxWait:r=1800*1e3}={}){const s=new Set(["processed","error","deleted"]),a=Date.now();let i=await this.retrieve(e);for(;!i.status||!s.has(i.status);)if(await kr(t),i=await this.retrieve(e),Date.now()-a>r)throw new zn({message:`Giving up on waiting for file ${e} to finish processing after ${r} milliseconds.`});return i}};class ql extends U{}let Hl=class extends U{run(e,t){return this._client.post("/fine_tuning/alpha/graders/run",{body:e,...t})}validate(e,t){return this._client.post("/fine_tuning/alpha/graders/validate",{body:e,...t})}};class Ii extends U{constructor(){super(...arguments),this.graders=new Hl(this._client)}}Ii.Graders=Hl;class Gl extends U{create(e,t,r){return this._client.getAPIList(A`/fine_tuning/checkpoints/${e}/permissions`,Gn,{body:t,method:"post",...r})}retrieve(e,t={},r){return this._client.get(A`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...r})}delete(e,t,r){const{fine_tuned_model_checkpoint:s}=t;return this._client.delete(A`/fine_tuning/checkpoints/${s}/permissions/${e}`,r)}}let xi=class extends U{constructor(){super(...arguments),this.permissions=new Gl(this._client)}};xi.Permissions=Gl;class Jl extends U{list(e,t={},r){return this._client.getAPIList(A`/fine_tuning/jobs/${e}/checkpoints`,re,{query:t,...r})}}class Ri extends U{constructor(){super(...arguments),this.checkpoints=new Jl(this._client)}create(e,t){return this._client.post("/fine_tuning/jobs",{body:e,...t})}retrieve(e,t){return this._client.get(A`/fine_tuning/jobs/${e}`,t)}list(e={},t){return this._client.getAPIList("/fine_tuning/jobs",re,{query:e,...t})}cancel(e,t){return this._client.post(A`/fine_tuning/jobs/${e}/cancel`,t)}listEvents(e,t={},r){return this._client.getAPIList(A`/fine_tuning/jobs/${e}/events`,re,{query:t,...r})}pause(e,t){return this._client.post(A`/fine_tuning/jobs/${e}/pause`,t)}resume(e,t){return this._client.post(A`/fine_tuning/jobs/${e}/resume`,t)}}Ri.Checkpoints=Jl;class Jt extends U{constructor(){super(...arguments),this.methods=new ql(this._client),this.jobs=new Ri(this._client),this.checkpoints=new xi(this._client),this.alpha=new Ii(this._client)}}Jt.Methods=ql;Jt.Jobs=Ri;Jt.Checkpoints=xi;Jt.Alpha=Ii;class Wl extends U{}class ki extends U{constructor(){super(...arguments),this.graderModels=new Wl(this._client)}}ki.GraderModels=Wl;class Zl extends U{createVariation(e,t){return this._client.post("/images/variations",Pt({body:e,...t},this._client))}edit(e,t){return this._client.post("/images/edits",Pt({body:e,...t,stream:e.stream??!1},this._client))}generate(e,t){return this._client.post("/images/generations",{body:e,...t,stream:e.stream??!1})}}class Kl extends U{retrieve(e,t){return this._client.get(A`/models/${e}`,t)}list(e){return this._client.getAPIList("/models",Gn,e)}delete(e,t){return this._client.delete(A`/models/${e}`,t)}}class Vl extends U{create(e,t){return this._client.post("/moderations",{body:e,...t})}}function Ef(n,e){return!e||!Of(e)?{...n,output_parsed:null,output:n.output.map(t=>t.type==="function_call"?{...t,parsed_arguments:null}:t.type==="message"?{...t,content:t.content.map(r=>({...r,parsed:null}))}:t)}:Xl(n,e)}function Xl(n,e){const t=n.output.map(s=>{if(s.type==="function_call")return{...s,parsed_arguments:Pf(e,s)};if(s.type==="message"){const a=s.content.map(i=>i.type==="output_text"?{...i,parsed:Sf(e,i.text)}:i);return{...s,content:a}}return s}),r=Object.assign({},n,{output:t});return Object.getOwnPropertyDescriptor(n,"output_text")||Va(r),Object.defineProperty(r,"output_parsed",{enumerable:!0,get(){for(const s of r.output)if(s.type==="message"){for(const a of s.content)if(a.type==="output_text"&&a.parsed!==null)return a.parsed}return null}}),r}function Sf(n,e){return n.text?.format?.type!=="json_schema"?null:"$parseRaw"in n.text?.format?(n.text?.format).$parseRaw(e):JSON.parse(e)}function Of(n){return!!_i(n.text?.format)}function Tf(n){return n?.$brand==="auto-parseable-tool"}function Af(n,e){return n.find(t=>t.type==="function"&&t.name===e)}function Pf(n,e){const t=Af(n.tools??[],e.name);return{...e,...e,parsed_arguments:Tf(t)?t.$parseRaw(e.arguments):t?.strict?JSON.parse(e.arguments):null}}function Va(n){const e=[];for(const t of n.output)if(t.type==="message")for(const r of t.content)r.type==="output_text"&&e.push(r.text);n.output_text=e.join("")}var Nt,Gr,ot,Jr,xo,Ro,ko,Co;class Ci extends bi{constructor(e){super(),Nt.add(this),Gr.set(this,void 0),ot.set(this,void 0),Jr.set(this,void 0),M(this,Gr,e)}static createResponse(e,t,r){const s=new Ci(t);return s._run(()=>s._createOrRetrieveResponse(e,t,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),s}async _createOrRetrieveResponse(e,t,r){const s=r?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),w(this,Nt,"m",xo).call(this);let a,i=null;"response_id"in t?(a=await e.responses.retrieve(t.response_id,{stream:!0},{...r,signal:this.controller.signal,stream:!0}),i=t.starting_after??null):a=await e.responses.create({...t,stream:!0},{...r,signal:this.controller.signal}),this._connected();for await(const o of a)w(this,Nt,"m",Ro).call(this,o,i);if(a.controller.signal?.aborted)throw new Ce;return w(this,Nt,"m",ko).call(this)}[(Gr=new WeakMap,ot=new WeakMap,Jr=new WeakMap,Nt=new WeakSet,xo=function(){this.ended||M(this,ot,void 0)},Ro=function(t,r){if(this.ended)return;const s=(i,o)=>{(r==null||o.sequence_number>r)&&this._emit(i,o)},a=w(this,Nt,"m",Co).call(this,t);switch(s("event",t),t.type){case"response.output_text.delta":{const i=a.output[t.output_index];if(!i)throw new L(`missing output at index ${t.output_index}`);if(i.type==="message"){const o=i.content[t.content_index];if(!o)throw new L(`missing content at index ${t.content_index}`);if(o.type!=="output_text")throw new L(`expected content to be 'output_text', got ${o.type}`);s("response.output_text.delta",{...t,snapshot:o.text})}break}case"response.function_call_arguments.delta":{const i=a.output[t.output_index];if(!i)throw new L(`missing output at index ${t.output_index}`);i.type==="function_call"&&s("response.function_call_arguments.delta",{...t,snapshot:i.arguments});break}default:s(t.type,t);break}},ko=function(){if(this.ended)throw new L("stream has ended, this shouldn't happen");const t=w(this,ot,"f");if(!t)throw new L("request ended without sending any events");M(this,ot,void 0);const r=If(t,w(this,Gr,"f"));return M(this,Jr,r),r},Co=function(t){let r=w(this,ot,"f");if(!r){if(t.type!=="response.created")throw new L(`When snapshot hasn't been set yet, expected 'response.created' event, got ${t.type}`);return r=M(this,ot,t.response),r}switch(t.type){case"response.output_item.added":{r.output.push(t.item);break}case"response.content_part.added":{const s=r.output[t.output_index];if(!s)throw new L(`missing output at index ${t.output_index}`);s.type==="message"&&s.content.push(t.part);break}case"response.output_text.delta":{const s=r.output[t.output_index];if(!s)throw new L(`missing output at index ${t.output_index}`);if(s.type==="message"){const a=s.content[t.content_index];if(!a)throw new L(`missing content at index ${t.content_index}`);if(a.type!=="output_text")throw new L(`expected content to be 'output_text', got ${a.type}`);a.text+=t.delta}break}case"response.function_call_arguments.delta":{const s=r.output[t.output_index];if(!s)throw new L(`missing output at index ${t.output_index}`);s.type==="function_call"&&(s.arguments+=t.delta);break}case"response.completed":{M(this,ot,t.response);break}}return r},Symbol.asyncIterator)](){const e=[],t=[];let r=!1;return this.on("event",s=>{const a=t.shift();a?a.resolve(s):e.push(s)}),this.on("end",()=>{r=!0;for(const s of t)s.resolve(void 0);t.length=0}),this.on("abort",s=>{r=!0;for(const a of t)a.reject(s);t.length=0}),this.on("error",s=>{r=!0;for(const a of t)a.reject(s);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((a,i)=>t.push({resolve:a,reject:i})).then(a=>a?{value:a,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();const e=w(this,Jr,"f");if(!e)throw new L("stream ended without producing a ChatCompletion");return e}}function If(n,e){return Ef(n,e)}class Ql extends U{list(e,t={},r){return this._client.getAPIList(A`/responses/${e}/input_items`,re,{query:t,...r})}}class $i extends U{constructor(){super(...arguments),this.inputItems=new Ql(this._client)}create(e,t){return this._client.post("/responses",{body:e,...t,stream:e.stream??!1})._thenUnwrap(r=>("object"in r&&r.object==="response"&&Va(r),r))}retrieve(e,t={},r){return this._client.get(A`/responses/${e}`,{query:t,...r,stream:t?.stream??!1})._thenUnwrap(s=>("object"in s&&s.object==="response"&&Va(s),s))}delete(e,t){return this._client.delete(A`/responses/${e}`,{...t,headers:$([{Accept:"*/*"},t?.headers])})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap(r=>Xl(r,e))}stream(e,t){return Ci.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(A`/responses/${e}/cancel`,t)}}$i.InputItems=Ql;class Yl extends U{create(e,t,r){return this._client.post(A`/uploads/${e}/parts`,Pt({body:t,...r},this._client))}}class Ni extends U{constructor(){super(...arguments),this.parts=new Yl(this._client)}create(e,t){return this._client.post("/uploads",{body:e,...t})}cancel(e,t){return this._client.post(A`/uploads/${e}/cancel`,t)}complete(e,t,r){return this._client.post(A`/uploads/${e}/complete`,{body:t,...r})}}Ni.Parts=Yl;const xf=async n=>{const e=await Promise.allSettled(n),t=e.filter(s=>s.status==="rejected");if(t.length){for(const s of t)console.error(s.reason);throw new Error(`${t.length} promise(s) failed - see the above errors`)}const r=[];for(const s of e)s.status==="fulfilled"&&r.push(s.value);return r};class ed extends U{create(e,t,r){return this._client.post(A`/vector_stores/${e}/file_batches`,{body:t,...r,headers:$([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(e,t,r){const{vector_store_id:s}=t;return this._client.get(A`/vector_stores/${s}/file_batches/${e}`,{...r,headers:$([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}cancel(e,t,r){const{vector_store_id:s}=t;return this._client.post(A`/vector_stores/${s}/file_batches/${e}/cancel`,{...r,headers:$([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async createAndPoll(e,t,r){const s=await this.create(e,t);return await this.poll(e,s.id,r)}listFiles(e,t,r){const{vector_store_id:s,...a}=t;return this._client.getAPIList(A`/vector_stores/${s}/file_batches/${e}/files`,re,{query:a,...r,headers:$([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async poll(e,t,r){const s=$([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);for(;;){const{data:a,response:i}=await this.retrieve(t,{vector_store_id:e},{...r,headers:s}).withResponse();switch(a.status){case"in_progress":let o=5e3;if(r?.pollIntervalMs)o=r.pollIntervalMs;else{const u=i.headers.get("openai-poll-after-ms");if(u){const c=parseInt(u);isNaN(c)||(o=c)}}await kr(o);break;case"failed":case"cancelled":case"completed":return a}}}async uploadAndPoll(e,{files:t,fileIds:r=[]},s){if(t==null||t.length==0)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");const a=s?.maxConcurrency??5,i=Math.min(a,t.length),o=this._client,u=t.values(),c=[...r];async function l(h){for(let f of h){const p=await o.files.create({file:f,purpose:"assistants"},s);c.push(p.id)}}const d=Array(i).fill(u).map(l);return await xf(d),await this.createAndPoll(e,{file_ids:c})}}class td extends U{create(e,t,r){return this._client.post(A`/vector_stores/${e}/files`,{body:t,...r,headers:$([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(e,t,r){const{vector_store_id:s}=t;return this._client.get(A`/vector_stores/${s}/files/${e}`,{...r,headers:$([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(e,t,r){const{vector_store_id:s,...a}=t;return this._client.post(A`/vector_stores/${s}/files/${e}`,{body:a,...r,headers:$([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t={},r){return this._client.getAPIList(A`/vector_stores/${e}/files`,re,{query:t,...r,headers:$([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}delete(e,t,r){const{vector_store_id:s}=t;return this._client.delete(A`/vector_stores/${s}/files/${e}`,{...r,headers:$([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async createAndPoll(e,t,r){const s=await this.create(e,t,r);return await this.poll(e,s.id,r)}async poll(e,t,r){const s=$([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);for(;;){const a=await this.retrieve(t,{vector_store_id:e},{...r,headers:s}).withResponse(),i=a.data;switch(i.status){case"in_progress":let o=5e3;if(r?.pollIntervalMs)o=r.pollIntervalMs;else{const u=a.response.headers.get("openai-poll-after-ms");if(u){const c=parseInt(u);isNaN(c)||(o=c)}}await kr(o);break;case"failed":case"completed":return i}}}async upload(e,t,r){const s=await this._client.files.create({file:t,purpose:"assistants"},r);return this.create(e,{file_id:s.id},r)}async uploadAndPoll(e,t,r){const s=await this.upload(e,t,r);return await this.poll(e,s.id,r)}content(e,t,r){const{vector_store_id:s}=t;return this._client.getAPIList(A`/vector_stores/${s}/files/${e}/content`,Gn,{...r,headers:$([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}}class Zn extends U{constructor(){super(...arguments),this.files=new td(this._client),this.fileBatches=new ed(this._client)}create(e,t){return this._client.post("/vector_stores",{body:e,...t,headers:$([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(A`/vector_stores/${e}`,{...t,headers:$([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,r){return this._client.post(A`/vector_stores/${e}`,{body:t,...r,headers:$([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e={},t){return this._client.getAPIList("/vector_stores",re,{query:e,...t,headers:$([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}delete(e,t){return this._client.delete(A`/vector_stores/${e}`,{...t,headers:$([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}search(e,t,r){return this._client.getAPIList(A`/vector_stores/${e}/search`,Gn,{body:t,method:"post",...r,headers:$([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}}Zn.Files=td;Zn.FileBatches=ed;var Ut,rd,mn;class nd extends U{constructor(){super(...arguments),Ut.add(this)}async unwrap(e,t,r=this._client.webhookSecret,s=300){return await this.verifySignature(e,t,r,s),JSON.parse(e)}async verifySignature(e,t,r=this._client.webhookSecret,s=300){if(typeof crypto>"u"||typeof crypto.subtle.importKey!="function"||typeof crypto.subtle.verify!="function")throw new Error("Webhook signature verification is only supported when the `crypto` global is defined");w(this,Ut,"m",rd).call(this,r);const a=$([t]).values,i=w(this,Ut,"m",mn).call(this,a,"webhook-signature"),o=w(this,Ut,"m",mn).call(this,a,"webhook-timestamp"),u=w(this,Ut,"m",mn).call(this,a,"webhook-id"),c=parseInt(o,10);if(isNaN(c))throw new ar("Invalid webhook timestamp format");const l=Math.floor(Date.now()/1e3);if(l-c>s)throw new ar("Webhook timestamp is too old");if(c>l+s)throw new ar("Webhook timestamp is too new");const d=i.split(" ").map(m=>m.startsWith("v1,")?m.substring(3):m),h=r.startsWith("whsec_")?Buffer.from(r.replace("whsec_",""),"base64"):Buffer.from(r,"utf-8"),f=u?`${u}.${o}.${e}`:`${o}.${e}`,p=await crypto.subtle.importKey("raw",h,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(const m of d)try{const g=Buffer.from(m,"base64");if(await crypto.subtle.verify("HMAC",p,g,new TextEncoder().encode(f)))return}catch{continue}throw new ar("The given webhook signature does not match the expected signature")}}Ut=new WeakSet,rd=function(e){if(typeof e!="string"||e.length===0)throw new Error("The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET, on the client class, OpenAI({ webhookSecret: '123' }), or passed to this function")},mn=function(e,t){if(!e)throw new Error("Headers are required");const r=e.get(t);if(r==null)throw new Error(`Missing required header: ${t}`);return r};var Xa,ji,gn,sd;let H=class{constructor({baseURL:e=$t("OPENAI_BASE_URL"),apiKey:t=$t("OPENAI_API_KEY"),organization:r=$t("OPENAI_ORG_ID")??null,project:s=$t("OPENAI_PROJECT_ID")??null,webhookSecret:a=$t("OPENAI_WEBHOOK_SECRET")??null,...i}={}){if(Xa.add(this),gn.set(this,void 0),this.completions=new Ul(this),this.chat=new Ei(this),this.embeddings=new Fl(this),this.files=new zl(this),this.images=new Zl(this),this.audio=new $r(this),this.moderations=new Vl(this),this.models=new Kl(this),this.fineTuning=new Jt(this),this.graders=new ki(this),this.vectorStores=new Zn(this),this.webhooks=new nd(this),this.beta=new Nr(this),this.batches=new Cl(this),this.uploads=new Ni(this),this.responses=new $i(this),this.evals=new Pi(this),this.containers=new Ti(this),t===void 0)throw new L("The OPENAI_API_KEY environment variable is missing or empty; either provide it, or instantiate the OpenAI client with an apiKey option, like new OpenAI({ apiKey: 'My API Key' }).");const o={apiKey:t,organization:r,project:s,webhookSecret:a,...i,baseURL:e||"https://api.openai.com/v1"};if(!o.dangerouslyAllowBrowser&&Ph())throw new L(`It looks like you're running in a browser-like environment.
|
|
15
|
+
|
|
16
|
+
This is disabled by default, as it risks exposing your secret API credentials to attackers.
|
|
17
|
+
If you understand the risks and have appropriate mitigations in place,
|
|
18
|
+
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
|
|
19
|
+
|
|
20
|
+
new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
|
|
21
|
+
|
|
22
|
+
https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
|
|
23
|
+
`);this.baseURL=o.baseURL,this.timeout=o.timeout??ji.DEFAULT_TIMEOUT,this.logger=o.logger??console;const u="warn";this.logLevel=u,this.logLevel=go(o.logLevel,"ClientOptions.logLevel",this)??go($t("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??u,this.fetchOptions=o.fetchOptions,this.maxRetries=o.maxRetries??2,this.fetch=o.fetch??Ch(),M(this,gn,Nh),this._options=o,this.apiKey=t,this.organization=r,this.project=s,this.webhookSecret=a}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){}async authHeaders(e){return $([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return Fh(e,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${Lt}`}defaultIdempotencyKey(){return`stainless-node-retry-${jc()}`}makeStatusError(e,t,r,s){return me.generate(e,t,r,s)}buildURL(e,t,r){const s=!w(this,Xa,"m",sd).call(this)&&r||this.baseURL,a=vh(e)?new URL(e):new URL(s+(s.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),i=this.defaultQuery();return Sh(i)||(t={...i,...t}),typeof t=="object"&&t&&!Array.isArray(t)&&(a.search=this.stringifyQuery(t)),a.toString()}async prepareOptions(e){}async prepareRequest(e,{url:t,options:r}){}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,r){return this.request(Promise.resolve(r).then(s=>({method:e,path:t,...s})))}request(e,t=null){return new Hn(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,r){const s=await e,a=s.maxRetries??this.maxRetries;t==null&&(t=a),await this.prepareOptions(s);const{req:i,url:o,timeout:u}=await this.buildRequest(s,{retryCount:a-t});await this.prepareRequest(i,{url:o,options:s});const c="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),l=r===void 0?"":`, retryOf: ${r}`,d=Date.now();if(fe(this).debug(`[${c}] sending request`,wt({retryOfRequestLogID:r,method:s.method,url:o,options:s,headers:i.headers})),s.signal?.aborted)throw new Ce;const h=new AbortController,f=await this.fetchWithTimeout(o,i,u,h).catch(Fa),p=Date.now();if(f instanceof Error){const _=`retrying, ${t} attempts remaining`;if(s.signal?.aborted)throw new Ce;const y=Da(f)||/timed? ?out/i.test(String(f)+("cause"in f?String(f.cause):""));if(t)return fe(this).info(`[${c}] connection ${y?"timed out":"failed"} - ${_}`),fe(this).debug(`[${c}] connection ${y?"timed out":"failed"} (${_})`,wt({retryOfRequestLogID:r,url:o,durationMs:p-d,message:f.message})),this.retryRequest(s,t,r??c);throw fe(this).info(`[${c}] connection ${y?"timed out":"failed"} - error; no more retries left`),fe(this).debug(`[${c}] connection ${y?"timed out":"failed"} (error; no more retries left)`,wt({retryOfRequestLogID:r,url:o,durationMs:p-d,message:f.message})),y?new zn:new Bn({cause:f})}const m=[...f.headers.entries()].filter(([_])=>_==="x-request-id").map(([_,y])=>", "+_+": "+JSON.stringify(y)).join(""),g=`[${c}${l}${m}] ${i.method} ${o} ${f.ok?"succeeded":"failed"} with status ${f.status} in ${p-d}ms`;if(!f.ok){const _=await this.shouldRetry(f);if(t&&_){const x=`retrying, ${t} attempts remaining`;return await $h(f.body),fe(this).info(`${g} - ${x}`),fe(this).debug(`[${c}] response error (${x})`,wt({retryOfRequestLogID:r,url:f.url,status:f.status,headers:f.headers,durationMs:p-d})),this.retryRequest(s,t,r??c,f.headers)}const y=_?"error; no more retries left":"error; not retryable";fe(this).info(`${g} - ${y}`);const b=await f.text().catch(x=>Fa(x).message),v=Ah(b),E=v?void 0:b;throw fe(this).debug(`[${c}] response error (${y})`,wt({retryOfRequestLogID:r,url:f.url,status:f.status,headers:f.headers,message:E,durationMs:Date.now()-d})),this.makeStatusError(f.status,v,E,f.headers)}return fe(this).info(g),fe(this).debug(`[${c}] response start`,wt({retryOfRequestLogID:r,url:f.url,status:f.status,headers:f.headers,durationMs:p-d})),{response:f,options:s,controller:h,requestLogID:c,retryOfRequestLogID:r,startTime:d}}getAPIList(e,t,r){return this.requestAPIList(t,{method:"get",path:e,...r})}requestAPIList(e,t){const r=this.makeRequest(t,null,void 0);return new Kh(this,r,e)}async fetchWithTimeout(e,t,r,s){const{signal:a,method:i,...o}=t||{};a&&a.addEventListener("abort",()=>s.abort());const u=setTimeout(()=>s.abort(),r),c=globalThis.ReadableStream&&o.body instanceof globalThis.ReadableStream||typeof o.body=="object"&&o.body!==null&&Symbol.asyncIterator in o.body,l={signal:s.signal,...c?{duplex:"half"}:{},method:"GET",...o};i&&(l.method=i.toUpperCase());try{return await this.fetch.call(void 0,e,l)}finally{clearTimeout(u)}}async shouldRetry(e){const t=e.headers.get("x-should-retry");return t==="true"?!0:t==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,r,s){let a;const i=s?.get("retry-after-ms");if(i){const u=parseFloat(i);Number.isNaN(u)||(a=u)}const o=s?.get("retry-after");if(o&&!a){const u=parseFloat(o);Number.isNaN(u)?a=Date.parse(o)-Date.now():a=u*1e3}if(!(a&&0<=a&&a<60*1e3)){const u=e.maxRetries??this.maxRetries;a=this.calculateDefaultRetryTimeoutMillis(t,u)}return await kr(a),this.makeRequest(e,t-1,r)}calculateDefaultRetryTimeoutMillis(e,t){const a=t-e,i=Math.min(.5*Math.pow(2,a),8),o=1-Math.random()*.25;return i*o*1e3}async buildRequest(e,{retryCount:t=0}={}){const r={...e},{method:s,path:a,query:i,defaultBaseURL:o}=r,u=this.buildURL(a,i,o);"timeout"in r&&Th("timeout",r.timeout),r.timeout=r.timeout??this.timeout;const{bodyHeaders:c,body:l}=this.buildBody({options:r}),d=await this.buildHeaders({options:e,method:s,bodyHeaders:c,retryCount:t});return{req:{method:s,headers:d,...r.signal&&{signal:r.signal},...globalThis.ReadableStream&&l instanceof globalThis.ReadableStream&&{duplex:"half"},...l&&{body:l},...this.fetchOptions??{},...r.fetchOptions??{}},url:u,timeout:r.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:r,retryCount:s}){let a={};this.idempotencyHeader&&t!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),a[this.idempotencyHeader]=e.idempotencyKey);const i=$([a,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(s),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...kh(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders(e),this._options.defaultHeaders,r,e.headers]);return this.validateHeaders(i),i.values}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};const r=$([t]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&r.values.has("content-type")||e instanceof Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:Wc(e)}:w(this,gn,"f").call(this,{body:e,headers:r})}};ji=H,gn=new WeakMap,Xa=new WeakSet,sd=function(){return this.baseURL!=="https://api.openai.com/v1"};H.OpenAI=ji;H.DEFAULT_TIMEOUT=6e5;H.OpenAIError=L;H.APIError=me;H.APIConnectionError=Bn;H.APIConnectionTimeoutError=zn;H.APIUserAbortError=Ce;H.NotFoundError=Dc;H.ConflictError=Fc;H.RateLimitError=zc;H.BadRequestError=Lc;H.AuthenticationError=Mc;H.InternalServerError=qc;H.PermissionDeniedError=Uc;H.UnprocessableEntityError=Bc;H.InvalidWebhookSignatureError=ar;H.toFile=tf;H.Completions=Ul;H.Chat=Ei;H.Embeddings=Fl;H.Files=zl;H.Images=Zl;H.Audio=$r;H.Moderations=Vl;H.Models=Kl;H.FineTuning=Jt;H.Graders=ki;H.VectorStores=Zn;H.Webhooks=nd;H.Beta=Nr;H.Batches=Cl;H.Uploads=Ni;H.Responses=$i;H.Evals=Pi;H.Containers=Ti;function $o(n,e=Li){n=n.trim();const t=n.indexOf("```");if(t===-1)return e(n);let r=n.substring(t+3);r.startsWith(`json
|
|
24
|
+
`)?r=r.substring(5):r.startsWith("json")?r=r.substring(4):r.startsWith(`
|
|
25
|
+
`)&&(r=r.substring(1));const s=r.indexOf("```");let a=r;return s!==-1&&(a=r.substring(0,s)),e(a.trim())}function Li(n){if(typeof n>"u")return null;try{return JSON.parse(n)}catch{}let e="";const t=[];let r=!1,s=!1;for(let a of n){if(r)a==='"'&&!s?r=!1:a===`
|
|
26
|
+
`&&!s?a="\\n":a==="\\"?s=!s:s=!1;else if(a==='"')r=!0,s=!1;else if(a==="{")t.push("}");else if(a==="[")t.push("]");else if(a==="}"||a==="]")if(t&&t[t.length-1]===a)t.pop();else return null;e+=a}r&&(e+='"');for(let a=t.length-1;a>=0;a-=1)e+=t[a];try{return JSON.parse(e)}catch{return null}}var Es,No;function Rf(){return No||(No=1,Es=function(n,e){if(typeof n!="string")throw new TypeError("Expected a string");return e=typeof e>"u"?"_":e,n.replace(/([a-z\d])([A-Z])/g,"$1"+e+"$2").replace(/([A-Z]+)([A-Z][a-z\d]+)/g,"$1"+e+"$2").toLowerCase()}),Es}var kf=Rf();const Cf=Rr(kf);var Wr={exports:{}},jo;function $f(){if(jo)return Wr.exports;jo=1;const n=/[\p{Lu}]/u,e=/[\p{Ll}]/u,t=/^[\p{Lu}](?![\p{Lu}])/gu,r=/([\p{Alpha}\p{N}_]|$)/u,s=/[_.\- ]+/,a=new RegExp("^"+s.source),i=new RegExp(s.source+r.source,"gu"),o=new RegExp("\\d+"+r.source,"gu"),u=(h,f,p)=>{let m=!1,g=!1,_=!1;for(let y=0;y<h.length;y++){const b=h[y];m&&n.test(b)?(h=h.slice(0,y)+"-"+h.slice(y),m=!1,_=g,g=!0,y++):g&&_&&e.test(b)?(h=h.slice(0,y-1)+"-"+h.slice(y-1),_=g,g=!1,m=!0):(m=f(b)===b&&p(b)!==b,_=g,g=p(b)===b&&f(b)!==b)}return h},c=(h,f)=>(t.lastIndex=0,h.replace(t,p=>f(p))),l=(h,f)=>(i.lastIndex=0,o.lastIndex=0,h.replace(i,(p,m)=>f(m)).replace(o,p=>f(p))),d=(h,f)=>{if(!(typeof h=="string"||Array.isArray(h)))throw new TypeError("Expected the input to be `string | string[]`");if(f={pascalCase:!1,preserveConsecutiveUppercase:!1,...f},Array.isArray(h)?h=h.map(_=>_.trim()).filter(_=>_.length).join("-"):h=h.trim(),h.length===0)return"";const p=f.locale===!1?_=>_.toLowerCase():_=>_.toLocaleLowerCase(f.locale),m=f.locale===!1?_=>_.toUpperCase():_=>_.toLocaleUpperCase(f.locale);return h.length===1?f.pascalCase?m(h):p(h):(h!==p(h)&&(h=u(h,p,m)),h=h.replace(a,""),f.preserveConsecutiveUppercase?h=c(h,p):h=p(h),f.pascalCase&&(h=m(h.charAt(0))+h.slice(1)),l(h,m))};return Wr.exports=d,Wr.exports.default=d,Wr.exports}$f();function Nf(n,e){return e?.[n]||Cf(n)}function jf(n,e,t){const r={};for(const s in n)Object.hasOwn(n,s)&&(r[e(s,t)]=n[s]);return r}function Lo(n){return Array.isArray(n)?[...n]:{...n}}function Lf(n,e){const t=Lo(n);for(const[r,s]of Object.entries(e)){const[a,...i]=r.split(".").reverse();let o=t;for(const u of i.reverse()){if(o[u]===void 0)break;o[u]=Lo(o[u]),o=o[u]}o[a]!==void 0&&(o[a]={lc:1,type:"secret",id:[s]})}return t}function ad(n){const e=Object.getPrototypeOf(n);return typeof n.lc_name=="function"&&(typeof e.lc_name!="function"||n.lc_name()!==e.lc_name())?n.lc_name():n.name}class It{static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,ad(this.constructor)]}get lc_secrets(){}get lc_attributes(){}get lc_aliases(){}get lc_serializable_keys(){}constructor(e,...t){Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"lc_kwargs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.lc_serializable_keys!==void 0?this.lc_kwargs=Object.fromEntries(Object.entries(e||{}).filter(([r])=>this.lc_serializable_keys?.includes(r))):this.lc_kwargs=e??{}}toJSON(){if(!this.lc_serializable)return this.toJSONNotImplemented();if(this.lc_kwargs instanceof It||typeof this.lc_kwargs!="object"||Array.isArray(this.lc_kwargs))return this.toJSONNotImplemented();const e={},t={},r=Object.keys(this.lc_kwargs).reduce((s,a)=>(s[a]=a in this?this[a]:this.lc_kwargs[a],s),{});for(let s=Object.getPrototypeOf(this);s;s=Object.getPrototypeOf(s))Object.assign(e,Reflect.get(s,"lc_aliases",this)),Object.assign(t,Reflect.get(s,"lc_secrets",this)),Object.assign(r,Reflect.get(s,"lc_attributes",this));return Object.keys(t).forEach(s=>{let a=this,i=r;const[o,...u]=s.split(".").reverse();for(const c of u.reverse()){if(!(c in a)||a[c]===void 0)return;(!(c in i)||i[c]===void 0)&&(typeof a[c]=="object"&&a[c]!=null?i[c]={}:Array.isArray(a[c])&&(i[c]=[])),a=a[c],i=i[c]}o in a&&a[o]!==void 0&&(i[o]=i[o]||a[o])}),{lc:1,type:"constructor",id:this.lc_id,kwargs:jf(Object.keys(t).length?Lf(r,t):r,Nf,e)}}toJSONNotImplemented(){return{lc:1,type:"not_implemented",id:this.lc_id}}}function xt(n){return typeof n=="object"&&n!==null&&"type"in n&&typeof n.type=="string"&&"source_type"in n&&(n.source_type==="url"||n.source_type==="base64"||n.source_type==="text"||n.source_type==="id")}function Mf(n){return xt(n)&&n.source_type==="url"&&"url"in n&&typeof n.url=="string"}function Uf(n){return xt(n)&&n.source_type==="base64"&&"data"in n&&typeof n.data=="string"}function Df(n){if(xt(n)){if(n.source_type==="url")return{type:"image_url",image_url:{url:n.url}};if(n.source_type==="base64"){if(!n.mime_type)throw new Error("mime_type key is required for base64 data.");return{type:"image_url",image_url:{url:`data:${n.mime_type};base64,${n.data}`}}}}throw new Error("Unsupported source type. Only 'url' and 'base64' are supported.")}function Mo(n){const e=n.split(";")[0].split("/");if(e.length!==2)throw new Error(`Invalid mime type: "${n}" - does not match type/subtype format.`);const t=e[0].trim(),r=e[1].trim();if(t===""||r==="")throw new Error(`Invalid mime type: "${n}" - type or subtype is empty.`);const s={};for(const a of n.split(";").slice(1)){const i=a.split("=");if(i.length!==2)throw new Error(`Invalid parameter syntax in mime type: "${n}".`);const o=i[0].trim(),u=i[1].trim();if(o==="")throw new Error(`Invalid parameter syntax in mime type: "${n}".`);s[o]=u}return{type:t,subtype:r,parameters:s}}function Uo({dataUrl:n,asTypedArray:e=!1}){const t=n.match(/^data:(\w+\/\w+);base64,([A-Za-z0-9+/]+=*)$/);let r;if(t){r=t[1].toLowerCase();const s=e?Uint8Array.from(atob(t[2]),a=>a.charCodeAt(0)):t[2];return{mime_type:r,data:s}}}function id(n,e){if(n.type==="text"){if(!e.fromStandardTextBlock)throw new Error(`Converter for ${e.providerName} does not implement \`fromStandardTextBlock\` method.`);return e.fromStandardTextBlock(n)}if(n.type==="image"){if(!e.fromStandardImageBlock)throw new Error(`Converter for ${e.providerName} does not implement \`fromStandardImageBlock\` method.`);return e.fromStandardImageBlock(n)}if(n.type==="audio"){if(!e.fromStandardAudioBlock)throw new Error(`Converter for ${e.providerName} does not implement \`fromStandardAudioBlock\` method.`);return e.fromStandardAudioBlock(n)}if(n.type==="file"){if(!e.fromStandardFileBlock)throw new Error(`Converter for ${e.providerName} does not implement \`fromStandardFileBlock\` method.`);return e.fromStandardFileBlock(n)}throw new Error(`Unable to convert content block type '${n.type}' to provider-specific format: not recognized.`)}function Wt(n,e){return typeof n=="string"?n===""?e:typeof e=="string"?n+e:Array.isArray(e)&&e.some(t=>xt(t))?[{type:"text",source_type:"text",text:n},...e]:[{type:"text",text:n},...e]:Array.isArray(e)?Kn(n,e)??[...n,...e]:e===""?n:Array.isArray(n)&&n.some(t=>xt(t))?[...n,{type:"file",source_type:"text",text:e}]:[...n,{type:"text",text:e}]}function Ff(n,e){return n==="error"||e==="error"?"error":"success"}function Bf(n,e){function t(r,s){if(typeof r!="object"||r===null||r===void 0)return r;if(s>=e)return Array.isArray(r)?"[Array]":"[Object]";if(Array.isArray(r))return r.map(i=>t(i,s+1));const a={};for(const i of Object.keys(r))a[i]=t(r[i],s+1);return a}return JSON.stringify(t(n,0),null,2)}class kt extends It{get lc_aliases(){return{additional_kwargs:"additional_kwargs",response_metadata:"response_metadata"}}get text(){return typeof this.content=="string"?this.content:Array.isArray(this.content)?this.content.map(e=>typeof e=="string"?e:e.type==="text"?e.text:"").join(""):""}getType(){return this._getType()}constructor(e,t){typeof e=="string"&&(e={content:e,additional_kwargs:t,response_metadata:{}}),e.additional_kwargs||(e.additional_kwargs={}),e.response_metadata||(e.response_metadata={}),super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","messages"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"content",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"additional_kwargs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"response_metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=e.name,this.content=e.content,this.additional_kwargs=e.additional_kwargs,this.response_metadata=e.response_metadata,this.id=e.id}toDict(){return{type:this._getType(),data:this.toJSON().kwargs}}static lc_name(){return"BaseMessage"}get _printableFields(){return{id:this.id,content:this.content,name:this.name,additional_kwargs:this.additional_kwargs,response_metadata:this.response_metadata}}_updateId(e){this.id=e,this.lc_kwargs.id=e}get[Symbol.toStringTag](){return this.constructor.lc_name()}[Symbol.for("nodejs.util.inspect.custom")](e){if(e===null)return this;const t=Bf(this._printableFields,Math.max(4,e));return`${this.constructor.lc_name()} ${t}`}}function ve(n,e){const t={...n};for(const[r,s]of Object.entries(e))if(t[r]==null)t[r]=s;else{if(s==null)continue;if(typeof t[r]!=typeof s||Array.isArray(t[r])!==Array.isArray(s))throw new Error(`field[${r}] already exists in the message chunk, but with a different type.`);if(typeof t[r]=="string"){if(r==="type")continue;["id","name","output_version","model_provider"].includes(r)?t[r]=s:t[r]+=s}else if(typeof t[r]=="object"&&!Array.isArray(t[r]))t[r]=ve(t[r],s);else if(Array.isArray(t[r]))t[r]=Kn(t[r],s);else{if(t[r]===s)continue;console.warn(`field[${r}] already exists in this message chunk and value has unsupported type.`)}}return t}function Kn(n,e){if(!(n===void 0&&e===void 0)){if(n===void 0||e===void 0)return n||e;{const t=[...n];for(const r of e)if(typeof r=="object"&&r!==null&&"index"in r&&typeof r.index=="number"){const s=t.findIndex(a=>{const i=typeof a=="object",o="index"in a&&a.index===r.index,u="id"in a&&"id"in r&&a?.id===r?.id,c=!("id"in a)||!a?.id||!("id"in r)||!r?.id;return i&&o&&(u||c)});s!==-1&&typeof t[s]=="object"&&t[s]!==null?t[s]=ve(t[s],r):t.push(r)}else{if(typeof r=="object"&&r!==null&&"text"in r&&r.text==="")continue;t.push(r)}return t}}}function zf(n,e){if(!n&&!e)throw new Error("Cannot merge two undefined objects.");if(!n||!e)return n||e;if(typeof n!=typeof e)throw new Error(`Cannot merge objects of different types.
|
|
27
|
+
Left ${typeof n}
|
|
28
|
+
Right ${typeof e}`);if(typeof n=="string"&&typeof e=="string")return n+e;if(Array.isArray(n)&&Array.isArray(e))return Kn(n,e);if(typeof n=="object"&&typeof e=="object")return ve(n,e);if(n===e)return n;throw new Error(`Can not merge objects of different types.
|
|
29
|
+
Left ${n}
|
|
30
|
+
Right ${e}`)}class Zt extends kt{}function qf(n){return typeof n.role=="string"}function Vn(n){return typeof n?._getType=="function"}function Hf(n){return Vn(n)&&typeof n.concat=="function"}class Gf extends kt{static lc_name(){return"ToolMessage"}get lc_aliases(){return{tool_call_id:"tool_call_id"}}constructor(e,t,r){typeof e=="string"&&(e={content:e,name:r,tool_call_id:t}),super(e),Object.defineProperty(this,"lc_direct_tool_output",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tool_call_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"artifact",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.tool_call_id=e.tool_call_id,this.artifact=e.artifact,this.status=e.status,this.metadata=e.metadata}_getType(){return"tool"}static isInstance(e){return e._getType()==="tool"}get _printableFields(){return{...super._printableFields,tool_call_id:this.tool_call_id,artifact:this.artifact}}}class Mi extends Zt{constructor(e){super(e),Object.defineProperty(this,"tool_call_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"artifact",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.tool_call_id=e.tool_call_id,this.artifact=e.artifact,this.status=e.status}static lc_name(){return"ToolMessageChunk"}_getType(){return"tool"}concat(e){return new Mi({content:Wt(this.content,e.content),additional_kwargs:ve(this.additional_kwargs,e.additional_kwargs),response_metadata:ve(this.response_metadata,e.response_metadata),artifact:zf(this.artifact,e.artifact),tool_call_id:this.tool_call_id,id:this.id??e.id,status:Ff(this.status,e.status)})}get _printableFields(){return{...super._printableFields,tool_call_id:this.tool_call_id,artifact:this.artifact}}}function Jf(n){const e=[],t=[];for(const r of n)if(r.function){const s=r.function.name;try{const a=JSON.parse(r.function.arguments),i={name:s||"",args:a||{},id:r.id};e.push(i)}catch{t.push({name:s,args:r.function.arguments,id:r.id,error:"Malformed args."})}}else continue;return[e,t]}class Tr extends kt{get lc_aliases(){return{...super.lc_aliases,tool_calls:"tool_calls",invalid_tool_calls:"invalid_tool_calls"}}constructor(e,t){let r;if(typeof e=="string")r={content:e,tool_calls:[],invalid_tool_calls:[],additional_kwargs:t??{}};else{r=e;const s=r.additional_kwargs?.tool_calls,a=r.tool_calls;s!=null&&s.length>0&&(a===void 0||a.length===0)&&console.warn(["New LangChain packages are available that more efficiently handle",`tool calling.
|
|
31
|
+
|
|
32
|
+
Please upgrade your packages to versions that set`,"message tool calls. e.g., `yarn add @langchain/anthropic`,","yarn add @langchain/openai`, etc."].join(" "));try{if(s!=null&&a===void 0){const[i,o]=Jf(s);r.tool_calls=i??[],r.invalid_tool_calls=o??[]}else r.tool_calls=r.tool_calls??[],r.invalid_tool_calls=r.invalid_tool_calls??[]}catch{r.tool_calls=[],r.invalid_tool_calls=[]}}super(r),Object.defineProperty(this,"tool_calls",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"invalid_tool_calls",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"usage_metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),typeof r!="string"&&(this.tool_calls=r.tool_calls??this.tool_calls,this.invalid_tool_calls=r.invalid_tool_calls??this.invalid_tool_calls),this.usage_metadata=r.usage_metadata}static lc_name(){return"AIMessage"}_getType(){return"ai"}get _printableFields(){return{...super._printableFields,tool_calls:this.tool_calls,invalid_tool_calls:this.invalid_tool_calls,usage_metadata:this.usage_metadata}}}function jr(n){return n._getType()==="ai"}function Do(n){return n._getType()==="ai"}class mt extends Zt{constructor(e){let t;if(typeof e=="string")t={content:e,tool_calls:[],invalid_tool_calls:[],tool_call_chunks:[]};else if(e.tool_call_chunks===void 0)t={...e,tool_calls:e.tool_calls??[],invalid_tool_calls:[],tool_call_chunks:[],usage_metadata:e.usage_metadata!==void 0?e.usage_metadata:void 0};else{const r=e.tool_call_chunks.reduce((i,o)=>{const u=i.findIndex(([c])=>"id"in o&&o.id&&"index"in o&&o.index!==void 0?o.id===c.id&&o.index===c.index:"id"in o&&o.id?o.id===c.id:"index"in o&&o.index!==void 0?o.index===c.index:!1);return u!==-1?i[u].push(o):i.push([o]),i},[]),s=[],a=[];for(const i of r){let o={};const u=i[0]?.name??"",c=i.map(h=>h.args||"").join(""),l=c.length?c:"{}",d=i[0]?.id;try{if(o=Li(l),!d||o===null||typeof o!="object"||Array.isArray(o))throw new Error("Malformed tool call chunk args.");s.push({name:u,args:o,id:d,type:"tool_call"})}catch{a.push({name:u,args:l,id:d,error:"Malformed args.",type:"invalid_tool_call"})}}t={...e,tool_calls:s,invalid_tool_calls:a,usage_metadata:e.usage_metadata!==void 0?e.usage_metadata:void 0}}super(t),Object.defineProperty(this,"tool_calls",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"invalid_tool_calls",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"tool_call_chunks",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"usage_metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.tool_call_chunks=t.tool_call_chunks??this.tool_call_chunks,this.tool_calls=t.tool_calls??this.tool_calls,this.invalid_tool_calls=t.invalid_tool_calls??this.invalid_tool_calls,this.usage_metadata=t.usage_metadata}get lc_aliases(){return{...super.lc_aliases,tool_calls:"tool_calls",invalid_tool_calls:"invalid_tool_calls",tool_call_chunks:"tool_call_chunks"}}static lc_name(){return"AIMessageChunk"}_getType(){return"ai"}get _printableFields(){return{...super._printableFields,tool_calls:this.tool_calls,tool_call_chunks:this.tool_call_chunks,invalid_tool_calls:this.invalid_tool_calls,usage_metadata:this.usage_metadata}}concat(e){const t={content:Wt(this.content,e.content),additional_kwargs:ve(this.additional_kwargs,e.additional_kwargs),response_metadata:ve(this.response_metadata,e.response_metadata),tool_call_chunks:[],id:this.id??e.id};if(this.tool_call_chunks!==void 0||e.tool_call_chunks!==void 0){const r=Kn(this.tool_call_chunks,e.tool_call_chunks);r!==void 0&&r.length>0&&(t.tool_call_chunks=r)}if(this.usage_metadata!==void 0||e.usage_metadata!==void 0){const r={...(this.usage_metadata?.input_token_details?.audio!==void 0||e.usage_metadata?.input_token_details?.audio!==void 0)&&{audio:(this.usage_metadata?.input_token_details?.audio??0)+(e.usage_metadata?.input_token_details?.audio??0)},...(this.usage_metadata?.input_token_details?.cache_read!==void 0||e.usage_metadata?.input_token_details?.cache_read!==void 0)&&{cache_read:(this.usage_metadata?.input_token_details?.cache_read??0)+(e.usage_metadata?.input_token_details?.cache_read??0)},...(this.usage_metadata?.input_token_details?.cache_creation!==void 0||e.usage_metadata?.input_token_details?.cache_creation!==void 0)&&{cache_creation:(this.usage_metadata?.input_token_details?.cache_creation??0)+(e.usage_metadata?.input_token_details?.cache_creation??0)}},s={...(this.usage_metadata?.output_token_details?.audio!==void 0||e.usage_metadata?.output_token_details?.audio!==void 0)&&{audio:(this.usage_metadata?.output_token_details?.audio??0)+(e.usage_metadata?.output_token_details?.audio??0)},...(this.usage_metadata?.output_token_details?.reasoning!==void 0||e.usage_metadata?.output_token_details?.reasoning!==void 0)&&{reasoning:(this.usage_metadata?.output_token_details?.reasoning??0)+(e.usage_metadata?.output_token_details?.reasoning??0)}},a=this.usage_metadata??{input_tokens:0,output_tokens:0,total_tokens:0},i=e.usage_metadata??{input_tokens:0,output_tokens:0,total_tokens:0},o={input_tokens:a.input_tokens+i.input_tokens,output_tokens:a.output_tokens+i.output_tokens,total_tokens:a.total_tokens+i.total_tokens,...Object.keys(r).length>0&&{input_token_details:r},...Object.keys(s).length>0&&{output_token_details:s}};t.usage_metadata=o}return new mt(t)}}class Lr extends kt{static lc_name(){return"ChatMessage"}static _chatMessageClass(){return Lr}constructor(e,t){typeof e=="string"&&(e={content:e,role:t}),super(e),Object.defineProperty(this,"role",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.role=e.role}_getType(){return"generic"}static isInstance(e){return e._getType()==="generic"}get _printableFields(){return{...super._printableFields,role:this.role}}}class Xn extends Zt{static lc_name(){return"ChatMessageChunk"}constructor(e,t){typeof e=="string"&&(e={content:e,role:t}),super(e),Object.defineProperty(this,"role",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.role=e.role}_getType(){return"generic"}concat(e){return new Xn({content:Wt(this.content,e.content),additional_kwargs:ve(this.additional_kwargs,e.additional_kwargs),response_metadata:ve(this.response_metadata,e.response_metadata),role:this.role,id:this.id??e.id})}get _printableFields(){return{...super._printableFields,role:this.role}}}class Qn extends Zt{static lc_name(){return"FunctionMessageChunk"}_getType(){return"function"}concat(e){return new Qn({content:Wt(this.content,e.content),additional_kwargs:ve(this.additional_kwargs,e.additional_kwargs),response_metadata:ve(this.response_metadata,e.response_metadata),name:this.name??"",id:this.id??e.id})}}class Yn extends kt{static lc_name(){return"HumanMessage"}_getType(){return"human"}constructor(e,t){super(e,t)}}class es extends Zt{static lc_name(){return"HumanMessageChunk"}_getType(){return"human"}constructor(e,t){super(e,t)}concat(e){return new es({content:Wt(this.content,e.content),additional_kwargs:ve(this.additional_kwargs,e.additional_kwargs),response_metadata:ve(this.response_metadata,e.response_metadata),id:this.id??e.id})}}class Fo extends kt{static lc_name(){return"SystemMessage"}_getType(){return"system"}constructor(e,t){super(e,t)}}class Ar extends Zt{static lc_name(){return"SystemMessageChunk"}_getType(){return"system"}constructor(e,t){super(e,t)}concat(e){return new Ar({content:Wt(this.content,e.content),additional_kwargs:ve(this.additional_kwargs,e.additional_kwargs),response_metadata:ve(this.response_metadata,e.response_metadata),id:this.id??e.id})}}function od(n,e){return n.lc_error_code=e,n.message=`${n.message}
|
|
33
|
+
|
|
34
|
+
Troubleshooting URL: https://js.langchain.com/docs/troubleshooting/errors/${e}/
|
|
35
|
+
`,n}function ud(n){return!!(n&&typeof n=="object"&&"type"in n&&n.type==="tool_call")}class Wf extends Error{constructor(e,t){super(e),Object.defineProperty(this,"output",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.output=t}}class Zf extends kt{constructor(e){super({...e,content:""}),Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.id=e.id}_getType(){return"remove"}get _printableFields(){return{...super._printableFields,id:this.id}}}function Kf(n){return ud(n)?n:typeof n.id=="string"&&n.type==="function"&&typeof n.function=="object"&&n.function!==null&&"arguments"in n.function&&typeof n.function.arguments=="string"&&"name"in n.function&&typeof n.function.name=="string"?{id:n.id,args:JSON.parse(n.function.arguments),name:n.function.name,type:"tool_call"}:n}function Vf(n){return typeof n=="object"&&n!=null&&n.lc===1&&Array.isArray(n.id)&&n.kwargs!=null&&typeof n.kwargs=="object"}function Ss(n){let e,t;if(Vf(n)){const r=n.id.at(-1);r==="HumanMessage"||r==="HumanMessageChunk"?e="user":r==="AIMessage"||r==="AIMessageChunk"?e="assistant":r==="SystemMessage"||r==="SystemMessageChunk"?e="system":r==="FunctionMessage"||r==="FunctionMessageChunk"?e="function":r==="ToolMessage"||r==="ToolMessageChunk"?e="tool":e="unknown",t=n.kwargs}else{const{type:r,...s}=n;e=r,t=s}if(e==="human"||e==="user")return new Yn(t);if(e==="ai"||e==="assistant"){const{tool_calls:r,...s}=t;if(!Array.isArray(r))return new Tr(t);const a=r.map(Kf);return new Tr({...s,tool_calls:a})}else{if(e==="system")return new Fo(t);if(e==="developer")return new Fo({...t,additional_kwargs:{...t.additional_kwargs,__openai_role__:"developer"}});if(e==="tool"&&"tool_call_id"in t)return new Gf({...t,content:t.content,tool_call_id:t.tool_call_id,name:t.name});if(e==="remove"&&"id"in t&&typeof t.id=="string")return new Zf({...t,id:t.id});throw od(new Error(`Unable to coerce message from array: only human, AI, system, developer, or tool message coercion is currently supported.
|
|
36
|
+
|
|
37
|
+
Received: ${JSON.stringify(n,null,2)}`),"MESSAGE_COERCION_FAILURE")}}function pr(n){if(typeof n=="string")return new Yn(n);if(Vn(n))return n;if(Array.isArray(n)){const[e,t]=n;return Ss({type:e,content:t})}else if(qf(n)){const{role:e,...t}=n;return Ss({...t,type:e})}else return Ss(n)}function cd(n,e="Human",t="AI"){const r=[];for(const s of n){let a;if(s._getType()==="human")a=e;else if(s._getType()==="ai")a=t;else if(s._getType()==="system")a="System";else if(s._getType()==="function")a="Function";else if(s._getType()==="tool")a="Tool";else if(s._getType()==="generic")a=s.role;else throw new Error(`Got unsupported message type: ${s._getType()}`);const i=s.name?`${s.name}, `:"",o=typeof s.content=="string"?s.content:JSON.stringify(s.content,null,2);r.push(`${a}: ${i}${o}`)}return r.join(`
|
|
38
|
+
`)}function Xf(n){const e=n._getType();if(e==="human")return new es({...n});if(e==="ai"){let t={...n};return"tool_calls"in t&&(t={...t,tool_call_chunks:t.tool_calls?.map(r=>({...r,type:"tool_call_chunk",index:void 0,args:JSON.stringify(r.args)}))}),new mt({...t})}else{if(e==="system")return new Ar({...n});if(e==="function")return new Qn({...n});if(Lr.isInstance(n))return new Xn({...n});throw new Error("Unknown message type.")}}var tr={exports:{}},Os={},Ts,Bo;function Qf(){if(Bo)return Ts;Bo=1;function n(e,t){typeof t=="boolean"&&(t={forever:t}),this._originalTimeouts=JSON.parse(JSON.stringify(e)),this._timeouts=e,this._options=t||{},this._maxRetryTime=t&&t.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}return Ts=n,n.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)},n.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null},n.prototype.retry=function(e){if(this._timeout&&clearTimeout(this._timeout),!e)return!1;var t=new Date().getTime();if(e&&t-this._operationStart>=this._maxRetryTime)return this._errors.push(e),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(e);var r=this._timeouts.shift();if(r===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),r=this._cachedTimeouts.slice(-1);else return!1;var s=this;return this._timer=setTimeout(function(){s._attempts++,s._operationTimeoutCb&&(s._timeout=setTimeout(function(){s._operationTimeoutCb(s._attempts)},s._operationTimeout),s._options.unref&&s._timeout.unref()),s._fn(s._attempts)},r),this._options.unref&&this._timer.unref(),!0},n.prototype.attempt=function(e,t){this._fn=e,t&&(t.timeout&&(this._operationTimeout=t.timeout),t.cb&&(this._operationTimeoutCb=t.cb));var r=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){r._operationTimeoutCb()},r._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)},n.prototype.try=function(e){console.log("Using RetryOperation.try() is deprecated"),this.attempt(e)},n.prototype.start=function(e){console.log("Using RetryOperation.start() is deprecated"),this.attempt(e)},n.prototype.start=n.prototype.try,n.prototype.errors=function(){return this._errors},n.prototype.attempts=function(){return this._attempts},n.prototype.mainError=function(){if(this._errors.length===0)return null;for(var e={},t=null,r=0,s=0;s<this._errors.length;s++){var a=this._errors[s],i=a.message,o=(e[i]||0)+1;e[i]=o,o>=r&&(t=a,r=o)}return t},Ts}var zo;function Yf(){return zo||(zo=1,(function(n){var e=Qf();n.operation=function(t){var r=n.timeouts(t);return new e(r,{forever:t&&(t.forever||t.retries===1/0),unref:t&&t.unref,maxRetryTime:t&&t.maxRetryTime})},n.timeouts=function(t){if(t instanceof Array)return[].concat(t);var r={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var s in t)r[s]=t[s];if(r.minTimeout>r.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var a=[],i=0;i<r.retries;i++)a.push(this.createTimeout(i,r));return t&&t.forever&&!a.length&&a.push(this.createTimeout(i,r)),a.sort(function(o,u){return o-u}),a},n.createTimeout=function(t,r){var s=r.randomize?Math.random()+1:1,a=Math.round(s*Math.max(r.minTimeout,1)*Math.pow(r.factor,t));return a=Math.min(a,r.maxTimeout),a},n.wrap=function(t,r,s){if(r instanceof Array&&(s=r,r=null),!s){s=[];for(var a in t)typeof t[a]=="function"&&s.push(a)}for(var i=0;i<s.length;i++){var o=s[i],u=t[o];t[o]=(function(l){var d=n.operation(r),h=Array.prototype.slice.call(arguments,1),f=h.pop();h.push(function(p){d.retry(p)||(p&&(arguments[0]=d.mainError()),f.apply(this,arguments))}),d.attempt(function(){l.apply(t,h)})}).bind(t,u),t[o].options=r}}})(Os)),Os}var As,qo;function ep(){return qo||(qo=1,As=Yf()),As}var Ho;function tp(){if(Ho)return tr.exports;Ho=1;const n=ep(),e=["Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed"];class t extends Error{constructor(o){super(),o instanceof Error?(this.originalError=o,{message:o}=o):(this.originalError=new Error(o),this.originalError.stack=this.stack),this.name="AbortError",this.message=o}}const r=(i,o,u)=>{const c=u.retries-(o-1);return i.attemptNumber=o,i.retriesLeft=c,i},s=i=>e.includes(i),a=(i,o)=>new Promise((u,c)=>{o={onFailedAttempt:()=>{},retries:10,...o};const l=n.operation(o);l.attempt(async d=>{try{u(await i(d))}catch(h){if(!(h instanceof Error)){c(new TypeError(`Non-error was thrown: "${h}". You should only throw errors.`));return}if(h instanceof t)l.stop(),c(h.originalError);else if(h instanceof TypeError&&!s(h.message))l.stop(),c(h);else{r(h,d,o);try{await o.onFailedAttempt(h)}catch(f){c(f);return}l.retry(h)||c(l.mainError())}}})});return tr.exports=a,tr.exports.default=a,tr.exports.AbortError=t,tr.exports}var rp=tp();const In=Rr(rp),np=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;function _n(n){return typeof n=="string"&&np.test(n)}var de=[];for(var Ps=0;Ps<256;++Ps)de.push((Ps+256).toString(16).slice(1));function sp(n,e=0){return(de[n[e+0]]+de[n[e+1]]+de[n[e+2]]+de[n[e+3]]+"-"+de[n[e+4]]+de[n[e+5]]+"-"+de[n[e+6]]+de[n[e+7]]+"-"+de[n[e+8]]+de[n[e+9]]+"-"+de[n[e+10]]+de[n[e+11]]+de[n[e+12]]+de[n[e+13]]+de[n[e+14]]+de[n[e+15]]).toLowerCase()}var Zr,ap=new Uint8Array(16);function ip(){if(!Zr&&(Zr=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!Zr))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Zr(ap)}var op=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);const Go={randomUUID:op};function nt(n,e,t){if(Go.randomUUID&&!n)return Go.randomUUID();n=n||{};var r=n.random||(n.rng||ip)();return r[6]=r[6]&15|64,r[8]=r[8]&63|128,sp(r)}let up=class{getStore(){}run(e,t){return t()}};const Is=Symbol.for("ls:tracing_async_local_storage"),cp=new up;let lp=class{getInstance(){return globalThis[Is]??cp}initializeGlobalInstance(e){globalThis[Is]===void 0&&(globalThis[Is]=e)}};const dp=new lp;function hp(n=!1){const e=dp.getInstance().getStore();if(!n&&e===void 0)throw new Error(`Could not get the current run tree.
|
|
39
|
+
|
|
40
|
+
Please make sure you are calling this method within a traceable function and that tracing is enabled.`);return e}function Ui(n){return typeof n=="function"&&"langsmith:traceable"in n}/*!
|
|
41
|
+
* https://github.com/Starcounter-Jack/JSON-Patch
|
|
42
|
+
* (c) 2017-2022 Joachim Wester
|
|
43
|
+
* MIT licensed
|
|
44
|
+
*/const fp=Object.prototype.hasOwnProperty;function Qa(n,e){return fp.call(n,e)}function Ya(n){if(Array.isArray(n)){const t=new Array(n.length);for(let r=0;r<t.length;r++)t[r]=""+r;return t}if(Object.keys)return Object.keys(n);let e=[];for(let t in n)Qa(n,t)&&e.push(t);return e}function Qe(n){switch(typeof n){case"object":return JSON.parse(JSON.stringify(n));case"undefined":return null;default:return n}}function ei(n){let e=0;const t=n.length;let r;for(;e<t;){if(r=n.charCodeAt(e),r>=48&&r<=57){e++;continue}return!1}return!0}function jt(n){return n.indexOf("/")===-1&&n.indexOf("~")===-1?n:n.replace(/~/g,"~0").replace(/\//g,"~1")}function pp(n){return n.replace(/~1/g,"/").replace(/~0/g,"~")}function ti(n){if(n===void 0)return!0;if(n){if(Array.isArray(n)){for(let t=0,r=n.length;t<r;t++)if(ti(n[t]))return!0}else if(typeof n=="object"){const t=Ya(n),r=t.length;for(var e=0;e<r;e++)if(ti(n[t[e]]))return!0}}return!1}function Jo(n,e){const t=[n];for(const r in e){const s=typeof e[r]=="object"?JSON.stringify(e[r],null,2):e[r];typeof s<"u"&&t.push(`${r}: ${s}`)}return t.join(`
|
|
45
|
+
`)}class mp extends Error{constructor(e,t,r,s,a){super(Jo(e,{name:t,index:r,operation:s,tree:a})),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"index",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(this,"operation",{enumerable:!0,configurable:!0,writable:!0,value:s}),Object.defineProperty(this,"tree",{enumerable:!0,configurable:!0,writable:!0,value:a}),Object.setPrototypeOf(this,new.target.prototype),this.message=Jo(e,{name:t,index:r,operation:s,tree:a})}}const te=mp,zt={add:function(n,e,t){return n[e]=this.value,{newDocument:t}},remove:function(n,e,t){var r=n[e];return delete n[e],{newDocument:t,removed:r}},replace:function(n,e,t){var r=n[e];return n[e]=this.value,{newDocument:t,removed:r}},move:function(n,e,t){let r=ri(t,this.path);r&&(r=Qe(r));const s=wr(t,{op:"remove",path:this.from}).removed;return wr(t,{op:"add",path:this.path,value:s}),{newDocument:t,removed:r}},copy:function(n,e,t){const r=ri(t,this.from);return wr(t,{op:"add",path:this.path,value:Qe(r)}),{newDocument:t}},test:function(n,e,t){return{newDocument:t,test:Rn(n[e],this.value)}},_get:function(n,e,t){return this.value=n[e],{newDocument:t}}};var gp={add:function(n,e,t){return ei(e)?n.splice(e,0,this.value):n[e]=this.value,{newDocument:t,index:e}},remove:function(n,e,t){var r=n.splice(e,1);return{newDocument:t,removed:r[0]}},replace:function(n,e,t){var r=n[e];return n[e]=this.value,{newDocument:t,removed:r}},move:zt.move,copy:zt.copy,test:zt.test,_get:zt._get};function ri(n,e){if(e=="")return n;var t={op:"_get",path:e};return wr(n,t),t.value}function wr(n,e,t=!1,r=!0,s=!0,a=0){if(t&&(typeof t=="function"?t(e,0,n,e.path):ni(e,0)),e.path===""){let i={newDocument:n};if(e.op==="add")return i.newDocument=e.value,i;if(e.op==="replace")return i.newDocument=e.value,i.removed=n,i;if(e.op==="move"||e.op==="copy")return i.newDocument=ri(n,e.from),e.op==="move"&&(i.removed=n),i;if(e.op==="test"){if(i.test=Rn(n,e.value),i.test===!1)throw new te("Test operation failed","TEST_OPERATION_FAILED",a,e,n);return i.newDocument=n,i}else{if(e.op==="remove")return i.removed=n,i.newDocument=null,i;if(e.op==="_get")return e.value=n,i;if(t)throw new te("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",a,e,n);return i}}else{r||(n=Qe(n));const o=(e.path||"").split("/");let u=n,c=1,l=o.length,d,h,f;for(typeof t=="function"?f=t:f=ni;;){if(h=o[c],h&&h.indexOf("~")!=-1&&(h=pp(h)),s&&(h=="__proto__"||h=="prototype"&&c>0&&o[c-1]=="constructor"))throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(t&&d===void 0&&(u[h]===void 0?d=o.slice(0,c).join("/"):c==l-1&&(d=e.path),d!==void 0&&f(e,0,n,d)),c++,Array.isArray(u)){if(h==="-")h=u.length;else{if(t&&!ei(h))throw new te("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",a,e,n);ei(h)&&(h=~~h)}if(c>=l){if(t&&e.op==="add"&&h>u.length)throw new te("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",a,e,n);const p=gp[e.op].call(e,u,h,n);if(p.test===!1)throw new te("Test operation failed","TEST_OPERATION_FAILED",a,e,n);return p}}else if(c>=l){const p=zt[e.op].call(e,u,h,n);if(p.test===!1)throw new te("Test operation failed","TEST_OPERATION_FAILED",a,e,n);return p}if(u=u[h],t&&c<l&&(!u||typeof u!="object"))throw new te("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",a,e,n)}}}function xn(n,e,t,r=!0,s=!0){if(t&&!Array.isArray(e))throw new te("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");r||(n=Qe(n));const a=new Array(e.length);for(let i=0,o=e.length;i<o;i++)a[i]=wr(n,e[i],t,!0,s,i),n=a[i].newDocument;return a.newDocument=n,a}function ni(n,e,t,r){if(typeof n!="object"||n===null||Array.isArray(n))throw new te("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,n,t);if(zt[n.op]){if(typeof n.path!="string")throw new te("Operation `path` property is not a string","OPERATION_PATH_INVALID",e,n,t);if(n.path.indexOf("/")!==0&&n.path.length>0)throw new te('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",e,n,t);if((n.op==="move"||n.op==="copy")&&typeof n.from!="string")throw new te("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",e,n,t);if((n.op==="add"||n.op==="replace"||n.op==="test")&&n.value===void 0)throw new te("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",e,n,t);if((n.op==="add"||n.op==="replace"||n.op==="test")&&ti(n.value))throw new te("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",e,n,t);if(t){if(n.op=="add"){var s=n.path.split("/").length,a=r.split("/").length;if(s!==a+1&&s!==a)throw new te("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",e,n,t)}else if(n.op==="replace"||n.op==="remove"||n.op==="_get"){if(n.path!==r)throw new te("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",e,n,t)}else if(n.op==="move"||n.op==="copy"){var i={op:"_get",path:n.from,value:void 0},o=_p([i],t);if(o&&o.name==="OPERATION_PATH_UNRESOLVABLE")throw new te("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",e,n,t)}}}else throw new te("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",e,n,t)}function _p(n,e,t){try{if(!Array.isArray(n))throw new te("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)xn(Qe(e),Qe(n),t||!0);else{t=t||ni;for(var r=0;r<n.length;r++)t(n[r],r,e,void 0)}}catch(s){if(s instanceof te)return s;throw s}}function Rn(n,e){if(n===e)return!0;if(n&&e&&typeof n=="object"&&typeof e=="object"){var t=Array.isArray(n),r=Array.isArray(e),s,a,i;if(t&&r){if(a=n.length,a!=e.length)return!1;for(s=a;s--!==0;)if(!Rn(n[s],e[s]))return!1;return!0}if(t!=r)return!1;var o=Object.keys(n);if(a=o.length,a!==Object.keys(e).length)return!1;for(s=a;s--!==0;)if(!e.hasOwnProperty(o[s]))return!1;for(s=a;s--!==0;)if(i=o[s],!Rn(n[i],e[i]))return!1;return!0}return n!==n&&e!==e}/*!
|
|
46
|
+
* https://github.com/Starcounter-Jack/JSON-Patch
|
|
47
|
+
* (c) 2013-2021 Joachim Wester
|
|
48
|
+
* MIT license
|
|
49
|
+
*/function ld(n,e,t,r,s){if(e!==n){typeof e.toJSON=="function"&&(e=e.toJSON());for(var a=Ya(e),i=Ya(n),o=!1,u=i.length-1;u>=0;u--){var c=i[u],l=n[c];if(Qa(e,c)&&!(e[c]===void 0&&l!==void 0&&Array.isArray(e)===!1)){var d=e[c];typeof l=="object"&&l!=null&&typeof d=="object"&&d!=null&&Array.isArray(l)===Array.isArray(d)?ld(l,d,t,r+"/"+jt(c),s):l!==d&&(s&&t.push({op:"test",path:r+"/"+jt(c),value:Qe(l)}),t.push({op:"replace",path:r+"/"+jt(c),value:Qe(d)}))}else Array.isArray(n)===Array.isArray(e)?(s&&t.push({op:"test",path:r+"/"+jt(c),value:Qe(l)}),t.push({op:"remove",path:r+"/"+jt(c)}),o=!0):(s&&t.push({op:"test",path:r,value:n}),t.push({op:"replace",path:r,value:e}))}if(!(!o&&a.length==i.length))for(var u=0;u<a.length;u++){var c=a[u];!Qa(n,c)&&e[c]!==void 0&&t.push({op:"add",path:r+"/"+jt(c),value:Qe(e[c])})}}}function yp(n,e,t=!1){var r=[];return ld(n,e,r,"",t),r}const bp=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;function wp(n){return typeof n=="string"&&bp.test(n)}function vp(n){if(!wp(n))throw TypeError("Invalid UUID");var e,t=new Uint8Array(16);return t[0]=(e=parseInt(n.slice(0,8),16))>>>24,t[1]=e>>>16&255,t[2]=e>>>8&255,t[3]=e&255,t[4]=(e=parseInt(n.slice(9,13),16))>>>8,t[5]=e&255,t[6]=(e=parseInt(n.slice(14,18),16))>>>8,t[7]=e&255,t[8]=(e=parseInt(n.slice(19,23),16))>>>8,t[9]=e&255,t[10]=(e=parseInt(n.slice(24,36),16))/1099511627776&255,t[11]=e/4294967296&255,t[12]=e>>>24&255,t[13]=e>>>16&255,t[14]=e>>>8&255,t[15]=e&255,t}var he=[];for(var xs=0;xs<256;++xs)he.push((xs+256).toString(16).slice(1));function dd(n,e=0){return(he[n[e+0]]+he[n[e+1]]+he[n[e+2]]+he[n[e+3]]+"-"+he[n[e+4]]+he[n[e+5]]+"-"+he[n[e+6]]+he[n[e+7]]+"-"+he[n[e+8]]+he[n[e+9]]+"-"+he[n[e+10]]+he[n[e+11]]+he[n[e+12]]+he[n[e+13]]+he[n[e+14]]+he[n[e+15]]).toLowerCase()}var Kr,Ep=new Uint8Array(16);function Sp(){if(!Kr&&(Kr=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!Kr))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Kr(Ep)}function Op(n){n=unescape(encodeURIComponent(n));for(var e=[],t=0;t<n.length;++t)e.push(n.charCodeAt(t));return e}var Tp="6ba7b810-9dad-11d1-80b4-00c04fd430c8",Ap="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function Pp(n,e,t){function r(s,a,i,o){var u;if(typeof s=="string"&&(s=Op(s)),typeof a=="string"&&(a=vp(a)),((u=a)===null||u===void 0?void 0:u.length)!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");var c=new Uint8Array(16+s.length);if(c.set(a),c.set(s,a.length),c=t(c),c[6]=c[6]&15|e,c[8]=c[8]&63|128,i){o=o||0;for(var l=0;l<16;++l)i[o+l]=c[l];return i}return dd(c)}try{r.name=n}catch{}return r.DNS=Tp,r.URL=Ap,r}var Ip=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);const Wo={randomUUID:Ip};function Dt(n,e,t){if(Wo.randomUUID&&!n)return Wo.randomUUID();n=n||{};var r=n.random||(n.rng||Sp)();return r[6]=r[6]&15|64,r[8]=r[8]&63|128,dd(r)}function xp(n,e,t,r){switch(n){case 0:return e&t^~e&r;case 1:return e^t^r;case 2:return e&t^e&r^t&r;case 3:return e^t^r}}function Rs(n,e){return n<<e|n>>>32-e}function Rp(n){var e=[1518500249,1859775393,2400959708,3395469782],t=[1732584193,4023233417,2562383102,271733878,3285377520];if(typeof n=="string"){var r=unescape(encodeURIComponent(n));n=[];for(var s=0;s<r.length;++s)n.push(r.charCodeAt(s))}else Array.isArray(n)||(n=Array.prototype.slice.call(n));n.push(128);for(var a=n.length/4+2,i=Math.ceil(a/16),o=new Array(i),u=0;u<i;++u){for(var c=new Uint32Array(16),l=0;l<16;++l)c[l]=n[u*64+l*4]<<24|n[u*64+l*4+1]<<16|n[u*64+l*4+2]<<8|n[u*64+l*4+3];o[u]=c}o[i-1][14]=(n.length-1)*8/Math.pow(2,32),o[i-1][14]=Math.floor(o[i-1][14]),o[i-1][15]=(n.length-1)*8&4294967295;for(var d=0;d<i;++d){for(var h=new Uint32Array(80),f=0;f<16;++f)h[f]=o[d][f];for(var p=16;p<80;++p)h[p]=Rs(h[p-3]^h[p-8]^h[p-14]^h[p-16],1);for(var m=t[0],g=t[1],_=t[2],y=t[3],b=t[4],v=0;v<80;++v){var E=Math.floor(v/20),I=Rs(m,5)+xp(E,g,_,y)+b+e[E]+h[v]>>>0;b=y,y=_,_=Rs(g,30)>>>0,g=m,m=I}t[0]=t[0]+m>>>0,t[1]=t[1]+g>>>0,t[2]=t[2]+_>>>0,t[3]=t[3]+y>>>0,t[4]=t[4]+b>>>0}return[t[0]>>24&255,t[0]>>16&255,t[0]>>8&255,t[0]&255,t[1]>>24&255,t[1]>>16&255,t[1]>>8&255,t[1]&255,t[2]>>24&255,t[2]>>16&255,t[2]>>8&255,t[2]&255,t[3]>>24&255,t[3]>>16&255,t[3]>>8&255,t[3]&255,t[4]>>24&255,t[4]>>16&255,t[4]>>8&255,t[4]&255]}var Zo=Pp("v5",80,Rp);const kp="gen_ai.operation.name",Cp="gen_ai.system",Ko="gen_ai.request.model",$p="gen_ai.response.model",Vo="gen_ai.usage.input_tokens",Xo="gen_ai.usage.output_tokens",Qo="gen_ai.usage.total_tokens",Np="gen_ai.request.max_tokens",jp="gen_ai.request.temperature",Lp="gen_ai.request.top_p",Mp="gen_ai.request.frequency_penalty",Up="gen_ai.request.presence_penalty",Dp="gen_ai.response.finish_reasons",Fp="gen_ai.prompt",Bp="gen_ai.completion",zp="gen_ai.request.extra_query",qp="gen_ai.request.extra_body",Hp="gen_ai.serialized.name",Gp="gen_ai.serialized.signature",Jp="gen_ai.serialized.doc",Wp="gen_ai.response.id",Zp="gen_ai.response.service_tier",Kp="gen_ai.response.system_fingerprint",Vp="gen_ai.usage.input_token_details",Xp="gen_ai.usage.output_token_details",Qp="langsmith.trace.session_id",Yp="langsmith.trace.session_name",em="langsmith.span.kind",tm="langsmith.trace.name",rm="langsmith.metadata",Yo="langsmith.span.tags",nm="langsmith.request.streaming",sm="langsmith.request.headers",am=(...n)=>fetch(...n),hd=Symbol.for("ls:fetch_implementation"),im=()=>{const n=globalThis[hd];return n?typeof n=="function"&&"Headers"in n&&"Request"in n&&"Response"in n:!1},om=n=>async(...e)=>{if(n||Ae("DEBUG")==="true"){const[r,s]=e;console.log(`→ ${s?.method||"GET"} ${r}`)}const t=await(globalThis[hd]??am)(...e);return(n||Ae("DEBUG")==="true")&&console.log(`← ${t.status} ${t.statusText} ${t.url}`),t},fd=()=>Ae("PROJECT")??Ye("LANGCHAIN_SESSION")??"default",pd="0.3.73";var si={};let Ke;const um=()=>typeof window<"u"&&typeof window.document<"u",cm=()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope",lm=()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),md=()=>typeof Deno<"u",dm=()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!md(),gd=()=>Ke||(typeof Bun<"u"?Ke="bun":um()?Ke="browser":dm()?Ke="node":cm()?Ke="webworker":lm()?Ke="jsdom":md()?Ke="deno":Ke="other",Ke);let ks;function _d(){if(ks===void 0){const n=gd(),e=fm();ks={library:"langsmith",runtime:n,sdk:"langsmith-js",sdk_version:pd,...e}}return ks}function yd(){const n=hm(),e={},t=["LANGCHAIN_API_KEY","LANGCHAIN_ENDPOINT","LANGCHAIN_TRACING_V2","LANGCHAIN_PROJECT","LANGCHAIN_SESSION","LANGSMITH_API_KEY","LANGSMITH_ENDPOINT","LANGSMITH_TRACING_V2","LANGSMITH_PROJECT","LANGSMITH_SESSION"];for(const[r,s]of Object.entries(n))typeof s=="string"&&!t.includes(r)&&!r.toLowerCase().includes("key")&&!r.toLowerCase().includes("secret")&&!r.toLowerCase().includes("token")&&(r==="LANGCHAIN_REVISION_ID"?e.revision_id=s:e[r]=s);return e}function hm(){const n={};try{if(typeof process<"u"&&si)for(const[e,t]of Object.entries(si))(e.startsWith("LANGCHAIN_")||e.startsWith("LANGSMITH_"))&&t!=null&&((e.toLowerCase().includes("key")||e.toLowerCase().includes("secret")||e.toLowerCase().includes("token"))&&typeof t=="string"?n[e]=t.slice(0,2)+"*".repeat(t.length-4)+t.slice(-2):n[e]=t)}catch{}return n}function Ye(n){try{return typeof process<"u"?si?.[n]:void 0}catch{return}}function Ae(n){return Ye(`LANGSMITH_${n}`)||Ye(`LANGCHAIN_${n}`)}let Cs;function fm(){if(Cs!==void 0)return Cs;const n=["VERCEL_GIT_COMMIT_SHA","NEXT_PUBLIC_VERCEL_GIT_COMMIT_SHA","COMMIT_REF","RENDER_GIT_COMMIT","CI_COMMIT_SHA","CIRCLE_SHA1","CF_PAGES_COMMIT_SHA","REACT_APP_GIT_SHA","SOURCE_VERSION","GITHUB_SHA","TRAVIS_COMMIT","GIT_COMMIT","BUILD_VCS_NUMBER","bamboo_planRepository_revision","Build.SourceVersion","BITBUCKET_COMMIT","DRONE_COMMIT_SHA","SEMAPHORE_GIT_SHA","BUILDKITE_COMMIT"],e={};for(const t of n){const r=Ye(t);r!==void 0&&(e[t]=r)}return Cs=e,e}function bd(){return Ye("OTEL_ENABLED")==="true"||Ae("OTEL_ENABLED")==="true"}class pm{constructor(){Object.defineProperty(this,"hasWarned",{enumerable:!0,configurable:!0,writable:!0,value:!1})}startActiveSpan(e,...t){!this.hasWarned&&bd()&&(console.warn('You have enabled OTEL export via the `OTEL_ENABLED` or `LANGSMITH_OTEL_ENABLED` environment variable, but have not initialized the required OTEL instances. Please add:\n```\nimport { initializeOTEL } from "langsmith/experimental/otel/setup";\ninitializeOTEL();\n```\nat the beginning of your code.'),this.hasWarned=!0);let r;if(t.length===1&&typeof t[0]=="function"?r=t[0]:t.length===2&&typeof t[1]=="function"?r=t[1]:t.length===3&&typeof t[2]=="function"&&(r=t[2]),typeof r=="function")return r()}}class mm{constructor(){Object.defineProperty(this,"mockTracer",{enumerable:!0,configurable:!0,writable:!0,value:new pm})}getTracer(e,t){return this.mockTracer}getActiveSpan(){}setSpan(e,t){return e}getSpan(e){}setSpanContext(e,t){return e}getTracerProvider(){}setGlobalTracerProvider(e){return!1}}class gm{active(){return{}}with(e,t){return t()}}const $s=Symbol.for("ls:otel_trace"),Ns=Symbol.for("ls:otel_context"),eu=Symbol.for("ls:otel_get_default_otlp_tracer_provider"),_m=new mm,ym=new gm;class bm{getTraceInstance(){return globalThis[$s]??_m}getContextInstance(){return globalThis[Ns]??ym}initializeGlobalInstances(e){globalThis[$s]===void 0&&(globalThis[$s]=e.trace),globalThis[Ns]===void 0&&(globalThis[Ns]=e.context)}setDefaultOTLPTracerComponents(e){globalThis[eu]=e}getDefaultOTLPTracerComponents(){return globalThis[eu]??void 0}}const Di=new bm;function wd(){return Di.getTraceInstance()}function wm(){return Di.getContextInstance()}function vm(){return Di.getDefaultOTLPTracerComponents()}const Em={llm:"chat",tool:"execute_tool",retriever:"embeddings",embedding:"embeddings",prompt:"chat"};function Sm(n){return Em[n]||n}class Om{constructor(){Object.defineProperty(this,"spans",{enumerable:!0,configurable:!0,writable:!0,value:new Map})}exportBatch(e,t){for(const r of e)try{if(!r.run)continue;if(r.operation==="post"){const s=this.createSpanForRun(r,r.run,t.get(r.id));s&&!r.run.end_time&&this.spans.set(r.id,s)}else this.updateSpanForRun(r,r.run)}catch(s){console.error(`Error processing operation ${r.id}:`,s)}}createSpanForRun(e,t,r){const s=r&&wd().getSpan(r);if(s)try{return this.finishSpanSetup(s,t,e)}catch(a){console.error(`Failed to create span for run ${e.id}:`,a);return}}finishSpanSetup(e,t,r){return this.setSpanAttributes(e,t,r),t.error?(e.setStatus({code:2}),e.recordException(new Error(t.error))):e.setStatus({code:1}),t.end_time&&e.end(new Date(t.end_time)),e}updateSpanForRun(e,t){try{const r=this.spans.get(e.id);if(!r){console.debug(`No span found for run ${e.id} during update`);return}this.setSpanAttributes(r,t,e),t.error?(r.setStatus({code:2}),r.recordException(new Error(t.error))):r.setStatus({code:1});const s=t.end_time;s&&(r.end(new Date(s)),this.spans.delete(e.id))}catch(r){console.error(`Failed to update span for run ${e.id}:`,r)}}extractModelName(e){if(e.extra?.metadata){const t=e.extra.metadata;if(t.ls_model_name)return t.ls_model_name;if(t.invocation_params){const r=t.invocation_params;if(r.model)return r.model;if(r.model_name)return r.model_name}}}setSpanAttributes(e,t,r){if("run_type"in t&&t.run_type){e.setAttribute(em,t.run_type);const o=Sm(t.run_type||"chain");e.setAttribute(kp,o)}"name"in t&&t.name&&e.setAttribute(tm,t.name),"session_id"in t&&t.session_id&&e.setAttribute(Qp,t.session_id),"session_name"in t&&t.session_name&&e.setAttribute(Yp,t.session_name),this.setGenAiSystem(e,t);const s=this.extractModelName(t);s&&e.setAttribute(Ko,s),"prompt_tokens"in t&&typeof t.prompt_tokens=="number"&&e.setAttribute(Vo,t.prompt_tokens),"completion_tokens"in t&&typeof t.completion_tokens=="number"&&e.setAttribute(Xo,t.completion_tokens),"total_tokens"in t&&typeof t.total_tokens=="number"&&e.setAttribute(Qo,t.total_tokens),this.setInvocationParameters(e,t);const a=t.extra?.metadata||{};for(const[o,u]of Object.entries(a))u!=null&&e.setAttribute(`${rm}.${o}`,String(u));const i=t.tags;if(i&&Array.isArray(i)?e.setAttribute(Yo,i.join(", ")):i&&e.setAttribute(Yo,String(i)),"serialized"in t&&typeof t.serialized=="object"){const o=t.serialized;o.name&&e.setAttribute(Hp,String(o.name)),o.signature&&e.setAttribute(Gp,String(o.signature)),o.doc&&e.setAttribute(Jp,String(o.doc))}this.setIOAttributes(e,r)}setGenAiSystem(e,t){let r="langchain";const s=this.extractModelName(t);if(s){const a=s.toLowerCase();a.includes("anthropic")||a.startsWith("claude")?r="anthropic":a.includes("bedrock")?r="aws.bedrock":a.includes("azure")&&a.includes("openai")?r="az.ai.openai":a.includes("azure")&&a.includes("inference")?r="az.ai.inference":a.includes("cohere")?r="cohere":a.includes("deepseek")?r="deepseek":a.includes("gemini")?r="gemini":a.includes("groq")?r="groq":a.includes("watson")||a.includes("ibm")?r="ibm.watsonx.ai":a.includes("mistral")?r="mistral_ai":a.includes("gpt")||a.includes("openai")?r="openai":a.includes("perplexity")||a.includes("sonar")?r="perplexity":a.includes("vertex")?r="vertex_ai":(a.includes("xai")||a.includes("grok"))&&(r="xai")}e.setAttribute(Cp,r)}setInvocationParameters(e,t){if(!t.extra?.metadata?.invocation_params)return;const r=t.extra.metadata.invocation_params;r.max_tokens!==void 0&&e.setAttribute(Np,r.max_tokens),r.temperature!==void 0&&e.setAttribute(jp,r.temperature),r.top_p!==void 0&&e.setAttribute(Lp,r.top_p),r.frequency_penalty!==void 0&&e.setAttribute(Mp,r.frequency_penalty),r.presence_penalty!==void 0&&e.setAttribute(Up,r.presence_penalty)}setIOAttributes(e,t){if(t.run.inputs)try{const r=t.run.inputs;typeof r=="object"&&r!==null&&(r.model&&Array.isArray(r.messages)&&e.setAttribute(Ko,r.model),r.stream!==void 0&&e.setAttribute(nm,r.stream),r.extra_headers&&e.setAttribute(sm,JSON.stringify(r.extra_headers)),r.extra_query&&e.setAttribute(zp,JSON.stringify(r.extra_query)),r.extra_body&&e.setAttribute(qp,JSON.stringify(r.extra_body))),e.setAttribute(Fp,JSON.stringify(r))}catch(r){console.debug(`Failed to process inputs for run ${t.id}`,r)}if(t.run.outputs)try{const r=t.run.outputs,s=this.getUnifiedRunTokens(r);if(s&&(e.setAttribute(Vo,s[0]),e.setAttribute(Xo,s[1]),e.setAttribute(Qo,s[0]+s[1])),r&&typeof r=="object"){if(r.model&&e.setAttribute($p,String(r.model)),r.id&&e.setAttribute(Wp,r.id),r.choices&&Array.isArray(r.choices)){const a=r.choices.map(i=>i.finish_reason).filter(i=>i).map(String);a.length>0&&e.setAttribute(Dp,a.join(", "))}if(r.service_tier&&e.setAttribute(Zp,r.service_tier),r.system_fingerprint&&e.setAttribute(Kp,r.system_fingerprint),r.usage_metadata&&typeof r.usage_metadata=="object"){const a=r.usage_metadata;a.input_token_details&&e.setAttribute(Vp,JSON.stringify(a.input_token_details)),a.output_token_details&&e.setAttribute(Xp,JSON.stringify(a.output_token_details))}}e.setAttribute(Bp,JSON.stringify(r))}catch(r){console.debug(`Failed to process outputs for run ${t.id}`,r)}}getUnifiedRunTokens(e){if(!e)return null;let t=this.extractUnifiedRunTokens(e.usage_metadata);if(t)return t;const r=Object.keys(e);for(const i of r){const o=e[i];if(!(!o||typeof o!="object")&&(t=this.extractUnifiedRunTokens(o.usage_metadata),t||o.lc===1&&o.kwargs&&typeof o.kwargs=="object"&&(t=this.extractUnifiedRunTokens(o.kwargs.usage_metadata),t)))return t}const s=e.generations||[];if(!Array.isArray(s))return null;const a=Array.isArray(s[0])?s.flat():s;for(const i of a)if(typeof i=="object"&&i.message&&typeof i.message=="object"&&i.message.kwargs&&typeof i.message.kwargs=="object"&&(t=this.extractUnifiedRunTokens(i.message.kwargs.usage_metadata),t))return t;return null}extractUnifiedRunTokens(e){return!e||typeof e!="object"||typeof e.input_tokens!="number"||typeof e.output_tokens!="number"?null:[e.input_tokens,e.output_tokens]}}var Vr={},js={exports:{}},tu;function Tm(){return tu||(tu=1,(function(n){var e=Object.prototype.hasOwnProperty,t="~";function r(){}Object.create&&(r.prototype=Object.create(null),new r().__proto__||(t=!1));function s(u,c,l){this.fn=u,this.context=c,this.once=l||!1}function a(u,c,l,d,h){if(typeof l!="function")throw new TypeError("The listener must be a function");var f=new s(l,d||u,h),p=t?t+c:c;return u._events[p]?u._events[p].fn?u._events[p]=[u._events[p],f]:u._events[p].push(f):(u._events[p]=f,u._eventsCount++),u}function i(u,c){--u._eventsCount===0?u._events=new r:delete u._events[c]}function o(){this._events=new r,this._eventsCount=0}o.prototype.eventNames=function(){var c=[],l,d;if(this._eventsCount===0)return c;for(d in l=this._events)e.call(l,d)&&c.push(t?d.slice(1):d);return Object.getOwnPropertySymbols?c.concat(Object.getOwnPropertySymbols(l)):c},o.prototype.listeners=function(c){var l=t?t+c:c,d=this._events[l];if(!d)return[];if(d.fn)return[d.fn];for(var h=0,f=d.length,p=new Array(f);h<f;h++)p[h]=d[h].fn;return p},o.prototype.listenerCount=function(c){var l=t?t+c:c,d=this._events[l];return d?d.fn?1:d.length:0},o.prototype.emit=function(c,l,d,h,f,p){var m=t?t+c:c;if(!this._events[m])return!1;var g=this._events[m],_=arguments.length,y,b;if(g.fn){switch(g.once&&this.removeListener(c,g.fn,void 0,!0),_){case 1:return g.fn.call(g.context),!0;case 2:return g.fn.call(g.context,l),!0;case 3:return g.fn.call(g.context,l,d),!0;case 4:return g.fn.call(g.context,l,d,h),!0;case 5:return g.fn.call(g.context,l,d,h,f),!0;case 6:return g.fn.call(g.context,l,d,h,f,p),!0}for(b=1,y=new Array(_-1);b<_;b++)y[b-1]=arguments[b];g.fn.apply(g.context,y)}else{var v=g.length,E;for(b=0;b<v;b++)switch(g[b].once&&this.removeListener(c,g[b].fn,void 0,!0),_){case 1:g[b].fn.call(g[b].context);break;case 2:g[b].fn.call(g[b].context,l);break;case 3:g[b].fn.call(g[b].context,l,d);break;case 4:g[b].fn.call(g[b].context,l,d,h);break;default:if(!y)for(E=1,y=new Array(_-1);E<_;E++)y[E-1]=arguments[E];g[b].fn.apply(g[b].context,y)}}return!0},o.prototype.on=function(c,l,d){return a(this,c,l,d,!1)},o.prototype.once=function(c,l,d){return a(this,c,l,d,!0)},o.prototype.removeListener=function(c,l,d,h){var f=t?t+c:c;if(!this._events[f])return this;if(!l)return i(this,f),this;var p=this._events[f];if(p.fn)p.fn===l&&(!h||p.once)&&(!d||p.context===d)&&i(this,f);else{for(var m=0,g=[],_=p.length;m<_;m++)(p[m].fn!==l||h&&!p[m].once||d&&p[m].context!==d)&&g.push(p[m]);g.length?this._events[f]=g.length===1?g[0]:g:i(this,f)}return this},o.prototype.removeAllListeners=function(c){var l;return c?(l=t?t+c:c,this._events[l]&&i(this,l)):(this._events=new r,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=t,o.EventEmitter=o,n.exports=o})(js)),js.exports}var rr={exports:{}},Ls,ru;function Am(){return ru||(ru=1,Ls=(n,e)=>(e=e||(()=>{}),n.then(t=>new Promise(r=>{r(e())}).then(()=>t),t=>new Promise(r=>{r(e())}).then(()=>{throw t})))),Ls}var nu;function Pm(){if(nu)return rr.exports;nu=1;const n=Am();class e extends Error{constructor(s){super(s),this.name="TimeoutError"}}const t=(r,s,a)=>new Promise((i,o)=>{if(typeof s!="number"||s<0)throw new TypeError("Expected `milliseconds` to be a positive number");if(s===1/0){i(r);return}const u=setTimeout(()=>{if(typeof a=="function"){try{i(a())}catch(d){o(d)}return}const c=typeof a=="string"?a:`Promise timed out after ${s} milliseconds`,l=a instanceof Error?a:new e(c);typeof r.cancel=="function"&&r.cancel(),o(l)},s);n(r.then(i,o),()=>{clearTimeout(u)})});return rr.exports=t,rr.exports.default=t,rr.exports.TimeoutError=e,rr.exports}var Xr={},Qr={},su;function Im(){if(su)return Qr;su=1,Object.defineProperty(Qr,"__esModule",{value:!0});function n(e,t,r){let s=0,a=e.length;for(;a>0;){const i=a/2|0;let o=s+i;r(e[o],t)<=0?(s=++o,a-=i+1):a=i}return s}return Qr.default=n,Qr}var au;function xm(){if(au)return Xr;au=1,Object.defineProperty(Xr,"__esModule",{value:!0});const n=Im();class e{constructor(){this._queue=[]}enqueue(r,s){s=Object.assign({priority:0},s);const a={priority:s.priority,run:r};if(this.size&&this._queue[this.size-1].priority>=s.priority){this._queue.push(a);return}const i=n.default(this._queue,a,(o,u)=>u.priority-o.priority);this._queue.splice(i,0,a)}dequeue(){const r=this._queue.shift();return r?.run}filter(r){return this._queue.filter(s=>s.priority===r.priority).map(s=>s.run)}get size(){return this._queue.length}}return Xr.default=e,Xr}var iu;function Rm(){if(iu)return Vr;iu=1,Object.defineProperty(Vr,"__esModule",{value:!0});const n=Tm(),e=Pm(),t=xm(),r=()=>{},s=new e.TimeoutError;class a extends n{constructor(o){var u,c,l,d;if(super(),this._intervalCount=0,this._intervalEnd=0,this._pendingCount=0,this._resolveEmpty=r,this._resolveIdle=r,o=Object.assign({carryoverConcurrencyCount:!1,intervalCap:1/0,interval:0,concurrency:1/0,autoStart:!0,queueClass:t.default},o),!(typeof o.intervalCap=="number"&&o.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${(c=(u=o.intervalCap)===null||u===void 0?void 0:u.toString())!==null&&c!==void 0?c:""}\` (${typeof o.intervalCap})`);if(o.interval===void 0||!(Number.isFinite(o.interval)&&o.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${(d=(l=o.interval)===null||l===void 0?void 0:l.toString())!==null&&d!==void 0?d:""}\` (${typeof o.interval})`);this._carryoverConcurrencyCount=o.carryoverConcurrencyCount,this._isIntervalIgnored=o.intervalCap===1/0||o.interval===0,this._intervalCap=o.intervalCap,this._interval=o.interval,this._queue=new o.queueClass,this._queueClass=o.queueClass,this.concurrency=o.concurrency,this._timeout=o.timeout,this._throwOnTimeout=o.throwOnTimeout===!0,this._isPaused=o.autoStart===!1}get _doesIntervalAllowAnother(){return this._isIntervalIgnored||this._intervalCount<this._intervalCap}get _doesConcurrentAllowAnother(){return this._pendingCount<this._concurrency}_next(){this._pendingCount--,this._tryToStartAnother(),this.emit("next")}_resolvePromises(){this._resolveEmpty(),this._resolveEmpty=r,this._pendingCount===0&&(this._resolveIdle(),this._resolveIdle=r,this.emit("idle"))}_onResumeInterval(){this._onInterval(),this._initializeIntervalIfNeeded(),this._timeoutId=void 0}_isIntervalPaused(){const o=Date.now();if(this._intervalId===void 0){const u=this._intervalEnd-o;if(u<0)this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0;else return this._timeoutId===void 0&&(this._timeoutId=setTimeout(()=>{this._onResumeInterval()},u)),!0}return!1}_tryToStartAnother(){if(this._queue.size===0)return this._intervalId&&clearInterval(this._intervalId),this._intervalId=void 0,this._resolvePromises(),!1;if(!this._isPaused){const o=!this._isIntervalPaused();if(this._doesIntervalAllowAnother&&this._doesConcurrentAllowAnother){const u=this._queue.dequeue();return u?(this.emit("active"),u(),o&&this._initializeIntervalIfNeeded(),!0):!1}}return!1}_initializeIntervalIfNeeded(){this._isIntervalIgnored||this._intervalId!==void 0||(this._intervalId=setInterval(()=>{this._onInterval()},this._interval),this._intervalEnd=Date.now()+this._interval)}_onInterval(){this._intervalCount===0&&this._pendingCount===0&&this._intervalId&&(clearInterval(this._intervalId),this._intervalId=void 0),this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0,this._processQueue()}_processQueue(){for(;this._tryToStartAnother(););}get concurrency(){return this._concurrency}set concurrency(o){if(!(typeof o=="number"&&o>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${o}\` (${typeof o})`);this._concurrency=o,this._processQueue()}async add(o,u={}){return new Promise((c,l)=>{const d=async()=>{this._pendingCount++,this._intervalCount++;try{const h=this._timeout===void 0&&u.timeout===void 0?o():e.default(Promise.resolve(o()),u.timeout===void 0?this._timeout:u.timeout,()=>{(u.throwOnTimeout===void 0?this._throwOnTimeout:u.throwOnTimeout)&&l(s)});c(await h)}catch(h){l(h)}this._next()};this._queue.enqueue(d,u),this._tryToStartAnother(),this.emit("add")})}async addAll(o,u){return Promise.all(o.map(async c=>this.add(c,u)))}start(){return this._isPaused?(this._isPaused=!1,this._processQueue(),this):this}pause(){this._isPaused=!0}clear(){this._queue=new this._queueClass}async onEmpty(){if(this._queue.size!==0)return new Promise(o=>{const u=this._resolveEmpty;this._resolveEmpty=()=>{u(),o()}})}async onIdle(){if(!(this._pendingCount===0&&this._queue.size===0))return new Promise(o=>{const u=this._resolveIdle;this._resolveIdle=()=>{u(),o()}})}get size(){return this._queue.size}sizeBy(o){return this._queue.filter(o).length}get pending(){return this._pendingCount}get isPaused(){return this._isPaused}get timeout(){return this._timeout}set timeout(o){this._timeout=o}}return Vr.default=a,Vr}var km=Rm();const at=Rr(km),Cm=[429,500,502,503,504];let ou=class{constructor(e){Object.defineProperty(this,"maxConcurrency",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"maxRetries",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"queue",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onFailedResponseHook",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxConcurrency=e.maxConcurrency??1/0,this.maxRetries=e.maxRetries??6,"default"in at?this.queue=new at.default({concurrency:this.maxConcurrency}):this.queue=new at({concurrency:this.maxConcurrency}),this.onFailedResponseHook=e?.onFailedResponseHook}call(e,...t){const r=this.onFailedResponseHook;return this.queue.add(()=>In(()=>e(...t).catch(s=>{throw s instanceof Error?s:new Error(s)}),{async onFailedAttempt(s){if(s.message.startsWith("Cancel")||s.message.startsWith("TimeoutError")||s.name==="TimeoutError"||s.message.startsWith("AbortError")||s?.code==="ECONNABORTED")throw s;const a=s?.response;if(r&&await r(a))return;const i=a?.status??s?.status;if(i&&!Cm.includes(+i))throw s},retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0})}callWithOptions(e,t,...r){return e.signal?Promise.race([this.call(t,...r),new Promise((s,a)=>{e.signal?.addEventListener("abort",()=>{a(new Error("AbortError"))})})]):this.call(t,...r)}};function uu(n){return typeof n?._getType=="function"}function cu(n){const e={type:n._getType(),data:{content:n.content}};return n?.additional_kwargs&&Object.keys(n.additional_kwargs).length>0&&(e.data.additional_kwargs={...n.additional_kwargs}),e}const $m=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function D(n,e){if(!$m.test(n)){const t=e!==void 0?`Invalid UUID for ${e}: ${n}`:`Invalid UUID: ${n}`;throw new Error(t)}return n}const lu={};function vd(n){lu[n]||(console.warn(n),lu[n]=!0)}var Yr={exports:{}},Ms,du;function ts(){if(du)return Ms;du=1;const n="2.0.0",e=256,t=Number.MAX_SAFE_INTEGER||9007199254740991,r=16,s=e-6;return Ms={MAX_LENGTH:e,MAX_SAFE_COMPONENT_LENGTH:r,MAX_SAFE_BUILD_LENGTH:s,MAX_SAFE_INTEGER:t,RELEASE_TYPES:["major","premajor","minor","preminor","patch","prepatch","prerelease"],SEMVER_SPEC_VERSION:n,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2},Ms}var Us,hu;function rs(){if(hu)return Us;hu=1;var n={};return Us=typeof process=="object"&&n&&n.NODE_DEBUG&&/\bsemver\b/i.test(n.NODE_DEBUG)?(...t)=>console.error("SEMVER",...t):()=>{},Us}var fu;function Mr(){return fu||(fu=1,(function(n,e){const{MAX_SAFE_COMPONENT_LENGTH:t,MAX_SAFE_BUILD_LENGTH:r,MAX_LENGTH:s}=ts(),a=rs();e=n.exports={};const i=e.re=[],o=e.safeRe=[],u=e.src=[],c=e.safeSrc=[],l=e.t={};let d=0;const h="[a-zA-Z0-9-]",f=[["\\s",1],["\\d",s],[h,r]],p=g=>{for(const[_,y]of f)g=g.split(`${_}*`).join(`${_}{0,${y}}`).split(`${_}+`).join(`${_}{1,${y}}`);return g},m=(g,_,y)=>{const b=p(_),v=d++;a(g,v,_),l[g]=v,u[v]=_,c[v]=b,i[v]=new RegExp(_,y?"g":void 0),o[v]=new RegExp(b,y?"g":void 0)};m("NUMERICIDENTIFIER","0|[1-9]\\d*"),m("NUMERICIDENTIFIERLOOSE","\\d+"),m("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${h}*`),m("MAINVERSION",`(${u[l.NUMERICIDENTIFIER]})\\.(${u[l.NUMERICIDENTIFIER]})\\.(${u[l.NUMERICIDENTIFIER]})`),m("MAINVERSIONLOOSE",`(${u[l.NUMERICIDENTIFIERLOOSE]})\\.(${u[l.NUMERICIDENTIFIERLOOSE]})\\.(${u[l.NUMERICIDENTIFIERLOOSE]})`),m("PRERELEASEIDENTIFIER",`(?:${u[l.NONNUMERICIDENTIFIER]}|${u[l.NUMERICIDENTIFIER]})`),m("PRERELEASEIDENTIFIERLOOSE",`(?:${u[l.NONNUMERICIDENTIFIER]}|${u[l.NUMERICIDENTIFIERLOOSE]})`),m("PRERELEASE",`(?:-(${u[l.PRERELEASEIDENTIFIER]}(?:\\.${u[l.PRERELEASEIDENTIFIER]})*))`),m("PRERELEASELOOSE",`(?:-?(${u[l.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${u[l.PRERELEASEIDENTIFIERLOOSE]})*))`),m("BUILDIDENTIFIER",`${h}+`),m("BUILD",`(?:\\+(${u[l.BUILDIDENTIFIER]}(?:\\.${u[l.BUILDIDENTIFIER]})*))`),m("FULLPLAIN",`v?${u[l.MAINVERSION]}${u[l.PRERELEASE]}?${u[l.BUILD]}?`),m("FULL",`^${u[l.FULLPLAIN]}$`),m("LOOSEPLAIN",`[v=\\s]*${u[l.MAINVERSIONLOOSE]}${u[l.PRERELEASELOOSE]}?${u[l.BUILD]}?`),m("LOOSE",`^${u[l.LOOSEPLAIN]}$`),m("GTLT","((?:<|>)?=?)"),m("XRANGEIDENTIFIERLOOSE",`${u[l.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`),m("XRANGEIDENTIFIER",`${u[l.NUMERICIDENTIFIER]}|x|X|\\*`),m("XRANGEPLAIN",`[v=\\s]*(${u[l.XRANGEIDENTIFIER]})(?:\\.(${u[l.XRANGEIDENTIFIER]})(?:\\.(${u[l.XRANGEIDENTIFIER]})(?:${u[l.PRERELEASE]})?${u[l.BUILD]}?)?)?`),m("XRANGEPLAINLOOSE",`[v=\\s]*(${u[l.XRANGEIDENTIFIERLOOSE]})(?:\\.(${u[l.XRANGEIDENTIFIERLOOSE]})(?:\\.(${u[l.XRANGEIDENTIFIERLOOSE]})(?:${u[l.PRERELEASELOOSE]})?${u[l.BUILD]}?)?)?`),m("XRANGE",`^${u[l.GTLT]}\\s*${u[l.XRANGEPLAIN]}$`),m("XRANGELOOSE",`^${u[l.GTLT]}\\s*${u[l.XRANGEPLAINLOOSE]}$`),m("COERCEPLAIN",`(^|[^\\d])(\\d{1,${t}})(?:\\.(\\d{1,${t}}))?(?:\\.(\\d{1,${t}}))?`),m("COERCE",`${u[l.COERCEPLAIN]}(?:$|[^\\d])`),m("COERCEFULL",u[l.COERCEPLAIN]+`(?:${u[l.PRERELEASE]})?(?:${u[l.BUILD]})?(?:$|[^\\d])`),m("COERCERTL",u[l.COERCE],!0),m("COERCERTLFULL",u[l.COERCEFULL],!0),m("LONETILDE","(?:~>?)"),m("TILDETRIM",`(\\s*)${u[l.LONETILDE]}\\s+`,!0),e.tildeTrimReplace="$1~",m("TILDE",`^${u[l.LONETILDE]}${u[l.XRANGEPLAIN]}$`),m("TILDELOOSE",`^${u[l.LONETILDE]}${u[l.XRANGEPLAINLOOSE]}$`),m("LONECARET","(?:\\^)"),m("CARETTRIM",`(\\s*)${u[l.LONECARET]}\\s+`,!0),e.caretTrimReplace="$1^",m("CARET",`^${u[l.LONECARET]}${u[l.XRANGEPLAIN]}$`),m("CARETLOOSE",`^${u[l.LONECARET]}${u[l.XRANGEPLAINLOOSE]}$`),m("COMPARATORLOOSE",`^${u[l.GTLT]}\\s*(${u[l.LOOSEPLAIN]})$|^$`),m("COMPARATOR",`^${u[l.GTLT]}\\s*(${u[l.FULLPLAIN]})$|^$`),m("COMPARATORTRIM",`(\\s*)${u[l.GTLT]}\\s*(${u[l.LOOSEPLAIN]}|${u[l.XRANGEPLAIN]})`,!0),e.comparatorTrimReplace="$1$2$3",m("HYPHENRANGE",`^\\s*(${u[l.XRANGEPLAIN]})\\s+-\\s+(${u[l.XRANGEPLAIN]})\\s*$`),m("HYPHENRANGELOOSE",`^\\s*(${u[l.XRANGEPLAINLOOSE]})\\s+-\\s+(${u[l.XRANGEPLAINLOOSE]})\\s*$`),m("STAR","(<|>)?=?\\s*\\*"),m("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$"),m("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")})(Yr,Yr.exports)),Yr.exports}var Ds,pu;function Fi(){if(pu)return Ds;pu=1;const n=Object.freeze({loose:!0}),e=Object.freeze({});return Ds=r=>r?typeof r!="object"?n:r:e,Ds}var Fs,mu;function Ed(){if(mu)return Fs;mu=1;const n=/^[0-9]+$/,e=(r,s)=>{if(typeof r=="number"&&typeof s=="number")return r===s?0:r<s?-1:1;const a=n.test(r),i=n.test(s);return a&&i&&(r=+r,s=+s),r===s?0:a&&!i?-1:i&&!a?1:r<s?-1:1};return Fs={compareIdentifiers:e,rcompareIdentifiers:(r,s)=>e(s,r)},Fs}var Bs,gu;function Ee(){if(gu)return Bs;gu=1;const n=rs(),{MAX_LENGTH:e,MAX_SAFE_INTEGER:t}=ts(),{safeRe:r,t:s}=Mr(),a=Fi(),{compareIdentifiers:i}=Ed();class o{constructor(c,l){if(l=a(l),c instanceof o){if(c.loose===!!l.loose&&c.includePrerelease===!!l.includePrerelease)return c;c=c.version}else if(typeof c!="string")throw new TypeError(`Invalid version. Must be a string. Got type "${typeof c}".`);if(c.length>e)throw new TypeError(`version is longer than ${e} characters`);n("SemVer",c,l),this.options=l,this.loose=!!l.loose,this.includePrerelease=!!l.includePrerelease;const d=c.trim().match(l.loose?r[s.LOOSE]:r[s.FULL]);if(!d)throw new TypeError(`Invalid Version: ${c}`);if(this.raw=c,this.major=+d[1],this.minor=+d[2],this.patch=+d[3],this.major>t||this.major<0)throw new TypeError("Invalid major version");if(this.minor>t||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>t||this.patch<0)throw new TypeError("Invalid patch version");d[4]?this.prerelease=d[4].split(".").map(h=>{if(/^[0-9]+$/.test(h)){const f=+h;if(f>=0&&f<t)return f}return h}):this.prerelease=[],this.build=d[5]?d[5].split("."):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(".")}`),this.version}toString(){return this.version}compare(c){if(n("SemVer.compare",this.version,this.options,c),!(c instanceof o)){if(typeof c=="string"&&c===this.version)return 0;c=new o(c,this.options)}return c.version===this.version?0:this.compareMain(c)||this.comparePre(c)}compareMain(c){return c instanceof o||(c=new o(c,this.options)),this.major<c.major?-1:this.major>c.major?1:this.minor<c.minor?-1:this.minor>c.minor?1:this.patch<c.patch?-1:this.patch>c.patch?1:0}comparePre(c){if(c instanceof o||(c=new o(c,this.options)),this.prerelease.length&&!c.prerelease.length)return-1;if(!this.prerelease.length&&c.prerelease.length)return 1;if(!this.prerelease.length&&!c.prerelease.length)return 0;let l=0;do{const d=this.prerelease[l],h=c.prerelease[l];if(n("prerelease compare",l,d,h),d===void 0&&h===void 0)return 0;if(h===void 0)return 1;if(d===void 0)return-1;if(d===h)continue;return i(d,h)}while(++l)}compareBuild(c){c instanceof o||(c=new o(c,this.options));let l=0;do{const d=this.build[l],h=c.build[l];if(n("build compare",l,d,h),d===void 0&&h===void 0)return 0;if(h===void 0)return 1;if(d===void 0)return-1;if(d===h)continue;return i(d,h)}while(++l)}inc(c,l,d){if(c.startsWith("pre")){if(!l&&d===!1)throw new Error("invalid increment argument: identifier is empty");if(l){const h=`-${l}`.match(this.options.loose?r[s.PRERELEASELOOSE]:r[s.PRERELEASE]);if(!h||h[1]!==l)throw new Error(`invalid identifier: ${l}`)}}switch(c){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",l,d);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",l,d);break;case"prepatch":this.prerelease.length=0,this.inc("patch",l,d),this.inc("pre",l,d);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",l,d),this.inc("pre",l,d);break;case"release":if(this.prerelease.length===0)throw new Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case"patch":this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case"pre":{const h=Number(d)?1:0;if(this.prerelease.length===0)this.prerelease=[h];else{let f=this.prerelease.length;for(;--f>=0;)typeof this.prerelease[f]=="number"&&(this.prerelease[f]++,f=-2);if(f===-1){if(l===this.prerelease.join(".")&&d===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(h)}}if(l){let f=[l,h];d===!1&&(f=[l]),i(this.prerelease[0],l)===0?isNaN(this.prerelease[1])&&(this.prerelease=f):this.prerelease=f}break}default:throw new Error(`invalid increment argument: ${c}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}}return Bs=o,Bs}var zs,_u;function Kt(){if(_u)return zs;_u=1;const n=Ee();return zs=(t,r,s=!1)=>{if(t instanceof n)return t;try{return new n(t,r)}catch(a){if(!s)return null;throw a}},zs}var qs,yu;function Nm(){if(yu)return qs;yu=1;const n=Kt();return qs=(t,r)=>{const s=n(t,r);return s?s.version:null},qs}var Hs,bu;function jm(){if(bu)return Hs;bu=1;const n=Kt();return Hs=(t,r)=>{const s=n(t.trim().replace(/^[=v]+/,""),r);return s?s.version:null},Hs}var Gs,wu;function Lm(){if(wu)return Gs;wu=1;const n=Ee();return Gs=(t,r,s,a,i)=>{typeof s=="string"&&(i=a,a=s,s=void 0);try{return new n(t instanceof n?t.version:t,s).inc(r,a,i).version}catch{return null}},Gs}var Js,vu;function Mm(){if(vu)return Js;vu=1;const n=Kt();return Js=(t,r)=>{const s=n(t,null,!0),a=n(r,null,!0),i=s.compare(a);if(i===0)return null;const o=i>0,u=o?s:a,c=o?a:s,l=!!u.prerelease.length;if(!!c.prerelease.length&&!l){if(!c.patch&&!c.minor)return"major";if(c.compareMain(u)===0)return c.minor&&!c.patch?"minor":"patch"}const h=l?"pre":"";return s.major!==a.major?h+"major":s.minor!==a.minor?h+"minor":s.patch!==a.patch?h+"patch":"prerelease"},Js}var Ws,Eu;function Um(){if(Eu)return Ws;Eu=1;const n=Ee();return Ws=(t,r)=>new n(t,r).major,Ws}var Zs,Su;function Dm(){if(Su)return Zs;Su=1;const n=Ee();return Zs=(t,r)=>new n(t,r).minor,Zs}var Ks,Ou;function Fm(){if(Ou)return Ks;Ou=1;const n=Ee();return Ks=(t,r)=>new n(t,r).patch,Ks}var Vs,Tu;function Bm(){if(Tu)return Vs;Tu=1;const n=Kt();return Vs=(t,r)=>{const s=n(t,r);return s&&s.prerelease.length?s.prerelease:null},Vs}var Xs,Au;function Ge(){if(Au)return Xs;Au=1;const n=Ee();return Xs=(t,r,s)=>new n(t,s).compare(new n(r,s)),Xs}var Qs,Pu;function zm(){if(Pu)return Qs;Pu=1;const n=Ge();return Qs=(t,r,s)=>n(r,t,s),Qs}var Ys,Iu;function qm(){if(Iu)return Ys;Iu=1;const n=Ge();return Ys=(t,r)=>n(t,r,!0),Ys}var ea,xu;function Bi(){if(xu)return ea;xu=1;const n=Ee();return ea=(t,r,s)=>{const a=new n(t,s),i=new n(r,s);return a.compare(i)||a.compareBuild(i)},ea}var ta,Ru;function Hm(){if(Ru)return ta;Ru=1;const n=Bi();return ta=(t,r)=>t.sort((s,a)=>n(s,a,r)),ta}var ra,ku;function Gm(){if(ku)return ra;ku=1;const n=Bi();return ra=(t,r)=>t.sort((s,a)=>n(a,s,r)),ra}var na,Cu;function ns(){if(Cu)return na;Cu=1;const n=Ge();return na=(t,r,s)=>n(t,r,s)>0,na}var sa,$u;function zi(){if($u)return sa;$u=1;const n=Ge();return sa=(t,r,s)=>n(t,r,s)<0,sa}var aa,Nu;function Sd(){if(Nu)return aa;Nu=1;const n=Ge();return aa=(t,r,s)=>n(t,r,s)===0,aa}var ia,ju;function Od(){if(ju)return ia;ju=1;const n=Ge();return ia=(t,r,s)=>n(t,r,s)!==0,ia}var oa,Lu;function qi(){if(Lu)return oa;Lu=1;const n=Ge();return oa=(t,r,s)=>n(t,r,s)>=0,oa}var ua,Mu;function Hi(){if(Mu)return ua;Mu=1;const n=Ge();return ua=(t,r,s)=>n(t,r,s)<=0,ua}var ca,Uu;function Td(){if(Uu)return ca;Uu=1;const n=Sd(),e=Od(),t=ns(),r=qi(),s=zi(),a=Hi();return ca=(o,u,c,l)=>{switch(u){case"===":return typeof o=="object"&&(o=o.version),typeof c=="object"&&(c=c.version),o===c;case"!==":return typeof o=="object"&&(o=o.version),typeof c=="object"&&(c=c.version),o!==c;case"":case"=":case"==":return n(o,c,l);case"!=":return e(o,c,l);case">":return t(o,c,l);case">=":return r(o,c,l);case"<":return s(o,c,l);case"<=":return a(o,c,l);default:throw new TypeError(`Invalid operator: ${u}`)}},ca}var la,Du;function Jm(){if(Du)return la;Du=1;const n=Ee(),e=Kt(),{safeRe:t,t:r}=Mr();return la=(a,i)=>{if(a instanceof n)return a;if(typeof a=="number"&&(a=String(a)),typeof a!="string")return null;i=i||{};let o=null;if(!i.rtl)o=a.match(i.includePrerelease?t[r.COERCEFULL]:t[r.COERCE]);else{const f=i.includePrerelease?t[r.COERCERTLFULL]:t[r.COERCERTL];let p;for(;(p=f.exec(a))&&(!o||o.index+o[0].length!==a.length);)(!o||p.index+p[0].length!==o.index+o[0].length)&&(o=p),f.lastIndex=p.index+p[1].length+p[2].length;f.lastIndex=-1}if(o===null)return null;const u=o[2],c=o[3]||"0",l=o[4]||"0",d=i.includePrerelease&&o[5]?`-${o[5]}`:"",h=i.includePrerelease&&o[6]?`+${o[6]}`:"";return e(`${u}.${c}.${l}${d}${h}`,i)},la}var da,Fu;function Wm(){if(Fu)return da;Fu=1;class n{constructor(){this.max=1e3,this.map=new Map}get(t){const r=this.map.get(t);if(r!==void 0)return this.map.delete(t),this.map.set(t,r),r}delete(t){return this.map.delete(t)}set(t,r){if(!this.delete(t)&&r!==void 0){if(this.map.size>=this.max){const a=this.map.keys().next().value;this.delete(a)}this.map.set(t,r)}return this}}return da=n,da}var ha,Bu;function Je(){if(Bu)return ha;Bu=1;const n=/\s+/g;class e{constructor(T,N){if(N=s(N),T instanceof e)return T.loose===!!N.loose&&T.includePrerelease===!!N.includePrerelease?T:new e(T.raw,N);if(T instanceof a)return this.raw=T.value,this.set=[[T]],this.formatted=void 0,this;if(this.options=N,this.loose=!!N.loose,this.includePrerelease=!!N.includePrerelease,this.raw=T.trim().replace(n," "),this.set=this.raw.split("||").map(k=>this.parseRange(k.trim())).filter(k=>k.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){const k=this.set[0];if(this.set=this.set.filter(j=>!m(j[0])),this.set.length===0)this.set=[k];else if(this.set.length>1){for(const j of this.set)if(j.length===1&&g(j[0])){this.set=[j];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let T=0;T<this.set.length;T++){T>0&&(this.formatted+="||");const N=this.set[T];for(let k=0;k<N.length;k++)k>0&&(this.formatted+=" "),this.formatted+=N[k].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(T){const k=((this.options.includePrerelease&&f)|(this.options.loose&&p))+":"+T,j=r.get(k);if(j)return j;const C=this.options.loose,F=C?u[c.HYPHENRANGELOOSE]:u[c.HYPHENRANGE];T=T.replace(F,Le(this.options.includePrerelease)),i("hyphen replace",T),T=T.replace(u[c.COMPARATORTRIM],l),i("comparator trim",T),T=T.replace(u[c.TILDETRIM],d),i("tilde trim",T),T=T.replace(u[c.CARETTRIM],h),i("caret trim",T);let W=T.split(" ").map(ee=>y(ee,this.options)).join(" ").split(/\s+/).map(ee=>V(ee,this.options));C&&(W=W.filter(ee=>(i("loose invalid filter",ee,this.options),!!ee.match(u[c.COMPARATORLOOSE])))),i("range list",W);const z=new Map,Y=W.map(ee=>new a(ee,this.options));for(const ee of Y){if(m(ee))return[ee];z.set(ee.value,ee)}z.size>1&&z.has("")&&z.delete("");const _e=[...z.values()];return r.set(k,_e),_e}intersects(T,N){if(!(T instanceof e))throw new TypeError("a Range is required");return this.set.some(k=>_(k,N)&&T.set.some(j=>_(j,N)&&k.every(C=>j.every(F=>C.intersects(F,N)))))}test(T){if(!T)return!1;if(typeof T=="string")try{T=new o(T,this.options)}catch{return!1}for(let N=0;N<this.set.length;N++)if(yt(this.set[N],T,this.options))return!0;return!1}}ha=e;const t=Wm(),r=new t,s=Fi(),a=ss(),i=rs(),o=Ee(),{safeRe:u,t:c,comparatorTrimReplace:l,tildeTrimReplace:d,caretTrimReplace:h}=Mr(),{FLAG_INCLUDE_PRERELEASE:f,FLAG_LOOSE:p}=ts(),m=P=>P.value==="<0.0.0-0",g=P=>P.value==="",_=(P,T)=>{let N=!0;const k=P.slice();let j=k.pop();for(;N&&k.length;)N=k.every(C=>j.intersects(C,T)),j=k.pop();return N},y=(P,T)=>(P=P.replace(u[c.BUILD],""),i("comp",P,T),P=I(P,T),i("caret",P),P=v(P,T),i("tildes",P),P=O(P,T),i("xrange",P),P=G(P,T),i("stars",P),P),b=P=>!P||P.toLowerCase()==="x"||P==="*",v=(P,T)=>P.trim().split(/\s+/).map(N=>E(N,T)).join(" "),E=(P,T)=>{const N=T.loose?u[c.TILDELOOSE]:u[c.TILDE];return P.replace(N,(k,j,C,F,W)=>{i("tilde",P,k,j,C,F,W);let z;return b(j)?z="":b(C)?z=`>=${j}.0.0 <${+j+1}.0.0-0`:b(F)?z=`>=${j}.${C}.0 <${j}.${+C+1}.0-0`:W?(i("replaceTilde pr",W),z=`>=${j}.${C}.${F}-${W} <${j}.${+C+1}.0-0`):z=`>=${j}.${C}.${F} <${j}.${+C+1}.0-0`,i("tilde return",z),z})},I=(P,T)=>P.trim().split(/\s+/).map(N=>x(N,T)).join(" "),x=(P,T)=>{i("caret",P,T);const N=T.loose?u[c.CARETLOOSE]:u[c.CARET],k=T.includePrerelease?"-0":"";return P.replace(N,(j,C,F,W,z)=>{i("caret",P,j,C,F,W,z);let Y;return b(C)?Y="":b(F)?Y=`>=${C}.0.0${k} <${+C+1}.0.0-0`:b(W)?C==="0"?Y=`>=${C}.${F}.0${k} <${C}.${+F+1}.0-0`:Y=`>=${C}.${F}.0${k} <${+C+1}.0.0-0`:z?(i("replaceCaret pr",z),C==="0"?F==="0"?Y=`>=${C}.${F}.${W}-${z} <${C}.${F}.${+W+1}-0`:Y=`>=${C}.${F}.${W}-${z} <${C}.${+F+1}.0-0`:Y=`>=${C}.${F}.${W}-${z} <${+C+1}.0.0-0`):(i("no pr"),C==="0"?F==="0"?Y=`>=${C}.${F}.${W}${k} <${C}.${F}.${+W+1}-0`:Y=`>=${C}.${F}.${W}${k} <${C}.${+F+1}.0-0`:Y=`>=${C}.${F}.${W} <${+C+1}.0.0-0`),i("caret return",Y),Y})},O=(P,T)=>(i("replaceXRanges",P,T),P.split(/\s+/).map(N=>q(N,T)).join(" ")),q=(P,T)=>{P=P.trim();const N=T.loose?u[c.XRANGELOOSE]:u[c.XRANGE];return P.replace(N,(k,j,C,F,W,z)=>{i("xRange",P,k,j,C,F,W,z);const Y=b(C),_e=Y||b(F),ee=_e||b(W),Yt=ee;return j==="="&&Yt&&(j=""),z=T.includePrerelease?"-0":"",Y?j===">"||j==="<"?k="<0.0.0-0":k="*":j&&Yt?(_e&&(F=0),W=0,j===">"?(j=">=",_e?(C=+C+1,F=0,W=0):(F=+F+1,W=0)):j==="<="&&(j="<",_e?C=+C+1:F=+F+1),j==="<"&&(z="-0"),k=`${j+C}.${F}.${W}${z}`):_e?k=`>=${C}.0.0${z} <${+C+1}.0.0-0`:ee&&(k=`>=${C}.${F}.0${z} <${C}.${+F+1}.0-0`),i("xRange return",k),k})},G=(P,T)=>(i("replaceStars",P,T),P.trim().replace(u[c.STAR],"")),V=(P,T)=>(i("replaceGTE0",P,T),P.trim().replace(u[T.includePrerelease?c.GTE0PRE:c.GTE0],"")),Le=P=>(T,N,k,j,C,F,W,z,Y,_e,ee,Yt)=>(b(k)?N="":b(j)?N=`>=${k}.0.0${P?"-0":""}`:b(C)?N=`>=${k}.${j}.0${P?"-0":""}`:F?N=`>=${N}`:N=`>=${N}${P?"-0":""}`,b(Y)?z="":b(_e)?z=`<${+Y+1}.0.0-0`:b(ee)?z=`<${Y}.${+_e+1}.0-0`:Yt?z=`<=${Y}.${_e}.${ee}-${Yt}`:P?z=`<${Y}.${_e}.${+ee+1}-0`:z=`<=${z}`,`${N} ${z}`.trim()),yt=(P,T,N)=>{for(let k=0;k<P.length;k++)if(!P[k].test(T))return!1;if(T.prerelease.length&&!N.includePrerelease){for(let k=0;k<P.length;k++)if(i(P[k].semver),P[k].semver!==a.ANY&&P[k].semver.prerelease.length>0){const j=P[k].semver;if(j.major===T.major&&j.minor===T.minor&&j.patch===T.patch)return!0}return!1}return!0};return ha}var fa,zu;function ss(){if(zu)return fa;zu=1;const n=Symbol("SemVer ANY");class e{static get ANY(){return n}constructor(l,d){if(d=t(d),l instanceof e){if(l.loose===!!d.loose)return l;l=l.value}l=l.trim().split(/\s+/).join(" "),i("comparator",l,d),this.options=d,this.loose=!!d.loose,this.parse(l),this.semver===n?this.value="":this.value=this.operator+this.semver.version,i("comp",this)}parse(l){const d=this.options.loose?r[s.COMPARATORLOOSE]:r[s.COMPARATOR],h=l.match(d);if(!h)throw new TypeError(`Invalid comparator: ${l}`);this.operator=h[1]!==void 0?h[1]:"",this.operator==="="&&(this.operator=""),h[2]?this.semver=new o(h[2],this.options.loose):this.semver=n}toString(){return this.value}test(l){if(i("Comparator.test",l,this.options.loose),this.semver===n||l===n)return!0;if(typeof l=="string")try{l=new o(l,this.options)}catch{return!1}return a(l,this.operator,this.semver,this.options)}intersects(l,d){if(!(l instanceof e))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new u(l.value,d).test(this.value):l.operator===""?l.value===""?!0:new u(this.value,d).test(l.semver):(d=t(d),d.includePrerelease&&(this.value==="<0.0.0-0"||l.value==="<0.0.0-0")||!d.includePrerelease&&(this.value.startsWith("<0.0.0")||l.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&l.operator.startsWith(">")||this.operator.startsWith("<")&&l.operator.startsWith("<")||this.semver.version===l.semver.version&&this.operator.includes("=")&&l.operator.includes("=")||a(this.semver,"<",l.semver,d)&&this.operator.startsWith(">")&&l.operator.startsWith("<")||a(this.semver,">",l.semver,d)&&this.operator.startsWith("<")&&l.operator.startsWith(">")))}}fa=e;const t=Fi(),{safeRe:r,t:s}=Mr(),a=Td(),i=rs(),o=Ee(),u=Je();return fa}var pa,qu;function as(){if(qu)return pa;qu=1;const n=Je();return pa=(t,r,s)=>{try{r=new n(r,s)}catch{return!1}return r.test(t)},pa}var ma,Hu;function Zm(){if(Hu)return ma;Hu=1;const n=Je();return ma=(t,r)=>new n(t,r).set.map(s=>s.map(a=>a.value).join(" ").trim().split(" ")),ma}var ga,Gu;function Km(){if(Gu)return ga;Gu=1;const n=Ee(),e=Je();return ga=(r,s,a)=>{let i=null,o=null,u=null;try{u=new e(s,a)}catch{return null}return r.forEach(c=>{u.test(c)&&(!i||o.compare(c)===-1)&&(i=c,o=new n(i,a))}),i},ga}var _a,Ju;function Vm(){if(Ju)return _a;Ju=1;const n=Ee(),e=Je();return _a=(r,s,a)=>{let i=null,o=null,u=null;try{u=new e(s,a)}catch{return null}return r.forEach(c=>{u.test(c)&&(!i||o.compare(c)===1)&&(i=c,o=new n(i,a))}),i},_a}var ya,Wu;function Xm(){if(Wu)return ya;Wu=1;const n=Ee(),e=Je(),t=ns();return ya=(s,a)=>{s=new e(s,a);let i=new n("0.0.0");if(s.test(i)||(i=new n("0.0.0-0"),s.test(i)))return i;i=null;for(let o=0;o<s.set.length;++o){const u=s.set[o];let c=null;u.forEach(l=>{const d=new n(l.semver.version);switch(l.operator){case">":d.prerelease.length===0?d.patch++:d.prerelease.push(0),d.raw=d.format();case"":case">=":(!c||t(d,c))&&(c=d);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${l.operator}`)}}),c&&(!i||t(i,c))&&(i=c)}return i&&s.test(i)?i:null},ya}var ba,Zu;function Qm(){if(Zu)return ba;Zu=1;const n=Je();return ba=(t,r)=>{try{return new n(t,r).range||"*"}catch{return null}},ba}var wa,Ku;function Gi(){if(Ku)return wa;Ku=1;const n=Ee(),e=ss(),{ANY:t}=e,r=Je(),s=as(),a=ns(),i=zi(),o=Hi(),u=qi();return wa=(l,d,h,f)=>{l=new n(l,f),d=new r(d,f);let p,m,g,_,y;switch(h){case">":p=a,m=o,g=i,_=">",y=">=";break;case"<":p=i,m=u,g=a,_="<",y="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(s(l,d,f))return!1;for(let b=0;b<d.set.length;++b){const v=d.set[b];let E=null,I=null;if(v.forEach(x=>{x.semver===t&&(x=new e(">=0.0.0")),E=E||x,I=I||x,p(x.semver,E.semver,f)?E=x:g(x.semver,I.semver,f)&&(I=x)}),E.operator===_||E.operator===y||(!I.operator||I.operator===_)&&m(l,I.semver))return!1;if(I.operator===y&&g(l,I.semver))return!1}return!0},wa}var va,Vu;function Ym(){if(Vu)return va;Vu=1;const n=Gi();return va=(t,r,s)=>n(t,r,">",s),va}var Ea,Xu;function eg(){if(Xu)return Ea;Xu=1;const n=Gi();return Ea=(t,r,s)=>n(t,r,"<",s),Ea}var Sa,Qu;function tg(){if(Qu)return Sa;Qu=1;const n=Je();return Sa=(t,r,s)=>(t=new n(t,s),r=new n(r,s),t.intersects(r,s)),Sa}var Oa,Yu;function rg(){if(Yu)return Oa;Yu=1;const n=as(),e=Ge();return Oa=(t,r,s)=>{const a=[];let i=null,o=null;const u=t.sort((h,f)=>e(h,f,s));for(const h of u)n(h,r,s)?(o=h,i||(i=h)):(o&&a.push([i,o]),o=null,i=null);i&&a.push([i,null]);const c=[];for(const[h,f]of a)h===f?c.push(h):!f&&h===u[0]?c.push("*"):f?h===u[0]?c.push(`<=${f}`):c.push(`${h} - ${f}`):c.push(`>=${h}`);const l=c.join(" || "),d=typeof r.raw=="string"?r.raw:String(r);return l.length<d.length?l:r},Oa}var Ta,ec;function ng(){if(ec)return Ta;ec=1;const n=Je(),e=ss(),{ANY:t}=e,r=as(),s=Ge(),a=(d,h,f={})=>{if(d===h)return!0;d=new n(d,f),h=new n(h,f);let p=!1;e:for(const m of d.set){for(const g of h.set){const _=u(m,g,f);if(p=p||_!==null,_)continue e}if(p)return!1}return!0},i=[new e(">=0.0.0-0")],o=[new e(">=0.0.0")],u=(d,h,f)=>{if(d===h)return!0;if(d.length===1&&d[0].semver===t){if(h.length===1&&h[0].semver===t)return!0;f.includePrerelease?d=i:d=o}if(h.length===1&&h[0].semver===t){if(f.includePrerelease)return!0;h=o}const p=new Set;let m,g;for(const O of d)O.operator===">"||O.operator===">="?m=c(m,O,f):O.operator==="<"||O.operator==="<="?g=l(g,O,f):p.add(O.semver);if(p.size>1)return null;let _;if(m&&g){if(_=s(m.semver,g.semver,f),_>0)return null;if(_===0&&(m.operator!==">="||g.operator!=="<="))return null}for(const O of p){if(m&&!r(O,String(m),f)||g&&!r(O,String(g),f))return null;for(const q of h)if(!r(O,String(q),f))return!1;return!0}let y,b,v,E,I=g&&!f.includePrerelease&&g.semver.prerelease.length?g.semver:!1,x=m&&!f.includePrerelease&&m.semver.prerelease.length?m.semver:!1;I&&I.prerelease.length===1&&g.operator==="<"&&I.prerelease[0]===0&&(I=!1);for(const O of h){if(E=E||O.operator===">"||O.operator===">=",v=v||O.operator==="<"||O.operator==="<=",m){if(x&&O.semver.prerelease&&O.semver.prerelease.length&&O.semver.major===x.major&&O.semver.minor===x.minor&&O.semver.patch===x.patch&&(x=!1),O.operator===">"||O.operator===">="){if(y=c(m,O,f),y===O&&y!==m)return!1}else if(m.operator===">="&&!r(m.semver,String(O),f))return!1}if(g){if(I&&O.semver.prerelease&&O.semver.prerelease.length&&O.semver.major===I.major&&O.semver.minor===I.minor&&O.semver.patch===I.patch&&(I=!1),O.operator==="<"||O.operator==="<="){if(b=l(g,O,f),b===O&&b!==g)return!1}else if(g.operator==="<="&&!r(g.semver,String(O),f))return!1}if(!O.operator&&(g||m)&&_!==0)return!1}return!(m&&v&&!g&&_!==0||g&&E&&!m&&_!==0||x||I)},c=(d,h,f)=>{if(!d)return h;const p=s(d.semver,h.semver,f);return p>0?d:p<0||h.operator===">"&&d.operator===">="?h:d},l=(d,h,f)=>{if(!d)return h;const p=s(d.semver,h.semver,f);return p<0?d:p>0||h.operator==="<"&&d.operator==="<="?h:d};return Ta=a,Ta}var Aa,tc;function sg(){if(tc)return Aa;tc=1;const n=Mr(),e=ts(),t=Ee(),r=Ed(),s=Kt(),a=Nm(),i=jm(),o=Lm(),u=Mm(),c=Um(),l=Dm(),d=Fm(),h=Bm(),f=Ge(),p=zm(),m=qm(),g=Bi(),_=Hm(),y=Gm(),b=ns(),v=zi(),E=Sd(),I=Od(),x=qi(),O=Hi(),q=Td(),G=Jm(),V=ss(),Le=Je(),yt=as(),P=Zm(),T=Km(),N=Vm(),k=Xm(),j=Qm(),C=Gi(),F=Ym(),W=eg(),z=tg(),Y=rg(),_e=ng();return Aa={parse:s,valid:a,clean:i,inc:o,diff:u,major:c,minor:l,patch:d,prerelease:h,compare:f,rcompare:p,compareLoose:m,compareBuild:g,sort:_,rsort:y,gt:b,lt:v,eq:E,neq:I,gte:x,lte:O,cmp:q,coerce:G,Comparator:V,Range:Le,satisfies:yt,toComparators:P,maxSatisfying:T,minSatisfying:N,minVersion:k,validRange:j,outside:C,gtr:F,ltr:W,intersects:z,simplifyRange:Y,subset:_e,SemVer:t,re:n.re,src:n.src,tokens:n.t,SEMVER_SPEC_VERSION:e.SEMVER_SPEC_VERSION,RELEASE_TYPES:e.RELEASE_TYPES,compareIdentifiers:r.compareIdentifiers,rcompareIdentifiers:r.rcompareIdentifiers},Aa}sg();function ut(n){if(!n||n.split("/").length>2||n.startsWith("/")||n.endsWith("/")||n.split(":").length>2)throw new Error(`Invalid identifier format: ${n}`);const[e,t]=n.split(":"),r=t||"latest";if(e.includes("/")){const[s,a]=e.split("/",2);if(!s||!a)throw new Error(`Invalid identifier format: ${n}`);return[s,a,r]}else{if(!e)throw new Error(`Invalid identifier format: ${n}`);return["-",e,r]}}class ag extends Error{constructor(e){super(e),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="LangSmithConflictError",this.status=409}}async function R(n,e,t){let r;if(n.ok){t&&(r=await n.text());return}if(n.status===403)try{(await n.json())?.error==="org_scoped_key_requires_workspace"&&(r="This API key is org-scoped and requires workspace specification. Please provide 'workspaceId' parameter, or set LANGSMITH_WORKSPACE_ID environment variable.")}catch{const o=new Error(`${n.status} ${n.statusText}`);throw o.status=n?.status,o}if(r===void 0)try{r=await n.text()}catch{r=""}const s=`Failed to ${e}. Received status [${n.status}]: ${n.statusText}. Message: ${r}`;if(n.status===409)throw new ag(s);const a=new Error(s);throw a.status=n.status,a}const Ad="ERR_CONFLICTING_ENDPOINTS";class ig extends Error{constructor(){super("You cannot provide both LANGSMITH_ENDPOINT / LANGCHAIN_ENDPOINT and LANGSMITH_RUNS_ENDPOINTS."),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:Ad}),this.name="ConflictingEndpointsError"}}function og(n){return typeof n=="object"&&n!==null&&n.code===Ad}var rc="[...]",ug={result:"[Circular]"},kn=[],qt=[];const cg=new TextEncoder;function lg(){return{depthLimit:Number.MAX_SAFE_INTEGER,edgesLimit:Number.MAX_SAFE_INTEGER}}function en(n){return cg.encode(n)}function Pd(n){if(n&&typeof n=="object"&&n!==null){if(n instanceof Map)return Object.fromEntries(n);if(n instanceof Set)return Array.from(n);if(n instanceof Date)return n.toISOString();if(n instanceof RegExp)return n.toString();if(n instanceof Error)return{name:n.name,message:n.message}}else if(typeof n=="bigint")return n.toString();return n}function dg(n){return function(e,t){return Pd(t)}}function Re(n,e,t,r,s){try{const a=JSON.stringify(n,dg(t),r);return en(a)}catch(a){if(!a.message?.includes("Converting circular structure to JSON"))return console.warn(`[WARNING]: LangSmith received unserializable value.${e?`
|
|
50
|
+
Context: ${e}`:""}`),en("[Unserializable]");Ae("SUPPRESS_CIRCULAR_JSON_WARNINGS")!=="true"&&console.warn(`[WARNING]: LangSmith received circular JSON. This will decrease tracer performance. ${e?`
|
|
51
|
+
Context: ${e}`:""}`),typeof s>"u"&&(s=lg()),ai(n,"",0,[],void 0,0,s);let i;try{qt.length===0?i=JSON.stringify(n,t,r):i=JSON.stringify(n,hg(t),r)}catch{return en("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;kn.length!==0;){const o=kn.pop();o.length===4?Object.defineProperty(o[0],o[1],o[3]):o[0][o[1]]=o[2]}}return en(i)}}function Pa(n,e,t,r){var s=Object.getOwnPropertyDescriptor(r,t);s.get!==void 0?s.configurable?(Object.defineProperty(r,t,{value:n}),kn.push([r,t,e,s])):qt.push([e,t,n]):(r[t]=n,kn.push([r,t,e]))}function ai(n,e,t,r,s,a,i){a+=1;var o;if(typeof n=="object"&&n!==null){for(o=0;o<r.length;o++)if(r[o]===n){Pa(ug,n,e,s);return}if(typeof i.depthLimit<"u"&&a>i.depthLimit){Pa(rc,n,e,s);return}if(typeof i.edgesLimit<"u"&&t+1>i.edgesLimit){Pa(rc,n,e,s);return}if(r.push(n),Array.isArray(n))for(o=0;o<n.length;o++)ai(n[o],o,o,r,n,a,i);else{n=Pd(n);var u=Object.keys(n);for(o=0;o<u.length;o++){var c=u[o];ai(n[c],c,o,r,n,a,i)}}r.pop()}}function hg(n){return n=typeof n<"u"?n:function(e,t){return t},function(e,t){if(qt.length>0)for(var r=0;r<qt.length;r++){var s=qt[r];if(s[1]===e&&s[0]===t){t=s[2],qt.splice(r,1);break}}return n.call(this,e,t)}}function nc(n,e){const t=_d(),r=e??yd(),s=n.extra??{},a=s.metadata;return n.extra={...s,runtime:{...t,...s?.runtime},metadata:{...r,...r.revision_id||"revision_id"in n&&n.revision_id?{revision_id:("revision_id"in n?n.revision_id:void 0)??r.revision_id}:{},...a}},n}const fg=n=>{const e=n?.toString()??Ae("TRACING_SAMPLING_RATE");if(e===void 0)return;const t=parseFloat(e);if(t<0||t>1)throw new Error(`LANGSMITH_TRACING_SAMPLING_RATE must be between 0 and 1 if set. Got: ${t}`);return t},pg=n=>{const t=n.replace("http://","").replace("https://","").split("/")[0].split(":")[0];return t==="localhost"||t==="127.0.0.1"||t==="::1"};async function mg(n){const e=[];for await(const t of n)e.push(t);return e}function tn(n){if(n!==void 0)return n.trim().replace(/^"(.*)"$/,"$1").replace(/^'(.*)'$/,"$1")}const gg=async n=>{if(n?.status===429){const e=parseInt(n.headers.get("retry-after")??"10",10)*1e3;if(e>0)return await new Promise(t=>setTimeout(t,e)),!0}return!1};function sc(n){return typeof n=="number"?Number(n.toFixed(4)):n}class _g{constructor(){Object.defineProperty(this,"items",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"sizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:0})}peek(){return this.items[0]}push(e){let t;const r=new Promise(a=>{t=a}),s=Re(e.item,`Serializing run with id: ${e.item.id}`).length;return this.items.push({action:e.action,payload:e.item,otelContext:e.otelContext,apiKey:e.apiKey,apiUrl:e.apiUrl,itemPromiseResolve:t,itemPromise:r,size:s}),this.sizeBytes+=s,r}pop({upToSizeBytes:e,upToSize:t}){if(e<1)throw new Error("Number of bytes to pop off may not be less than 1.");const r=[];let s=0;for(;s+(this.peek()?.size??0)<e&&this.items.length>0&&r.length<t;){const a=this.items.shift();a&&(r.push(a),s+=a.size,this.sizeBytes-=a.size)}if(r.length===0&&this.items.length>0){const a=this.items.shift();r.push(a),s+=a.size,this.sizeBytes-=a.size}return[r.map(a=>({action:a.action,item:a.payload,otelContext:a.otelContext,apiKey:a.apiKey,apiUrl:a.apiUrl})),()=>r.forEach(a=>a.itemPromiseResolve())]}}const yg=24*1024*1024,bg=1e4,wg=100,ac="https://api.smith.langchain.com";class Pr{get _fetch(){return this.fetchImplementation||om(this.debug)}constructor(e={}){Object.defineProperty(this,"apiKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"apiUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"webUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"workspaceId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"caller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"batchIngestCaller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"timeout_ms",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_tenantId",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"hideInputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"hideOutputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tracingSampleRate",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"filteredPostUuids",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"autoBatchTracing",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"autoBatchQueue",{enumerable:!0,configurable:!0,writable:!0,value:new _g}),Object.defineProperty(this,"autoBatchTimeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"autoBatchAggregationDelayMs",{enumerable:!0,configurable:!0,writable:!0,value:250}),Object.defineProperty(this,"batchSizeBytesLimit",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"batchSizeLimit",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"fetchOptions",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"settings",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"blockOnRootRunFinalization",{enumerable:!0,configurable:!0,writable:!0,value:Ye("LANGSMITH_TRACING_BACKGROUND")==="false"}),Object.defineProperty(this,"traceBatchConcurrency",{enumerable:!0,configurable:!0,writable:!0,value:5}),Object.defineProperty(this,"_serverInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_getServerInfoPromise",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"manualFlushMode",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"langSmithToOTELTranslator",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"fetchImplementation",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cachedLSEnvVarsForMetadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"multipartStreamingDisabled",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"debug",{enumerable:!0,configurable:!0,writable:!0,value:Ye("LANGSMITH_DEBUG")==="true"});const t=Pr.getDefaultClientConfig();if(this.tracingSampleRate=fg(e.tracingSamplingRate),this.apiUrl=tn(e.apiUrl??t.apiUrl)??"",this.apiUrl.endsWith("/")&&(this.apiUrl=this.apiUrl.slice(0,-1)),this.apiKey=tn(e.apiKey??t.apiKey),this.webUrl=tn(e.webUrl??t.webUrl),this.webUrl?.endsWith("/")&&(this.webUrl=this.webUrl.slice(0,-1)),this.workspaceId=tn(e.workspaceId??Ae("WORKSPACE_ID")),this.timeout_ms=e.timeout_ms??9e4,this.caller=new ou({...e.callerOptions??{},maxRetries:4,debug:e.debug??this.debug}),this.traceBatchConcurrency=e.traceBatchConcurrency??this.traceBatchConcurrency,this.traceBatchConcurrency<1)throw new Error("Trace batch concurrency must be positive.");this.debug=e.debug??this.debug,this.fetchImplementation=e.fetchImplementation,this.batchIngestCaller=new ou({maxRetries:2,maxConcurrency:this.traceBatchConcurrency,...e.callerOptions??{},onFailedResponseHook:gg,debug:e.debug??this.debug}),this.hideInputs=e.hideInputs??e.anonymizer??t.hideInputs,this.hideOutputs=e.hideOutputs??e.anonymizer??t.hideOutputs,this.autoBatchTracing=e.autoBatchTracing??this.autoBatchTracing,this.blockOnRootRunFinalization=e.blockOnRootRunFinalization??this.blockOnRootRunFinalization,this.batchSizeBytesLimit=e.batchSizeBytesLimit,this.batchSizeLimit=e.batchSizeLimit,this.fetchOptions=e.fetchOptions||{},this.manualFlushMode=e.manualFlushMode??this.manualFlushMode,bd()&&(this.langSmithToOTELTranslator=new Om),this.cachedLSEnvVarsForMetadata=yd()}static getDefaultClientConfig(){const e=Ae("API_KEY"),t=Ae("ENDPOINT")??ac,r=Ae("HIDE_INPUTS")==="true",s=Ae("HIDE_OUTPUTS")==="true";return{apiUrl:t,apiKey:e,webUrl:void 0,hideInputs:r,hideOutputs:s}}getHostUrl(){return this.webUrl?this.webUrl:pg(this.apiUrl)?(this.webUrl="http://localhost:3000",this.webUrl):this.apiUrl.endsWith("/api/v1")?(this.webUrl=this.apiUrl.replace("/api/v1",""),this.webUrl):this.apiUrl.includes("/api")&&!this.apiUrl.split(".",1)[0].endsWith("api")?(this.webUrl=this.apiUrl.replace("/api",""),this.webUrl):this.apiUrl.split(".",1)[0].includes("dev")?(this.webUrl="https://dev.smith.langchain.com",this.webUrl):this.apiUrl.split(".",1)[0].includes("eu")?(this.webUrl="https://eu.smith.langchain.com",this.webUrl):this.apiUrl.split(".",1)[0].includes("beta")?(this.webUrl="https://beta.smith.langchain.com",this.webUrl):(this.webUrl="https://smith.langchain.com",this.webUrl)}get headers(){const e={"User-Agent":`langsmith-js/${pd}`};return this.apiKey&&(e["x-api-key"]=`${this.apiKey}`),this.workspaceId&&(e["x-tenant-id"]=this.workspaceId),e}_getPlatformEndpointPath(e){return this.apiUrl.slice(-3)!=="/v1"&&this.apiUrl.slice(-4)!=="/v1/"?`/v1/platform/${e}`:`/platform/${e}`}async processInputs(e){return this.hideInputs===!1?e:this.hideInputs===!0?{}:typeof this.hideInputs=="function"?this.hideInputs(e):e}async processOutputs(e){return this.hideOutputs===!1?e:this.hideOutputs===!0?{}:typeof this.hideOutputs=="function"?this.hideOutputs(e):e}async prepareRunCreateOrUpdateInputs(e){const t={...e};return t.inputs!==void 0&&(t.inputs=await this.processInputs(t.inputs)),t.outputs!==void 0&&(t.outputs=await this.processOutputs(t.outputs)),t}async _getResponse(e,t){const r=t?.toString()??"",s=`${this.apiUrl}${e}?${r}`;return await this.caller.call(async()=>{const i=await this._fetch(s,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await R(i,`fetch ${e}`),i})}async _get(e,t){return(await this._getResponse(e,t)).json()}async*_getPaginated(e,t=new URLSearchParams,r){let s=Number(t.get("offset"))||0;const a=Number(t.get("limit"))||100;for(;;){t.set("offset",String(s)),t.set("limit",String(a));const i=`${this.apiUrl}${e}?${t}`,o=await this.caller.call(async()=>{const c=await this._fetch(i,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await R(c,`fetch ${e}`),c}),u=r?r(await o.json()):await o.json();if(u.length===0||(yield u,u.length<a))break;s+=u.length}}async*_getCursorPaginatedList(e,t=null,r="POST",s="runs"){const a=t?{...t}:{};for(;;){const i=JSON.stringify(a),u=await(await this.caller.call(async()=>{const l=await this._fetch(`${this.apiUrl}${e}`,{method:r,headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await R(l,`fetch ${e}`),l})).json();if(!u||!u[s])break;yield u[s];const c=u.cursors;if(!c||!c.next)break;a.cursor=c.next}}_shouldSample(){return this.tracingSampleRate===void 0?!0:Math.random()<this.tracingSampleRate}_filterForSampling(e,t=!1){if(this.tracingSampleRate===void 0)return e;if(t){const r=[];for(const s of e)this.filteredPostUuids.has(s.trace_id)?s.id===s.trace_id&&this.filteredPostUuids.delete(s.trace_id):r.push(s);return r}else{const r=[];for(const s of e){const a=s.trace_id??s.id;this.filteredPostUuids.has(a)||(s.id===a?this._shouldSample()?r.push(s):this.filteredPostUuids.add(a):r.push(s))}return r}}async _getBatchSizeLimitBytes(){const e=await this._ensureServerInfo();return this.batchSizeBytesLimit??e.batch_ingest_config?.size_limit_bytes??yg}async _getBatchSizeLimit(){const e=await this._ensureServerInfo();return this.batchSizeLimit??e.batch_ingest_config?.size_limit??wg}async _getDatasetExamplesMultiPartSupport(){return(await this._ensureServerInfo()).instance_flags?.dataset_examples_multipart_enabled??!1}drainAutoBatchQueue({batchSizeLimitBytes:e,batchSizeLimit:t}){const r=[];for(;this.autoBatchQueue.items.length>0;){const[s,a]=this.autoBatchQueue.pop({upToSizeBytes:e,upToSize:t});if(!s.length){a();break}const i=s.reduce((c,l)=>{const d=l.apiUrl??this.apiUrl,h=l.apiKey??this.apiKey,p=l.apiKey===this.apiKey&&l.apiUrl===this.apiUrl?"default":`${d}|${h}`;return c[p]||(c[p]=[]),c[p].push(l),c},{}),o=[];for(const[c,l]of Object.entries(i)){const d=this._processBatch(l,{apiUrl:c==="default"?void 0:c.split("|")[0],apiKey:c==="default"?void 0:c.split("|")[1]});o.push(d)}const u=Promise.all(o).finally(a);r.push(u)}return Promise.all(r)}async _processBatch(e,t){if(e.length)try{if(this.langSmithToOTELTranslator!==void 0)this._sendBatchToOTELTranslator(e);else{const r={runCreates:e.filter(a=>a.action==="create").map(a=>a.item),runUpdates:e.filter(a=>a.action==="update").map(a=>a.item)},s=await this._ensureServerInfo();if(s?.batch_ingest_config?.use_multipart_endpoint){const a=s?.instance_flags?.gzip_body_enabled;await this.multipartIngestRuns(r,{...t,useGzip:a})}else await this.batchIngestRuns(r,t)}}catch(r){console.error("Error exporting batch:",r)}}_sendBatchToOTELTranslator(e){if(this.langSmithToOTELTranslator!==void 0){const t=new Map,r=[];for(const s of e)s.item.id&&s.otelContext&&(t.set(s.item.id,s.otelContext),s.action==="create"?r.push({operation:"post",id:s.item.id,trace_id:s.item.trace_id??s.item.id,run:s.item}):r.push({operation:"patch",id:s.item.id,trace_id:s.item.trace_id??s.item.id,run:s.item}));this.langSmithToOTELTranslator.exportBatch(r,t)}}async processRunOperation(e){clearTimeout(this.autoBatchTimeout),this.autoBatchTimeout=void 0,e.item=nc(e.item,this.cachedLSEnvVarsForMetadata);const t=this.autoBatchQueue.push(e);if(this.manualFlushMode)return t;const r=await this._getBatchSizeLimitBytes(),s=await this._getBatchSizeLimit();return(this.autoBatchQueue.sizeBytes>r||this.autoBatchQueue.items.length>s)&&this.drainAutoBatchQueue({batchSizeLimitBytes:r,batchSizeLimit:s}),this.autoBatchQueue.items.length>0&&(this.autoBatchTimeout=setTimeout(()=>{this.autoBatchTimeout=void 0,this.drainAutoBatchQueue({batchSizeLimitBytes:r,batchSizeLimit:s})},this.autoBatchAggregationDelayMs)),t}async _getServerInfo(){const t=await(await this.caller.call(async()=>{const r=await this._fetch(`${this.apiUrl}/info`,{method:"GET",headers:{Accept:"application/json"},signal:AbortSignal.timeout(bg),...this.fetchOptions});return await R(r,"get server info"),r})).json();return this.debug&&console.log(`
|
|
52
|
+
=== LangSmith Server Configuration ===
|
|
53
|
+
`+JSON.stringify(t,null,2)+`
|
|
54
|
+
`),t}async _ensureServerInfo(){return this._getServerInfoPromise===void 0&&(this._getServerInfoPromise=(async()=>{if(this._serverInfo===void 0)try{this._serverInfo=await this._getServerInfo()}catch(e){console.warn(`[LANGSMITH]: Failed to fetch info on supported operations. Falling back to batch operations and default limits. Info: ${e.status??"Unspecified status code"} ${e.message}`)}return this._serverInfo??{}})()),this._getServerInfoPromise.then(e=>(this._serverInfo===void 0&&(this._getServerInfoPromise=void 0),e))}async _getSettings(){return this.settings||(this.settings=this._get("/settings")),await this.settings}async flush(){const e=await this._getBatchSizeLimitBytes(),t=await this._getBatchSizeLimit();await this.drainAutoBatchQueue({batchSizeLimitBytes:e,batchSizeLimit:t})}_cloneCurrentOTELContext(){const e=wd(),t=wm();if(this.langSmithToOTELTranslator!==void 0){const r=e.getActiveSpan();if(r)return e.setSpan(t.active(),r)}}async createRun(e,t){if(!this._filterForSampling([e]).length)return;const r={...this.headers,"Content-Type":"application/json"},s=e.project_name;delete e.project_name;const a=await this.prepareRunCreateOrUpdateInputs({session_name:s,...e,start_time:e.start_time??Date.now()});if(this.autoBatchTracing&&a.trace_id!==void 0&&a.dotted_order!==void 0){const u=this._cloneCurrentOTELContext();this.processRunOperation({action:"create",item:a,otelContext:u,apiKey:t?.apiKey,apiUrl:t?.apiUrl}).catch(console.error);return}const i=nc(a,this.cachedLSEnvVarsForMetadata);t?.apiKey!==void 0&&(r["x-api-key"]=t.apiKey),t?.workspaceId!==void 0&&(r["x-tenant-id"]=t.workspaceId);const o=Re(i,`Creating run with id: ${i.id}`);await this.caller.call(async()=>{const u=await this._fetch(`${t?.apiUrl??this.apiUrl}/runs`,{method:"POST",headers:r,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await R(u,"create run",!0),u})}async batchIngestRuns({runCreates:e,runUpdates:t},r){if(e===void 0&&t===void 0)return;let s=await Promise.all(e?.map(u=>this.prepareRunCreateOrUpdateInputs(u))??[]),a=await Promise.all(t?.map(u=>this.prepareRunCreateOrUpdateInputs(u))??[]);if(s.length>0&&a.length>0){const u=s.reduce((l,d)=>(d.id&&(l[d.id]=d),l),{}),c=[];for(const l of a)l.id!==void 0&&u[l.id]?u[l.id]={...u[l.id],...l}:c.push(l);s=Object.values(u),a=c}const i={post:s,patch:a};if(!i.post.length&&!i.patch.length)return;const o={post:[],patch:[]};for(const u of["post","patch"]){const c=u,l=i[c].reverse();let d=l.pop();for(;d!==void 0;)o[c].push(d),d=l.pop()}if(o.post.length>0||o.patch.length>0){const u=o.post.map(c=>c.id).concat(o.patch.map(c=>c.id)).join(",");await this._postBatchIngestRuns(Re(o,`Ingesting runs with ids: ${u}`),r)}}async _postBatchIngestRuns(e,t){const r={...this.headers,"Content-Type":"application/json",Accept:"application/json"};t?.apiKey!==void 0&&(r["x-api-key"]=t.apiKey),await this.batchIngestCaller.call(async()=>{const s=await this._fetch(`${t?.apiUrl??this.apiUrl}/runs/batch`,{method:"POST",headers:r,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:e});return await R(s,"batch create run",!0),s})}async multipartIngestRuns({runCreates:e,runUpdates:t},r){if(e===void 0&&t===void 0)return;const s={};let a=[];for(const d of e??[]){const h=await this.prepareRunCreateOrUpdateInputs(d);h.id!==void 0&&h.attachments!==void 0&&(s[h.id]=h.attachments),delete h.attachments,a.push(h)}let i=[];for(const d of t??[])i.push(await this.prepareRunCreateOrUpdateInputs(d));if(a.find(d=>d.trace_id===void 0||d.dotted_order===void 0)!==void 0)throw new Error('Multipart ingest requires "trace_id" and "dotted_order" to be set when creating a run');if(i.find(d=>d.trace_id===void 0||d.dotted_order===void 0)!==void 0)throw new Error('Multipart ingest requires "trace_id" and "dotted_order" to be set when updating a run');if(a.length>0&&i.length>0){const d=a.reduce((f,p)=>(p.id&&(f[p.id]=p),f),{}),h=[];for(const f of i)f.id!==void 0&&d[f.id]?d[f.id]={...d[f.id],...f}:h.push(f);a=Object.values(d),i=h}if(a.length===0&&i.length===0)return;const c=[],l=[];for(const[d,h]of[["post",a],["patch",i]])for(const f of h){const{inputs:p,outputs:m,events:g,extra:_,error:y,serialized:b,attachments:v,...E}=f,I={inputs:p,outputs:m,events:g,extra:_,error:y,serialized:b},x=Re(E,`Serializing for multipart ingestion of run with id: ${E.id}`);l.push({name:`${d}.${E.id}`,payload:new Blob([x],{type:`application/json; length=${x.length}`})});for(const[O,q]of Object.entries(I)){if(q===void 0)continue;const G=Re(q,`Serializing ${O} for multipart ingestion of run with id: ${E.id}`);l.push({name:`${d}.${E.id}.${O}`,payload:new Blob([G],{type:`application/json; length=${G.length}`})})}if(E.id!==void 0){const O=s[E.id];if(O){delete s[E.id];for(const[q,G]of Object.entries(O)){let V,Le;if(Array.isArray(G)?[V,Le]=G:(V=G.mimeType,Le=G.data),q.includes(".")){console.warn(`Skipping attachment '${q}' for run ${E.id}: Invalid attachment name. Attachment names must not contain periods ('.'). Please rename the attachment and try again.`);continue}l.push({name:`attachment.${E.id}.${q}`,payload:new Blob([Le],{type:`${V}; length=${Le.byteLength}`})})}}}c.push(`trace=${E.trace_id},id=${E.id}`)}await this._sendMultipartRequest(l,c.join("; "),r)}async _createNodeFetchBody(e,t){const r=[];for(const i of e)r.push(new Blob([`--${t}\r
|
|
55
|
+
`])),r.push(new Blob([`Content-Disposition: form-data; name="${i.name}"\r
|
|
56
|
+
`,`Content-Type: ${i.payload.type}\r
|
|
57
|
+
\r
|
|
58
|
+
`])),r.push(i.payload),r.push(new Blob([`\r
|
|
59
|
+
`]));return r.push(new Blob([`--${t}--\r
|
|
60
|
+
`])),await new Blob(r).arrayBuffer()}async _createMultipartStream(e,t){const r=new TextEncoder;return new ReadableStream({async start(a){const i=async o=>{typeof o=="string"?a.enqueue(r.encode(o)):a.enqueue(o)};for(const o of e){await i(`--${t}\r
|
|
61
|
+
`),await i(`Content-Disposition: form-data; name="${o.name}"\r
|
|
62
|
+
`),await i(`Content-Type: ${o.payload.type}\r
|
|
63
|
+
\r
|
|
64
|
+
`);const c=o.payload.stream().getReader();try{let l;for(;!(l=await c.read()).done;)a.enqueue(l.value)}finally{c.releaseLock()}await i(`\r
|
|
65
|
+
`)}await i(`--${t}--\r
|
|
66
|
+
`),a.close()}})}async _sendMultipartRequest(e,t,r){const s="----LangSmithFormBoundary"+Math.random().toString(36).slice(2),a=im(),i=()=>this._createNodeFetchBody(e,s),o=()=>this._createMultipartStream(e,s),u=async c=>this.batchIngestCaller.call(async()=>{const l=await c(),d={...this.headers,"Content-Type":`multipart/form-data; boundary=${s}`};r?.apiKey!==void 0&&(d["x-api-key"]=r.apiKey);let h=l;r?.useGzip&&typeof l=="object"&&"pipeThrough"in l&&(h=l.pipeThrough(new CompressionStream("gzip")),d["Content-Encoding"]="gzip");const f=await this._fetch(`${r?.apiUrl??this.apiUrl}/runs/multipart`,{method:"POST",headers:d,body:h,duplex:"half",signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await R(f,"Failed to send multipart request",!0),f});try{let c,l=!1;!a&&!this.multipartStreamingDisabled&&gd()!=="bun"?(l=!0,c=await u(o)):c=await u(i),(!this.multipartStreamingDisabled||l)&&c.status===422&&(r?.apiUrl??this.apiUrl)!==ac&&(console.warn(`Streaming multipart upload to ${r?.apiUrl??this.apiUrl}/runs/multipart failed. This usually means the host does not support chunked uploads. Retrying with a buffered upload for operation "${t}".`),this.multipartStreamingDisabled=!0,c=await u(i))}catch(c){console.warn(`${c.message.trim()}
|
|
67
|
+
|
|
68
|
+
Context: ${t}`)}}async updateRun(e,t,r){D(e),t.inputs&&(t.inputs=await this.processInputs(t.inputs)),t.outputs&&(t.outputs=await this.processOutputs(t.outputs));const s={...t,id:e};if(!this._filterForSampling([s],!0).length)return;if(this.autoBatchTracing&&s.trace_id!==void 0&&s.dotted_order!==void 0){const o=this._cloneCurrentOTELContext();if(t.end_time!==void 0&&s.parent_run_id===void 0&&this.blockOnRootRunFinalization&&!this.manualFlushMode){await this.processRunOperation({action:"update",item:s,otelContext:o,apiKey:r?.apiKey,apiUrl:r?.apiUrl}).catch(console.error);return}else this.processRunOperation({action:"update",item:s,otelContext:o,apiKey:r?.apiKey,apiUrl:r?.apiUrl}).catch(console.error);return}const a={...this.headers,"Content-Type":"application/json"};r?.apiKey!==void 0&&(a["x-api-key"]=r.apiKey),r?.workspaceId!==void 0&&(a["x-tenant-id"]=r.workspaceId);const i=Re(t,`Serializing payload to update run with id: ${e}`);await this.caller.call(async()=>{const o=await this._fetch(`${r?.apiUrl??this.apiUrl}/runs/${e}`,{method:"PATCH",headers:a,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await R(o,"update run",!0),o})}async readRun(e,{loadChildRuns:t}={loadChildRuns:!1}){D(e);let r=await this._get(`/runs/${e}`);return t&&(r=await this._loadChildRuns(r)),r}async getRunUrl({runId:e,run:t,projectOpts:r}){if(t!==void 0){let s;t.session_id?s=t.session_id:r?.projectName?s=(await this.readProject({projectName:r?.projectName})).id:r?.projectId?s=r?.projectId:s=(await this.readProject({projectName:Ae("PROJECT")||"default"})).id;const a=await this._getTenantId();return`${this.getHostUrl()}/o/${a}/projects/p/${s}/r/${t.id}?poll=true`}else if(e!==void 0){const s=await this.readRun(e);if(!s.app_path)throw new Error(`Run ${e} has no app_path`);return`${this.getHostUrl()}${s.app_path}`}else throw new Error("Must provide either runId or run")}async _loadChildRuns(e){const t=await mg(this.listRuns({isRoot:!1,projectId:e.session_id,traceId:e.trace_id})),r={},s={};t.sort((a,i)=>(a?.dotted_order??"").localeCompare(i?.dotted_order??""));for(const a of t){if(a.parent_run_id===null||a.parent_run_id===void 0)throw new Error(`Child run ${a.id} has no parent`);a.dotted_order?.startsWith(e.dotted_order??"")&&a.id!==e.id&&(a.parent_run_id in r||(r[a.parent_run_id]=[]),r[a.parent_run_id].push(a),s[a.id]=a)}e.child_runs=r[e.id]||[];for(const a in r)a!==e.id&&(s[a].child_runs=r[a]);return e}async*listRuns(e){const{projectId:t,projectName:r,parentRunId:s,traceId:a,referenceExampleId:i,startTime:o,executionOrder:u,isRoot:c,runType:l,error:d,id:h,query:f,filter:p,traceFilter:m,treeFilter:g,limit:_,select:y,order:b}=e;let v=[];if(t&&(v=Array.isArray(t)?t:[t]),r){const O=Array.isArray(r)?r:[r],q=await Promise.all(O.map(G=>this.readProject({projectName:G}).then(V=>V.id)));v.push(...q)}const E=["app_path","completion_cost","completion_tokens","dotted_order","end_time","error","events","extra","feedback_stats","first_token_time","id","inputs","name","outputs","parent_run_id","parent_run_ids","prompt_cost","prompt_tokens","reference_example_id","run_type","session_id","start_time","status","tags","total_cost","total_tokens","trace_id"],I={session:v.length?v:null,run_type:l,reference_example:i,query:f,filter:p,trace_filter:m,tree_filter:g,execution_order:u,parent_run:s,start_time:o?o.toISOString():null,error:d,id:h,limit:_,trace:a,select:y||E,is_root:c,order:b};let x=0;for await(const O of this._getCursorPaginatedList("/runs/query",I))if(_){if(x>=_)break;if(O.length+x>_){yield*O.slice(0,_-x);break}x+=O.length,yield*O}else yield*O}async*listGroupRuns(e){const{projectId:t,projectName:r,groupBy:s,filter:a,startTime:i,endTime:o,limit:u,offset:c}=e,d={session_id:t||(await this.readProject({projectName:r})).id,group_by:s,filter:a,start_time:i?i.toISOString():null,end_time:o?o.toISOString():null,limit:Number(u)||100};let h=Number(c)||0;const f="/runs/group",p=`${this.apiUrl}${f}`;for(;;){const m={...d,offset:h},g=Object.fromEntries(Object.entries(m).filter(([I,x])=>x!==void 0)),_=JSON.stringify(g),b=await(await this.caller.call(async()=>{const I=await this._fetch(p,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:_});return await R(I,`Failed to fetch ${f}`),I})).json(),{groups:v,total:E}=b;if(v.length===0)break;for(const I of v)yield I;if(h+=v.length,h>=E)break}}async getRunStats({id:e,trace:t,parentRun:r,runType:s,projectNames:a,projectIds:i,referenceExampleIds:o,startTime:u,endTime:c,error:l,query:d,filter:h,traceFilter:f,treeFilter:p,isRoot:m,dataSourceType:g}){let _=i||[];a&&(_=[...i||[],...await Promise.all(a.map(x=>this.readProject({projectName:x}).then(O=>O.id)))]);const b=Object.fromEntries(Object.entries({id:e,trace:t,parent_run:r,run_type:s,session:_,reference_example:o,start_time:u,end_time:c,error:l,query:d,filter:h,trace_filter:f,tree_filter:p,is_root:m,data_source_type:g}).filter(([x,O])=>O!==void 0)),v=JSON.stringify(b);return await(await this.caller.call(async()=>{const x=await this._fetch(`${this.apiUrl}/runs/stats`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:v});return await R(x,"get run stats"),x})).json()}async shareRun(e,{shareId:t}={}){const r={run_id:e,share_token:t||Dt()};D(e);const s=JSON.stringify(r),i=await(await this.caller.call(async()=>{const o=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:"PUT",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await R(o,"share run"),o})).json();if(i===null||!("share_token"in i))throw new Error("Invalid response from server");return`${this.getHostUrl()}/public/${i.share_token}/r`}async unshareRun(e){D(e),await this.caller.call(async()=>{const t=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await R(t,"unshare run",!0),t})}async readRunSharedLink(e){D(e);const r=await(await this.caller.call(async()=>{const s=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await R(s,"read run shared link"),s})).json();if(!(r===null||!("share_token"in r)))return`${this.getHostUrl()}/public/${r.share_token}/r`}async listSharedRuns(e,{runIds:t}={}){const r=new URLSearchParams({share_token:e});if(t!==void 0)for(const i of t)r.append("id",i);return D(e),await(await this.caller.call(async()=>{const i=await this._fetch(`${this.apiUrl}/public/${e}/runs${r}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await R(i,"list shared runs"),i})).json()}async readDatasetSharedSchema(e,t){if(!e&&!t)throw new Error("Either datasetId or datasetName must be given");e||(e=(await this.readDataset({datasetName:t})).id),D(e);const s=await(await this.caller.call(async()=>{const a=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await R(a,"read dataset shared schema"),a})).json();return s.url=`${this.getHostUrl()}/public/${s.share_token}/d`,s}async shareDataset(e,t){if(!e&&!t)throw new Error("Either datasetId or datasetName must be given");e||(e=(await this.readDataset({datasetName:t})).id);const r={dataset_id:e};D(e);const s=JSON.stringify(r),i=await(await this.caller.call(async()=>{const o=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:"PUT",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await R(o,"share dataset"),o})).json();return i.url=`${this.getHostUrl()}/public/${i.share_token}/d`,i}async unshareDataset(e){D(e),await this.caller.call(async()=>{const t=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await R(t,"unshare dataset",!0),t})}async readSharedDataset(e){return D(e),await(await this.caller.call(async()=>{const s=await this._fetch(`${this.apiUrl}/public/${e}/datasets`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await R(s,"read shared dataset"),s})).json()}async listSharedExamples(e,t){const r={};t?.exampleIds&&(r.id=t.exampleIds);const s=new URLSearchParams;Object.entries(r).forEach(([o,u])=>{Array.isArray(u)?u.forEach(c=>s.append(o,c)):s.append(o,u)});const a=await this.caller.call(async()=>{const o=await this._fetch(`${this.apiUrl}/public/${e}/examples?${s.toString()}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await R(o,"list shared examples"),o}),i=await a.json();if(!a.ok)throw"detail"in i?new Error(`Failed to list shared examples.
|
|
69
|
+
Status: ${a.status}
|
|
70
|
+
Message: ${Array.isArray(i.detail)?i.detail.join(`
|
|
71
|
+
`):"Unspecified error"}`):new Error(`Failed to list shared examples: ${a.status} ${a.statusText}`);return i.map(o=>({...o,_hostUrl:this.getHostUrl()}))}async createProject({projectName:e,description:t=null,metadata:r=null,upsert:s=!1,projectExtra:a=null,referenceDatasetId:i=null}){const o=s?"?upsert=true":"",u=`${this.apiUrl}/sessions${o}`,c=a||{};r&&(c.metadata=r);const l={name:e,extra:c,description:t};i!==null&&(l.reference_dataset_id=i);const d=JSON.stringify(l);return await(await this.caller.call(async()=>{const p=await this._fetch(u,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:d});return await R(p,"create project"),p})).json()}async updateProject(e,{name:t=null,description:r=null,metadata:s=null,projectExtra:a=null,endTime:i=null}){const o=`${this.apiUrl}/sessions/${e}`;let u=a;s&&(u={...u||{},metadata:s});const c=JSON.stringify({name:t,extra:u,description:r,end_time:i?new Date(i).toISOString():null});return await(await this.caller.call(async()=>{const h=await this._fetch(o,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await R(h,"update project"),h})).json()}async hasProject({projectId:e,projectName:t}){let r="/sessions";const s=new URLSearchParams;if(e!==void 0&&t!==void 0)throw new Error("Must provide either projectName or projectId, not both");if(e!==void 0)D(e),r+=`/${e}`;else if(t!==void 0)s.append("name",t);else throw new Error("Must provide projectName or projectId");const a=await this.caller.call(async()=>{const i=await this._fetch(`${this.apiUrl}${r}?${s}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await R(i,"has project"),i});try{const i=await a.json();return a.ok?Array.isArray(i)?i.length>0:!0:!1}catch{return!1}}async readProject({projectId:e,projectName:t,includeStats:r}){let s="/sessions";const a=new URLSearchParams;if(e!==void 0&&t!==void 0)throw new Error("Must provide either projectName or projectId, not both");if(e!==void 0)D(e),s+=`/${e}`;else if(t!==void 0)a.append("name",t);else throw new Error("Must provide projectName or projectId");r!==void 0&&a.append("include_stats",r.toString());const i=await this._get(s,a);let o;if(Array.isArray(i)){if(i.length===0)throw new Error(`Project[id=${e}, name=${t}] not found`);o=i[0]}else o=i;return o}async getProjectUrl({projectId:e,projectName:t}){if(e===void 0&&t===void 0)throw new Error("Must provide either projectName or projectId");const r=await this.readProject({projectId:e,projectName:t}),s=await this._getTenantId();return`${this.getHostUrl()}/o/${s}/projects/p/${r.id}`}async getDatasetUrl({datasetId:e,datasetName:t}){if(e===void 0&&t===void 0)throw new Error("Must provide either datasetName or datasetId");const r=await this.readDataset({datasetId:e,datasetName:t}),s=await this._getTenantId();return`${this.getHostUrl()}/o/${s}/datasets/${r.id}`}async _getTenantId(){if(this._tenantId!==null)return this._tenantId;const e=new URLSearchParams({limit:"1"});for await(const t of this._getPaginated("/sessions",e))return this._tenantId=t[0].tenant_id,t[0].tenant_id;throw new Error("No projects found to resolve tenant.")}async*listProjects({projectIds:e,name:t,nameContains:r,referenceDatasetId:s,referenceDatasetName:a,includeStats:i,datasetVersion:o,referenceFree:u,metadata:c}={}){const l=new URLSearchParams;if(e!==void 0)for(const d of e)l.append("id",d);if(t!==void 0&&l.append("name",t),r!==void 0&&l.append("name_contains",r),s!==void 0)l.append("reference_dataset",s);else if(a!==void 0){const d=await this.readDataset({datasetName:a});l.append("reference_dataset",d.id)}i!==void 0&&l.append("include_stats",i.toString()),o!==void 0&&l.append("dataset_version",o),u!==void 0&&l.append("reference_free",u.toString()),c!==void 0&&l.append("metadata",JSON.stringify(c));for await(const d of this._getPaginated("/sessions",l))yield*d}async deleteProject({projectId:e,projectName:t}){let r;if(e===void 0&&t===void 0)throw new Error("Must provide projectName or projectId");if(e!==void 0&&t!==void 0)throw new Error("Must provide either projectName or projectId, not both");e===void 0?r=(await this.readProject({projectName:t})).id:r=e,D(r),await this.caller.call(async()=>{const s=await this._fetch(`${this.apiUrl}/sessions/${r}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await R(s,`delete session ${r} (${t})`,!0),s})}async uploadCsv({csvFile:e,fileName:t,inputKeys:r,outputKeys:s,description:a,dataType:i,name:o}){const u=`${this.apiUrl}/datasets/upload`,c=new FormData;return c.append("file",e,t),r.forEach(h=>{c.append("input_keys",h)}),s.forEach(h=>{c.append("output_keys",h)}),a&&c.append("description",a),i&&c.append("data_type",i),o&&c.append("name",o),await(await this.caller.call(async()=>{const h=await this._fetch(u,{method:"POST",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await R(h,"upload CSV"),h})).json()}async createDataset(e,{description:t,dataType:r,inputsSchema:s,outputsSchema:a,metadata:i}={}){const o={name:e,description:t,extra:i?{metadata:i}:void 0};r&&(o.data_type=r),s&&(o.inputs_schema_definition=s),a&&(o.outputs_schema_definition=a);const u=JSON.stringify(o);return await(await this.caller.call(async()=>{const d=await this._fetch(`${this.apiUrl}/datasets`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:u});return await R(d,"create dataset"),d})).json()}async readDataset({datasetId:e,datasetName:t}){let r="/datasets";const s=new URLSearchParams({limit:"1"});if(e&&t)throw new Error("Must provide either datasetName or datasetId, not both");if(e)D(e),r+=`/${e}`;else if(t)s.append("name",t);else throw new Error("Must provide datasetName or datasetId");const a=await this._get(r,s);let i;if(Array.isArray(a)){if(a.length===0)throw new Error(`Dataset[id=${e}, name=${t}] not found`);i=a[0]}else i=a;return i}async hasDataset({datasetId:e,datasetName:t}){try{return await this.readDataset({datasetId:e,datasetName:t}),!0}catch(r){if(r instanceof Error&&r.message.toLocaleLowerCase().includes("not found"))return!1;throw r}}async diffDatasetVersions({datasetId:e,datasetName:t,fromVersion:r,toVersion:s}){let a=e;if(a===void 0&&t===void 0)throw new Error("Must provide either datasetName or datasetId");if(a!==void 0&&t!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");a===void 0&&(a=(await this.readDataset({datasetName:t})).id);const i=new URLSearchParams({from_version:typeof r=="string"?r:r.toISOString(),to_version:typeof s=="string"?s:s.toISOString()});return await this._get(`/datasets/${a}/versions/diff`,i)}async readDatasetOpenaiFinetuning({datasetId:e,datasetName:t}){const r="/datasets";if(e===void 0)if(t!==void 0)e=(await this.readDataset({datasetName:t})).id;else throw new Error("Must provide either datasetName or datasetId");return(await(await this._getResponse(`${r}/${e}/openai_ft`)).text()).trim().split(`
|
|
72
|
+
`).map(o=>JSON.parse(o))}async*listDatasets({limit:e=100,offset:t=0,datasetIds:r,datasetName:s,datasetNameContains:a,metadata:i}={}){const o="/datasets",u=new URLSearchParams({limit:e.toString(),offset:t.toString()});if(r!==void 0)for(const c of r)u.append("id",c);s!==void 0&&u.append("name",s),a!==void 0&&u.append("name_contains",a),i!==void 0&&u.append("metadata",JSON.stringify(i));for await(const c of this._getPaginated(o,u))yield*c}async updateDataset(e){const{datasetId:t,datasetName:r,...s}=e;if(!t&&!r)throw new Error("Must provide either datasetName or datasetId");const a=t??(await this.readDataset({datasetName:r})).id;D(a);const i=JSON.stringify(s);return await(await this.caller.call(async()=>{const u=await this._fetch(`${this.apiUrl}/datasets/${a}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await R(u,"update dataset"),u})).json()}async updateDatasetTag(e){const{datasetId:t,datasetName:r,asOf:s,tag:a}=e;if(!t&&!r)throw new Error("Must provide either datasetName or datasetId");const i=t??(await this.readDataset({datasetName:r})).id;D(i);const o=JSON.stringify({as_of:typeof s=="string"?s:s.toISOString(),tag:a});await this.caller.call(async()=>{const u=await this._fetch(`${this.apiUrl}/datasets/${i}/tags`,{method:"PUT",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await R(u,"update dataset tags",!0),u})}async deleteDataset({datasetId:e,datasetName:t}){let r="/datasets",s=e;if(e!==void 0&&t!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");if(t!==void 0&&(s=(await this.readDataset({datasetName:t})).id),s!==void 0)D(s),r+=`/${s}`;else throw new Error("Must provide datasetName or datasetId");await this.caller.call(async()=>{const a=await this._fetch(this.apiUrl+r,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await R(a,`delete ${r}`,!0),a})}async indexDataset({datasetId:e,datasetName:t,tag:r}){let s=e;if(!s&&!t)throw new Error("Must provide either datasetName or datasetId");if(s&&t)throw new Error("Must provide either datasetName or datasetId, not both");s||(s=(await this.readDataset({datasetName:t})).id),D(s);const i=JSON.stringify({tag:r});await(await this.caller.call(async()=>{const u=await this._fetch(`${this.apiUrl}/datasets/${s}/index`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await R(u,"index dataset"),u})).json()}async similarExamples(e,t,r,{filter:s}={}){const a={limit:r,inputs:e};s!==void 0&&(a.filter=s),D(t);const i=JSON.stringify(a);return(await(await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/datasets/${t}/search`,{headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,method:"POST",body:i});return await R(c,"fetch similar examples"),c})).json()).examples}async createExample(e,t,r){if(ic(e)&&(t!==void 0||r!==void 0))throw new Error("Cannot provide outputs or options when using ExampleCreate object");let s=t?r?.datasetId:e.dataset_id;const a=t?r?.datasetName:e.dataset_name;if(s===void 0&&a===void 0)throw new Error("Must provide either datasetName or datasetId");if(s!==void 0&&a!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");s===void 0&&(s=(await this.readDataset({datasetName:a})).id);const i=(t?r?.createdAt:e.created_at)||new Date;let o;ic(e)?o=e:o={inputs:e,outputs:t,created_at:i?.toISOString(),id:r?.exampleId,metadata:r?.metadata,split:r?.split,source_run_id:r?.sourceRunId,use_source_run_io:r?.useSourceRunIO,use_source_run_attachments:r?.useSourceRunAttachments,attachments:r?.attachments};const u=await this._uploadExamplesMultipart(s,[o]);return await this.readExample(u.example_ids?.[0]??Dt())}async createExamples(e){if(Array.isArray(e)){if(e.length===0)return[];const y=e;let b=y[0].dataset_id;const v=y[0].dataset_name;if(b===void 0&&v===void 0)throw new Error("Must provide either datasetName or datasetId");if(b!==void 0&&v!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");b===void 0&&(b=(await this.readDataset({datasetName:v})).id);const E=await this._uploadExamplesMultipart(b,y);return await Promise.all(E.example_ids.map(x=>this.readExample(x)))}const{inputs:t,outputs:r,metadata:s,splits:a,sourceRunIds:i,useSourceRunIOs:o,useSourceRunAttachments:u,attachments:c,exampleIds:l,datasetId:d,datasetName:h}=e;if(t===void 0)throw new Error("Must provide inputs when using legacy parameters");let f=d;const p=h;if(f===void 0&&p===void 0)throw new Error("Must provide either datasetName or datasetId");if(f!==void 0&&p!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");f===void 0&&(f=(await this.readDataset({datasetName:p})).id);const m=t.map((y,b)=>({dataset_id:f,inputs:y,outputs:r?.[b],metadata:s?.[b],split:a?.[b],id:l?.[b],attachments:c?.[b],source_run_id:i?.[b],use_source_run_io:o?.[b],use_source_run_attachments:u?.[b]})),g=await this._uploadExamplesMultipart(f,m);return await Promise.all(g.example_ids.map(y=>this.readExample(y)))}async createLLMExample(e,t,r){return this.createExample({input:e},{output:t},r)}async createChatExample(e,t,r){const s=e.map(i=>uu(i)?cu(i):i),a=uu(t)?cu(t):t;return this.createExample({input:s},{output:a},r)}async readExample(e){D(e);const t=`/examples/${e}`,r=await this._get(t),{attachment_urls:s,...a}=r,i=a;return s&&(i.attachments=Object.entries(s).reduce((o,[u,c])=>(o[u.slice(11)]={presigned_url:c.presigned_url,mime_type:c.mime_type},o),{})),i}async*listExamples({datasetId:e,datasetName:t,exampleIds:r,asOf:s,splits:a,inlineS3Urls:i,metadata:o,limit:u,offset:c,filter:l,includeAttachments:d}={}){let h;if(e!==void 0&&t!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");if(e!==void 0)h=e;else if(t!==void 0)h=(await this.readDataset({datasetName:t})).id;else throw new Error("Must provide a datasetName or datasetId");const f=new URLSearchParams({dataset:h}),p=s?typeof s=="string"?s:s?.toISOString():void 0;p&&f.append("as_of",p);const m=i??!0;if(f.append("inline_s3_urls",m.toString()),r!==void 0)for(const _ of r)f.append("id",_);if(a!==void 0)for(const _ of a)f.append("splits",_);if(o!==void 0){const _=JSON.stringify(o);f.append("metadata",_)}u!==void 0&&f.append("limit",u.toString()),c!==void 0&&f.append("offset",c.toString()),l!==void 0&&f.append("filter",l),d===!0&&["attachment_urls","outputs","metadata"].forEach(_=>f.append("select",_));let g=0;for await(const _ of this._getPaginated("/examples",f)){for(const y of _){const{attachment_urls:b,...v}=y,E=v;b&&(E.attachments=Object.entries(b).reduce((I,[x,O])=>(I[x.slice(11)]={presigned_url:O.presigned_url,mime_type:O.mime_type||void 0},I),{})),yield E,g++}if(u!==void 0&&g>=u)break}}async deleteExample(e){D(e);const t=`/examples/${e}`;await this.caller.call(async()=>{const r=await this._fetch(this.apiUrl+t,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await R(r,`delete ${t}`,!0),r})}async updateExample(e,t){let r;t?r=e:r=e.id,D(r);let s;t?s={id:r,...t}:s=e;let a;return s.dataset_id!==void 0?a=s.dataset_id:a=(await this.readExample(r)).dataset_id,this._updateExamplesMultipart(a,[s])}async updateExamples(e){let t;return e[0].dataset_id===void 0?t=(await this.readExample(e[0].id)).dataset_id:t=e[0].dataset_id,this._updateExamplesMultipart(t,e)}async readDatasetVersion({datasetId:e,datasetName:t,asOf:r,tag:s}){let a;if(e?a=e:a=(await this.readDataset({datasetName:t})).id,D(a),r&&s||!r&&!s)throw new Error("Exactly one of asOf and tag must be specified.");const i=new URLSearchParams;return r!==void 0&&i.append("as_of",typeof r=="string"?r:r.toISOString()),s!==void 0&&i.append("tag",s),await(await this.caller.call(async()=>{const u=await this._fetch(`${this.apiUrl}/datasets/${a}/version?${i.toString()}`,{method:"GET",headers:{...this.headers},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await R(u,"read dataset version"),u})).json()}async listDatasetSplits({datasetId:e,datasetName:t,asOf:r}){let s;if(e===void 0&&t===void 0)throw new Error("Must provide dataset name or ID");if(e!==void 0&&t!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");e===void 0?s=(await this.readDataset({datasetName:t})).id:s=e,D(s);const a=new URLSearchParams,i=r?typeof r=="string"?r:r?.toISOString():void 0;return i&&a.append("as_of",i),await this._get(`/datasets/${s}/splits`,a)}async updateDatasetSplits({datasetId:e,datasetName:t,splitName:r,exampleIds:s,remove:a=!1}){let i;if(e===void 0&&t===void 0)throw new Error("Must provide dataset name or ID");if(e!==void 0&&t!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");e===void 0?i=(await this.readDataset({datasetName:t})).id:i=e,D(i);const o={split_name:r,examples:s.map(c=>(D(c),c)),remove:a},u=JSON.stringify(o);await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/datasets/${i}/splits`,{method:"PUT",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:u});return await R(c,"update dataset splits",!0),c})}async evaluateRun(e,t,{sourceInfo:r,loadChildRuns:s,referenceExample:a}={loadChildRuns:!1}){vd("This method is deprecated and will be removed in future LangSmith versions, use `evaluate` from `langsmith/evaluation` instead.");let i;if(typeof e=="string")i=await this.readRun(e,{loadChildRuns:s});else if(typeof e=="object"&&"id"in e)i=e;else throw new Error(`Invalid run type: ${typeof e}`);i.reference_example_id!==null&&i.reference_example_id!==void 0&&(a=await this.readExample(i.reference_example_id));const o=await t.evaluateRun(i,a),[u,c]=await this._logEvaluationFeedback(o,i,r);return c[0]}async createFeedback(e,t,{score:r,value:s,correction:a,comment:i,sourceInfo:o,feedbackSourceType:u="api",sourceRunId:c,feedbackId:l,feedbackConfig:d,projectId:h,comparativeExperimentId:f}){if(!e&&!h)throw new Error("One of runId or projectId must be provided");if(e&&h)throw new Error("Only one of runId or projectId can be provided");const p={type:u??"api",metadata:o??{}};c!==void 0&&p?.metadata!==void 0&&!p.metadata.__run&&(p.metadata.__run={run_id:c}),p?.metadata!==void 0&&p.metadata.__run?.run_id!==void 0&&D(p.metadata.__run.run_id);const m={id:l??Dt(),run_id:e,key:t,score:sc(r),value:s,correction:a,comment:i,feedback_source:p,comparative_experiment_id:f,feedbackConfig:d,session_id:h},g=JSON.stringify(m),_=`${this.apiUrl}/feedback`;return await this.caller.call(async()=>{const y=await this._fetch(_,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:g});return await R(y,"create feedback",!0),y}),m}async updateFeedback(e,{score:t,value:r,correction:s,comment:a}){const i={};t!=null&&(i.score=sc(t)),r!=null&&(i.value=r),s!=null&&(i.correction=s),a!=null&&(i.comment=a),D(e);const o=JSON.stringify(i);await this.caller.call(async()=>{const u=await this._fetch(`${this.apiUrl}/feedback/${e}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await R(u,"update feedback",!0),u})}async readFeedback(e){D(e);const t=`/feedback/${e}`;return await this._get(t)}async deleteFeedback(e){D(e);const t=`/feedback/${e}`;await this.caller.call(async()=>{const r=await this._fetch(this.apiUrl+t,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await R(r,`delete ${t}`,!0),r})}async*listFeedback({runIds:e,feedbackKeys:t,feedbackSourceTypes:r}={}){const s=new URLSearchParams;if(e)for(const a of e)D(a),s.append("run",a);if(t)for(const a of t)s.append("key",a);if(r)for(const a of r)s.append("source",a);for await(const a of this._getPaginated("/feedback",s))yield*a}async createPresignedFeedbackToken(e,t,{expiration:r,feedbackConfig:s}={}){const a={run_id:e,feedback_key:t,feedback_config:s};r?typeof r=="string"?a.expires_at=r:(r?.hours||r?.minutes||r?.days)&&(a.expires_in=r):a.expires_in={hours:3};const i=JSON.stringify(a);return await(await this.caller.call(async()=>{const u=await this._fetch(`${this.apiUrl}/feedback/tokens`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await R(u,"create presigned feedback token"),u})).json()}async createComparativeExperiment({name:e,experimentIds:t,referenceDatasetId:r,createdAt:s,description:a,metadata:i,id:o}){if(t.length===0)throw new Error("At least one experiment is required");if(r||(r=(await this.readProject({projectId:t[0]})).reference_dataset_id),!r==null)throw new Error("A reference dataset is required");const u={id:o,name:e,experiment_ids:t,reference_dataset_id:r,description:a,created_at:(s??new Date)?.toISOString(),extra:{}};i&&(u.extra.metadata=i);const c=JSON.stringify(u);return(await this.caller.call(async()=>{const d=await this._fetch(`${this.apiUrl}/datasets/comparative`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await R(d,"create comparative experiment"),d})).json()}async*listPresignedFeedbackTokens(e){D(e);const t=new URLSearchParams({run_id:e});for await(const r of this._getPaginated("/feedback/tokens",t))yield*r}_selectEvalResults(e){let t;return"results"in e?t=e.results:Array.isArray(e)?t=e:t=[e],t}async _logEvaluationFeedback(e,t,r){const s=this._selectEvalResults(e),a=[];for(const i of s){let o=r||{};i.evaluatorInfo&&(o={...i.evaluatorInfo,...o});let u=null;i.targetRunId?u=i.targetRunId:t&&(u=t.id),a.push(await this.createFeedback(u,i.key,{score:i.score,value:i.value,comment:i.comment,correction:i.correction,sourceInfo:o,sourceRunId:i.sourceRunId,feedbackConfig:i.feedbackConfig,feedbackSourceType:"model"}))}return[s,a]}async logEvaluationFeedback(e,t,r){const[s]=await this._logEvaluationFeedback(e,t,r);return s}async*listAnnotationQueues(e={}){const{queueIds:t,name:r,nameContains:s,limit:a}=e,i=new URLSearchParams;t&&t.forEach((u,c)=>{D(u,`queueIds[${c}]`),i.append("ids",u)}),r&&i.append("name",r),s&&i.append("name_contains",s),i.append("limit",(a!==void 0?Math.min(a,100):100).toString());let o=0;for await(const u of this._getPaginated("/annotation-queues",i))if(yield*u,o++,a!==void 0&&o>=a)break}async createAnnotationQueue(e){const{name:t,description:r,queueId:s,rubricInstructions:a}=e,i={name:t,description:r,id:s||Dt(),rubric_instructions:a},o=JSON.stringify(Object.fromEntries(Object.entries(i).filter(([c,l])=>l!==void 0)));return(await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/annotation-queues`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await R(c,"create annotation queue"),c})).json()}async readAnnotationQueue(e){return(await this.caller.call(async()=>{const r=await this._fetch(`${this.apiUrl}/annotation-queues/${D(e,"queueId")}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await R(r,"read annotation queue"),r})).json()}async updateAnnotationQueue(e,t){const{name:r,description:s,rubricInstructions:a}=t,i=JSON.stringify({name:r,description:s,rubric_instructions:a});await this.caller.call(async()=>{const o=await this._fetch(`${this.apiUrl}/annotation-queues/${D(e,"queueId")}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await R(o,"update annotation queue",!0),o})}async deleteAnnotationQueue(e){await this.caller.call(async()=>{const t=await this._fetch(`${this.apiUrl}/annotation-queues/${D(e,"queueId")}`,{method:"DELETE",headers:{...this.headers,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await R(t,"delete annotation queue",!0),t})}async addRunsToAnnotationQueue(e,t){const r=JSON.stringify(t.map((s,a)=>D(s,`runIds[${a}]`).toString()));await this.caller.call(async()=>{const s=await this._fetch(`${this.apiUrl}/annotation-queues/${D(e,"queueId")}/runs`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:r});return await R(s,"add runs to annotation queue",!0),s})}async getRunFromAnnotationQueue(e,t){const r=`/annotation-queues/${D(e,"queueId")}/run`;return(await this.caller.call(async()=>{const a=await this._fetch(`${this.apiUrl}${r}/${t}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await R(a,"get run from annotation queue"),a})).json()}async deleteRunFromAnnotationQueue(e,t){await this.caller.call(async()=>{const r=await this._fetch(`${this.apiUrl}/annotation-queues/${D(e,"queueId")}/runs/${D(t,"queueRunId")}`,{method:"DELETE",headers:{...this.headers,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await R(r,"delete run from annotation queue",!0),r})}async getSizeFromAnnotationQueue(e){return(await this.caller.call(async()=>{const r=await this._fetch(`${this.apiUrl}/annotation-queues/${D(e,"queueId")}/size`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await R(r,"get size from annotation queue"),r})).json()}async _currentTenantIsOwner(e){const t=await this._getSettings();return e=="-"||t.tenant_handle===e}async _ownerConflictError(e,t){const r=await this._getSettings();return new Error(`Cannot ${e} for another tenant.
|
|
73
|
+
|
|
74
|
+
Current tenant: ${r.tenant_handle}
|
|
75
|
+
|
|
76
|
+
Requested tenant: ${t}`)}async _getLatestCommitHash(e){const r=await(await this.caller.call(async()=>{const s=await this._fetch(`${this.apiUrl}/commits/${e}/?limit=1&offset=0`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await R(s,"get latest commit hash"),s})).json();if(r.commits.length!==0)return r.commits[0].commit_hash}async _likeOrUnlikePrompt(e,t){const[r,s,a]=ut(e),i=JSON.stringify({like:t});return(await this.caller.call(async()=>{const u=await this._fetch(`${this.apiUrl}/likes/${r}/${s}`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await R(u,`${t?"like":"unlike"} prompt`),u})).json()}async _getPromptUrl(e){const[t,r,s]=ut(e);if(await this._currentTenantIsOwner(t)){const a=await this._getSettings();return s!=="latest"?`${this.getHostUrl()}/prompts/${r}/${s.substring(0,8)}?organizationId=${a.id}`:`${this.getHostUrl()}/prompts/${r}?organizationId=${a.id}`}else return s!=="latest"?`${this.getHostUrl()}/hub/${t}/${r}/${s.substring(0,8)}`:`${this.getHostUrl()}/hub/${t}/${r}`}async promptExists(e){return!!await this.getPrompt(e)}async likePrompt(e){return this._likeOrUnlikePrompt(e,!0)}async unlikePrompt(e){return this._likeOrUnlikePrompt(e,!1)}async*listCommits(e){for await(const t of this._getPaginated(`/commits/${e}/`,new URLSearchParams,r=>r.commits))yield*t}async*listPrompts(e){const t=new URLSearchParams;t.append("sort_field",e?.sortField??"updated_at"),t.append("sort_direction","desc"),t.append("is_archived",(!!e?.isArchived).toString()),e?.isPublic!==void 0&&t.append("is_public",e.isPublic.toString()),e?.query&&t.append("query",e.query);for await(const r of this._getPaginated("/repos",t,s=>s.repos))yield*r}async getPrompt(e){const[t,r,s]=ut(e),i=await(await this.caller.call(async()=>{const o=await this._fetch(`${this.apiUrl}/repos/${t}/${r}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return o?.status===404?null:(await R(o,"get prompt"),o)}))?.json();return i?.repo?i.repo:null}async createPrompt(e,t){const r=await this._getSettings();if(t?.isPublic&&!r.tenant_handle)throw new Error(`Cannot create a public prompt without first
|
|
77
|
+
|
|
78
|
+
creating a LangChain Hub handle.
|
|
79
|
+
You can add a handle by creating a public prompt at:
|
|
80
|
+
|
|
81
|
+
https://smith.langchain.com/prompts`);const[s,a,i]=ut(e);if(!await this._currentTenantIsOwner(s))throw await this._ownerConflictError("create a prompt",s);const o={repo_handle:a,...t?.description&&{description:t.description},...t?.readme&&{readme:t.readme},...t?.tags&&{tags:t.tags},is_public:!!t?.isPublic},u=JSON.stringify(o),c=await this.caller.call(async()=>{const d=await this._fetch(`${this.apiUrl}/repos/`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:u});return await R(d,"create prompt"),d}),{repo:l}=await c.json();return l}async createCommit(e,t,r){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");const[s,a,i]=ut(e),o=r?.parentCommitHash==="latest"||!r?.parentCommitHash?await this._getLatestCommitHash(`${s}/${a}`):r?.parentCommitHash,u={manifest:JSON.parse(JSON.stringify(t)),parent_commit:o},c=JSON.stringify(u),d=await(await this.caller.call(async()=>{const h=await this._fetch(`${this.apiUrl}/commits/${s}/${a}`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await R(h,"create commit"),h})).json();return this._getPromptUrl(`${s}/${a}${d.commit_hash?`:${d.commit_hash}`:""}`)}async updateExamplesMultipart(e,t=[]){return this._updateExamplesMultipart(e,t)}async _updateExamplesMultipart(e,t=[]){if(!await this._getDatasetExamplesMultiPartSupport())throw new Error("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version.");const r=new FormData;for(const i of t){const o=i.id,u={...i.metadata&&{metadata:i.metadata},...i.split&&{split:i.split}},c=Re(u,`Serializing body for example with id: ${o}`),l=new Blob([c],{type:"application/json"});if(r.append(o,l),i.inputs){const d=Re(i.inputs,`Serializing inputs for example with id: ${o}`),h=new Blob([d],{type:"application/json"});r.append(`${o}.inputs`,h)}if(i.outputs){const d=Re(i.outputs,`Serializing outputs whle updating example with id: ${o}`),h=new Blob([d],{type:"application/json"});r.append(`${o}.outputs`,h)}if(i.attachments)for(const[d,h]of Object.entries(i.attachments)){let f,p;Array.isArray(h)?[f,p]=h:(f=h.mimeType,p=h.data);const m=new Blob([p],{type:`${f}; length=${p.byteLength}`});r.append(`${o}.attachment.${d}`,m)}if(i.attachments_operations){const d=Re(i.attachments_operations,`Serializing attachments while updating example with id: ${o}`),h=new Blob([d],{type:"application/json"});r.append(`${o}.attachments_operations`,h)}}const s=e??t[0]?.dataset_id;return(await this.caller.call(async()=>{const i=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${s}/examples`)}`,{method:"PATCH",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:r});return await R(i,"update examples"),i})).json()}async uploadExamplesMultipart(e,t=[]){return this._uploadExamplesMultipart(e,t)}async _uploadExamplesMultipart(e,t=[]){if(!await this._getDatasetExamplesMultiPartSupport())throw new Error("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version.");const r=new FormData;for(const a of t){const i=(a.id??Dt()).toString(),o={created_at:a.created_at,...a.metadata&&{metadata:a.metadata},...a.split&&{split:a.split},...a.source_run_id&&{source_run_id:a.source_run_id},...a.use_source_run_io&&{use_source_run_io:a.use_source_run_io},...a.use_source_run_attachments&&{use_source_run_attachments:a.use_source_run_attachments}},u=Re(o,`Serializing body for uploaded example with id: ${i}`),c=new Blob([u],{type:"application/json"});if(r.append(i,c),a.inputs){const l=Re(a.inputs,`Serializing inputs for uploaded example with id: ${i}`),d=new Blob([l],{type:"application/json"});r.append(`${i}.inputs`,d)}if(a.outputs){const l=Re(a.outputs,`Serializing outputs for uploaded example with id: ${i}`),d=new Blob([l],{type:"application/json"});r.append(`${i}.outputs`,d)}if(a.attachments)for(const[l,d]of Object.entries(a.attachments)){let h,f;Array.isArray(d)?[h,f]=d:(h=d.mimeType,f=d.data);const p=new Blob([f],{type:`${h}; length=${f.byteLength}`});r.append(`${i}.attachment.${l}`,p)}}return(await this.caller.call(async()=>{const a=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${e}/examples`)}`,{method:"POST",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:r});return await R(a,"upload examples"),a})).json()}async updatePrompt(e,t){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");const[r,s]=ut(e);if(!await this._currentTenantIsOwner(r))throw await this._ownerConflictError("update a prompt",r);const a={};if(t?.description!==void 0&&(a.description=t.description),t?.readme!==void 0&&(a.readme=t.readme),t?.tags!==void 0&&(a.tags=t.tags),t?.isPublic!==void 0&&(a.is_public=t.isPublic),t?.isArchived!==void 0&&(a.is_archived=t.isArchived),Object.keys(a).length===0)throw new Error("No valid update options provided");const i=JSON.stringify(a);return(await this.caller.call(async()=>{const u=await this._fetch(`${this.apiUrl}/repos/${r}/${s}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await R(u,"update prompt"),u})).json()}async deletePrompt(e){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");const[t,r,s]=ut(e);if(!await this._currentTenantIsOwner(t))throw await this._ownerConflictError("delete a prompt",t);return(await this.caller.call(async()=>{const i=await this._fetch(`${this.apiUrl}/repos/${t}/${r}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await R(i,"delete prompt"),i})).json()}async pullPromptCommit(e,t){const[r,s,a]=ut(e),o=await(await this.caller.call(async()=>{const u=await this._fetch(`${this.apiUrl}/commits/${r}/${s}/${a}${t?.includeModel?"?include_model=true":""}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await R(u,"pull prompt commit"),u})).json();return{owner:r,repo:s,commit_hash:o.commit_hash,manifest:o.manifest,examples:o.examples}}async _pullPrompt(e,t){const r=await this.pullPromptCommit(e,{includeModel:t?.includeModel});return JSON.stringify(r.manifest)}async pushPrompt(e,t){return await this.promptExists(e)?t&&Object.keys(t).some(s=>s!=="object")&&await this.updatePrompt(e,{description:t?.description,readme:t?.readme,tags:t?.tags,isPublic:t?.isPublic}):await this.createPrompt(e,{description:t?.description,readme:t?.readme,tags:t?.tags,isPublic:t?.isPublic}),t?.object?await this.createCommit(e,t?.object,{parentCommitHash:t?.parentCommitHash}):await this._getPromptUrl(e)}async clonePublicDataset(e,t={}){const{sourceApiUrl:r=this.apiUrl,datasetName:s}=t,[a,i]=this.parseTokenOrUrl(e,r),o=new Pr({apiUrl:a,apiKey:"placeholder"}),u=await o.readSharedDataset(i),c=s||u.name;try{if(await this.hasDataset({datasetId:c})){console.log(`Dataset ${c} already exists in your tenant. Skipping.`);return}}catch{}const l=await o.listSharedExamples(i),d=await this.createDataset(c,{description:u.description,dataType:u.data_type||"kv",inputsSchema:u.inputs_schema_definition??void 0,outputsSchema:u.outputs_schema_definition??void 0});try{await this.createExamples({inputs:l.map(h=>h.inputs),outputs:l.flatMap(h=>h.outputs?[h.outputs]:[]),datasetId:d.id})}catch(h){throw console.error(`An error occurred while creating dataset ${c}. You should delete it manually.`),h}}parseTokenOrUrl(e,t,r=2,s="dataset"){try{return D(e),[t,e]}catch{}try{const i=new URL(e).pathname.split("/").filter(o=>o!=="");if(i.length>=r){const o=i[i.length-r];return[t,o]}else throw new Error(`Invalid public ${s} URL: ${e}`)}catch{throw new Error(`Invalid public ${s} URL or token: ${e}`)}}async awaitPendingTraceBatches(){if(this.manualFlushMode)return console.warn("[WARNING]: When tracing in manual flush mode, you must call `await client.flush()` manually to submit trace batches."),Promise.resolve();await Promise.all([...this.autoBatchQueue.items.map(({itemPromise:e})=>e),this.batchIngestCaller.queue.onIdle()]),this.langSmithToOTELTranslator!==void 0&&await vm()?.DEFAULT_LANGSMITH_SPAN_PROCESSOR?.forceFlush()}}function ic(n){return"dataset_id"in n||"dataset_name"in n}const vg=n=>!!["TRACING_V2","TRACING"].find(t=>Ae(t)==="true"),Ia=Symbol.for("lc:context_variables");function Eg(n){return n.replace(/[-:.]/g,"")}function Id(n,e,t=1){const r=t.toFixed(0).slice(0,3).padStart(3,"0"),s=`${new Date(n).toISOString().slice(0,-1)}${r}Z`;return{dottedOrder:Eg(s)+e,microsecondPrecisionDatestring:s}}class Cn{constructor(e,t,r,s){Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"project_name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"replicas",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.metadata=e,this.tags=t,this.project_name=r,this.replicas=s}static fromHeader(e){const t=e.split(",");let r={},s=[],a,i;for(const o of t){const[u,c]=o.split("="),l=decodeURIComponent(c);u==="langsmith-metadata"?r=JSON.parse(l):u==="langsmith-tags"?s=l.split(","):u==="langsmith-project"?a=l:u==="langsmith-replicas"&&(i=JSON.parse(l))}return new Cn(r,s,a,i)}toHeader(){const e=[];return this.metadata&&Object.keys(this.metadata).length>0&&e.push(`langsmith-metadata=${encodeURIComponent(JSON.stringify(this.metadata))}`),this.tags&&this.tags.length>0&&e.push(`langsmith-tags=${encodeURIComponent(this.tags.join(","))}`),this.project_name&&e.push(`langsmith-project=${encodeURIComponent(this.project_name)}`),e.join(",")}}class Oe{constructor(e){if(Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"run_type",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"project_name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"parent_run",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"parent_run_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"child_runs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"start_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"end_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"extra",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"error",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"serialized",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"inputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"outputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"reference_example_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"events",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"trace_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"dotted_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tracingEnabled",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"execution_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"child_execution_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"attachments",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"replicas",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_serialized_start_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Sg(e)){Object.assign(this,{...e});return}const t=Oe.getDefaultConfig(),{metadata:r,...s}=e,a=s.client??Oe.getSharedClient(),i={...r,...s?.extra?.metadata};if(s.extra={...s.extra,metadata:i},Object.assign(this,{...t,...s,client:a}),this.trace_id||(this.parent_run?this.trace_id=this.parent_run.trace_id??this.id:this.trace_id=this.id),this.replicas=Ig(this.replicas),this.execution_order??=1,this.child_execution_order??=1,!this.dotted_order){const{dottedOrder:o,microsecondPrecisionDatestring:u}=Id(this.start_time,this.id,this.execution_order);this.parent_run?this.dotted_order=this.parent_run.dotted_order+"."+o:this.dotted_order=o,this._serialized_start_time=u}}set metadata(e){this.extra={...this.extra,metadata:{...this.extra?.metadata,...e}}}get metadata(){return this.extra?.metadata}static getDefaultConfig(){return{id:Dt(),run_type:"chain",project_name:fd(),child_runs:[],api_url:Ye("LANGCHAIN_ENDPOINT")??"http://localhost:1984",api_key:Ye("LANGCHAIN_API_KEY"),caller_options:{},start_time:Date.now(),serialized:{},inputs:{},extra:{}}}static getSharedClient(){return Oe.sharedClient||(Oe.sharedClient=new Pr),Oe.sharedClient}createChild(e){const t=this.child_execution_order+1,r=new Oe({...e,parent_run:this,project_name:this.project_name,replicas:this.replicas,client:this.client,tracingEnabled:this.tracingEnabled,execution_order:t,child_execution_order:t});Ia in this&&(r[Ia]=this[Ia]);const s=Symbol.for("lc:child_config"),a=e.extra?.[s]??this.extra[s];if(Tg(a)){const u={...a},c=Og(u.callbacks)?u.callbacks.copy?.():void 0;c&&(Object.assign(c,{_parentRunId:r.id}),c.handlers?.find(xd)?.updateFromRunTree?.(r),u.callbacks=c),r.extra[s]=u}const i=new Set;let o=this;for(;o!=null&&!i.has(o.id);)i.add(o.id),o.child_execution_order=Math.max(o.child_execution_order,t),o=o.parent_run;return this.child_runs.push(r),r}async end(e,t,r=Date.now(),s){this.outputs=this.outputs??e,this.error=this.error??t,this.end_time=this.end_time??r,s&&Object.keys(s).length>0&&(this.extra=this.extra?{...this.extra,metadata:{...this.extra.metadata,...s}}:{metadata:s})}_convertToCreate(e,t,r=!0){const s=e.extra??{};if(s?.runtime?.library===void 0&&(s.runtime||(s.runtime={}),t))for(const[o,u]of Object.entries(t))s.runtime[o]||(s.runtime[o]=u);let a,i;return r?(i=e.parent_run?.id??e.parent_run_id,a=[]):(a=e.child_runs.map(o=>this._convertToCreate(o,t,r)),i=void 0),{id:e.id,name:e.name,start_time:e._serialized_start_time??e.start_time,end_time:e.end_time,run_type:e.run_type,reference_example_id:e.reference_example_id,extra:s,serialized:e.serialized,error:e.error,inputs:e.inputs,outputs:e.outputs,session_name:e.project_name,child_runs:a,parent_run_id:i,trace_id:e.trace_id,dotted_order:e.dotted_order,tags:e.tags,attachments:e.attachments,events:e.events}}_remapForProject(e,t,r=!0){const s=this._convertToCreate(this,t,r);if(e===this.project_name)return s;const a=d=>Zo(`${d}:${e}`,Zo.DNS),i=a(s.id),o=s.trace_id?a(s.trace_id):void 0,u=s.parent_run_id?a(s.parent_run_id):void 0;let c;if(s.dotted_order){const d=Ag(s.dotted_order),h=[];for(let p=0;p<d.length-1;p++){const[m,g]=d[p],_=a(g);h.push(m.toISOString().replace(/[-:]/g,"").replace(".","")+_)}const[f]=d[d.length-1];h.push(f.toISOString().replace(/[-:]/g,"").replace(".","")+i),c=h.join(".")}else c=void 0;return{...s,id:i,trace_id:o,parent_run_id:u,dotted_order:c,session_name:e}}async postRun(e=!0){try{const t=_d();if(this.replicas&&this.replicas.length>0)for(const{projectName:r,apiKey:s,apiUrl:a,workspaceId:i}of this.replicas){const o=this._remapForProject(r??this.project_name,t,!0);await this.client.createRun(o,{apiKey:s,apiUrl:a,workspaceId:i})}else{const r=this._convertToCreate(this,t,e);await this.client.createRun(r)}if(!e){vd("Posting with excludeChildRuns=false is deprecated and will be removed in a future version.");for(const r of this.child_runs)await r.postRun(!1)}}catch(t){console.error(`Error in postRun for run ${this.id}:`,t)}}async patchRun(e){if(this.replicas&&this.replicas.length>0)for(const{projectName:t,apiKey:r,apiUrl:s,workspaceId:a,updates:i}of this.replicas){const o=this._remapForProject(t??this.project_name),u={id:o.id,outputs:o.outputs,error:o.error,parent_run_id:o.parent_run_id,session_name:o.session_name,reference_example_id:o.reference_example_id,end_time:o.end_time,dotted_order:o.dotted_order,trace_id:o.trace_id,events:o.events,tags:o.tags,extra:o.extra,attachments:this.attachments,...i};e?.excludeInputs||(u.inputs=o.inputs),await this.client.updateRun(o.id,u,{apiKey:r,apiUrl:s,workspaceId:a})}else try{const t={end_time:this.end_time,error:this.error,outputs:this.outputs,parent_run_id:this.parent_run?.id??this.parent_run_id,reference_example_id:this.reference_example_id,extra:this.extra,events:this.events,dotted_order:this.dotted_order,trace_id:this.trace_id,tags:this.tags,attachments:this.attachments,session_name:this.project_name};e?.excludeInputs||(t.inputs=this.inputs),await this.client.updateRun(this.id,t)}catch(t){console.error(`Error in patchRun for run ${this.id}`,t)}}toJSON(){return this._convertToCreate(this,void 0,!1)}addEvent(e){this.events||(this.events=[]),typeof e=="string"?this.events.push({name:"event",time:new Date().toISOString(),message:e}):this.events.push({...e,time:e.time??new Date().toISOString()})}static fromRunnableConfig(e,t){const r=e?.callbacks;let s,a,i,o=vg();if(r){const c=r?.getParentRunId?.()??"",l=r?.handlers?.find(d=>d?.name=="langchain_tracer");s=l?.getRun?.(c),a=l?.projectName,i=l?.client,o=o||!!l}return s?new Oe({name:s.name,id:s.id,trace_id:s.trace_id,dotted_order:s.dotted_order,client:i,tracingEnabled:o,project_name:a,tags:[...new Set((s?.tags??[]).concat(e?.tags??[]))],extra:{metadata:{...s?.extra?.metadata,...e?.metadata}}}).createChild(t):new Oe({...t,client:i,tracingEnabled:o,project_name:a})}static fromDottedOrder(e){return this.fromHeaders({"langsmith-trace":e})}static fromHeaders(e,t){const r="get"in e&&typeof e.get=="function"?{"langsmith-trace":e.get("langsmith-trace"),baggage:e.get("baggage")}:e,s=r["langsmith-trace"];if(!s||typeof s!="string")return;const a=s.trim(),i=a.split(".").map(c=>{const[l,d]=c.split("Z");return{strTime:l,time:Date.parse(l+"Z"),uuid:d}}),o=i[0].uuid,u={...t,name:t?.name??"parent",run_type:t?.run_type??"chain",start_time:t?.start_time??Date.now(),id:i.at(-1)?.uuid,trace_id:o,dotted_order:a};if(r.baggage&&typeof r.baggage=="string"){const c=Cn.fromHeader(r.baggage);u.metadata=c.metadata,u.tags=c.tags,u.project_name=c.project_name,u.replicas=c.replicas}return new Oe(u)}toHeaders(e){const t={"langsmith-trace":this.dotted_order,baggage:new Cn(this.extra?.metadata,this.tags,this.project_name,this.replicas).toHeader()};if(e)for(const[r,s]of Object.entries(t))e.set(r,s);return t}}Object.defineProperty(Oe,"sharedClient",{enumerable:!0,configurable:!0,writable:!0,value:null});function Sg(n){return n!=null&&typeof n.createChild=="function"&&typeof n.postRun=="function"}function xd(n){return typeof n=="object"&&n!=null&&typeof n.name=="string"&&n.name==="langchain_tracer"}function oc(n){return Array.isArray(n)&&n.some(e=>xd(e))}function Og(n){return typeof n=="object"&&n!=null&&Array.isArray(n.handlers)}function Tg(n){return n!=null&&typeof n.callbacks=="object"&&(oc(n.callbacks?.handlers)||oc(n.callbacks))}function Ag(n){return n.split(".").map(t=>{const r=t.slice(0,-36),s=t.slice(-36),a=parseInt(r.slice(0,4)),i=parseInt(r.slice(4,6))-1,o=parseInt(r.slice(6,8)),u=parseInt(r.slice(9,11)),c=parseInt(r.slice(11,13)),l=parseInt(r.slice(13,15)),d=parseInt(r.slice(15,21));return[new Date(a,i,o,u,c,l,d/1e3),s]})}function Pg(){const n=Ye("LANGSMITH_RUNS_ENDPOINTS");if(!n)return[];try{const e=JSON.parse(n);if(Array.isArray(e)){const t=[];for(const r of e){if(typeof r!="object"||r===null){console.warn(`Invalid item type in LANGSMITH_RUNS_ENDPOINTS: expected object, got ${typeof r}`);continue}if(typeof r.api_url!="string"){console.warn(`Invalid api_url type in LANGSMITH_RUNS_ENDPOINTS: expected string, got ${typeof r.api_url}`);continue}if(typeof r.api_key!="string"){console.warn(`Invalid api_key type in LANGSMITH_RUNS_ENDPOINTS: expected string, got ${typeof r.api_key}`);continue}t.push({apiUrl:r.api_url.replace(/\/$/,""),apiKey:r.api_key})}return t}else if(typeof e=="object"&&e!==null){xg(e);const t=[];for(const[r,s]of Object.entries(e)){const a=r.replace(/\/$/,"");if(typeof s=="string")t.push({apiUrl:a,apiKey:s});else{console.warn(`Invalid value type in LANGSMITH_RUNS_ENDPOINTS for URL ${r}: expected string, got ${typeof s}`);continue}}return t}else return console.warn(`Invalid LANGSMITH_RUNS_ENDPOINTS – must be valid JSON array of objects with api_url and api_key properties, or object mapping url->apiKey, got ${typeof e}`),[]}catch(e){if(og(e))throw e;return console.warn("Invalid LANGSMITH_RUNS_ENDPOINTS – must be valid JSON array of objects with api_url and api_key properties, or object mapping url->apiKey"),[]}}function Ig(n){return n?n.map(e=>Array.isArray(e)?{projectName:e[0],updates:e[1]}:e):Pg()}function xg(n){if(Object.keys(n).length>0&&Ae("ENDPOINT"))throw new ig}var Rg={};const kg=()=>typeof window<"u"&&typeof window.document<"u",Cg=()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope",$g=()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),Ji=()=>typeof Deno<"u",Ng=()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!Ji(),jg=()=>{let n;return kg()?n="browser":Ng()?n="node":Cg()?n="webworker":$g()?n="jsdom":Ji()?n="deno":n="other",n};let xa;function Lg(){return xa===void 0&&(xa={library:"langchain-js",runtime:jg()}),xa}function pt(n){try{return typeof process<"u"?Rg?.[n]:Ji()?Deno?.env.get(n):void 0}catch{return}}class Mg{}function Ug(n){return"lc_prefer_streaming"in n&&n.lc_prefer_streaming}class Ur extends Mg{get lc_namespace(){return["langchain_core","callbacks",this.name]}get lc_secrets(){}get lc_attributes(){}get lc_aliases(){}get lc_serializable_keys(){}static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,ad(this.constructor)]}constructor(e){super(),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"lc_kwargs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"ignoreLLM",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"ignoreChain",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"ignoreAgent",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"ignoreRetriever",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"ignoreCustomEvent",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"raiseError",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"awaitHandlers",{enumerable:!0,configurable:!0,writable:!0,value:pt("LANGCHAIN_CALLBACKS_BACKGROUND")==="false"}),this.lc_kwargs=e||{},e&&(this.ignoreLLM=e.ignoreLLM??this.ignoreLLM,this.ignoreChain=e.ignoreChain??this.ignoreChain,this.ignoreAgent=e.ignoreAgent??this.ignoreAgent,this.ignoreRetriever=e.ignoreRetriever??this.ignoreRetriever,this.ignoreCustomEvent=e.ignoreCustomEvent??this.ignoreCustomEvent,this.raiseError=e.raiseError??this.raiseError,this.awaitHandlers=this.raiseError||(e._awaitHandler??this.awaitHandlers))}copy(){return new this.constructor(this)}toJSON(){return It.prototype.toJSON.call(this)}toJSONNotImplemented(){return It.prototype.toJSONNotImplemented.call(this)}static fromMethods(e){class t extends Ur{constructor(){super(),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:nt()}),Object.assign(this,e)}}return new t}}const Dg=n=>{const e=n;return e!==void 0&&typeof e.copy=="function"&&typeof e.name=="string"&&typeof e.awaitHandlers=="boolean"},Fg=n=>{if(n)return n.events=n.events??[],n.child_runs=n.child_runs??[],n};function ii(n,e){if(n)return new Oe({...n,start_time:n._serialized_start_time??n.start_time,parent_run:ii(e),child_runs:n.child_runs.map(t=>ii(t)).filter(t=>t!==void 0),extra:{...n.extra,runtime:Lg()},tracingEnabled:!1})}function Ra(n,e){return n&&!Array.isArray(n)&&typeof n=="object"?n:{[e]:n}}function nr(n){return typeof n._addRunToRunMap=="function"}class Dr extends Ur{constructor(e){super(...arguments),Object.defineProperty(this,"runMap",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"runTreeMap",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"usesRunTreeMap",{enumerable:!0,configurable:!0,writable:!0,value:!1})}copy(){return this}getRunById(e){if(e!==void 0)return this.usesRunTreeMap?Fg(this.runTreeMap.get(e)):this.runMap.get(e)}stringifyError(e){return e instanceof Error?e.message+(e?.stack?`
|
|
82
|
+
|
|
83
|
+
${e.stack}`:""):typeof e=="string"?e:`${e}`}_addChildRun(e,t){e.child_runs.push(t)}_addRunToRunMap(e){const{dottedOrder:t,microsecondPrecisionDatestring:r}=Id(new Date(e.start_time).getTime(),e.id,e.execution_order),s={...e},a=this.getRunById(s.parent_run_id);if(s.parent_run_id!==void 0?a&&(this._addChildRun(a,s),a.child_execution_order=Math.max(a.child_execution_order,s.child_execution_order),s.trace_id=a.trace_id,a.dotted_order!==void 0&&(s.dotted_order=[a.dotted_order,t].join("."),s._serialized_start_time=r)):(s.trace_id=s.id,s.dotted_order=t,s._serialized_start_time=r),this.usesRunTreeMap){const i=ii(s,a);i!==void 0&&this.runTreeMap.set(s.id,i)}else this.runMap.set(s.id,s);return s}async _endTrace(e){const t=e.parent_run_id!==void 0&&this.getRunById(e.parent_run_id);t?t.child_execution_order=Math.max(t.child_execution_order,e.child_execution_order):await this.persistRun(e),await this.onRunUpdate?.(e),this.usesRunTreeMap?this.runTreeMap.delete(e.id):this.runMap.delete(e.id)}_getExecutionOrder(e){const t=e!==void 0&&this.getRunById(e);return t?t.child_execution_order+1:1}_createRunForLLMStart(e,t,r,s,a,i,o,u){const c=this._getExecutionOrder(s),l=Date.now(),d=o?{...a,metadata:o}:a,h={id:r,name:u??e.id[e.id.length-1],parent_run_id:s,start_time:l,serialized:e,events:[{name:"start",time:new Date(l).toISOString()}],inputs:{prompts:t},execution_order:c,child_runs:[],child_execution_order:c,run_type:"llm",extra:d??{},tags:i||[]};return this._addRunToRunMap(h)}async handleLLMStart(e,t,r,s,a,i,o,u){const c=this.getRunById(r)??this._createRunForLLMStart(e,t,r,s,a,i,o,u);return await this.onRunCreate?.(c),await this.onLLMStart?.(c),c}_createRunForChatModelStart(e,t,r,s,a,i,o,u){const c=this._getExecutionOrder(s),l=Date.now(),d=o?{...a,metadata:o}:a,h={id:r,name:u??e.id[e.id.length-1],parent_run_id:s,start_time:l,serialized:e,events:[{name:"start",time:new Date(l).toISOString()}],inputs:{messages:t},execution_order:c,child_runs:[],child_execution_order:c,run_type:"llm",extra:d??{},tags:i||[]};return this._addRunToRunMap(h)}async handleChatModelStart(e,t,r,s,a,i,o,u){const c=this.getRunById(r)??this._createRunForChatModelStart(e,t,r,s,a,i,o,u);return await this.onRunCreate?.(c),await this.onLLMStart?.(c),c}async handleLLMEnd(e,t,r,s,a){const i=this.getRunById(t);if(!i||i?.run_type!=="llm")throw new Error("No LLM run to end.");return i.end_time=Date.now(),i.outputs=e,i.events.push({name:"end",time:new Date(i.end_time).toISOString()}),i.extra={...i.extra,...a},await this.onLLMEnd?.(i),await this._endTrace(i),i}async handleLLMError(e,t,r,s,a){const i=this.getRunById(t);if(!i||i?.run_type!=="llm")throw new Error("No LLM run to end.");return i.end_time=Date.now(),i.error=this.stringifyError(e),i.events.push({name:"error",time:new Date(i.end_time).toISOString()}),i.extra={...i.extra,...a},await this.onLLMError?.(i),await this._endTrace(i),i}_createRunForChainStart(e,t,r,s,a,i,o,u){const c=this._getExecutionOrder(s),l=Date.now(),d={id:r,name:u??e.id[e.id.length-1],parent_run_id:s,start_time:l,serialized:e,events:[{name:"start",time:new Date(l).toISOString()}],inputs:t,execution_order:c,child_execution_order:c,run_type:o??"chain",child_runs:[],extra:i?{metadata:i}:{},tags:a||[]};return this._addRunToRunMap(d)}async handleChainStart(e,t,r,s,a,i,o,u){const c=this.getRunById(r)??this._createRunForChainStart(e,t,r,s,a,i,o,u);return await this.onRunCreate?.(c),await this.onChainStart?.(c),c}async handleChainEnd(e,t,r,s,a){const i=this.getRunById(t);if(!i)throw new Error("No chain run to end.");return i.end_time=Date.now(),i.outputs=Ra(e,"output"),i.events.push({name:"end",time:new Date(i.end_time).toISOString()}),a?.inputs!==void 0&&(i.inputs=Ra(a.inputs,"input")),await this.onChainEnd?.(i),await this._endTrace(i),i}async handleChainError(e,t,r,s,a){const i=this.getRunById(t);if(!i)throw new Error("No chain run to end.");return i.end_time=Date.now(),i.error=this.stringifyError(e),i.events.push({name:"error",time:new Date(i.end_time).toISOString()}),a?.inputs!==void 0&&(i.inputs=Ra(a.inputs,"input")),await this.onChainError?.(i),await this._endTrace(i),i}_createRunForToolStart(e,t,r,s,a,i,o){const u=this._getExecutionOrder(s),c=Date.now(),l={id:r,name:o??e.id[e.id.length-1],parent_run_id:s,start_time:c,serialized:e,events:[{name:"start",time:new Date(c).toISOString()}],inputs:{input:t},execution_order:u,child_execution_order:u,run_type:"tool",child_runs:[],extra:i?{metadata:i}:{},tags:a||[]};return this._addRunToRunMap(l)}async handleToolStart(e,t,r,s,a,i,o){const u=this.getRunById(r)??this._createRunForToolStart(e,t,r,s,a,i,o);return await this.onRunCreate?.(u),await this.onToolStart?.(u),u}async handleToolEnd(e,t){const r=this.getRunById(t);if(!r||r?.run_type!=="tool")throw new Error("No tool run to end");return r.end_time=Date.now(),r.outputs={output:e},r.events.push({name:"end",time:new Date(r.end_time).toISOString()}),await this.onToolEnd?.(r),await this._endTrace(r),r}async handleToolError(e,t){const r=this.getRunById(t);if(!r||r?.run_type!=="tool")throw new Error("No tool run to end");return r.end_time=Date.now(),r.error=this.stringifyError(e),r.events.push({name:"error",time:new Date(r.end_time).toISOString()}),await this.onToolError?.(r),await this._endTrace(r),r}async handleAgentAction(e,t){const r=this.getRunById(t);if(!r||r?.run_type!=="chain")return;const s=r;s.actions=s.actions||[],s.actions.push(e),s.events.push({name:"agent_action",time:new Date().toISOString(),kwargs:{action:e}}),await this.onAgentAction?.(r)}async handleAgentEnd(e,t){const r=this.getRunById(t);!r||r?.run_type!=="chain"||(r.events.push({name:"agent_end",time:new Date().toISOString(),kwargs:{action:e}}),await this.onAgentEnd?.(r))}_createRunForRetrieverStart(e,t,r,s,a,i,o){const u=this._getExecutionOrder(s),c=Date.now(),l={id:r,name:o??e.id[e.id.length-1],parent_run_id:s,start_time:c,serialized:e,events:[{name:"start",time:new Date(c).toISOString()}],inputs:{query:t},execution_order:u,child_execution_order:u,run_type:"retriever",child_runs:[],extra:i?{metadata:i}:{},tags:a||[]};return this._addRunToRunMap(l)}async handleRetrieverStart(e,t,r,s,a,i,o){const u=this.getRunById(r)??this._createRunForRetrieverStart(e,t,r,s,a,i,o);return await this.onRunCreate?.(u),await this.onRetrieverStart?.(u),u}async handleRetrieverEnd(e,t){const r=this.getRunById(t);if(!r||r?.run_type!=="retriever")throw new Error("No retriever run to end");return r.end_time=Date.now(),r.outputs={documents:e},r.events.push({name:"end",time:new Date(r.end_time).toISOString()}),await this.onRetrieverEnd?.(r),await this._endTrace(r),r}async handleRetrieverError(e,t){const r=this.getRunById(t);if(!r||r?.run_type!=="retriever")throw new Error("No retriever run to end");return r.end_time=Date.now(),r.error=this.stringifyError(e),r.events.push({name:"error",time:new Date(r.end_time).toISOString()}),await this.onRetrieverError?.(r),await this._endTrace(r),r}async handleText(e,t){const r=this.getRunById(t);!r||r?.run_type!=="chain"||(r.events.push({name:"text",time:new Date().toISOString(),kwargs:{text:e}}),await this.onText?.(r))}async handleLLMNewToken(e,t,r,s,a,i){const o=this.getRunById(r);if(!o||o?.run_type!=="llm")throw new Error('Invalid "runId" provided to "handleLLMNewToken" callback.');return o.events.push({name:"new_token",time:new Date().toISOString(),kwargs:{token:e,idx:t,chunk:i?.chunk}}),await this.onLLMNewToken?.(o,e,{chunk:i?.chunk}),o}}var yn={exports:{}};yn.exports;var uc;function Bg(){return uc||(uc=1,(function(n){const t=(a=0)=>i=>`\x1B[${38+a};5;${i}m`,r=(a=0)=>(i,o,u)=>`\x1B[${38+a};2;${i};${o};${u}m`;function s(){const a=new Map,i={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};i.color.gray=i.color.blackBright,i.bgColor.bgGray=i.bgColor.bgBlackBright,i.color.grey=i.color.blackBright,i.bgColor.bgGrey=i.bgColor.bgBlackBright;for(const[o,u]of Object.entries(i)){for(const[c,l]of Object.entries(u))i[c]={open:`\x1B[${l[0]}m`,close:`\x1B[${l[1]}m`},u[c]=i[c],a.set(l[0],l[1]);Object.defineProperty(i,o,{value:u,enumerable:!1})}return Object.defineProperty(i,"codes",{value:a,enumerable:!1}),i.color.close="\x1B[39m",i.bgColor.close="\x1B[49m",i.color.ansi256=t(),i.color.ansi16m=r(),i.bgColor.ansi256=t(10),i.bgColor.ansi16m=r(10),Object.defineProperties(i,{rgbToAnsi256:{value:(o,u,c)=>o===u&&u===c?o<8?16:o>248?231:Math.round((o-8)/247*24)+232:16+36*Math.round(o/255*5)+6*Math.round(u/255*5)+Math.round(c/255*5),enumerable:!1},hexToRgb:{value:o=>{const u=/(?<colorString>[a-f\d]{6}|[a-f\d]{3})/i.exec(o.toString(16));if(!u)return[0,0,0];let{colorString:c}=u.groups;c.length===3&&(c=c.split("").map(d=>d+d).join(""));const l=Number.parseInt(c,16);return[l>>16&255,l>>8&255,l&255]},enumerable:!1},hexToAnsi256:{value:o=>i.rgbToAnsi256(...i.hexToRgb(o)),enumerable:!1}}),i}Object.defineProperty(n,"exports",{enumerable:!0,get:s})})(yn)),yn.exports}var zg=Bg();const Rd=Rr(zg);function ye(n,e){return`${n.open}${e}${n.close}`}function je(n,e){try{return JSON.stringify(n,null,2)}catch{return e}}function cc(n){return typeof n=="string"?n.trim():n==null?n:je(n,n.toString())}function ct(n){if(!n.end_time)return"";const e=n.end_time-n.start_time;return e<1e3?`${e}ms`:`${(e/1e3).toFixed(2)}s`}const{color:Se}=Rd;class lc extends Dr{constructor(){super(...arguments),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"console_callback_handler"})}persistRun(e){return Promise.resolve()}getParents(e){const t=[];let r=e;for(;r.parent_run_id;){const s=this.runMap.get(r.parent_run_id);if(s)t.push(s),r=s;else break}return t}getBreadcrumbs(e){const r=[...this.getParents(e).reverse(),e].map((s,a,i)=>{const o=`${s.execution_order}:${s.run_type}:${s.name}`;return a===i.length-1?ye(Rd.bold,o):o}).join(" > ");return ye(Se.grey,r)}onChainStart(e){const t=this.getBreadcrumbs(e);console.log(`${ye(Se.green,"[chain/start]")} [${t}] Entering Chain run with input: ${je(e.inputs,"[inputs]")}`)}onChainEnd(e){const t=this.getBreadcrumbs(e);console.log(`${ye(Se.cyan,"[chain/end]")} [${t}] [${ct(e)}] Exiting Chain run with output: ${je(e.outputs,"[outputs]")}`)}onChainError(e){const t=this.getBreadcrumbs(e);console.log(`${ye(Se.red,"[chain/error]")} [${t}] [${ct(e)}] Chain run errored with error: ${je(e.error,"[error]")}`)}onLLMStart(e){const t=this.getBreadcrumbs(e),r="prompts"in e.inputs?{prompts:e.inputs.prompts.map(s=>s.trim())}:e.inputs;console.log(`${ye(Se.green,"[llm/start]")} [${t}] Entering LLM run with input: ${je(r,"[inputs]")}`)}onLLMEnd(e){const t=this.getBreadcrumbs(e);console.log(`${ye(Se.cyan,"[llm/end]")} [${t}] [${ct(e)}] Exiting LLM run with output: ${je(e.outputs,"[response]")}`)}onLLMError(e){const t=this.getBreadcrumbs(e);console.log(`${ye(Se.red,"[llm/error]")} [${t}] [${ct(e)}] LLM run errored with error: ${je(e.error,"[error]")}`)}onToolStart(e){const t=this.getBreadcrumbs(e);console.log(`${ye(Se.green,"[tool/start]")} [${t}] Entering Tool run with input: "${cc(e.inputs.input)}"`)}onToolEnd(e){const t=this.getBreadcrumbs(e);console.log(`${ye(Se.cyan,"[tool/end]")} [${t}] [${ct(e)}] Exiting Tool run with output: "${cc(e.outputs?.output)}"`)}onToolError(e){const t=this.getBreadcrumbs(e);console.log(`${ye(Se.red,"[tool/error]")} [${t}] [${ct(e)}] Tool run errored with error: ${je(e.error,"[error]")}`)}onRetrieverStart(e){const t=this.getBreadcrumbs(e);console.log(`${ye(Se.green,"[retriever/start]")} [${t}] Entering Retriever run with input: ${je(e.inputs,"[inputs]")}`)}onRetrieverEnd(e){const t=this.getBreadcrumbs(e);console.log(`${ye(Se.cyan,"[retriever/end]")} [${t}] [${ct(e)}] Exiting Retriever run with output: ${je(e.outputs,"[outputs]")}`)}onRetrieverError(e){const t=this.getBreadcrumbs(e);console.log(`${ye(Se.red,"[retriever/error]")} [${t}] [${ct(e)}] Retriever run errored with error: ${je(e.error,"[error]")}`)}onAgentAction(e){const t=e,r=this.getBreadcrumbs(e);console.log(`${ye(Se.blue,"[agent/action]")} [${r}] Agent selected action: ${je(t.actions[t.actions.length-1],"[action]")}`)}}let ka;const qg=()=>{if(ka===void 0){const n=pt("LANGCHAIN_CALLBACKS_BACKGROUND")==="false"?{blockOnRootRunFinalization:!0}:{};ka=new Pr(n)}return ka};class vr extends Dr{constructor(e={}){super(e),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"langchain_tracer"}),Object.defineProperty(this,"projectName",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"exampleId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"replicas",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"usesRunTreeMap",{enumerable:!0,configurable:!0,writable:!0,value:!0});const{exampleId:t,projectName:r,client:s,replicas:a}=e;this.projectName=r??fd(),this.replicas=a,this.exampleId=t,this.client=s??qg();const i=vr.getTraceableRunTree();i&&this.updateFromRunTree(i)}async persistRun(e){}async onRunCreate(e){await this.getRunTreeWithTracingConfig(e.id)?.postRun()}async onRunUpdate(e){await this.getRunTreeWithTracingConfig(e.id)?.patchRun()}getRun(e){return this.runTreeMap.get(e)}updateFromRunTree(e){this.runTreeMap.set(e.id,e);let t=e;const r=new Set;for(;t.parent_run&&!(r.has(t.id)||(r.add(t.id),!t.parent_run));)t=t.parent_run;r.clear();const s=[t];for(;s.length>0;){const a=s.shift();!a||r.has(a.id)||(r.add(a.id),this.runTreeMap.set(a.id,a),a.child_runs&&s.push(...a.child_runs))}this.client=e.client??this.client,this.replicas=e.replicas??this.replicas,this.projectName=e.project_name??this.projectName,this.exampleId=e.reference_example_id??this.exampleId}getRunTreeWithTracingConfig(e){const t=this.runTreeMap.get(e);if(t)return new Oe({...t,client:this.client,project_name:this.projectName,replicas:this.replicas,reference_example_id:this.exampleId,tracingEnabled:!0})}static getTraceableRunTree(){try{return hp(!0)}catch{return}}}const kd=Symbol.for("ls:tracing_async_local_storage"),bn=Symbol.for("lc:context_variables"),Hg=n=>{globalThis[kd]=n},Ir=()=>globalThis[kd];let Er;function Gg(){const n="default"in at?at.default:at;return new n({autoStart:!0,concurrency:1})}function Jg(){return typeof Er>"u"&&(Er=Gg()),Er}async function ie(n,e){if(e===!0){const t=Ir();t!==void 0?await t.run(void 0,async()=>n()):await n()}else Er=Jg(),Er.add(async()=>{const t=Ir();t!==void 0?await t.run(void 0,async()=>n()):await n()})}const Wg=n=>!!["LANGSMITH_TRACING_V2","LANGCHAIN_TRACING_V2","LANGSMITH_TRACING","LANGCHAIN_TRACING"].find(t=>pt(t)==="true");function Cd(n){const e=Ir();return e===void 0?void 0:e.getStore()?.[bn]?.[n]}const Zg=Symbol("lc:configure_hooks"),Kg=()=>Cd(Zg)||[];class Vg{setHandler(e){return this.setHandlers([e])}}class is{constructor(e,t,r,s,a,i,o,u){Object.defineProperty(this,"runId",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"handlers",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"inheritableHandlers",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:s}),Object.defineProperty(this,"inheritableTags",{enumerable:!0,configurable:!0,writable:!0,value:a}),Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:i}),Object.defineProperty(this,"inheritableMetadata",{enumerable:!0,configurable:!0,writable:!0,value:o}),Object.defineProperty(this,"_parentRunId",{enumerable:!0,configurable:!0,writable:!0,value:u})}get parentRunId(){return this._parentRunId}async handleText(e){await Promise.all(this.handlers.map(t=>ie(async()=>{try{await t.handleText?.(e,this.runId,this._parentRunId,this.tags)}catch(r){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleText: ${r}`),t.raiseError)throw r}},t.awaitHandlers)))}async handleCustomEvent(e,t,r,s,a){await Promise.all(this.handlers.map(i=>ie(async()=>{try{await i.handleCustomEvent?.(e,t,this.runId,this.tags,this.metadata)}catch(o){if((i.raiseError?console.error:console.warn)(`Error in handler ${i.constructor.name}, handleCustomEvent: ${o}`),i.raiseError)throw o}},i.awaitHandlers)))}}class Xg extends is{getChild(e){const t=new Pe(this.runId);return t.setHandlers(this.inheritableHandlers),t.addTags(this.inheritableTags),t.addMetadata(this.inheritableMetadata),e&&t.addTags([e],!1),t}async handleRetrieverEnd(e){await Promise.all(this.handlers.map(t=>ie(async()=>{if(!t.ignoreRetriever)try{await t.handleRetrieverEnd?.(e,this.runId,this._parentRunId,this.tags)}catch(r){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleRetriever`),t.raiseError)throw r}},t.awaitHandlers)))}async handleRetrieverError(e){await Promise.all(this.handlers.map(t=>ie(async()=>{if(!t.ignoreRetriever)try{await t.handleRetrieverError?.(e,this.runId,this._parentRunId,this.tags)}catch(r){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleRetrieverError: ${r}`),t.raiseError)throw e}},t.awaitHandlers)))}}class dc extends is{async handleLLMNewToken(e,t,r,s,a,i){await Promise.all(this.handlers.map(o=>ie(async()=>{if(!o.ignoreLLM)try{await o.handleLLMNewToken?.(e,t??{prompt:0,completion:0},this.runId,this._parentRunId,this.tags,i)}catch(u){if((o.raiseError?console.error:console.warn)(`Error in handler ${o.constructor.name}, handleLLMNewToken: ${u}`),o.raiseError)throw u}},o.awaitHandlers)))}async handleLLMError(e,t,r,s,a){await Promise.all(this.handlers.map(i=>ie(async()=>{if(!i.ignoreLLM)try{await i.handleLLMError?.(e,this.runId,this._parentRunId,this.tags,a)}catch(o){if((i.raiseError?console.error:console.warn)(`Error in handler ${i.constructor.name}, handleLLMError: ${o}`),i.raiseError)throw o}},i.awaitHandlers)))}async handleLLMEnd(e,t,r,s,a){await Promise.all(this.handlers.map(i=>ie(async()=>{if(!i.ignoreLLM)try{await i.handleLLMEnd?.(e,this.runId,this._parentRunId,this.tags,a)}catch(o){if((i.raiseError?console.error:console.warn)(`Error in handler ${i.constructor.name}, handleLLMEnd: ${o}`),i.raiseError)throw o}},i.awaitHandlers)))}}class Qg extends is{getChild(e){const t=new Pe(this.runId);return t.setHandlers(this.inheritableHandlers),t.addTags(this.inheritableTags),t.addMetadata(this.inheritableMetadata),e&&t.addTags([e],!1),t}async handleChainError(e,t,r,s,a){await Promise.all(this.handlers.map(i=>ie(async()=>{if(!i.ignoreChain)try{await i.handleChainError?.(e,this.runId,this._parentRunId,this.tags,a)}catch(o){if((i.raiseError?console.error:console.warn)(`Error in handler ${i.constructor.name}, handleChainError: ${o}`),i.raiseError)throw o}},i.awaitHandlers)))}async handleChainEnd(e,t,r,s,a){await Promise.all(this.handlers.map(i=>ie(async()=>{if(!i.ignoreChain)try{await i.handleChainEnd?.(e,this.runId,this._parentRunId,this.tags,a)}catch(o){if((i.raiseError?console.error:console.warn)(`Error in handler ${i.constructor.name}, handleChainEnd: ${o}`),i.raiseError)throw o}},i.awaitHandlers)))}async handleAgentAction(e){await Promise.all(this.handlers.map(t=>ie(async()=>{if(!t.ignoreAgent)try{await t.handleAgentAction?.(e,this.runId,this._parentRunId,this.tags)}catch(r){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleAgentAction: ${r}`),t.raiseError)throw r}},t.awaitHandlers)))}async handleAgentEnd(e){await Promise.all(this.handlers.map(t=>ie(async()=>{if(!t.ignoreAgent)try{await t.handleAgentEnd?.(e,this.runId,this._parentRunId,this.tags)}catch(r){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleAgentEnd: ${r}`),t.raiseError)throw r}},t.awaitHandlers)))}}class Yg extends is{getChild(e){const t=new Pe(this.runId);return t.setHandlers(this.inheritableHandlers),t.addTags(this.inheritableTags),t.addMetadata(this.inheritableMetadata),e&&t.addTags([e],!1),t}async handleToolError(e){await Promise.all(this.handlers.map(t=>ie(async()=>{if(!t.ignoreAgent)try{await t.handleToolError?.(e,this.runId,this._parentRunId,this.tags)}catch(r){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleToolError: ${r}`),t.raiseError)throw r}},t.awaitHandlers)))}async handleToolEnd(e){await Promise.all(this.handlers.map(t=>ie(async()=>{if(!t.ignoreAgent)try{await t.handleToolEnd?.(e,this.runId,this._parentRunId,this.tags)}catch(r){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleToolEnd: ${r}`),t.raiseError)throw r}},t.awaitHandlers)))}}class Pe extends Vg{constructor(e,t){super(),Object.defineProperty(this,"handlers",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"inheritableHandlers",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"inheritableTags",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"inheritableMetadata",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"callback_manager"}),Object.defineProperty(this,"_parentRunId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.handlers=t?.handlers??this.handlers,this.inheritableHandlers=t?.inheritableHandlers??this.inheritableHandlers,this.tags=t?.tags??this.tags,this.inheritableTags=t?.inheritableTags??this.inheritableTags,this.metadata=t?.metadata??this.metadata,this.inheritableMetadata=t?.inheritableMetadata??this.inheritableMetadata,this._parentRunId=e}getParentRunId(){return this._parentRunId}async handleLLMStart(e,t,r=void 0,s=void 0,a=void 0,i=void 0,o=void 0,u=void 0){return Promise.all(t.map(async(c,l)=>{const d=l===0&&r?r:nt();return await Promise.all(this.handlers.map(h=>{if(!h.ignoreLLM)return nr(h)&&h._createRunForLLMStart(e,[c],d,this._parentRunId,a,this.tags,this.metadata,u),ie(async()=>{try{await h.handleLLMStart?.(e,[c],d,this._parentRunId,a,this.tags,this.metadata,u)}catch(f){if((h.raiseError?console.error:console.warn)(`Error in handler ${h.constructor.name}, handleLLMStart: ${f}`),h.raiseError)throw f}},h.awaitHandlers)})),new dc(d,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChatModelStart(e,t,r=void 0,s=void 0,a=void 0,i=void 0,o=void 0,u=void 0){return Promise.all(t.map(async(c,l)=>{const d=l===0&&r?r:nt();return await Promise.all(this.handlers.map(h=>{if(!h.ignoreLLM)return nr(h)&&h._createRunForChatModelStart(e,[c],d,this._parentRunId,a,this.tags,this.metadata,u),ie(async()=>{try{if(h.handleChatModelStart)await h.handleChatModelStart?.(e,[c],d,this._parentRunId,a,this.tags,this.metadata,u);else if(h.handleLLMStart){const f=cd(c);await h.handleLLMStart?.(e,[f],d,this._parentRunId,a,this.tags,this.metadata,u)}}catch(f){if((h.raiseError?console.error:console.warn)(`Error in handler ${h.constructor.name}, handleLLMStart: ${f}`),h.raiseError)throw f}},h.awaitHandlers)})),new dc(d,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChainStart(e,t,r=nt(),s=void 0,a=void 0,i=void 0,o=void 0){return await Promise.all(this.handlers.map(u=>{if(!u.ignoreChain)return nr(u)&&u._createRunForChainStart(e,t,r,this._parentRunId,this.tags,this.metadata,s,o),ie(async()=>{try{await u.handleChainStart?.(e,t,r,this._parentRunId,this.tags,this.metadata,s,o)}catch(c){if((u.raiseError?console.error:console.warn)(`Error in handler ${u.constructor.name}, handleChainStart: ${c}`),u.raiseError)throw c}},u.awaitHandlers)})),new Qg(r,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleToolStart(e,t,r=nt(),s=void 0,a=void 0,i=void 0,o=void 0){return await Promise.all(this.handlers.map(u=>{if(!u.ignoreAgent)return nr(u)&&u._createRunForToolStart(e,t,r,this._parentRunId,this.tags,this.metadata,o),ie(async()=>{try{await u.handleToolStart?.(e,t,r,this._parentRunId,this.tags,this.metadata,o)}catch(c){if((u.raiseError?console.error:console.warn)(`Error in handler ${u.constructor.name}, handleToolStart: ${c}`),u.raiseError)throw c}},u.awaitHandlers)})),new Yg(r,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleRetrieverStart(e,t,r=nt(),s=void 0,a=void 0,i=void 0,o=void 0){return await Promise.all(this.handlers.map(u=>{if(!u.ignoreRetriever)return nr(u)&&u._createRunForRetrieverStart(e,t,r,this._parentRunId,this.tags,this.metadata,o),ie(async()=>{try{await u.handleRetrieverStart?.(e,t,r,this._parentRunId,this.tags,this.metadata,o)}catch(c){if((u.raiseError?console.error:console.warn)(`Error in handler ${u.constructor.name}, handleRetrieverStart: ${c}`),u.raiseError)throw c}},u.awaitHandlers)})),new Xg(r,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleCustomEvent(e,t,r,s,a){await Promise.all(this.handlers.map(i=>ie(async()=>{if(!i.ignoreCustomEvent)try{await i.handleCustomEvent?.(e,t,r,this.tags,this.metadata)}catch(o){if((i.raiseError?console.error:console.warn)(`Error in handler ${i.constructor.name}, handleCustomEvent: ${o}`),i.raiseError)throw o}},i.awaitHandlers)))}addHandler(e,t=!0){this.handlers.push(e),t&&this.inheritableHandlers.push(e)}removeHandler(e){this.handlers=this.handlers.filter(t=>t!==e),this.inheritableHandlers=this.inheritableHandlers.filter(t=>t!==e)}setHandlers(e,t=!0){this.handlers=[],this.inheritableHandlers=[];for(const r of e)this.addHandler(r,t)}addTags(e,t=!0){this.removeTags(e),this.tags.push(...e),t&&this.inheritableTags.push(...e)}removeTags(e){this.tags=this.tags.filter(t=>!e.includes(t)),this.inheritableTags=this.inheritableTags.filter(t=>!e.includes(t))}addMetadata(e,t=!0){this.metadata={...this.metadata,...e},t&&(this.inheritableMetadata={...this.inheritableMetadata,...e})}removeMetadata(e){for(const t of Object.keys(e))delete this.metadata[t],delete this.inheritableMetadata[t]}copy(e=[],t=!0){const r=new Pe(this._parentRunId);for(const s of this.handlers){const a=this.inheritableHandlers.includes(s);r.addHandler(s,a)}for(const s of this.tags){const a=this.inheritableTags.includes(s);r.addTags([s],a)}for(const s of Object.keys(this.metadata)){const a=Object.keys(this.inheritableMetadata).includes(s);r.addMetadata({[s]:this.metadata[s]},a)}for(const s of e)r.handlers.filter(a=>a.name==="console_callback_handler").some(a=>a.name===s.name)||r.addHandler(s,t);return r}static fromHandlers(e){class t extends Ur{constructor(){super(),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:nt()}),Object.assign(this,e)}}const r=new this;return r.addHandler(new t),r}static configure(e,t,r,s,a,i,o){return this._configureSync(e,t,r,s,a,i,o)}static _configureSync(e,t,r,s,a,i,o){let u;(e||t)&&(Array.isArray(e)||!e?(u=new Pe,u.setHandlers(e?.map($n)??[],!0)):u=e,u=u.copy(Array.isArray(t)?t.map($n):t?.handlers,!1));const c=pt("LANGCHAIN_VERBOSE")==="true"||o?.verbose,l=vr.getTraceableRunTree()?.tracingEnabled||Wg(),d=l||(pt("LANGCHAIN_TRACING")??!1);if(c||d){if(u||(u=new Pe),c&&!u.handlers.some(h=>h.name===lc.prototype.name)){const h=new lc;u.addHandler(h,!0)}if(d&&!u.handlers.some(h=>h.name==="langchain_tracer")&&l){const h=new vr;u.addHandler(h,!0)}if(l){const h=vr.getTraceableRunTree();h&&u._parentRunId===void 0&&(u._parentRunId=h.id,u.handlers.find(p=>p.name==="langchain_tracer")?.updateFromRunTree(h))}}for(const{contextVar:h,inheritable:f=!0,handlerClass:p,envVar:m}of Kg()){const g=m&&pt(m)==="true"&&p;let _;const y=h!==void 0?Cd(h):void 0;y&&Dg(y)?_=y:g&&(_=new p({})),_!==void 0&&(u||(u=new Pe),u.handlers.some(b=>b.name===_.name)||u.addHandler(_,f))}return(r||s)&&u&&(u.addTags(r??[]),u.addTags(s??[],!1)),(a||i)&&u&&(u.addMetadata(a??{}),u.addMetadata(i??{},!1)),u}}function $n(n){return"name"in n?n:Ur.fromMethods(n)}class e_{getStore(){}run(e,t){return t()}enterWith(e){}}const t_=new e_,hc=Symbol.for("lc:child_config");class r_{getInstance(){return Ir()??t_}getRunnableConfig(){return this.getInstance().getStore()?.extra?.[hc]}runWithConfig(e,t,r){const s=Pe._configureSync(e?.callbacks,void 0,e?.tags,void 0,e?.metadata),a=this.getInstance(),i=a.getStore(),o=s?.getParentRunId(),u=s?.handlers?.find(l=>l?.name==="langchain_tracer");let c;return u&&o?c=u.getRunTreeWithTracingConfig(o):r||(c=new Oe({name:"<runnable_lambda>",tracingEnabled:!1})),c&&(c.extra={...c.extra,[hc]:e}),i!==void 0&&i[bn]!==void 0&&(c===void 0&&(c={}),c[bn]=i[bn]),a.run(c,t)}initializeGlobalInstance(e){Ir()===void 0&&Hg(e)}}const gt=new r_,Ca=25;async function qe(n){return Pe._configureSync(n?.callbacks,void 0,n?.tags,void 0,n?.metadata)}function fc(...n){const e={};for(const t of n.filter(r=>!!r))for(const r of Object.keys(t))if(r==="metadata")e[r]={...e[r],...t[r]};else if(r==="tags"){const s=e[r]??[];e[r]=[...new Set(s.concat(t[r]??[]))]}else if(r==="configurable")e[r]={...e[r],...t[r]};else if(r==="timeout")e.timeout===void 0?e.timeout=t.timeout:t.timeout!==void 0&&(e.timeout=Math.min(e.timeout,t.timeout));else if(r==="signal")e.signal===void 0?e.signal=t.signal:t.signal!==void 0&&("any"in AbortSignal?e.signal=AbortSignal.any([e.signal,t.signal]):e.signal=t.signal);else if(r==="callbacks"){const s=e.callbacks,a=t.callbacks;if(Array.isArray(a))if(!s)e.callbacks=a;else if(Array.isArray(s))e.callbacks=s.concat(a);else{const i=s.copy();for(const o of a)i.addHandler($n(o),!0);e.callbacks=i}else if(a)if(!s)e.callbacks=a;else if(Array.isArray(s)){const i=a.copy();for(const o of s)i.addHandler($n(o),!0);e.callbacks=i}else e.callbacks=new Pe(a._parentRunId,{handlers:s.handlers.concat(a.handlers),inheritableHandlers:s.inheritableHandlers.concat(a.inheritableHandlers),tags:Array.from(new Set(s.tags.concat(a.tags))),inheritableTags:Array.from(new Set(s.inheritableTags.concat(a.inheritableTags))),metadata:{...s.metadata,...a.metadata}})}else{const s=r;e[s]=t[s]??e[s]}return e}const n_=new Set(["string","number","boolean"]);function Z(n){const e=gt.getRunnableConfig();let t={tags:[],metadata:{},recursionLimit:25,runId:void 0};if(e){const{runId:r,runName:s,...a}=e;t=Object.entries(a).reduce((i,[o,u])=>(u!==void 0&&(i[o]=u),i),t)}if(n&&(t=Object.entries(n).reduce((r,[s,a])=>(a!==void 0&&(r[s]=a),r),t)),t?.configurable)for(const r of Object.keys(t.configurable))n_.has(typeof t.configurable[r])&&!t.metadata?.[r]&&(t.metadata||(t.metadata={}),t.metadata[r]=t.configurable[r]);if(t.timeout!==void 0){if(t.timeout<=0)throw new Error("Timeout must be a positive number");const r=AbortSignal.timeout(t.timeout);t.signal!==void 0?"any"in AbortSignal&&(t.signal=AbortSignal.any([t.signal,r])):t.signal=r,delete t.timeout}return t}function ge(n={},{callbacks:e,maxConcurrency:t,recursionLimit:r,runName:s,configurable:a,runId:i}={}){const o=Z(n);return e!==void 0&&(delete o.runName,o.callbacks=e),r!==void 0&&(o.recursionLimit=r),t!==void 0&&(o.maxConcurrency=t),s!==void 0&&(o.runName=s),a!==void 0&&(o.configurable={...o.configurable,...a}),i!==void 0&&delete o.runId,o}function Ht(n){return n?{configurable:n.configurable,recursionLimit:n.recursionLimit,callbacks:n.callbacks,tags:n.tags,metadata:n.metadata,maxConcurrency:n.maxConcurrency,timeout:n.timeout,signal:n.signal}:void 0}async function _t(n,e){if(e===void 0)return n;let t;return Promise.race([n.catch(r=>{if(!e?.aborted)throw r}),new Promise((r,s)=>{t=()=>{s(new Error("Aborted"))},e.addEventListener("abort",t),e.aborted&&s(new Error("Aborted"))})]).finally(()=>e.removeEventListener("abort",t))}class $e extends ReadableStream{constructor(){super(...arguments),Object.defineProperty(this,"reader",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}ensureReader(){this.reader||(this.reader=this.getReader())}async next(){this.ensureReader();try{const e=await this.reader.read();return e.done?(this.reader.releaseLock(),{done:!0,value:void 0}):{done:!1,value:e.value}}catch(e){throw this.reader.releaseLock(),e}}async return(){if(this.ensureReader(),this.locked){const e=this.reader.cancel();this.reader.releaseLock(),await e}return{done:!0,value:void 0}}async throw(e){if(this.ensureReader(),this.locked){const t=this.reader.cancel();this.reader.releaseLock(),await t}throw e}[Symbol.asyncIterator](){return this}async[Symbol.asyncDispose](){await this.return()}static fromReadableStream(e){const t=e.getReader();return new $e({start(r){return s();function s(){return t.read().then(({done:a,value:i})=>{if(a){r.close();return}return r.enqueue(i),s()})}},cancel(){t.releaseLock()}})}static fromAsyncGenerator(e){return new $e({async pull(t){const{value:r,done:s}=await e.next();s&&t.close(),t.enqueue(r)},async cancel(t){await e.return(t)}})}}function $d(n,e=2){const t=Array.from({length:e},()=>[]);return t.map(async function*(s){for(;;)if(s.length===0){const a=await n.next();for(const i of t)i.push(a)}else{if(s[0].done)return;yield s.shift().value}})}function os(n,e){if(Array.isArray(n)&&Array.isArray(e))return n.concat(e);if(typeof n=="string"&&typeof e=="string")return n+e;if(typeof n=="number"&&typeof e=="number")return n+e;if("concat"in n&&typeof n.concat=="function")return n.concat(e);if(typeof n=="object"&&typeof e=="object"){const t={...n};for(const[r,s]of Object.entries(e))r in t&&!Array.isArray(t[r])?t[r]=os(t[r],s):t[r]=s;return t}else throw new Error(`Cannot concat ${typeof n} and ${typeof e}`)}class Vt{constructor(e){Object.defineProperty(this,"generator",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"setup",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"config",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"signal",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"firstResult",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"firstResultUsed",{enumerable:!0,configurable:!0,writable:!0,value:!1}),this.generator=e.generator,this.config=e.config,this.signal=e.signal??this.config?.signal,this.setup=new Promise((t,r)=>{gt.runWithConfig(Ht(e.config),async()=>{this.firstResult=e.generator.next(),e.startSetup?this.firstResult.then(e.startSetup).then(t,r):this.firstResult.then(s=>t(void 0),r)},!0)})}async next(...e){return this.signal?.throwIfAborted(),this.firstResultUsed?gt.runWithConfig(Ht(this.config),this.signal?async()=>_t(this.generator.next(...e),this.signal):async()=>this.generator.next(...e),!0):(this.firstResultUsed=!0,this.firstResult)}async return(e){return this.generator.return(e)}async throw(e){return this.generator.throw(e)}[Symbol.asyncIterator](){return this}async[Symbol.asyncDispose](){await this.return()}}async function s_(n,e,t,r,...s){const a=new Vt({generator:e,startSetup:t,signal:r}),i=await a.setup;return{output:n(a,i,...s),setup:i}}class lt{constructor(e){Object.defineProperty(this,"ops",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.ops=e.ops??[]}concat(e){const t=this.ops.concat(e.ops),r=xn({},t);return new xr({ops:t,state:r[r.length-1].newDocument})}}class xr extends lt{constructor(e){super(e),Object.defineProperty(this,"state",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.state=e.state}concat(e){const t=this.ops.concat(e.ops),r=xn(this.state,e.ops);return new xr({ops:t,state:r[r.length-1].newDocument})}static fromRunLogPatch(e){const t=xn({},e.ops);return new xr({ops:e.ops,state:t[t.length-1].newDocument})}}const a_=n=>n.name==="log_stream_tracer";async function pc(n,e){if(e==="original")throw new Error("Do not assign inputs with original schema drop the key for now. When inputs are added to streamLog they should be added with standardized schema for streaming events.");const{inputs:t}=n;if(["retriever","llm","prompt"].includes(n.run_type))return t;if(!(Object.keys(t).length===1&&t?.input===""))return t.input}async function mc(n,e){const{outputs:t}=n;return e==="original"||["retriever","llm","prompt"].includes(n.run_type)?t:t!==void 0&&Object.keys(t).length===1&&t?.output!==void 0?t.output:t}function i_(n){return n!==void 0&&n.message!==void 0}class gc extends Dr{constructor(e){super({_awaitHandler:!0,...e}),Object.defineProperty(this,"autoClose",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"includeNames",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"includeTypes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"includeTags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeNames",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeTypes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeTags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_schemaFormat",{enumerable:!0,configurable:!0,writable:!0,value:"original"}),Object.defineProperty(this,"rootId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"keyMapByRunId",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"counterMapByRunName",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"transformStream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"writer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"receiveStream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"log_stream_tracer"}),Object.defineProperty(this,"lc_prefer_streaming",{enumerable:!0,configurable:!0,writable:!0,value:!0}),this.autoClose=e?.autoClose??!0,this.includeNames=e?.includeNames,this.includeTypes=e?.includeTypes,this.includeTags=e?.includeTags,this.excludeNames=e?.excludeNames,this.excludeTypes=e?.excludeTypes,this.excludeTags=e?.excludeTags,this._schemaFormat=e?._schemaFormat??this._schemaFormat,this.transformStream=new TransformStream,this.writer=this.transformStream.writable.getWriter(),this.receiveStream=$e.fromReadableStream(this.transformStream.readable)}[Symbol.asyncIterator](){return this.receiveStream}async persistRun(e){}_includeRun(e){if(e.id===this.rootId)return!1;const t=e.tags??[];let r=this.includeNames===void 0&&this.includeTags===void 0&&this.includeTypes===void 0;return this.includeNames!==void 0&&(r=r||this.includeNames.includes(e.name)),this.includeTypes!==void 0&&(r=r||this.includeTypes.includes(e.run_type)),this.includeTags!==void 0&&(r=r||t.find(s=>this.includeTags?.includes(s))!==void 0),this.excludeNames!==void 0&&(r=r&&!this.excludeNames.includes(e.name)),this.excludeTypes!==void 0&&(r=r&&!this.excludeTypes.includes(e.run_type)),this.excludeTags!==void 0&&(r=r&&t.every(s=>!this.excludeTags?.includes(s))),r}async*tapOutputIterable(e,t){for await(const r of t){if(e!==this.rootId){const s=this.keyMapByRunId[e];s&&await this.writer.write(new lt({ops:[{op:"add",path:`/logs/${s}/streamed_output/-`,value:r}]}))}yield r}}async onRunCreate(e){if(this.rootId===void 0&&(this.rootId=e.id,await this.writer.write(new lt({ops:[{op:"replace",path:"",value:{id:e.id,name:e.name,type:e.run_type,streamed_output:[],final_output:void 0,logs:{}}}]}))),!this._includeRun(e))return;this.counterMapByRunName[e.name]===void 0&&(this.counterMapByRunName[e.name]=0),this.counterMapByRunName[e.name]+=1;const t=this.counterMapByRunName[e.name];this.keyMapByRunId[e.id]=t===1?e.name:`${e.name}:${t}`;const r={id:e.id,name:e.name,type:e.run_type,tags:e.tags??[],metadata:e.extra?.metadata??{},start_time:new Date(e.start_time).toISOString(),streamed_output:[],streamed_output_str:[],final_output:void 0,end_time:void 0};this._schemaFormat==="streaming_events"&&(r.inputs=await pc(e,this._schemaFormat)),await this.writer.write(new lt({ops:[{op:"add",path:`/logs/${this.keyMapByRunId[e.id]}`,value:r}]}))}async onRunUpdate(e){try{const t=this.keyMapByRunId[e.id];if(t===void 0)return;const r=[];this._schemaFormat==="streaming_events"&&r.push({op:"replace",path:`/logs/${t}/inputs`,value:await pc(e,this._schemaFormat)}),r.push({op:"add",path:`/logs/${t}/final_output`,value:await mc(e,this._schemaFormat)}),e.end_time!==void 0&&r.push({op:"add",path:`/logs/${t}/end_time`,value:new Date(e.end_time).toISOString()});const s=new lt({ops:r});await this.writer.write(s)}finally{if(e.id===this.rootId){const t=new lt({ops:[{op:"replace",path:"/final_output",value:await mc(e,this._schemaFormat)}]});await this.writer.write(t),this.autoClose&&await this.writer.close()}}}async onLLMNewToken(e,t,r){const s=this.keyMapByRunId[e.id];if(s===void 0)return;const a=e.inputs.messages!==void 0;let i;a?i_(r?.chunk)?i=r?.chunk:i=new mt({id:`run-${e.id}`,content:t}):i=t;const o=new lt({ops:[{op:"add",path:`/logs/${s}/streamed_output_str/-`,value:t},{op:"add",path:`/logs/${s}/streamed_output/-`,value:i}]});await this.writer.write(o)}}const _c="__run";class Gt{constructor(e){Object.defineProperty(this,"text",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"generationInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.text=e.text,this.generationInfo=e.generationInfo}concat(e){return new Gt({text:this.text+e.text,generationInfo:{...this.generationInfo,...e.generationInfo}})}}class Rt extends Gt{constructor(e){super(e),Object.defineProperty(this,"message",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.message=e.message}concat(e){return new Rt({text:this.text+e.text,generationInfo:{...this.generationInfo,...e.generationInfo},message:this.message.concat(e.message)})}}function rn({name:n,serialized:e}){return n!==void 0?n:e?.name!==void 0?e.name:e?.id!==void 0&&Array.isArray(e?.id)?e.id[e.id.length-1]:"Unnamed"}const o_=n=>n.name==="event_stream_tracer";class u_ extends Dr{constructor(e){super({_awaitHandler:!0,...e}),Object.defineProperty(this,"autoClose",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"includeNames",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"includeTypes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"includeTags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeNames",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeTypes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeTags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"runInfoMap",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"tappedPromises",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"transformStream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"writer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"receiveStream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"event_stream_tracer"}),Object.defineProperty(this,"lc_prefer_streaming",{enumerable:!0,configurable:!0,writable:!0,value:!0}),this.autoClose=e?.autoClose??!0,this.includeNames=e?.includeNames,this.includeTypes=e?.includeTypes,this.includeTags=e?.includeTags,this.excludeNames=e?.excludeNames,this.excludeTypes=e?.excludeTypes,this.excludeTags=e?.excludeTags,this.transformStream=new TransformStream,this.writer=this.transformStream.writable.getWriter(),this.receiveStream=$e.fromReadableStream(this.transformStream.readable)}[Symbol.asyncIterator](){return this.receiveStream}async persistRun(e){}_includeRun(e){const t=e.tags??[];let r=this.includeNames===void 0&&this.includeTags===void 0&&this.includeTypes===void 0;return this.includeNames!==void 0&&(r=r||this.includeNames.includes(e.name)),this.includeTypes!==void 0&&(r=r||this.includeTypes.includes(e.runType)),this.includeTags!==void 0&&(r=r||t.find(s=>this.includeTags?.includes(s))!==void 0),this.excludeNames!==void 0&&(r=r&&!this.excludeNames.includes(e.name)),this.excludeTypes!==void 0&&(r=r&&!this.excludeTypes.includes(e.runType)),this.excludeTags!==void 0&&(r=r&&t.every(s=>!this.excludeTags?.includes(s))),r}async*tapOutputIterable(e,t){const r=await t.next();if(r.done)return;const s=this.runInfoMap.get(e);if(s===void 0){yield r.value;return}function a(o,u){return o==="llm"&&typeof u=="string"?new Gt({text:u}):u}let i=this.tappedPromises.get(e);if(i===void 0){let o;i=new Promise(u=>{o=u}),this.tappedPromises.set(e,i);try{const u={event:`on_${s.runType}_stream`,run_id:e,name:s.name,tags:s.tags,metadata:s.metadata,data:{}};await this.send({...u,data:{chunk:a(s.runType,r.value)}},s),yield r.value;for await(const c of t)s.runType!=="tool"&&s.runType!=="retriever"&&await this.send({...u,data:{chunk:a(s.runType,c)}},s),yield c}finally{o()}}else{yield r.value;for await(const o of t)yield o}}async send(e,t){this._includeRun(t)&&await this.writer.write(e)}async sendEndEvent(e,t){const r=this.tappedPromises.get(e.run_id);r!==void 0?r.then(()=>{this.send(e,t)}):await this.send(e,t)}async onLLMStart(e){const t=rn(e),r=e.inputs.messages!==void 0?"chat_model":"llm",s={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:r,inputs:e.inputs};this.runInfoMap.set(e.id,s);const a=`on_${r}_start`;await this.send({event:a,data:{input:e.inputs},name:t,tags:e.tags??[],run_id:e.id,metadata:e.extra?.metadata??{}},s)}async onLLMNewToken(e,t,r){const s=this.runInfoMap.get(e.id);let a,i;if(s===void 0)throw new Error(`onLLMNewToken: Run ID ${e.id} not found in run map.`);if(this.runInfoMap.size!==1){if(s.runType==="chat_model")i="on_chat_model_stream",r?.chunk===void 0?a=new mt({content:t,id:`run-${e.id}`}):a=r.chunk.message;else if(s.runType==="llm")i="on_llm_stream",r?.chunk===void 0?a=new Gt({text:t}):a=r.chunk;else throw new Error(`Unexpected run type ${s.runType}`);await this.send({event:i,data:{chunk:a},run_id:e.id,name:s.name,tags:s.tags,metadata:s.metadata},s)}}async onLLMEnd(e){const t=this.runInfoMap.get(e.id);this.runInfoMap.delete(e.id);let r;if(t===void 0)throw new Error(`onLLMEnd: Run ID ${e.id} not found in run map.`);const s=e.outputs?.generations;let a;if(t.runType==="chat_model"){for(const i of s??[]){if(a!==void 0)break;a=i[0]?.message}r="on_chat_model_end"}else if(t.runType==="llm")a={generations:s?.map(i=>i.map(o=>({text:o.text,generationInfo:o.generationInfo}))),llmOutput:e.outputs?.llmOutput??{}},r="on_llm_end";else throw new Error(`onLLMEnd: Unexpected run type: ${t.runType}`);await this.sendEndEvent({event:r,data:{output:a,input:t.inputs},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async onChainStart(e){const t=rn(e),r=e.run_type??"chain",s={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:e.run_type};let a={};e.inputs.input===""&&Object.keys(e.inputs).length===1?(a={},s.inputs={}):e.inputs.input!==void 0?(a.input=e.inputs.input,s.inputs=e.inputs.input):(a.input=e.inputs,s.inputs=e.inputs),this.runInfoMap.set(e.id,s),await this.send({event:`on_${r}_start`,data:a,name:t,tags:e.tags??[],run_id:e.id,metadata:e.extra?.metadata??{}},s)}async onChainEnd(e){const t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),t===void 0)throw new Error(`onChainEnd: Run ID ${e.id} not found in run map.`);const r=`on_${e.run_type}_end`,s=e.inputs??t.inputs??{},i={output:e.outputs?.output??e.outputs,input:s};s.input&&Object.keys(s).length===1&&(i.input=s.input,t.inputs=s.input),await this.sendEndEvent({event:r,data:i,run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata??{}},t)}async onToolStart(e){const t=rn(e),r={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:"tool",inputs:e.inputs??{}};this.runInfoMap.set(e.id,r),await this.send({event:"on_tool_start",data:{input:e.inputs??{}},name:t,run_id:e.id,tags:e.tags??[],metadata:e.extra?.metadata??{}},r)}async onToolEnd(e){const t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),t===void 0)throw new Error(`onToolEnd: Run ID ${e.id} not found in run map.`);if(t.inputs===void 0)throw new Error(`onToolEnd: Run ID ${e.id} is a tool call, and is expected to have traced inputs.`);const r=e.outputs?.output===void 0?e.outputs:e.outputs.output;await this.sendEndEvent({event:"on_tool_end",data:{output:r,input:t.inputs},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async onRetrieverStart(e){const t=rn(e),s={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:"retriever",inputs:{query:e.inputs.query}};this.runInfoMap.set(e.id,s),await this.send({event:"on_retriever_start",data:{input:{query:e.inputs.query}},name:t,tags:e.tags??[],run_id:e.id,metadata:e.extra?.metadata??{}},s)}async onRetrieverEnd(e){const t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),t===void 0)throw new Error(`onRetrieverEnd: Run ID ${e.id} not found in run map.`);await this.sendEndEvent({event:"on_retriever_end",data:{output:e.outputs?.documents??e.outputs,input:t.inputs},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async handleCustomEvent(e,t,r){const s=this.runInfoMap.get(r);if(s===void 0)throw new Error(`handleCustomEvent: Run ID ${r} not found in run map.`);await this.send({event:"on_custom_event",run_id:r,name:e,tags:s.tags,metadata:s.metadata,data:t},s)}async finish(){const e=[...this.tappedPromises.values()];Promise.all(e).finally(()=>{this.writer.close()})}}const c_=[400,401,402,403,404,405,406,407,409],l_=n=>{if(n.message.startsWith("Cancel")||n.message.startsWith("AbortError")||n.name==="AbortError"||n?.code==="ECONNABORTED")throw n;const e=n?.response?.status??n?.status;if(e&&c_.includes(+e))throw n;if(n?.error?.code==="insufficient_quota"){const t=new Error(n?.message);throw t.name="InsufficientQuotaError",t}};class Wi{constructor(e){Object.defineProperty(this,"maxConcurrency",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"maxRetries",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onFailedAttempt",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"queue",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxConcurrency=e.maxConcurrency??1/0,this.maxRetries=e.maxRetries??6,this.onFailedAttempt=e.onFailedAttempt??l_;const t="default"in at?at.default:at;this.queue=new t({concurrency:this.maxConcurrency})}call(e,...t){return this.queue.add(()=>In(()=>e(...t).catch(r=>{throw r instanceof Error?r:new Error(r)}),{onFailedAttempt:this.onFailedAttempt,retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0})}callWithOptions(e,t,...r){return e.signal?Promise.race([this.call(t,...r),new Promise((s,a)=>{e.signal?.addEventListener("abort",()=>{a(new Error("AbortError"))})})]):this.call(t,...r)}fetch(...e){return this.call(()=>fetch(...e).then(t=>t.ok?t:Promise.reject(t)))}}class Nd extends Dr{constructor({config:e,onStart:t,onEnd:r,onError:s}){super({_awaitHandler:!0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"RootListenersTracer"}),Object.defineProperty(this,"rootId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"config",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"argOnStart",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"argOnEnd",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"argOnError",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.config=e,this.argOnStart=t,this.argOnEnd=r,this.argOnError=s}persistRun(e){return Promise.resolve()}async onRunCreate(e){this.rootId||(this.rootId=e.id,this.argOnStart&&await this.argOnStart(e,this.config))}async onRunUpdate(e){e.id===this.rootId&&(e.error?this.argOnError&&await this.argOnError(e,this.config):this.argOnEnd&&await this.argOnEnd(e,this.config))}}function Zi(n){return n?n.lc_runnable:!1}class d_{constructor(e){Object.defineProperty(this,"includeNames",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"includeTypes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"includeTags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeNames",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeTypes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeTags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.includeNames=e.includeNames,this.includeTypes=e.includeTypes,this.includeTags=e.includeTags,this.excludeNames=e.excludeNames,this.excludeTypes=e.excludeTypes,this.excludeTags=e.excludeTags}includeEvent(e,t){let r=this.includeNames===void 0&&this.includeTypes===void 0&&this.includeTags===void 0;const s=e.tags??[];return this.includeNames!==void 0&&(r=r||this.includeNames.includes(e.name)),this.includeTypes!==void 0&&(r=r||this.includeTypes.includes(t)),this.includeTags!==void 0&&(r=r||s.some(a=>this.includeTags?.includes(a))),this.excludeNames!==void 0&&(r=r&&!this.excludeNames.includes(e.name)),this.excludeTypes!==void 0&&(r=r&&!this.excludeTypes.includes(t)),this.excludeTags!==void 0&&(r=r&&s.every(a=>!this.excludeTags?.includes(a))),r}}function $a(n){return n.replace(/[^a-zA-Z-_0-9]/g,"_")}const h_=["*","_","`"];function f_(n){let e="";for(const[t,r]of Object.entries(n))e+=` classDef ${t} ${r};
|
|
84
|
+
`;return e}function p_(n,e,t){const{firstNode:r,lastNode:s,nodeColors:a,withStyles:i=!0,curveStyle:o="linear",wrapLabelNWords:u=9}=t??{};let c=i?`%%{init: {'flowchart': {'curve': '${o}'}}}%%
|
|
85
|
+
graph TD;
|
|
86
|
+
`:`graph TD;
|
|
87
|
+
`;if(i){const f="default",p={[f]:"{0}({1})"};r!==void 0&&(p[r]="{0}([{1}]):::first"),s!==void 0&&(p[s]="{0}([{1}]):::last");for(const[m,g]of Object.entries(n)){const _=g.name.split(":").pop()??"";let b=h_.some(E=>_.startsWith(E)&&_.endsWith(E))?`<p>${_}</p>`:_;Object.keys(g.metadata??{}).length&&(b+=`<hr/><small><em>${Object.entries(g.metadata??{}).map(([E,I])=>`${E} = ${I}`).join(`
|
|
88
|
+
`)}</em></small>`);const v=(p[m]??p[f]).replace("{0}",$a(m)).replace("{1}",b);c+=` ${v}
|
|
89
|
+
`}}const l={};for(const f of e){const p=f.source.split(":"),m=f.target.split(":"),g=p.filter((_,y)=>_===m[y]).join(":");l[g]||(l[g]=[]),l[g].push(f)}const d=new Set;function h(f,p){const m=f.length===1&&f[0].source===f[0].target;if(p&&!m){const g=p.split(":").pop();if(d.has(g))throw new Error(`Found duplicate subgraph '${g}' -- this likely means that you're reusing a subgraph node with the same name. Please adjust your graph to have subgraph nodes with unique names.`);d.add(g),c+=` subgraph ${g}
|
|
90
|
+
`}for(const g of f){const{source:_,target:y,data:b,conditional:v}=g;let E="";if(b!==void 0){let I=b;const x=I.split(" ");x.length>u&&(I=Array.from({length:Math.ceil(x.length/u)},(O,q)=>x.slice(q*u,(q+1)*u).join(" ")).join(" <br> ")),E=v?` -. ${I} .-> `:` -- ${I} --> `}else E=v?" -.-> ":" --> ";c+=` ${$a(_)}${E}${$a(y)};
|
|
91
|
+
`}for(const g in l)g.startsWith(`${p}:`)&&g!==p&&h(l[g],g);p&&!m&&(c+=` end
|
|
92
|
+
`)}h(l[""]??[],"");for(const f in l)!f.includes(":")&&f!==""&&h(l[f],f);return i&&(c+=f_(a??{})),c}async function m_(n,e){return g_(n,{...e,imageType:"png"})}async function g_(n,e){let t=e?.backgroundColor??"white";const r=e?.imageType,s=btoa(n);t!==void 0&&(/^#(?:[0-9a-fA-F]{3}){1,2}$/.test(t)||(t=`!${t}`));const a=`https://mermaid.ink/img/${s}?bgColor=${t}&type=${r}`,i=await fetch(a);if(!i.ok)throw new Error(["Failed to render the graph using the Mermaid.INK API.",`Status code: ${i.status}`,`Status text: ${i.statusText}`].join(`
|
|
93
|
+
`));return await i.blob()}function us(n,e,t){function r(o,u){var c;Object.defineProperty(o,"_zod",{value:o._zod??{},enumerable:!1}),(c=o._zod).traits??(c.traits=new Set),o._zod.traits.add(n),e(o,u);for(const l in i.prototype)l in o||Object.defineProperty(o,l,{value:i.prototype[l].bind(o)});o._zod.constr=i,o._zod.def=u}const s=t?.Parent??Object;class a extends s{}Object.defineProperty(a,"name",{value:n});function i(o){var u;const c=t?.Parent?new a:this;r(c,o),(u=c._zod).deferred??(u.deferred=[]);for(const l of c._zod.deferred)l();return c}return Object.defineProperty(i,"init",{value:r}),Object.defineProperty(i,Symbol.hasInstance,{value:o=>t?.Parent&&o instanceof t.Parent?!0:o?._zod?.traits?.has(n)}),Object.defineProperty(i,"name",{value:n}),i}class Nn extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}const __={};function cs(n){return __}function y_(n){const e=Object.values(n).filter(r=>typeof r=="number");return Object.entries(n).filter(([r,s])=>e.indexOf(+r)===-1).map(([r,s])=>s)}function b_(n,e){return typeof e=="bigint"?e.toString():e}const jd=Error.captureStackTrace?Error.captureStackTrace:(...n)=>{};function jn(n,e,t){const r=new n._zod.constr(e??n._zod.def);return(!e||t?.parent)&&(r._zod.parent=n),r}function w_(n){return{}}function Na(n,e=0){for(let t=e;t<n.issues.length;t++)if(n.issues[t]?.continue!==!0)return!0;return!1}function nn(n){return typeof n=="string"?n:n?.message}function ls(n,e,t){const r={...n,path:n.path??[]};if(!n.message){const s=nn(n.inst?._zod.def?.error?.(n))??nn(e?.error?.(n))??nn(t.customError?.(n))??nn(t.localeError?.(n))??"Invalid input";r.message=s}return delete r.inst,delete r.continue,e?.reportInput||delete r.input,r}const Ld=(n,e)=>{n.name="$ZodError",Object.defineProperty(n,"_zod",{value:n._zod,enumerable:!1}),Object.defineProperty(n,"issues",{value:e,enumerable:!1}),Object.defineProperty(n,"message",{get(){return JSON.stringify(e,b_,2)},enumerable:!0}),Object.defineProperty(n,"toString",{value:()=>n.message,enumerable:!1})},v_=us("$ZodError",Ld),ds=us("$ZodError",Ld,{Parent:Error}),E_=n=>(e,t,r,s)=>{const a=r?Object.assign(r,{async:!1}):{async:!1},i=e._zod.run({value:t,issues:[]},a);if(i instanceof Promise)throw new Nn;if(i.issues.length){const o=new(s?.Err??n)(i.issues.map(u=>ls(u,a,cs())));throw jd(o,s?.callee),o}return i.value},Md=E_(ds),S_=n=>async(e,t,r,s)=>{const a=r?Object.assign(r,{async:!0}):{async:!0};let i=e._zod.run({value:t,issues:[]},a);if(i instanceof Promise&&(i=await i),i.issues.length){const o=new(s?.Err??n)(i.issues.map(u=>ls(u,a,cs())));throw jd(o,s?.callee),o}return i.value},O_=S_(ds),T_=n=>(e,t,r)=>{const s=r?{...r,async:!1}:{async:!1},a=e._zod.run({value:t,issues:[]},s);if(a instanceof Promise)throw new Nn;return a.issues.length?{success:!1,error:new(n??v_)(a.issues.map(i=>ls(i,s,cs())))}:{success:!0,data:a.value}},A_=T_(ds),P_=n=>async(e,t,r)=>{const s=r?Object.assign(r,{async:!0}):{async:!0};let a=e._zod.run({value:t,issues:[]},s);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new n(a.issues.map(i=>ls(i,s,cs())))}:{success:!0,data:a.value}},I_=P_(ds),x_={major:4,minor:0,patch:0},R_=us("$ZodType",(n,e)=>{var t;n??(n={}),n._zod.def=e,n._zod.bag=n._zod.bag||{},n._zod.version=x_;const r=[...n._zod.def.checks??[]];n._zod.traits.has("$ZodCheck")&&r.unshift(n);for(const s of r)for(const a of s._zod.onattach)a(n);if(r.length===0)(t=n._zod).deferred??(t.deferred=[]),n._zod.deferred?.push(()=>{n._zod.run=n._zod.parse});else{const s=(a,i,o)=>{let u=Na(a),c;for(const l of i){if(l._zod.def.when){if(!l._zod.def.when(a))continue}else if(u)continue;const d=a.issues.length,h=l._zod.check(a);if(h instanceof Promise&&o?.async===!1)throw new Nn;if(c||h instanceof Promise)c=(c??Promise.resolve()).then(async()=>{await h,a.issues.length!==d&&(u||(u=Na(a,d)))});else{if(a.issues.length===d)continue;u||(u=Na(a,d))}}return c?c.then(()=>a):a};n._zod.run=(a,i)=>{const o=n._zod.parse(a,i);if(o instanceof Promise){if(i.async===!1)throw new Nn;return o.then(u=>s(u,r,i))}return s(o,r,i)}}n["~standard"]={validate:s=>{try{const a=A_(n,s);return a.success?{value:a.data}:{issues:a.error?.issues}}catch{return I_(n,s).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}}),k_=us("$ZodNever",(n,e)=>{R_.init(n,e),n._zod.parse=(t,r)=>(t.issues.push({expected:"never",code:"invalid_type",input:t.value,inst:n}),t)});class Ud{constructor(){this._map=new Map,this._idmap=new Map}add(e,...t){const r=t[0];if(this._map.set(e,r),r&&typeof r=="object"&&"id"in r){if(this._idmap.has(r.id))throw new Error(`ID ${r.id} already exists in the registry`);this._idmap.set(r.id,e)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(e){const t=this._map.get(e);return t&&typeof t=="object"&&"id"in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){const t=e._zod.parent;if(t){const r={...this.get(t)??{}};return delete r.id,{...r,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}}function C_(){return new Ud}const ht=C_();function $_(n,e){return new n({type:"never",...w_()})}class yc{constructor(e){this.counter=0,this.metadataRegistry=e?.metadata??ht,this.target=e?.target??"draft-2020-12",this.unrepresentable=e?.unrepresentable??"throw",this.override=e?.override??(()=>{}),this.io=e?.io??"output",this.seen=new Map}process(e,t={path:[],schemaPath:[]}){var r;const s=e._zod.def,a={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},i=this.seen.get(e);if(i)return i.count++,t.schemaPath.includes(e)&&(i.cycle=t.path),i.schema;const o={schema:{},count:1,cycle:void 0,path:t.path};this.seen.set(e,o);const u=e._zod.toJSONSchema?.();if(u)o.schema=u;else{const d={...t,schemaPath:[...t.schemaPath,e],path:t.path},h=e._zod.parent;if(h)o.ref=h,this.process(h,d),this.seen.get(h).isParent=!0;else{const f=o.schema;switch(s.type){case"string":{const p=f;p.type="string";const{minimum:m,maximum:g,format:_,patterns:y,contentEncoding:b}=e._zod.bag;if(typeof m=="number"&&(p.minLength=m),typeof g=="number"&&(p.maxLength=g),_&&(p.format=a[_]??_,p.format===""&&delete p.format),b&&(p.contentEncoding=b),y&&y.size>0){const v=[...y];v.length===1?p.pattern=v[0].source:v.length>1&&(o.schema.allOf=[...v.map(E=>({...this.target==="draft-7"?{type:"string"}:{},pattern:E.source}))])}break}case"number":{const p=f,{minimum:m,maximum:g,format:_,multipleOf:y,exclusiveMaximum:b,exclusiveMinimum:v}=e._zod.bag;typeof _=="string"&&_.includes("int")?p.type="integer":p.type="number",typeof v=="number"&&(p.exclusiveMinimum=v),typeof m=="number"&&(p.minimum=m,typeof v=="number"&&(v>=m?delete p.minimum:delete p.exclusiveMinimum)),typeof b=="number"&&(p.exclusiveMaximum=b),typeof g=="number"&&(p.maximum=g,typeof b=="number"&&(b<=g?delete p.maximum:delete p.exclusiveMaximum)),typeof y=="number"&&(p.multipleOf=y);break}case"boolean":{const p=f;p.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema");break}case"null":{f.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema");break}case"never":{f.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{const p=f,{minimum:m,maximum:g}=e._zod.bag;typeof m=="number"&&(p.minItems=m),typeof g=="number"&&(p.maxItems=g),p.type="array",p.items=this.process(s.element,{...d,path:[...d.path,"items"]});break}case"object":{const p=f;p.type="object",p.properties={};const m=s.shape;for(const y in m)p.properties[y]=this.process(m[y],{...d,path:[...d.path,"properties",y]});const g=new Set(Object.keys(m)),_=new Set([...g].filter(y=>{const b=s.shape[y]._zod;return this.io==="input"?b.optin===void 0:b.optout===void 0}));_.size>0&&(p.required=Array.from(_)),s.catchall?._zod.def.type==="never"?p.additionalProperties=!1:s.catchall?s.catchall&&(p.additionalProperties=this.process(s.catchall,{...d,path:[...d.path,"additionalProperties"]})):this.io==="output"&&(p.additionalProperties=!1);break}case"union":{const p=f;p.anyOf=s.options.map((m,g)=>this.process(m,{...d,path:[...d.path,"anyOf",g]}));break}case"intersection":{const p=f,m=this.process(s.left,{...d,path:[...d.path,"allOf",0]}),g=this.process(s.right,{...d,path:[...d.path,"allOf",1]}),_=b=>"allOf"in b&&Object.keys(b).length===1,y=[..._(m)?m.allOf:[m],..._(g)?g.allOf:[g]];p.allOf=y;break}case"tuple":{const p=f;p.type="array";const m=s.items.map((y,b)=>this.process(y,{...d,path:[...d.path,"prefixItems",b]}));if(this.target==="draft-2020-12"?p.prefixItems=m:p.items=m,s.rest){const y=this.process(s.rest,{...d,path:[...d.path,"items"]});this.target==="draft-2020-12"?p.items=y:p.additionalItems=y}s.rest&&(p.items=this.process(s.rest,{...d,path:[...d.path,"items"]}));const{minimum:g,maximum:_}=e._zod.bag;typeof g=="number"&&(p.minItems=g),typeof _=="number"&&(p.maxItems=_);break}case"record":{const p=f;p.type="object",p.propertyNames=this.process(s.keyType,{...d,path:[...d.path,"propertyNames"]}),p.additionalProperties=this.process(s.valueType,{...d,path:[...d.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema");break}case"enum":{const p=f,m=y_(s.entries);m.every(g=>typeof g=="number")&&(p.type="number"),m.every(g=>typeof g=="string")&&(p.type="string"),p.enum=m;break}case"literal":{const p=f,m=[];for(const g of s.values)if(g===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof g=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");m.push(Number(g))}else m.push(g);if(m.length!==0)if(m.length===1){const g=m[0];p.type=g===null?"null":typeof g,p.const=g}else m.every(g=>typeof g=="number")&&(p.type="number"),m.every(g=>typeof g=="string")&&(p.type="string"),m.every(g=>typeof g=="boolean")&&(p.type="string"),m.every(g=>g===null)&&(p.type="null"),p.enum=m;break}case"file":{const p=f,m={type:"string",format:"binary",contentEncoding:"binary"},{minimum:g,maximum:_,mime:y}=e._zod.bag;g!==void 0&&(m.minLength=g),_!==void 0&&(m.maxLength=_),y?y.length===1?(m.contentMediaType=y[0],Object.assign(p,m)):p.anyOf=y.map(b=>({...m,contentMediaType:b})):Object.assign(p,m);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{const p=this.process(s.innerType,d);f.anyOf=[p,{type:"null"}];break}case"nonoptional":{this.process(s.innerType,d),o.ref=s.innerType;break}case"success":{const p=f;p.type="boolean";break}case"default":{this.process(s.innerType,d),o.ref=s.innerType,f.default=JSON.parse(JSON.stringify(s.defaultValue));break}case"prefault":{this.process(s.innerType,d),o.ref=s.innerType,this.io==="input"&&(f._prefault=JSON.parse(JSON.stringify(s.defaultValue)));break}case"catch":{this.process(s.innerType,d),o.ref=s.innerType;let p;try{p=s.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}f.default=p;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{const p=f,m=e._zod.pattern;if(!m)throw new Error("Pattern not found in template literal");p.type="string",p.pattern=m.source;break}case"pipe":{const p=this.io==="input"?s.in._zod.def.type==="transform"?s.out:s.in:s.out;this.process(p,d),o.ref=p;break}case"readonly":{this.process(s.innerType,d),o.ref=s.innerType,f.readOnly=!0;break}case"promise":{this.process(s.innerType,d),o.ref=s.innerType;break}case"optional":{this.process(s.innerType,d),o.ref=s.innerType;break}case"lazy":{const p=e._zod.innerType;this.process(p,d),o.ref=p;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}}}}const c=this.metadataRegistry.get(e);return c&&Object.assign(o.schema,c),this.io==="input"&&se(e)&&(delete o.schema.examples,delete o.schema.default),this.io==="input"&&o.schema._prefault&&((r=o.schema).default??(r.default=o.schema._prefault)),delete o.schema._prefault,this.seen.get(e).schema}emit(e,t){const r={cycles:t?.cycles??"ref",reused:t?.reused??"inline",external:t?.external??void 0},s=this.seen.get(e);if(!s)throw new Error("Unprocessed schema. This is a bug in Zod.");const a=l=>{const d=this.target==="draft-2020-12"?"$defs":"definitions";if(r.external){const m=r.external.registry.get(l[0])?.id,g=r.external.uri??(y=>y);if(m)return{ref:g(m)};const _=l[1].defId??l[1].schema.id??`schema${this.counter++}`;return l[1].defId=_,{defId:_,ref:`${g("__shared")}#/${d}/${_}`}}if(l[1]===s)return{ref:"#"};const f=`#/${d}/`,p=l[1].schema.id??`__schema${this.counter++}`;return{defId:p,ref:f+p}},i=l=>{if(l[1].schema.$ref)return;const d=l[1],{ref:h,defId:f}=a(l);d.def={...d.schema},f&&(d.defId=f);const p=d.schema;for(const m in p)delete p[m];p.$ref=h};if(r.cycles==="throw")for(const l of this.seen.entries()){const d=l[1];if(d.cycle)throw new Error(`Cycle detected: #/${d.cycle?.join("/")}/<root>
|
|
94
|
+
|
|
95
|
+
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const l of this.seen.entries()){const d=l[1];if(e===l[0]){i(l);continue}if(r.external){const f=r.external.registry.get(l[0])?.id;if(e!==l[0]&&f){i(l);continue}}if(this.metadataRegistry.get(l[0])?.id){i(l);continue}if(d.cycle){i(l);continue}if(d.count>1&&r.reused==="ref"){i(l);continue}}const o=(l,d)=>{const h=this.seen.get(l),f=h.def??h.schema,p={...f};if(h.ref===null)return;const m=h.ref;if(h.ref=null,m){o(m,d);const g=this.seen.get(m).schema;g.$ref&&d.target==="draft-7"?(f.allOf=f.allOf??[],f.allOf.push(g)):(Object.assign(f,g),Object.assign(f,p))}h.isParent||this.override({zodSchema:l,jsonSchema:f,path:h.path??[]})};for(const l of[...this.seen.entries()].reverse())o(l[0],{target:this.target});const u={};if(this.target==="draft-2020-12"?u.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?u.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),r.external?.uri){const l=r.external.registry.get(e)?.id;if(!l)throw new Error("Schema is missing an `id` property");u.$id=r.external.uri(l)}Object.assign(u,s.def);const c=r.external?.defs??{};for(const l of this.seen.entries()){const d=l[1];d.def&&d.defId&&(c[d.defId]=d.def)}r.external||Object.keys(c).length>0&&(this.target==="draft-2020-12"?u.$defs=c:u.definitions=c);try{return JSON.parse(JSON.stringify(u))}catch{throw new Error("Error converting schema to JSON.")}}}function oi(n,e){if(n instanceof Ud){const r=new yc(e),s={};for(const o of n._idmap.entries()){const[u,c]=o;r.process(c)}const a={},i={registry:n,uri:e?.uri,defs:s};for(const o of n._idmap.entries()){const[u,c]=o;a[u]=r.emit(c,{...e,external:i})}if(Object.keys(s).length>0){const o=r.target==="draft-2020-12"?"$defs":"definitions";a.__shared={[o]:s}}return{schemas:a}}const t=new yc(e);return t.process(n),t.emit(n,e)}function se(n,e){const t=e??{seen:new Set};if(t.seen.has(n))return!1;t.seen.add(n);const s=n._zod.def;switch(s.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":return!1;case"array":return se(s.element,t);case"object":{for(const a in s.shape)if(se(s.shape[a],t))return!0;return!1}case"union":{for(const a of s.options)if(se(a,t))return!0;return!1}case"intersection":return se(s.left,t)||se(s.right,t);case"tuple":{for(const a of s.items)if(se(a,t))return!0;return!!(s.rest&&se(s.rest,t))}case"record":return se(s.keyType,t)||se(s.valueType,t);case"map":return se(s.keyType,t)||se(s.valueType,t);case"set":return se(s.valueType,t);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return se(s.innerType,t);case"lazy":return se(s.getter(),t);case"default":return se(s.innerType,t);case"prefault":return se(s.innerType,t);case"custom":return!1;case"transform":return!0;case"pipe":return se(s.in,t)||se(s.out,t);case"success":return!1;case"catch":return!1}throw new Error(`Unknown schema type: ${s.type}`)}const N_=Symbol("Let zodToJsonSchema decide on which parser to use"),j_={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},L_=n=>({...j_,...n}),M_=n=>{const e=L_(n),t=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:t,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([r,s])=>[s._def,{def:s._def,path:[...e.basePath,e.definitionPath,r],jsonSchema:void 0}]))}};function Dd(n,e,t,r){r?.errorMessages&&t&&(n.errorMessage={...n.errorMessage,[e]:t})}function X(n,e,t,r,s){n[e]=t,Dd(n,e,r,s)}const Fd=(n,e)=>{let t=0;for(;t<n.length&&t<e.length&&n[t]===e[t];t++);return[(n.length-t).toString(),...e.slice(t)].join("/")};function Ne(n){if(n.target!=="openAi")return{};const e=[...n.basePath,n.definitionPath,n.openAiAnyTypeName];return n.flags.hasReferencedOpenAiAnyType=!0,{$ref:n.$refStrategy==="relative"?Fd(e,n.currentPath):e.join("/")}}function U_(n,e){const t={type:"array"};return n.type?._def&&n.type?._def?.typeName!==S.ZodAny&&(t.items=K(n.type._def,{...e,currentPath:[...e.currentPath,"items"]})),n.minLength&&X(t,"minItems",n.minLength.value,n.minLength.message,e),n.maxLength&&X(t,"maxItems",n.maxLength.value,n.maxLength.message,e),n.exactLength&&(X(t,"minItems",n.exactLength.value,n.exactLength.message,e),X(t,"maxItems",n.exactLength.value,n.exactLength.message,e)),t}function D_(n,e){const t={type:"integer",format:"int64"};if(!n.checks)return t;for(const r of n.checks)switch(r.kind){case"min":e.target==="jsonSchema7"?r.inclusive?X(t,"minimum",r.value,r.message,e):X(t,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(t.exclusiveMinimum=!0),X(t,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?X(t,"maximum",r.value,r.message,e):X(t,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(t.exclusiveMaximum=!0),X(t,"maximum",r.value,r.message,e));break;case"multipleOf":X(t,"multipleOf",r.value,r.message,e);break}return t}function F_(){return{type:"boolean"}}function Bd(n,e){return K(n.type._def,e)}const B_=(n,e)=>K(n.innerType._def,e);function zd(n,e,t){const r=t??e.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((s,a)=>zd(n,e,s))};switch(r){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return z_(n,e)}}const z_=(n,e)=>{const t={type:"integer",format:"unix-time"};if(e.target==="openApi3")return t;for(const r of n.checks)switch(r.kind){case"min":X(t,"minimum",r.value,r.message,e);break;case"max":X(t,"maximum",r.value,r.message,e);break}return t};function q_(n,e){return{...K(n.innerType._def,e),default:n.defaultValue()}}function H_(n,e){return e.effectStrategy==="input"?K(n.schema._def,e):Ne(e)}function G_(n){return{type:"string",enum:Array.from(n.values)}}const J_=n=>"type"in n&&n.type==="string"?!1:"allOf"in n;function W_(n,e){const t=[K(n.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),K(n.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(a=>!!a);let r=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0;const s=[];return t.forEach(a=>{if(J_(a))s.push(...a.allOf),a.unevaluatedProperties===void 0&&(r=void 0);else{let i=a;if("additionalProperties"in a&&a.additionalProperties===!1){const{additionalProperties:o,...u}=a;i=u}else r=void 0;s.push(i)}}),s.length?{allOf:s,...r}:void 0}function Z_(n,e){const t=typeof n.value;return t!=="bigint"&&t!=="number"&&t!=="boolean"&&t!=="string"?{type:Array.isArray(n.value)?"array":"object"}:e.target==="openApi3"?{type:t==="bigint"?"integer":t,enum:[n.value]}:{type:t==="bigint"?"integer":t,const:n.value}}let ja;const Me={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(ja===void 0&&(ja=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),ja),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function qd(n,e){const t={type:"string"};if(n.checks)for(const r of n.checks)switch(r.kind){case"min":X(t,"minLength",typeof t.minLength=="number"?Math.max(t.minLength,r.value):r.value,r.message,e);break;case"max":X(t,"maxLength",typeof t.maxLength=="number"?Math.min(t.maxLength,r.value):r.value,r.message,e);break;case"email":switch(e.emailStrategy){case"format:email":Ue(t,"email",r.message,e);break;case"format:idn-email":Ue(t,"idn-email",r.message,e);break;case"pattern:zod":be(t,Me.email,r.message,e);break}break;case"url":Ue(t,"uri",r.message,e);break;case"uuid":Ue(t,"uuid",r.message,e);break;case"regex":be(t,r.regex,r.message,e);break;case"cuid":be(t,Me.cuid,r.message,e);break;case"cuid2":be(t,Me.cuid2,r.message,e);break;case"startsWith":be(t,RegExp(`^${La(r.value,e)}`),r.message,e);break;case"endsWith":be(t,RegExp(`${La(r.value,e)}$`),r.message,e);break;case"datetime":Ue(t,"date-time",r.message,e);break;case"date":Ue(t,"date",r.message,e);break;case"time":Ue(t,"time",r.message,e);break;case"duration":Ue(t,"duration",r.message,e);break;case"length":X(t,"minLength",typeof t.minLength=="number"?Math.max(t.minLength,r.value):r.value,r.message,e),X(t,"maxLength",typeof t.maxLength=="number"?Math.min(t.maxLength,r.value):r.value,r.message,e);break;case"includes":{be(t,RegExp(La(r.value,e)),r.message,e);break}case"ip":{r.version!=="v6"&&Ue(t,"ipv4",r.message,e),r.version!=="v4"&&Ue(t,"ipv6",r.message,e);break}case"base64url":be(t,Me.base64url,r.message,e);break;case"jwt":be(t,Me.jwt,r.message,e);break;case"cidr":{r.version!=="v6"&&be(t,Me.ipv4Cidr,r.message,e),r.version!=="v4"&&be(t,Me.ipv6Cidr,r.message,e);break}case"emoji":be(t,Me.emoji(),r.message,e);break;case"ulid":{be(t,Me.ulid,r.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{Ue(t,"binary",r.message,e);break}case"contentEncoding:base64":{X(t,"contentEncoding","base64",r.message,e);break}case"pattern:zod":{be(t,Me.base64,r.message,e);break}}break}case"nanoid":be(t,Me.nanoid,r.message,e)}return t}function La(n,e){return e.patternStrategy==="escape"?V_(n):n}const K_=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function V_(n){let e="";for(let t=0;t<n.length;t++)K_.has(n[t])||(e+="\\"),e+=n[t];return e}function Ue(n,e,t,r){n.format||n.anyOf?.some(s=>s.format)?(n.anyOf||(n.anyOf=[]),n.format&&(n.anyOf.push({format:n.format,...n.errorMessage&&r.errorMessages&&{errorMessage:{format:n.errorMessage.format}}}),delete n.format,n.errorMessage&&(delete n.errorMessage.format,Object.keys(n.errorMessage).length===0&&delete n.errorMessage)),n.anyOf.push({format:e,...t&&r.errorMessages&&{errorMessage:{format:t}}})):X(n,"format",e,t,r)}function be(n,e,t,r){n.pattern||n.allOf?.some(s=>s.pattern)?(n.allOf||(n.allOf=[]),n.pattern&&(n.allOf.push({pattern:n.pattern,...n.errorMessage&&r.errorMessages&&{errorMessage:{pattern:n.errorMessage.pattern}}}),delete n.pattern,n.errorMessage&&(delete n.errorMessage.pattern,Object.keys(n.errorMessage).length===0&&delete n.errorMessage)),n.allOf.push({pattern:bc(e,r),...t&&r.errorMessages&&{errorMessage:{pattern:t}}})):X(n,"pattern",bc(e,r),t,r)}function bc(n,e){if(!e.applyRegexFlags||!n.flags)return n.source;const t={i:n.flags.includes("i"),m:n.flags.includes("m"),s:n.flags.includes("s")},r=t.i?n.source.toLowerCase():n.source;let s="",a=!1,i=!1,o=!1;for(let u=0;u<r.length;u++){if(a){s+=r[u],a=!1;continue}if(t.i){if(i){if(r[u].match(/[a-z]/)){o?(s+=r[u],s+=`${r[u-2]}-${r[u]}`.toUpperCase(),o=!1):r[u+1]==="-"&&r[u+2]?.match(/[a-z]/)?(s+=r[u],o=!0):s+=`${r[u]}${r[u].toUpperCase()}`;continue}}else if(r[u].match(/[a-z]/)){s+=`[${r[u]}${r[u].toUpperCase()}]`;continue}}if(t.m){if(r[u]==="^"){s+=`(^|(?<=[\r
|
|
96
|
+
]))`;continue}else if(r[u]==="$"){s+=`($|(?=[\r
|
|
97
|
+
]))`;continue}}if(t.s&&r[u]==="."){s+=i?`${r[u]}\r
|
|
98
|
+
`:`[${r[u]}\r
|
|
99
|
+
]`;continue}s+=r[u],r[u]==="\\"?a=!0:i&&r[u]==="]"?i=!1:!i&&r[u]==="["&&(i=!0)}try{new RegExp(s)}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 s}function Hd(n,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&n.keyType?._def.typeName===S.ZodEnum)return{type:"object",required:n.keyType._def.values,properties:n.keyType._def.values.reduce((r,s)=>({...r,[s]:K(n.valueType._def,{...e,currentPath:[...e.currentPath,"properties",s]})??Ne(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};const t={type:"object",additionalProperties:K(n.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return t;if(n.keyType?._def.typeName===S.ZodString&&n.keyType._def.checks?.length){const{type:r,...s}=qd(n.keyType._def,e);return{...t,propertyNames:s}}else{if(n.keyType?._def.typeName===S.ZodEnum)return{...t,propertyNames:{enum:n.keyType._def.values}};if(n.keyType?._def.typeName===S.ZodBranded&&n.keyType._def.type._def.typeName===S.ZodString&&n.keyType._def.type._def.checks?.length){const{type:r,...s}=Bd(n.keyType._def,e);return{...t,propertyNames:s}}}return t}function X_(n,e){if(e.mapStrategy==="record")return Hd(n,e);const t=K(n.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||Ne(e),r=K(n.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||Ne(e);return{type:"array",maxItems:125,items:{type:"array",items:[t,r],minItems:2,maxItems:2}}}function Q_(n){const e=n.values,r=Object.keys(n.values).filter(a=>typeof e[e[a]]!="number").map(a=>e[a]),s=Array.from(new Set(r.map(a=>typeof a)));return{type:s.length===1?s[0]==="string"?"string":"number":["string","number"],enum:r}}function Y_(n){return n.target==="openAi"?void 0:{not:Ne({...n,currentPath:[...n.currentPath,"not"]})}}function ey(n){return n.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}const Ln={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function ty(n,e){if(e.target==="openApi3")return wc(n,e);const t=n.options instanceof Map?Array.from(n.options.values()):n.options;if(t.every(r=>r._def.typeName in Ln&&(!r._def.checks||!r._def.checks.length))){const r=t.reduce((s,a)=>{const i=Ln[a._def.typeName];return i&&!s.includes(i)?[...s,i]:s},[]);return{type:r.length>1?r:r[0]}}else if(t.every(r=>r._def.typeName==="ZodLiteral"&&!r.description)){const r=t.reduce((s,a)=>{const i=typeof a._def.value;switch(i){case"string":case"number":case"boolean":return[...s,i];case"bigint":return[...s,"integer"];case"object":if(a._def.value===null)return[...s,"null"];case"symbol":case"undefined":case"function":default:return s}},[]);if(r.length===t.length){const s=r.filter((a,i,o)=>o.indexOf(a)===i);return{type:s.length>1?s:s[0],enum:t.reduce((a,i)=>a.includes(i._def.value)?a:[...a,i._def.value],[])}}}else if(t.every(r=>r._def.typeName==="ZodEnum"))return{type:"string",enum:t.reduce((r,s)=>[...r,...s._def.values.filter(a=>!r.includes(a))],[])};return wc(n,e)}const wc=(n,e)=>{const t=(n.options instanceof Map?Array.from(n.options.values()):n.options).map((r,s)=>K(r._def,{...e,currentPath:[...e.currentPath,"anyOf",`${s}`]})).filter(r=>!!r&&(!e.strictUnions||typeof r=="object"&&Object.keys(r).length>0));return t.length?{anyOf:t}:void 0};function ry(n,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(n.innerType._def.typeName)&&(!n.innerType._def.checks||!n.innerType._def.checks.length))return e.target==="openApi3"?{type:Ln[n.innerType._def.typeName],nullable:!0}:{type:[Ln[n.innerType._def.typeName],"null"]};if(e.target==="openApi3"){const r=K(n.innerType._def,{...e,currentPath:[...e.currentPath]});return r&&"$ref"in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}const t=K(n.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return t&&{anyOf:[t,{type:"null"}]}}function ny(n,e){const t={type:"number"};if(!n.checks)return t;for(const r of n.checks)switch(r.kind){case"int":t.type="integer",Dd(t,"type",r.message,e);break;case"min":e.target==="jsonSchema7"?r.inclusive?X(t,"minimum",r.value,r.message,e):X(t,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(t.exclusiveMinimum=!0),X(t,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?X(t,"maximum",r.value,r.message,e):X(t,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(t.exclusiveMaximum=!0),X(t,"maximum",r.value,r.message,e));break;case"multipleOf":X(t,"multipleOf",r.value,r.message,e);break}return t}function sy(n,e){const t=e.target==="openAi",r={type:"object",properties:{}},s=[],a=n.shape();for(const o in a){let u=a[o];if(u===void 0||u._def===void 0)continue;let c=iy(u);c&&t&&(u._def.typeName==="ZodOptional"&&(u=u._def.innerType),u.isNullable()||(u=u.nullable()),c=!1);const l=K(u._def,{...e,currentPath:[...e.currentPath,"properties",o],propertyPath:[...e.currentPath,"properties",o]});l!==void 0&&(r.properties[o]=l,c||s.push(o))}s.length&&(r.required=s);const i=ay(n,e);return i!==void 0&&(r.additionalProperties=i),r}function ay(n,e){if(n.catchall._def.typeName!=="ZodNever")return K(n.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(n.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function iy(n){try{return n.isOptional()}catch{return!0}}const oy=(n,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return K(n.innerType._def,e);const t=K(n.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return t?{anyOf:[{not:Ne(e)},t]}:Ne(e)},uy=(n,e)=>{if(e.pipeStrategy==="input")return K(n.in._def,e);if(e.pipeStrategy==="output")return K(n.out._def,e);const t=K(n.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),r=K(n.out._def,{...e,currentPath:[...e.currentPath,"allOf",t?"1":"0"]});return{allOf:[t,r].filter(s=>s!==void 0)}};function cy(n,e){return K(n.type._def,e)}function ly(n,e){const r={type:"array",uniqueItems:!0,items:K(n.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return n.minSize&&X(r,"minItems",n.minSize.value,n.minSize.message,e),n.maxSize&&X(r,"maxItems",n.maxSize.value,n.maxSize.message,e),r}function dy(n,e){return n.rest?{type:"array",minItems:n.items.length,items:n.items.map((t,r)=>K(t._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((t,r)=>r===void 0?t:[...t,r],[]),additionalItems:K(n.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:n.items.length,maxItems:n.items.length,items:n.items.map((t,r)=>K(t._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((t,r)=>r===void 0?t:[...t,r],[])}}function hy(n){return{not:Ne(n)}}function fy(n){return Ne(n)}const py=(n,e)=>K(n.innerType._def,e),my=(n,e,t)=>{switch(e){case S.ZodString:return qd(n,t);case S.ZodNumber:return ny(n,t);case S.ZodObject:return sy(n,t);case S.ZodBigInt:return D_(n,t);case S.ZodBoolean:return F_();case S.ZodDate:return zd(n,t);case S.ZodUndefined:return hy(t);case S.ZodNull:return ey(t);case S.ZodArray:return U_(n,t);case S.ZodUnion:case S.ZodDiscriminatedUnion:return ty(n,t);case S.ZodIntersection:return W_(n,t);case S.ZodTuple:return dy(n,t);case S.ZodRecord:return Hd(n,t);case S.ZodLiteral:return Z_(n,t);case S.ZodEnum:return G_(n);case S.ZodNativeEnum:return Q_(n);case S.ZodNullable:return ry(n,t);case S.ZodOptional:return oy(n,t);case S.ZodMap:return X_(n,t);case S.ZodSet:return ly(n,t);case S.ZodLazy:return()=>n.getter()._def;case S.ZodPromise:return cy(n,t);case S.ZodNaN:case S.ZodNever:return Y_(t);case S.ZodEffects:return H_(n,t);case S.ZodAny:return Ne(t);case S.ZodUnknown:return fy(t);case S.ZodDefault:return q_(n,t);case S.ZodBranded:return Bd(n,t);case S.ZodReadonly:return py(n,t);case S.ZodCatch:return B_(n,t);case S.ZodPipeline:return uy(n,t);case S.ZodFunction:case S.ZodVoid:case S.ZodSymbol:return;default:return(r=>{})()}};function K(n,e,t=!1){const r=e.seen.get(n);if(e.override){const o=e.override?.(n,e,r,t);if(o!==N_)return o}if(r&&!t){const o=gy(r,e);if(o!==void 0)return o}const s={def:n,path:e.currentPath,jsonSchema:void 0};e.seen.set(n,s);const a=my(n,n.typeName,e),i=typeof a=="function"?K(a(),e):a;if(i&&_y(n,e,i),e.postProcess){const o=e.postProcess(i,n,e);return s.jsonSchema=i,o}return s.jsonSchema=i,i}const gy=(n,e)=>{switch(e.$refStrategy){case"root":return{$ref:n.path.join("/")};case"relative":return{$ref:Fd(e.currentPath,n.path)};case"none":case"seen":return n.path.length<e.currentPath.length&&n.path.every((t,r)=>e.currentPath[r]===t)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),Ne(e)):e.$refStrategy==="seen"?Ne(e):void 0}},_y=(n,e,t)=>(n.description&&(t.description=n.description,e.markdownDescription&&(t.markdownDescription=n.description)),t),yy=(n,e)=>{const t=M_(e);let r;const s=e?.name,a=K(n._def,t,!1)??Ne(t);t.flags.hasReferencedOpenAiAnyType&&(r||(r={}),r[t.openAiAnyTypeName]||(r[t.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:t.$refStrategy==="relative"?"1":[...t.basePath,t.definitionPath,t.openAiAnyTypeName].join("/")}}));const i=s===void 0?r?{...a,[t.definitionPath]:r}:a:{$ref:[...t.$refStrategy==="relative"?[]:t.basePath,t.definitionPath,s].join("/"),[t.definitionPath]:{...r,[s]:a}};return t.target==="jsonSchema7"?i.$schema="http://json-schema.org/draft-07/schema#":(t.target==="jsonSchema2019-09"||t.target==="openAi")&&(i.$schema="https://json-schema.org/draft/2019-09/schema#"),t.target==="openAi"&&("anyOf"in i||"oneOf"in i||"allOf"in i||"type"in i&&Array.isArray(i.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),i};function ui(n,e){const t=typeof n;if(t!==typeof e)return!1;if(Array.isArray(n)){if(!Array.isArray(e))return!1;const r=n.length;if(r!==e.length)return!1;for(let s=0;s<r;s++)if(!ui(n[s],e[s]))return!1;return!0}if(t==="object"){if(!n||!e)return n===e;const r=Object.keys(n),s=Object.keys(e);if(r.length!==s.length)return!1;for(const i of r)if(!ui(n[i],e[i]))return!1;return!0}return n===e}function We(n){if(typeof n!="object"||n===null)return!1;const e=n;if(!("_zod"in e))return!1;const t=e._zod;return typeof t=="object"&&t!==null&&"def"in t}function et(n){if(typeof n!="object"||n===null)return!1;const e=n;if(!("_def"in e)||"_zod"in e)return!1;const t=e._def;return typeof t=="object"&&t!=null&&"typeName"in t}function Ot(n){return!n||typeof n!="object"||Array.isArray(n)?!1:!!(We(n)||et(n))}async function by(n,e){if(We(n))try{return{success:!0,data:await O_(n,e)}}catch(t){return{success:!1,error:t}}if(et(n))return n.safeParse(e);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}async function Gd(n,e){if(We(n))return Md(n,e);if(et(n))return n.parse(e);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function Ki(n){if(We(n))return ht.get(n)?.description;if(et(n)||"description"in n&&typeof n.description=="string")return n.description}function wy(n){return Ot(n)?et(n)?n._def.typeName==="ZodString":We(n)?n._zod.def.type==="string":!1:!1}function Sr(n){return We(n)?typeof n=="object"&&n!==null&&"_zod"in n&&typeof n._zod=="object"&&n._zod!==null&&"def"in n._zod&&typeof n._zod.def=="object"&&n._zod.def!==null&&"type"in n._zod.def&&n._zod.def.type==="object":!1}function Jd(n){return We(n)?typeof n=="object"&&n!==null&&"_zod"in n&&typeof n._zod=="object"&&n._zod!==null&&"def"in n._zod&&typeof n._zod.def=="object"&&n._zod.def!==null&&"type"in n._zod.def&&n._zod.def.type==="array":!1}function ci(n,e=!1){if(et(n))return n.strict();if(Sr(n)){const t=n._zod.def.shape;if(e)for(const[a,i]of Object.entries(n._zod.def.shape)){if(Sr(i)){const u=ci(i,e);t[a]=u}else if(Jd(i)){let u=i._zod.def.element;Sr(u)&&(u=ci(u,e)),t[a]=jn(i,{...i._zod.def,element:u})}else t[a]=i;const o=ht.get(i);o&&ht.add(t[a],o)}const r=jn(n,{...n._zod.def,shape:t,catchall:$_(k_)}),s=ht.get(n);return s&&ht.add(r,s),r}throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function vy(n){return et(n)&&"typeName"in n._def&&n._def.typeName==="ZodEffects"}function Ey(n){return We(n)&&n._zod.def.type==="pipe"}function mr(n,e=!1){if(et(n))return vy(n)?mr(n._def.schema,e):n;if(We(n)){let t=n;if(Ey(n)&&(t=mr(n._zod.def.in,e)),e){if(Sr(t)){const s=t._zod.def.shape;for(const[a,i]of Object.entries(t._zod.def.shape))s[a]=mr(i,e);t=jn(t,{...t._zod.def,shape:s})}else if(Jd(t)){const s=mr(t._zod.def.element,e);t=jn(t,{...t._zod.def,element:s})}}const r=ht.get(n);return r&&ht.add(t,r),t}throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function ft(n){if(We(n)){const e=mr(n,!0);if(Sr(e)){const t=ci(e,!0);return oi(t)}else return oi(n)}return et(n)?yy(n):n}function Sy(n,e){if(n!==void 0&&!_n(n))return n;if(Zi(e))try{let t=e.getName();return t=t.startsWith("Runnable")?t.slice(8):t,t}catch{return e.getName()}else return e.name??"UnknownSchema"}function Oy(n){return Zi(n.data)?{type:"runnable",data:{id:n.data.lc_id,name:n.data.getName()}}:{type:"schema",data:{...ft(n.data.schema),title:n.data.name}}}class hs{constructor(e){Object.defineProperty(this,"nodes",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"edges",{enumerable:!0,configurable:!0,writable:!0,value:[]}),this.nodes=e?.nodes??this.nodes,this.edges=e?.edges??this.edges}toJSON(){const e={};return Object.values(this.nodes).forEach((t,r)=>{e[t.id]=_n(t.id)?r:t.id}),{nodes:Object.values(this.nodes).map(t=>({id:e[t.id],...Oy(t)})),edges:this.edges.map(t=>{const r={source:e[t.source],target:e[t.target]};return typeof t.data<"u"&&(r.data=t.data),typeof t.conditional<"u"&&(r.conditional=t.conditional),r})}}addNode(e,t,r){if(t!==void 0&&this.nodes[t]!==void 0)throw new Error(`Node with id ${t} already exists`);const s=t??nt(),a={id:s,data:e,name:Sy(t,e),metadata:r};return this.nodes[s]=a,a}removeNode(e){delete this.nodes[e.id],this.edges=this.edges.filter(t=>t.source!==e.id&&t.target!==e.id)}addEdge(e,t,r,s){if(this.nodes[e.id]===void 0)throw new Error(`Source node ${e.id} not in graph`);if(this.nodes[t.id]===void 0)throw new Error(`Target node ${t.id} not in graph`);const a={source:e.id,target:t.id,data:r,conditional:s};return this.edges.push(a),a}firstNode(){return vc(this)}lastNode(){return Ec(this)}extend(e,t=""){let r=t;Object.values(e.nodes).map(c=>c.id).every(_n)&&(r="");const a=c=>r?`${r}:${c}`:c;Object.entries(e.nodes).forEach(([c,l])=>{this.nodes[a(c)]={...l,id:a(c)}});const i=e.edges.map(c=>({...c,source:a(c.source),target:a(c.target)}));this.edges=[...this.edges,...i];const o=e.firstNode(),u=e.lastNode();return[o?{id:a(o.id),data:o.data}:void 0,u?{id:a(u.id),data:u.data}:void 0]}trimFirstNode(){const e=this.firstNode();e&&vc(this,[e.id])&&this.removeNode(e)}trimLastNode(){const e=this.lastNode();e&&Ec(this,[e.id])&&this.removeNode(e)}reid(){const e=Object.fromEntries(Object.values(this.nodes).map(s=>[s.id,s.name])),t=new Map;Object.values(e).forEach(s=>{t.set(s,(t.get(s)||0)+1)});const r=s=>{const a=e[s];return _n(s)&&t.get(a)===1?a:s};return new hs({nodes:Object.fromEntries(Object.entries(this.nodes).map(([s,a])=>[r(s),{...a,id:r(s)}])),edges:this.edges.map(s=>({...s,source:r(s.source),target:r(s.target)}))})}drawMermaid(e){const{withStyles:t,curveStyle:r,nodeColors:s={default:"fill:#f2f0ff,line-height:1.2",first:"fill-opacity:0",last:"fill:#bfb6fc"},wrapLabelNWords:a}=e??{},i=this.reid(),o=i.firstNode(),u=i.lastNode();return p_(i.nodes,i.edges,{firstNode:o?.id,lastNode:u?.id,withStyles:t,curveStyle:r,nodeColors:s,wrapLabelNWords:a})}async drawMermaidPng(e){const t=this.drawMermaid(e);return m_(t,{backgroundColor:e?.backgroundColor})}}function vc(n,e=[]){const t=new Set(n.edges.filter(s=>!e.includes(s.source)).map(s=>s.target)),r=[];for(const s of Object.values(n.nodes))!e.includes(s.id)&&!t.has(s.id)&&r.push(s);return r.length===1?r[0]:void 0}function Ec(n,e=[]){const t=new Set(n.edges.filter(s=>!e.includes(s.target)).map(s=>s.source)),r=[];for(const s of Object.values(n.nodes))!e.includes(s.id)&&!t.has(s.id)&&r.push(s);return r.length===1?r[0]:void 0}function Ty(n){const e=new TextEncoder,t=new ReadableStream({async start(r){for await(const s of n)r.enqueue(e.encode(`event: data
|
|
100
|
+
data: ${JSON.stringify(s)}
|
|
101
|
+
|
|
102
|
+
`));r.enqueue(e.encode(`event: end
|
|
103
|
+
|
|
104
|
+
`)),r.close()}});return $e.fromReadableStream(t)}function Sc(n){return typeof n=="object"&&n!==null&&typeof n[Symbol.iterator]=="function"&&typeof n.next=="function"}const Ay=n=>n!=null&&typeof n=="object"&&"next"in n&&typeof n.next=="function";function li(n){return typeof n=="object"&&n!==null&&typeof n[Symbol.asyncIterator]=="function"}function*Oc(n,e){for(;;){const{value:t,done:r}=gt.runWithConfig(Ht(n),e.next.bind(e),!0);if(r)break;yield t}}async function*di(n,e){const t=e[Symbol.asyncIterator]();for(;;){const{value:r,done:s}=await gt.runWithConfig(Ht(n),t.next.bind(e),!0);if(s)break;yield r}}function ce(n,e){return n&&!Array.isArray(n)&&!(n instanceof Date)&&typeof n=="object"?n:{[e]:n}}class le extends It{constructor(){super(...arguments),Object.defineProperty(this,"lc_runnable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}getName(e){const t=this.name??this.constructor.lc_name()??this.constructor.name;return e?`${t}${e}`:t}bind(e){return new At({bound:this,kwargs:e,config:{}})}map(){return new Mn({bound:this})}withRetry(e){return new Wd({bound:this,kwargs:{},config:{},maxAttemptNumber:e?.stopAfterAttempt,...e})}withConfig(e){return new At({bound:this,config:e,kwargs:{}})}withFallbacks(e){const t=Array.isArray(e)?e:e.fallbacks;return new Iy({runnable:this,fallbacks:t})}_getOptionsList(e,t=0){if(Array.isArray(e)&&e.length!==t)throw new Error(`Passed "options" must be an array with the same length as the inputs, but got ${e.length} options for ${t} inputs`);if(Array.isArray(e))return e.map(Z);if(t>1&&!Array.isArray(e)&&e.runId){console.warn("Provided runId will be used only for the first element of the batch.");const r=Object.fromEntries(Object.entries(e).filter(([s])=>s!=="runId"));return Array.from({length:t},(s,a)=>Z(a===0?e:r))}return Array.from({length:t},()=>Z(e))}async batch(e,t,r){const s=this._getOptionsList(t??{},e.length),a=s[0]?.maxConcurrency??r?.maxConcurrency,i=new Wi({maxConcurrency:a,onFailedAttempt:u=>{throw u}}),o=e.map((u,c)=>i.call(async()=>{try{return await this.invoke(u,s[c])}catch(l){if(r?.returnExceptions)return l;throw l}}));return Promise.all(o)}async*_streamIterator(e,t){yield this.invoke(e,t)}async stream(e,t){const r=Z(t),s=new Vt({generator:this._streamIterator(e,r),config:r});return await s.setup,$e.fromAsyncGenerator(s)}_separateRunnableConfigFromCallOptions(e){let t;e===void 0?t=Z(e):t=Z({callbacks:e.callbacks,tags:e.tags,metadata:e.metadata,runName:e.runName,configurable:e.configurable,recursionLimit:e.recursionLimit,maxConcurrency:e.maxConcurrency,runId:e.runId,timeout:e.timeout,signal:e.signal});const r={...e};return delete r.callbacks,delete r.tags,delete r.metadata,delete r.runName,delete r.configurable,delete r.recursionLimit,delete r.maxConcurrency,delete r.runId,delete r.timeout,delete r.signal,[t,r]}async _callWithConfig(e,t,r){const s=Z(r),i=await(await qe(s))?.handleChainStart(this.toJSON(),ce(t,"input"),s.runId,s?.runType,void 0,void 0,s?.runName??this.getName());delete s.runId;let o;try{const u=e.call(this,t,s,i);o=await _t(u,r?.signal)}catch(u){throw await i?.handleChainError(u),u}return await i?.handleChainEnd(ce(o,"output")),o}async _batchWithConfig(e,t,r,s){const a=this._getOptionsList(r??{},t.length),i=await Promise.all(a.map(qe)),o=await Promise.all(i.map(async(c,l)=>{const d=await c?.handleChainStart(this.toJSON(),ce(t[l],"input"),a[l].runId,a[l].runType,void 0,void 0,a[l].runName??this.getName());return delete a[l].runId,d}));let u;try{const c=e.call(this,t,a,o,s);u=await _t(c,a?.[0]?.signal)}catch(c){throw await Promise.all(o.map(l=>l?.handleChainError(c))),c}return await Promise.all(o.map(c=>c?.handleChainEnd(ce(u,"output")))),u}_concatOutputChunks(e,t){return os(e,t)}async*_transformStreamWithConfig(e,t,r){let s,a=!0,i,o=!0;const u=Z(r),c=await qe(u),l=this;async function*d(){for await(const f of e){if(a)if(s===void 0)s=f;else try{s=l._concatOutputChunks(s,f)}catch{s=void 0,a=!1}yield f}}let h;try{const f=await s_(t.bind(this),d(),async()=>c?.handleChainStart(this.toJSON(),{input:""},u.runId,u.runType,void 0,void 0,u.runName??this.getName()),r?.signal,u);delete u.runId,h=f.setup;const p=h?.handlers.find(o_);let m=f.output;p!==void 0&&h!==void 0&&(m=p.tapOutputIterable(h.runId,m));const g=h?.handlers.find(a_);g!==void 0&&h!==void 0&&(m=g.tapOutputIterable(h.runId,m));for await(const _ of m)if(yield _,o)if(i===void 0)i=_;else try{i=this._concatOutputChunks(i,_)}catch{i=void 0,o=!1}}catch(f){throw await h?.handleChainError(f,void 0,void 0,void 0,{inputs:ce(s,"input")}),f}await h?.handleChainEnd(i??{},void 0,void 0,void 0,{inputs:ce(s,"input")})}getGraph(e){const t=new hs,r=t.addNode({name:`${this.getName()}Input`,schema:Ft()}),s=t.addNode(this),a=t.addNode({name:`${this.getName()}Output`,schema:Ft()});return t.addEdge(r,s),t.addEdge(s,a),t}pipe(e){return new st({first:this,last:Tt(e)})}pick(e){return this.pipe(new xy(e))}assign(e){return this.pipe(new Zd(new Xt({steps:e})))}async*transform(e,t){let r;for await(const s of e)r===void 0?r=s:r=this._concatOutputChunks(r,s);yield*this._streamIterator(r,Z(t))}async*streamLog(e,t,r){const s=new gc({...r,autoClose:!1,_schemaFormat:"original"}),a=Z(t);yield*this._streamLog(e,s,a)}async*_streamLog(e,t,r){const{callbacks:s}=r;if(s===void 0)r.callbacks=[t];else if(Array.isArray(s))r.callbacks=s.concat([t]);else{const u=s.copy();u.addHandler(t,!0),r.callbacks=u}const a=this.stream(e,r);async function i(){try{const u=await a;for await(const c of u){const l=new lt({ops:[{op:"add",path:"/streamed_output/-",value:c}]});await t.writer.write(l)}}finally{await t.writer.close()}}const o=i();try{for await(const u of t)yield u}finally{await o}}streamEvents(e,t,r){let s;if(t.version==="v1")s=this._streamEventsV1(e,t,r);else if(t.version==="v2")s=this._streamEventsV2(e,t,r);else throw new Error('Only versions "v1" and "v2" of the schema are currently supported.');return t.encoding==="text/event-stream"?Ty(s):$e.fromAsyncGenerator(s)}async*_streamEventsV2(e,t,r){const s=new u_({...r,autoClose:!1}),a=Z(t),i=a.runId??nt();a.runId=i;const o=a.callbacks;if(o===void 0)a.callbacks=[s];else if(Array.isArray(o))a.callbacks=o.concat(s);else{const p=o.copy();p.addHandler(s,!0),a.callbacks=p}const u=new AbortController,c=this;async function l(){let p,m=null;try{t?.signal?"any"in AbortSignal?p=AbortSignal.any([u.signal,t.signal]):(p=t.signal,m=()=>{u.abort()},t.signal.addEventListener("abort",m,{once:!0})):p=u.signal;const g=await c.stream(e,{...a,signal:p}),_=s.tapOutputIterable(i,g);for await(const y of _)if(u.signal.aborted)break}finally{await s.finish(),p&&m&&p.removeEventListener("abort",m)}}const d=l();let h=!1,f;try{for await(const p of s){if(!h){p.data.input=e,h=!0,f=p.run_id,yield p;continue}p.run_id===f&&p.event.endsWith("_end")&&p.data?.input&&delete p.data.input,yield p}}finally{u.abort(),await d}}async*_streamEventsV1(e,t,r){let s,a=!1;const i=Z(t),o=i.tags??[],u=i.metadata??{},c=i.runName??this.getName(),l=new gc({...r,autoClose:!1,_schemaFormat:"streaming_events"}),d=new d_({...r}),h=this._streamLog(e,l,i);for await(const p of h){if(s?s=s.concat(p):s=xr.fromRunLogPatch(p),s.state===void 0)throw new Error('Internal error: "streamEvents" state is missing. Please open a bug report.');if(!a){a=!0;const y={...s.state},b={run_id:y.id,event:`on_${y.type}_start`,name:c,tags:o,metadata:u,data:{input:e}};d.includeEvent(b,y.type)&&(yield b)}const m=p.ops.filter(y=>y.path.startsWith("/logs/")).map(y=>y.path.split("/")[2]),g=[...new Set(m)];for(const y of g){let b,v={};const E=s.state.logs[y];if(E.end_time===void 0?E.streamed_output.length>0?b="stream":b="start":b="end",b==="start")E.inputs!==void 0&&(v.input=E.inputs);else if(b==="end")E.inputs!==void 0&&(v.input=E.inputs),v.output=E.final_output;else if(b==="stream"){const I=E.streamed_output.length;if(I!==1)throw new Error(`Expected exactly one chunk of streamed output, got ${I} instead. Encountered in: "${E.name}"`);v={chunk:E.streamed_output[0]},E.streamed_output=[]}yield{event:`on_${E.type}_${b}`,name:E.name,run_id:E.id,tags:E.tags,metadata:E.metadata,data:v}}const{state:_}=s;if(_.streamed_output.length>0){const y=_.streamed_output.length;if(y!==1)throw new Error(`Expected exactly one chunk of streamed output, got ${y} instead. Encountered in: "${_.name}"`);const b={chunk:_.streamed_output[0]};_.streamed_output=[];const v={event:`on_${_.type}_stream`,run_id:_.id,tags:o,metadata:u,name:c,data:b};d.includeEvent(v,_.type)&&(yield v)}}const f=s?.state;if(f!==void 0){const p={event:`on_${f.type}_end`,name:c,run_id:f.id,tags:o,metadata:u,data:{output:f.final_output}};d.includeEvent(p,f.type)&&(yield p)}}static isRunnable(e){return Zi(e)}withListeners({onStart:e,onEnd:t,onError:r}){return new At({bound:this,config:{},configFactories:[s=>({callbacks:[new Nd({config:s,onStart:e,onEnd:t,onError:r})]})]})}asTool(e){return Ry(this,e)}}class At extends le{static lc_name(){return"RunnableBinding"}constructor(e){super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"bound",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"config",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"kwargs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"configFactories",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.bound=e.bound,this.kwargs=e.kwargs,this.config=e.config,this.configFactories=e.configFactories}getName(e){return this.bound.getName(e)}async _mergeConfig(...e){const t=fc(this.config,...e);return fc(t,...this.configFactories?await Promise.all(this.configFactories.map(async r=>await r(t))):[])}bind(e){return new this.constructor({bound:this.bound,kwargs:{...this.kwargs,...e},config:this.config})}withConfig(e){return new this.constructor({bound:this.bound,kwargs:this.kwargs,config:{...this.config,...e}})}withRetry(e){return new Wd({bound:this.bound,kwargs:this.kwargs,config:this.config,maxAttemptNumber:e?.stopAfterAttempt,...e})}async invoke(e,t){return this.bound.invoke(e,await this._mergeConfig(Z(t),this.kwargs))}async batch(e,t,r){const s=Array.isArray(t)?await Promise.all(t.map(async a=>this._mergeConfig(Z(a),this.kwargs))):await this._mergeConfig(Z(t),this.kwargs);return this.bound.batch(e,s,r)}_concatOutputChunks(e,t){return this.bound._concatOutputChunks(e,t)}async*_streamIterator(e,t){yield*this.bound._streamIterator(e,await this._mergeConfig(Z(t),this.kwargs))}async stream(e,t){return this.bound.stream(e,await this._mergeConfig(Z(t),this.kwargs))}async*transform(e,t){yield*this.bound.transform(e,await this._mergeConfig(Z(t),this.kwargs))}streamEvents(e,t,r){const s=this,a=async function*(){yield*s.bound.streamEvents(e,{...await s._mergeConfig(Z(t),s.kwargs),version:t.version},r)};return $e.fromAsyncGenerator(a())}static isRunnableBinding(e){return e.bound&&le.isRunnable(e.bound)}withListeners({onStart:e,onEnd:t,onError:r}){return new At({bound:this.bound,kwargs:this.kwargs,config:this.config,configFactories:[s=>({callbacks:[new Nd({config:s,onStart:e,onEnd:t,onError:r})]})]})}}class Mn extends le{static lc_name(){return"RunnableEach"}constructor(e){super(e),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"bound",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.bound=e.bound}bind(e){return new Mn({bound:this.bound.bind(e)})}async invoke(e,t){return this._callWithConfig(this._invoke.bind(this),e,t)}async _invoke(e,t,r){return this.bound.batch(e,ge(t,{callbacks:r?.getChild()}))}withListeners({onStart:e,onEnd:t,onError:r}){return new Mn({bound:this.bound.withListeners({onStart:e,onEnd:t,onError:r})})}}class Wd extends At{static lc_name(){return"RunnableRetry"}constructor(e){super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"maxAttemptNumber",{enumerable:!0,configurable:!0,writable:!0,value:3}),Object.defineProperty(this,"onFailedAttempt",{enumerable:!0,configurable:!0,writable:!0,value:()=>{}}),this.maxAttemptNumber=e.maxAttemptNumber??this.maxAttemptNumber,this.onFailedAttempt=e.onFailedAttempt??this.onFailedAttempt}_patchConfigForRetry(e,t,r){const s=e>1?`retry:attempt:${e}`:void 0;return ge(t,{callbacks:r?.getChild(s)})}async _invoke(e,t,r){return In(s=>super.invoke(e,this._patchConfigForRetry(s,t,r)),{onFailedAttempt:s=>this.onFailedAttempt(s,e),retries:Math.max(this.maxAttemptNumber-1,0),randomize:!0})}async invoke(e,t){return this._callWithConfig(this._invoke.bind(this),e,t)}async _batch(e,t,r,s){const a={};try{await In(async i=>{const o=e.map((h,f)=>f).filter(h=>a[h.toString()]===void 0||a[h.toString()]instanceof Error),u=o.map(h=>e[h]),c=o.map(h=>this._patchConfigForRetry(i,t?.[h],r?.[h])),l=await super.batch(u,c,{...s,returnExceptions:!0});let d;for(let h=0;h<l.length;h+=1){const f=l[h],p=o[h];f instanceof Error&&d===void 0&&(d=f,d.input=u[h]),a[p.toString()]=f}if(d)throw d;return l},{onFailedAttempt:i=>this.onFailedAttempt(i,i.input),retries:Math.max(this.maxAttemptNumber-1,0),randomize:!0})}catch(i){if(s?.returnExceptions!==!0)throw i}return Object.keys(a).sort((i,o)=>parseInt(i,10)-parseInt(o,10)).map(i=>a[parseInt(i,10)])}async batch(e,t,r){return this._batchWithConfig(this._batch.bind(this),e,t,r)}}class st extends le{static lc_name(){return"RunnableSequence"}constructor(e){super(e),Object.defineProperty(this,"first",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"middle",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"last",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"omitSequenceTags",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),this.first=e.first,this.middle=e.middle??this.middle,this.last=e.last,this.name=e.name,this.omitSequenceTags=e.omitSequenceTags??this.omitSequenceTags}get steps(){return[this.first,...this.middle,this.last]}async invoke(e,t){const r=Z(t),a=await(await qe(r))?.handleChainStart(this.toJSON(),ce(e,"input"),r.runId,void 0,void 0,void 0,r?.runName);delete r.runId;let i=e,o;try{const u=[this.first,...this.middle];for(let c=0;c<u.length;c+=1){const d=u[c].invoke(i,ge(r,{callbacks:a?.getChild(this.omitSequenceTags?void 0:`seq:step:${c+1}`)}));i=await _t(d,t?.signal)}if(t?.signal?.aborted)throw new Error("Aborted");o=await this.last.invoke(i,ge(r,{callbacks:a?.getChild(this.omitSequenceTags?void 0:`seq:step:${this.steps.length}`)}))}catch(u){throw await a?.handleChainError(u),u}return await a?.handleChainEnd(ce(o,"output")),o}async batch(e,t,r){const s=this._getOptionsList(t??{},e.length),a=await Promise.all(s.map(qe)),i=await Promise.all(a.map(async(u,c)=>{const l=await u?.handleChainStart(this.toJSON(),ce(e[c],"input"),s[c].runId,void 0,void 0,void 0,s[c].runName);return delete s[c].runId,l}));let o=e;try{for(let u=0;u<this.steps.length;u+=1){const l=this.steps[u].batch(o,i.map((d,h)=>{const f=d?.getChild(this.omitSequenceTags?void 0:`seq:step:${u+1}`);return ge(s[h],{callbacks:f})}),r);o=await _t(l,s[0]?.signal)}}catch(u){throw await Promise.all(i.map(c=>c?.handleChainError(u))),u}return await Promise.all(i.map(u=>u?.handleChainEnd(ce(o,"output")))),o}_concatOutputChunks(e,t){return this.last._concatOutputChunks(e,t)}async*_streamIterator(e,t){const r=await qe(t),{runId:s,...a}=t??{},i=await r?.handleChainStart(this.toJSON(),ce(e,"input"),s,void 0,void 0,void 0,a?.runName),o=[this.first,...this.middle,this.last];let u=!0,c;async function*l(){yield e}try{let d=o[0].transform(l(),ge(a,{callbacks:i?.getChild(this.omitSequenceTags?void 0:"seq:step:1")}));for(let h=1;h<o.length;h+=1)d=await o[h].transform(d,ge(a,{callbacks:i?.getChild(this.omitSequenceTags?void 0:`seq:step:${h+1}`)}));for await(const h of d)if(t?.signal?.throwIfAborted(),yield h,u)if(c===void 0)c=h;else try{c=this._concatOutputChunks(c,h)}catch{c=void 0,u=!1}}catch(d){throw await i?.handleChainError(d),d}await i?.handleChainEnd(ce(c,"output"))}getGraph(e){const t=new hs;let r=null;return this.steps.forEach((s,a)=>{const i=s.getGraph(e);a!==0&&i.trimFirstNode(),a!==this.steps.length-1&&i.trimLastNode(),t.extend(i);const o=i.firstNode();if(!o)throw new Error(`Runnable ${s} has no first node`);r&&t.addEdge(r,o),r=i.lastNode()}),t}pipe(e){return st.isRunnableSequence(e)?new st({first:this.first,middle:this.middle.concat([this.last,e.first,...e.middle]),last:e.last,name:this.name??e.name}):new st({first:this.first,middle:[...this.middle,this.last],last:Tt(e),name:this.name})}static isRunnableSequence(e){return Array.isArray(e.middle)&&le.isRunnable(e)}static from([e,...t],r){let s={};return typeof r=="string"?s.name=r:r!==void 0&&(s=r),new st({...s,first:Tt(e),middle:t.slice(0,-1).map(Tt),last:Tt(t[t.length-1])})}}class Xt extends le{static lc_name(){return"RunnableMap"}getStepsKeys(){return Object.keys(this.steps)}constructor(e){super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"steps",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.steps={};for(const[t,r]of Object.entries(e.steps))this.steps[t]=Tt(r)}static from(e){return new Xt({steps:e})}async invoke(e,t){const r=Z(t),a=await(await qe(r))?.handleChainStart(this.toJSON(),{input:e},r.runId,void 0,void 0,void 0,r?.runName);delete r.runId;const i={};try{const o=Object.entries(this.steps).map(async([u,c])=>{i[u]=await c.invoke(e,ge(r,{callbacks:a?.getChild(`map:key:${u}`)}))});await _t(Promise.all(o),t?.signal)}catch(o){throw await a?.handleChainError(o),o}return await a?.handleChainEnd(i),i}async*_transform(e,t,r){const s={...this.steps},a=$d(e,Object.keys(s).length),i=new Map(Object.entries(s).map(([o,u],c)=>{const l=u.transform(a[c],ge(r,{callbacks:t?.getChild(`map:key:${o}`)}));return[o,l.next().then(d=>({key:o,gen:l,result:d}))]}));for(;i.size;){const o=Promise.race(i.values()),{key:u,result:c,gen:l}=await _t(o,r?.signal);i.delete(u),c.done||(yield{[u]:c.value},i.set(u,l.next().then(d=>({key:u,gen:l,result:d}))))}}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){async function*r(){yield e}const s=Z(t),a=new Vt({generator:this.transform(r(),s),config:s});return await a.setup,$e.fromAsyncGenerator(a)}}class Vi extends le{constructor(e){if(super(e),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"func",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),!Ui(e.func))throw new Error("RunnableTraceable requires a function that is wrapped in traceable higher-order function");this.func=e.func}async invoke(e,t){const[r]=this._getOptionsList(t??{},1),s=await qe(r),a=this.func(ge(r,{callbacks:s}),e);return _t(a,r?.signal)}async*_streamIterator(e,t){const[r]=this._getOptionsList(t??{},1),s=await this.invoke(e,t);if(li(s)){for await(const a of s)r?.signal?.throwIfAborted(),yield a;return}if(Ay(s)){for(;;){r?.signal?.throwIfAborted();const a=s.next();if(a.done)break;yield a.value}return}yield s}static from(e){return new Vi({func:e})}}function Py(n){if(Ui(n))throw new Error("RunnableLambda requires a function that is not wrapped in traceable higher-order function. This shouldn't happen.")}class Qt extends le{static lc_name(){return"RunnableLambda"}constructor(e){if(Ui(e.func))return Vi.from(e.func);super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"func",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Py(e.func),this.func=e.func}static from(e){return new Qt({func:e})}async _invoke(e,t,r){return new Promise((s,a)=>{const i=ge(t,{callbacks:r?.getChild(),recursionLimit:(t?.recursionLimit??Ca)-1});gt.runWithConfig(Ht(i),async()=>{try{let o=await this.func(e,{...i});if(o&&le.isRunnable(o)){if(t?.recursionLimit===0)throw new Error("Recursion limit reached.");o=await o.invoke(e,{...i,recursionLimit:(i.recursionLimit??Ca)-1})}else if(li(o)){let u;for await(const c of di(i,o))if(t?.signal?.throwIfAborted(),u===void 0)u=c;else try{u=this._concatOutputChunks(u,c)}catch{u=c}o=u}else if(Sc(o)){let u;for(const c of Oc(i,o))if(t?.signal?.throwIfAborted(),u===void 0)u=c;else try{u=this._concatOutputChunks(u,c)}catch{u=c}o=u}s(o)}catch(o){a(o)}})})}async invoke(e,t){return this._callWithConfig(this._invoke.bind(this),e,t)}async*_transform(e,t,r){let s;for await(const o of e)if(s===void 0)s=o;else try{s=this._concatOutputChunks(s,o)}catch{s=o}const a=ge(r,{callbacks:t?.getChild(),recursionLimit:(r?.recursionLimit??Ca)-1}),i=await new Promise((o,u)=>{gt.runWithConfig(Ht(a),async()=>{try{const c=await this.func(s,{...a,config:a});o(c)}catch(c){u(c)}})});if(i&&le.isRunnable(i)){if(r?.recursionLimit===0)throw new Error("Recursion limit reached.");const o=await i.stream(s,a);for await(const u of o)yield u}else if(li(i))for await(const o of di(a,i))r?.signal?.throwIfAborted(),yield o;else if(Sc(i))for(const o of Oc(a,i))r?.signal?.throwIfAborted(),yield o;else yield i}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){async function*r(){yield e}const s=Z(t),a=new Vt({generator:this.transform(r(),s),config:s});return await a.setup,$e.fromAsyncGenerator(a)}}class Iy extends le{static lc_name(){return"RunnableWithFallbacks"}constructor(e){super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"runnable",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"fallbacks",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.runnable=e.runnable,this.fallbacks=e.fallbacks}*runnables(){yield this.runnable;for(const e of this.fallbacks)yield e}async invoke(e,t){const r=Z(t),s=await qe(r),{runId:a,...i}=r,o=await s?.handleChainStart(this.toJSON(),ce(e,"input"),a,void 0,void 0,void 0,i?.runName),u=ge(i,{callbacks:o?.getChild()});return await gt.runWithConfig(u,async()=>{let l;for(const d of this.runnables()){r?.signal?.throwIfAborted();try{const h=await d.invoke(e,u);return await o?.handleChainEnd(ce(h,"output")),h}catch(h){l===void 0&&(l=h)}}throw l===void 0?new Error("No error stored at end of fallback."):(await o?.handleChainError(l),l)})}async*_streamIterator(e,t){const r=Z(t),s=await qe(r),{runId:a,...i}=r,o=await s?.handleChainStart(this.toJSON(),ce(e,"input"),a,void 0,void 0,void 0,i?.runName);let u,c;for(const d of this.runnables()){r?.signal?.throwIfAborted();const h=ge(i,{callbacks:o?.getChild()});try{const f=await d.stream(e,h);c=di(h,f);break}catch(f){u===void 0&&(u=f)}}if(c===void 0){const d=u??new Error("No error stored at end of fallback.");throw await o?.handleChainError(d),d}let l;try{for await(const d of c){yield d;try{l=l===void 0?l:this._concatOutputChunks(l,d)}catch{l=void 0}}}catch(d){throw await o?.handleChainError(d),d}await o?.handleChainEnd(ce(l,"output"))}async batch(e,t,r){if(r?.returnExceptions)throw new Error("Not implemented.");const s=this._getOptionsList(t??{},e.length),a=await Promise.all(s.map(u=>qe(u))),i=await Promise.all(a.map(async(u,c)=>{const l=await u?.handleChainStart(this.toJSON(),ce(e[c],"input"),s[c].runId,void 0,void 0,void 0,s[c].runName);return delete s[c].runId,l}));let o;for(const u of this.runnables()){s[0].signal?.throwIfAborted();try{const c=await u.batch(e,i.map((l,d)=>ge(s[d],{callbacks:l?.getChild()})),r);return await Promise.all(i.map((l,d)=>l?.handleChainEnd(ce(c[d],"output")))),c}catch(c){o===void 0&&(o=c)}}throw o?(await Promise.all(i.map(u=>u?.handleChainError(o))),o):new Error("No error stored at end of fallbacks.")}}function Tt(n){if(typeof n=="function")return new Qt({func:n});if(le.isRunnable(n))return n;if(!Array.isArray(n)&&typeof n=="object"){const e={};for(const[t,r]of Object.entries(n))e[t]=Tt(r);return new Xt({steps:e})}else throw new Error(`Expected a Runnable, function or object.
|
|
105
|
+
Instead got an unsupported type.`)}class Zd extends le{static lc_name(){return"RunnableAssign"}constructor(e){e instanceof Xt&&(e={mapper:e}),super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"mapper",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.mapper=e.mapper}async invoke(e,t){const r=await this.mapper.invoke(e,t);return{...e,...r}}async*_transform(e,t,r){const s=this.mapper.getStepsKeys(),[a,i]=$d(e),o=this.mapper.transform(i,ge(r,{callbacks:t?.getChild()})),u=o.next();for await(const c of a){if(typeof c!="object"||Array.isArray(c))throw new Error(`RunnableAssign can only be used with objects as input, got ${typeof c}`);const l=Object.fromEntries(Object.entries(c).filter(([d])=>!s.includes(d)));Object.keys(l).length>0&&(yield l)}yield(await u).value;for await(const c of o)yield c}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){async function*r(){yield e}const s=Z(t),a=new Vt({generator:this.transform(r(),s),config:s});return await a.setup,$e.fromAsyncGenerator(a)}}class xy extends le{static lc_name(){return"RunnablePick"}constructor(e){(typeof e=="string"||Array.isArray(e))&&(e={keys:e}),super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"keys",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.keys=e.keys}async _pick(e){if(typeof this.keys=="string")return e[this.keys];{const t=this.keys.map(r=>[r,e[r]]).filter(r=>r[1]!==void 0);return t.length===0?void 0:Object.fromEntries(t)}}async invoke(e,t){return this._callWithConfig(this._pick.bind(this),e,t)}async*_transform(e){for await(const t of e){const r=await this._pick(t);r!==void 0&&(yield r)}}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){async function*r(){yield e}const s=Z(t),a=new Vt({generator:this.transform(r(),s),config:s});return await a.setup,$e.fromAsyncGenerator(a)}}class Tc extends At{constructor(e){const t=st.from([Qt.from(async r=>{let s;if(ud(r))try{s=await Gd(this.schema,r.args)}catch{throw new Wf("Received tool input did not match expected schema",JSON.stringify(r.args))}else s=r;return s}).withConfig({runName:`${e.name}:parse_input`}),e.bound]).withConfig({runName:e.name});super({bound:t,config:e.config??{}}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"description",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"schema",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=e.name,this.description=e.description,this.schema=e.schema}static lc_name(){return"RunnableToolLike"}}function Ry(n,e){const t=e.name??n.getName(),r=e.description??Ki(e.schema);return wy(e.schema)?new Tc({name:t,description:r,schema:gr({input:mi()}).transform(s=>s.input),bound:n}):new Tc({name:t,description:r,schema:e.schema,bound:n})}/*
|
|
106
|
+
* [js-sha1]{@link https://github.com/emn178/js-sha1}
|
|
107
|
+
*
|
|
108
|
+
* @version 0.6.0
|
|
109
|
+
* @author Chen, Yi-Cyuan [emn178@gmail.com]
|
|
110
|
+
* @copyright Chen, Yi-Cyuan 2014-2017
|
|
111
|
+
* @license MIT
|
|
112
|
+
*/var ky=typeof window=="object"?window:{},B="0123456789abcdef".split(""),Cy=[-2147483648,8388608,32768,128],De=[24,16,8,0],oe=[];function He(n){n?(oe[0]=oe[16]=oe[1]=oe[2]=oe[3]=oe[4]=oe[5]=oe[6]=oe[7]=oe[8]=oe[9]=oe[10]=oe[11]=oe[12]=oe[13]=oe[14]=oe[15]=0,this.blocks=oe):this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],this.h0=1732584193,this.h1=4023233417,this.h2=2562383102,this.h3=271733878,this.h4=3285377520,this.block=this.start=this.bytes=this.hBytes=0,this.finalized=this.hashed=!1,this.first=!0}He.prototype.update=function(n){if(!this.finalized){var e=typeof n!="string";e&&n.constructor===ky.ArrayBuffer&&(n=new Uint8Array(n));for(var t,r=0,s,a=n.length||0,i=this.blocks;r<a;){if(this.hashed&&(this.hashed=!1,i[0]=this.block,i[16]=i[1]=i[2]=i[3]=i[4]=i[5]=i[6]=i[7]=i[8]=i[9]=i[10]=i[11]=i[12]=i[13]=i[14]=i[15]=0),e)for(s=this.start;r<a&&s<64;++r)i[s>>2]|=n[r]<<De[s++&3];else for(s=this.start;r<a&&s<64;++r)t=n.charCodeAt(r),t<128?i[s>>2]|=t<<De[s++&3]:t<2048?(i[s>>2]|=(192|t>>6)<<De[s++&3],i[s>>2]|=(128|t&63)<<De[s++&3]):t<55296||t>=57344?(i[s>>2]|=(224|t>>12)<<De[s++&3],i[s>>2]|=(128|t>>6&63)<<De[s++&3],i[s>>2]|=(128|t&63)<<De[s++&3]):(t=65536+((t&1023)<<10|n.charCodeAt(++r)&1023),i[s>>2]|=(240|t>>18)<<De[s++&3],i[s>>2]|=(128|t>>12&63)<<De[s++&3],i[s>>2]|=(128|t>>6&63)<<De[s++&3],i[s>>2]|=(128|t&63)<<De[s++&3]);this.lastByteIndex=s,this.bytes+=s-this.start,s>=64?(this.block=i[16],this.start=s-64,this.hash(),this.hashed=!0):this.start=s}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296<<0,this.bytes=this.bytes%4294967296),this}};He.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var n=this.blocks,e=this.lastByteIndex;n[16]=this.block,n[e>>2]|=Cy[e&3],this.block=n[16],e>=56&&(this.hashed||this.hash(),n[0]=this.block,n[16]=n[1]=n[2]=n[3]=n[4]=n[5]=n[6]=n[7]=n[8]=n[9]=n[10]=n[11]=n[12]=n[13]=n[14]=n[15]=0),n[14]=this.hBytes<<3|this.bytes>>>29,n[15]=this.bytes<<3,this.hash()}};He.prototype.hash=function(){var n=this.h0,e=this.h1,t=this.h2,r=this.h3,s=this.h4,a,i,o,u=this.blocks;for(i=16;i<80;++i)o=u[i-3]^u[i-8]^u[i-14]^u[i-16],u[i]=o<<1|o>>>31;for(i=0;i<20;i+=5)a=e&t|~e&r,o=n<<5|n>>>27,s=o+a+s+1518500249+u[i]<<0,e=e<<30|e>>>2,a=n&e|~n&t,o=s<<5|s>>>27,r=o+a+r+1518500249+u[i+1]<<0,n=n<<30|n>>>2,a=s&n|~s&e,o=r<<5|r>>>27,t=o+a+t+1518500249+u[i+2]<<0,s=s<<30|s>>>2,a=r&s|~r&n,o=t<<5|t>>>27,e=o+a+e+1518500249+u[i+3]<<0,r=r<<30|r>>>2,a=t&r|~t&s,o=e<<5|e>>>27,n=o+a+n+1518500249+u[i+4]<<0,t=t<<30|t>>>2;for(;i<40;i+=5)a=e^t^r,o=n<<5|n>>>27,s=o+a+s+1859775393+u[i]<<0,e=e<<30|e>>>2,a=n^e^t,o=s<<5|s>>>27,r=o+a+r+1859775393+u[i+1]<<0,n=n<<30|n>>>2,a=s^n^e,o=r<<5|r>>>27,t=o+a+t+1859775393+u[i+2]<<0,s=s<<30|s>>>2,a=r^s^n,o=t<<5|t>>>27,e=o+a+e+1859775393+u[i+3]<<0,r=r<<30|r>>>2,a=t^r^s,o=e<<5|e>>>27,n=o+a+n+1859775393+u[i+4]<<0,t=t<<30|t>>>2;for(;i<60;i+=5)a=e&t|e&r|t&r,o=n<<5|n>>>27,s=o+a+s-1894007588+u[i]<<0,e=e<<30|e>>>2,a=n&e|n&t|e&t,o=s<<5|s>>>27,r=o+a+r-1894007588+u[i+1]<<0,n=n<<30|n>>>2,a=s&n|s&e|n&e,o=r<<5|r>>>27,t=o+a+t-1894007588+u[i+2]<<0,s=s<<30|s>>>2,a=r&s|r&n|s&n,o=t<<5|t>>>27,e=o+a+e-1894007588+u[i+3]<<0,r=r<<30|r>>>2,a=t&r|t&s|r&s,o=e<<5|e>>>27,n=o+a+n-1894007588+u[i+4]<<0,t=t<<30|t>>>2;for(;i<80;i+=5)a=e^t^r,o=n<<5|n>>>27,s=o+a+s-899497514+u[i]<<0,e=e<<30|e>>>2,a=n^e^t,o=s<<5|s>>>27,r=o+a+r-899497514+u[i+1]<<0,n=n<<30|n>>>2,a=s^n^e,o=r<<5|r>>>27,t=o+a+t-899497514+u[i+2]<<0,s=s<<30|s>>>2,a=r^s^n,o=t<<5|t>>>27,e=o+a+e-899497514+u[i+3]<<0,r=r<<30|r>>>2,a=t^r^s,o=e<<5|e>>>27,n=o+a+n-899497514+u[i+4]<<0,t=t<<30|t>>>2;this.h0=this.h0+n<<0,this.h1=this.h1+e<<0,this.h2=this.h2+t<<0,this.h3=this.h3+r<<0,this.h4=this.h4+s<<0};He.prototype.hex=function(){this.finalize();var n=this.h0,e=this.h1,t=this.h2,r=this.h3,s=this.h4;return B[n>>28&15]+B[n>>24&15]+B[n>>20&15]+B[n>>16&15]+B[n>>12&15]+B[n>>8&15]+B[n>>4&15]+B[n&15]+B[e>>28&15]+B[e>>24&15]+B[e>>20&15]+B[e>>16&15]+B[e>>12&15]+B[e>>8&15]+B[e>>4&15]+B[e&15]+B[t>>28&15]+B[t>>24&15]+B[t>>20&15]+B[t>>16&15]+B[t>>12&15]+B[t>>8&15]+B[t>>4&15]+B[t&15]+B[r>>28&15]+B[r>>24&15]+B[r>>20&15]+B[r>>16&15]+B[r>>12&15]+B[r>>8&15]+B[r>>4&15]+B[r&15]+B[s>>28&15]+B[s>>24&15]+B[s>>20&15]+B[s>>16&15]+B[s>>12&15]+B[s>>8&15]+B[s>>4&15]+B[s&15]};He.prototype.toString=He.prototype.hex;He.prototype.digest=function(){this.finalize();var n=this.h0,e=this.h1,t=this.h2,r=this.h3,s=this.h4;return[n>>24&255,n>>16&255,n>>8&255,n&255,e>>24&255,e>>16&255,e>>8&255,e&255,t>>24&255,t>>16&255,t>>8&255,t&255,r>>24&255,r>>16&255,r>>8&255,r&255,s>>24&255,s>>16&255,s>>8&255,s&255]};He.prototype.array=He.prototype.digest;He.prototype.arrayBuffer=function(){this.finalize();var n=new ArrayBuffer(20),e=new DataView(n);return e.setUint32(0,this.h0),e.setUint32(4,this.h1),e.setUint32(8,this.h2),e.setUint32(12,this.h3),e.setUint32(16,this.h4),n};let Ac=!1;const $y=n=>(Ac||(console.warn(["The default method for hashing keys is insecure and will be replaced in a future version,","but hasn't been replaced yet as to not break existing caches. It's recommended that you use","a more secure hashing algorithm to avoid cache poisoning.","","See this page for more information:","|","└> https://js.langchain.com/docs/troubleshooting/warnings/insecure-cache-algorithm"].join(`
|
|
113
|
+
`)),Ac=!0),new He(!0).update(n).hex()),Ny=(...n)=>$y(n.join("_"));class jy{constructor(){Object.defineProperty(this,"keyEncoder",{enumerable:!0,configurable:!0,writable:!0,value:Ny})}makeDefaultKeyEncoder(e){this.keyEncoder=e}}const Ly=new Map;class Xi extends jy{constructor(e){super(),Object.defineProperty(this,"cache",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.cache=e??new Map}lookup(e,t){return Promise.resolve(this.cache.get(this.keyEncoder(e,t))??null)}async update(e,t,r){this.cache.set(this.keyEncoder(e,t),r)}static global(){return new Xi(Ly)}}class Kd extends It{}class My extends Kd{static lc_name(){return"StringPromptValue"}constructor(e){super({value:e}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","prompt_values"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"value",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.value=e}toString(){return this.value}toChatMessages(){return[new Yn(this.value)]}}class Uy extends Kd{static lc_name(){return"ChatPromptValue"}constructor(e){Array.isArray(e)&&(e={messages:e}),super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","prompt_values"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"messages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.messages=e.messages}toString(){return cd(this.messages)}toChatMessages(){return this.messages}}var sr={},Pc;function Dy(){if(Pc)return sr;Pc=1,sr.byteLength=o,sr.toByteArray=c,sr.fromByteArray=h;for(var n=[],e=[],t=typeof Uint8Array<"u"?Uint8Array:Array,r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",s=0,a=r.length;s<a;++s)n[s]=r[s],e[r.charCodeAt(s)]=s;e[45]=62,e[95]=63;function i(f){var p=f.length;if(p%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var m=f.indexOf("=");m===-1&&(m=p);var g=m===p?0:4-m%4;return[m,g]}function o(f){var p=i(f),m=p[0],g=p[1];return(m+g)*3/4-g}function u(f,p,m){return(p+m)*3/4-m}function c(f){var p,m=i(f),g=m[0],_=m[1],y=new t(u(f,g,_)),b=0,v=_>0?g-4:g,E;for(E=0;E<v;E+=4)p=e[f.charCodeAt(E)]<<18|e[f.charCodeAt(E+1)]<<12|e[f.charCodeAt(E+2)]<<6|e[f.charCodeAt(E+3)],y[b++]=p>>16&255,y[b++]=p>>8&255,y[b++]=p&255;return _===2&&(p=e[f.charCodeAt(E)]<<2|e[f.charCodeAt(E+1)]>>4,y[b++]=p&255),_===1&&(p=e[f.charCodeAt(E)]<<10|e[f.charCodeAt(E+1)]<<4|e[f.charCodeAt(E+2)]>>2,y[b++]=p>>8&255,y[b++]=p&255),y}function l(f){return n[f>>18&63]+n[f>>12&63]+n[f>>6&63]+n[f&63]}function d(f,p,m){for(var g,_=[],y=p;y<m;y+=3)g=(f[y]<<16&16711680)+(f[y+1]<<8&65280)+(f[y+2]&255),_.push(l(g));return _.join("")}function h(f){for(var p,m=f.length,g=m%3,_=[],y=16383,b=0,v=m-g;b<v;b+=y)_.push(d(f,b,b+y>v?v:b+y));return g===1?(p=f[m-1],_.push(n[p>>2]+n[p<<4&63]+"==")):g===2&&(p=(f[m-2]<<8)+f[m-1],_.push(n[p>>10]+n[p>>4&63]+n[p<<2&63]+"=")),_.join("")}return sr}var Fy=Dy();const By=Rr(Fy);var zy=Object.defineProperty,qy=(n,e,t)=>e in n?zy(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,Hy=(n,e,t)=>(qy(n,e+"",t),t);function Gy(n,e){let t=Array.from({length:n.length},(r,s)=>({start:s,end:s+1}));for(;t.length>1;){let r=null;for(let s=0;s<t.length-1;s++){const a=n.slice(t[s].start,t[s+1].end),i=e.get(a.join(","));i!=null&&(r==null||i<r[0])&&(r=[i,s])}if(r!=null){const s=r[1];t[s]={start:t[s].start,end:t[s+1].end},t.splice(s+1,1)}else break}return t}function Jy(n,e){return n.length===1?[e.get(n.join(","))]:Gy(n,e).map(t=>e.get(n.slice(t.start,t.end).join(","))).filter(t=>t!=null)}function Wy(n){return n.replace(/[\\^$*+?.()|[\]{}]/g,"\\$&")}var hi=class{specialTokens;inverseSpecialTokens;patStr;textEncoder=new TextEncoder;textDecoder=new TextDecoder("utf-8");rankMap=new Map;textMap=new Map;constructor(n,e){this.patStr=n.pat_str;const t=n.bpe_ranks.split(`
|
|
114
|
+
`).filter(Boolean).reduce((r,s)=>{const[a,i,...o]=s.split(" "),u=Number.parseInt(i,10);return o.forEach((c,l)=>r[c]=u+l),r},{});for(const[r,s]of Object.entries(t)){const a=By.toByteArray(r);this.rankMap.set(a.join(","),s),this.textMap.set(s,a)}this.specialTokens={...n.special_tokens,...e},this.inverseSpecialTokens=Object.entries(this.specialTokens).reduce((r,[s,a])=>(r[a]=this.textEncoder.encode(s),r),{})}encode(n,e=[],t="all"){const r=new RegExp(this.patStr,"ug"),s=hi.specialTokenRegex(Object.keys(this.specialTokens)),a=[],i=new Set(e==="all"?Object.keys(this.specialTokens):e),o=new Set(t==="all"?Object.keys(this.specialTokens).filter(c=>!i.has(c)):t);if(o.size>0){const c=hi.specialTokenRegex([...o]),l=n.match(c);if(l!=null)throw new Error(`The text contains a special token that is not allowed: ${l[0]}`)}let u=0;for(;;){let c=null,l=u;for(;s.lastIndex=l,c=s.exec(n),!(c==null||i.has(c[0]));)l=c.index+1;const d=c?.index??n.length;for(const f of n.substring(u,d).matchAll(r)){const p=this.textEncoder.encode(f[0]),m=this.rankMap.get(p.join(","));if(m!=null){a.push(m);continue}a.push(...Jy(p,this.rankMap))}if(c==null)break;let h=this.specialTokens[c[0]];a.push(h),u=c.index+c[0].length}return a}decode(n){const e=[];let t=0;for(let a=0;a<n.length;++a){const i=n[a],o=this.textMap.get(i)??this.inverseSpecialTokens[i];o!=null&&(e.push(o),t+=o.length)}const r=new Uint8Array(t);let s=0;for(const a of e)r.set(a,s),s+=a.length;return this.textDecoder.decode(r)}},Vd=hi;Hy(Vd,"specialTokenRegex",n=>new RegExp(n.map(e=>Wy(e)).join("|"),"g"));function Zy(n){switch(n){case"gpt2":return"gpt2";case"code-cushman-001":case"code-cushman-002":case"code-davinci-001":case"code-davinci-002":case"cushman-codex":case"davinci-codex":case"davinci-002":case"text-davinci-002":case"text-davinci-003":return"p50k_base";case"code-davinci-edit-001":case"text-davinci-edit-001":return"p50k_edit";case"ada":case"babbage":case"babbage-002":case"code-search-ada-code-001":case"code-search-babbage-code-001":case"curie":case"davinci":case"text-ada-001":case"text-babbage-001":case"text-curie-001":case"text-davinci-001":case"text-search-ada-doc-001":case"text-search-babbage-doc-001":case"text-search-curie-doc-001":case"text-search-davinci-doc-001":case"text-similarity-ada-001":case"text-similarity-babbage-001":case"text-similarity-curie-001":case"text-similarity-davinci-001":return"r50k_base";case"gpt-3.5-turbo-instruct-0914":case"gpt-3.5-turbo-instruct":case"gpt-3.5-turbo-16k-0613":case"gpt-3.5-turbo-16k":case"gpt-3.5-turbo-0613":case"gpt-3.5-turbo-0301":case"gpt-3.5-turbo":case"gpt-4-32k-0613":case"gpt-4-32k-0314":case"gpt-4-32k":case"gpt-4-0613":case"gpt-4-0314":case"gpt-4":case"gpt-3.5-turbo-1106":case"gpt-35-turbo":case"gpt-4-1106-preview":case"gpt-4-vision-preview":case"gpt-3.5-turbo-0125":case"gpt-4-turbo":case"gpt-4-turbo-2024-04-09":case"gpt-4-turbo-preview":case"gpt-4-0125-preview":case"text-embedding-ada-002":case"text-embedding-3-small":case"text-embedding-3-large":return"cl100k_base";case"gpt-4o":case"gpt-4o-2024-05-13":case"gpt-4o-2024-08-06":case"gpt-4o-2024-11-20":case"gpt-4o-mini-2024-07-18":case"gpt-4o-mini":case"gpt-4o-search-preview":case"gpt-4o-search-preview-2025-03-11":case"gpt-4o-mini-search-preview":case"gpt-4o-mini-search-preview-2025-03-11":case"gpt-4o-audio-preview":case"gpt-4o-audio-preview-2024-12-17":case"gpt-4o-audio-preview-2024-10-01":case"gpt-4o-mini-audio-preview":case"gpt-4o-mini-audio-preview-2024-12-17":case"o1":case"o1-2024-12-17":case"o1-mini":case"o1-mini-2024-09-12":case"o1-preview":case"o1-preview-2024-09-12":case"o1-pro":case"o1-pro-2025-03-19":case"o3":case"o3-2025-04-16":case"o3-mini":case"o3-mini-2025-01-31":case"o4-mini":case"o4-mini-2025-04-16":case"chatgpt-4o-latest":case"gpt-4o-realtime":case"gpt-4o-realtime-preview-2024-10-01":case"gpt-4o-realtime-preview-2024-12-17":case"gpt-4o-mini-realtime-preview":case"gpt-4o-mini-realtime-preview-2024-12-17":case"gpt-4.1":case"gpt-4.1-2025-04-14":case"gpt-4.1-mini":case"gpt-4.1-mini-2025-04-14":case"gpt-4.1-nano":case"gpt-4.1-nano-2025-04-14":case"gpt-4.5-preview":case"gpt-4.5-preview-2025-02-27":case"gpt-5":case"gpt-5-2025-08-07":case"gpt-5-nano":case"gpt-5-nano-2025-08-07":case"gpt-5-mini":case"gpt-5-mini-2025-08-07":case"gpt-5-chat-latest":return"o200k_base";default:throw new Error("Unknown model")}}const sn={},Ky=new Wi({});async function Vy(n){return n in sn||(sn[n]=Ky.fetch(`https://tiktoken.pages.dev/js/${n}.json`).then(e=>e.json()).then(e=>new Vd(e)).catch(e=>{throw delete sn[n],e})),await sn[n]}async function Xy(n){return Vy(Zy(n))}const Qy=n=>n.startsWith("gpt-3.5-turbo-16k")?"gpt-3.5-turbo-16k":n.startsWith("gpt-3.5-turbo-")?"gpt-3.5-turbo":n.startsWith("gpt-4-32k")?"gpt-4-32k":n.startsWith("gpt-4-")?"gpt-4":n.startsWith("gpt-4o")?"gpt-4o":n;function Xd(n){return typeof n!="object"||!n?!1:!!("type"in n&&n.type==="function"&&"function"in n&&typeof n.function=="object"&&n.function&&"name"in n.function&&"parameters"in n.function)}const Yy=()=>!1;class eb extends le{get lc_attributes(){return{callbacks:void 0,verbose:void 0}}constructor(e){super(e),Object.defineProperty(this,"verbose",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"callbacks",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.verbose=e.verbose??Yy(),this.callbacks=e.callbacks,this.tags=e.tags??[],this.metadata=e.metadata??{}}}class tb extends eb{get callKeys(){return["stop","timeout","signal","tags","metadata","callbacks"]}constructor({callbacks:e,callbackManager:t,...r}){const{cache:s,...a}=r;super({callbacks:e??t,...a}),Object.defineProperty(this,"caller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cache",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_encoding",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),typeof s=="object"?this.cache=s:s?this.cache=Xi.global():this.cache=void 0,this.caller=new Wi(r??{})}async getNumTokens(e){let t;typeof e=="string"?t=e:t=e.map(s=>typeof s=="string"?s:s.type==="text"&&"text"in s?s.text:"").join("");let r=Math.ceil(t.length/4);if(!this._encoding)try{this._encoding=await Xy("modelName"in this?Qy(this.modelName):"gpt2")}catch(s){console.warn("Failed to calculate number of tokens, falling back to approximate count",s)}if(this._encoding)try{r=this._encoding.encode(t).length}catch(s){console.warn("Failed to calculate number of tokens, falling back to approximate count",s)}return r}static _convertInputToPromptValue(e){return typeof e=="string"?new My(e):Array.isArray(e)?new Uy(e.map(pr)):e}_identifyingParams(){return{}}_getSerializedCacheKeyParametersForCall({config:e,...t}){const r={...this._identifyingParams(),...t,_type:this._llmType(),_model:this._modelType()};return Object.entries(r).filter(([i,o])=>o!==void 0).map(([i,o])=>`${i}:${JSON.stringify(o)}`).sort().join(",")}serialize(){return{...this._identifyingParams(),_type:this._llmType(),_model:this._modelType()}}static async deserialize(e){throw new Error("Use .toJSON() instead")}}class Un extends le{static lc_name(){return"RunnablePassthrough"}constructor(e){super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"func",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),e&&(this.func=e.func)}async invoke(e,t){const r=Z(t);return this.func&&await this.func(e,r),this._callWithConfig(s=>Promise.resolve(s),e,r)}async*transform(e,t){const r=Z(t);let s,a=!0;for await(const i of this._transformStreamWithConfig(e,o=>o,r))if(yield i,a)if(s===void 0)s=i;else try{s=os(s,i)}catch{s=void 0,a=!1}this.func&&s!==void 0&&await this.func(s,r)}static assign(e){return new Zd(new Xt({steps:e}))}}function Ma(n){const e=[];for(const t of n){let r=t;if(Array.isArray(t.content))for(let s=0;s<t.content.length;s++){const a=t.content[s];(Mf(a)||Uf(a))&&r===t&&(r=new t.constructor({...r,content:[...t.content.slice(0,s),Df(a),...t.content.slice(s+1)]}))}e.push(r)}return e}class dt extends tb{constructor(e){super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain","chat_models",this._llmType()]}),Object.defineProperty(this,"disableStreaming",{enumerable:!0,configurable:!0,writable:!0,value:!1})}_separateRunnableConfigFromCallOptionsCompat(e){const[t,r]=super._separateRunnableConfigFromCallOptions(e);return r.signal=t.signal,[t,r]}async invoke(e,t){const r=dt._convertInputToPromptValue(e);return(await this.generatePrompt([r],t,t?.callbacks)).generations[0][0].message}async*_streamResponseChunks(e,t,r){throw new Error("Not implemented.")}async*_streamIterator(e,t){if(this._streamResponseChunks===dt.prototype._streamResponseChunks||this.disableStreaming)yield this.invoke(e,t);else{const s=dt._convertInputToPromptValue(e).toChatMessages(),[a,i]=this._separateRunnableConfigFromCallOptionsCompat(t),o={...a.metadata,...this.getLsParams(i)},u=await Pe.configure(a.callbacks,this.callbacks,a.tags,this.tags,o,this.metadata,{verbose:this.verbose}),c={options:i,invocation_params:this?.invocationParams(i),batch_size:1},l=await u?.handleChatModelStart(this.toJSON(),[Ma(s)],a.runId,void 0,c,void 0,void 0,a.runName);let d,h;try{for await(const f of this._streamResponseChunks(s,i,l?.[0])){if(f.message.id==null){const p=l?.at(0)?.runId;p!=null&&f.message._updateId(`run-${p}`)}f.message.response_metadata={...f.generationInfo,...f.message.response_metadata},yield f.message,d?d=d.concat(f):d=f,Do(f.message)&&f.message.usage_metadata!==void 0&&(h={tokenUsage:{promptTokens:f.message.usage_metadata.input_tokens,completionTokens:f.message.usage_metadata.output_tokens,totalTokens:f.message.usage_metadata.total_tokens}})}}catch(f){throw await Promise.all((l??[]).map(p=>p?.handleLLMError(f))),f}await Promise.all((l??[]).map(f=>f?.handleLLMEnd({generations:[[d]],llmOutput:h})))}}getLsParams(e){const t=this.getName().startsWith("Chat")?this.getName().replace("Chat",""):this.getName();return{ls_model_type:"chat",ls_stop:e.stop,ls_provider:t}}async _generateUncached(e,t,r,s){const a=e.map(d=>d.map(pr));let i;if(s!==void 0&&s.length===a.length)i=s;else{const d={...r.metadata,...this.getLsParams(t)},h=await Pe.configure(r.callbacks,this.callbacks,r.tags,this.tags,d,this.metadata,{verbose:this.verbose}),f={options:t,invocation_params:this?.invocationParams(t),batch_size:1};i=await h?.handleChatModelStart(this.toJSON(),a.map(Ma),r.runId,void 0,f,void 0,void 0,r.runName)}const o=[],u=[];if(!!i?.[0].handlers.find(Ug)&&!this.disableStreaming&&a.length===1&&this._streamResponseChunks!==dt.prototype._streamResponseChunks)try{const d=await this._streamResponseChunks(a[0],t,i?.[0]);let h,f;for await(const p of d){if(p.message.id==null){const m=i?.at(0)?.runId;m!=null&&p.message._updateId(`run-${m}`)}h===void 0?h=p:h=os(h,p),Do(p.message)&&p.message.usage_metadata!==void 0&&(f={tokenUsage:{promptTokens:p.message.usage_metadata.input_tokens,completionTokens:p.message.usage_metadata.output_tokens,totalTokens:p.message.usage_metadata.total_tokens}})}if(h===void 0)throw new Error("Received empty response from chat model call.");o.push([h]),await i?.[0].handleLLMEnd({generations:o,llmOutput:f})}catch(d){throw await i?.[0].handleLLMError(d),d}else{const d=await Promise.allSettled(a.map((h,f)=>this._generate(h,{...t,promptIndex:f},i?.[f])));await Promise.all(d.map(async(h,f)=>{if(h.status==="fulfilled"){const p=h.value;for(const m of p.generations){if(m.message.id==null){const g=i?.at(0)?.runId;g!=null&&m.message._updateId(`run-${g}`)}m.message.response_metadata={...m.generationInfo,...m.message.response_metadata}}return p.generations.length===1&&(p.generations[0].message.response_metadata={...p.llmOutput,...p.generations[0].message.response_metadata}),o[f]=p.generations,u[f]=p.llmOutput,i?.[f]?.handleLLMEnd({generations:[p.generations],llmOutput:p.llmOutput})}else return await i?.[f]?.handleLLMError(h.reason),Promise.reject(h.reason)}))}const l={generations:o,llmOutput:u.length?this._combineLLMOutput?.(...u):void 0};return Object.defineProperty(l,_c,{value:i?{runIds:i?.map(d=>d.runId)}:void 0,configurable:!0}),l}async _generateCached({messages:e,cache:t,llmStringKey:r,parsedOptions:s,handledOptions:a}){const i=e.map(g=>g.map(pr)),o={...a.metadata,...this.getLsParams(s)},u=await Pe.configure(a.callbacks,this.callbacks,a.tags,this.tags,o,this.metadata,{verbose:this.verbose}),c={options:s,invocation_params:this?.invocationParams(s),batch_size:1},l=await u?.handleChatModelStart(this.toJSON(),i.map(Ma),a.runId,void 0,c,void 0,void 0,a.runName),d=[],f=(await Promise.allSettled(i.map(async(g,_)=>{const y=dt._convertInputToPromptValue(g).toString(),b=await t.lookup(y,r);return b==null&&d.push(_),b}))).map((g,_)=>({result:g,runManager:l?.[_]})).filter(({result:g})=>g.status==="fulfilled"&&g.value!=null||g.status==="rejected"),p=[];await Promise.all(f.map(async({result:g,runManager:_},y)=>{if(g.status==="fulfilled"){const b=g.value;return p[y]=b.map(v=>("message"in v&&Vn(v.message)&&jr(v.message)&&(v.message.usage_metadata={input_tokens:0,output_tokens:0,total_tokens:0}),v.generationInfo={...v.generationInfo,tokenUsage:{}},v)),b.length&&await _?.handleLLMNewToken(b[0].text),_?.handleLLMEnd({generations:[b]},void 0,void 0,void 0,{cached:!0})}else return await _?.handleLLMError(g.reason,void 0,void 0,void 0,{cached:!0}),Promise.reject(g.reason)}));const m={generations:p,missingPromptIndices:d,startedRunManagers:l};return Object.defineProperty(m,_c,{value:l?{runIds:l?.map(g=>g.runId)}:void 0,configurable:!0}),m}async generate(e,t,r){let s;Array.isArray(t)?s={stop:t}:s=t;const a=e.map(p=>p.map(pr)),[i,o]=this._separateRunnableConfigFromCallOptionsCompat(s);if(i.callbacks=i.callbacks??r,!this.cache)return this._generateUncached(a,o,i);const{cache:u}=this,c=this._getSerializedCacheKeyParametersForCall(o),{generations:l,missingPromptIndices:d,startedRunManagers:h}=await this._generateCached({messages:a,cache:u,llmStringKey:c,parsedOptions:o,handledOptions:i});let f={};if(d.length>0){const p=await this._generateUncached(d.map(m=>a[m]),o,i,h!==void 0?d.map(m=>h?.[m]):void 0);await Promise.all(p.generations.map(async(m,g)=>{const _=d[g];l[_]=m;const y=dt._convertInputToPromptValue(a[_]).toString();return u.update(y,c,m)})),f=p.llmOutput??{}}return{generations:l,llmOutput:f}}invocationParams(e){return{}}_modelType(){return"base_chat_model"}serialize(){return{...this.invocationParams(),_type:this._llmType(),_model:this._modelType()}}async generatePrompt(e,t,r){const s=e.map(a=>a.toChatMessages());return this.generate(s,t,r)}async call(e,t,r){return(await this.generate([e.map(pr)],t,r)).generations[0][0].message}async callPrompt(e,t,r){const s=e.toChatMessages();return this.call(s,t,r)}async predictMessages(e,t,r){return this.call(e,t,r)}async predict(e,t,r){const s=new Yn(e),a=await this.call([s],t,r);if(typeof a.content!="string")throw new Error("Cannot use predict when output is not a string.");return a.content}withStructuredOutput(e,t){if(typeof this.bindTools!="function")throw new Error('Chat model must implement ".bindTools()" to use withStructuredOutput.');if(t?.strict)throw new Error('"strict" mode is not supported for this model by default.');const r=e,s=t?.name,a=Ki(r)??"A function available to call.",i=t?.method,o=t?.includeRaw;if(i==="jsonMode")throw new Error('Base withStructuredOutput implementation only supports "functionCalling" as a method.');let u=s??"extract",c;Ot(r)?c=[{type:"function",function:{name:u,description:a,parameters:ft(r)}}]:("name"in r&&(u=r.name),c=[{type:"function",function:{name:u,description:a,parameters:r}}]);const l=this.bindTools(c),d=Qt.from(m=>{if(!m.tool_calls||m.tool_calls.length===0)throw new Error("No tool calls found in the response.");const g=m.tool_calls.find(_=>_.name===u);if(!g)throw new Error(`No tool call found with name ${u}.`);return g.args});if(!o)return l.pipe(d).withConfig({runName:"StructuredOutput"});const h=Un.assign({parsed:(m,g)=>d.invoke(m.raw,g)}),f=Un.assign({parsed:()=>null}),p=h.withFallbacks({fallbacks:[f]});return st.from([{raw:l},p]).withConfig({runName:"StructuredOutputRunnable"})}}class rb extends le{parseResultWithPrompt(e,t,r){return this.parseResult(e,r)}_baseMessageToString(e){return typeof e.content=="string"?e.content:this._baseMessageContentToString(e.content)}_baseMessageContentToString(e){return JSON.stringify(e)}async invoke(e,t){return typeof e=="string"?this._callWithConfig(async(r,s)=>this.parseResult([{text:r}],s?.callbacks),e,{...t,runType:"parser"}):this._callWithConfig(async(r,s)=>this.parseResult([{message:r,text:this._baseMessageToString(r)}],s?.callbacks),e,{...t,runType:"parser"})}}class Qd extends rb{parseResult(e,t){return this.parse(e[0].text,t)}async parseWithPrompt(e,t,r){return this.parse(e,r)}_type(){throw new Error("_type not implemented")}}class Qi extends Error{constructor(e,t,r,s=!1){if(super(e),Object.defineProperty(this,"llmOutput",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"observation",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"sendToLLM",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.llmOutput=t,this.observation=r,this.sendToLLM=s,s&&(r===void 0||t===void 0))throw new Error("Arguments 'observation' & 'llmOutput' are required if 'sendToLlm' is true");od(this,"OUTPUT_PARSING_FAILURE")}}class nb extends Qd{async*_transform(e){for await(const t of e)typeof t=="string"?yield this.parseResult([{text:t}]):yield this.parseResult([{message:t,text:this._baseMessageToString(t)}])}async*transform(e,t){yield*this._transformStreamWithConfig(e,this._transform.bind(this),{...t,runType:"parser"})}}class Yd extends nb{constructor(e){super(e),Object.defineProperty(this,"diff",{enumerable:!0,configurable:!0,writable:!0,value:!1}),this.diff=e?.diff??this.diff}async*_transform(e){let t,r;for await(const s of e){if(typeof s!="string"&&typeof s.content!="string")throw new Error("Cannot handle non-string output.");let a;if(Hf(s)){if(typeof s.content!="string")throw new Error("Cannot handle non-string message output.");a=new Rt({message:s,text:s.content})}else if(Vn(s)){if(typeof s.content!="string")throw new Error("Cannot handle non-string message output.");a=new Rt({message:Xf(s),text:s.content})}else a=new Gt({text:s});r===void 0?r=a:r=r.concat(a);const i=await this.parsePartialResult([r]);i!=null&&!ui(i,t)&&(this.diff?yield this._diff(t,i):yield i,t=i)}}getFormatInstructions(){return""}}class Ic extends Qd{static lc_name(){return"StructuredOutputParser"}toJSON(){return this.toJSONNotImplemented()}constructor(e){super(e),Object.defineProperty(this,"schema",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain","output_parsers","structured"]})}static fromZodSchema(e){return new this(e)}static fromNamesAndDescriptions(e){const t=gr(Object.fromEntries(Object.entries(e).map(([r,s])=>[r,mi().describe(s)])));return new this(t)}getFormatInstructions(){return`You must format your output as a JSON value that adheres to a given "JSON Schema" instance.
|
|
115
|
+
|
|
116
|
+
"JSON Schema" is a declarative language that allows you to annotate and validate JSON documents.
|
|
117
|
+
|
|
118
|
+
For example, the example "JSON Schema" instance {{"properties": {{"foo": {{"description": "a list of test words", "type": "array", "items": {{"type": "string"}}}}}}, "required": ["foo"]}}
|
|
119
|
+
would match an object with one required property, "foo". The "type" property specifies "foo" must be an "array", and the "description" property semantically describes it as "a list of test words". The items within "foo" must be strings.
|
|
120
|
+
Thus, the object {{"foo": ["bar", "baz"]}} is a well-formatted instance of this example "JSON Schema". The object {{"properties": {{"foo": ["bar", "baz"]}}}} is not well-formatted.
|
|
121
|
+
|
|
122
|
+
Your output will be parsed and type-checked according to the provided schema instance, so make sure all fields in your output match the schema exactly and there are no trailing commas!
|
|
123
|
+
|
|
124
|
+
Here is the JSON Schema instance your output must adhere to. Include the enclosing markdown codeblock:
|
|
125
|
+
\`\`\`json
|
|
126
|
+
${JSON.stringify(ft(this.schema))}
|
|
127
|
+
\`\`\`
|
|
128
|
+
`}async parse(e){try{const t=e.trim(),s=(t.match(/^```(?:json)?\s*([\s\S]*?)```/)?.[1]||t.match(/```json\s*([\s\S]*?)```/)?.[1]||t).replace(/"([^"\\]*(\\.[^"\\]*)*)"/g,(a,i)=>`"${i.replace(/\n/g,"\\n")}"`).replace(/\n/g,"");return await Gd(this.schema,JSON.parse(s))}catch(t){throw new Qi(`Failed to parse. Text: "${e}". Error: ${t}`,e)}}}class xc extends Yd{constructor(){super(...arguments),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","output_parsers"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0})}static lc_name(){return"JsonOutputParser"}_concatOutputChunks(e,t){return this.diff?super._concatOutputChunks(e,t):t}_diff(e,t){if(t)return e?yp(e,t):[{op:"replace",path:"",value:t}]}async parsePartialResult(e){return $o(e[0].text)}async parse(e){return $o(e,JSON.parse)}getFormatInstructions(){return""}}function Yi(n,e){if(n.function===void 0)return;let t;if(e?.partial)try{t=Li(n.function.arguments??"{}")}catch{return}else try{t=JSON.parse(n.function.arguments)}catch(s){throw new Qi([`Function "${n.function.name}" arguments:`,"",n.function.arguments,"","are not valid JSON.",`Error: ${s.message}`].join(`
|
|
129
|
+
`))}const r={name:n.function.name,args:t,type:"tool_call"};return e?.returnId&&(r.id=n.id),r}function sb(n){if(n.id===void 0)throw new Error('All OpenAI tool calls must have an "id" field.');return{id:n.id,type:"function",function:{name:n.name,arguments:JSON.stringify(n.args)}}}function fi(n,e){return{name:n.function?.name,args:n.function?.arguments,id:n.id,error:e,type:"invalid_tool_call"}}class ab extends Yd{static lc_name(){return"JsonOutputToolsParser"}constructor(e){super(e),Object.defineProperty(this,"returnId",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain","output_parsers","openai_tools"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),this.returnId=e?.returnId??this.returnId}_diff(){throw new Error("Not supported.")}async parse(){throw new Error("Not implemented.")}async parseResult(e){return await this.parsePartialResult(e,!1)}async parsePartialResult(e,t=!0){const r=e[0].message;let s;if(jr(r)&&r.tool_calls?.length?s=r.tool_calls.map(i=>{const{id:o,...u}=i;return this.returnId?{id:o,...u}:u}):r.additional_kwargs.tool_calls!==void 0&&(s=JSON.parse(JSON.stringify(r.additional_kwargs.tool_calls)).map(o=>Yi(o,{returnId:this.returnId,partial:t}))),!s)return[];const a=[];for(const i of s)if(i!==void 0){const o={type:i.name,args:i.args,id:i.id};a.push(o)}return a}}class Rc extends ab{static lc_name(){return"JsonOutputKeyToolsParser"}constructor(e){super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain","output_parsers","openai_tools"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"returnId",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"keyName",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"returnSingle",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"zodSchema",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.keyName=e.keyName,this.returnSingle=e.returnSingle??this.returnSingle,this.zodSchema=e.zodSchema}async _validateResult(e){if(this.zodSchema===void 0)return e;const t=await by(this.zodSchema,e);if(t.success)return t.data;throw new Qi(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(t.error?.issues)}`,JSON.stringify(e,null,2))}async parsePartialResult(e){const r=(await super.parsePartialResult(e)).filter(a=>a.type===this.keyName);let s=r;if(r.length)return this.returnId||(s=r.map(a=>a.args)),this.returnSingle?s[0]:s}async parseResult(e){const r=(await super.parsePartialResult(e,!1)).filter(i=>i.type===this.keyName);let s=r;return r.length?(this.returnId||(s=r.map(i=>i.args)),this.returnSingle?this._validateResult(s[0]):await Promise.all(s.map(i=>this._validateResult(i)))):void 0}}function ib(n){const{azureOpenAIApiDeploymentName:e,azureOpenAIApiInstanceName:t,azureOpenAIApiKey:r,azureOpenAIBasePath:s,baseURL:a,azureADTokenProvider:i,azureOpenAIEndpoint:o}=n;if((r||i)&&s&&e)return`${s}/${e}`;if((r||i)&&o&&e)return`${o}/openai/deployments/${e}`;if(r||i){if(!t)throw new Error("azureOpenAIApiInstanceName is required when using azureOpenAIApiKey");if(!e)throw new Error("azureOpenAIApiDeploymentName is a required parameter when using azureOpenAIApiKey");return`https://${t}.openai.azure.com/openai/deployments/${e}`}return a}function ob(n){return n!==void 0&&Array.isArray(n.lc_namespace)}function ub(n){return n!==void 0&&le.isRunnable(n)&&"lc_name"in n.constructor&&typeof n.constructor.lc_name=="function"&&n.constructor.lc_name()==="RunnableToolLike"}function cb(n){return!!n&&typeof n=="object"&&"name"in n&&"schema"in n&&(Ot(n.schema)||n.schema!=null&&typeof n.schema=="object"&&"type"in n.schema&&typeof n.schema.type=="string"&&["null","boolean","object","array","number","string"].includes(n.schema.type))}function eh(n){return cb(n)||ub(n)||ob(n)}function lb(n,e){return{name:n.name,description:n.description,parameters:ft(n.schema)}}function db(n,e){let t;return eh(n)?t={type:"function",function:lb(n)}:t=n,t}const hb=Symbol("Let zodToJsonSchema decide on which parser to use"),kc={name:void 0,$refStrategy:"root",effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",nullableStrategy:"from-target",removeAdditionalStrategy:"passthrough",definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},fb=n=>typeof n=="string"?{...kc,basePath:["#"],definitions:{},name:n}:{...kc,basePath:["#"],definitions:{},...n},pi=n=>"_def"in n?n._def:n;function pb(n){if(!n)return!0;for(const e in n)return!1;return!0}const mb=n=>{const e=fb(n),t=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,currentPath:t,propertyPath:void 0,seenRefs:new Set,seen:new Map(Object.entries(e.definitions).map(([r,s])=>[pi(s),{def:pi(s),path:[...e.basePath,e.definitionPath,r],jsonSchema:void 0}]))}};function th(n,e,t,r){r?.errorMessages&&t&&(n.errorMessage={...n.errorMessage,[e]:t})}function Q(n,e,t,r,s){n[e]=t,th(n,e,r,s)}function gb(){return{}}function _b(n,e){const t={type:"array"};return n.type?._def?.typeName!==S.ZodAny&&(t.items=J(n.type._def,{...e,currentPath:[...e.currentPath,"items"]})),n.minLength&&Q(t,"minItems",n.minLength.value,n.minLength.message,e),n.maxLength&&Q(t,"maxItems",n.maxLength.value,n.maxLength.message,e),n.exactLength&&(Q(t,"minItems",n.exactLength.value,n.exactLength.message,e),Q(t,"maxItems",n.exactLength.value,n.exactLength.message,e)),t}function yb(n,e){const t={type:"integer",format:"int64"};if(!n.checks)return t;for(const r of n.checks)switch(r.kind){case"min":e.target==="jsonSchema7"?r.inclusive?Q(t,"minimum",r.value,r.message,e):Q(t,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(t.exclusiveMinimum=!0),Q(t,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?Q(t,"maximum",r.value,r.message,e):Q(t,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(t.exclusiveMaximum=!0),Q(t,"maximum",r.value,r.message,e));break;case"multipleOf":Q(t,"multipleOf",r.value,r.message,e);break}return t}function bb(){return{type:"boolean"}}function wb(n,e){return J(n.type._def,e)}const vb=(n,e)=>J(n.innerType._def,e);function rh(n,e,t){const r=t??e.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((s,a)=>rh(n,e,s))};switch(r){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return Eb(n,e)}}const Eb=(n,e)=>{const t={type:"integer",format:"unix-time"};if(e.target==="openApi3")return t;for(const r of n.checks)switch(r.kind){case"min":Q(t,"minimum",r.value,r.message,e);break;case"max":Q(t,"maximum",r.value,r.message,e);break}return t};function Sb(n,e){return{...J(n.innerType._def,e),default:n.defaultValue()}}function Ob(n,e,t){return e.effectStrategy==="input"?J(n.schema._def,e,t):{}}function Tb(n){return{type:"string",enum:[...n.values]}}const Ab=n=>"type"in n&&n.type==="string"?!1:"allOf"in n;function Pb(n,e){const t=[J(n.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),J(n.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(a=>!!a);let r=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0;const s=[];return t.forEach(a=>{if(Ab(a))s.push(...a.allOf),a.unevaluatedProperties===void 0&&(r=void 0);else{let i=a;if("additionalProperties"in a&&a.additionalProperties===!1){const{additionalProperties:o,...u}=a;i=u}else r=void 0;s.push(i)}}),s.length?{allOf:s,...r}:void 0}function Ib(n,e){const t=typeof n.value;return t!=="bigint"&&t!=="number"&&t!=="boolean"&&t!=="string"?{type:Array.isArray(n.value)?"array":"object"}:e.target==="openApi3"?{type:t==="bigint"?"integer":t,enum:[n.value]}:{type:t==="bigint"?"integer":t,const:n.value}}let Ua;const bt={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(Ua===void 0&&(Ua=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Ua),base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/};function nh(n,e){const t={type:"string"};function r(s){return e.patternStrategy==="escape"?xb(s):s}if(n.checks)for(const s of n.checks)switch(s.kind){case"min":Q(t,"minLength",typeof t.minLength=="number"?Math.max(t.minLength,s.value):s.value,s.message,e);break;case"max":Q(t,"maxLength",typeof t.maxLength=="number"?Math.min(t.maxLength,s.value):s.value,s.message,e);break;case"email":switch(e.emailStrategy){case"format:email":Fe(t,"email",s.message,e);break;case"format:idn-email":Fe(t,"idn-email",s.message,e);break;case"pattern:zod":Be(t,bt.email,s.message,e);break}break;case"url":Fe(t,"uri",s.message,e);break;case"uuid":Fe(t,"uuid",s.message,e);break;case"regex":Be(t,s.regex,s.message,e);break;case"cuid":Be(t,bt.cuid,s.message,e);break;case"cuid2":Be(t,bt.cuid2,s.message,e);break;case"startsWith":Be(t,RegExp(`^${r(s.value)}`),s.message,e);break;case"endsWith":Be(t,RegExp(`${r(s.value)}$`),s.message,e);break;case"datetime":Fe(t,"date-time",s.message,e);break;case"date":Fe(t,"date",s.message,e);break;case"time":Fe(t,"time",s.message,e);break;case"duration":Fe(t,"duration",s.message,e);break;case"length":Q(t,"minLength",typeof t.minLength=="number"?Math.max(t.minLength,s.value):s.value,s.message,e),Q(t,"maxLength",typeof t.maxLength=="number"?Math.min(t.maxLength,s.value):s.value,s.message,e);break;case"includes":{Be(t,RegExp(r(s.value)),s.message,e);break}case"ip":{s.version!=="v6"&&Fe(t,"ipv4",s.message,e),s.version!=="v4"&&Fe(t,"ipv6",s.message,e);break}case"emoji":Be(t,bt.emoji,s.message,e);break;case"ulid":{Be(t,bt.ulid,s.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{Fe(t,"binary",s.message,e);break}case"contentEncoding:base64":{Q(t,"contentEncoding","base64",s.message,e);break}case"pattern:zod":{Be(t,bt.base64,s.message,e);break}}break}case"nanoid":Be(t,bt.nanoid,s.message,e)}return t}const xb=n=>Array.from(n).map(e=>/[a-zA-Z0-9]/.test(e)?e:`\\${e}`).join(""),Fe=(n,e,t,r)=>{n.format||n.anyOf?.some(s=>s.format)?(n.anyOf||(n.anyOf=[]),n.format&&(n.anyOf.push({format:n.format,...n.errorMessage&&r.errorMessages&&{errorMessage:{format:n.errorMessage.format}}}),delete n.format,n.errorMessage&&(delete n.errorMessage.format,Object.keys(n.errorMessage).length===0&&delete n.errorMessage)),n.anyOf.push({format:e,...t&&r.errorMessages&&{errorMessage:{format:t}}})):Q(n,"format",e,t,r)},Be=(n,e,t,r)=>{n.pattern||n.allOf?.some(s=>s.pattern)?(n.allOf||(n.allOf=[]),n.pattern&&(n.allOf.push({pattern:n.pattern,...n.errorMessage&&r.errorMessages&&{errorMessage:{pattern:n.errorMessage.pattern}}}),delete n.pattern,n.errorMessage&&(delete n.errorMessage.pattern,Object.keys(n.errorMessage).length===0&&delete n.errorMessage)),n.allOf.push({pattern:Cc(e,r),...t&&r.errorMessages&&{errorMessage:{pattern:t}}})):Q(n,"pattern",Cc(e,r),t,r)},Cc=(n,e)=>{const t=typeof n=="function"?n():n;if(!e.applyRegexFlags||!t.flags)return t.source;const r={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},s=r.i?t.source.toLowerCase():t.source;let a="",i=!1,o=!1,u=!1;for(let c=0;c<s.length;c++){if(i){a+=s[c],i=!1;continue}if(r.i){if(o){if(s[c].match(/[a-z]/)){u?(a+=s[c],a+=`${s[c-2]}-${s[c]}`.toUpperCase(),u=!1):s[c+1]==="-"&&s[c+2]?.match(/[a-z]/)?(a+=s[c],u=!0):a+=`${s[c]}${s[c].toUpperCase()}`;continue}}else if(s[c].match(/[a-z]/)){a+=`[${s[c]}${s[c].toUpperCase()}]`;continue}}if(r.m){if(s[c]==="^"){a+=`(^|(?<=[\r
|
|
130
|
+
]))`;continue}else if(s[c]==="$"){a+=`($|(?=[\r
|
|
131
|
+
]))`;continue}}if(r.s&&s[c]==="."){a+=o?`${s[c]}\r
|
|
132
|
+
`:`[${s[c]}\r
|
|
133
|
+
]`;continue}a+=s[c],s[c]==="\\"?i=!0:o&&s[c]==="]"?o=!1:!o&&s[c]==="["&&(o=!0)}try{const c=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`),t.source}return a};function sh(n,e){if(e.target==="openApi3"&&n.keyType?._def.typeName===S.ZodEnum)return{type:"object",required:n.keyType._def.values,properties:n.keyType._def.values.reduce((r,s)=>({...r,[s]:J(n.valueType._def,{...e,currentPath:[...e.currentPath,"properties",s]})??{}}),{}),additionalProperties:!1};const t={type:"object",additionalProperties:J(n.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??{}};if(e.target==="openApi3")return t;if(n.keyType?._def.typeName===S.ZodString&&n.keyType._def.checks?.length){const r=Object.entries(nh(n.keyType._def,e)).reduce((s,[a,i])=>a==="type"?s:{...s,[a]:i},{});return{...t,propertyNames:r}}else if(n.keyType?._def.typeName===S.ZodEnum)return{...t,propertyNames:{enum:n.keyType._def.values}};return t}function Rb(n,e){if(e.mapStrategy==="record")return sh(n,e);const t=J(n.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},r=J(n.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||{};return{type:"array",maxItems:125,items:{type:"array",items:[t,r],minItems:2,maxItems:2}}}function kb(n){const e=n.values,r=Object.keys(n.values).filter(a=>typeof e[e[a]]!="number").map(a=>e[a]),s=Array.from(new Set(r.map(a=>typeof a)));return{type:s.length===1?s[0]==="string"?"string":"number":["string","number"],enum:r}}function Cb(){return{not:{}}}function $b(n){return n.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}const Dn={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Nb(n,e){if(e.target==="openApi3")return $c(n,e);const t=n.options instanceof Map?Array.from(n.options.values()):n.options;if(t.every(r=>r._def.typeName in Dn&&(!r._def.checks||!r._def.checks.length))){const r=t.reduce((s,a)=>{const i=Dn[a._def.typeName];return i&&!s.includes(i)?[...s,i]:s},[]);return{type:r.length>1?r:r[0]}}else if(t.every(r=>r._def.typeName==="ZodLiteral"&&!r.description)){const r=t.reduce((s,a)=>{const i=typeof a._def.value;switch(i){case"string":case"number":case"boolean":return[...s,i];case"bigint":return[...s,"integer"];case"object":if(a._def.value===null)return[...s,"null"];case"symbol":case"undefined":case"function":default:return s}},[]);if(r.length===t.length){const s=r.filter((a,i,o)=>o.indexOf(a)===i);return{type:s.length>1?s:s[0],enum:t.reduce((a,i)=>a.includes(i._def.value)?a:[...a,i._def.value],[])}}}else if(t.every(r=>r._def.typeName==="ZodEnum"))return{type:"string",enum:t.reduce((r,s)=>[...r,...s._def.values.filter(a=>!r.includes(a))],[])};return $c(n,e)}const $c=(n,e)=>{const t=(n.options instanceof Map?Array.from(n.options.values()):n.options).map((r,s)=>J(r._def,{...e,currentPath:[...e.currentPath,"anyOf",`${s}`]})).filter(r=>!!r&&(!e.strictUnions||typeof r=="object"&&Object.keys(r).length>0));return t.length?{anyOf:t}:void 0};function jb(n,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(n.innerType._def.typeName)&&(!n.innerType._def.checks||!n.innerType._def.checks.length))return e.target==="openApi3"||e.nullableStrategy==="property"?{type:Dn[n.innerType._def.typeName],nullable:!0}:{type:[Dn[n.innerType._def.typeName],"null"]};if(e.target==="openApi3"){const r=J(n.innerType._def,{...e,currentPath:[...e.currentPath]});return r&&"$ref"in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}const t=J(n.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return t&&{anyOf:[t,{type:"null"}]}}function Lb(n,e){const t={type:"number"};if(!n.checks)return t;for(const r of n.checks)switch(r.kind){case"int":t.type="integer",th(t,"type",r.message,e);break;case"min":e.target==="jsonSchema7"?r.inclusive?Q(t,"minimum",r.value,r.message,e):Q(t,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(t.exclusiveMinimum=!0),Q(t,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?Q(t,"maximum",r.value,r.message,e):Q(t,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(t.exclusiveMaximum=!0),Q(t,"maximum",r.value,r.message,e));break;case"multipleOf":Q(t,"multipleOf",r.value,r.message,e);break}return t}function Mb(n,e){return e.removeAdditionalStrategy==="strict"?n.catchall._def.typeName==="ZodNever"?n.unknownKeys!=="strict":J(n.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0:n.catchall._def.typeName==="ZodNever"?n.unknownKeys==="passthrough":J(n.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0}function Ub(n,e){const t={type:"object",...Object.entries(n.shape()).reduce((r,[s,a])=>{if(a===void 0||a._def===void 0)return r;const i=[...e.currentPath,"properties",s],o=J(a._def,{...e,currentPath:i,propertyPath:i});if(o===void 0)return r;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:{...r.properties,[s]:o},required:a.isOptional()&&!e.openaiStrictMode?r.required:[...r.required,s]}},{properties:{},required:[]}),additionalProperties:Mb(n,e)};return t.required.length||delete t.required,t}const Db=(n,e)=>{if(e.propertyPath&&e.currentPath.slice(0,e.propertyPath.length).toString()===e.propertyPath.toString())return J(n.innerType._def,{...e,currentPath:e.currentPath});const t=J(n.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return t?{anyOf:[{not:{}},t]}:{}},Fb=(n,e)=>{if(e.pipeStrategy==="input")return J(n.in._def,e);if(e.pipeStrategy==="output")return J(n.out._def,e);const t=J(n.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),r=J(n.out._def,{...e,currentPath:[...e.currentPath,"allOf",t?"1":"0"]});return{allOf:[t,r].filter(s=>s!==void 0)}};function Bb(n,e){return J(n.type._def,e)}function zb(n,e){const r={type:"array",uniqueItems:!0,items:J(n.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return n.minSize&&Q(r,"minItems",n.minSize.value,n.minSize.message,e),n.maxSize&&Q(r,"maxItems",n.maxSize.value,n.maxSize.message,e),r}function qb(n,e){return n.rest?{type:"array",minItems:n.items.length,items:n.items.map((t,r)=>J(t._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((t,r)=>r===void 0?t:[...t,r],[]),additionalItems:J(n.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:n.items.length,maxItems:n.items.length,items:n.items.map((t,r)=>J(t._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((t,r)=>r===void 0?t:[...t,r],[])}}function Hb(){return{not:{}}}function Gb(){return{}}const Jb=(n,e)=>J(n.innerType._def,e);function J(n,e,t=!1){const r=e.seen.get(n);if(e.override){const i=e.override?.(n,e,r,t);if(i!==hb)return i}if(r&&!t){const i=Wb(r,e);if(i!==void 0)return"$ref"in i&&e.seenRefs.add(i.$ref),i}const s={def:n,path:e.currentPath,jsonSchema:void 0};e.seen.set(n,s);const a=Kb(n,n.typeName,e,t);return a&&Vb(n,e,a),s.jsonSchema=a,a}const Wb=(n,e)=>{switch(e.$refStrategy){case"root":return{$ref:n.path.join("/")};case"extract-to-root":const t=n.path.slice(e.basePath.length+1).join("_");return t!==e.name&&e.nameStrategy==="duplicate-ref"&&(e.definitions[t]=n.def),{$ref:[...e.basePath,e.definitionPath,t].join("/")};case"relative":return{$ref:Zb(e.currentPath,n.path)};case"none":case"seen":return n.path.length<e.currentPath.length&&n.path.every((r,s)=>e.currentPath[s]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),{}):e.$refStrategy==="seen"?{}:void 0}},Zb=(n,e)=>{let t=0;for(;t<n.length&&t<e.length&&n[t]===e[t];t++);return[(n.length-t).toString(),...e.slice(t)].join("/")},Kb=(n,e,t,r)=>{switch(e){case S.ZodString:return nh(n,t);case S.ZodNumber:return Lb(n,t);case S.ZodObject:return Ub(n,t);case S.ZodBigInt:return yb(n,t);case S.ZodBoolean:return bb();case S.ZodDate:return rh(n,t);case S.ZodUndefined:return Hb();case S.ZodNull:return $b(t);case S.ZodArray:return _b(n,t);case S.ZodUnion:case S.ZodDiscriminatedUnion:return Nb(n,t);case S.ZodIntersection:return Pb(n,t);case S.ZodTuple:return qb(n,t);case S.ZodRecord:return sh(n,t);case S.ZodLiteral:return Ib(n,t);case S.ZodEnum:return Tb(n);case S.ZodNativeEnum:return kb(n);case S.ZodNullable:return jb(n,t);case S.ZodOptional:return Db(n,t);case S.ZodMap:return Rb(n,t);case S.ZodSet:return zb(n,t);case S.ZodLazy:return J(n.getter()._def,t);case S.ZodPromise:return Bb(n,t);case S.ZodNaN:case S.ZodNever:return Cb();case S.ZodEffects:return Ob(n,t,r);case S.ZodAny:return gb();case S.ZodUnknown:return Gb();case S.ZodDefault:return Sb(n,t);case S.ZodBranded:return wb(n,t);case S.ZodReadonly:return Jb(n,t);case S.ZodCatch:return vb(n,t);case S.ZodPipeline:return Fb(n,t);case S.ZodFunction:case S.ZodVoid:case S.ZodSymbol:return;default:return(s=>{})()}},Vb=(n,e,t)=>(n.description&&(t.description=n.description,e.markdownDescription&&(t.markdownDescription=n.description)),t),Xb=(n,e)=>{const t=mb(e),r=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,s=J(n._def,r===void 0?t:{...t,currentPath:[...t.basePath,t.definitionPath,r]},!1)??{},a=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;a!==void 0&&(s.title=a);const i=(()=>{if(pb(t.definitions))return;const u={},c=new Set;for(let l=0;l<500;l++){const d=Object.entries(t.definitions).filter(([h])=>!c.has(h));if(d.length===0)break;for(const[h,f]of d)u[h]=J(pi(f),{...t,currentPath:[...t.basePath,t.definitionPath,h]},!0)??{},c.add(h)}return u})(),o=r===void 0?i?{...s,[t.definitionPath]:i}:s:t.nameStrategy==="duplicate-ref"?{...s,...i||t.seenRefs.size?{[t.definitionPath]:{...i,...t.seenRefs.size?{[r]:s}:void 0}}:void 0}:{$ref:[...t.$refStrategy==="relative"?[]:t.basePath,t.definitionPath,r].join("/"),[t.definitionPath]:{...i,[r]:s}};return t.target==="jsonSchema7"?o.$schema="http://json-schema.org/draft-07/schema#":t.target==="jsonSchema2019-09"&&(o.$schema="https://json-schema.org/draft/2019-09/schema#"),o};function Qb(n,e){return Xb(n,{openaiStrictMode:!0,name:e.name,nameStrategy:"duplicate-ref",$refStrategy:"extract-to-root",nullableStrategy:"property"})}function Yb(n,e,t){return sf({type:"json_schema",json_schema:{...t,name:e,strict:!0,schema:Qb(n,{name:e})}},r=>n.parse(JSON.parse(r)))}function an(n,e){return n.lc_error_code=e,n.message=`${n.message}
|
|
134
|
+
|
|
135
|
+
Troubleshooting URL: https://js.langchain.com/docs/troubleshooting/errors/${e}/
|
|
136
|
+
`,n}function ah(n){let e;return n.constructor.name===zn.name?(e=new Error(n.message),e.name="TimeoutError"):n.constructor.name===Ce.name?(e=new Error(n.message),e.name="AbortError"):n.status===400&&n.message.includes("tool_calls")?e=an(n,"INVALID_TOOL_RESULTS"):n.status===401?e=an(n,"MODEL_AUTHENTICATION"):n.status===429?e=an(n,"MODEL_RATE_LIMIT"):n.status===404?e=an(n,"MODEL_NOT_FOUND"):e=n,e}function ih(n){if(n)return n==="any"||n==="required"?"required":n==="auto"?"auto":n==="none"?"none":typeof n=="string"?{type:"function",function:{name:n}}:n}function ew(n,e){const t={...n};return Object.defineProperties(t,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:e,enumerable:!1}}),t}function tw(n,e,t){if(et(n))return Yb(n,e,t);if(We(n))return ew({type:"json_schema",json_schema:{...t,name:e,strict:!0,schema:oi(n,{cycles:"ref",reused:"ref",override(r){r.jsonSchema.title=e}})}},r=>Md(n,JSON.parse(r)));throw new Error("Unsupported schema response format")}function rw(n){return n.anyOf!==void 0&&Array.isArray(n.anyOf)}function nw(n){const e=["namespace functions {",""];for(const t of n)t.description&&e.push(`// ${t.description}`),Object.keys(t.parameters.properties??{}).length>0?(e.push(`type ${t.name} = (_: {`),e.push(oh(t.parameters,0)),e.push("}) => any;")):e.push(`type ${t.name} = () => any;`),e.push("");return e.push("} // namespace functions"),e.join(`
|
|
137
|
+
`)}function oh(n,e){const t=[];for(const[r,s]of Object.entries(n.properties??{}))s.description&&e<2&&t.push(`// ${s.description}`),n.required?.includes(r)?t.push(`${r}: ${Fn(s,e)},`):t.push(`${r}?: ${Fn(s,e)},`);return t.map(r=>" ".repeat(e)+r).join(`
|
|
138
|
+
`)}function Fn(n,e){if(rw(n))return n.anyOf.map(t=>Fn(t,e)).join(" | ");switch(n.type){case"string":return n.enum?n.enum.map(t=>`"${t}"`).join(" | "):"string";case"number":return n.enum?n.enum.map(t=>`${t}`).join(" | "):"number";case"integer":return n.enum?n.enum.map(t=>`${t}`).join(" | "):"number";case"boolean":return"boolean";case"null":return"null";case"object":return["{",oh(n,e+2),"}"].join(`
|
|
139
|
+
`);case"array":return n.items?`${Fn(n.items,e)}[]`:"any[]";default:return""}}function sw(n,e){let t;return eh(n)?t=db(n):t=n,t.type==="function"&&e?.strict!==void 0&&(t.function.strict=e.strict),t}function eo(n){return"type"in n&&n.type!=="function"&&n.type!=="custom"}function aw(n){return n!=null&&typeof n=="object"&&"type"in n&&n.type!=="function"}function iw(n){return typeof n=="object"&&n!==null&&"metadata"in n&&typeof n.metadata=="object"&&n.metadata!==null&&"customTool"in n.metadata&&typeof n.metadata.customTool=="object"&&n.metadata.customTool!==null}function uh(n){return"type"in n&&n.type==="custom"&&"custom"in n&&typeof n.custom=="object"&&n.custom!==null}function ow(n){if(n.type==="custom_tool_call")return{...n,type:"tool_call",call_id:n.id,id:n.call_id,name:n.name,isCustomTool:!0,args:{input:n.input}}}function uw(n){return n.type==="tool_call"&&"isCustomTool"in n&&n.isCustomTool===!0}function cw(n){const e=()=>{if(n.custom.format){if(n.custom.format.type==="grammar")return{type:"grammar",definition:n.custom.format.grammar.definition,syntax:n.custom.format.grammar.syntax};if(n.custom.format.type==="text")return{type:"text"}}};return{type:"custom",name:n.custom.name,description:n.custom.description,format:e()}}function lw(n){const e=()=>{if(n.format){if(n.format.type==="grammar")return{type:"grammar",grammar:{definition:n.format.definition,syntax:n.format.syntax}};if(n.format.type==="text")return{type:"text"}}};return{type:"custom",custom:{name:n.name,description:n.description,format:e()}}}function dw(n,e){if(e&&typeof e=="object"&&"images"in e&&Array.isArray(e.images)){const t=e.images.filter(r=>typeof r?.image_url?.url=="string").map(r=>({type:"image",url:r.image_url.url,source_type:"url"}));return[{type:"text",text:n,source_type:"text"},...t]}return n}const on="__openai_function_call_ids__";function fs(n){return n?!!(/^o\d/.test(n??"")||n.startsWith("gpt-5")&&!n.startsWith("gpt-5-chat")):!1}function hw(n){return n!==void 0&&typeof n.schema=="object"}function fw(n){return n.role!=="system"&&n.role!=="developer"&&n.role!=="assistant"&&n.role!=="user"&&n.role!=="function"&&n.role!=="tool"&&console.warn(`Unknown message role: ${n.role}`),n.role}function to(n){const e=n._getType();switch(e){case"system":return"system";case"ai":return"assistant";case"human":return"user";case"function":return"function";case"tool":return"tool";case"generic":{if(!Lr.isInstance(n))throw new Error("Invalid generic chat message");return fw(n)}default:throw new Error(`Unknown message type: ${e}`)}}const ch={providerName:"ChatOpenAI",fromStandardTextBlock(n){return{type:"text",text:n.text}},fromStandardImageBlock(n){if(n.source_type==="url")return{type:"image_url",image_url:{url:n.url,...n.metadata?.detail?{detail:n.metadata.detail}:{}}};if(n.source_type==="base64")return{type:"image_url",image_url:{url:`data:${n.mime_type??""};base64,${n.data}`,...n.metadata?.detail?{detail:n.metadata.detail}:{}}};throw new Error(`Image content blocks with source_type ${n.source_type} are not supported for ChatOpenAI`)},fromStandardAudioBlock(n){if(n.source_type==="url"){const e=Uo({dataUrl:n.url});if(!e)throw new Error(`URL audio blocks with source_type ${n.source_type} must be formatted as a data URL for ChatOpenAI`);const t=e.mime_type||n.mime_type||"";let r;try{r=Mo(t)}catch{throw new Error(`Audio blocks with source_type ${n.source_type} must have mime type of audio/wav or audio/mp3`)}if(r.type!=="audio"||r.subtype!=="wav"&&r.subtype!=="mp3")throw new Error(`Audio blocks with source_type ${n.source_type} must have mime type of audio/wav or audio/mp3`);return{type:"input_audio",input_audio:{format:r.subtype,data:e.data}}}if(n.source_type==="base64"){let e;try{e=Mo(n.mime_type??"")}catch{throw new Error(`Audio blocks with source_type ${n.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 ${n.source_type} must have mime type of audio/wav or audio/mp3`);return{type:"input_audio",input_audio:{format:e.subtype,data:n.data}}}throw new Error(`Audio content blocks with source_type ${n.source_type} are not supported for ChatOpenAI`)},fromStandardFileBlock(n){if(n.source_type==="url"){if(!Uo({dataUrl:n.url}))throw new Error(`URL file blocks with source_type ${n.source_type} must be formatted as a data URL for ChatOpenAI`);return{type:"file",file:{file_data:n.url,...n.metadata?.filename||n.metadata?.name?{filename:n.metadata?.filename||n.metadata?.name}:{}}}}if(n.source_type==="base64")return{type:"file",file:{file_data:`data:${n.mime_type??""};base64,${n.data}`,...n.metadata?.filename||n.metadata?.name||n.metadata?.title?{filename:n.metadata?.filename||n.metadata?.name||n.metadata?.title}:{}}};if(n.source_type==="id")return{type:"file",file:{file_id:n.id}};throw new Error(`File content blocks with source_type ${n.source_type} are not supported for ChatOpenAI`)}};function Nc(n,e){return n.flatMap(t=>{let r=to(t);r==="system"&&fs(e)&&(r="developer");const s=typeof t.content=="string"?t.content:t.content.map(i=>xt(i)?id(i,ch):i),a={role:r,content:s};if(t.name!=null&&(a.name=t.name),t.additional_kwargs.function_call!=null&&(a.function_call=t.additional_kwargs.function_call,a.content=""),jr(t)&&t.tool_calls?.length?(a.tool_calls=t.tool_calls.map(sb),a.content=""):(t.additional_kwargs.tool_calls!=null&&(a.tool_calls=t.additional_kwargs.tool_calls),t.tool_call_id!=null&&(a.tool_call_id=t.tool_call_id)),t.additional_kwargs.audio&&typeof t.additional_kwargs.audio=="object"&&"id"in t.additional_kwargs.audio){const i={role:"assistant",audio:{id:t.additional_kwargs.audio.id}};return[a,i]}return a})}class ro extends dt{_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","reasoningEffort","service_tier"]}get lc_secrets(){return{apiKey:"OPENAI_API_KEY",organization:"OPENAI_ORGANIZATION"}}get lc_aliases(){return{apiKey:"openai_api_key",modelName:"model",reasoningEffort:"reasoning_effort"}}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","reasoningEffort","promptCacheKey","verbosity"]}getLsParams(e){const t=this.invocationParams(e);return{ls_provider:"openai",ls_model_name:this.model,ls_model_type:"chat",ls_temperature:t.temperature??void 0,ls_max_tokens:t.max_tokens??void 0,ls_stop:e.stop}}_identifyingParams(){return{model_name:this.model,...this.invocationParams(),...this.clientConfig}}identifyingParams(){return this._identifyingParams()}constructor(e){super(e??{}),Object.defineProperty(this,"temperature",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"topP",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"frequencyPenalty",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"presencePenalty",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"n",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"logitBias",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"model",{enumerable:!0,configurable:!0,writable:!0,value:"gpt-3.5-turbo"}),Object.defineProperty(this,"modelKwargs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"stop",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"stopSequences",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"user",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"timeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"streaming",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"streamUsage",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"maxTokens",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"logprobs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"topLogprobs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"apiKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"organization",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"__includeRawResponse",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"clientConfig",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"supportsStrictToolCalling",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"audio",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"modalities",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"reasoning",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"zdrEnabled",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"service_tier",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"promptCacheKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"verbosity",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"defaultOptions",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),this.apiKey=e?.apiKey??e?.configuration?.apiKey??pt("OPENAI_API_KEY"),this.organization=e?.configuration?.organization??pt("OPENAI_ORGANIZATION"),this.model=e?.model??e?.modelName??this.model,this.modelKwargs=e?.modelKwargs??{},this.timeout=e?.timeout,this.temperature=e?.temperature??this.temperature,this.topP=e?.topP??this.topP,this.frequencyPenalty=e?.frequencyPenalty??this.frequencyPenalty,this.presencePenalty=e?.presencePenalty??this.presencePenalty,this.logprobs=e?.logprobs,this.topLogprobs=e?.topLogprobs,this.n=e?.n??this.n,this.logitBias=e?.logitBias,this.stop=e?.stopSequences??e?.stop,this.stopSequences=this.stop,this.user=e?.user,this.__includeRawResponse=e?.__includeRawResponse,this.audio=e?.audio,this.modalities=e?.modalities,this.reasoning=e?.reasoning??e?.reasoningEffort?{effort:e.reasoningEffort}:void 0,this.maxTokens=e?.maxCompletionTokens??e?.maxTokens,this.disableStreaming=e?.disableStreaming===!0,this.streaming=e?.streaming===!0,this.promptCacheKey=e?.promptCacheKey??this.promptCacheKey,this.verbosity=e?.verbosity??this.verbosity,e?.streaming===!1&&(this.disableStreaming=!0),this.disableStreaming===!0&&(this.streaming=!1),this.streamUsage=e?.streamUsage??this.streamUsage,this.disableStreaming&&(this.streamUsage=!1),this.clientConfig={apiKey:this.apiKey,organization:this.organization,dangerouslyAllowBrowser:!0,...e?.configuration},e?.supportsStrictToolCalling!==void 0&&(this.supportsStrictToolCalling=e.supportsStrictToolCalling),e?.service_tier!==void 0&&(this.service_tier=e.service_tier),this.zdrEnabled=e?.zdrEnabled??!1}_getReasoningParams(e){if(!fs(this.model))return;let t;return this.reasoning!==void 0&&(t={...t,...this.reasoning}),e?.reasoning!==void 0&&(t={...t,...e.reasoning}),t}_getResponseFormat(e){return e&&e.type==="json_schema"&&e.json_schema.schema&&Ot(e.json_schema.schema)?tw(e.json_schema.schema,e.json_schema.name,{description:e.json_schema.description}):e}_combineCallOptions(e){return{...this.defaultOptions,...e??{}}}_getClientOptions(e){if(!this.client){const r={baseURL:this.clientConfig.baseURL},s=ib(r),a={...this.clientConfig,baseURL:s,timeout:this.timeout,maxRetries:0};a.baseURL||delete a.baseURL,this.client=new H(a)}return{...this.clientConfig,...e}}_convertChatOpenAIToolToCompletionsTool(e,t){return iw(e)?lw(e.metadata.customTool):Xd(e)?t?.strict!==void 0?{...e,function:{...e.function,strict:t.strict}}:e:sw(e,t)}bindTools(e,t){let r;return t?.strict!==void 0?r=t.strict:this.supportsStrictToolCalling!==void 0&&(r=this.supportsStrictToolCalling),this.withConfig({tools:e.map(s=>eo(s)?s:this._convertChatOpenAIToolToCompletionsTool(s,{strict:r})),...t})}async stream(e,t){return super.stream(e,this._combineCallOptions(t))}async invoke(e,t){return super.invoke(e,this._combineCallOptions(t))}_combineLLMOutput(...e){return e.reduce((t,r)=>(r&&r.tokenUsage&&(t.tokenUsage.completionTokens+=r.tokenUsage.completionTokens??0,t.tokenUsage.promptTokens+=r.tokenUsage.promptTokens??0,t.tokenUsage.totalTokens+=r.tokenUsage.totalTokens??0),t),{tokenUsage:{completionTokens:0,promptTokens:0,totalTokens:0}})}async getNumTokensFromMessages(e){let t=0,r=0,s=0;this.model==="gpt-3.5-turbo-0301"?(r=4,s=-1):(r=3,s=1);const a=await Promise.all(e.map(async i=>{const o=await this.getNumTokens(i.content),u=await this.getNumTokens(to(i)),c=i.name!==void 0?s+await this.getNumTokens(i.name):0;let l=o+r+u+c;const d=i;if(d._getType()==="function"&&(l-=2),d.additional_kwargs?.function_call&&(l+=3),d?.additional_kwargs.function_call?.name&&(l+=await this.getNumTokens(d.additional_kwargs.function_call?.name)),d.additional_kwargs.function_call?.arguments)try{l+=await this.getNumTokens(JSON.stringify(JSON.parse(d.additional_kwargs.function_call?.arguments)))}catch(h){console.error("Error parsing function arguments",h,JSON.stringify(d.additional_kwargs.function_call)),l+=await this.getNumTokens(d.additional_kwargs.function_call?.arguments)}return t+=l,l}));return t+=3,{totalCount:t,countPerMessage:a}}async _getNumTokensFromGenerations(e){return(await Promise.all(e.map(async r=>r.message.additional_kwargs?.function_call?(await this.getNumTokensFromMessages([r.message])).countPerMessage[0]:await this.getNumTokens(r.message.content)))).reduce((r,s)=>r+s,0)}async _getEstimatedTokenCountFromPrompt(e,t,r){let s=(await this.getNumTokensFromMessages(e)).totalCount;if(t&&r!=="auto"){const a=nw(t);s+=await this.getNumTokens(a),s+=9}return t&&e.find(a=>a._getType()==="system")&&(s-=4),r==="none"?s+=1:typeof r=="object"&&(s+=await this.getNumTokens(r.name)+4),s}_getStructuredOutputMethod(e){const t={...e};if(!this.model.startsWith("gpt-3")&&!this.model.startsWith("gpt-4-")&&this.model!=="gpt-4"){if(t?.method===void 0)return"jsonSchema"}else t.method==="jsonSchema"&&console.warn(`[WARNING]: JSON Schema is not supported for model "${this.model}". Falling back to tool calling.`);return t.method}withStructuredOutput(e,t){let r,s,a,i;hw(e)?(r=e.schema,s=e.name,a=e.method,i=e.includeRaw):(r=e,s=t?.name,a=t?.method,i=t?.includeRaw);let o,u;if(t?.strict!==void 0&&a==="jsonMode")throw new Error("Argument `strict` is only supported for `method` = 'function_calling'");if(a=this._getStructuredOutputMethod({...t,method:a}),a==="jsonMode"){Ot(r)?u=Ic.fromZodSchema(r):u=new xc;const h=ft(r);o=this.withConfig({response_format:{type:"json_object"},ls_structured_output_format:{kwargs:{method:"json_mode"},schema:{title:s??"extract",...h}}})}else if(a==="jsonSchema"){const h={name:s??"extract",description:Ki(r),schema:r,strict:t?.strict},f=ft(h.schema);if(o=this.withConfig({response_format:{type:"json_schema",json_schema:h},ls_structured_output_format:{kwargs:{method:"json_schema"},schema:{title:h.name,description:h.description,...f}}}),Ot(r)){const p=Ic.fromZodSchema(r);u=Qt.from(m=>"parsed"in m.additional_kwargs?m.additional_kwargs.parsed:p)}else u=new xc}else{let h=s??"extract";if(Ot(r)){const f=ft(r);o=this.withConfig({tools:[{type:"function",function:{name:h,description:f.description,parameters:f}}],tool_choice:{type:"function",function:{name:h}},ls_structured_output_format:{kwargs:{method:"function_calling"},schema:{title:h,...f}},...t?.strict!==void 0?{strict:t.strict}:{}}),u=new Rc({returnSingle:!0,keyName:h,zodSchema:r})}else{let f;typeof r.name=="string"&&typeof r.parameters=="object"&&r.parameters!=null?(f=r,h=r.name):(h=r.title??h,f={name:h,description:r.description??"",parameters:r});const p=ft(r);o=this.withConfig({tools:[{type:"function",function:f}],tool_choice:{type:"function",function:{name:h}},ls_structured_output_format:{kwargs:{method:"function_calling"},schema:{title:h,...p}},...t?.strict!==void 0?{strict:t.strict}:{}}),u=new Rc({returnSingle:!0,keyName:h})}}if(!i)return o.pipe(u);const c=Un.assign({parsed:(h,f)=>u.invoke(h.raw,f)}),l=Un.assign({parsed:()=>null}),d=c.withFallbacks({fallbacks:[l]});return st.from([{raw:o},d])}}class pw extends ro{invocationParams(e){let t;e?.strict!==void 0?t=e.strict:this.supportsStrictToolCalling!==void 0&&(t=this.supportsStrictToolCalling);const r={model:this.model,temperature:this.temperature,top_p:this.topP,user:this.user,stream:this.streaming,previous_response_id:e?.previous_response_id,truncation:e?.truncation,include:e?.include,tools:e?.tools?.length?this._reduceChatOpenAITools(e.tools,{stream:this.streaming,strict:t}):void 0,tool_choice:aw(e?.tool_choice)?e?.tool_choice:(()=>{const a=ih(e?.tool_choice);if(typeof a=="object"&&"type"in a){if(a.type==="function")return{type:"function",name:a.function.name};if(a.type==="allowed_tools")return{type:"allowed_tools",mode:a.allowed_tools.mode,tools:a.allowed_tools.tools};if(a.type==="custom")return{type:"custom",name:a.custom.name}}})(),text:(()=>{if(e?.text)return e.text;const a=this._getResponseFormat(e?.response_format);return a?.type==="json_schema"?a.json_schema.schema!=null?{format:{type:"json_schema",schema:a.json_schema.schema,description:a.json_schema.description,name:a.json_schema.name,strict:a.json_schema.strict},verbosity:e?.verbosity}:void 0:{format:a,verbosity:e?.verbosity}})(),parallel_tool_calls:e?.parallel_tool_calls,max_output_tokens:this.maxTokens===-1?void 0:this.maxTokens,prompt_cache_key:e?.promptCacheKey??this.promptCacheKey,...this.zdrEnabled?{store:!1}:{},...this.modelKwargs},s=this._getReasoningParams(e);return s!==void 0&&(r.reasoning=s),r}async _generate(e,t){const r=this.invocationParams(t);if(r.stream){const s=this._streamResponseChunks(e,t);let a;for await(const i of s)i.message.response_metadata={...i.generationInfo,...i.message.response_metadata},a=a?.concat(i)??i;return{generations:a?[a]:[],llmOutput:{estimatedTokenUsage:a?.message?.usage_metadata}}}else{const s=this._convertMessagesToResponsesParams(e),a=await this.completionWithRetry({input:s,...r,stream:!1},{signal:t?.signal,...t?.options});return{generations:[{text:a.output_text,message:this._convertResponsesMessageToBaseMessage(a)}],llmOutput:{id:a.id,estimatedTokenUsage:a.usage?{promptTokens:a.usage.input_tokens,completionTokens:a.usage.output_tokens,totalTokens:a.usage.total_tokens}:void 0}}}}async*_streamResponseChunks(e,t,r){const s=await this.completionWithRetry({...this.invocationParams(t),input:this._convertMessagesToResponsesParams(e),stream:!0},t);for await(const a of s){const i=this._convertResponsesDeltaToBaseMessageChunk(a);i!=null&&(yield i,await r?.handleLLMNewToken(i.text||"",{prompt:t.promptIndex??0,completion:0},void 0,void 0,void 0,{chunk:i}))}}async completionWithRetry(e,t){return this.caller.call(async()=>{const r=this._getClientOptions(t);try{return e.text?.format?.type==="json_schema"&&!e.stream?await this.client.responses.parse(e,r):await this.client.responses.create(e,r)}catch(s){throw ah(s)}})}_convertResponsesMessageToBaseMessage(e){if(e.error){const u=new Error(e.error.message);throw u.name=e.error.code,u}let t;const r=[],s=[],a=[],i={model:e.model,created_at:e.created_at,id:e.id,incomplete_details:e.incomplete_details,metadata:e.metadata,object:e.object,status:e.status,user:e.user,service_tier:e.service_tier,model_name:e.model},o={};for(const u of e.output)if(u.type==="message")t=u.id,r.push(...u.content.flatMap(c=>c.type==="output_text"?("parsed"in c&&c.parsed!=null&&(o.parsed=c.parsed),{type:"text",text:c.text,annotations:c.annotations}):c.type==="refusal"?(o.refusal=c.refusal,[]):c));else if(u.type==="function_call"){const c={function:{name:u.name,arguments:u.arguments},id:u.call_id};try{s.push(Yi(c,{returnId:!0}))}catch(l){let d;typeof l=="object"&&l!=null&&"message"in l&&typeof l.message=="string"&&(d=l.message),a.push(fi(c,d))}o[on]??={},u.id&&(o[on][u.call_id]=u.id)}else if(u.type==="reasoning")o.reasoning=u;else if(u.type==="custom_tool_call"){const c=ow(u);c?s.push(c):a.push(fi(u,"Malformed custom tool call"))}else o.tool_outputs??=[],o.tool_outputs.push(u);return new Tr({id:t,content:r,tool_calls:s,invalid_tool_calls:a,usage_metadata:e.usage,additional_kwargs:o,response_metadata:i})}_convertResponsesDeltaToBaseMessageChunk(e){const t=[];let r={},s;const a=[],i={},o={};let u;if(e.type==="response.output_text.delta")t.push({type:"text",text:e.delta,index:e.content_index});else if(e.type==="response.output_text.annotation.added")t.push({type:"text",text:"",annotations:[e.annotation],index:e.content_index});else if(e.type==="response.output_item.added"&&e.item.type==="message")u=e.item.id;else if(e.type==="response.output_item.added"&&e.item.type==="function_call")a.push({type:"tool_call_chunk",name:e.item.name,args:e.item.arguments,id:e.item.call_id,index:e.output_index}),o[on]={[e.item.call_id]:e.item.id};else if(e.type==="response.output_item.done"&&["web_search_call","file_search_call","computer_call","code_interpreter_call","mcp_call","mcp_list_tools","mcp_approval_request","image_generation_call","custom_tool_call"].includes(e.item.type))o.tool_outputs=[e.item];else if(e.type==="response.created")i.id=e.response.id,i.model_name=e.response.model,i.model=e.response.model;else if(e.type==="response.completed"){const c=this._convertResponsesMessageToBaseMessage(e.response);s=e.response.usage,e.response.text?.format?.type==="json_schema"&&(o.parsed??=JSON.parse(c.text));for(const[l,d]of Object.entries(e.response))l!=="id"&&(i[l]=d)}else if(e.type==="response.function_call_arguments.delta"||e.type==="response.custom_tool_call_input.delta")a.push({type:"tool_call_chunk",args:e.delta,index:e.output_index});else if(e.type==="response.web_search_call.completed"||e.type==="response.file_search_call.completed")r={tool_outputs:{id:e.item_id,type:e.type.replace("response.","").replace(".completed",""),status:"completed"}};else if(e.type==="response.refusal.done")o.refusal=e.refusal;else if(e.type==="response.output_item.added"&&"item"in e&&e.item.type==="reasoning"){const c=e.item.summary?e.item.summary.map((l,d)=>({...l,index:d})):void 0;o.reasoning={id:e.item.id,type:e.item.type,...c?{summary:c}:{}}}else if(e.type==="response.reasoning_summary_part.added")o.reasoning={type:"reasoning",summary:[{...e.part,index:e.summary_index}]};else if(e.type==="response.reasoning_summary_text.delta")o.reasoning={type:"reasoning",summary:[{text:e.delta,type:"summary_text",index:e.summary_index}]};else return e.type==="response.image_generation_call.partial_image",null;return new Rt({text:t.map(c=>c.text).join(""),message:new mt({id:u,content:t,tool_call_chunks:a,usage_metadata:s,additional_kwargs:o,response_metadata:i}),generationInfo:r})}_convertMessagesToResponsesParams(e){return e.flatMap(t=>{const r=t.additional_kwargs;let s=to(t);if(s==="system"&&fs(this.model)&&(s="developer"),s==="function")throw new Error("Function messages are not supported in Responses API");if(s==="tool"){const a=t;return r?.type==="computer_call_output"?{type:"computer_call_output",output:(()=>{if(typeof a.content=="string")return{type:"computer_screenshot",image_url:a.content};if(Array.isArray(a.content)){const o=a.content.find(c=>c.type==="computer_screenshot");if(o)return o;const u=a.content.find(c=>c.type==="image_url");if(u)return{type:"computer_screenshot",image_url:typeof u.image_url=="string"?u.image_url:u.image_url.url}}throw new Error("Invalid computer call output")})(),call_id:a.tool_call_id}:a.metadata?.customTool?{type:"custom_tool_call_output",call_id:a.tool_call_id,output:a.content}:{type:"function_call_output",call_id:a.tool_call_id,id:a.id?.startsWith("fc_")?a.id:void 0,output:typeof a.content!="string"?JSON.stringify(a.content):a.content}}if(s==="assistant"){if(!this.zdrEnabled&&t.response_metadata.output!=null&&Array.isArray(t.response_metadata.output)&&t.response_metadata.output.length>0&&t.response_metadata.output.every(l=>"type"in l))return t.response_metadata.output;const a=[];if(r?.reasoning&&!this.zdrEnabled){const l=this._convertReasoningSummary(r.reasoning);a.push(l)}let{content:i}=t;r?.refusal&&(typeof i=="string"&&(i=[{type:"output_text",text:i,annotations:[]}]),i=[...i,{type:"refusal",refusal:r.refusal}]),(typeof i=="string"||i.length>0)&&a.push({type:"message",role:"assistant",...t.id&&!this.zdrEnabled&&t.id.startsWith("msg_")?{id:t.id}:{},content:typeof i=="string"?i:i.flatMap(l=>l.type==="text"?{type:"output_text",text:l.text,annotations:l.annotations??[]}:l.type==="output_text"||l.type==="refusal"?l:[])});const o=r?.[on];jr(t)&&t.tool_calls?.length?a.push(...t.tool_calls.map(l=>uw(l)?{type:"custom_tool_call",id:l.call_id,call_id:l.id??"",input:l.args.input,name:l.name}:{type:"function_call",name:l.name,arguments:JSON.stringify(l.args),call_id:l.id,...this.zdrEnabled?{id:o?.[l.id]}:{}})):r?.tool_calls&&a.push(...r.tool_calls.map(l=>({type:"function_call",name:l.function.name,call_id:l.id,arguments:l.function.arguments,...this.zdrEnabled?{id:o?.[l.id]}:{}})));const u=t.response_metadata.output?.length?t.response_metadata.output:r.tool_outputs,c=["computer_call","mcp_call","code_interpreter_call","image_generation_call"];if(u!=null){const d=u?.filter(h=>c.includes(h.type));d.length>0&&a.push(...d)}return a}if(s==="user"||s==="system"||s==="developer"){if(typeof t.content=="string")return{type:"message",role:s,content:t.content};const a=[],i=t.content.flatMap(o=>(o.type==="mcp_approval_response"&&a.push({type:"mcp_approval_response",approval_request_id:o.approval_request_id,approve:o.approve}),xt(o)?id(o,ch):o.type==="text"?{type:"input_text",text:o.text}:o.type==="image_url"?{type:"input_image",image_url:typeof o.image_url=="string"?o.image_url:o.image_url.url,detail:typeof o.image_url=="string"?"auto":o.image_url.detail}:o.type==="input_text"||o.type==="input_image"||o.type==="input_file"?o:[]));return i.length>0&&a.push({type:"message",role:s,content:i}),a}return console.warn(`Unsupported role found when converting to OpenAI Responses API: ${s}`),[]})}_convertReasoningSummary(e){const t=(e.summary.length>1?e.summary.reduce((r,s)=>{const a=r.at(-1);return a.index===s.index?a.text+=s.text:r.push(s),r},[{...e.summary[0]}]):e.summary).map(r=>Object.fromEntries(Object.entries(r).filter(([s])=>s!=="index")));return{...e,summary:t}}_reduceChatOpenAITools(e,t){const r=[];for(const s of e)eo(s)?(s.type==="image_generation"&&t?.stream&&(s.partial_images=1),r.push(s)):Xd(s)?r.push({type:"function",name:s.function.name,parameters:s.function.parameters,description:s.function.description,strict:t?.strict??null}):uh(s)&&r.push(cw(s));return r}}class mw extends ro{invocationParams(e,t){let r;e?.strict!==void 0?r=e.strict:this.supportsStrictToolCalling!==void 0&&(r=this.supportsStrictToolCalling);let s={};e?.stream_options!==void 0?s={stream_options:e.stream_options}:this.streamUsage&&(this.streaming||t?.streaming)&&(s={stream_options:{include_usage:!0}});const a={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:e?.stop??this.stopSequences,user:this.user,stream:this.streaming,functions:e?.functions,function_call:e?.function_call,tools:e?.tools?.length?e.tools.map(o=>this._convertChatOpenAIToolToCompletionsTool(o,{strict:r})):void 0,tool_choice:ih(e?.tool_choice),response_format:this._getResponseFormat(e?.response_format),seed:e?.seed,...s,parallel_tool_calls:e?.parallel_tool_calls,...this.audio||e?.audio?{audio:this.audio||e?.audio}:{},...this.modalities||e?.modalities?{modalities:this.modalities||e?.modalities}:{},...this.modelKwargs,prompt_cache_key:e?.promptCacheKey??this.promptCacheKey,verbosity:e?.verbosity??this.verbosity};e?.prediction!==void 0&&(a.prediction=e.prediction),this.service_tier!==void 0&&(a.service_tier=this.service_tier),e?.service_tier!==void 0&&(a.service_tier=e.service_tier);const i=this._getReasoningParams(e);return i!==void 0&&i.effort!==void 0&&(a.reasoning_effort=i.effort),fs(a.model)?a.max_completion_tokens=this.maxTokens===-1?void 0:this.maxTokens:a.max_tokens=this.maxTokens===-1?void 0:this.maxTokens,a}async _generate(e,t,r){const s={},a=this.invocationParams(t),i=Nc(e,this.model);if(a.stream){const o=this._streamResponseChunks(e,t,r),u={};for await(const p of o){p.message.response_metadata={...p.generationInfo,...p.message.response_metadata};const m=p.generationInfo?.completion??0;u[m]===void 0?u[m]=p:u[m]=u[m].concat(p)}const c=Object.entries(u).sort(([p],[m])=>parseInt(p,10)-parseInt(m,10)).map(([p,m])=>m),{functions:l,function_call:d}=this.invocationParams(t),h=await this._getEstimatedTokenCountFromPrompt(e,l,d),f=await this._getNumTokensFromGenerations(c);return s.input_tokens=h,s.output_tokens=f,s.total_tokens=h+f,{generations:c,llmOutput:{estimatedTokenUsage:{promptTokens:s.input_tokens,completionTokens:s.output_tokens,totalTokens:s.total_tokens}}}}else{const o=await this.completionWithRetry({...a,stream:!1,messages:i},{signal:t?.signal,...t?.options}),{completion_tokens:u,prompt_tokens:c,total_tokens:l,prompt_tokens_details:d,completion_tokens_details:h}=o?.usage??{};u&&(s.output_tokens=(s.output_tokens??0)+u),c&&(s.input_tokens=(s.input_tokens??0)+c),l&&(s.total_tokens=(s.total_tokens??0)+l),(d?.audio_tokens!==null||d?.cached_tokens!==null)&&(s.input_token_details={...d?.audio_tokens!==null&&{audio:d?.audio_tokens},...d?.cached_tokens!==null&&{cache_read:d?.cached_tokens}}),(h?.audio_tokens!==null||h?.reasoning_tokens!==null)&&(s.output_token_details={...h?.audio_tokens!==null&&{audio:h?.audio_tokens},...h?.reasoning_tokens!==null&&{reasoning:h?.reasoning_tokens}});const f=[];for(const p of o?.choices??[]){const g={text:p.message?.content??"",message:this._convertCompletionsMessageToBaseMessage(p.message??{role:"assistant"},o)};g.generationInfo={...p.finish_reason?{finish_reason:p.finish_reason}:{},...p.logprobs?{logprobs:p.logprobs}:{}},jr(g.message)&&(g.message.usage_metadata=s),g.message=new Tr(Object.fromEntries(Object.entries(g.message).filter(([_])=>!_.startsWith("lc_")))),f.push(g)}return{generations:f,llmOutput:{tokenUsage:{promptTokens:s.input_tokens,completionTokens:s.output_tokens,totalTokens:s.total_tokens}}}}}async*_streamResponseChunks(e,t,r){const s=Nc(e,this.model),a={...this.invocationParams(t,{streaming:!0}),messages:s,stream:!0};let i;const o=await this.completionWithRetry(a,t);let u;for await(const c of o){const l=c?.choices?.[0];if(c.usage&&(u=c.usage),!l)continue;const{delta:d}=l;if(!d)continue;const h=this._convertCompletionsDeltaToBaseMessageChunk(d,c,i);i=d.role??i;const f={prompt:t.promptIndex??0,completion:l.index??0};if(typeof h.content!="string"){console.log("[WARNING]: Received non-string content from OpenAI. This is currently not supported.");continue}const p={...f};l.finish_reason!=null&&(p.finish_reason=l.finish_reason,p.system_fingerprint=c.system_fingerprint,p.model_name=c.model,p.service_tier=c.service_tier),this.logprobs&&(p.logprobs=l.logprobs);const m=new Rt({message:h,text:h.content,generationInfo:p});yield m,await r?.handleLLMNewToken(m.text??"",f,void 0,void 0,void 0,{chunk:m})}if(u){const c={...u.prompt_tokens_details?.audio_tokens!==null&&{audio:u.prompt_tokens_details?.audio_tokens},...u.prompt_tokens_details?.cached_tokens!==null&&{cache_read:u.prompt_tokens_details?.cached_tokens}},l={...u.completion_tokens_details?.audio_tokens!==null&&{audio:u.completion_tokens_details?.audio_tokens},...u.completion_tokens_details?.reasoning_tokens!==null&&{reasoning:u.completion_tokens_details?.reasoning_tokens}};yield new Rt({message:new mt({content:"",response_metadata:{usage:{...u}},usage_metadata:{input_tokens:u.prompt_tokens,output_tokens:u.completion_tokens,total_tokens:u.total_tokens,...Object.keys(c).length>0&&{input_token_details:c},...Object.keys(l).length>0&&{output_token_details:l}}}),text:""})}if(t.signal?.aborted)throw new Error("AbortError")}async completionWithRetry(e,t){const r=this._getClientOptions(t),s=e.response_format&&e.response_format.type==="json_schema";return this.caller.call(async()=>{try{return s&&!e.stream?await this.client.chat.completions.parse(e,r):await this.client.chat.completions.create(e,r)}catch(a){throw ah(a)}})}_convertCompletionsMessageToBaseMessage(e,t){const r=e.tool_calls;switch(e.role){case"assistant":{const s=[],a=[];for(const c of r??[])try{s.push(Yi(c,{returnId:!0}))}catch(l){a.push(fi(c,l.message))}const i={function_call:e.function_call,tool_calls:r};this.__includeRawResponse!==void 0&&(i.__raw_response=t);const o={model_name:t.model,...t.system_fingerprint?{usage:{...t.usage},system_fingerprint:t.system_fingerprint}:{}};e.audio&&(i.audio=e.audio);const u=dw(e.content||"",t.choices?.[0]?.message);return new Tr({content:u,tool_calls:s,invalid_tool_calls:a,additional_kwargs:i,response_metadata:o,id:t.id})}default:return new Lr(e.content||"",e.role??"unknown")}}_convertCompletionsDeltaToBaseMessageChunk(e,t,r){const s=e.role??r,a=e.content??"";let i;e.function_call?i={function_call:e.function_call}:e.tool_calls?i={tool_calls:e.tool_calls}:i={},this.__includeRawResponse&&(i.__raw_response=t),e.audio&&(i.audio={...e.audio,index:t.choices[0].index});const o={usage:{...t.usage}};if(s==="user")return new es({content:a,response_metadata:o});if(s==="assistant"){const u=[];if(Array.isArray(e.tool_calls))for(const c of e.tool_calls)u.push({name:c.function?.name,args:c.function?.arguments,id:c.id,index:c.index,type:"tool_call_chunk"});return new mt({content:a,tool_call_chunks:u,additional_kwargs:i,id:t.id,response_metadata:o})}else return s==="system"?new Ar({content:a,response_metadata:o}):s==="developer"?new Ar({content:a,response_metadata:o,additional_kwargs:{__openai_role__:"developer"}}):s==="function"?new Qn({content:a,additional_kwargs:i,name:e.name,response_metadata:o}):s==="tool"?new Mi({content:a,additional_kwargs:i,tool_call_id:e.tool_call_id,response_metadata:o}):new Xn({content:a,role:s,response_metadata:o})}}class no extends ro{get lc_serializable_keys(){return[...super.lc_serializable_keys,"useResponsesApi"]}constructor(e){super(e),Object.defineProperty(this,"fields",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"useResponsesApi",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"responses",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"completions",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.useResponsesApi=e?.useResponsesApi??!1,this.responses=e?.responses??new pw(e),this.completions=e?.completions??new mw(e)}_useResponsesApi(e){const t=e?.tools?.some(eo),r=e?.previous_response_id!=null||e?.text!=null||e?.truncation!=null||e?.include!=null||e?.reasoning?.summary!=null||this.reasoning?.summary!=null,s=e?.tools?.some(uh);return this.useResponsesApi||t||r||s}getLsParams(e){const t=this._combineCallOptions(e);return this._useResponsesApi(e)?this.responses.getLsParams(t):this.completions.getLsParams(t)}invocationParams(e){const t=this._combineCallOptions(e);return this._useResponsesApi(e)?this.responses.invocationParams(t):this.completions.invocationParams(t)}async _generate(e,t,r){return this._useResponsesApi(t)?this.responses._generate(e,t):this.completions._generate(e,t,r)}async*_streamResponseChunks(e,t,r){if(this._useResponsesApi(t)){yield*this.responses._streamResponseChunks(e,this._combineCallOptions(t),r);return}yield*this.completions._streamResponseChunks(e,this._combineCallOptions(t),r)}withConfig(e){const t=new no(this.fields);return t.defaultOptions={...this.defaultOptions,...e},t}}class gw{constructor(){}async handleParseData(e,t){try{console.log("[AiParsingService] Handle parse data request");const r=await this.parseData(e);r.success?t({success:!0,data:r.data}):t({$isError:!0,message:r.error||"AI parsing failed",data:null})}catch(r){console.error("[AiParsingService] Parse data error:",r),t({$isError:!0,message:r instanceof Error?r.message:"Unknown error in AI parsing",data:null})}}async parseData(e){try{const{sourceData:t,schemaDefinition:r,prompt:s,model:a="gpt-4o-mini",apiKey:i}=e;if(!i||i.trim()==="")return{success:!1,error:"OpenAI API key is required. Please provide it in the ai-parse-data block."};const o=r.type==="array",u=this.reconstructZodSchema(r),l=new no({apiKey:i,modelName:a,temperature:0}).withStructuredOutput(u),d=this.buildPrompt(t,r,s),h=await l.invoke(d);return{success:!0,data:o&&h&&typeof h=="object"&&"items"in h?h.items:h}}catch(t){return console.error("[AI Parsing Service] Parsing failed:",t),{success:!1,error:t instanceof Error?t.message:"Unknown error during AI parsing"}}}reconstructZodSchema(e){if(e.type==="array"&&e.items){const t=this.buildZodType(e.items);return gr({items:so(t)})}if(e.type==="object"&&e.shape){const t={};for(const[r,s]of Object.entries(e.shape))t[r]=this.buildZodType(s);return gr(t)}return Ft()}buildZodType(e){let t;switch(e.type){case"string":e.enum&&Array.isArray(e.enum)&&e.enum.length>0?t=yh(e.enum):t=mi();break;case"number":if(e.enum&&Array.isArray(e.enum)&&e.enum.length>0){const r=e.enum.map(s=>mh(s));t=gh(r)}else t=_h();break;case"boolean":t=ph();break;case"array":t=so(e.items?this.buildZodType(e.items):Ft());break;case"object":if(e.shape){const r={};for(const[s,a]of Object.entries(e.shape))r[s]=this.buildZodType(a);t=gr(r)}else t=Ft();break;default:t=Ft()}return e.optional&&(t=t.optional()),t}buildPrompt(e,t,r){const s=typeof e=="string"?e:JSON.stringify(e,null,2),a=this.describeSchema(t),i=t.type==="array";return`You are a data parsing assistant. Your task is to extract and structure data according to the provided schema.
|
|
140
|
+
|
|
141
|
+
Source Data:
|
|
142
|
+
\`\`\`
|
|
143
|
+
${s}
|
|
144
|
+
\`\`\`
|
|
145
|
+
|
|
146
|
+
Expected Output Schema:
|
|
147
|
+
${a}
|
|
148
|
+
|
|
149
|
+
${r?`
|
|
150
|
+
Additional Instructions:
|
|
151
|
+
${r}
|
|
152
|
+
`:""}
|
|
153
|
+
|
|
154
|
+
Please parse the source data and return it in the exact format specified by the schema. Extract all relevant information and ensure the data types match the schema.${i?`
|
|
155
|
+
|
|
156
|
+
IMPORTANT: Return the array in an object with "items" field: { items: [...your array here...] }`:""}`}describeSchema(e,t=0){const r=" ".repeat(t);if(e.type==="array"&&e.items)return`Array<${this.describeSchema(e.items,0)}>`;if(e.type==="object"&&e.shape){let s=`${r}{
|
|
157
|
+
`;for(const[a,i]of Object.entries(e.shape)){const o=i.optional?" (optional)":"",u=i.description?` // ${i.description}`:"";s+=`${r} ${a}: ${this.describeSchema(i,t+1)}${o}${u}
|
|
158
|
+
`}return s+=`${r}}`,s}return e.enum&&Array.isArray(e.enum)?e.enum.map(a=>JSON.stringify(a)).join(" | "):e.type||"any"}}class _w{async handleClick(e,t){try{console.log("[CdpService] Handle click request:",e);const{tabId:r,x:s,y:a}=e;await this.click(r,s,a),t({success:!0,data:{clicked:!0}})}catch(r){console.error("[CdpService] Click error:",r),t({$isError:!0,message:r instanceof Error?r.message:"CDP click failed",data:null})}}async handleKeypress(e,t){try{console.log("[CdpService] Handle keypress request:",e);const{tabId:r,key:s,code:a,keyCode:i,modifiers:o}=e;await this.keypress(r,s,a,i,o),t({success:!0,data:{pressed:!0}})}catch(r){console.error("[CdpService] Keypress error:",r),t({$isError:!0,message:r instanceof Error?r.message:"CDP keypress failed",data:null})}}async click(e,t,r){console.log("[CdpService] Click request - tabId:",e,"x:",t,"y:",r),await chrome.debugger.attach({tabId:e},"1.3"),console.log("[CdpService] Debugger attached to tab:",e);try{await chrome.debugger.sendCommand({tabId:e},"Input.dispatchMouseEvent",{type:"mouseMoved",x:t,y:r,button:"none",clickCount:0}),await chrome.debugger.sendCommand({tabId:e},"Input.dispatchMouseEvent",{type:"mousePressed",x:t,y:r,button:"left",clickCount:1}),await chrome.debugger.sendCommand({tabId:e},"Input.dispatchMouseEvent",{type:"mouseReleased",x:t,y:r,button:"left",clickCount:1}),console.log("[CdpService] Click completed successfully")}finally{await chrome.debugger.detach({tabId:e}),console.log("[CdpService] Debugger detached from tab:",e)}}async keypress(e,t,r,s,a=[]){console.log("[CdpService] Keypress request - tabId:",e,"key:",t),await chrome.debugger.attach({tabId:e},"1.3"),console.log("[CdpService] Debugger attached to tab:",e);try{const i=this.convertModifiersToCdp(a);await chrome.debugger.sendCommand({tabId:e},"Input.dispatchKeyEvent",{type:"keyDown",key:t,code:r,windowsVirtualKeyCode:s,nativeVirtualKeyCode:s,modifiers:i}),await chrome.debugger.sendCommand({tabId:e},"Input.dispatchKeyEvent",{type:"keyUp",key:t,code:r,windowsVirtualKeyCode:s,nativeVirtualKeyCode:s,modifiers:i}),console.log("[CdpService] Keypress completed successfully")}finally{await chrome.debugger.detach({tabId:e}),console.log("[CdpService] Debugger detached from tab:",e)}}convertModifiersToCdp(e){let t=0;return e.includes("Alt")&&(t|=1),e.includes("Control")&&(t|=2),e.includes("Meta")&&(t|=4),e.includes("Shift")&&(t|=8),t}}class yw{constructor(e){this.tabManager=e}async run(e,t){const r={steps:{},vars:{}},s=new Map(e.steps.map(o=>[o.id,o]));let a=e.start;const i=[];for(;a;){const o=s.get(a);if(!o)break;const u=new Date().toISOString();let c=!1,l=!0,d="",h=null,f=0;if(!this.evaluateWhen(o.when,r))c=!0;else if(o.block)if(o.repeat)h=await this.executeWithRepeat(o,r,t),l=!h?.hasError,d=h?.message||"";else{const _=Math.max(1,o.retry?.attempts??1),y=o.retry?.delayMs??0,b=o.retry?.backoffFactor??1;for(;f<_;){f++;try{const v=this.resolveBindings(o.block,r);if(h=await this.runWithTimeout(()=>this.tabManager.executeBlock(v,t),o.timeoutMs),l=!h?.hasError,d=h?.message||"",l)break}catch(v){l=!1,d=v?.message||"Workflow step error"}if(f<_){const v=y*Math.pow(b,f-1);v>0&&await new Promise(E=>setTimeout(E,v))}}}else c=!0;const m=new Date().toISOString(),g={stepId:o.id,skipped:c,success:l,message:d,result:h,startedAt:u,finishedAt:m,attempts:f};if(i.push(g),r.steps[o.id]={result:h,success:l,skipped:c},o.switch&&o.switch.length>0){const _=o.switch.find(y=>this.evaluateWhen(y.when,r));if(_){!c&&typeof o.delayAfterMs=="number"&&o.delayAfterMs>0&&await new Promise(y=>setTimeout(y,o.delayAfterMs)),a=_.next;continue}}if(l&&o.onSuccess){!c&&typeof o.delayAfterMs=="number"&&o.delayAfterMs>0&&await new Promise(_=>setTimeout(_,o.delayAfterMs)),a=o.onSuccess;continue}if(!l&&o.onFailure){!c&&typeof o.delayAfterMs=="number"&&o.delayAfterMs>0&&await new Promise(_=>setTimeout(_,o.delayAfterMs)),a=o.onFailure;continue}if(o.next){!c&&typeof o.delayAfterMs=="number"&&o.delayAfterMs>0&&await new Promise(_=>setTimeout(_,o.delayAfterMs)),a=o.next;continue}break}return{steps:i}}evaluateWhen(e,t){if(!e)return!0;if(typeof e=="object"&&e!==null&&("exists"in e||"equals"in e||"notEquals"in e||"contains"in e||"regex"in e||"and"in e||"or"in e||"not"in e))return this.evaluateJsonCondition(e,t);if(e.expr&&typeof e.expr=="string")try{const s=t;return!!new Function("$",`return (${e.expr});`)(s)}catch{return!1}return e.json?this.evaluateJsonCondition(e.json,t):!0}evaluateJsonCondition(e,t){if(e.exists)return this.getByPath(t,e.exists)!==void 0;if(e.equals)return this.getByPath(t,e.equals.left)===e.equals.right;if(e.notEquals)return this.getByPath(t,e.notEquals.left)!==e.notEquals.right;if(e.contains){const r=this.getByPath(t,e.contains.value);return Array.isArray(r)?r.some(s=>(s+"").includes(e.contains.search+"")):(r+"").includes(e.contains.search+"")}if(e.regex){const r=this.getByPath(t,e.regex.value)+"";return new RegExp(e.regex.pattern,e.regex.flags||"").test(r)}return e.and?e.and.every(r=>this.evaluateJsonCondition(r,t)):e.or?e.or.some(r=>this.evaluateJsonCondition(r,t)):e.not?!this.evaluateJsonCondition(e.not,t):!1}resolveBindings(e,t){if(e==null)return e;if(typeof e=="string")return this.interpolate(e,t);if(Array.isArray(e))return e.map(r=>this.resolveBindings(r,t));if(typeof e=="object"){if(Object.prototype.hasOwnProperty.call(e,"valueFrom")||Object.prototype.hasOwnProperty.call(e,"template")){const s=e.valueFrom,a=e.template,i=e.default;try{if(typeof s=="string"){const o=this.getByPath(t,s);return o===void 0?i:o}if(typeof a=="string"){const o=this.interpolate(a,t);return o==null||o===""?i:o}}catch{return i}}const r=Array.isArray(e)?[]:{};for(const s of Object.keys(e))r[s]=this.resolveBindings(e[s],t);return r}return e}interpolate(e,t){const r=/^\$\{([^}]+)\}$/.exec(e);return r?this.getByPath(t,r[1].trim()):/^\$\./.test(e)?this.getByPath(t,e):e.replace(/\$\{([^}]+)\}/g,(s,a)=>{const i=this.getByPath(t,a.trim());return i==null?"":typeof i=="object"?JSON.stringify(i):String(i)})}getByPath(e,t){return(t.startsWith("$.")?t.slice(2):t).split(".").reduce((s,a)=>s?.[a],e)}async runWithTimeout(e,t){return!t||t<=0?e():new Promise((r,s)=>{const a=setTimeout(()=>s(new Error("Step timeout")),t);e().then(i=>{clearTimeout(a),r(i)}).catch(i=>{clearTimeout(a),s(i)})})}async executeWithRepeat(e,t,r){const s=e.repeat,a=[],i=[];let o=[],u=!1;if(s.forEach){u=!0;const c=this.getByPath(t,s.forEach);Array.isArray(c)?o=c:c!=null?o=[c]:o=[]}else if(s.count!=null){let c;typeof s.count=="string"?c=this.getByPath(t,s.count)??0:c=s.count,o=Array.from({length:Math.max(0,c)},(l,d)=>d)}else return{hasError:!0,message:"repeat requires either forEach or count",data:null};for(let c=0;c<o.length;c++){const l=o[c];u?t.forEach={item:l,index:c,total:o.length}:t.loop={index:c,count:o.length};try{const d=Math.max(1,e.retry?.attempts??1),h=e.retry?.delayMs??0,f=e.retry?.backoffFactor??1;let p=null,m=!1;for(let g=0;g<d;g++){try{const _=this.resolveBindings(e.block,t);if(p=await this.runWithTimeout(()=>this.tabManager.executeBlock(_,r),e.timeoutMs),m=!p?.hasError,m)break}catch(_){p={hasError:!0,message:_?.message||"Block execution error"}}if(g<d-1){const _=h*Math.pow(f,g);_>0&&await new Promise(y=>setTimeout(y,_))}}if(m)a.push(p);else if(i.push({index:c,item:l,error:p}),s.continueOnError)a.push(null);else return{hasError:!0,message:`Repeat failed at index ${c}: ${p?.message||"Unknown error"}`,data:{results:a,errors:i,stoppedAt:c}}}catch(d){if(i.push({index:c,item:l,error:d.message}),s.continueOnError)a.push(null);else return{hasError:!0,message:`Repeat failed at index ${c}: ${d.message}`,data:{results:a,errors:i,stoppedAt:c}}}s.delayBetween&&c<o.length-1&&await new Promise(d=>setTimeout(d,s.delayBetween))}return u?delete t.forEach:delete t.loop,{hasError:i.length>0&&!s.continueOnError,message:i.length>0?`Completed with ${i.length} error(s) out of ${o.length}`:`Completed ${o.length} iteration(s)`,data:a}}}class bw{constructor(e){this.tabManager=e,this.workflowRunner=new yw(e)}workflowRunner;async handleCollectWorkflow(e,t){const r=this.validateRequest(e);if(!r.success){t({$isError:!0,message:r.error,data:{}});return}const s=await this.tabManager.createTab(e.targetUrl,e.activateTab===!0);if(s.id===void 0){t({$isError:!0,message:"Failed to create tab or tab ID is missing",data:{}});return}try{console.log("[WorkflowService] Running workflow in tab:",s.id);const a=await this.workflowRunner.run(e.workflow,s.id);t({success:!0,targetUrl:e.targetUrl,tabId:s.id,result:a,timestamp:new Date().toISOString(),closeTabAfterCollection:e.closeTabAfterCollection!==!1})}catch(a){console.error("[WorkflowService] Workflow execution error:",a),t({$isError:!0,message:a instanceof Error?a.message:"Workflow execution failed",data:{}})}finally{await this.cleanup(s.id)}}validateRequest(e){return e.targetUrl?e.workflow?{success:!0}:{success:!1,error:"Workflow is required"}:{success:!1,error:"Target URL is required for workflow"}}async cleanup(e){console.log("[WorkflowService] Cleanup - closing tab:",e),await new Promise(t=>setTimeout(t,1e3)),await this.tabManager.closeTab(e)}}class ww{async handleRequest(e,t){try{console.log("[ApiService] Handle API request:",e.url);const r=await this.fetchData(e);t({success:!0,data:r})}catch(r){console.error("[ApiService] API request error:",r),t({$isError:!0,message:r instanceof Error?r.message:"Unknown error in API request",data:null})}}async fetchData(e){const{url:t,method:r,headers:s,body:a,timeout:i,parseJson:o,returnHeaders:u}=e;console.log(`[ApiService] Fetching ${r} ${t}`);const c=new AbortController,l=setTimeout(()=>c.abort(),i);try{const d={method:r,headers:s,signal:c.signal};a&&!["GET","HEAD"].includes(r)&&(typeof a=="string"?d.body=a:(d.body=JSON.stringify(a),!s["Content-Type"]&&!s["content-type"]&&(d.headers={...s,"Content-Type":"application/json"})));const h=await fetch(t,d);clearTimeout(l);let f;const p=h.headers.get("content-type")||"";if(o&&p.includes("application/json"))try{f=await h.json()}catch{f=await h.text()}else f=await h.text();let m;u&&(m={},h.headers.forEach((_,y)=>{m[y]=_}));const g={status:h.status,statusText:h.statusText,data:f,headers:m};return console.log(`[ApiService] Response status: ${h.status}`),g}catch(d){throw clearTimeout(l),d instanceof Error&&d.name==="AbortError"?new Error(`Request timeout after ${i}ms`):d}}}class vw{aiParsingService;cdpService;workflowService;apiService;constructor(){this.aiParsingService=new gw,this.cdpService=new _w,this.workflowService=new bw(new bh),this.apiService=new ww}initHandler(){chrome.runtime.onMessage.addListener((e,t,r)=>{if(e.type==="COLLECT_WORKFLOW_NEW_TAB")return this.handleAsyncCollectWorkflow(e.data,r),!0;if(e.type==="CDP_CLICK"&&dh(e)){const s=t.tab?.id;return s?(this.handleAsyncCdpClick({...e.data,tabId:s},r),!0):(r({$isError:!0,message:"Tab ID not found in sender",data:null}),!1)}if(e.type==="CDP_KEYPRESS"&&hh(e)){const s=t.tab?.id;return s?(this.handleAsyncCdpKeypress({...e.data,tabId:s},r),!0):(r({$isError:!0,message:"Tab ID not found in sender",data:null}),!1)}return e.type==="AI_PARSE_DATA"?(this.handleAsyncAiParseData(e.data,r),!0):e.type==="FETCH_API"&&fh(e)?(this.handleAsyncFetchApi(e.data,r),!0):(r({$isError:!0,message:"Invalid message type",data:{}}),!1)})}async handleAsyncCollectWorkflow(e,t){await this.workflowService.handleCollectWorkflow(e,t)}async handleAsyncCdpClick(e,t){await this.cdpService.handleClick(e,t)}async handleAsyncCdpKeypress(e,t){await this.cdpService.handleKeypress(e,t)}async handleAsyncAiParseData(e,t){await this.aiParsingService.handleParseData(e,t)}async handleAsyncFetchApi(e,t){await this.apiService.handleRequest(e,t)}}console.log("[8G Extension] Background script starting...");const Ew=new vw;Ew.initHandler();
|